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
Vectors.__init__
(self, name, cache=None, url=None, unk_init=None)
Arguments: name: name of the file that contains the vectors cache: directory for cached vectors url: url for download if vectors not found in cache unk_init (callback): by default, initalize out-of-vocabulary word vectors to zero vectors; can be any fu...
Arguments: name: name of the file that contains the vectors cache: directory for cached vectors url: url for download if vectors not found in cache unk_init (callback): by default, initalize out-of-vocabulary word vectors to zero vectors; can be any fu...
def __init__(self, name, cache=None, url=None, unk_init=None): """ Arguments: name: name of the file that contains the vectors cache: directory for cached vectors url: url for download if vectors not found in cache unk_init (callback): by defa...
[ "def", "__init__", "(", "self", ",", "name", ",", "cache", "=", "None", ",", "url", "=", "None", ",", "unk_init", "=", "None", ")", ":", "cache", "=", "'.vector_cache'", "if", "cache", "is", "None", "else", "cache", "self", ".", "unk_init", "=", "tor...
[ 181, 4 ]
[ 194, 40 ]
python
en
['en', 'error', 'th']
False
main
()
Run administrative tasks.
Run administrative tasks.
def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "enrollXchange.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's ins...
[ "def", "main", "(", ")", ":", "os", ".", "environ", ".", "setdefault", "(", "\"DJANGO_SETTINGS_MODULE\"", ",", "\"enrollXchange.settings\"", ")", "try", ":", "from", "django", ".", "core", ".", "management", "import", "execute_from_command_line", "except", "Import...
[ 6, 0 ]
[ 17, 39 ]
python
en
['lv', 'gd', 'en']
False
capitalize
(s)
Just capitalize first letter (different from .title, as it preserves the rest of the case). e.g. accountSettings -> AccountSettings
Just capitalize first letter (different from .title, as it preserves the rest of the case). e.g. accountSettings -> AccountSettings
def capitalize(s): """ Just capitalize first letter (different from .title, as it preserves the rest of the case). e.g. accountSettings -> AccountSettings """ return s[0].upper() + s[1:]
[ "def", "capitalize", "(", "s", ")", ":", "return", "s", "[", "0", "]", ".", "upper", "(", ")", "+", "s", "[", "1", ":", "]" ]
[ 85, 0 ]
[ 91, 31 ]
python
en
['en', 'error', 'th']
False
refresh_access_token
( *, scratch_org, config, org_name, keychain=None, originating_user_id=None )
Construct a new OrgConfig because ScratchOrgConfig tries to use sfdx which we don't want now -- this is a total hack which I'll try to smooth over with some improvements in CumulusCI
Construct a new OrgConfig because ScratchOrgConfig tries to use sfdx which we don't want now -- this is a total hack which I'll try to smooth over with some improvements in CumulusCI
def refresh_access_token( *, scratch_org, config, org_name, keychain=None, originating_user_id=None ): """ Construct a new OrgConfig because ScratchOrgConfig tries to use sfdx which we don't want now -- this is a total hack which I'll try to smooth over with some improvements in CumulusCI """ ...
[ "def", "refresh_access_token", "(", "*", ",", "scratch_org", ",", "config", ",", "org_name", ",", "keychain", "=", "None", ",", "originating_user_id", "=", "None", ")", ":", "with", "delete_org_on_error", "(", "scratch_org", "=", "scratch_org", ",", "originating...
[ 105, 0 ]
[ 118, 25 ]
python
en
['en', 'error', 'th']
False
get_devhub_api
(*, devhub_username, scratch_org=None)
Get an access token (session) for the specified dev hub username. This only works if the user has already authorized the connected app via an interactive login flow, such as the django-allauth login.
Get an access token (session) for the specified dev hub username. This only works if the user has already authorized the connected app via an interactive login flow, such as the django-allauth login.
def get_devhub_api(*, devhub_username, scratch_org=None): """ Get an access token (session) for the specified dev hub username. This only works if the user has already authorized the connected app via an interactive login flow, such as the django-allauth login. """ with delete_org_on_error(scrat...
[ "def", "get_devhub_api", "(", "*", ",", "devhub_username", ",", "scratch_org", "=", "None", ")", ":", "with", "delete_org_on_error", "(", "scratch_org", "=", "scratch_org", ")", ":", "jwt", "=", "jwt_session", "(", "SF_CLIENT_ID", ",", "SF_CLIENT_KEY", ",", "d...
[ 121, 0 ]
[ 134, 9 ]
python
en
['en', 'error', 'th']
False
get_org_details
(*, cci, org_name, project_path)
Obtain details needed to create a scratch org. Returns scratch_org_config (from the project's cumulusci.yml) and scratch_org_definition (the sfdx *.org file with JSON specifying what kind of org to create)
Obtain details needed to create a scratch org.
def get_org_details(*, cci, org_name, project_path): """Obtain details needed to create a scratch org. Returns scratch_org_config (from the project's cumulusci.yml) and scratch_org_definition (the sfdx *.org file with JSON specifying what kind of org to create) """ scratch_org_config = cci....
[ "def", "get_org_details", "(", "*", ",", "cci", ",", "org_name", ",", "project_path", ")", ":", "scratch_org_config", "=", "cci", ".", "keychain", ".", "get_org", "(", "org_name", ")", "scratch_org_definition_path", "=", "os", ".", "path", ".", "join", "(", ...
[ 137, 0 ]
[ 152, 55 ]
python
en
['en', 'en', 'en']
True
get_org_result
( *, email, repo_owner, repo_name, repo_branch, scratch_org_config, scratch_org_definition, cci, devhub_api, )
Create a new scratch org using the ScratchOrgInfo object in the Dev Hub org, and get the result.
Create a new scratch org using the ScratchOrgInfo object in the Dev Hub org, and get the result.
def get_org_result( *, email, repo_owner, repo_name, repo_branch, scratch_org_config, scratch_org_definition, cci, devhub_api, ): """Create a new scratch org using the ScratchOrgInfo object in the Dev Hub org, and get the result.""" # Schema for ScratchOrgInfo object: ...
[ "def", "get_org_result", "(", "*", ",", "email", ",", "repo_owner", ",", "repo_name", ",", "repo_branch", ",", "scratch_org_config", ",", "scratch_org_definition", ",", "cci", ",", "devhub_api", ",", ")", ":", "# Schema for ScratchOrgInfo object:", "# https://develope...
[ 155, 0 ]
[ 196, 56 ]
python
en
['en', 'co', 'en']
True
mutate_scratch_org
(*, scratch_org_config, org_result, email)
Updates the org config for a new scratch org with details from its ScratchOrgInfo
Updates the org config for a new scratch org with details from its ScratchOrgInfo
def mutate_scratch_org(*, scratch_org_config, org_result, email): """Updates the org config for a new scratch org with details from its ScratchOrgInfo""" scratch_org_config._scratch_info = { "instance_url": org_result["LoginUrl"], "org_id": org_result["ScratchOrg"], "username": org_r...
[ "def", "mutate_scratch_org", "(", "*", ",", "scratch_org_config", ",", "org_result", ",", "email", ")", ":", "scratch_org_config", ".", "_scratch_info", "=", "{", "\"instance_url\"", ":", "org_result", "[", "\"LoginUrl\"", "]", ",", "\"org_id\"", ":", "org_result"...
[ 199, 0 ]
[ 217, 5 ]
python
en
['en', 'en', 'en']
True
get_access_token
(*, org_result, scratch_org_config)
Trades the AuthCode from a ScratchOrgInfo for an org access token, and stores it in the org config. The AuthCode is short-lived so this is only useful immediately after the scratch org is created. This must be completed once in order for future access tokens to be obtained using the JWT token flow. ...
Trades the AuthCode from a ScratchOrgInfo for an org access token, and stores it in the org config.
def get_access_token(*, org_result, scratch_org_config): """Trades the AuthCode from a ScratchOrgInfo for an org access token, and stores it in the org config. The AuthCode is short-lived so this is only useful immediately after the scratch org is created. This must be completed once in order for futur...
[ "def", "get_access_token", "(", "*", ",", "org_result", ",", "scratch_org_config", ")", ":", "oauth", "=", "SalesforceOAuth2", "(", "SF_CLIENT_ID", ",", "SF_CLIENT_SECRET", ",", "SF_CALLBACK_URL", ",", "scratch_org_config", ".", "instance_url", ")", "auth_result", "...
[ 220, 0 ]
[ 234, 35 ]
python
en
['en', 'en', 'en']
True
deploy_org_settings
( *, cci, org_name, scratch_org_config, scratch_org, originating_user_id )
Do a Metadata API deployment to configure org settings as specified in the scratch org definition file.
Do a Metadata API deployment to configure org settings as specified in the scratch org definition file.
def deploy_org_settings( *, cci, org_name, scratch_org_config, scratch_org, originating_user_id ): """Do a Metadata API deployment to configure org settings as specified in the scratch org definition file. """ org_config = refresh_access_token( scratch_org=scratch_org, config=scratch...
[ "def", "deploy_org_settings", "(", "*", ",", "cci", ",", "org_name", ",", "scratch_org_config", ",", "scratch_org", ",", "originating_user_id", ")", ":", "org_config", "=", "refresh_access_token", "(", "scratch_org", "=", "scratch_org", ",", "config", "=", "scratc...
[ 237, 0 ]
[ 254, 21 ]
python
en
['en', 'pt', 'en']
True
create_org
( *, repo_owner, repo_name, repo_url, repo_branch, user, project_path, scratch_org, org_name, originating_user_id, sf_username=None, )
Create a new scratch org
Create a new scratch org
def create_org( *, repo_owner, repo_name, repo_url, repo_branch, user, project_path, scratch_org, org_name, originating_user_id, sf_username=None, ): """Create a new scratch org""" devhub_username = sf_username or user.sf_username email = user.email # TODO: check...
[ "def", "create_org", "(", "*", ",", "repo_owner", ",", "repo_name", ",", "repo_url", ",", "repo_branch", ",", "user", ",", "project_path", ",", "scratch_org", ",", "org_name", ",", "originating_user_id", ",", "sf_username", "=", "None", ",", ")", ":", "devhu...
[ 257, 0 ]
[ 311, 48 ]
python
en
['en', 'co', 'en']
True
run_flow
(*, cci, org_config, flow_name, project_path, user)
Run a flow on a scratch org
Run a flow on a scratch org
def run_flow(*, cci, org_config, flow_name, project_path, user): """Run a flow on a scratch org""" # Run flow in a subprocess so we can control the environment gh_token = user.gh_token command = shutil.which("cci") args = [command, "flow", "run", flow_name, "--org", "dev"] env = { "CUMUL...
[ "def", "run_flow", "(", "*", ",", "cci", ",", "org_config", ",", "flow_name", ",", "project_path", ",", "user", ")", ":", "# Run flow in a subprocess so we can control the environment", "gh_token", "=", "user", ".", "gh_token", "command", "=", "shutil", ".", "whic...
[ 314, 0 ]
[ 357, 9 ]
python
en
['en', 'lb', 'en']
True
delete_org
(scratch_org)
Delete a scratch org by deleting its ActiveScratchOrg record in the Dev Hub org.
Delete a scratch org by deleting its ActiveScratchOrg record in the Dev Hub org.
def delete_org(scratch_org): """Delete a scratch org by deleting its ActiveScratchOrg record in the Dev Hub org.""" devhub_username = scratch_org.owner_sf_username org_id = scratch_org.config["org_id"] devhub_api = get_devhub_api( devhub_username=devhub_username, scratch_org=scratch_org ...
[ "def", "delete_org", "(", "scratch_org", ")", ":", "devhub_username", "=", "scratch_org", ".", "owner_sf_username", "org_id", "=", "scratch_org", ".", "config", "[", "\"org_id\"", "]", "devhub_api", "=", "get_devhub_api", "(", "devhub_username", "=", "devhub_usernam...
[ 360, 0 ]
[ 382, 51 ]
python
en
['en', 'en', 'en']
True
TestServiceBotBasics.test_service_events_for_private_mentions
(self)
Service bots should not get access to mentions if they aren't a direct recipient.
Service bots should not get access to mentions if they aren't a direct recipient.
def test_service_events_for_private_mentions(self) -> None: """Service bots should not get access to mentions if they aren't a direct recipient.""" sender = self.example_user("hamlet") assert not sender.is_bot outgoing_bot = self._get_outgoing_bot() assert outgoing_bot.b...
[ "def", "test_service_events_for_private_mentions", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "assert", "not", "sender", ".", "is_bot", "outgoing_bot", "=", "self", ".", "_get_outgoing_bot", "(", ")",...
[ 119, 4 ]
[ 138, 44 ]
python
en
['en', 'en', 'en']
True
choose_art
(phonemes)
choose correct article for the phonemes: return "a" or "an" or NotImplemented
choose correct article for the phonemes: return "a" or "an" or NotImplemented
def choose_art(phonemes): ''' choose correct article for the phonemes: return "a" or "an" or NotImplemented ''' try: p = phonemes.strip(accents)[0] except IndexError: return NotImplemented if p in phonetics.consonants: return 'a' elif p in phonetics.vowels: ...
[ "def", "choose_art", "(", "phonemes", ")", ":", "try", ":", "p", "=", "phonemes", ".", "strip", "(", "accents", ")", "[", "0", "]", "except", "IndexError", ":", "return", "NotImplemented", "if", "p", "in", "phonetics", ".", "consonants", ":", "return", ...
[ 28, 0 ]
[ 42, 29 ]
python
en
['en', 'error', 'th']
False
FreshdeskHookTests.test_ticket_creation
(self)
Messages are generated on ticket creation through Freshdesk's "Dispatch'r" service.
Messages are generated on ticket creation through Freshdesk's "Dispatch'r" service.
def test_ticket_creation(self) -> None: """ Messages are generated on ticket creation through Freshdesk's "Dispatch'r" service. """ expected_topic = "#11: Test ticket subject ☃" expected_message = """ Requester ☃ Bob <requester-bob@example.com> created [ticket #11](http:/...
[ "def", "test_ticket_creation", "(", "self", ")", "->", "None", ":", "expected_topic", "=", "\"#11: Test ticket subject ☃\"", "expected_message", "=", "\"\"\"\nRequester ☃ Bob <requester-bob@example.com> created [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11):\n\n``` quot...
[ 10, 4 ]
[ 34, 9 ]
python
en
['en', 'error', 'th']
False
FreshdeskHookTests.test_status_change
(self)
Messages are generated when a ticket's status changes through Freshdesk's "Observer" service.
Messages are generated when a ticket's status changes through Freshdesk's "Observer" service.
def test_status_change(self) -> None: """ Messages are generated when a ticket's status changes through Freshdesk's "Observer" service. """ expected_topic = "#11: Test ticket subject ☃" expected_message = """ Requester Bob <requester-bob@example.com> updated [ticket #11](...
[ "def", "test_status_change", "(", "self", ")", "->", "None", ":", "expected_topic", "=", "\"#11: Test ticket subject ☃\"", "expected_message", "=", "\"\"\"\nRequester Bob <requester-bob@example.com> updated [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11):\n\n* **Status**...
[ 36, 4 ]
[ 54, 9 ]
python
en
['en', 'error', 'th']
False
FreshdeskHookTests.test_priority_change
(self)
Messages are generated when a ticket's priority changes through Freshdesk's "Observer" service.
Messages are generated when a ticket's priority changes through Freshdesk's "Observer" service.
def test_priority_change(self) -> None: """ Messages are generated when a ticket's priority changes through Freshdesk's "Observer" service. """ expected_topic = "#11: Test ticket subject" expected_message = """ Requester Bob <requester-bob@example.com> updated [ticket #11...
[ "def", "test_priority_change", "(", "self", ")", "->", "None", ":", "expected_topic", "=", "\"#11: Test ticket subject\"", "expected_message", "=", "\"\"\"\nRequester Bob <requester-bob@example.com> updated [ticket #11](http://test1234zzz.freshdesk.com/helpdesk/tickets/11):\n\n* **Priority...
[ 56, 4 ]
[ 73, 9 ]
python
en
['en', 'error', 'th']
False
FreshdeskHookTests.test_unknown_event_payload_ignore
(self, check_send_webhook_message_mock: MagicMock)
Ignore unknown event payloads.
Ignore unknown event payloads.
def test_unknown_event_payload_ignore(self, check_send_webhook_message_mock: MagicMock) -> None: """ Ignore unknown event payloads. """ self.url = self.build_webhook_url() payload = self.get_body("unknown_payload") kwargs = { "HTTP_AUTHORIZATION": self.encode_...
[ "def", "test_unknown_event_payload_ignore", "(", "self", ",", "check_send_webhook_message_mock", ":", "MagicMock", ")", "->", "None", ":", "self", ".", "url", "=", "self", ".", "build_webhook_url", "(", ")", "payload", "=", "self", ".", "get_body", "(", "\"unkno...
[ 76, 4 ]
[ 88, 40 ]
python
en
['en', 'error', 'th']
False
FreshdeskHookTests.note_change
(self, fixture: str, note_type: str)
Messages are generated when a note gets added to a ticket through Freshdesk's "Observer" service.
Messages are generated when a note gets added to a ticket through Freshdesk's "Observer" service.
def note_change(self, fixture: str, note_type: str) -> None: """ Messages are generated when a note gets added to a ticket through Freshdesk's "Observer" service. """ expected_topic = "#11: Test ticket subject" expected_message = """ Requester Bob <requester-bob@example.c...
[ "def", "note_change", "(", "self", ",", "fixture", ":", "str", ",", "note_type", ":", "str", ")", "->", "None", ":", "expected_topic", "=", "\"#11: Test ticket subject\"", "expected_message", "=", "\"\"\"\nRequester Bob <requester-bob@example.com> added a {} note to \\\n[ti...
[ 90, 4 ]
[ 108, 9 ]
python
en
['en', 'error', 'th']
False
FreshdeskHookTests.test_inline_image
(self)
Freshdesk sends us descriptions as HTML, so we have to make the descriptions Zulip Markdown-friendly while still doing our best to preserve links and images.
Freshdesk sends us descriptions as HTML, so we have to make the descriptions Zulip Markdown-friendly while still doing our best to preserve links and images.
def test_inline_image(self) -> None: """ Freshdesk sends us descriptions as HTML, so we have to make the descriptions Zulip Markdown-friendly while still doing our best to preserve links and images. """ expected_topic = "#12: Not enough ☃ guinea pigs" expected_mes...
[ "def", "test_inline_image", "(", "self", ")", "->", "None", ":", "expected_topic", "=", "\"#12: Not enough ☃ guinea pigs\"", "expected_message", "=", "\"\"\"\nRequester \\u2603 Bob <requester-bob@example.com> created [ticket #12](http://test1234zzz.freshdesk.com/helpdesk/tickets/12):\\n\\n...
[ 116, 4 ]
[ 132, 9 ]
python
en
['en', 'error', 'th']
False
Content.__init__
(self, tag=None, value=None, **kwargs)
@param tag: The content tag. @type tag: str @param value: The content's value. @type value: I{any}
def __init__(self, tag=None, value=None, **kwargs): """ @param tag: The content tag. @type tag: str @param value: The content's value. @type value: I{any} """ Object.__init__(self) self.tag = tag self.value = value for k,v in kwargs.items()...
[ "def", "__init__", "(", "self", ",", "tag", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "Object", ".", "__init__", "(", "self", ")", "self", ".", "tag", "=", "tag", "self", ".", "value", "=", "value", "for", "k", ...
[ 35, 4 ]
[ 46, 31 ]
python
en
['en', 'error', 'th']
False
is_canarytoken
(message: Dict[str, Any])
Requests sent from Thinkst canaries are either from canarytokens or canaries, which can be differentiated by the value of the `AlertType` field.
Requests sent from Thinkst canaries are either from canarytokens or canaries, which can be differentiated by the value of the `AlertType` field.
def is_canarytoken(message: Dict[str, Any]) -> bool: """ Requests sent from Thinkst canaries are either from canarytokens or canaries, which can be differentiated by the value of the `AlertType` field. """ return message["AlertType"] == "CanarytokenIncident"
[ "def", "is_canarytoken", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "bool", ":", "return", "message", "[", "\"AlertType\"", "]", "==", "\"CanarytokenIncident\"" ]
[ 12, 0 ]
[ 18, 56 ]
python
en
['en', 'error', 'th']
False
canary_name
(message: Dict[str, Any])
Returns the name of the canary or canarytoken.
Returns the name of the canary or canarytoken.
def canary_name(message: Dict[str, Any]) -> str: """ Returns the name of the canary or canarytoken. """ if is_canarytoken(message): return message["Reminder"] else: return message["CanaryName"]
[ "def", "canary_name", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "if", "is_canarytoken", "(", "message", ")", ":", "return", "message", "[", "\"Reminder\"", "]", "else", ":", "return", "message", "[", "\"CanaryName\"...
[ 21, 0 ]
[ 28, 36 ]
python
en
['en', 'error', 'th']
False
canary_kind
(message: Dict[str, Any])
Returns a description of the kind of request - canary or canarytoken.
Returns a description of the kind of request - canary or canarytoken.
def canary_kind(message: Dict[str, Any]) -> str: """ Returns a description of the kind of request - canary or canarytoken. """ if is_canarytoken(message): return "canarytoken" else: return "canary"
[ "def", "canary_kind", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "if", "is_canarytoken", "(", "message", ")", ":", "return", "\"canarytoken\"", "else", ":", "return", "\"canary\"" ]
[ 31, 0 ]
[ 38, 23 ]
python
en
['en', 'error', 'th']
False
source_ip_and_reverse_dns
(message: Dict[str, Any])
Extract the source IP and reverse DNS information from a canary request.
Extract the source IP and reverse DNS information from a canary request.
def source_ip_and_reverse_dns(message: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]: """ Extract the source IP and reverse DNS information from a canary request. """ reverse_dns, source_ip = (None, None) if "SourceIP" in message: source_ip = message["SourceIP"] # `ReverseDNS` ...
[ "def", "source_ip_and_reverse_dns", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "str", "]", "]", ":", "reverse_dns", ",", "source_ip", "=", "(", "None", ",", "N...
[ 41, 0 ]
[ 53, 35 ]
python
en
['en', 'error', 'th']
False
body
(message: Dict[str, Any])
Construct the response to a canary or canarytoken request.
Construct the response to a canary or canarytoken request.
def body(message: Dict[str, Any]) -> str: """ Construct the response to a canary or canarytoken request. """ title = canary_kind(message).title() name = canary_name(message) body = f"**:alert: {title} *{name}* has been triggered!**\n\n{message['Intro']}\n\n" if "IncidentHash" in message: ...
[ "def", "body", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "title", "=", "canary_kind", "(", "message", ")", ".", "title", "(", ")", "name", "=", "canary_name", "(", "message", ")", "body", "=", "f\"**:alert: {tit...
[ 56, 0 ]
[ 102, 15 ]
python
en
['en', 'error', 'th']
False
api_thinkst_webhook
( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), )
Construct a response to a webhook event from a Thinkst canary or canarytoken. Thinkst offers public canarytokens with canarytokens.org and with their canary product, but the schema returned by these identically named services are completely different - canarytokens from canarytokens.org are handled by...
Construct a response to a webhook event from a Thinkst canary or canarytoken.
def api_thinkst_webhook( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), ) -> HttpResponse: """ Construct a response to a webhook event from a Thinkst canary or canarytoken. ...
[ "def", "api_thinkst_webhook", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "message", ":", "Dict", "[", "str", ",", "Any", "]", "=", "REQ", "(", "argument_type", "=", "\"body\"", ")", ",", "user_specified_topic", ":", "Op...
[ 107, 0 ]
[ 139, 25 ]
python
en
['en', 'error', 'th']
False
test_helpful_error_message_received_on_connection_reset_error
()
Tests that if connection to the server fails with a ConnectionResetError then a helpful error message is logged.
Tests that if connection to the server fails with a ConnectionResetError then a helpful error message is logged.
def test_helpful_error_message_received_on_connection_reset_error(): """Tests that if connection to the server fails with a ConnectionResetError then a helpful error message is logged. """ ws_client, _, _ = default_ws_client_setup("wss://this-url-wont-be-used:1") async def mock_connect(*args, **kwa...
[ "def", "test_helpful_error_message_received_on_connection_reset_error", "(", ")", ":", "ws_client", ",", "_", ",", "_", "=", "default_ws_client_setup", "(", "\"wss://this-url-wont-be-used:1\"", ")", "async", "def", "mock_connect", "(", "*", "args", ",", "*", "*", "kwa...
[ 202, 0 ]
[ 227, 37 ]
python
en
['en', 'en', 'en']
True
test__buffer_semaphore
()
Test the WebsocketClient internal BoundedSemaphore.
Test the WebsocketClient internal BoundedSemaphore.
async def test__buffer_semaphore(): """ Test the WebsocketClient internal BoundedSemaphore. """ # pylint: disable=protected-access buffer_size = 123 ws_client = client.WebsocketClient( ConnectionSettings(url="fake url", message_buffer_size=buffer_size) ) await ws_client._init_synchroniza...
[ "async", "def", "test__buffer_semaphore", "(", ")", ":", "# pylint: disable=protected-access", "buffer_size", "=", "123", "ws_client", "=", "client", ".", "WebsocketClient", "(", "ConnectionSettings", "(", "url", "=", "\"fake url\"", ",", "message_buffer_size", "=", "...
[ 231, 0 ]
[ 276, 51 ]
python
en
['en', 'lb', 'en']
True
test__producer_happy_path
(mocker)
Happy path _producer test where the client sends 8 audio chunks and then stops.
Happy path _producer test where the client sends 8 audio chunks and then stops.
async def test__producer_happy_path(mocker): """ Happy path _producer test where the client sends 8 audio chunks and then stops. """ # pylint: disable=protected-access,too-many-locals no_chunks_to_send = 8 buffer_size = no_chunks_to_send + 1 ws_client = client.WebsocketClient( Co...
[ "async", "def", "test__producer_happy_path", "(", "mocker", ")", ":", "# pylint: disable=protected-access,too-many-locals", "no_chunks_to_send", "=", "8", "buffer_size", "=", "no_chunks_to_send", "+", "1", "ws_client", "=", "client", ".", "WebsocketClient", "(", "Connecti...
[ 280, 0 ]
[ 331, 5 ]
python
en
['en', 'error', 'th']
False
test__producer_semaphore_pause_and_resume
(mocker)
Test simulating the client sending audio chunks to a server faster than it can reply to them with AudioAdded acks causing the client throttling logic to kick-in.
Test simulating the client sending audio chunks to a server faster than it can reply to them with AudioAdded acks causing the client throttling logic to kick-in.
async def test__producer_semaphore_pause_and_resume(mocker): """ Test simulating the client sending audio chunks to a server faster than it can reply to them with AudioAdded acks causing the client throttling logic to kick-in. """ # pylint: disable=protected-access,too-many-locals no_chunks_...
[ "async", "def", "test__producer_semaphore_pause_and_resume", "(", "mocker", ")", ":", "# pylint: disable=protected-access,too-many-locals", "no_chunks_to_send", "=", "5", "buffer_size", "=", "no_chunks_to_send", "-", "1", "exp_iters", "=", "no_chunks_to_send", "+", "1", "ws...
[ 335, 0 ]
[ 386, 33 ]
python
en
['en', 'error', 'th']
False
test__producer_semaphore_timeout
(mocker)
Test simulating the client continually sending audio chunks to a server that isn't responding with AudioAdded acks.
Test simulating the client continually sending audio chunks to a server that isn't responding with AudioAdded acks.
async def test__producer_semaphore_timeout(mocker): """ Test simulating the client continually sending audio chunks to a server that isn't responding with AudioAdded acks. """ # pylint: disable=protected-access,too-many-locals no_chunks_to_send = 5 buffer_size = no_chunks_to_send - 1 quick_t...
[ "async", "def", "test__producer_semaphore_timeout", "(", "mocker", ")", ":", "# pylint: disable=protected-access,too-many-locals", "no_chunks_to_send", "=", "5", "buffer_size", "=", "no_chunks_to_send", "-", "1", "quick_timeout", "=", "0.1", "ws_client", "=", "client", "....
[ 390, 0 ]
[ 442, 35 ]
python
en
['en', 'error', 'th']
False
deepcopy_state
(obj)
Return a deepcopy of the __dict__ (or state) of an object but ignore the keys that cause trouble when trying to copy.deepcopy them.
Return a deepcopy of the __dict__ (or state) of an object but ignore the keys that cause trouble when trying to copy.deepcopy them.
def deepcopy_state(obj): """ Return a deepcopy of the __dict__ (or state) of an object but ignore the keys that cause trouble when trying to copy.deepcopy them. """ state = vars(obj) state_copy = {} # copy.deepcopy will raise an exception on these types because they # can't be pickled. ...
[ "def", "deepcopy_state", "(", "obj", ")", ":", "state", "=", "vars", "(", "obj", ")", "state_copy", "=", "{", "}", "# copy.deepcopy will raise an exception on these types because they", "# can't be pickled.", "# The try..except method you'd expect to see here causes pytest warnin...
[ 445, 0 ]
[ 464, 21 ]
python
en
['en', 'error', 'th']
False
AbbrExtension.extendMarkdown
(self, md, md_globals)
Insert AbbrPreprocessor before ReferencePreprocessor.
Insert AbbrPreprocessor before ReferencePreprocessor.
def extendMarkdown(self, md, md_globals): """ Insert AbbrPreprocessor before ReferencePreprocessor. """ md.preprocessors.add('abbr', AbbrPreprocessor(md), '<reference')
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "md", ".", "preprocessors", ".", "add", "(", "'abbr'", ",", "AbbrPreprocessor", "(", "md", ")", ",", "'<reference'", ")" ]
[ 34, 4 ]
[ 36, 72 ]
python
en
['en', 'it', 'en']
True
AbbrPreprocessor.run
(self, lines)
Find and remove all Abbreviation references from the text. Each reference is set as a new AbbrPattern in the markdown instance.
Find and remove all Abbreviation references from the text. Each reference is set as a new AbbrPattern in the markdown instance.
def run(self, lines): ''' Find and remove all Abbreviation references from the text. Each reference is set as a new AbbrPattern in the markdown instance. ''' new_text = [] for line in lines: m = ABBR_REF_RE.match(line) if m: ...
[ "def", "run", "(", "self", ",", "lines", ")", ":", "new_text", "=", "[", "]", "for", "line", "in", "lines", ":", "m", "=", "ABBR_REF_RE", ".", "match", "(", "line", ")", "if", "m", ":", "abbr", "=", "m", ".", "group", "(", "'abbr'", ")", ".", ...
[ 42, 4 ]
[ 58, 23 ]
python
en
['en', 'error', 'th']
False
AbbrPreprocessor._generate_pattern
(self, text)
Given a string, returns an regex pattern to match that string. 'HTML' -> r'(?P<abbr>[H][T][M][L])' Note: we force each char as a literal match (in brackets) as we don't know what they will be beforehand.
Given a string, returns an regex pattern to match that string. 'HTML' -> r'(?P<abbr>[H][T][M][L])' Note: we force each char as a literal match (in brackets) as we don't know what they will be beforehand.
def _generate_pattern(self, text): ''' Given a string, returns an regex pattern to match that string. 'HTML' -> r'(?P<abbr>[H][T][M][L])' Note: we force each char as a literal match (in brackets) as we don't know what they will be beforehand. ''' ...
[ "def", "_generate_pattern", "(", "self", ",", "text", ")", ":", "chars", "=", "list", "(", "text", ")", "for", "i", "in", "range", "(", "len", "(", "chars", ")", ")", ":", "chars", "[", "i", "]", "=", "r'[%s]'", "%", "chars", "[", "i", "]", "re...
[ 60, 4 ]
[ 73, 54 ]
python
en
['en', 'error', 'th']
False
get_context
(request, context=None)
Returns common context data for network topology views.
Returns common context data for network topology views.
def get_context(request, context=None): """Returns common context data for network topology views.""" if context is None: context = {} context['launch_instance_allowed'] = policy.check( (("compute", "os_compute_api:servers:create"),), request) context['instance_quota_exceeded'] = _quota...
[ "def", "get_context", "(", "request", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "{", "}", "context", "[", "'launch_instance_allowed'", "]", "=", "policy", ".", "check", "(", "(", "(", "\"compute\"", ",", ...
[ 26, 0 ]
[ 49, 18 ]
python
en
['en', 'en', 'en']
True
get_tagname_or_hash
()
return tagname if exists else hash
return tagname if exists else hash
def get_tagname_or_hash(): """return tagname if exists else hash""" # get hash hash_cmd = ['git', 'rev-parse', '--short', 'HEAD'] hash_ = check_output(hash_cmd).decode('utf-8').strip() # get tagname tags_cmd = ['git', 'for-each-ref', '--points-at=HEAD', '--count=2', '--sort=-version:refname', '...
[ "def", "get_tagname_or_hash", "(", ")", ":", "# get hash", "hash_cmd", "=", "[", "'git'", ",", "'rev-parse'", ",", "'--short'", ",", "'HEAD'", "]", "hash_", "=", "check_output", "(", "hash_cmd", ")", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ...
[ 9, 0 ]
[ 23, 15 ]
python
en
['en', 'en', 'en']
True
WeakValueDictionary.itervaluerefs
(self)
Return an iterator that yields the weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the g...
Return an iterator that yields the weak references to the values.
def itervaluerefs(self): """Return an iterator that yields the weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creat...
[ "def", "itervaluerefs", "(", "self", ")", ":", "if", "self", ".", "_pending_removals", ":", "self", ".", "_commit_removals", "(", ")", "with", "_IterationGuard", "(", "self", ")", ":", "yield", "from", "self", ".", "data", ".", "values", "(", ")" ]
[ 226, 4 ]
[ 239, 41 ]
python
en
['en', 'en', 'en']
True
WeakValueDictionary.valuerefs
(self)
Return a list of weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector t...
Return a list of weak references to the values.
def valuerefs(self): """Return a list of weak references to the values. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that wi...
[ "def", "valuerefs", "(", "self", ")", ":", "if", "self", ".", "_pending_removals", ":", "self", ".", "_commit_removals", "(", ")", "return", "list", "(", "self", ".", "data", ".", "values", "(", ")", ")" ]
[ 306, 4 ]
[ 318, 39 ]
python
en
['en', 'en', 'en']
True
WeakKeyDictionary.keyrefs
(self)
Return a list of weak references to the keys. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to ...
Return a list of weak references to the keys.
def keyrefs(self): """Return a list of weak references to the keys. The references are not guaranteed to be 'live' at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will c...
[ "def", "keyrefs", "(", "self", ")", ":", "return", "list", "(", "self", ".", "data", ")" ]
[ 459, 4 ]
[ 469, 30 ]
python
en
['en', 'en', 'en']
True
finalize.__call__
(self, _=None)
If alive then mark as dead and return func(*args, **kwargs); otherwise return None
If alive then mark as dead and return func(*args, **kwargs); otherwise return None
def __call__(self, _=None): """If alive then mark as dead and return func(*args, **kwargs); otherwise return None""" info = self._registry.pop(self, None) if info and not self._shutdown: return info.func(*info.args, **(info.kwargs or {}))
[ "def", "__call__", "(", "self", ",", "_", "=", "None", ")", ":", "info", "=", "self", ".", "_registry", ".", "pop", "(", "self", ",", "None", ")", "if", "info", "and", "not", "self", ".", "_shutdown", ":", "return", "info", ".", "func", "(", "*",...
[ 542, 4 ]
[ 547, 63 ]
python
en
['en', 'en', 'en']
True
finalize.detach
(self)
If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None
If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None
def detach(self): """If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None and self._registry.pop(self, None): return (obj, info.func, info.args, info....
[ "def", "detach", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", "and", "self", ".", "_registry", ".", "pop...
[ 549, 4 ]
[ 555, 65 ]
python
en
['en', 'en', 'sw']
True
finalize.peek
(self)
If alive then return (obj, func, args, kwargs); otherwise return None
If alive then return (obj, func, args, kwargs); otherwise return None
def peek(self): """If alive then return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None: return (obj, info.func, info.args, info.kwargs or {})
[ "def", "peek", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", ":", "return", "(", "obj", ",", "info", "....
[ 557, 4 ]
[ 563, 65 ]
python
en
['en', 'fy', 'sw']
False
finalize.alive
(self)
Whether finalizer is alive
Whether finalizer is alive
def alive(self): """Whether finalizer is alive""" return self in self._registry
[ "def", "alive", "(", "self", ")", ":", "return", "self", "in", "self", ".", "_registry" ]
[ 566, 4 ]
[ 568, 37 ]
python
en
['en', 'en', 'en']
True
finalize.atexit
(self)
Whether finalizer should be called at exit
Whether finalizer should be called at exit
def atexit(self): """Whether finalizer should be called at exit""" info = self._registry.get(self) return bool(info) and info.atexit
[ "def", "atexit", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "return", "bool", "(", "info", ")", "and", "info", ".", "atexit" ]
[ 571, 4 ]
[ 574, 41 ]
python
en
['en', 'en', 'en']
True
NaNJSONEncoder.iterencode
(self, o, _one_shot=False)
JSON encoder with NaN and float inf support. The sole purpose of defining a custom JSONEncoder class is to override floatstr() inner function, or more specifically the representation of NaN and +/-float('inf') values in a JSON. Although Infinity values are not supported by JSON standard...
JSON encoder with NaN and float inf support.
def iterencode(self, o, _one_shot=False): """JSON encoder with NaN and float inf support. The sole purpose of defining a custom JSONEncoder class is to override floatstr() inner function, or more specifically the representation of NaN and +/-float('inf') values in a JSON. Although ...
[ "def", "iterencode", "(", "self", ",", "o", ",", "_one_shot", "=", "False", ")", ":", "if", "self", ".", "check_circular", ":", "markers", "=", "{", "}", "else", ":", "markers", "=", "None", "if", "self", ".", "ensure_ascii", ":", "_encoder", "=", "e...
[ 26, 4 ]
[ 83, 32 ]
python
en
['en', 'en', 'en']
True
with_cleanup
(func)
Decorator for common logic related to managing temporary directories.
Decorator for common logic related to managing temporary directories.
def with_cleanup(func): # type: (Any) -> Any """Decorator for common logic related to managing temporary directories. """ def configure_tempdir_registry(registry): # type: (TempDirectoryTypeRegistry) -> None for t in KEEPABLE_TEMPDIR_TYPES: registry.set_delete(t, False) ...
[ "def", "with_cleanup", "(", "func", ")", ":", "# type: (Any) -> Any", "def", "configure_tempdir_registry", "(", "registry", ")", ":", "# type: (TempDirectoryTypeRegistry) -> None", "for", "t", "in", "KEEPABLE_TEMPDIR_TYPES", ":", "registry", ".", "set_delete", "(", "t",...
[ 164, 0 ]
[ 189, 18 ]
python
en
['en', 'en', 'en']
True
SessionCommandMixin._get_index_urls
(cls, options)
Return a list of index urls from user-provided options.
Return a list of index urls from user-provided options.
def _get_index_urls(cls, options): # type: (Values) -> Optional[List[str]] """Return a list of index urls from user-provided options.""" index_urls = [] if not getattr(options, "no_index", False): url = getattr(options, "index_url", None) if url: i...
[ "def", "_get_index_urls", "(", "cls", ",", "options", ")", ":", "# type: (Values) -> Optional[List[str]]", "index_urls", "=", "[", "]", "if", "not", "getattr", "(", "options", ",", "\"no_index\"", ",", "False", ")", ":", "url", "=", "getattr", "(", "options", ...
[ 61, 4 ]
[ 73, 33 ]
python
en
['en', 'en', 'en']
True
SessionCommandMixin.get_default_session
(self, options)
Get a default-managed session.
Get a default-managed session.
def get_default_session(self, options): # type: (Values) -> PipSession """Get a default-managed session.""" if self._session is None: self._session = self.enter_context(self._build_session(options)) # there's no type annotation on requests.Session, so it's # a...
[ "def", "get_default_session", "(", "self", ",", "options", ")", ":", "# type: (Values) -> PipSession", "if", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "self", ".", "enter_context", "(", "self", ".", "_build_session", "(", "optio...
[ 75, 4 ]
[ 84, 28 ]
python
en
['en', 'da', 'en']
True
IndexGroupCommand.handle_pip_version_check
(self, options)
Do the pip version check if not disabled. This overrides the default behavior of not doing the check.
Do the pip version check if not disabled.
def handle_pip_version_check(self, options): # type: (Values) -> None """ Do the pip version check if not disabled. This overrides the default behavior of not doing the check. """ # Make sure the index_group options are present. assert hasattr(options, 'no_index'...
[ "def", "handle_pip_version_check", "(", "self", ",", "options", ")", ":", "# type: (Values) -> None", "# Make sure the index_group options are present.", "assert", "hasattr", "(", "options", ",", "'no_index'", ")", "if", "options", ".", "disable_pip_version_check", "or", ...
[ 134, 4 ]
[ 154, 52 ]
python
en
['en', 'error', 'th']
False
RequirementCommand.make_requirement_preparer
( temp_build_dir, # type: TempDirectory options, # type: Values req_tracker, # type: RequirementTracker session, # type: PipSession finder, # type: PackageFinder use_user_site, # type: b...
Create a RequirementPreparer instance for the given parameters.
Create a RequirementPreparer instance for the given parameters.
def make_requirement_preparer( temp_build_dir, # type: TempDirectory options, # type: Values req_tracker, # type: RequirementTracker session, # type: PipSession finder, # type: PackageFinder use_us...
[ "def", "make_requirement_preparer", "(", "temp_build_dir", ",", "# type: TempDirectory", "options", ",", "# type: Values", "req_tracker", ",", "# type: RequirementTracker", "session", ",", "# type: PipSession", "finder", ",", "# type: PackageFinder", "use_user_site", ",", "# ...
[ 201, 4 ]
[ 231, 9 ]
python
en
['en', 'error', 'th']
False
RequirementCommand.make_resolver
( preparer, # type: RequirementPreparer finder, # type: PackageFinder options, # type: Values wheel_cache=None, # type: Optional[WheelCache] use_user_site=False, ...
Create a Resolver instance for the given parameters.
Create a Resolver instance for the given parameters.
def make_resolver( preparer, # type: RequirementPreparer finder, # type: PackageFinder options, # type: Values wheel_cache=None, # type: Optional[WheelCache] use_user_site=False...
[ "def", "make_resolver", "(", "preparer", ",", "# type: RequirementPreparer", "finder", ",", "# type: PackageFinder", "options", ",", "# type: Values", "wheel_cache", "=", "None", ",", "# type: Optional[WheelCache]", "use_user_site", "=", "False", ",", "# type: bool", "ign...
[ 234, 4 ]
[ 288, 9 ]
python
en
['en', 'error', 'th']
False
RequirementCommand.get_requirements
( self, args, # type: List[str] options, # type: Values finder, # type: PackageFinder session, # type: PipSession )
Parse command-line arguments into the corresponding requirements.
Parse command-line arguments into the corresponding requirements.
def get_requirements( self, args, # type: List[str] options, # type: Values finder, # type: PackageFinder session, # type: PipSession ): # type: (...) -> List[InstallRequirement] """ Parse command-line arguments ...
[ "def", "get_requirements", "(", "self", ",", "args", ",", "# type: List[str]", "options", ",", "# type: Values", "finder", ",", "# type: PackageFinder", "session", ",", "# type: PipSession", ")", ":", "# type: (...) -> List[InstallRequirement]", "requirements", "=", "[", ...
[ 290, 4 ]
[ 360, 27 ]
python
en
['en', 'error', 'th']
False
RequirementCommand.trace_basic_info
(finder)
Trace basic information about the provided objects.
Trace basic information about the provided objects.
def trace_basic_info(finder): # type: (PackageFinder) -> None """ Trace basic information about the provided objects. """ # Display where finder is looking for packages search_scope = finder.search_scope locations = search_scope.get_formatted_locations() i...
[ "def", "trace_basic_info", "(", "finder", ")", ":", "# type: (PackageFinder) -> None", "# Display where finder is looking for packages", "search_scope", "=", "finder", ".", "search_scope", "locations", "=", "search_scope", ".", "get_formatted_locations", "(", ")", "if", "lo...
[ 363, 4 ]
[ 372, 34 ]
python
en
['en', 'error', 'th']
False
RequirementCommand._build_package_finder
( self, options, # type: Values session, # type: PipSession target_python=None, # type: Optional[TargetPython] ignore_requires_python=None, # type: Optional[bool] )
Create a package finder appropriate to this requirement command. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False.
Create a package finder appropriate to this requirement command.
def _build_package_finder( self, options, # type: Values session, # type: PipSession target_python=None, # type: Optional[TargetPython] ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> PackageFinder """ ...
[ "def", "_build_package_finder", "(", "self", ",", "options", ",", "# type: Values", "session", ",", "# type: PipSession", "target_python", "=", "None", ",", "# type: Optional[TargetPython]", "ignore_requires_python", "=", "None", ",", "# type: Optional[bool]", ")", ":", ...
[ 374, 4 ]
[ 401, 9 ]
python
en
['en', 'error', 'th']
False
init
()
initialize underlying speech engine
initialize underlying speech engine
def init(): ''' initialize underlying speech engine ''' global espeak # pylint: disable=global-statement,global-variable-not-assigned from lib import espeak # pylint: disable=redefined-outer-name,import-outside-toplevel espeak.init() espeak.set_voice_by_name('en') here = os.path.dirnam...
[ "def", "init", "(", ")", ":", "global", "espeak", "# pylint: disable=global-statement,global-variable-not-assigned", "from", "lib", "import", "espeak", "# pylint: disable=redefined-outer-name,import-outside-toplevel", "espeak", ".", "init", "(", ")", "espeak", ".", "set_voice...
[ 43, 0 ]
[ 60, 34 ]
python
en
['en', 'error', 'th']
False
text_to_phonemes
(s, *, ipa=False)
translate text to phonemes
translate text to phonemes
def text_to_phonemes(s, *, ipa=False): ''' translate text to phonemes ''' s = overrides.get(s.lower(), s) if s.startswith('[[') and s.endswith(']]'): return s.split('\t')[ipa][2:-2] else: return espeak.text_to_phonemes(s, ipa=ipa)
[ "def", "text_to_phonemes", "(", "s", ",", "*", ",", "ipa", "=", "False", ")", ":", "s", "=", "overrides", ".", "get", "(", "s", ".", "lower", "(", ")", ",", "s", ")", "if", "s", ".", "startswith", "(", "'[['", ")", "and", "s", ".", "endswith", ...
[ 63, 0 ]
[ 71, 50 ]
python
en
['en', 'error', 'th']
False
TravisHookTests.test_travis_message
(self)
Build notifications are generated by Travis after build completes. The subject describes the repo and Stash "project". The content describes the commits pushed.
Build notifications are generated by Travis after build completes.
def test_travis_message(self) -> None: """ Build notifications are generated by Travis after build completes. The subject describes the repo and Stash "project". The content describes the commits pushed. """ expected_message = ( "Author: josh_mandel\nBuild st...
[ "def", "test_travis_message", "(", "self", ")", "->", "None", ":", "expected_message", "=", "(", "\"Author: josh_mandel\\nBuild status: Passed :thumbs_up:\\n\"", "\"Details: [changes](https://github.com/hl7-fhir/fhir-sv\"", "\"n/compare/6dccb98bcfd9...6c457d366a31), [build log](ht\"", "\...
[ 11, 4 ]
[ 30, 9 ]
python
en
['en', 'error', 'th']
False
event_list_chords
(quantized_sequence, event_lists)
Extract corresponding chords for multiple EventSequences. Args: quantized_sequence: The underlying quantized NoteSequence from which to extract the chords. It is assumed that the step numbering in this sequence matches the step numbering in each EventSequence in `event_lists`. event_l...
Extract corresponding chords for multiple EventSequences.
def event_list_chords(quantized_sequence, event_lists): """Extract corresponding chords for multiple EventSequences. Args: quantized_sequence: The underlying quantized NoteSequence from which to extract the chords. It is assumed that the step numbering in this sequence matches the step numberin...
[ "def", "event_list_chords", "(", "quantized_sequence", ",", "event_lists", ")", ":", "sequences_lib", ".", "assert_is_relative_quantized_sequence", "(", "quantized_sequence", ")", "chords", "=", "ChordProgression", "(", ")", "if", "quantized_sequence", ".", "total_quantiz...
[ 249, 0 ]
[ 277, 20 ]
python
en
['en', 'en', 'en']
True
event_list_keys
(sequence, event_lists, steps_per_second)
Extract corresponding keys for multiple EventSequences. Args: sequence: The underlying NoteSequence from which to extract the keys. event_lists: A list of EventSequence objects. steps_per_second: The number of quantized steps per second in the event lists. Returns: A nested list of keys (i...
Extract corresponding keys for multiple EventSequences.
def event_list_keys(sequence, event_lists, steps_per_second): """Extract corresponding keys for multiple EventSequences. Args: sequence: The underlying NoteSequence from which to extract the keys. event_lists: A list of EventSequence objects. steps_per_second: The number of quantized steps per second i...
[ "def", "event_list_keys", "(", "sequence", ",", "event_lists", ",", "steps_per_second", ")", ":", "if", "not", "sequence", ".", "key_signatures", ":", "raise", "ValueError", "(", "'Sequence has no key signatures.'", ")", "key_changes", "=", "sorted", "(", "(", "st...
[ 280, 0 ]
[ 313, 18 ]
python
en
['en', 'en', 'en']
True
add_chords_to_sequence
(note_sequence, chords, chord_times)
Add chords to a NoteSequence (in place) at specified times. Args: note_sequence: The NoteSequence proto to which chords will be added (in place). Should not already have chords. chords: A Python list of chord figure strings to add to `note_sequence` as text annotations. chord_times: A Pyt...
Add chords to a NoteSequence (in place) at specified times.
def add_chords_to_sequence(note_sequence, chords, chord_times): """Add chords to a NoteSequence (in place) at specified times. Args: note_sequence: The NoteSequence proto to which chords will be added (in place). Should not already have chords. chords: A Python list of chord figure strings to add t...
[ "def", "add_chords_to_sequence", "(", "note_sequence", ",", "chords", ",", "chord_times", ")", ":", "if", "any", "(", "ta", ".", "annotation_type", "==", "CHORD_SYMBOL", "for", "ta", "in", "note_sequence", ".", "text_annotations", ")", ":", "raise", "ValueError"...
[ 316, 0 ]
[ 344, 21 ]
python
en
['en', 'en', 'en']
True
add_keys_to_sequence
(note_sequence, keys, key_times)
Add key signatures to a NoteSequence (in place) at specified times. Args: note_sequence: The NoteSequence proto to which key signatures will be added (in place). Should not already have key signatures. keys: A Python list of keys (integers 0-11) to add to `note_sequence` as KeySignature field...
Add key signatures to a NoteSequence (in place) at specified times.
def add_keys_to_sequence(note_sequence, keys, key_times): """Add key signatures to a NoteSequence (in place) at specified times. Args: note_sequence: The NoteSequence proto to which key signatures will be added (in place). Should not already have key signatures. keys: A Python list of keys (integer...
[ "def", "add_keys_to_sequence", "(", "note_sequence", ",", "keys", ",", "key_times", ")", ":", "if", "note_sequence", ".", "key_signatures", ":", "raise", "ValueError", "(", "'NoteSequence already has keys.'", ")", "if", "any", "(", "t1", ">", "t2", "for", "t1", ...
[ 347, 0 ]
[ 374, 18 ]
python
en
['en', 'en', 'en']
True
ChordProgression.__init__
(self, events=None, **kwargs)
Construct a ChordProgression.
Construct a ChordProgression.
def __init__(self, events=None, **kwargs): """Construct a ChordProgression.""" if 'pad_event' in kwargs: del kwargs['pad_event'] super(ChordProgression, self).__init__(pad_event=NO_CHORD, events=events, **kwargs)
[ "def", "__init__", "(", "self", ",", "events", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'pad_event'", "in", "kwargs", ":", "del", "kwargs", "[", "'pad_event'", "]", "super", "(", "ChordProgression", ",", "self", ")", ".", "__init__", "(",...
[ 77, 2 ]
[ 82, 67 ]
python
en
['en', 'en', 'en']
True
ChordProgression._add_chord
(self, figure, start_step, end_step)
Adds the given chord to the `events` list. `start_step` is set to the given chord. Everything after `start_step` in `events` is deleted before the chord is added. `events`'s length will be changed so that the last event has index `end_step` - 1. Args: figure: Chord symbol figure. A string like ...
Adds the given chord to the `events` list.
def _add_chord(self, figure, start_step, end_step): """Adds the given chord to the `events` list. `start_step` is set to the given chord. Everything after `start_step` in `events` is deleted before the chord is added. `events`'s length will be changed so that the last event has index `end_step` - 1. ...
[ "def", "_add_chord", "(", "self", ",", "figure", ",", "start_step", ",", "end_step", ")", ":", "if", "start_step", ">=", "end_step", ":", "raise", "BadChordError", "(", "'Start step does not precede end step: start=%d, end=%d'", "%", "(", "start_step", ",", "end_ste...
[ 84, 2 ]
[ 109, 30 ]
python
en
['en', 'en', 'en']
True
ChordProgression.from_quantized_sequence
(self, quantized_sequence, start_step, end_step)
Populate self with the chords from the given quantized NoteSequence. A chord progression is extracted from the given sequence starting at time step `start_step` and ending at time step `end_step`. The number of time steps per bar is computed from the time signature in `quantized_sequence`. Args: ...
Populate self with the chords from the given quantized NoteSequence.
def from_quantized_sequence(self, quantized_sequence, start_step, end_step): """Populate self with the chords from the given quantized NoteSequence. A chord progression is extracted from the given sequence starting at time step `start_step` and ending at time step `end_step`. The number of time steps ...
[ "def", "from_quantized_sequence", "(", "self", ",", "quantized_sequence", ",", "start_step", ",", "end_step", ")", ":", "sequences_lib", ".", "assert_is_relative_quantized_sequence", "(", "quantized_sequence", ")", "self", ".", "_reset", "(", ")", "steps_per_bar_float",...
[ 111, 2 ]
[ 196, 29 ]
python
en
['en', 'en', 'en']
True
ChordProgression.to_sequence
(self, sequence_start_time=0.0, qpm=120.0)
Converts the ChordProgression to NoteSequence proto. This doesn't generate actual notes, but text annotations specifying the chord changes when they occur. Args: sequence_start_time: A time in seconds (float) that the first chord in the sequence will land on. qpm: Quarter notes per m...
Converts the ChordProgression to NoteSequence proto.
def to_sequence(self, sequence_start_time=0.0, qpm=120.0): """Converts the ChordProgression to NoteSequence proto. This doesn't generate actual notes, but text annotations specifying the chord changes when they occur. Args: sequence_start_time: A time in secon...
[ "def", "to_sequence", "(", "self", ",", "sequence_start_time", "=", "0.0", ",", "qpm", "=", "120.0", ")", ":", "seconds_per_step", "=", "60.0", "/", "qpm", "/", "self", ".", "steps_per_quarter", "sequence", "=", "music_pb2", ".", "NoteSequence", "(", ")", ...
[ 198, 2 ]
[ 229, 19 ]
python
en
['en', 'en', 'en']
True
ChordProgression.transpose
(self, transpose_amount)
Transpose chords in this ChordProgression. Args: transpose_amount: The number of half steps to transpose this ChordProgression. Positive values transpose up. Negative values transpose down. Raises: ChordSymbolError: If a chord (other than "no chord") fails to be inter...
Transpose chords in this ChordProgression.
def transpose(self, transpose_amount): """Transpose chords in this ChordProgression. Args: transpose_amount: The number of half steps to transpose this ChordProgression. Positive values transpose up. Negative values transpose down. Raises: ChordSymbolError: If a chord (othe...
[ "def", "transpose", "(", "self", ",", "transpose_amount", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_events", ")", ")", ":", "if", "self", ".", "_events", "[", "i", "]", "!=", "NO_CHORD", ":", "self", ".", "_events", "[", ...
[ 231, 2 ]
[ 246, 65 ]
python
en
['en', 'en', 'en']
True
ChordRenderer.render
(self, sequence)
Renders the chord symbols of a NoteSequence. This function renders chord symbol annotations in a NoteSequence as actual notes. Notes are added to the NoteSequence object, and the chord symbols remain also. Args: sequence: The NoteSequence for which to render chord symbols.
Renders the chord symbols of a NoteSequence.
def render(self, sequence): """Renders the chord symbols of a NoteSequence. This function renders chord symbol annotations in a NoteSequence as actual notes. Notes are added to the NoteSequence object, and the chord symbols remain also. Args: sequence: The NoteSequence for which to render ch...
[ "def", "render", "(", "self", ",", "sequence", ")", ":", "pass" ]
[ 382, 2 ]
[ 392, 8 ]
python
en
['en', 'en', 'en']
True
BasicChordRenderer.__init__
(self, velocity=100, instrument=1, program=88, octave=4, bass_octave=3)
Initialize a BasicChordRenderer object. Args: velocity: The MIDI note velocity to use. instrument: The MIDI instrument to use. program: The MIDI program to use. octave: The octave in which to render chord notes. If the bass note is not otherwise part of the chord, it will not be r...
Initialize a BasicChordRenderer object.
def __init__(self, velocity=100, instrument=1, program=88, octave=4, bass_octave=3): """Initialize a BasicChordRenderer object. Args: velocity: The MIDI note velocity to use. instrument: The MIDI instrument to use. pro...
[ "def", "__init__", "(", "self", ",", "velocity", "=", "100", ",", "instrument", "=", "1", ",", "program", "=", "88", ",", "octave", "=", "4", ",", "bass_octave", "=", "3", ")", ":", "self", ".", "_velocity", "=", "velocity", "self", ".", "_instrument...
[ 398, 2 ]
[ 418, 35 ]
python
da
['da', 'da', 'en']
True
BasicChordRenderer._render_notes
(self, sequence, pitches, bass_pitch, start_time, end_time)
Renders notes.
Renders notes.
def _render_notes(self, sequence, pitches, bass_pitch, start_time, end_time): """Renders notes.""" all_pitches = [] for pitch in pitches: all_pitches.append(12 * self._octave + pitch % 12) all_pitches.append(12 * self._bass_octave + bass_pitch % 12) for pitch in all_pitches: # Add a not...
[ "def", "_render_notes", "(", "self", ",", "sequence", ",", "pitches", ",", "bass_pitch", ",", "start_time", ",", "end_time", ")", ":", "all_pitches", "=", "[", "]", "for", "pitch", "in", "pitches", ":", "all_pitches", ".", "append", "(", "12", "*", "self...
[ 420, 2 ]
[ 435, 34 ]
python
af
['de', 'af', 'en']
False
__optim_args_from_interpreter_flags
()
Return a list of command-line arguments reproducing the current optimization settings in sys.flags.
Return a list of command-line arguments reproducing the current optimization settings in sys.flags.
def __optim_args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current optimization settings in sys.flags.""" args = [] value = sys.flags.optimize if value > 0: args.append("-" + "O" * value) return args
[ "def", "__optim_args_from_interpreter_flags", "(", ")", ":", "args", "=", "[", "]", "value", "=", "sys", ".", "flags", ".", "optimize", "if", "value", ">", "0", ":", "args", ".", "append", "(", "\"-\"", "+", "\"O\"", "*", "value", ")", "return", "args"...
[ 4, 0 ]
[ 11, 15 ]
python
en
['en', 'en', 'en']
True
TestDataContainer.add
(self, *args)
Add a new object to this container. Generally this method should only be used during data loading, since adding data during a test can affect the results of other tests.
Add a new object to this container.
def add(self, *args): """Add a new object to this container. Generally this method should only be used during data loading, since adding data during a test can affect the results of other tests. """ for obj in args: if obj not in self._objects: self._...
[ "def", "add", "(", "self", ",", "*", "args", ")", ":", "for", "obj", "in", "args", ":", "if", "obj", "not", "in", "self", ".", "_objects", ":", "self", ".", "_objects", ".", "append", "(", "obj", ")" ]
[ 80, 4 ]
[ 88, 41 ]
python
en
['en', 'en', 'en']
True
TestDataContainer.list
(self)
Returns a list of all objects in this container.
Returns a list of all objects in this container.
def list(self): """Returns a list of all objects in this container.""" return self._objects
[ "def", "list", "(", "self", ")", ":", "return", "self", ".", "_objects" ]
[ 90, 4 ]
[ 92, 28 ]
python
en
['en', 'en', 'en']
True
TestDataContainer.filter
(self, filtered=None, **kwargs)
Returns objects whose attributes match the given kwargs.
Returns objects whose attributes match the given kwargs.
def filter(self, filtered=None, **kwargs): """Returns objects whose attributes match the given kwargs.""" if filtered is None: filtered = self._objects try: key, value = kwargs.popitem() except KeyError: # We're out of filters, return retur...
[ "def", "filter", "(", "self", ",", "filtered", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "filtered", "is", "None", ":", "filtered", "=", "self", ".", "_objects", "try", ":", "key", ",", "value", "=", "kwargs", ".", "popitem", "(", ")", ...
[ 94, 4 ]
[ 108, 55 ]
python
en
['en', 'en', 'en']
True
TestDataContainer.get
(self, **kwargs)
Returns a single object whose attributes match the given kwargs. An error will be raised if the arguments provided don't return exactly one match.
Returns a single object whose attributes match the given kwargs.
def get(self, **kwargs): """Returns a single object whose attributes match the given kwargs. An error will be raised if the arguments provided don't return exactly one match. """ matches = self.filter(**kwargs) if not matches: raise Exception("No matches foun...
[ "def", "get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "matches", "=", "self", ".", "filter", "(", "*", "*", "kwargs", ")", "if", "not", "matches", ":", "raise", "Exception", "(", "\"No matches found.\"", ")", "elif", "len", "(", "matches", ")...
[ 110, 4 ]
[ 122, 32 ]
python
en
['en', 'en', 'en']
True
TestDataContainer.first
(self)
Returns the first object from this container.
Returns the first object from this container.
def first(self): """Returns the first object from this container.""" return self._objects[0]
[ "def", "first", "(", "self", ")", ":", "return", "self", ".", "_objects", "[", "0", "]" ]
[ 124, 4 ]
[ 126, 31 ]
python
en
['en', 'en', 'en']
True
ZulipBaseCommand.get_client
(self)
Returns a Zulip Client object to be used for things done in management commands
Returns a Zulip Client object to be used for things done in management commands
def get_client(self) -> Client: """Returns a Zulip Client object to be used for things done in management commands""" return get_client("ZulipServer")
[ "def", "get_client", "(", "self", ")", "->", "Client", ":", "return", "get_client", "(", "\"ZulipServer\"", ")" ]
[ 145, 4 ]
[ 147, 40 ]
python
en
['en', 'en', 'en']
True
GroupActionProvider.view
(self)
Handles the view logic. If no response is given, we continue to the next action provider.
Handles the view logic. If no response is given, we continue to the next action provider.
def view(self): """ Handles the view logic. If no response is given, we continue to the next action provider. """
[ "def", "view", "(", "self", ")", ":" ]
[ 71, 4 ]
[ 74, 11 ]
python
en
['en', 'error', 'th']
False
GroupActionProvider.tags
(self, request, tag_list, group)
Modifies the tag list for a grouped message.
Modifies the tag list for a grouped message.
def tags(self, request, tag_list, group): """Modifies the tag list for a grouped message.""" return tag_list
[ "def", "tags", "(", "self", ",", "request", ",", "tag_list", ",", "group", ")", ":", "return", "tag_list" ]
[ 76, 4 ]
[ 78, 23 ]
python
en
['en', 'en', 'en']
True
GroupActionProvider.actions
(self, request, action_list, group)
Modifies the action list for a grouped message.
Modifies the action list for a grouped message.
def actions(self, request, action_list, group): """Modifies the action list for a grouped message.""" return action_list
[ "def", "actions", "(", "self", ",", "request", ",", "action_list", ",", "group", ")", ":", "return", "action_list" ]
[ 80, 4 ]
[ 82, 26 ]
python
en
['en', 'en', 'en']
True
GroupActionProvider.panels
(self, request, panel_list, group)
Modifies the panel list for a grouped message.
Modifies the panel list for a grouped message.
def panels(self, request, panel_list, group): """Modifies the panel list for a grouped message.""" return panel_list
[ "def", "panels", "(", "self", ",", "request", ",", "panel_list", ",", "group", ")", ":", "return", "panel_list" ]
[ 84, 4 ]
[ 86, 25 ]
python
en
['en', 'en', 'en']
True
GroupActionProvider.widget
(self, request, group)
Renders as a widget in the group details sidebar.
Renders as a widget in the group details sidebar.
def widget(self, request, group): """ Renders as a widget in the group details sidebar. """
[ "def", "widget", "(", "self", ",", "request", ",", "group", ")", ":" ]
[ 88, 4 ]
[ 91, 11 ]
python
en
['en', 'error', 'th']
False
Random.__init__
(self, x=None)
Initialize an instance. Optional argument x controls seeding, as for Random.seed().
Initialize an instance.
def __init__(self, x=None): """Initialize an instance. Optional argument x controls seeding, as for Random.seed(). """ self.seed(x) self.gauss_next = None
[ "def", "__init__", "(", "self", ",", "x", "=", "None", ")", ":", "self", ".", "seed", "(", "x", ")", "self", ".", "gauss_next", "=", "None" ]
[ 86, 4 ]
[ 93, 30 ]
python
en
['en', 'en', 'en']
True
Random.seed
(self, a=None, version=2)
Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the bits are used if *a* is a str, bytes, o...
Initialize internal state from hashable object.
def seed(self, a=None, version=2): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits are used. For version 2 (the default), all of the b...
[ "def", "seed", "(", "self", ",", "a", "=", "None", ",", "version", "=", "2", ")", ":", "if", "version", "==", "1", "and", "isinstance", "(", "a", ",", "(", "str", ",", "bytes", ")", ")", ":", "a", "=", "a", ".", "decode", "(", "'latin-1'", ")...
[ 95, 4 ]
[ 125, 30 ]
python
en
['en', 'en', 'en']
True
Random.getstate
(self)
Return internal state; can be passed to setstate() later.
Return internal state; can be passed to setstate() later.
def getstate(self): """Return internal state; can be passed to setstate() later.""" return self.VERSION, super().getstate(), self.gauss_next
[ "def", "getstate", "(", "self", ")", ":", "return", "self", ".", "VERSION", ",", "super", "(", ")", ".", "getstate", "(", ")", ",", "self", ".", "gauss_next" ]
[ 127, 4 ]
[ 129, 64 ]
python
en
['en', 'en', 'en']
True
Random.setstate
(self, state)
Restore internal state from object returned by getstate().
Restore internal state from object returned by getstate().
def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3: version, internalstate, self.gauss_next = state super().setstate(internalstate) elif version == 2: version, internalstate, s...
[ "def", "setstate", "(", "self", ",", "state", ")", ":", "version", "=", "state", "[", "0", "]", "if", "version", "==", "3", ":", "version", ",", "internalstate", ",", "self", ".", "gauss_next", "=", "state", "super", "(", ")", ".", "setstate", "(", ...
[ 131, 4 ]
[ 151, 53 ]
python
en
['en', 'en', 'en']
True
Random.randrange
(self, start, stop=None, step=1, _int=int)
Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.
Choose a random item from range(start, stop[, step]).
def randrange(self, start, stop=None, step=1, _int=int): """Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. """ # This code is a bit messy to make it fast for ...
[ "def", "randrange", "(", "self", ",", "start", ",", "stop", "=", "None", ",", "step", "=", "1", ",", "_int", "=", "int", ")", ":", "# This code is a bit messy to make it fast for the", "# common case while still doing adequate error checking.", "istart", "=", "_int", ...
[ 172, 4 ]
[ 214, 48 ]
python
en
['en', 'no', 'en']
True
Random.randint
(self, a, b)
Return random integer in range [a, b], including both end points.
Return random integer in range [a, b], including both end points.
def randint(self, a, b): """Return random integer in range [a, b], including both end points. """ return self.randrange(a, b+1)
[ "def", "randint", "(", "self", ",", "a", ",", "b", ")", ":", "return", "self", ".", "randrange", "(", "a", ",", "b", "+", "1", ")" ]
[ 216, 4 ]
[ 220, 37 ]
python
en
['en', 'da', 'en']
True
Random._randbelow
(self, n, int=int, maxsize=1<<BPF, type=type, Method=_MethodType, BuiltinMethod=_BuiltinMethodType)
Return a random int in the range [0,n). Raises ValueError if n==0.
Return a random int in the range [0,n). Raises ValueError if n==0.
def _randbelow(self, n, int=int, maxsize=1<<BPF, type=type, Method=_MethodType, BuiltinMethod=_BuiltinMethodType): "Return a random int in the range [0,n). Raises ValueError if n==0." random = self.random getrandbits = self.getrandbits # Only call self.getrandbits if...
[ "def", "_randbelow", "(", "self", ",", "n", ",", "int", "=", "int", ",", "maxsize", "=", "1", "<<", "BPF", ",", "type", "=", "type", ",", "Method", "=", "_MethodType", ",", "BuiltinMethod", "=", "_BuiltinMethodType", ")", ":", "random", "=", "self", ...
[ 222, 4 ]
[ 250, 33 ]
python
en
['en', 'et', 'en']
True
Random.choice
(self, seq)
Choose a random element from a non-empty sequence.
Choose a random element from a non-empty sequence.
def choice(self, seq): """Choose a random element from a non-empty sequence.""" try: i = self._randbelow(len(seq)) except ValueError: raise IndexError('Cannot choose from an empty sequence') from None return seq[i]
[ "def", "choice", "(", "self", ",", "seq", ")", ":", "try", ":", "i", "=", "self", ".", "_randbelow", "(", "len", "(", "seq", ")", ")", "except", "ValueError", ":", "raise", "IndexError", "(", "'Cannot choose from an empty sequence'", ")", "from", "None", ...
[ 254, 4 ]
[ 260, 21 ]
python
en
['en', 'en', 'en']
True
Random.shuffle
(self, x, random=None)
Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used.
Shuffle list x in place, and return None.
def shuffle(self, x, random=None): """Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used. """ if random is None: ...
[ "def", "shuffle", "(", "self", ",", "x", ",", "random", "=", "None", ")", ":", "if", "random", "is", "None", ":", "randbelow", "=", "self", ".", "_randbelow", "for", "i", "in", "reversed", "(", "range", "(", "1", ",", "len", "(", "x", ")", ")", ...
[ 262, 4 ]
[ 282, 39 ]
python
en
['en', 'en', 'en']
True
Random.sample
(self, population, k)
Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allow...
Chooses k unique random elements from a population sequence or set.
def sample(self, population, k): """Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also ...
[ "def", "sample", "(", "self", ",", "population", ",", "k", ")", ":", "# Sampling without replacement entails tracking either potential", "# selections (the pool) in a list or previous selections in a set.", "# When the number of selections is small compared to the", "# population, then tra...
[ 284, 4 ]
[ 340, 21 ]
python
en
['en', 'en', 'en']
True
Random.choices
(self, population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability.
Return a k sized list of population elements chosen with replacement.
def choices(self, population, weights=None, *, cum_weights=None, k=1): """Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified, the selections are made with equal probability. """ random = self.ran...
[ "def", "choices", "(", "self", ",", "population", ",", "weights", "=", "None", ",", "*", ",", "cum_weights", "=", "None", ",", "k", "=", "1", ")", ":", "random", "=", "self", ".", "random", "if", "cum_weights", "is", "None", ":", "if", "weights", "...
[ 342, 4 ]
[ 362, 84 ]
python
en
['en', 'en', 'en']
True
Random.uniform
(self, a, b)
Get a random number in the range [a, b) or [a, b] depending on rounding.
Get a random number in the range [a, b) or [a, b] depending on rounding.
def uniform(self, a, b): "Get a random number in the range [a, b) or [a, b] depending on rounding." return a + (b-a) * self.random()
[ "def", "uniform", "(", "self", ",", "a", ",", "b", ")", ":", "return", "a", "+", "(", "b", "-", "a", ")", "*", "self", ".", "random", "(", ")" ]
[ 368, 4 ]
[ 370, 40 ]
python
en
['en', 'en', 'en']
True
Random.triangular
(self, low=0.0, high=1.0, mode=None)
Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution
Triangular distribution.
def triangular(self, low=0.0, high=1.0, mode=None): """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution """ u = self.random() ...
[ "def", "triangular", "(", "self", ",", "low", "=", "0.0", ",", "high", "=", "1.0", ",", "mode", "=", "None", ")", ":", "u", "=", "self", ".", "random", "(", ")", "try", ":", "c", "=", "0.5", "if", "mode", "is", "None", "else", "(", "mode", "-...
[ 374, 4 ]
[ 392, 50 ]
python
de
['de', 'ja', 'en']
False
Random.normalvariate
(self, mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.
Normal distribution.
def normalvariate(self, mu, sigma): """Normal distribution. mu is the mean, and sigma is the standard deviation. """ # mu = mean, sigma = standard deviation # Uses Kinderman and Monahan method. Reference: Kinderman, # A.J. and Monahan, J.F., "Computer generation of ran...
[ "def", "normalvariate", "(", "self", ",", "mu", ",", "sigma", ")", ":", "# mu = mean, sigma = standard deviation", "# Uses Kinderman and Monahan method. Reference: Kinderman,", "# A.J. and Monahan, J.F., \"Computer generation of random", "# variables using the ratio of uniform deviates\", ...
[ 396, 4 ]
[ 417, 27 ]
python
en
['es', 'en', 'en']
False
Random.lognormvariate
(self, mu, sigma)
Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.
Log normal distribution.
def lognormvariate(self, mu, sigma): """Log normal distribution. If you take the natural logarithm of this distribution, you'll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero. """ return _e...
[ "def", "lognormvariate", "(", "self", ",", "mu", ",", "sigma", ")", ":", "return", "_exp", "(", "self", ".", "normalvariate", "(", "mu", ",", "sigma", ")", ")" ]
[ 421, 4 ]
[ 429, 50 ]
python
ceb
['da', 'ceb', 'en']
False
Random.expovariate
(self, lambd)
Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 i...
Exponential distribution.
def expovariate(self, lambd): """Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called "lambda", but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, ...
[ "def", "expovariate", "(", "self", ",", "lambd", ")", ":", "# lambd: rate lambd = 1/mean", "# ('lambda' is a Python reserved word)", "# we use 1-random() instead of random() to preclude the", "# possibility of taking the log of zero.", "return", "-", "_log", "(", "1.0", "-", "sel...
[ 433, 4 ]
[ 448, 47 ]
python
en
['da', 'en', 'en']
False