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
OperationLogMiddleware._get_log_format
(self, request)
Return operation log format.
Return operation log format.
def _get_log_format(self, request): """Return operation log format.""" user = getattr(request, 'user', None) if not user: return if not request.user.is_authenticated: return method = request.method.upper() if not (method in self.target_methods): ...
[ "def", "_get_log_format", "(", "self", ",", "request", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "not", "user", ":", "return", "if", "not", "request", ".", "user", ".", "is_authenticated", ":", "return", "...
[ 115, 4 ]
[ 129, 26 ]
python
da
['nl', 'da', 'en']
False
OperationLogMiddleware._get_parameters_from_request
(self, request, exception=False)
Get parameters to log in OPERATION_LOG.
Get parameters to log in OPERATION_LOG.
def _get_parameters_from_request(self, request, exception=False): """Get parameters to log in OPERATION_LOG.""" user = request.user referer_url = None try: referer_dic = urlparse.urlsplit( urlparse.unquote(request.META.get('HTTP_REFERER'))) referer...
[ "def", "_get_parameters_from_request", "(", "self", ",", "request", ",", "exception", "=", "False", ")", ":", "user", "=", "request", ".", "user", "referer_url", "=", "None", "try", ":", "referer_dic", "=", "urlparse", ".", "urlsplit", "(", "urlparse", ".", ...
[ 131, 4 ]
[ 161, 9 ]
python
en
['en', 'en', 'en']
True
OperationLogMiddleware._get_request_param
(self, request)
Change POST data to JSON string and mask data.
Change POST data to JSON string and mask data.
def _get_request_param(self, request): """Change POST data to JSON string and mask data.""" params = {} try: params = request.POST.copy() if not params: params = json.loads(request.body) except Exception: pass for key in params:...
[ "def", "_get_request_param", "(", "self", ",", "request", ")", ":", "params", "=", "{", "}", "try", ":", "params", "=", "request", ".", "POST", ".", "copy", "(", ")", "if", "not", "params", ":", "params", "=", "json", ".", "loads", "(", "request", ...
[ 163, 4 ]
[ 187, 42 ]
python
en
['en', 'en', 'en']
True
ensure_socialapp_in_db
(token)
Make sure that token is attached to a SocialApp in the db. Since we are using SocialApps constructed from settings, there are none in the db for tokens to be related to unless we create them here.
Make sure that token is attached to a SocialApp in the db.
def ensure_socialapp_in_db(token): """Make sure that token is attached to a SocialApp in the db. Since we are using SocialApps constructed from settings, there are none in the db for tokens to be related to unless we create them here. """ if token.app.pk is None: provider = providers.re...
[ "def", "ensure_socialapp_in_db", "(", "token", ")", ":", "if", "token", ".", "app", ".", "pk", "is", "None", ":", "provider", "=", "providers", ".", "registry", ".", "by_id", "(", "token", ".", "app", ".", "provider", ")", "app", ",", "created", "=", ...
[ 13, 0 ]
[ 27, 23 ]
python
en
['en', 'en', 'en']
True
import_setting
(name)
Imports an object specified either directly or as a module path.
Imports an object specified either directly or as a module path.
def import_setting(name): """Imports an object specified either directly or as a module path.""" value = getattr(settings, name, None) return import_object(value)
[ "def", "import_setting", "(", "name", ")", ":", "value", "=", "getattr", "(", "settings", ",", "name", ",", "None", ")", "return", "import_object", "(", "value", ")" ]
[ 26, 0 ]
[ 29, 31 ]
python
en
['en', 'en', 'en']
True
iris
()
Return iris dataset with custom descriptions. Returns: tuple: X, y, descriptions
Return iris dataset with custom descriptions.
def iris(): """Return iris dataset with custom descriptions. Returns: tuple: X, y, descriptions """ _ = load_iris(as_frame=True) X = _["data"] y = _["target"] descriptions = { "target": { "mapping": { 0: "Iris-Setosa", 1: "Iris-V...
[ "def", "iris", "(", ")", ":", "_", "=", "load_iris", "(", "as_frame", "=", "True", ")", "X", "=", "_", "[", "\"data\"", "]", "y", "=", "_", "[", "\"target\"", "]", "descriptions", "=", "{", "\"target\"", ":", "{", "\"mapping\"", ":", "{", "0", ":...
[ 4, 0 ]
[ 25, 29 ]
python
en
['en', 'la', 'en']
True
boston
()
Return boston dataset with custom descriptions. Returns: tuple: X, y, descriptions
Return boston dataset with custom descriptions.
def boston(): """Return boston dataset with custom descriptions. Returns: tuple: X, y, descriptions """ _ = load_boston() X = pd.DataFrame(_["data"], columns=_["feature_names"]) y = pd.Series(_["target"], name="MEDV") d = "description" descriptions = { "CRIM": { ...
[ "def", "boston", "(", ")", ":", "_", "=", "load_boston", "(", ")", "X", "=", "pd", ".", "DataFrame", "(", "_", "[", "\"data\"", "]", ",", "columns", "=", "_", "[", "\"feature_names\"", "]", ")", "y", "=", "pd", ".", "Series", "(", "_", "[", "\"...
[ 28, 0 ]
[ 86, 29 ]
python
en
['en', 'no', 'en']
True
diabetes
()
Return diabetes dataset with custom descriptions. Returns: tuple: X, y, descriptions
Return diabetes dataset with custom descriptions.
def diabetes(): """Return diabetes dataset with custom descriptions. Returns: tuple: X, y, descriptions """ _ = load_diabetes(as_frame=True) X = _["data"] y = _["target"] d = "description" descriptions = { "age": { d: "age in years" }, "bmi...
[ "def", "diabetes", "(", ")", ":", "_", "=", "load_diabetes", "(", "as_frame", "=", "True", ")", "X", "=", "_", "[", "\"data\"", "]", "y", "=", "_", "[", "\"target\"", "]", "d", "=", "\"description\"", "descriptions", "=", "{", "\"age\"", ":", "{", ...
[ 89, 0 ]
[ 132, 29 ]
python
en
['en', 'la', 'en']
True
digits
(n_class=10)
Return digits dataset. Descriptions are None. Args: n_class (int, optional): number of classes to return, defaults to 10 Returns: tuple: X, y, descriptions
Return digits dataset. Descriptions are None.
def digits(n_class=10): """Return digits dataset. Descriptions are None. Args: n_class (int, optional): number of classes to return, defaults to 10 Returns: tuple: X, y, descriptions """ _ = load_digits(n_class=n_class, as_frame=True) X = _["data"] y = _["target"] descr...
[ "def", "digits", "(", "n_class", "=", "10", ")", ":", "_", "=", "load_digits", "(", "n_class", "=", "n_class", ",", "as_frame", "=", "True", ")", "X", "=", "_", "[", "\"data\"", "]", "y", "=", "_", "[", "\"target\"", "]", "descriptions", "=", "None...
[ 135, 0 ]
[ 149, 29 ]
python
en
['en', 'fr', 'en']
True
wine
()
Return wine dataset. Descriptions are None. Returns: tuple: X, y, descriptions
Return wine dataset. Descriptions are None.
def wine(): """Return wine dataset. Descriptions are None. Returns: tuple: X, y, descriptions """ _ = load_wine(as_frame=True) X = _["data"] y = _["target"] descriptions = None return X, y, descriptions
[ "def", "wine", "(", ")", ":", "_", "=", "load_wine", "(", "as_frame", "=", "True", ")", "X", "=", "_", "[", "\"data\"", "]", "y", "=", "_", "[", "\"target\"", "]", "descriptions", "=", "None", "return", "X", ",", "y", ",", "descriptions" ]
[ 152, 0 ]
[ 164, 29 ]
python
en
['en', 'it', 'en']
True
breast_cancer
()
Return breast cancer dataset. Descriptions are None. Returns: tuple: X, y, descriptions
Return breast cancer dataset. Descriptions are None.
def breast_cancer(): """Return breast cancer dataset. Descriptions are None. Returns: tuple: X, y, descriptions """ _ = load_breast_cancer(as_frame=True) X = _["data"] y = _["target"] descriptions = None return X, y, descriptions
[ "def", "breast_cancer", "(", ")", ":", "_", "=", "load_breast_cancer", "(", "as_frame", "=", "True", ")", "X", "=", "_", "[", "\"data\"", "]", "y", "=", "_", "[", "\"target\"", "]", "descriptions", "=", "None", "return", "X", ",", "y", ",", "descript...
[ 167, 0 ]
[ 180, 29 ]
python
en
['en', 'en', 'en']
True
doom_lock_file
(max_parallel)
Doom instances tend to have problems starting when a lot of them are initialized in parallel. This is not a problem during normal execution once the envs are initialized. The "sweet spot" for the number of envs that can be initialized in parallel is about 5-10. Here we use file locking mechanism to en...
Doom instances tend to have problems starting when a lot of them are initialized in parallel. This is not a problem during normal execution once the envs are initialized.
def doom_lock_file(max_parallel): """ Doom instances tend to have problems starting when a lot of them are initialized in parallel. This is not a problem during normal execution once the envs are initialized. The "sweet spot" for the number of envs that can be initialized in parallel is about 5-10. ...
[ "def", "doom_lock_file", "(", "max_parallel", ")", ":", "lock_filename", "=", "f'doom_{random.randrange(0, max_parallel):03d}.lockfile'", "tmp_dir", "=", "project_tmp_dir", "(", ")", "lock_path", "=", "join", "(", "tmp_dir", ",", "lock_filename", ")", "return", "lock_pa...
[ 19, 0 ]
[ 35, 20 ]
python
en
['en', 'error', 'th']
False
key_to_action_default
(key)
MOVE_FORWARD MOVE_BACKWARD MOVE_RIGHT MOVE_LEFT SELECT_WEAPON1 SELECT_WEAPON2 SELECT_WEAPON3 SELECT_WEAPON4 SELECT_WEAPON5 SELECT_WEAPON6 SELECT_WEAPON7 ATTACK SPEED TURN_LEFT_RIGHT_DELTA
MOVE_FORWARD MOVE_BACKWARD MOVE_RIGHT MOVE_LEFT SELECT_WEAPON1 SELECT_WEAPON2 SELECT_WEAPON3 SELECT_WEAPON4 SELECT_WEAPON5 SELECT_WEAPON6 SELECT_WEAPON7 ATTACK SPEED TURN_LEFT_RIGHT_DELTA
def key_to_action_default(key): """ MOVE_FORWARD MOVE_BACKWARD MOVE_RIGHT MOVE_LEFT SELECT_WEAPON1 SELECT_WEAPON2 SELECT_WEAPON3 SELECT_WEAPON4 SELECT_WEAPON5 SELECT_WEAPON6 SELECT_WEAPON7 ATTACK SPEED TU...
[ "def", "key_to_action_default", "(", "key", ")", ":", "from", "pynput", ".", "keyboard", "import", "Key", "# health gathering", "action_table", "=", "{", "Key", ".", "left", ":", "0", ",", "Key", ".", "right", ":", "1", ",", "Key", ".", "up", ":", "2",...
[ 38, 0 ]
[ 76, 38 ]
python
en
['en', 'error', 'th']
False
VizdoomEnv._convert_actions
(self, actions)
Convert actions from gym action space to the action space expected by Doom game.
Convert actions from gym action space to the action space expected by Doom game.
def _convert_actions(self, actions): """Convert actions from gym action space to the action space expected by Doom game.""" if self.composite_action_space: # composite action space with multiple subspaces spaces = self.action_space.spaces else: # simple actio...
[ "def", "_convert_actions", "(", "self", ",", "actions", ")", ":", "if", "self", ".", "composite_action_space", ":", "# composite action space with multiple subspaces", "spaces", "=", "self", ".", "action_space", ".", "spaces", "else", ":", "# simple action space, e.g. D...
[ 337, 4 ]
[ 371, 32 ]
python
en
['en', 'en', 'en']
True
VizdoomEnv._vizdoom_variables_bug_workaround
(self, info, done)
Some variables don't get reset to zero on game.new_episode(). This fixes it (also check overflow?).
Some variables don't get reset to zero on game.new_episode(). This fixes it (also check overflow?).
def _vizdoom_variables_bug_workaround(self, info, done): """Some variables don't get reset to zero on game.new_episode(). This fixes it (also check overflow?).""" if done and 'DAMAGECOUNT' in info: log.info('DAMAGECOUNT value on done: %r', info.get('DAMAGECOUNT')) if self._last_epis...
[ "def", "_vizdoom_variables_bug_workaround", "(", "self", ",", "info", ",", "done", ")", ":", "if", "done", "and", "'DAMAGECOUNT'", "in", "info", ":", "log", ".", "info", "(", "'DAMAGECOUNT value on done: %r'", ",", "info", ".", "get", "(", "'DAMAGECOUNT'", ")"...
[ 373, 4 ]
[ 382, 64 ]
python
en
['en', 'en', 'en']
True
VizdoomEnv.step
(self, actions)
Action is either a single value (discrete, one-hot), or a tuple with an action for each of the discrete action subspaces.
Action is either a single value (discrete, one-hot), or a tuple with an action for each of the discrete action subspaces.
def step(self, actions): """ Action is either a single value (discrete, one-hot), or a tuple with an action for each of the discrete action subspaces. """ if self._actions_flattened is not None: # provided externally, e.g. via human play actions_flattened ...
[ "def", "step", "(", "self", ",", "actions", ")", ":", "if", "self", ".", "_actions_flattened", "is", "not", "None", ":", "# provided externally, e.g. via human play", "actions_flattened", "=", "self", ".", "_actions_flattened", "self", ".", "_actions_flattened", "="...
[ 401, 4 ]
[ 419, 46 ]
python
en
['en', 'error', 'th']
False
TestPasteCapture.test_non_ascii_paste_text
(self, testdir)
Make sure that text which contains non-ascii characters is pasted correctly. See #1219.
Make sure that text which contains non-ascii characters is pasted correctly. See #1219.
def test_non_ascii_paste_text(self, testdir): """Make sure that text which contains non-ascii characters is pasted correctly. See #1219. """ testdir.makepyfile(test_unicode=""" # encoding: utf-8 def test(): assert '☺' == 1 """) resu...
[ "def", "test_non_ascii_paste_text", "(", "self", ",", "testdir", ")", ":", "testdir", ".", "makepyfile", "(", "test_unicode", "=", "\"\"\"\n # encoding: utf-8\n def test():\n assert '☺' == 1\n \"\"\"", ")", "result", "=", "testdir", "...
[ 54, 4 ]
[ 72, 10 ]
python
en
['en', 'en', 'en']
True
TestPaste.mocked_urlopen
(self, monkeypatch)
monkeypatch the actual urlopen calls done by the internal plugin function that connects to bpaste service.
monkeypatch the actual urlopen calls done by the internal plugin function that connects to bpaste service.
def mocked_urlopen(self, monkeypatch): """ monkeypatch the actual urlopen calls done by the internal plugin function that connects to bpaste service. """ calls = [] def mocked(url, data): calls.append((url, data)) class DummyFile(object): ...
[ "def", "mocked_urlopen", "(", "self", ",", "monkeypatch", ")", ":", "calls", "=", "[", "]", "def", "mocked", "(", "url", ",", "data", ")", ":", "calls", ".", "append", "(", "(", "url", ",", "data", ")", ")", "class", "DummyFile", "(", "object", ")"...
[ 82, 4 ]
[ 104, 20 ]
python
en
['en', 'error', 'th']
False
test_exception_repr_extraction_error_on_recursion
()
Ensure we can properly detect a recursion error even if some locals raise error on comparision (#2459).
Ensure we can properly detect a recursion error even if some locals raise error on comparision (#2459).
def test_exception_repr_extraction_error_on_recursion(): """ Ensure we can properly detect a recursion error even if some locals raise error on comparision (#2459). """ class numpy_like(object): def __eq__(self, other): if type(other) is numpy_like: raise ValueEr...
[ "def", "test_exception_repr_extraction_error_on_recursion", "(", ")", ":", "class", "numpy_like", "(", "object", ")", ":", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "type", "(", "other", ")", "is", "numpy_like", ":", "raise", "ValueError", ...
[ 1197, 0 ]
[ 1227, 10 ]
python
en
['en', 'error', 'th']
False
test_no_recursion_index_on_recursion_error
()
Ensure that we don't break in case we can't find the recursion index during a recursion error (#2486).
Ensure that we don't break in case we can't find the recursion index during a recursion error (#2486).
def test_no_recursion_index_on_recursion_error(): """ Ensure that we don't break in case we can't find the recursion index during a recursion error (#2486). """ try: class RecursionDepthError(object): def __getattr__(self, attr): return getattr(self, '_' + attr) ...
[ "def", "test_no_recursion_index_on_recursion_error", "(", ")", ":", "try", ":", "class", "RecursionDepthError", "(", "object", ")", ":", "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "return", "getattr", "(", "self", ",", "'_'", "+", "attr", ")",...
[ 1230, 0 ]
[ 1246, 16 ]
python
en
['en', 'error', 'th']
False
TestFormattedExcinfo.test_repr_source_excinfo
(self)
check if indentation is right
check if indentation is right
def test_repr_source_excinfo(self): """ check if indentation is right """ pr = FormattedExcinfo() excinfo = self.excinfo_from_exec(""" def f(): assert 0 f() """) pr = FormattedExcinfo() source = pr._getentrysource(excinf...
[ "def", "test_repr_source_excinfo", "(", "self", ")", ":", "pr", "=", "FormattedExcinfo", "(", ")", "excinfo", "=", "self", ".", "excinfo_from_exec", "(", "\"\"\"\n def f():\n assert 0\n f()\n \"\"\"", ")", "pr", "=", "...
[ 450, 4 ]
[ 465, 9 ]
python
en
['en', 'en', 'en']
True
TestFormattedExcinfo.test_exc_chain_repr_without_traceback
(self, importasmod, reason, description)
Handle representation of exception chains where one of the exceptions doesn't have a real traceback, such as those raised in a subprocess submitted by the multiprocessing module (#1984).
Handle representation of exception chains where one of the exceptions doesn't have a real traceback, such as those raised in a subprocess submitted by the multiprocessing module (#1984).
def test_exc_chain_repr_without_traceback(self, importasmod, reason, description): """ Handle representation of exception chains where one of the exceptions doesn't have a real traceback, such as those raised in a subprocess submitted by the multiprocessing module (#1984). """ ...
[ "def", "test_exc_chain_repr_without_traceback", "(", "self", ",", "importasmod", ",", "reason", ",", "description", ")", ":", "from", "_pytest", ".", "pytester", "import", "LineMatcher", "exc_handling_code", "=", "' from e'", "if", "reason", "==", "'cause'", "else",...
[ 1130, 4 ]
[ 1167, 10 ]
python
en
['en', 'error', 'th']
False
load_pyproject_toml
( use_pep517, # type: Optional[bool] pyproject_toml, # type: str setup_py, # type: str req_name # type: str )
Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing? None means the user hasn't explicitly specified. pyproject_toml - Location of the project's pyproject.toml file setup_py - Location of the project's setup.py file r...
Load the pyproject.toml file.
def load_pyproject_toml( use_pep517, # type: Optional[bool] pyproject_toml, # type: str setup_py, # type: str req_name # type: str ): # type: (...) -> Optional[BuildSystemDetails] """Load the pyproject.toml file. Parameters: use_pep517 - Has the user requested PEP 517 processing...
[ "def", "load_pyproject_toml", "(", "use_pep517", ",", "# type: Optional[bool]", "pyproject_toml", ",", "# type: str", "setup_py", ",", "# type: str", "req_name", "# type: str", ")", ":", "# type: (...) -> Optional[BuildSystemDetails]", "has_pyproject", "=", "os", ".", "path...
[ 41, 0 ]
[ 195, 69 ]
python
en
['en', 'en', 'en']
True
has_permissions
(user, component)
Checks if the given user meets the permissions requirements.
Checks if the given user meets the permissions requirements.
def has_permissions(user, component): """Checks if the given user meets the permissions requirements.""" return user.has_perms(getattr(component, 'permissions', set()))
[ "def", "has_permissions", "(", "user", ",", "component", ")", ":", "return", "user", ".", "has_perms", "(", "getattr", "(", "component", ",", "'permissions'", ",", "set", "(", ")", ")", ")" ]
[ 43, 0 ]
[ 45, 67 ]
python
en
['en', 'en', 'en']
True
horizon_main_nav
(context)
Generates top-level dashboard navigation entries.
Generates top-level dashboard navigation entries.
def horizon_main_nav(context): """Generates top-level dashboard navigation entries.""" if 'request' not in context: return {} current_dashboard = context['request'].horizon.get('dashboard', None) dashboards = [] for dash in Horizon.get_dashboards(): if dash.can_access(context): ...
[ "def", "horizon_main_nav", "(", "context", ")", ":", "if", "'request'", "not", "in", "context", ":", "return", "{", "}", "current_dashboard", "=", "context", "[", "'request'", "]", ".", "horizon", ".", "get", "(", "'dashboard'", ",", "None", ")", "dashboar...
[ 93, 0 ]
[ 108, 42 ]
python
en
['es', 'en', 'en']
True
horizon_dashboard_nav
(context)
Generates sub-navigation entries for the current dashboard.
Generates sub-navigation entries for the current dashboard.
def horizon_dashboard_nav(context): """Generates sub-navigation entries for the current dashboard.""" if 'request' not in context: return {} dashboard = context['request'].horizon['dashboard'] panel_groups = dashboard.get_panel_groups() non_empty_groups = [] for group in panel_groups.va...
[ "def", "horizon_dashboard_nav", "(", "context", ")", ":", "if", "'request'", "not", "in", "context", ":", "return", "{", "}", "dashboard", "=", "context", "[", "'request'", "]", ".", "horizon", "[", "'dashboard'", "]", "panel_groups", "=", "dashboard", ".", ...
[ 112, 0 ]
[ 138, 42 ]
python
en
['en', 'en', 'en']
True
jstemplate
(parser, token)
Templatetag to handle any of the Mustache-based templates. Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any of the Mustache-based templating l...
Templatetag to handle any of the Mustache-based templates.
def jstemplate(parser, token): """Templatetag to handle any of the Mustache-based templates. Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``, ``[[`` and ``]]`` with ``{{`` and ``}}`` and ``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts with Django's template engine when using any ...
[ "def", "jstemplate", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endjstemplate'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "JSTemplateNode", "(", "nodelist", ")" ]
[ 186, 0 ]
[ 197, 35 ]
python
en
['en', 'en', 'en']
True
minifyspace
(parser, token)
Removes whitespace including tab and newline characters. Do not use this if you are using a <pre> tag. Example usage:: {% minifyspace %} <p> <a title="foo" href="foo/"> Foo </a> </p> {% endminifysp...
Removes whitespace including tab and newline characters.
def minifyspace(parser, token): """Removes whitespace including tab and newline characters. Do not use this if you are using a <pre> tag. Example usage:: {% minifyspace %} <p> <a title="foo" href="foo/"> Foo </a> ...
[ "def", "minifyspace", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endminifyspace'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "MinifiedNode", "(", "nodelist", ")" ]
[ 217, 0 ]
[ 240, 33 ]
python
en
['en', 'en', 'en']
True
_wikify_one
(language, pat)
Wikifies one link.
Wikifies one link.
def _wikify_one(language, pat): """ Wikifies one link. """ page_title = pat.group(2) if pat.group(1): page_name = pat.group(1).rstrip('|') else: page_name = page_title # interwiki if ':' in page_name and not page_name.startswith("http"): parts = page_name.split('...
[ "def", "_wikify_one", "(", "language", ",", "pat", ")", ":", "page_title", "=", "pat", ".", "group", "(", "2", ")", "if", "pat", ".", "group", "(", "1", ")", ":", "page_name", "=", "pat", ".", "group", "(", "1", ")", ".", "rstrip", "(", "'|'", ...
[ 105, 0 ]
[ 122, 15 ]
python
en
['en', 'error', 'th']
False
expand_reqs
(fpath: str)
Returns a sorted list of unique dependencies specified by the requirements file `fpath`. Removes comments from the output and recursively visits files specified inside `fpath`. `fpath` can be either an absolute path or a relative path.
Returns a sorted list of unique dependencies specified by the requirements file `fpath`. Removes comments from the output and recursively visits files specified inside `fpath`. `fpath` can be either an absolute path or a relative path.
def expand_reqs(fpath: str) -> List[str]: """ Returns a sorted list of unique dependencies specified by the requirements file `fpath`. Removes comments from the output and recursively visits files specified inside `fpath`. `fpath` can be either an absolute path or a relative path. """ absfpath =...
[ "def", "expand_reqs", "(", "fpath", ":", "str", ")", "->", "List", "[", "str", "]", ":", "absfpath", "=", "os", ".", "path", ".", "abspath", "(", "fpath", ")", "output", "=", "expand_reqs_helper", "(", "absfpath", ")", "return", "sorted", "(", "set", ...
[ 22, 0 ]
[ 30, 30 ]
python
en
['en', 'error', 'th']
False
python_version
()
Returns the Python version as string 'Python major.minor.patchlevel'
Returns the Python version as string 'Python major.minor.patchlevel'
def python_version() -> str: """ Returns the Python version as string 'Python major.minor.patchlevel' """ return subprocess.check_output(["/usr/bin/python3", "-VV"], universal_newlines=True)
[ "def", "python_version", "(", ")", "->", "str", ":", "return", "subprocess", ".", "check_output", "(", "[", "\"/usr/bin/python3\"", ",", "\"-VV\"", "]", ",", "universal_newlines", "=", "True", ")" ]
[ 33, 0 ]
[ 37, 88 ]
python
en
['en', 'error', 'th']
False
safe_get
(q, timeout=1e6, msg='Queue timeout')
Using queue.get() with timeout is necessary, otherwise KeyboardInterrupt is not handled.
Using queue.get() with timeout is necessary, otherwise KeyboardInterrupt is not handled.
def safe_get(q, timeout=1e6, msg='Queue timeout'): """Using queue.get() with timeout is necessary, otherwise KeyboardInterrupt is not handled.""" while True: try: return q.get(timeout=timeout) except Empty: log.info('Queue timed out (%s), timeout %.3f', msg, timeout)
[ "def", "safe_get", "(", "q", ",", "timeout", "=", "1e6", ",", "msg", "=", "'Queue timeout'", ")", ":", "while", "True", ":", "try", ":", "return", "q", ".", "get", "(", "timeout", "=", "timeout", ")", "except", "Empty", ":", "log", ".", "info", "("...
[ 109, 0 ]
[ 115, 72 ]
python
en
['en', 'en', 'en']
True
numpy_all_the_way
(list_of_arrays)
Turn a list of numpy arrays into a 2D numpy array.
Turn a list of numpy arrays into a 2D numpy array.
def numpy_all_the_way(list_of_arrays): """Turn a list of numpy arrays into a 2D numpy array.""" shape = list(list_of_arrays[0].shape) shape[:0] = [len(list_of_arrays)] arr = np.concatenate(list_of_arrays).reshape(shape) return arr
[ "def", "numpy_all_the_way", "(", "list_of_arrays", ")", ":", "shape", "=", "list", "(", "list_of_arrays", "[", "0", "]", ".", "shape", ")", "shape", "[", ":", "0", "]", "=", "[", "len", "(", "list_of_arrays", ")", "]", "arr", "=", "np", ".", "concate...
[ 144, 0 ]
[ 149, 14 ]
python
en
['en', 'ga', 'en']
True
numpy_flatten
(list_of_arrays)
Turn a list of numpy arrays into a 1D numpy array (flattened).
Turn a list of numpy arrays into a 1D numpy array (flattened).
def numpy_flatten(list_of_arrays): """Turn a list of numpy arrays into a 1D numpy array (flattened).""" return np.concatenate(list_of_arrays, axis=0)
[ "def", "numpy_flatten", "(", "list_of_arrays", ")", ":", "return", "np", ".", "concatenate", "(", "list_of_arrays", ",", "axis", "=", "0", ")" ]
[ 152, 0 ]
[ 154, 49 ]
python
en
['en', 'hu', 'en']
True
figure_to_numpy
(figure)
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param figure a matplotlib figure @return a numpy 3D array of RGBA values
def figure_to_numpy(figure): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param figure a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer figure.canvas.draw() # Get the RGBA buffer from the figure w, h ...
[ "def", "figure_to_numpy", "(", "figure", ")", ":", "# draw the renderer", "figure", ".", "canvas", ".", "draw", "(", ")", "# Get the RGBA buffer from the figure", "w", ",", "h", "=", "figure", ".", "canvas", ".", "get_width_height", "(", ")", "buffer", "=", "n...
[ 165, 0 ]
[ 181, 17 ]
python
en
['en', 'error', 'th']
False
memory_consumption_mb
()
Memory consumption of the current process.
Memory consumption of the current process.
def memory_consumption_mb(): """Memory consumption of the current process.""" process = psutil.Process(os.getpid()) return process.memory_info().rss / (1024 * 1024)
[ "def", "memory_consumption_mb", "(", ")", ":", "process", "=", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", "return", "process", ".", "memory_info", "(", ")", ".", "rss", "/", "(", "1024", "*", "1024", ")" ]
[ 191, 0 ]
[ 194, 52 ]
python
en
['en', 'en', 'en']
True
cores_for_worker_process
(worker_idx, num_workers, cpu_count)
Returns core indices, assuming available cores are [0, ..., cpu_count). If this is not the case (e.g. SLURM) use these as indices in the array of actual available cores.
Returns core indices, assuming available cores are [0, ..., cpu_count). If this is not the case (e.g. SLURM) use these as indices in the array of actual available cores.
def cores_for_worker_process(worker_idx, num_workers, cpu_count): """ Returns core indices, assuming available cores are [0, ..., cpu_count). If this is not the case (e.g. SLURM) use these as indices in the array of actual available cores. """ worker_idx_modulo = worker_idx % cpu_count # tryin...
[ "def", "cores_for_worker_process", "(", "worker_idx", ",", "num_workers", ",", "cpu_count", ")", ":", "worker_idx_modulo", "=", "worker_idx", "%", "cpu_count", "# trying to optimally assign workers to CPU cores to minimize context switching", "# logic here is best illustrated with an...
[ 245, 0 ]
[ 270, 16 ]
python
en
['en', 'error', 'th']
False
safe_ensure_dir_exists
(path)
Should be safer in multi-treaded environment.
Should be safer in multi-treaded environment.
def safe_ensure_dir_exists(path): """Should be safer in multi-treaded environment.""" try: return ensure_dir_exists(path) except FileExistsError: return path
[ "def", "safe_ensure_dir_exists", "(", "path", ")", ":", "try", ":", "return", "ensure_dir_exists", "(", "path", ")", "except", "FileExistsError", ":", "return", "path" ]
[ 297, 0 ]
[ 302, 19 ]
python
en
['en', 'en', 'en']
True
resolve_name
(name, package)
Resolve a relative module name to an absolute one.
Resolve a relative module name to an absolute one.
def resolve_name(name, package): """Resolve a relative module name to an absolute one.""" if not name.startswith('.'): return name elif not package: raise ValueError(f'no package specified for {repr(name)} ' '(required for relative module names)') level = 0 f...
[ "def", "resolve_name", "(", "name", ",", "package", ")", ":", "if", "not", "name", ".", "startswith", "(", "'.'", ")", ":", "return", "name", "elif", "not", "package", ":", "raise", "ValueError", "(", "f'no package specified for {repr(name)} '", "'(required for ...
[ 19, 0 ]
[ 31, 54 ]
python
en
['en', 'en', 'en']
True
_find_spec_from_path
(name, path=None)
Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_path is searched for a ...
Return the spec for the specified module.
def _find_spec_from_path(name, path=None): """Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in ...
[ "def", "_find_spec_from_path", "(", "name", ",", "path", "=", "None", ")", ":", "if", "name", "not", "in", "sys", ".", "modules", ":", "return", "_find_spec", "(", "name", ",", "path", ")", "else", ":", "module", "=", "sys", ".", "modules", "[", "nam...
[ 34, 0 ]
[ 62, 23 ]
python
en
['en', 'en', 'en']
True
find_spec
(name, package=None)
Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_path is searched for a ...
Return the spec for the specified module.
def find_spec(name, package=None): """Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modu...
[ "def", "find_spec", "(", "name", ",", "package", "=", "None", ")", ":", "fullname", "=", "resolve_name", "(", "name", ",", "package", ")", "if", "name", ".", "startswith", "(", "'.'", ")", "else", "name", "if", "fullname", "not", "in", "sys", ".", "m...
[ 65, 0 ]
[ 102, 23 ]
python
en
['en', 'en', 'en']
True
set_package
(fxn)
Set __package__ on the returned module. This function is deprecated.
Set __package__ on the returned module.
def set_package(fxn): """Set __package__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_package_wrapper(*args, **kwargs): warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2)...
[ "def", "set_package", "(", "fxn", ")", ":", "@", "functools", ".", "wraps", "(", "fxn", ")", "def", "set_package_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'The import system now takes care of this automatical...
[ 131, 0 ]
[ 147, 30 ]
python
en
['en', 'en', 'en']
True
set_loader
(fxn)
Set __loader__ on the returned module. This function is deprecated.
Set __loader__ on the returned module.
def set_loader(fxn): """Set __loader__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_loader_wrapper(self, *args, **kwargs): warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel...
[ "def", "set_loader", "(", "fxn", ")", ":", "@", "functools", ".", "wraps", "(", "fxn", ")", "def", "set_loader_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "'The import system now takes care of t...
[ 150, 0 ]
[ 164, 29 ]
python
en
['en', 'da', 'en']
True
module_for_loader
(fxn)
Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then __name__ is set the first argum...
Decorator to handle selecting the proper module for loaders.
def module_for_loader(fxn): """Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then ...
[ "def", "module_for_loader", "(", "fxn", ")", ":", "warnings", ".", "warn", "(", "'The import system now takes care of this automatically.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "@", "functools", ".", "wraps", "(", "fxn", ")", "def", "modul...
[ 167, 0 ]
[ 203, 36 ]
python
en
['en', 'en', 'en']
True
_LazyModule.__getattribute__
(self, attr)
Trigger the load of the module and return the attribute.
Trigger the load of the module and return the attribute.
def __getattribute__(self, attr): """Trigger the load of the module and return the attribute.""" # All module metadata must be garnered from __spec__ in order to avoid # using mutated values. # Stop triggering this method. self.__class__ = types.ModuleType # Get the origi...
[ "def", "__getattribute__", "(", "self", ",", "attr", ")", ":", "# All module metadata must be garnered from __spec__ in order to avoid", "# using mutated values.", "# Stop triggering this method.", "self", ".", "__class__", "=", "types", ".", "ModuleType", "# Get the original nam...
[ 210, 4 ]
[ 243, 34 ]
python
en
['en', 'en', 'en']
True
_LazyModule.__delattr__
(self, attr)
Trigger the load and then perform the deletion.
Trigger the load and then perform the deletion.
def __delattr__(self, attr): """Trigger the load and then perform the deletion.""" # To trigger the load and raise an exception if the attribute # doesn't exist. self.__getattribute__(attr) delattr(self, attr)
[ "def", "__delattr__", "(", "self", ",", "attr", ")", ":", "# To trigger the load and raise an exception if the attribute", "# doesn't exist.", "self", ".", "__getattribute__", "(", "attr", ")", "delattr", "(", "self", ",", "attr", ")" ]
[ 245, 4 ]
[ 250, 27 ]
python
en
['en', 'en', 'en']
True
LazyLoader.factory
(cls, loader)
Construct a callable which returns the eager loader made lazy.
Construct a callable which returns the eager loader made lazy.
def factory(cls, loader): """Construct a callable which returns the eager loader made lazy.""" cls.__check_eager_loader(loader) return lambda *args, **kwargs: cls(loader(*args, **kwargs))
[ "def", "factory", "(", "cls", ",", "loader", ")", ":", "cls", ".", "__check_eager_loader", "(", "loader", ")", "return", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "cls", "(", "loader", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ...
[ 263, 4 ]
[ 266, 67 ]
python
en
['en', 'en', 'en']
True
LazyLoader.exec_module
(self, module)
Make the module load lazily.
Make the module load lazily.
def exec_module(self, module): """Make the module load lazily.""" module.__spec__.loader = self.loader module.__loader__ = self.loader # Don't need to worry about deep-copying as trying to set an attribute # on an object would have triggered the load, # e.g. ``module.__sp...
[ "def", "exec_module", "(", "self", ",", "module", ")", ":", "module", ".", "__spec__", ".", "loader", "=", "self", ".", "loader", "module", ".", "__loader__", "=", "self", ".", "loader", "# Don't need to worry about deep-copying as trying to set an attribute", "# on...
[ 275, 4 ]
[ 287, 38 ]
python
en
['en', 'it', 'en']
True
BaseHeuristic.warning
(self, response)
Return a valid 1xx warning header value describing the cache adjustments. The response is provided too allow warnings like 113 http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need to explicitly say response is over 24 hours old.
Return a valid 1xx warning header value describing the cache adjustments.
def warning(self, response): """ Return a valid 1xx warning header value describing the cache adjustments. The response is provided too allow warnings like 113 http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need to explicitly say response is over 24 hours old....
[ "def", "warning", "(", "self", ",", "response", ")", ":", "return", "'110 - \"Response is Stale\"'" ]
[ 21, 4 ]
[ 30, 42 ]
python
en
['en', 'error', 'th']
False
BaseHeuristic.update_headers
(self, response)
Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers.
Update the response headers with any new headers.
def update_headers(self, response): """Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers. """ return {}
[ "def", "update_headers", "(", "self", ",", "response", ")", ":", "return", "{", "}" ]
[ 32, 4 ]
[ 39, 17 ]
python
en
['en', 'en', 'en']
True
sanitize_name
(value: str)
Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding '.' to the list of allowed characters. *...
Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_".
def sanitize_name(value: str) -> str: """ Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding...
[ "def", "sanitize_name", "(", "value", ":", "str", ")", "->", "str", ":", "value", "=", "unicodedata", ".", "normalize", "(", "\"NFKC\"", ",", "value", ")", "value", "=", "re", ".", "sub", "(", "r\"[^\\w\\s.-]\"", ",", "\"\"", ",", "value", ",", "flags"...
[ 81, 0 ]
[ 97, 27 ]
python
en
['en', 'error', 'th']
False
_match_vcs_scheme
(url)
Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match.
Look for VCS schemes in the URL.
def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ for scheme in vcs.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme return Non...
[ "def", "_match_vcs_scheme", "(", "url", ")", ":", "# type: (str) -> Optional[str]", "for", "scheme", "in", "vcs", ".", "schemes", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "scheme", ")", "and", "url", "[", "len", "(", "scheme", ")...
[ 69, 0 ]
[ 78, 15 ]
python
en
['en', 'en', 'en']
True
_is_url_like_archive
(url)
Return whether the URL looks like an archive.
Return whether the URL looks like an archive.
def _is_url_like_archive(url): # type: (str) -> bool """Return whether the URL looks like an archive. """ filename = Link(url).filename for bad_ext in ARCHIVE_EXTENSIONS: if filename.endswith(bad_ext): return True return False
[ "def", "_is_url_like_archive", "(", "url", ")", ":", "# type: (str) -> bool", "filename", "=", "Link", "(", "url", ")", ".", "filename", "for", "bad_ext", "in", "ARCHIVE_EXTENSIONS", ":", "if", "filename", ".", "endswith", "(", "bad_ext", ")", ":", "return", ...
[ 81, 0 ]
[ 89, 16 ]
python
en
['en', 'en', 'en']
True
_ensure_html_header
(response)
Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html.
Check the Content-Type header to ensure the response contains HTML.
def _ensure_html_header(response): # type: (Response) -> None """Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. """ content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/h...
[ "def", "_ensure_html_header", "(", "response", ")", ":", "# type: (Response) -> None", "content_type", "=", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"\"", ")", "if", "not", "content_type", ".", "lower", "(", ")", ".", "startswith",...
[ 100, 0 ]
[ 108, 61 ]
python
en
['en', 'en', 'en']
True
_ensure_html_response
(url, session)
Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html.
Send a HEAD request to the URL, and ensure the response contains HTML.
def _ensure_html_response(url, session): # type: (str, PipSession) -> None """Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. """ scheme, netloc, path, qu...
[ "def", "_ensure_html_response", "(", "url", ",", "session", ")", ":", "# type: (str, PipSession) -> None", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urllib_parse", ".", "urlsplit", "(", "url", ")", "if", "scheme", "not", "in", ...
[ 115, 0 ]
[ 129, 29 ]
python
en
['en', 'en', 'en']
True
_get_html_response
(url, session)
Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_No...
Access an HTML page with GET, and return the response.
def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large...
[ "def", "_get_html_response", "(", "url", ",", "session", ")", ":", "# type: (str, PipSession) -> Response", "if", "_is_url_like_archive", "(", "url", ")", ":", "_ensure_html_response", "(", "url", ",", "session", "=", "session", ")", "logger", ".", "debug", "(", ...
[ 132, 0 ]
[ 180, 15 ]
python
en
['en', 'en', 'en']
True
_get_encoding_from_headers
(headers)
Determine if we have any encoding information in our headers.
Determine if we have any encoding information in our headers.
def _get_encoding_from_headers(headers): # type: (ResponseHeaders) -> Optional[str] """Determine if we have any encoding information in our headers. """ if headers and "Content-Type" in headers: content_type, params = cgi.parse_header(headers["Content-Type"]) if "charset" in params: ...
[ "def", "_get_encoding_from_headers", "(", "headers", ")", ":", "# type: (ResponseHeaders) -> Optional[str]", "if", "headers", "and", "\"Content-Type\"", "in", "headers", ":", "content_type", ",", "params", "=", "cgi", ".", "parse_header", "(", "headers", "[", "\"Conte...
[ 183, 0 ]
[ 191, 15 ]
python
en
['en', 'en', 'en']
True
_determine_base_url
(document, page_url)
Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the HTML file's URL is used as the base URL. :p...
Determine the HTML document's base URL.
def _determine_base_url(document, page_url): # type: (HTMLElement, str) -> str """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does ...
[ "def", "_determine_base_url", "(", "document", ",", "page_url", ")", ":", "# type: (HTMLElement, str) -> str", "for", "base", "in", "document", ".", "findall", "(", "\".//base\"", ")", ":", "href", "=", "base", ".", "get", "(", "\"href\"", ")", "if", "href", ...
[ 194, 0 ]
[ 211, 19 ]
python
en
['en', 'no', 'en']
True
_clean_url_path_part
(part)
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
Clean a "part" of a URL path (i.e. after splitting on "
def _clean_url_path_part(part): # type: (str) -> str """ Clean a "part" of a URL path (i.e. after splitting on "@" characters). """ # We unquote prior to quoting to make sure nothing is double quoted. return urllib_parse.quote(urllib_parse.unquote(part))
[ "def", "_clean_url_path_part", "(", "part", ")", ":", "# type: (str) -> str", "# We unquote prior to quoting to make sure nothing is double quoted.", "return", "urllib_parse", ".", "quote", "(", "urllib_parse", ".", "unquote", "(", "part", ")", ")" ]
[ 214, 0 ]
[ 220, 57 ]
python
en
['en', 'error', 'th']
False
_clean_file_url_path
(part)
Clean the first part of a URL path that corresponds to a local filesystem path (i.e. the first part after splitting on "@" characters).
Clean the first part of a URL path that corresponds to a local filesystem path (i.e. the first part after splitting on "
def _clean_file_url_path(part): # type: (str) -> str """ Clean the first part of a URL path that corresponds to a local filesystem path (i.e. the first part after splitting on "@" characters). """ # We unquote prior to quoting to make sure nothing is double quoted. # Also, on Windows the pat...
[ "def", "_clean_file_url_path", "(", "part", ")", ":", "# type: (str) -> str", "# We unquote prior to quoting to make sure nothing is double quoted.", "# Also, on Windows the path part might contain a drive letter which", "# should not be quoted. On Linux where drive letters do not", "# exist, th...
[ 223, 0 ]
[ 234, 73 ]
python
en
['en', 'error', 'th']
False
_clean_url_path
(path, is_local_path)
Clean the path portion of a URL.
Clean the path portion of a URL.
def _clean_url_path(path, is_local_path): # type: (str, bool) -> str """ Clean the path portion of a URL. """ if is_local_path: clean_func = _clean_file_url_path else: clean_func = _clean_url_path_part # Split on the reserved characters prior to cleaning so that # revisi...
[ "def", "_clean_url_path", "(", "path", ",", "is_local_path", ")", ":", "# type: (str, bool) -> str", "if", "is_local_path", ":", "clean_func", "=", "_clean_file_url_path", "else", ":", "clean_func", "=", "_clean_url_path_part", "# Split on the reserved characters prior to cle...
[ 241, 0 ]
[ 261, 33 ]
python
en
['en', 'error', 'th']
False
_clean_link
(url)
Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters.
Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters.
def _clean_link(url): # type: (str) -> str """ Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters. """ # Split the URL into parts according to the general structure # `scheme://netloc/path;p...
[ "def", "_clean_link", "(", "url", ")", ":", "# type: (str) -> str", "# Split the URL into parts according to the general structure", "# `scheme://netloc/path;parameters?query#fragment`.", "result", "=", "urllib_parse", ".", "urlparse", "(", "url", ")", "# If the netloc is empty, th...
[ 264, 0 ]
[ 277, 62 ]
python
en
['en', 'error', 'th']
False
_create_link_from_element
( anchor, # type: HTMLElement page_url, # type: str base_url, # type: str )
Convert an anchor element in a simple repository page to a Link.
Convert an anchor element in a simple repository page to a Link.
def _create_link_from_element( anchor, # type: HTMLElement page_url, # type: str base_url, # type: str ): # type: (...) -> Optional[Link] """ Convert an anchor element in a simple repository page to a Link. """ href = anchor.get("href") if not href: return None url ...
[ "def", "_create_link_from_element", "(", "anchor", ",", "# type: HTMLElement", "page_url", ",", "# type: str", "base_url", ",", "# type: str", ")", ":", "# type: (...) -> Optional[Link]", "href", "=", "anchor", ".", "get", "(", "\"href\"", ")", "if", "not", "href", ...
[ 280, 0 ]
[ 309, 15 ]
python
en
['en', 'error', 'th']
False
with_cached_html_pages
( fn, # type: Callable[[HTMLPage], Iterable[Link]] )
Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`.
Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `page.cache_link_parsing == False`.
def with_cached_html_pages( fn, # type: Callable[[HTMLPage], Iterable[Link]] ): # type: (...) -> Callable[[HTMLPage], List[Link]] """ Given a function that parses an Iterable[Link] from an HTMLPage, cache the function's result (keyed by CacheablePageContent), unless the HTMLPage `page` has `p...
[ "def", "with_cached_html_pages", "(", "fn", ",", "# type: Callable[[HTMLPage], Iterable[Link]]", ")", ":", "# type: (...) -> Callable[[HTMLPage], List[Link]]", "@", "_lru_cache", "(", "maxsize", "=", "None", ")", "def", "wrapper", "(", "cacheable_page", ")", ":", "# type:...
[ 328, 0 ]
[ 350, 26 ]
python
en
['en', 'error', 'th']
False
parse_links
(page)
Parse an HTML document, and yield its anchor elements as Link objects.
Parse an HTML document, and yield its anchor elements as Link objects.
def parse_links(page): # type: (HTMLPage) -> Iterable[Link] """ Parse an HTML document, and yield its anchor elements as Link objects. """ document = html5lib.parse( page.content, transport_encoding=page.encoding, namespaceHTMLElements=False, ) url = page.url bas...
[ "def", "parse_links", "(", "page", ")", ":", "# type: (HTMLPage) -> Iterable[Link]", "document", "=", "html5lib", ".", "parse", "(", "page", ".", "content", ",", "transport_encoding", "=", "page", ".", "encoding", ",", "namespaceHTMLElements", "=", "False", ",", ...
[ 354, 0 ]
[ 375, 18 ]
python
en
['en', 'error', 'th']
False
_remove_duplicate_links
(links)
Return a list of links, with duplicates removed and ordering preserved.
Return a list of links, with duplicates removed and ordering preserved.
def _remove_duplicate_links(links): # type: (Iterable[Link]) -> List[Link] """ Return a list of links, with duplicates removed and ordering preserved. """ # We preserve the ordering when removing duplicates because we can. return list(OrderedDict.fromkeys(links))
[ "def", "_remove_duplicate_links", "(", "links", ")", ":", "# type: (Iterable[Link]) -> List[Link]", "# We preserve the ordering when removing duplicates because we can.", "return", "list", "(", "OrderedDict", ".", "fromkeys", "(", "links", ")", ")" ]
[ 484, 0 ]
[ 490, 44 ]
python
en
['en', 'error', 'th']
False
group_locations
(locations, expand_dir=False)
Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls).
Divide a list of locations into two groups: "files" (archives) and "urls."
def group_locations(locations, expand_dir=False): # type: (Sequence[str], bool) -> Tuple[List[str], List[str]] """ Divide a list of locations into two groups: "files" (archives) and "urls." :return: A pair of lists (files, urls). """ files = [] urls = [] # puts the url for the given fi...
[ "def", "group_locations", "(", "locations", ",", "expand_dir", "=", "False", ")", ":", "# type: (Sequence[str], bool) -> Tuple[List[str], List[str]]", "files", "=", "[", "]", "urls", "=", "[", "]", "# puts the url for the given file path into the appropriate list", "def", "...
[ 493, 0 ]
[ 549, 22 ]
python
en
['en', 'error', 'th']
False
HTMLPage.__init__
( self, content, # type: bytes encoding, # type: Optional[str] url, # type: str cache_link_parsing=True, # type: bool )
:param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. :param cache_link_parsing: whether links parsed from this page's url should be cached. PyPI index urls should ...
:param encoding: the encoding to decode the given content. :param url: the URL from which the HTML was downloaded. :param cache_link_parsing: whether links parsed from this page's url should be cached. PyPI index urls should ...
def __init__( self, content, # type: bytes encoding, # type: Optional[str] url, # type: str cache_link_parsing=True, # type: bool ): # type: (...) -> None """ :param encoding: the encoding to decod...
[ "def", "__init__", "(", "self", ",", "content", ",", "# type: bytes", "encoding", ",", "# type: Optional[str]", "url", ",", "# type: str", "cache_link_parsing", "=", "True", ",", "# type: bool", ")", ":", "# type: (...) -> None", "self", ".", "content", "=", "cont...
[ 381, 4 ]
[ 399, 52 ]
python
en
['en', 'error', 'th']
False
CollectedLinks.__init__
( self, files, # type: List[Link] find_links, # type: List[Link] project_urls, # type: List[Link] )
:param files: Links from file locations. :param find_links: Links from find_links. :param project_urls: URLs to HTML project pages, as described by the PEP 503 simple repository API.
:param files: Links from file locations. :param find_links: Links from find_links. :param project_urls: URLs to HTML project pages, as described by the PEP 503 simple repository API.
def __init__( self, files, # type: List[Link] find_links, # type: List[Link] project_urls, # type: List[Link] ): # type: (...) -> None """ :param files: Links from file locations. :param find_links: Links from find_links. :param pro...
[ "def", "__init__", "(", "self", ",", "files", ",", "# type: List[Link]", "find_links", ",", "# type: List[Link]", "project_urls", ",", "# type: List[Link]", ")", ":", "# type: (...) -> None", "self", ".", "files", "=", "files", "self", ".", "find_links", "=", "fin...
[ 569, 4 ]
[ 584, 40 ]
python
en
['en', 'error', 'th']
False
LinkCollector.create
(cls, session, options, suppress_no_index=False)
:param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object.
:param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object.
def create(cls, session, options, suppress_no_index=False): # type: (PipSession, Values, bool) -> LinkCollector """ :param session: The Session to use to make requests. :param suppress_no_index: Whether to ignore the --no-index option when constructing the SearchScope object....
[ "def", "create", "(", "cls", ",", "session", ",", "options", ",", "suppress_no_index", "=", "False", ")", ":", "# type: (PipSession, Values, bool) -> LinkCollector", "index_urls", "=", "[", "options", ".", "index_url", "]", "+", "options", ".", "extra_index_urls", ...
[ 606, 4 ]
[ 630, 29 ]
python
en
['en', 'error', 'th']
False
LinkCollector.fetch_page
(self, location)
Fetch an HTML page containing package links.
Fetch an HTML page containing package links.
def fetch_page(self, location): # type: (Link) -> Optional[HTMLPage] """ Fetch an HTML page containing package links. """ return _get_html_page(location, session=self.session)
[ "def", "fetch_page", "(", "self", ",", "location", ")", ":", "# type: (Link) -> Optional[HTMLPage]", "return", "_get_html_page", "(", "location", ",", "session", "=", "self", ".", "session", ")" ]
[ 637, 4 ]
[ 642, 61 ]
python
en
['en', 'error', 'th']
False
LinkCollector.collect_links
(self, project_name)
Find all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object.
Find all available links for the given project name.
def collect_links(self, project_name): # type: (str) -> CollectedLinks """Find all available links for the given project name. :return: All the Link objects (unfiltered), as a CollectedLinks object. """ search_scope = self.search_scope index_locations = search_scope.get_...
[ "def", "collect_links", "(", "self", ",", "project_name", ")", ":", "# type: (str) -> CollectedLinks", "search_scope", "=", "self", ".", "search_scope", "index_locations", "=", "search_scope", ".", "get_index_urls_locations", "(", "project_name", ")", "index_file_loc", ...
[ 644, 4 ]
[ 691, 9 ]
python
en
['en', 'en', 'en']
True
check_flags
(flags: List[str], expected: Set[str])
The has_alert_word flag can be ignored for most tests.
The has_alert_word flag can be ignored for most tests.
def check_flags(flags: List[str], expected: Set[str]) -> None: """ The has_alert_word flag can be ignored for most tests. """ assert "has_alert_word" not in expected flag_set = set(flags) flag_set.discard("has_alert_word") if flag_set != expected: raise AssertionError(f"expected flag...
[ "def", "check_flags", "(", "flags", ":", "List", "[", "str", "]", ",", "expected", ":", "Set", "[", "str", "]", ")", "->", "None", ":", "assert", "\"has_alert_word\"", "not", "in", "expected", "flag_set", "=", "set", "(", "flags", ")", "flag_set", ".",...
[ 32, 0 ]
[ 40, 90 ]
python
en
['en', 'error', 'th']
False
MessageAccessTests.test_change_star
(self)
You can set a message as starred/un-starred through POST /json/messages/flags.
You can set a message as starred/un-starred through POST /json/messages/flags.
def test_change_star(self) -> None: """ You can set a message as starred/un-starred through POST /json/messages/flags. """ self.login("hamlet") message_ids = [ self.send_personal_message( self.example_user("hamlet"), self.example_user("hamlet")...
[ "def", "test_change_star", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "message_ids", "=", "[", "self", ".", "send_personal_message", "(", "self", ".", "example_user", "(", "\"hamlet\"", ")", ",", "self", ".", "exampl...
[ 1035, 4 ]
[ 1063, 48 ]
python
en
['en', 'error', 'th']
False
MessageAccessTests.test_change_star_public_stream_historical
(self)
You can set a message as starred/un-starred through POST /json/messages/flags.
You can set a message as starred/un-starred through POST /json/messages/flags.
def test_change_star_public_stream_historical(self) -> None: """ You can set a message as starred/un-starred through POST /json/messages/flags. """ stream_name = "new_stream" self.subscribe(self.example_user("hamlet"), stream_name) self.login("hamlet") mes...
[ "def", "test_change_star_public_stream_historical", "(", "self", ")", "->", "None", ":", "stream_name", "=", "\"new_stream\"", "self", ".", "subscribe", "(", "self", ".", "example_user", "(", "\"hamlet\"", ")", ",", "stream_name", ")", "self", ".", "login", "(",...
[ 1065, 4 ]
[ 1134, 60 ]
python
en
['en', 'error', 'th']
False
MessageAccessTests.test_change_star_private_message_security
(self)
You can set a message as starred/un-starred through POST /json/messages/flags.
You can set a message as starred/un-starred through POST /json/messages/flags.
def test_change_star_private_message_security(self) -> None: """ You can set a message as starred/un-starred through POST /json/messages/flags. """ self.login("hamlet") message_ids = [ self.send_personal_message( self.example_user("hamlet"), ...
[ "def", "test_change_star_private_message_security", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "message_ids", "=", "[", "self", ".", "send_personal_message", "(", "self", ".", "example_user", "(", "\"hamlet\"", ")", ",", ...
[ 1136, 4 ]
[ 1153, 60 ]
python
en
['en', 'error', 'th']
False
MessageAccessTests.test_new_message
(self)
New messages aren't starred.
New messages aren't starred.
def test_new_message(self) -> None: """ New messages aren't starred. """ sender = self.example_user("hamlet") self.login_user(sender) content = "Test message for star" self.send_stream_message(sender, "Verona", content=content) sent_message = ( ...
[ "def", "test_new_message", "(", "self", ")", "->", "None", ":", "sender", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "self", ".", "login_user", "(", "sender", ")", "content", "=", "\"Test message for star\"", "self", ".", "send_stream_message", ...
[ 1193, 4 ]
[ 1210, 52 ]
python
en
['en', 'error', 'th']
False
PersonalMessagesFlagTest.test_is_private_flag_not_leaked
(self)
Make sure `is_private` flag is not leaked to the API.
Make sure `is_private` flag is not leaked to the API.
def test_is_private_flag_not_leaked(self) -> None: """ Make sure `is_private` flag is not leaked to the API. """ self.login("hamlet") self.send_personal_message( self.example_user("hamlet"), self.example_user("cordelia"), "test" ) for msg in self.get_...
[ "def", "test_is_private_flag_not_leaked", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "self", ".", "send_personal_message", "(", "self", ".", "example_user", "(", "\"hamlet\"", ")", ",", "self", ".", "example_user", "(", ...
[ 1377, 4 ]
[ 1387, 56 ]
python
en
['en', 'error', 'th']
False
TargetPython.__init__
( self, platform=None, # type: Optional[str] py_version_info=None, # type: Optional[Tuple[int, ...]] abi=None, # type: Optional[str] implementation=None, # type: Optional[str] )
:param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built ...
:param platform: A string or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platform passed in. These packages will only be downloaded for distribution: they will not be built ...
def __init__( self, platform=None, # type: Optional[str] py_version_info=None, # type: Optional[Tuple[int, ...]] abi=None, # type: Optional[str] implementation=None, # type: Optional[str] ): # type: (...) -> None """ :param platform: A string or No...
[ "def", "__init__", "(", "self", ",", "platform", "=", "None", ",", "# type: Optional[str]", "py_version_info", "=", "None", ",", "# type: Optional[Tuple[int, ...]]", "abi", "=", "None", ",", "# type: Optional[str]", "implementation", "=", "None", ",", "# type: Optiona...
[ 32, 4 ]
[ 71, 31 ]
python
en
['en', 'error', 'th']
False
TargetPython.format_given
(self)
Format the given, non-None attributes for display.
Format the given, non-None attributes for display.
def format_given(self): # type: () -> str """ Format the given, non-None attributes for display. """ display_version = None if self._given_py_version_info is not None: display_version = '.'.join( str(part) for part in self._given_py_version_inf...
[ "def", "format_given", "(", "self", ")", ":", "# type: () -> str", "display_version", "=", "None", "if", "self", ".", "_given_py_version_info", "is", "not", "None", ":", "display_version", "=", "'.'", ".", "join", "(", "str", "(", "part", ")", "for", "part",...
[ 73, 4 ]
[ 93, 9 ]
python
en
['en', 'error', 'th']
False
TargetPython.get_tags
(self)
Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first).
Return the supported PEP 425 tags to check wheel candidates against.
def get_tags(self): # type: () -> List[Tag] """ Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first). """ if self._valid_tags is None: # Pass versions=None if no py_version_in...
[ "def", "get_tags", "(", "self", ")", ":", "# type: () -> List[Tag]", "if", "self", ".", "_valid_tags", "is", "None", ":", "# Pass versions=None if no py_version_info was given since", "# versions=None uses special default logic.", "py_version_info", "=", "self", ".", "_given_...
[ 95, 4 ]
[ 119, 31 ]
python
en
['en', 'error', 'th']
False
retry
(*dargs, **dkw)
Decorator function that instantiates the Retrying object @param *dargs: positional arguments passed to Retrying object @param **dkw: keyword arguments passed to the Retrying object
Decorator function that instantiates the Retrying object
def retry(*dargs, **dkw): """ Decorator function that instantiates the Retrying object @param *dargs: positional arguments passed to Retrying object @param **dkw: keyword arguments passed to the Retrying object """ # support both @retry and @retry() as valid syntax if len(dargs) == 1 and cal...
[ "def", "retry", "(", "*", "dargs", ",", "*", "*", "dkw", ")", ":", "# support both @retry and @retry() as valid syntax", "if", "len", "(", "dargs", ")", "==", "1", "and", "callable", "(", "dargs", "[", "0", "]", ")", ":", "def", "wrap_simple", "(", "f", ...
[ 25, 0 ]
[ 52, 19 ]
python
en
['en', 'error', 'th']
False
Retrying.stop_after_attempt
(self, previous_attempt_number, delay_since_first_attempt_ms)
Stop after the previous attempt >= stop_max_attempt_number.
Stop after the previous attempt >= stop_max_attempt_number.
def stop_after_attempt(self, previous_attempt_number, delay_since_first_attempt_ms): """Stop after the previous attempt >= stop_max_attempt_number.""" return previous_attempt_number >= self._stop_max_attempt_number
[ "def", "stop_after_attempt", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "previous_attempt_number", ">=", "self", ".", "_stop_max_attempt_number" ]
[ 140, 4 ]
[ 142, 71 ]
python
en
['en', 'en', 'en']
True
Retrying.stop_after_delay
(self, previous_attempt_number, delay_since_first_attempt_ms)
Stop after the time from the first attempt >= stop_max_delay.
Stop after the time from the first attempt >= stop_max_delay.
def stop_after_delay(self, previous_attempt_number, delay_since_first_attempt_ms): """Stop after the time from the first attempt >= stop_max_delay.""" return delay_since_first_attempt_ms >= self._stop_max_delay
[ "def", "stop_after_delay", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "delay_since_first_attempt_ms", ">=", "self", ".", "_stop_max_delay" ]
[ 144, 4 ]
[ 146, 67 ]
python
en
['en', 'en', 'en']
True
Retrying.no_sleep
(self, previous_attempt_number, delay_since_first_attempt_ms)
Don't sleep at all before retrying.
Don't sleep at all before retrying.
def no_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Don't sleep at all before retrying.""" return 0
[ "def", "no_sleep", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "0" ]
[ 148, 4 ]
[ 150, 16 ]
python
en
['en', 'en', 'en']
True
Retrying.fixed_sleep
(self, previous_attempt_number, delay_since_first_attempt_ms)
Sleep a fixed amount of time between each retry.
Sleep a fixed amount of time between each retry.
def fixed_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Sleep a fixed amount of time between each retry.""" return self._wait_fixed
[ "def", "fixed_sleep", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "self", ".", "_wait_fixed" ]
[ 152, 4 ]
[ 154, 31 ]
python
en
['en', 'en', 'en']
True
Retrying.random_sleep
(self, previous_attempt_number, delay_since_first_attempt_ms)
Sleep a random amount of time between wait_random_min and wait_random_max
Sleep a random amount of time between wait_random_min and wait_random_max
def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Sleep a random amount of time between wait_random_min and wait_random_max""" return random.randint(self._wait_random_min, self._wait_random_max)
[ "def", "random_sleep", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "random", ".", "randint", "(", "self", ".", "_wait_random_min", ",", "self", ".", "_wait_random_max", ")" ]
[ 156, 4 ]
[ 158, 75 ]
python
en
['en', 'so', 'en']
True
Retrying.incrementing_sleep
(self, previous_attempt_number, delay_since_first_attempt_ms)
Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment
Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment
def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """ Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment """ result = self._wait_incrementing_start + (self....
[ "def", "incrementing_sleep", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "result", "=", "self", ".", "_wait_incrementing_start", "+", "(", "self", ".", "_wait_incrementing_increment", "*", "(", "previous_attempt_number", "...
[ 160, 4 ]
[ 168, 21 ]
python
en
['en', 'error', 'th']
False
Attempt.get
(self, wrap_exception=False)
Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised.
Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised.
def get(self, wrap_exception=False): """ Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised. """ if self.has_exception: if wrap_exception: ...
[ "def", "get", "(", "self", ",", "wrap_exception", "=", "False", ")", ":", "if", "self", ".", "has_exception", ":", "if", "wrap_exception", ":", "raise", "RetryError", "(", "self", ")", "else", ":", "six", ".", "reraise", "(", "self", ".", "value", "[",...
[ 236, 4 ]
[ 248, 29 ]
python
en
['en', 'error', 'th']
False
_best_version
(fields)
Detect the best version depending on the fields used.
Detect the best version depending on the fields used.
def _best_version(fields): """Detect the best version depending on the fields used.""" def _has_marker(keys, markers): for marker in markers: if marker in keys: return True return False keys = [] for key, value in fields.items(): if value in ([], 'UNK...
[ "def", "_best_version", "(", "fields", ")", ":", "def", "_has_marker", "(", "keys", ",", "markers", ")", ":", "for", "marker", "in", "markers", ":", "if", "marker", "in", "keys", ":", "return", "True", "return", "False", "keys", "=", "[", "]", "for", ...
[ 125, 0 ]
[ 194, 16 ]
python
en
['en', 'en', 'en']
True
_get_name_and_version
(name, version, for_filename=False)
Return the distribution name with version. If for_filename is true, return a filename-escaped form.
Return the distribution name with version.
def _get_name_and_version(name, version, for_filename=False): """Return the distribution name with version. If for_filename is true, return a filename-escaped form.""" if for_filename: # For both name and version any runs of non-alphanumeric or '.' # characters are replaced with a single '-...
[ "def", "_get_name_and_version", "(", "name", ",", "version", ",", "for_filename", "=", "False", ")", ":", "if", "for_filename", ":", "# For both name and version any runs of non-alphanumeric or '.'", "# characters are replaced with a single '-'. Additionally any", "# spaces in the...
[ 222, 0 ]
[ 232, 36 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.get_fullname
(self, filesafe=False)
Return the distribution name with version. If filesafe is true, return a filename-escaped form.
Return the distribution name with version.
def get_fullname(self, filesafe=False): """Return the distribution name with version. If filesafe is true, return a filename-escaped form.""" return _get_name_and_version(self['Name'], self['Version'], filesafe)
[ "def", "get_fullname", "(", "self", ",", "filesafe", "=", "False", ")", ":", "return", "_get_name_and_version", "(", "self", "[", "'Name'", "]", ",", "self", "[", "'Version'", "]", ",", "filesafe", ")" ]
[ 314, 4 ]
[ 318, 77 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.is_field
(self, name)
return True if name is a valid metadata key
return True if name is a valid metadata key
def is_field(self, name): """return True if name is a valid metadata key""" name = self._convert_name(name) return name in _ALL_FIELDS
[ "def", "is_field", "(", "self", ",", "name", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "return", "name", "in", "_ALL_FIELDS" ]
[ 320, 4 ]
[ 323, 34 ]
python
en
['en', 'et', 'en']
True
LegacyMetadata.read
(self, filepath)
Read the metadata values from a file path.
Read the metadata values from a file path.
def read(self, filepath): """Read the metadata values from a file path.""" fp = codecs.open(filepath, 'r', encoding='utf-8') try: self.read_file(fp) finally: fp.close()
[ "def", "read", "(", "self", ",", "filepath", ")", ":", "fp", "=", "codecs", ".", "open", "(", "filepath", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "self", ".", "read_file", "(", "fp", ")", "finally", ":", "fp", ".", "close", ...
[ 329, 4 ]
[ 335, 22 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.read_file
(self, fileob)
Read the metadata values from a file object.
Read the metadata values from a file object.
def read_file(self, fileob): """Read the metadata values from a file object.""" msg = message_from_file(fileob) self._fields['Metadata-Version'] = msg['metadata-version'] # When reading, get all the fields we can for field in _ALL_FIELDS: if field not in msg: ...
[ "def", "read_file", "(", "self", ",", "fileob", ")", ":", "msg", "=", "message_from_file", "(", "fileob", ")", "self", ".", "_fields", "[", "'Metadata-Version'", "]", "=", "msg", "[", "'metadata-version'", "]", "# When reading, get all the fields we can", "for", ...
[ 337, 4 ]
[ 361, 67 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.write
(self, filepath, skip_unknown=False)
Write the metadata fields to filepath.
Write the metadata fields to filepath.
def write(self, filepath, skip_unknown=False): """Write the metadata fields to filepath.""" fp = codecs.open(filepath, 'w', encoding='utf-8') try: self.write_file(fp, skip_unknown) finally: fp.close()
[ "def", "write", "(", "self", ",", "filepath", ",", "skip_unknown", "=", "False", ")", ":", "fp", "=", "codecs", ".", "open", "(", "filepath", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "self", ".", "write_file", "(", "fp", ",", "...
[ 365, 4 ]
[ 371, 22 ]
python
en
['en', 'el-Latn', 'en']
True
LegacyMetadata.write_file
(self, fileobject, skip_unknown=False)
Write the PKG-INFO format data to a file object.
Write the PKG-INFO format data to a file object.
def write_file(self, fileobject, skip_unknown=False): """Write the PKG-INFO format data to a file object.""" self.set_metadata_version() for field in _version2fieldlist(self['Metadata-Version']): values = self.get(field) if skip_unknown and values in ('UNKNOWN', [], ['UN...
[ "def", "write_file", "(", "self", ",", "fileobject", ",", "skip_unknown", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "for", "field", "in", "_version2fieldlist", "(", "self", "[", "'Metadata-Version'", "]", ")", ":", "values", "=",...
[ 373, 4 ]
[ 396, 59 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.update
(self, other=None, **kwargs)
Set metadata values from the given iterable `other` and kwargs. Behavior is like `dict.update`: If `other` has a ``keys`` method, they are looped over and ``self[key]`` is assigned ``other[key]``. Else, ``other`` is an iterable of ``(key, value)`` iterables. Keys that don't match a met...
Set metadata values from the given iterable `other` and kwargs.
def update(self, other=None, **kwargs): """Set metadata values from the given iterable `other` and kwargs. Behavior is like `dict.update`: If `other` has a ``keys`` method, they are looped over and ``self[key]`` is assigned ``other[key]``. Else, ``other`` is an iterable of ``(key, value...
[ "def", "update", "(", "self", ",", "other", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_set", "(", "key", ",", "value", ")", ":", "if", "key", "in", "_ATTR2FIELD", "and", "value", ":", "self", ".", "set", "(", "self", ".", "_convert_...
[ 398, 4 ]
[ 424, 26 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.set
(self, name, value)
Control then set a metadata field.
Control then set a metadata field.
def set(self, name, value): """Control then set a metadata field.""" name = self._convert_name(name) if ((name in _ELEMENTSFIELD or name == 'Platform') and not isinstance(value, (list, tuple))): if isinstance(value, string_types): value = [v.strip() for v...
[ "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "if", "(", "(", "name", "in", "_ELEMENTSFIELD", "or", "name", "==", "'Platform'", ")", "and", "not", "isinstance", "(", "valu...
[ 426, 4 ]
[ 468, 34 ]
python
en
['en', 'lb', 'en']
True
LegacyMetadata.get
(self, name, default=_MISSING)
Get a metadata field.
Get a metadata field.
def get(self, name, default=_MISSING): """Get a metadata field.""" name = self._convert_name(name) if name not in self._fields: if default is _MISSING: default = self._default_value(name) return default if name in _UNICODEFIELDS: value ...
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "if", "name", "not", "in", "self", ".", "_fields", ":", "if", "default", "is", "_MISSING", ":", "default",...
[ 470, 4 ]
[ 497, 33 ]
python
en
['ro', 'lb', 'en']
False