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
Builder.add_attributes
(self, data, type)
add required attributes
add required attributes
def add_attributes(self, data, type): """ add required attributes """ for attr, ancestry in type.attributes(): name = '_%s' % attr.name value = attr.get_default() setattr(data, name, value)
[ "def", "add_attributes", "(", "self", ",", "data", ",", "type", ")", ":", "for", "attr", ",", "ancestry", "in", "type", ".", "attributes", "(", ")", ":", "name", "=", "'_%s'", "%", "attr", ".", "name", "value", "=", "attr", ".", "get_default", "(", ...
[ 94, 4 ]
[ 99, 38 ]
python
en
['en', 'en', 'en']
True
Builder.skip_child
(self, child, ancestry)
get whether or not to skip the specified child
get whether or not to skip the specified child
def skip_child(self, child, ancestry): """ get whether or not to skip the specified child """ if child.any(): return True for x in ancestry: if x.choice(): return True return False
[ "def", "skip_child", "(", "self", ",", "child", ",", "ancestry", ")", ":", "if", "child", ".", "any", "(", ")", ":", "return", "True", "for", "x", "in", "ancestry", ":", "if", "x", ".", "choice", "(", ")", ":", "return", "True", "return", "False" ]
[ 101, 4 ]
[ 107, 20 ]
python
en
['en', 'en', 'en']
True
Builder.ordering
(self, type)
get the ordering
get the ordering
def ordering(self, type): """ get the ordering """ result = [] for child, ancestry in type.resolve(): name = child.name if child.name is None: continue if child.isattr(): name = '_%s' % child.name result.append(name)...
[ "def", "ordering", "(", "self", ",", "type", ")", ":", "result", "=", "[", "]", "for", "child", ",", "ancestry", "in", "type", ".", "resolve", "(", ")", ":", "name", "=", "child", ".", "name", "if", "child", ".", "name", "is", "None", ":", "conti...
[ 109, 4 ]
[ 119, 21 ]
python
en
['en', 'en', 'en']
True
BaseAdapter.send
(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up...
Sends PreparedRequest object. Returns Response object.
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request co...
[ "def", "send", "(", "self", ",", "request", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ")", ":", "raise", "NotImplementedError" ]
[ 60, 4 ]
[ 76, 33 ]
python
en
['en', 'lb', 'en']
True
BaseAdapter.close
(self)
Cleans up adapter specific items.
Cleans up adapter specific items.
def close(self): """Cleans up adapter specific items.""" raise NotImplementedError
[ "def", "close", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 78, 4 ]
[ 80, 33 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.init_poolmanager
(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs)
Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The ma...
Initializes a urllib3 PoolManager.
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): """Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. ...
[ "def", "init_poolmanager", "(", "self", ",", "connections", ",", "maxsize", ",", "block", "=", "DEFAULT_POOLBLOCK", ",", "*", "*", "pool_kwargs", ")", ":", "# save these values for pickling", "self", ".", "_pool_connections", "=", "connections", "self", ".", "_poo...
[ 145, 4 ]
[ 163, 79 ]
python
en
['en', 'en', 'it']
True
HTTPAdapter.proxy_manager_for
(self, proxy, **proxy_kwargs)
Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kw...
Return urllib3 ProxyManager for the given proxy.
def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The prox...
[ "def", "proxy_manager_for", "(", "self", ",", "proxy", ",", "*", "*", "proxy_kwargs", ")", ":", "if", "proxy", "in", "self", ".", "proxy_manager", ":", "manager", "=", "self", ".", "proxy_manager", "[", "proxy", "]", "elif", "proxy", ".", "lower", "(", ...
[ 165, 4 ]
[ 200, 22 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.cert_verify
(self, conn, url, verify, cert)
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :...
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with...
[ "def", "cert_verify", "(", "self", ",", "conn", ",", "url", ",", "verify", ",", "cert", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "'https'", ")", "and", "verify", ":", "cert_loc", "=", "None", "# Allow self-specified cert loc...
[ 202, 4 ]
[ 252, 71 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.build_response
(self, req, resp)
Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used ...
Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The ...
[ "def", "build_response", "(", "self", ",", "req", ",", "resp", ")", ":", "response", "=", "Response", "(", ")", "# Fallback to None if there's no status_code, for whatever reason.", "response", ".", "status_code", "=", "getattr", "(", "resp", ",", "'status'", ",", ...
[ 254, 4 ]
[ 289, 23 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.get_connection
(self, url, proxies=None)
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of p...
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :pa...
[ "def", "get_connection", "(", "self", ",", "url", ",", "proxies", "=", "None", ")", ":", "proxy", "=", "select_proxy", "(", "url", ",", "proxies", ")", "if", "proxy", ":", "proxy", "=", "prepend_scheme_if_needed", "(", "proxy", ",", "'http'", ")", "proxy...
[ 291, 4 ]
[ 316, 19 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.close
(self)
Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections.
Disposes of any internal state.
def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
[ "def", "close", "(", "self", ")", ":", "self", ".", "poolmanager", ".", "clear", "(", ")", "for", "proxy", "in", "self", ".", "proxy_manager", ".", "values", "(", ")", ":", "proxy", ".", "clear", "(", ")" ]
[ 318, 4 ]
[ 326, 25 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.request_url
(self, request, proxies)
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the ...
Obtain the url to use when making the final request.
def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is o...
[ "def", "request_url", "(", "self", ",", "request", ",", "proxies", ")", ":", "proxy", "=", "select_proxy", "(", "request", ".", "url", ",", "proxies", ")", "scheme", "=", "urlparse", "(", "request", ".", "url", ")", ".", "scheme", "is_proxied_http_request"...
[ 328, 4 ]
[ 355, 18 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.add_headers
(self, request, **kwargs)
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the ...
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is on...
[ "def", "add_headers", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "pass" ]
[ 357, 4 ]
[ 369, 12 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.proxy_headers
(self, proxy)
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed f...
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used.
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be c...
[ "def", "proxy_headers", "(", "self", ",", "proxy", ")", ":", "headers", "=", "{", "}", "username", ",", "password", "=", "get_auth_from_url", "(", "proxy", ")", "if", "username", ":", "headers", "[", "'Proxy-Authorization'", "]", "=", "_basic_auth_str", "(",...
[ 371, 4 ]
[ 391, 22 ]
python
en
['en', 'en', 'en']
True
HTTPAdapter.send
(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up...
Sends PreparedRequest object. Returns Response object.
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. ...
[ "def", "send", "(", "self", ",", "request", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ")", ":", "try", ":", "conn", "=", "self", ".", "get_connection...
[ 393, 4 ]
[ 532, 49 ]
python
en
['en', 'lb', 'en']
True
enabled
()
Allow selection of distutils by environment variable.
Allow selection of distutils by environment variable.
def enabled(): """ Allow selection of distutils by environment variable. """ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib') return which == 'local'
[ "def", "enabled", "(", ")", ":", "which", "=", "os", ".", "environ", ".", "get", "(", "'SETUPTOOLS_USE_DISTUTILS'", ",", "'stdlib'", ")", "return", "which", "==", "'local'" ]
[ 35, 0 ]
[ 40, 27 ]
python
en
['en', 'error', 'th']
False
do_override
()
Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation.
Ensure that the local copy of distutils is preferred over stdlib.
def do_override(): """ Ensure that the local copy of distutils is preferred over stdlib. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 for more motivation. """ if enabled(): warn_distutils_present() ensure_local_distutils()
[ "def", "do_override", "(", ")", ":", "if", "enabled", "(", ")", ":", "warn_distutils_present", "(", ")", "ensure_local_distutils", "(", ")" ]
[ 54, 0 ]
[ 63, 32 ]
python
en
['en', 'error', 'th']
False
DistutilsMetaFinder.spec_for_pip
(self)
Ensure stdlib distutils when running under pip. See pypa/pip#8761 for rationale.
Ensure stdlib distutils when running under pip. See pypa/pip#8761 for rationale.
def spec_for_pip(self): """ Ensure stdlib distutils when running under pip. See pypa/pip#8761 for rationale. """ if self.pip_imported_during_build(): return clear_distutils() self.spec_for_distutils = lambda: None
[ "def", "spec_for_pip", "(", "self", ")", ":", "if", "self", ".", "pip_imported_during_build", "(", ")", ":", "return", "clear_distutils", "(", ")", "self", ".", "spec_for_distutils", "=", "lambda", ":", "None" ]
[ 89, 4 ]
[ 97, 46 ]
python
en
['en', 'error', 'th']
False
DistutilsMetaFinder.pip_imported_during_build
()
Detect if pip is being imported in a build script. Ref #2355.
Detect if pip is being imported in a build script. Ref #2355.
def pip_imported_during_build(): """ Detect if pip is being imported in a build script. Ref #2355. """ import traceback return any( frame.f_globals['__file__'].endswith('setup.py') for frame, line in traceback.walk_stack(None) )
[ "def", "pip_imported_during_build", "(", ")", ":", "import", "traceback", "return", "any", "(", "frame", ".", "f_globals", "[", "'__file__'", "]", ".", "endswith", "(", "'setup.py'", ")", "for", "frame", ",", "line", "in", "traceback", ".", "walk_stack", "("...
[ 100, 4 ]
[ 108, 9 ]
python
en
['en', 'error', 'th']
False
generate_saml_response
( self, email: str, name: str, extra_attributes: Mapping[str, List[str]] = {} )
The samlresponse.txt fixture has a pre-generated SAMLResponse, with {email}, {first_name}, {last_name} placeholders, that can be filled out with the data we want.
The samlresponse.txt fixture has a pre-generated SAMLResponse, with {email}, {first_name}, {last_name} placeholders, that can be filled out with the data we want.
def generate_saml_response( self, email: str, name: str, extra_attributes: Mapping[str, List[str]] = {} ) -> str: """ The samlresponse.txt fixture has a pre-generated SAMLResponse, with {email}, {first_name}, {last_name} placeholders, that can be filled out with the data we w...
[ "def", "generate_saml_response", "(", "self", ",", "email", ":", "str", ",", "name", ":", "str", ",", "extra_attributes", ":", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", "=", "{", "}", ")", "->", "str", ":", "name_parts", "=", "name", ...
[ 1802, 4 ]
[ 1837, 28 ]
python
en
['en', 'error', 'th']
False
test_social_auth_no_key
(self)
Since in the case of SAML there isn't a direct equivalent of CLIENT_KEY_SETTING, we override this test, to test for the case where the obligatory SOCIAL_AUTH_SAML_ENABLED_IDPS isn't configured.
Since in the case of SAML there isn't a direct equivalent of CLIENT_KEY_SETTING, we override this test, to test for the case where the obligatory SOCIAL_AUTH_SAML_ENABLED_IDPS isn't configured.
def test_social_auth_no_key(self) -> None: """ Since in the case of SAML there isn't a direct equivalent of CLIENT_KEY_SETTING, we override this test, to test for the case where the obligatory SOCIAL_AUTH_SAML_ENABLED_IDPS isn't configured. """ account_data_dict = self.ge...
[ "def", "test_social_auth_no_key", "(", "self", ")", "->", "None", ":", "account_data_dict", "=", "self", ".", "get_account_data_dict", "(", "email", "=", "self", ".", "email", ",", "name", "=", "self", ".", "name", ")", "with", "self", ".", "settings", "("...
[ 1842, 4 ]
[ 1859, 99 ]
python
en
['en', 'error', 'th']
False
test_social_auth_complete_valid_get_idp_bad_samlresponse
(self)
This tests for a hypothetical scenario where our basic parsing of the SAMLResponse successfully returns the issuing IdP, but it fails further down the line, during proper validation in the underlying libraries.
This tests for a hypothetical scenario where our basic parsing of the SAMLResponse successfully returns the issuing IdP, but it fails further down the line, during proper validation in the underlying libraries.
def test_social_auth_complete_valid_get_idp_bad_samlresponse(self) -> None: """ This tests for a hypothetical scenario where our basic parsing of the SAMLResponse successfully returns the issuing IdP, but it fails further down the line, during proper validation in the underlying librarie...
[ "def", "test_social_auth_complete_valid_get_idp_bad_samlresponse", "(", "self", ")", "->", "None", ":", "with", "self", ".", "assertLogs", "(", "self", ".", "logger_string", ",", "level", "=", "\"INFO\"", ")", "as", "m", ",", "mock", ".", "patch", ".", "object...
[ 2049, 4 ]
[ 2072, 39 ]
python
en
['en', 'error', 'th']
False
test_social_auth_invalid_email
(self)
This test needs an override from the original class. For security reasons, the 'next' and 'mobile_flow_otp' params don't get passed on in the session if the authentication attempt failed. See SAMLAuthBackend.auth_complete for details.
This test needs an override from the original class. For security reasons, the 'next' and 'mobile_flow_otp' params don't get passed on in the session if the authentication attempt failed. See SAMLAuthBackend.auth_complete for details.
def test_social_auth_invalid_email(self) -> None: """ This test needs an override from the original class. For security reasons, the 'next' and 'mobile_flow_otp' params don't get passed on in the session if the authentication attempt failed. See SAMLAuthBackend.auth_complete for details....
[ "def", "test_social_auth_invalid_email", "(", "self", ")", "->", "None", ":", "account_data_dict", "=", "self", ".", "get_account_data_dict", "(", "email", "=", "\"invalid\"", ",", "name", "=", "self", ".", "name", ")", "with", "self", ".", "assertLogs", "(", ...
[ 2101, 4 ]
[ 2119, 47 ]
python
en
['en', 'error', 'th']
False
SocialAuthBase.social_auth_test
( self, account_data_dict: Dict[str, str], *, subdomain: str, mobile_flow_otp: Optional[str] = None, desktop_flow_otp: Optional[str] = None, is_signup: bool = False, next: str = "", multiuse_object_key: str = "", expect_choose_email_screen:...
Main entrypoint for all social authentication tests. * account_data_dict: Dictionary containing the name/email data that should be returned by the social auth backend. * subdomain: Which organization's login page is being accessed. * desktop_flow_otp / mobile_flow_otp: Token to be use...
Main entrypoint for all social authentication tests.
def social_auth_test( self, account_data_dict: Dict[str, str], *, subdomain: str, mobile_flow_otp: Optional[str] = None, desktop_flow_otp: Optional[str] = None, is_signup: bool = False, next: str = "", multiuse_object_key: str = "", expect_...
[ "def", "social_auth_test", "(", "self", ",", "account_data_dict", ":", "Dict", "[", "str", ",", "str", "]", ",", "*", ",", "subdomain", ":", "str", ",", "mobile_flow_otp", ":", "Optional", "[", "str", "]", "=", "None", ",", "desktop_flow_otp", ":", "Opti...
[ 892, 4 ]
[ 985, 21 ]
python
en
['en', 'en', 'en']
True
SocialAuthBase.test_social_auth_registration_existing_account
(self)
If the user already exists, signup flow just logs them in
If the user already exists, signup flow just logs them in
def test_social_auth_registration_existing_account(self) -> None: """If the user already exists, signup flow just logs them in""" email = "hamlet@zulip.com" name = "Full Name" account_data_dict = self.get_account_data_dict(email=email, name=name) result = self.social_auth_test( ...
[ "def", "test_social_auth_registration_existing_account", "(", "self", ")", "->", "None", ":", "email", "=", "\"hamlet@zulip.com\"", "name", "=", "\"Full Name\"", "account_data_dict", "=", "self", ".", "get_account_data_dict", "(", "email", "=", "email", ",", "name", ...
[ 1246, 4 ]
[ 1265, 57 ]
python
en
['en', 'en', 'en']
True
SocialAuthBase.test_social_auth_registration
(self)
If the user doesn't exist yet, social auth can be used to register an account
If the user doesn't exist yet, social auth can be used to register an account
def test_social_auth_registration(self) -> None: """If the user doesn't exist yet, social auth can be used to register an account""" email = "newuser@zulip.com" name = "Full Name" subdomain = "zulip" realm = get_realm("zulip") account_data_dict = self.get_account_data_dic...
[ "def", "test_social_auth_registration", "(", "self", ")", "->", "None", ":", "email", "=", "\"newuser@zulip.com\"", "name", "=", "\"Full Name\"", "subdomain", "=", "\"zulip\"", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "account_data_dict", "=", "self", "."...
[ 1350, 4 ]
[ 1362, 9 ]
python
en
['en', 'en', 'en']
True
SocialAuthBase.test_social_auth_registration_invitation_exists
(self)
This tests the registration flow in the case where an invitation for the user was generated.
This tests the registration flow in the case where an invitation for the user was generated.
def test_social_auth_registration_invitation_exists(self) -> None: """ This tests the registration flow in the case where an invitation for the user was generated. """ email = "newuser@zulip.com" name = "Full Name" subdomain = "zulip" realm = get_realm("zu...
[ "def", "test_social_auth_registration_invitation_exists", "(", "self", ")", "->", "None", ":", "email", "=", "\"newuser@zulip.com\"", "name", "=", "\"Full Name\"", "subdomain", "=", "\"zulip\"", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "iago", "=", "self", ...
[ 1419, 4 ]
[ 1438, 9 ]
python
en
['en', 'error', 'th']
False
SocialAuthBase.test_social_auth_registration_using_multiuse_invite
(self)
If the user doesn't exist yet, social auth can be used to register an account
If the user doesn't exist yet, social auth can be used to register an account
def test_social_auth_registration_using_multiuse_invite(self) -> None: """If the user doesn't exist yet, social auth can be used to register an account""" email = "newuser@zulip.com" name = "Full Name" subdomain = "zulip" realm = get_realm("zulip") realm.invite_required =...
[ "def", "test_social_auth_registration_using_multiuse_invite", "(", "self", ")", "->", "None", ":", "email", "=", "\"newuser@zulip.com\"", "name", "=", "\"Full Name\"", "subdomain", "=", "\"zulip\"", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "realm", ".", "in...
[ 1441, 4 ]
[ 1482, 9 ]
python
en
['en', 'en', 'en']
True
SocialAuthBase.test_social_auth_registration_without_is_signup
(self)
If `is_signup` is not set then a new account isn't created
If `is_signup` is not set then a new account isn't created
def test_social_auth_registration_without_is_signup(self) -> None: """If `is_signup` is not set then a new account isn't created""" email = "newuser@zulip.com" name = "Full Name" account_data_dict = self.get_account_data_dict(email=email, name=name) result = self.social_auth_test...
[ "def", "test_social_auth_registration_without_is_signup", "(", "self", ")", "->", "None", ":", "email", "=", "\"newuser@zulip.com\"", "name", "=", "\"Full Name\"", "account_data_dict", "=", "self", ".", "get_account_data_dict", "(", "email", "=", "email", ",", "name",...
[ 1484, 4 ]
[ 1504, 82 ]
python
en
['en', 'en', 'en']
True
SocialAuthBase.test_social_auth_registration_without_is_signup_closed_realm
(self)
If the user doesn't exist yet in closed realm, give an error
If the user doesn't exist yet in closed realm, give an error
def test_social_auth_registration_without_is_signup_closed_realm(self) -> None: """If the user doesn't exist yet in closed realm, give an error""" realm = get_realm("zulip") do_set_realm_property(realm, "emails_restricted_to_domains", True, acting_user=None) email = "nonexisting@phantom....
[ "def", "test_social_auth_registration_without_is_signup_closed_realm", "(", "self", ")", "->", "None", ":", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "do_set_realm_property", "(", "realm", ",", "\"emails_restricted_to_domains\"", ",", "True", ",", "acting_user", ...
[ 1506, 4 ]
[ 1534, 9 ]
python
en
['en', 'en', 'en']
True
SocialAuthBase.test_social_auth_with_ldap_auth_registration_from_confirmation
(self)
This test checks that in configurations that use the LDAP authentication backend and a social backend, it is possible to create non-LDAP users via the social backend.
This test checks that in configurations that use the LDAP authentication backend and a social backend, it is possible to create non-LDAP users via the social backend.
def test_social_auth_with_ldap_auth_registration_from_confirmation(self) -> None: """ This test checks that in configurations that use the LDAP authentication backend and a social backend, it is possible to create non-LDAP users via the social backend. """ self.init_default_ldap_...
[ "def", "test_social_auth_with_ldap_auth_registration_from_confirmation", "(", "self", ")", "->", "None", ":", "self", ".", "init_default_ldap_database", "(", ")", "email", "=", "self", ".", "nonreg_email", "(", "\"alice\"", ")", "name", "=", "\"Alice Social\"", "realm...
[ 1600, 4 ]
[ 1652, 9 ]
python
en
['en', 'error', 'th']
False
path_to_test_resource
(file_name)
Given a file name in the test resources directory, returns a complete path to that file. Args: file_name (str): Name of the file in the test resources directory. Returns: str: Full path to the file relative to the current working directory.
Given a file name in the test resources directory, returns a complete path to that file.
def path_to_test_resource(file_name): """ Given a file name in the test resources directory, returns a complete path to that file. Args: file_name (str): Name of the file in the test resources directory. Returns: str: Full path to the file relative to the current working directory....
[ "def", "path_to_test_resource", "(", "file_name", ")", ":", "path_here", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "resource_directory", "=", "os", ".", "path", ".", "join", "(", "path_here...
[ 8, 0 ]
[ 22, 20 ]
python
en
['en', 'error', 'th']
False
default_ws_client_setup
(mock_server_url)
Returns a 3-tuple with a WebsocketClient, TranscriptionConfig and AudioSettings all with default settings for use in test cases. Args: mock_server_url (str): address that the mock RT server is listening on. Returns: Tuple[WebsocketClient, TranscriptionConfig, AudioSettings]: Websocket...
Returns a 3-tuple with a WebsocketClient, TranscriptionConfig and AudioSettings all with default settings for use in test cases.
def default_ws_client_setup(mock_server_url): """ Returns a 3-tuple with a WebsocketClient, TranscriptionConfig and AudioSettings all with default settings for use in test cases. Args: mock_server_url (str): address that the mock RT server is listening on. Returns: Tuple[WebsocketC...
[ "def", "default_ws_client_setup", "(", "mock_server_url", ")", ":", "ssl_context", "=", "ssl", ".", "create_default_context", "(", ")", "ssl_context", ".", "check_hostname", "=", "False", "ssl_context", ".", "verify_mode", "=", "ssl", ".", "CERT_NONE", "conn_setting...
[ 25, 0 ]
[ 49, 58 ]
python
en
['en', 'error', 'th']
False
default_cfg
(algo='APPO', env='env', experiment='test')
Useful for tests.
Useful for tests.
def default_cfg(algo='APPO', env='env', experiment='test'): """Useful for tests.""" return parse_args(argv=[f'--algo={algo}', f'--env={env}', f'--experiment={experiment}'])
[ "def", "default_cfg", "(", "algo", "=", "'APPO'", ",", "env", "=", "'env'", ",", "experiment", "=", "'test'", ")", ":", "return", "parse_args", "(", "argv", "=", "[", "f'--algo={algo}'", ",", "f'--env={env}'", ",", "f'--experiment={experiment}'", "]", ")" ]
[ 103, 0 ]
[ 105, 92 ]
python
en
['en', 'en', 'en']
True
delete_old_scheduled_jobs
(apps: StateApps, schema_editor: DatabaseSchemaEditor)
Delete any old scheduled jobs, to handle changes in the format of send_email. Ideally, we'd translate the jobs, but it's not really worth the development effort to save a few invitation reminders and day2 followup emails.
Delete any old scheduled jobs, to handle changes in the format of send_email. Ideally, we'd translate the jobs, but it's not really worth the development effort to save a few invitation reminders and day2 followup emails.
def delete_old_scheduled_jobs(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: """Delete any old scheduled jobs, to handle changes in the format of send_email. Ideally, we'd translate the jobs, but it's not really worth the development effort to save a few invitation reminders and day2 fol...
[ "def", "delete_old_scheduled_jobs", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "ScheduledJob", "=", "apps", ".", "get_model", "(", "\"zerver\"", ",", "\"ScheduledJob\"", ")", "ScheduledJob", ".", "obje...
[ 6, 0 ]
[ 13, 39 ]
python
en
['en', 'en', 'en']
True
MongoChangeStream.__watch_all
(self)
Watch entire mongo instance and all its databases
Watch entire mongo instance and all its databases
def __watch_all(self): """Watch entire mongo instance and all its databases""" print("watching all databases and collections")
[ "def", "__watch_all", "(", "self", ")", ":", "print", "(", "\"watching all databases and collections\"", ")" ]
[ 12, 4 ]
[ 14, 55 ]
python
en
['en', 'en', 'en']
True
MongoChangeStream.__watch_database
(self)
Watch entire database and all its collections
Watch entire database and all its collections
def __watch_database(self): """Watch entire database and all its collections""" print("watching all collections within [x] database")
[ "def", "__watch_database", "(", "self", ")", ":", "print", "(", "\"watching all collections within [x] database\"", ")" ]
[ 16, 4 ]
[ 18, 61 ]
python
en
['en', 'en', 'en']
True
MongoChangeStream.__watch_collection
(self)
Watch entire collection
Watch entire collection
def __watch_collection(self): """Watch entire collection""" print("watching [x] collection")
[ "def", "__watch_collection", "(", "self", ")", ":", "print", "(", "\"watching [x] collection\"", ")" ]
[ 20, 4 ]
[ 22, 40 ]
python
en
['en', 'en', 'en']
True
MongoChangeStream.start
(self)
Start MongoDB change stream with watch type selected. Default watch option will be all if none is configured.
Start MongoDB change stream with watch type selected. Default watch option will be all if none is configured.
def start(self) -> None: """ Start MongoDB change stream with watch type selected. Default watch option will be all if none is configured. """ mongo_watch_options = { "ALL": self.__watch_all(), "DATABASE": self.__watch_database(), "COLLECTION":...
[ "def", "start", "(", "self", ")", "->", "None", ":", "mongo_watch_options", "=", "{", "\"ALL\"", ":", "self", ".", "__watch_all", "(", ")", ",", "\"DATABASE\"", ":", "self", ".", "__watch_database", "(", ")", ",", "\"COLLECTION\"", ":", "self", ".", "__w...
[ 24, 4 ]
[ 35, 73 ]
python
en
['en', 'error', 'th']
False
get_keyring_auth
(url, username)
Return the tuple auth for a given url from keyring.
Return the tuple auth for a given url from keyring.
def get_keyring_auth(url, username): # type: (str, str) -> Optional[AuthInfo] """Return the tuple auth for a given url from keyring.""" global keyring if not url or not keyring: return None try: try: get_credential = keyring.get_credential except AttributeError: ...
[ "def", "get_keyring_auth", "(", "url", ",", "username", ")", ":", "# type: (str, str) -> Optional[AuthInfo]", "global", "keyring", "if", "not", "url", "or", "not", "keyring", ":", "return", "None", "try", ":", "try", ":", "get_credential", "=", "keyring", ".", ...
[ 43, 0 ]
[ 73, 15 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth._get_index_url
(self, url)
Return the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its username and password removed already. If the original index url had credentia...
Return the original index URL matching the requested URL.
def _get_index_url(self, url): # type: (str) -> Optional[str] """Return the original index URL matching the requested URL. Cached or dynamically generated credentials may work against the original index URL rather than just the netloc. The provided url should have had its usern...
[ "def", "_get_index_url", "(", "self", ",", "url", ")", ":", "# type: (str) -> Optional[str]", "if", "not", "url", "or", "not", "self", ".", "index_urls", ":", "return", "None", "for", "u", "in", "self", ".", "index_urls", ":", "prefix", "=", "remove_auth_fro...
[ 90, 4 ]
[ 111, 19 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth._get_new_credentials
(self, original_url, allow_netrc=True, allow_keyring=True)
Find and return credentials for the specified URL.
Find and return credentials for the specified URL.
def _get_new_credentials(self, original_url, allow_netrc=True, allow_keyring=True): # type: (str, bool, bool) -> AuthInfo """Find and return credentials for the specified URL.""" # Split the credentials and netloc from the url. url, netloc, url_user_password ...
[ "def", "_get_new_credentials", "(", "self", ",", "original_url", ",", "allow_netrc", "=", "True", ",", "allow_keyring", "=", "True", ")", ":", "# type: (str, bool, bool) -> AuthInfo", "# Split the credentials and netloc from the url.", "url", ",", "netloc", ",", "url_user...
[ 113, 4 ]
[ 162, 33 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth._get_url_and_credentials
(self, original_url)
Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, username, password). Note that even if the original URL contains credentials, this function may return a different ...
Return the credentials to use for the provided URL.
def _get_url_and_credentials(self, original_url): # type: (str) -> Tuple[str, Optional[str], Optional[str]] """Return the credentials to use for the provided URL. If allowed, netrc and keyring may be used to obtain the correct credentials. Returns (url_without_credentials, user...
[ "def", "_get_url_and_credentials", "(", "self", ",", "original_url", ")", ":", "# type: (str) -> Tuple[str, Optional[str], Optional[str]]", "url", ",", "netloc", ",", "_", "=", "split_auth_netloc_from_url", "(", "original_url", ")", "# Use any stored credentials that we have fo...
[ 164, 4 ]
[ 203, 38 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth.warn_on_401
(self, resp, **kwargs)
Response callback to warn about incorrect credentials.
Response callback to warn about incorrect credentials.
def warn_on_401(self, resp, **kwargs): # type: (Response, **Any) -> None """Response callback to warn about incorrect credentials.""" if resp.status_code == 401: logger.warning( '401 Error, Credentials not correct for %s', resp.request.url, )
[ "def", "warn_on_401", "(", "self", ",", "resp", ",", "*", "*", "kwargs", ")", ":", "# type: (Response, **Any) -> None", "if", "resp", ".", "status_code", "==", "401", ":", "logger", ".", "warning", "(", "'401 Error, Credentials not correct for %s'", ",", "resp", ...
[ 287, 4 ]
[ 293, 13 ]
python
en
['en', 'en', 'en']
True
MultiDomainBasicAuth.save_credentials
(self, resp, **kwargs)
Response callback to save credentials on success.
Response callback to save credentials on success.
def save_credentials(self, resp, **kwargs): # type: (Response, **Any) -> None """Response callback to save credentials on success.""" assert keyring is not None, "should never reach here without keyring" if not keyring: return creds = self._credentials_to_save ...
[ "def", "save_credentials", "(", "self", ",", "resp", ",", "*", "*", "kwargs", ")", ":", "# type: (Response, **Any) -> None", "assert", "keyring", "is", "not", "None", ",", "\"should never reach here without keyring\"", "if", "not", "keyring", ":", "return", "creds",...
[ 295, 4 ]
[ 309, 62 ]
python
en
['en', 'en', 'en']
True
read_setup_file
(filename)
Reads a Setup file and returns Extension instances.
Reads a Setup file and returns Extension instances.
def read_setup_file(filename): """Reads a Setup file and returns Extension instances.""" from distutils.sysconfig import (parse_makefile, expand_makefile_vars, _variable_rx) from distutils.text_file import TextFile from distutils.util import split_quoted # Firs...
[ "def", "read_setup_file", "(", "filename", ")", ":", "from", "distutils", ".", "sysconfig", "import", "(", "parse_makefile", ",", "expand_makefile_vars", ",", "_variable_rx", ")", "from", "distutils", ".", "text_file", "import", "TextFile", "from", "distutils", "....
[ 140, 0 ]
[ 239, 21 ]
python
en
['en', 'en', 'en']
True
find_log_caller_module
(record: logging.LogRecord)
Find the module name corresponding to where this record was logged. Sadly `record.module` is just the innermost component of the full module name, so we have to go reconstruct this ourselves.
Find the module name corresponding to where this record was logged.
def find_log_caller_module(record: logging.LogRecord) -> Optional[str]: """Find the module name corresponding to where this record was logged. Sadly `record.module` is just the innermost component of the full module name, so we have to go reconstruct this ourselves. """ # Repeat a search similar to...
[ "def", "find_log_caller_module", "(", "record", ":", "logging", ".", "LogRecord", ")", "->", "Optional", "[", "str", "]", ":", "# Repeat a search similar to that in logging.Logger.findCaller.", "# The logging call should still be on the stack somewhere; search until", "# we find so...
[ 143, 0 ]
[ 159, 20 ]
python
en
['en', 'en', 'en']
True
log_to_file
( logger: Logger, filename: str, log_format: str = "%(asctime)s %(levelname)-8s %(message)s", )
Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.
Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.
def log_to_file( logger: Logger, filename: str, log_format: str = "%(asctime)s %(levelname)-8s %(message)s", ) -> None: """Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.""" formatter = logging.Formatter(log_format) handler = logging.FileHandler(filename) ...
[ "def", "log_to_file", "(", "logger", ":", "Logger", ",", "filename", ":", "str", ",", "log_format", ":", "str", "=", "\"%(asctime)s %(levelname)-8s %(message)s\"", ",", ")", "->", "None", ":", "formatter", "=", "logging", ".", "Formatter", "(", "log_format", "...
[ 288, 0 ]
[ 297, 30 ]
python
en
['en', 'en', 'en']
True
CodeHilite.hilite
(self)
Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with css to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">). returns : A string of html.
Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with css to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">).
def hilite(self): """ Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with css to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">). returns : A s...
[ "def", "hilite", "(", "self", ")", ":", "self", ".", "src", "=", "self", ".", "src", ".", "strip", "(", "'\\n'", ")", "self", ".", "_getLang", "(", ")", "try", ":", "from", "pygments", "import", "highlight", "from", "pygments", ".", "lexers", "import...
[ 61, 4 ]
[ 100, 56 ]
python
en
['en', 'error', 'th']
False
CodeHilite._escape
(self, txt)
basic html escaping
basic html escaping
def _escape(self, txt): """ basic html escaping """ txt = txt.replace('&', '&amp;') txt = txt.replace('<', '&lt;') txt = txt.replace('>', '&gt;') txt = txt.replace('"', '&quot;') return txt
[ "def", "_escape", "(", "self", ",", "txt", ")", ":", "txt", "=", "txt", ".", "replace", "(", "'&'", ",", "'&amp;'", ")", "txt", "=", "txt", ".", "replace", "(", "'<'", ",", "'&lt;'", ")", "txt", "=", "txt", ".", "replace", "(", "'>'", ",", "'&g...
[ 102, 4 ]
[ 108, 18 ]
python
en
['es', 'en', 'en']
True
CodeHilite._number
(self, txt)
Use <ol> for line numbering
Use <ol> for line numbering
def _number(self, txt): """ Use <ol> for line numbering """ # Fix Whitespace txt = txt.replace('\t', ' '*TAB_LENGTH) txt = txt.replace(" "*4, "&nbsp; &nbsp; ") txt = txt.replace(" "*3, "&nbsp; &nbsp;") txt = txt.replace(" "*2, "&nbsp; ") # Add lin...
[ "def", "_number", "(", "self", ",", "txt", ")", ":", "# Fix Whitespace", "txt", "=", "txt", ".", "replace", "(", "'\\t'", ",", "' '", "*", "TAB_LENGTH", ")", "txt", "=", "txt", ".", "replace", "(", "\" \"", "*", "4", ",", "\"&nbsp; &nbsp; \"", ")", "...
[ 110, 4 ]
[ 124, 18 ]
python
en
['en', 'en', 'en']
True
CodeHilite._getLang
(self)
Determines language of a code block from shebang lines and whether said line should be removed or left in place. If the sheband line contains a path (even a single /) then it is assumed to be a real shebang lines and left alone. However, if no path is given (e.i.: #!python or :::python...
Determines language of a code block from shebang lines and whether said line should be removed or left in place. If the sheband line contains a path (even a single /) then it is assumed to be a real shebang lines and left alone. However, if no path is given (e.i.: #!python or :::python...
def _getLang(self): """ Determines language of a code block from shebang lines and whether said line should be removed or left in place. If the sheband line contains a path (even a single /) then it is assumed to be a real shebang lines and left alone. However, if no path is giv...
[ "def", "_getLang", "(", "self", ")", ":", "import", "re", "#split text into lines", "lines", "=", "self", ".", "src", ".", "split", "(", "\"\\n\"", ")", "#pull first line to examine", "fl", "=", "lines", ".", "pop", "(", "0", ")", "c", "=", "re", ".", ...
[ 127, 4 ]
[ 172, 47 ]
python
en
['en', 'ja', 'th']
False
HiliteTreeprocessor.run
(self, root)
Find code blocks and store in htmlStash.
Find code blocks and store in htmlStash.
def run(self, root): """ Find code blocks and store in htmlStash. """ blocks = root.getiterator('pre') for block in blocks: children = block.getchildren() if len(children) == 1 and children[0].tag == 'code': code = CodeHilite(children[0].text, ...
[ "def", "run", "(", "self", ",", "root", ")", ":", "blocks", "=", "root", ".", "getiterator", "(", "'pre'", ")", "for", "block", "in", "blocks", ":", "children", "=", "block", ".", "getchildren", "(", ")", "if", "len", "(", "children", ")", "==", "1...
[ 180, 4 ]
[ 196, 40 ]
python
en
['en', 'en', 'en']
True
CodeHiliteExtension.extendMarkdown
(self, md, md_globals)
Add HilitePostprocessor to Markdown instance.
Add HilitePostprocessor to Markdown instance.
def extendMarkdown(self, md, md_globals): """ Add HilitePostprocessor to Markdown instance. """ hiliter = HiliteTreeprocessor(md) hiliter.config = self.config md.treeprocessors.add("hilite", hiliter, "_begin")
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "hiliter", "=", "HiliteTreeprocessor", "(", "md", ")", "hiliter", ".", "config", "=", "self", ".", "config", "md", ".", "treeprocessors", ".", "add", "(", "\"hilite\"", ",", "h...
[ 214, 4 ]
[ 218, 58 ]
python
en
['en', 'mt', 'en']
True
LPS25H.__init__
(self, bus_id=1)
Set up and access LPS25H digital barometer.
Set up and access LPS25H digital barometer.
def __init__(self, bus_id=1): """ Set up and access LPS25H digital barometer. """ super(LPS25H, self).__init__(bus_id) self.is_barometer_enabled = False
[ "def", "__init__", "(", "self", ",", "bus_id", "=", "1", ")", ":", "super", "(", "LPS25H", ",", "self", ")", ".", "__init__", "(", "bus_id", ")", "self", ".", "is_barometer_enabled", "=", "False" ]
[ 26, 4 ]
[ 31, 41 ]
python
en
['en', 'en', 'en']
True
LPS25H.__del__
(self)
Clean up.
Clean up.
def __del__(self): """ Clean up. """ try: # Power down barometer self.write_register(LPS25H_ADDR, LPS25H_CTRL_REG1, 0x00) super(LPS25H, self).__del__() except: pass
[ "def", "__del__", "(", "self", ")", ":", "try", ":", "# Power down barometer", "self", ".", "write_register", "(", "LPS25H_ADDR", ",", "LPS25H_CTRL_REG1", ",", "0x00", ")", "super", "(", "LPS25H", ",", "self", ")", ".", "__del__", "(", ")", "except", ":", ...
[ 33, 4 ]
[ 40, 16 ]
python
en
['de', 'en', 'en']
False
LPS25H.enable
(self)
Enable and set up the LPS25H barometer.
Enable and set up the LPS25H barometer.
def enable(self): """ Enable and set up the LPS25H barometer. """ # Power down device first self.write_register(LPS25H_ADDR, LPS25H_CTRL_REG1, 0x00) # Output data rate 12.5Hz # binary value -> 10110000, hex value -> 0xb0 self.write_register(LPS25H_ADDR, LPS25H_CTRL_REG1,...
[ "def", "enable", "(", "self", ")", ":", "# Power down device first", "self", ".", "write_register", "(", "LPS25H_ADDR", ",", "LPS25H_CTRL_REG1", ",", "0x00", ")", "# Output data rate 12.5Hz", "# binary value -> 10110000, hex value -> 0xb0", "self", ".", "write_register", ...
[ 42, 4 ]
[ 51, 40 ]
python
en
['en', 'en', 'en']
True
LPS25H.get_barometer_raw
(self)
Return the raw barometer sensor data.
Return the raw barometer sensor data.
def get_barometer_raw(self): """ Return the raw barometer sensor data. """ # Check if barometer has been enabled if not self.is_barometer_enabled: raise(Exception('Barometer is not enabled')) return self.read_1d_sensor(LPS25H_ADDR, self.barometer_registers)
[ "def", "get_barometer_raw", "(", "self", ")", ":", "# Check if barometer has been enabled", "if", "not", "self", ".", "is_barometer_enabled", ":", "raise", "(", "Exception", "(", "'Barometer is not enabled'", ")", ")", "return", "self", ".", "read_1d_sensor", "(", "...
[ 53, 4 ]
[ 59, 73 ]
python
en
['en', 'id', 'en']
True
description_of
(lines, name='stdin')
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
Return a string describing the probable encoding of a file or list of strings.
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = Univers...
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "bytearray", "(", "line", ")", "u", ".", "feed", "(", "line", ")", "# shortcut out of...
[ 25, 0 ]
[ 50, 44 ]
python
en
['en', 'error', 'th']
False
main
(argv=None)
Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str
Handles command line arguments and gets things started.
def main(argv=None): """ Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str """ # Get command line arguments parser = argparse.Argume...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "# Get command line arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Takes one or more file paths and reports their detected \\\n encodings\"", ")", "parser", ".", ...
[ 53, 0 ]
[ 80, 40 ]
python
en
['en', 'error', 'th']
False
dummy_add_partial_transcript
()
Returns a dummy AddPartialTranscript message.
Returns a dummy AddPartialTranscript message.
def dummy_add_partial_transcript(): """Returns a dummy AddPartialTranscript message.""" return { "message": "AddPartialTranscript", "format": "2.1", "metadata": {"start_time": 0.0, "end_time": 1.0, "transcript": "foo"}, "results": [ { "type": "word", ...
[ "def", "dummy_add_partial_transcript", "(", ")", ":", "return", "{", "\"message\"", ":", "\"AddPartialTranscript\"", ",", "\"format\"", ":", "\"2.1\"", ",", "\"metadata\"", ":", "{", "\"start_time\"", ":", "0.0", ",", "\"end_time\"", ":", "1.0", ",", "\"transcript...
[ 206, 0 ]
[ 222, 5 ]
python
en
['en', 'lb', 'en']
True
dummy_add_transcript
()
Returns a dummy AddTranscript message.
Returns a dummy AddTranscript message.
def dummy_add_transcript(): """Returns a dummy AddTranscript message.""" return { "message": "AddTranscript", "format": "2.1", "metadata": { "start_time": 0.0, "end_time": 2.0, "transcript": "Foo\nBar."}, "results": [ { "type": "word", ...
[ "def", "dummy_add_transcript", "(", ")", ":", "return", "{", "\"message\"", ":", "\"AddTranscript\"", ",", "\"format\"", ":", "\"2.1\"", ",", "\"metadata\"", ":", "{", "\"start_time\"", ":", "0.0", ",", "\"end_time\"", ":", "2.0", ",", "\"transcript\"", ":", "...
[ 225, 0 ]
[ 262, 5 ]
python
en
['en', 'lb', 'en']
True
MockRealtimeLogbook.find_messages_by_type
(self, msg_name)
Returns all messages received from the client of the given type. For `AddAudio` messages use `find_add_audio_messages`. Args: msg_name (str): The message type e.g. "SetRecognitionConfig" Returns: List[dict]: The matching list of messages.
Returns all messages received from the client of the given type. For `AddAudio` messages use `find_add_audio_messages`.
def find_messages_by_type(self, msg_name): """ Returns all messages received from the client of the given type. For `AddAudio` messages use `find_add_audio_messages`. Args: msg_name (str): The message type e.g. "SetRecognitionConfig" Returns: List[dict]:...
[ "def", "find_messages_by_type", "(", "self", ",", "msg_name", ")", ":", "return", "[", "msg", "for", "msg", "in", "self", ".", "messages_received", "if", "isinstance", "(", "msg", ",", "dict", ")", "and", "msg", "[", "\"message\"", "]", "==", "msg_name", ...
[ 22, 4 ]
[ 37, 9 ]
python
en
['en', 'error', 'th']
False
MockRealtimeLogbook.find_sent_messages_by_type
(self, msg_name)
Returns all messages sent to the client of the given type. Args: msg_name (str): The message type e.g. "AddTranscript" Returns: List[dict]: The matching list of messages.
Returns all messages sent to the client of the given type.
def find_sent_messages_by_type(self, msg_name): """ Returns all messages sent to the client of the given type. Args: msg_name (str): The message type e.g. "AddTranscript" Returns: List[dict]: The matching list of messages. """ return [ ...
[ "def", "find_sent_messages_by_type", "(", "self", ",", "msg_name", ")", ":", "return", "[", "msg", "for", "msg", "in", "self", ".", "messages_sent", "if", "isinstance", "(", "msg", ",", "dict", ")", "and", "msg", "[", "\"message\"", "]", "==", "msg_name", ...
[ 39, 4 ]
[ 53, 9 ]
python
en
['en', 'error', 'th']
False
MockRealtimeLogbook.find_add_audio_messages
(self)
Returns all binary `AddAudio` messages received from the client. Returns: List[bytearray]: The matching list of messages.
Returns all binary `AddAudio` messages received from the client.
def find_add_audio_messages(self): """ Returns all binary `AddAudio` messages received from the client. Returns: List[bytearray]: The matching list of messages. """ return [ msg for msg in self.messages_received if not isinstance(msg, dict)]
[ "def", "find_add_audio_messages", "(", "self", ")", ":", "return", "[", "msg", "for", "msg", "in", "self", ".", "messages_received", "if", "not", "isinstance", "(", "msg", ",", "dict", ")", "]" ]
[ 55, 4 ]
[ 63, 79 ]
python
en
['en', 'error', 'th']
False
MockRealtimeLogbook.find_start_recognition_message
(self)
Returns the `StartRecognition` message received from the client, assuming it was sent. Raises: AssertionError: If `StartRecognition` was not received. Returns: dict: The `StartRecognition` message.
Returns the `StartRecognition` message received from the client, assuming it was sent.
def find_start_recognition_message(self): """ Returns the `StartRecognition` message received from the client, assuming it was sent. Raises: AssertionError: If `StartRecognition` was not received. Returns: dict: The `StartRecognition` message. ""...
[ "def", "find_start_recognition_message", "(", "self", ")", ":", "messages", "=", "self", ".", "find_messages_by_type", "(", "\"StartRecognition\"", ")", "assert", "len", "(", "messages", ")", "==", "1", "return", "messages", "[", "0", "]" ]
[ 65, 4 ]
[ 78, 26 ]
python
en
['en', 'error', 'th']
False
MockRealtimeLogbook.wait_for_clean_disconnects
(self, num_disconnects=1, timeout=15)
Blocks until `clients_disconnected_count` is equal to the target value. This is a convenience for unit-tests which may need to wait until all connections have been closed cleanly. Args: num_disconnects (int, optional): Target number of disconnects to wait fo...
Blocks until `clients_disconnected_count` is equal to the target value. This is a convenience for unit-tests which may need to wait until all connections have been closed cleanly.
def wait_for_clean_disconnects(self, num_disconnects=1, timeout=15): """ Blocks until `clients_disconnected_count` is equal to the target value. This is a convenience for unit-tests which may need to wait until all connections have been closed cleanly. Args: num_disc...
[ "def", "wait_for_clean_disconnects", "(", "self", ",", "num_disconnects", "=", "1", ",", "timeout", "=", "15", ")", ":", "start", "=", "time", ".", "time", "(", ")", "while", "True", ":", "if", "self", ".", "clients_disconnected_count", ">=", "num_disconnect...
[ 80, 4 ]
[ 104, 17 ]
python
en
['en', 'error', 'th']
False
MockRealtimeServer.handleMessage
(self)
Deal with a message received from the client.
Deal with a message received from the client.
def handleMessage(self): """Deal with a message received from the client.""" try: # This whole block is wrapped in a try/except because the default # behaviour of the SimpleWebSocketServer library is to silently # discard any exceptions raised by these handlers. This ...
[ "def", "handleMessage", "(", "self", ")", ":", "try", ":", "# This whole block is wrapped in a try/except because the default", "# behaviour of the SimpleWebSocketServer library is to silently", "# discard any exceptions raised by these handlers. This is very", "# unhelpful. A workaround is to...
[ 119, 4 ]
[ 140, 67 ]
python
en
['en', 'en', 'en']
True
MockRealtimeServer.handleConnected
(self)
Called when a new client connects to the server.
Called when a new client connects to the server.
def handleConnected(self): """Called when a new client connects to the server.""" logging.info("%s %s", self.address, "connected") self.logbook.connection_request = self.request self.logbook.clients_connected_count += 1
[ "def", "handleConnected", "(", "self", ")", ":", "logging", ".", "info", "(", "\"%s %s\"", ",", "self", ".", "address", ",", "\"connected\"", ")", "self", ".", "logbook", ".", "connection_request", "=", "self", ".", "request", "self", ".", "logbook", ".", ...
[ 142, 4 ]
[ 146, 49 ]
python
en
['en', 'en', 'en']
True
MockRealtimeServer.handleClose
(self)
Called when a client disconnects from the server.
Called when a client disconnects from the server.
def handleClose(self): """Called when a client disconnects from the server.""" logging.info("%s %s", self.address, "closed") self.logbook.clients_disconnected_count += 1
[ "def", "handleClose", "(", "self", ")", ":", "logging", ".", "info", "(", "\"%s %s\"", ",", "self", ".", "address", ",", "\"closed\"", ")", "self", ".", "logbook", ".", "clients_disconnected_count", "+=", "1" ]
[ 148, 4 ]
[ 151, 52 ]
python
en
['en', 'en', 'en']
True
MockRealtimeServer.get_responses
(self, message, is_binary=False)
Optionally creates a response to the given message from the client. Either returns a dictionary with the response message or `None` if no response should be sent. Args: message (Union[dict, bytearray]): The message received from the client. Assumes that if t...
Optionally creates a response to the given message from the client. Either returns a dictionary with the response message or `None` if no response should be sent.
def get_responses(self, message, is_binary=False): """ Optionally creates a response to the given message from the client. Either returns a dictionary with the response message or `None` if no response should be sent. Args: message (Union[dict, bytearray]): The messa...
[ "def", "get_responses", "(", "self", ",", "message", ",", "is_binary", "=", "False", ")", ":", "responses", "=", "[", "]", "if", "is_binary", ":", "# AddAudio is the only binary message, so we can assume it's that.", "responses", ".", "append", "(", "{", "\"message\...
[ 153, 4 ]
[ 203, 24 ]
python
en
['en', 'error', 'th']
False
makedirs
(name, mode=0o777, exist_ok=False)
makedirs(name [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target directory already exists, raise an OSError if exist_o...
makedirs(name [, mode=0o777][, exist_ok=False])
def makedirs(name, mode=0o777, exist_ok=False): """makedirs(name [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target di...
[ "def", "makedirs", "(", "name", ",", "mode", "=", "0o777", ",", "exist_ok", "=", "False", ")", ":", "head", ",", "tail", "=", "path", ".", "split", "(", "name", ")", "if", "not", "tail", ":", "head", ",", "tail", "=", "path", ".", "split", "(", ...
[ 194, 0 ]
[ 224, 17 ]
python
en
['en', 'pt', 'en']
True
removedirs
(name)
removedirs(name) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. ...
removedirs(name)
def removedirs(name): """removedirs(name) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is c...
[ "def", "removedirs", "(", "name", ")", ":", "rmdir", "(", "name", ")", "head", ",", "tail", "=", "path", ".", "split", "(", "name", ")", "if", "not", "tail", ":", "head", ",", "tail", "=", "path", ".", "split", "(", "head", ")", "while", "head", ...
[ 226, 0 ]
[ 246, 37 ]
python
ceb
['en', 'ceb', 'hi']
False
renames
(old, new)
renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old ...
renames(old, new)
def renames(old, new): """renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost...
[ "def", "renames", "(", "old", ",", "new", ")", ":", "head", ",", "tail", "=", "path", ".", "split", "(", "new", ")", "if", "head", "and", "tail", "and", "not", "path", ".", "exists", "(", "head", ")", ":", "makedirs", "(", "head", ")", "rename", ...
[ 248, 0 ]
[ 272, 16 ]
python
en
['en', 'en', 'en']
False
walk
(top, topdown=True, onerror=None, followlinks=False)
Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath ...
Directory tree generator.
def walk(top, topdown=True, onerror=None, followlinks=False): """Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. ...
[ "def", "walk", "(", "top", ",", "topdown", "=", "True", ",", "onerror", "=", "None", ",", "followlinks", "=", "False", ")", ":", "top", "=", "fspath", "(", "top", ")", "dirs", "=", "[", "]", "nondirs", "=", "[", "]", "walk_dirs", "=", "[", "]", ...
[ 276, 0 ]
[ 414, 32 ]
python
en
['en', 'ja', 'en']
True
execl
(file, *args)
execl(file, *args) Execute the executable file with argument list args, replacing the current process.
execl(file, *args)
def execl(file, *args): """execl(file, *args) Execute the executable file with argument list args, replacing the current process. """ execv(file, args)
[ "def", "execl", "(", "file", ",", "*", "args", ")", ":", "execv", "(", "file", ",", "args", ")" ]
[ 521, 0 ]
[ 526, 21 ]
python
en
['en', 'gl', 'en']
False
execle
(file, *args)
execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process.
execle(file, *args, env)
def execle(file, *args): """execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process. """ env = args[-1] execve(file, args[:-1], env)
[ "def", "execle", "(", "file", ",", "*", "args", ")", ":", "env", "=", "args", "[", "-", "1", "]", "execve", "(", "file", ",", "args", "[", ":", "-", "1", "]", ",", "env", ")" ]
[ 528, 0 ]
[ 534, 32 ]
python
en
['en', 'es', 'en']
True
execlp
(file, *args)
execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process.
execlp(file, *args)
def execlp(file, *args): """execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. """ execvp(file, args)
[ "def", "execlp", "(", "file", ",", "*", "args", ")", ":", "execvp", "(", "file", ",", "args", ")" ]
[ 536, 0 ]
[ 541, 22 ]
python
en
['en', 'gl', 'sw']
False
execlpe
(file, *args)
execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process.
execlpe(file, *args, env)
def execlpe(file, *args): """execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process. """ env = args[-1] execvpe(file, args[:-1], env)
[ "def", "execlpe", "(", "file", ",", "*", "args", ")", ":", "env", "=", "args", "[", "-", "1", "]", "execvpe", "(", "file", ",", "args", "[", ":", "-", "1", "]", ",", "env", ")" ]
[ 543, 0 ]
[ 550, 33 ]
python
en
['en', 'gl', 'sw']
False
execvp
(file, args)
execvp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. args may be a list or tuple of strings.
execvp(file, args)
def execvp(file, args): """execvp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args)
[ "def", "execvp", "(", "file", ",", "args", ")", ":", "_execvpe", "(", "file", ",", "args", ")" ]
[ 552, 0 ]
[ 558, 24 ]
python
en
['en', 'fr', 'sw']
False
execvpe
(file, args, env)
execvpe(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env , replacing the current process. args may be a list or tuple of strings.
execvpe(file, args, env)
def execvpe(file, args, env): """execvpe(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env , replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args, env)
[ "def", "execvpe", "(", "file", ",", "args", ",", "env", ")", ":", "_execvpe", "(", "file", ",", "args", ",", "env", ")" ]
[ 560, 0 ]
[ 567, 29 ]
python
en
['en', 'gl', 'it']
False
get_exec_path
(env=None)
Returns the sequence of directories that will be searched for the named executable (similar to a shell) when launching a process. *env* must be an environment variable dict or None. If *env* is None, os.environ will be used.
Returns the sequence of directories that will be searched for the named executable (similar to a shell) when launching a process.
def get_exec_path(env=None): """Returns the sequence of directories that will be searched for the named executable (similar to a shell) when launching a process. *env* must be an environment variable dict or None. If *env* is None, os.environ will be used. """ # Use a local import instead of a...
[ "def", "get_exec_path", "(", "env", "=", "None", ")", ":", "# Use a local import instead of a global import to limit the number of", "# modules loaded at startup: the os module is always loaded at startup by", "# Python. It may also avoid a bootstrap issue.", "import", "warnings", "if", ...
[ 606, 0 ]
[ 647, 35 ]
python
en
['en', 'en', 'en']
True
getenv
(key, default=None)
Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.
Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.
def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.""" return environ.get(key, default)
[ "def", "getenv", "(", "key", ",", "default", "=", "None", ")", ":", "return", "environ", ".", "get", "(", "key", ",", "default", ")" ]
[ 759, 0 ]
[ 763, 36 ]
python
en
['br', 'en', 'en']
True
_fspath
(path)
Return the path representation of a path-like object. If str or bytes is passed in, it is returned unchanged. Otherwise the os.PathLike interface is used to get the path representation. If the path representation is not str or bytes, TypeError is raised. If the provided path is not str, bytes, or os.Pa...
Return the path representation of a path-like object.
def _fspath(path): """Return the path representation of a path-like object. If str or bytes is passed in, it is returned unchanged. Otherwise the os.PathLike interface is used to get the path representation. If the path representation is not str or bytes, TypeError is raised. If the provided path i...
[ "def", "_fspath", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "(", "str", ",", "bytes", ")", ")", ":", "return", "path", "# Work from the object's type to match method resolution of other magic", "# methods.", "path_type", "=", "type", "(", "path"...
[ 1021, 0 ]
[ 1048, 66 ]
python
en
['en', 'en', 'en']
True
PathLike.__fspath__
(self)
Return the file system path representation of the object.
Return the file system path representation of the object.
def __fspath__(self): """Return the file system path representation of the object.""" raise NotImplementedError
[ "def", "__fspath__", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 1062, 4 ]
[ 1064, 33 ]
python
en
['en', 'en', 'en']
True
clear_duplicate_counts
(apps: StateApps, schema_editor: DatabaseSchemaEditor)
This is a preparatory migration for our Analytics tables. The backstory is that Django's unique_together indexes do not properly handle the subgroup=None corner case (allowing duplicate rows that have a subgroup of None), which meant that in race conditions, rather than updating an existing row for the...
This is a preparatory migration for our Analytics tables.
def clear_duplicate_counts(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: """This is a preparatory migration for our Analytics tables. The backstory is that Django's unique_together indexes do not properly handle the subgroup=None corner case (allowing duplicate rows that have a subgrou...
[ "def", "clear_duplicate_counts", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "count_tables", "=", "dict", "(", "realm", "=", "apps", ".", "get_model", "(", "\"analytics\"", ",", "\"RealmCount\"", ")",...
[ 6, 0 ]
[ 53, 40 ]
python
en
['en', 'en', 'en']
True
monkeypatch
()
The returned ``monkeypatch`` fixture provides these helper methods to modify objects, dictionaries or os.environ:: monkeypatch.setattr(obj, name, value, raising=True) monkeypatch.delattr(obj, name, raising=True) monkeypatch.setitem(mapping, name, value) monkeypatch.delitem(obj, name...
The returned ``monkeypatch`` fixture provides these helper methods to modify objects, dictionaries or os.environ::
def monkeypatch(): """The returned ``monkeypatch`` fixture provides these helper methods to modify objects, dictionaries or os.environ:: monkeypatch.setattr(obj, name, value, raising=True) monkeypatch.delattr(obj, name, raising=True) monkeypatch.setitem(mapping, name, value) mon...
[ "def", "monkeypatch", "(", ")", ":", "mpatch", "=", "MonkeyPatch", "(", ")", "yield", "mpatch", "mpatch", ".", "undo", "(", ")" ]
[ 13, 0 ]
[ 33, 17 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.setattr
(self, target, name, value=notset, raising=True)
Set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist. For convenience you can specify a string as ``target`` which will be interpreted as a dotted import path, with the last part being the attribute name. Example: ...
Set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist.
def setattr(self, target, name, value=notset, raising=True): """ Set attribute value on target, memorizing the old value. By default raise AttributeError if the attribute did not exist. For convenience you can specify a string as ``target`` which will be interpreted as a dotted import p...
[ "def", "setattr", "(", "self", ",", "target", ",", "name", ",", "value", "=", "notset", ",", "raising", "=", "True", ")", ":", "__tracebackhide__", "=", "True", "import", "inspect", "if", "value", "is", "notset", ":", "if", "not", "isinstance", "(", "t...
[ 108, 4 ]
[ 141, 36 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.delattr
(self, target, name=notset, raising=True)
Delete attribute ``name`` from ``target``, by default raise AttributeError it the attribute did not previously exist. If no ``name`` is specified and ``target`` is a string it will be interpreted as a dotted import path with the last part being the attribute name. If ``raising...
Delete attribute ``name`` from ``target``, by default raise AttributeError it the attribute did not previously exist.
def delattr(self, target, name=notset, raising=True): """ Delete attribute ``name`` from ``target``, by default raise AttributeError it the attribute did not previously exist. If no ``name`` is specified and ``target`` is a string it will be interpreted as a dotted import path with the ...
[ "def", "delattr", "(", "self", ",", "target", ",", "name", "=", "notset", ",", "raising", "=", "True", ")", ":", "__tracebackhide__", "=", "True", "if", "name", "is", "notset", ":", "if", "not", "isinstance", "(", "target", ",", "six", ".", "string_typ...
[ 143, 4 ]
[ 167, 33 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.setitem
(self, dic, name, value)
Set dictionary entry ``name`` to value.
Set dictionary entry ``name`` to value.
def setitem(self, dic, name, value): """ Set dictionary entry ``name`` to value. """ self._setitem.append((dic, name, dic.get(name, notset))) dic[name] = value
[ "def", "setitem", "(", "self", ",", "dic", ",", "name", ",", "value", ")", ":", "self", ".", "_setitem", ".", "append", "(", "(", "dic", ",", "name", ",", "dic", ".", "get", "(", "name", ",", "notset", ")", ")", ")", "dic", "[", "name", "]", ...
[ 169, 4 ]
[ 172, 25 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.delitem
(self, dic, name, raising=True)
Delete ``name`` from dict. Raise KeyError if it doesn't exist. If ``raising`` is set to False, no exception will be raised if the key is missing.
Delete ``name`` from dict. Raise KeyError if it doesn't exist.
def delitem(self, dic, name, raising=True): """ Delete ``name`` from dict. Raise KeyError if it doesn't exist. If ``raising`` is set to False, no exception will be raised if the key is missing. """ if name not in dic: if raising: raise KeyError(name) ...
[ "def", "delitem", "(", "self", ",", "dic", ",", "name", ",", "raising", "=", "True", ")", ":", "if", "name", "not", "in", "dic", ":", "if", "raising", ":", "raise", "KeyError", "(", "name", ")", "else", ":", "self", ".", "_setitem", ".", "append", ...
[ 174, 4 ]
[ 185, 25 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.setenv
(self, name, value, prepend=None)
Set environment variable ``name`` to ``value``. If ``prepend`` is a character, read the current environment variable value and prepend the ``value`` adjoined with the ``prepend`` character.
Set environment variable ``name`` to ``value``. If ``prepend`` is a character, read the current environment variable value and prepend the ``value`` adjoined with the ``prepend`` character.
def setenv(self, name, value, prepend=None): """ Set environment variable ``name`` to ``value``. If ``prepend`` is a character, read the current environment variable value and prepend the ``value`` adjoined with the ``prepend`` character.""" value = str(value) if prepend and nam...
[ "def", "setenv", "(", "self", ",", "name", ",", "value", ",", "prepend", "=", "None", ")", ":", "value", "=", "str", "(", "value", ")", "if", "prepend", "and", "name", "in", "os", ".", "environ", ":", "value", "=", "value", "+", "prepend", "+", "...
[ 187, 4 ]
[ 194, 45 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.delenv
(self, name, raising=True)
Delete ``name`` from the environment. Raise KeyError it does not exist. If ``raising`` is set to False, no exception will be raised if the environment variable is missing.
Delete ``name`` from the environment. Raise KeyError it does not exist.
def delenv(self, name, raising=True): """ Delete ``name`` from the environment. Raise KeyError it does not exist. If ``raising`` is set to False, no exception will be raised if the environment variable is missing. """ self.delitem(os.environ, name, raising=raising)
[ "def", "delenv", "(", "self", ",", "name", ",", "raising", "=", "True", ")", ":", "self", ".", "delitem", "(", "os", ".", "environ", ",", "name", ",", "raising", "=", "raising", ")" ]
[ 196, 4 ]
[ 203, 55 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.syspath_prepend
(self, path)
Prepend ``path`` to ``sys.path`` list of import locations.
Prepend ``path`` to ``sys.path`` list of import locations.
def syspath_prepend(self, path): """ Prepend ``path`` to ``sys.path`` list of import locations. """ if self._savesyspath is None: self._savesyspath = sys.path[:] sys.path.insert(0, str(path))
[ "def", "syspath_prepend", "(", "self", ",", "path", ")", ":", "if", "self", ".", "_savesyspath", "is", "None", ":", "self", ".", "_savesyspath", "=", "sys", ".", "path", "[", ":", "]", "sys", ".", "path", ".", "insert", "(", "0", ",", "str", "(", ...
[ 205, 4 ]
[ 209, 37 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.chdir
(self, path)
Change the current working directory to the specified path. Path can be a string or a py.path.local object.
Change the current working directory to the specified path. Path can be a string or a py.path.local object.
def chdir(self, path): """ Change the current working directory to the specified path. Path can be a string or a py.path.local object. """ if self._cwd is None: self._cwd = os.getcwd() if hasattr(path, "chdir"): path.chdir() else: os.ch...
[ "def", "chdir", "(", "self", ",", "path", ")", ":", "if", "self", ".", "_cwd", "is", "None", ":", "self", ".", "_cwd", "=", "os", ".", "getcwd", "(", ")", "if", "hasattr", "(", "path", ",", "\"chdir\"", ")", ":", "path", ".", "chdir", "(", ")",...
[ 211, 4 ]
[ 220, 26 ]
python
en
['en', 'en', 'en']
True
MonkeyPatch.undo
(self)
Undo previous changes. This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call. There is generally no need to call `undo()`, since it is called automatically during tear-down. Note that the same `monkeypa...
Undo previous changes. This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call.
def undo(self): """ Undo previous changes. This call consumes the undo stack. Calling it a second time has no effect unless you do more monkeypatching after the undo call. There is generally no need to call `undo()`, since it is called automatically during tear-down. N...
[ "def", "undo", "(", "self", ")", ":", "for", "obj", ",", "name", ",", "value", "in", "reversed", "(", "self", ".", "_setattr", ")", ":", "if", "value", "is", "not", "notset", ":", "setattr", "(", "obj", ",", "name", ",", "value", ")", "else", ":"...
[ 222, 4 ]
[ 257, 28 ]
python
en
['en', 'en', 'en']
True
Query.__init__
(self, ref=None)
@param ref: The schema reference being queried. @type ref: qref
def __init__(self, ref=None): """ @param ref: The schema reference being queried. @type ref: qref """ Object.__init__(self) self.id = objid(self) self.ref = ref self.history = [] self.resolved = False if not isqref(self.ref): ra...
[ "def", "__init__", "(", "self", ",", "ref", "=", "None", ")", ":", "Object", ".", "__init__", "(", "self", ")", "self", ".", "id", "=", "objid", "(", "self", ")", "self", ".", "ref", "=", "ref", "self", ".", "history", "=", "[", "]", "self", "....
[ 34, 4 ]
[ 45, 65 ]
python
en
['en', 'error', 'th']
False
Query.execute
(self, schema)
Execute this query using the specified schema. @param schema: The schema associated with the query. The schema is used by the query to search for items. @type schema: L{schema.Schema} @return: The item matching the search criteria. @rtype: L{sxbase.SchemaObject} ...
Execute this query using the specified schema.
def execute(self, schema): """ Execute this query using the specified schema. @param schema: The schema associated with the query. The schema is used by the query to search for items. @type schema: L{schema.Schema} @return: The item matching the search criteria. ...
[ "def", "execute", "(", "self", ",", "schema", ")", ":", "raise", "Exception", ",", "'not-implemented by subclass'" ]
[ 47, 4 ]
[ 56, 54 ]
python
en
['en', 'error', 'th']
False
Query.filter
(self, result)
Filter the specified result based on query criteria. @param result: A potential result. @type result: L{sxbase.SchemaObject} @return: True if result should be excluded. @rtype: boolean
Filter the specified result based on query criteria.
def filter(self, result): """ Filter the specified result based on query criteria. @param result: A potential result. @type result: L{sxbase.SchemaObject} @return: True if result should be excluded. @rtype: boolean """ if result is None: return...
[ "def", "filter", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "return", "True", "reject", "=", "(", "result", "in", "self", ".", "history", ")", "if", "reject", ":", "log", ".", "debug", "(", "'result %s, rejected by\\n%s'", ...
[ 58, 4 ]
[ 71, 21 ]
python
en
['en', 'error', 'th']
False
Query.result
(self, result)
Query result post processing. @param result: A query result. @type result: L{sxbase.SchemaObject}
Query result post processing.
def result(self, result): """ Query result post processing. @param result: A query result. @type result: L{sxbase.SchemaObject} """ if result is None: log.debug('%s, not-found', self.ref) return if self.resolved: result = result...
[ "def", "result", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "log", ".", "debug", "(", "'%s, not-found'", ",", "self", ".", "ref", ")", "return", "if", "self", ".", "resolved", ":", "result", "=", "result", ".", "resolve"...
[ 73, 4 ]
[ 86, 21 ]
python
en
['en', 'error', 'th']
False