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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test_models_view_classification_single_matrix_table | (input_array, expected_string, template) | Testing if confusion matrix html table is created correctly. | Testing if confusion matrix html table is created correctly. | def test_models_view_classification_single_matrix_table(input_array, expected_string, template):
"""Testing if confusion matrix html table is created correctly."""
expected_class = "test-class"
mv = ModelsViewClassification(template, "test_css", "params", "test-class")
mv._confusion_matrices_single_matr... | [
"def",
"test_models_view_classification_single_matrix_table",
"(",
"input_array",
",",
"expected_string",
",",
"template",
")",
":",
"expected_class",
"=",
"\"test-class\"",
"mv",
"=",
"ModelsViewClassification",
"(",
"template",
",",
"\"test_css\"",
",",
"\"params\"",
",... | [
377,
0
] | [
385,
42
] | python | en | ['en', 'en', 'en'] | True |
test_models_view_classification_confusion_matrices | (input_tuple, template) | Testing if the confusion matrices html is created correctly and classes are assigned to elements
appropriately. | Testing if the confusion matrices html is created correctly and classes are assigned to elements
appropriately. | def test_models_view_classification_confusion_matrices(input_tuple, template):
"""Testing if the confusion matrices html is created correctly and classes are assigned to elements
appropriately."""
first_model = "test-first-model"
other_model = "test-other-model"
title_class = "test-title-class"
... | [
"def",
"test_models_view_classification_confusion_matrices",
"(",
"input_tuple",
",",
"template",
")",
":",
"first_model",
"=",
"\"test-first-model\"",
"other_model",
"=",
"\"test-other-model\"",
"title_class",
"=",
"\"test-title-class\"",
"matrix_class",
"=",
"\"test-matrix-cl... | [
402,
0
] | [
427,
45
] | python | en | ['en', 'en', 'en'] | True |
bdist_rpm._make_spec_file | (self) | Generate the text of an RPM spec file and return it as a
list of strings (one per line).
| Generate the text of an RPM spec file and return it as a
list of strings (one per line).
| def _make_spec_file(self):
"""Generate the text of an RPM spec file and return it as a
list of strings (one per line).
"""
# definitions and headers
spec_file = [
'%define name ' + self.distribution.get_name(),
'%define version ' + self.distribution.get_ve... | [
"def",
"_make_spec_file",
"(",
"self",
")",
":",
"# definitions and headers",
"spec_file",
"=",
"[",
"'%define name '",
"+",
"self",
".",
"distribution",
".",
"get_name",
"(",
")",
",",
"'%define version '",
"+",
"self",
".",
"distribution",
".",
"get_version",
... | [
390,
4
] | [
557,
24
] | python | en | ['en', 'en', 'en'] | True |
bdist_rpm._format_changelog | (self, changelog) | Format the changelog correctly and convert it to a list of strings
| Format the changelog correctly and convert it to a list of strings
| def _format_changelog(self, changelog):
"""Format the changelog correctly and convert it to a list of strings
"""
if not changelog:
return changelog
new_changelog = []
for line in changelog.strip().split('\n'):
line = line.strip()
if line[0] ==... | [
"def",
"_format_changelog",
"(",
"self",
",",
"changelog",
")",
":",
"if",
"not",
"changelog",
":",
"return",
"changelog",
"new_changelog",
"=",
"[",
"]",
"for",
"line",
"in",
"changelog",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"... | [
559,
4
] | [
578,
28
] | python | en | ['en', 'en', 'en'] | True |
move_rows | (
base_model: Model,
raw_query: Composable,
*,
src_db_table: Optional[str] = None,
returning_id: bool = False,
**kwargs: Composable,
) | Core helper for bulk moving rows between a table and its archive table | Core helper for bulk moving rows between a table and its archive table | def move_rows(
base_model: Model,
raw_query: Composable,
*,
src_db_table: Optional[str] = None,
returning_id: bool = False,
**kwargs: Composable,
) -> List[int]:
"""Core helper for bulk moving rows between a table and its archive table"""
if src_db_table is None:
# Use base_model... | [
"def",
"move_rows",
"(",
"base_model",
":",
"Model",
",",
"raw_query",
":",
"Composable",
",",
"*",
",",
"src_db_table",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"returning_id",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
":",
"Compo... | [
92,
0
] | [
119,
21
] | python | en | ['en', 'en', 'en'] | True |
get_realms_and_streams_for_archiving | () |
This function constructs a list of (realm, streams_of_the_realm) tuples
where each realm is a Realm that requires calling the archiving functions on it,
and streams_of_the_realm is a list of streams of the realm to call archive_stream_messages with.
The purpose of this is performance - for servers wit... |
This function constructs a list of (realm, streams_of_the_realm) tuples
where each realm is a Realm that requires calling the archiving functions on it,
and streams_of_the_realm is a list of streams of the realm to call archive_stream_messages with. | def get_realms_and_streams_for_archiving() -> List[Tuple[Realm, List[Stream]]]:
"""
This function constructs a list of (realm, streams_of_the_realm) tuples
where each realm is a Realm that requires calling the archiving functions on it,
and streams_of_the_realm is a list of streams of the realm to call ... | [
"def",
"get_realms_and_streams_for_archiving",
"(",
")",
"->",
"List",
"[",
"Tuple",
"[",
"Realm",
",",
"List",
"[",
"Stream",
"]",
"]",
"]",
":",
"realm_id_to_realm",
"=",
"{",
"}",
"realm_id_to_streams_list",
":",
"Dict",
"[",
"int",
",",
"List",
"[",
"S... | [
438,
0
] | [
485,
5
] | python | en | ['en', 'error', 'th'] | False |
restore_retention_policy_deletions_for_stream | (stream: Stream) |
Utility function for calling in the Django shell if a stream's policy was
set to something too aggressive and the administrator wants to restore
the messages deleted as a result.
|
Utility function for calling in the Django shell if a stream's policy was
set to something too aggressive and the administrator wants to restore
the messages deleted as a result.
| def restore_retention_policy_deletions_for_stream(stream: Stream) -> None:
"""
Utility function for calling in the Django shell if a stream's policy was
set to something too aggressive and the administrator wants to restore
the messages deleted as a result.
"""
relevant_transactions = ArchiveTra... | [
"def",
"restore_retention_policy_deletions_for_stream",
"(",
"stream",
":",
"Stream",
")",
"->",
"None",
":",
"relevant_transactions",
"=",
"ArchiveTransaction",
".",
"objects",
".",
"filter",
"(",
"archivedmessage__recipient",
"=",
"stream",
".",
"recipient",
",",
"t... | [
656,
0
] | [
666,
74
] | python | en | ['en', 'error', 'th'] | False |
user_groups_in_realm_serialized | (realm: Realm) | This function is used in do_events_register code path so this code
should be performant. We need to do 2 database queries because
Django's ORM doesn't properly support the left join between
UserGroup and UserGroupMembership that we need.
| This function is used in do_events_register code path so this code
should be performant. We need to do 2 database queries because
Django's ORM doesn't properly support the left join between
UserGroup and UserGroupMembership that we need.
| def user_groups_in_realm_serialized(realm: Realm) -> List[Dict[str, Any]]:
"""This function is used in do_events_register code path so this code
should be performant. We need to do 2 database queries because
Django's ORM doesn't properly support the left join between
UserGroup and UserGroupMembership t... | [
"def",
"user_groups_in_realm_serialized",
"(",
"realm",
":",
"Realm",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"realm_groups",
"=",
"UserGroup",
".",
"objects",
".",
"filter",
"(",
"realm",
"=",
"realm",
")",
"group_dicts",
... | [
26,
0
] | [
50,
80
] | python | en | ['en', 'en', 'en'] | True |
TestParser.test_multiple_metavar_help | (self, parser) |
Help text for options with a metavar tuple should display help
in the form "--preferences=value1 value2 value3" (#2004).
|
Help text for options with a metavar tuple should display help
in the form "--preferences=value1 value2 value3" (#2004).
| def test_multiple_metavar_help(self, parser):
"""
Help text for options with a metavar tuple should display help
in the form "--preferences=value1 value2 value3" (#2004).
"""
group = parser.getgroup("general")
group.addoption('--preferences', metavar=('value1', 'value2', ... | [
"def",
"test_multiple_metavar_help",
"(",
"self",
",",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"getgroup",
"(",
"\"general\"",
")",
"group",
".",
"addoption",
"(",
"'--preferences'",
",",
"metavar",
"=",
"(",
"'value1'",
",",
"'value2'",
",",
"'valu... | [
260,
4
] | [
270,
59
] | python | en | ['en', 'error', 'th'] | False |
unique_counts | (labels) |
Unique count function used to count labels.
|
Unique count function used to count labels.
| def unique_counts(labels):
"""
Unique count function used to count labels.
"""
results = {}
for label in labels:
value = label.item()
if value not in results.keys():
results[value] = 0
results[value] += 1
return results | [
"def",
"unique_counts",
"(",
"labels",
")",
":",
"results",
"=",
"{",
"}",
"for",
"label",
"in",
"labels",
":",
"value",
"=",
"label",
".",
"item",
"(",
")",
"if",
"value",
"not",
"in",
"results",
".",
"keys",
"(",
")",
":",
"results",
"[",
"value"... | [
6,
0
] | [
16,
18
] | python | en | ['en', 'error', 'th'] | False |
divide_set | (vectors, labels, column, value) |
Divide the sets into two different sets along a specific dimension and value.
|
Divide the sets into two different sets along a specific dimension and value.
| def divide_set(vectors, labels, column, value):
"""
Divide the sets into two different sets along a specific dimension and value.
"""
set_1 = [(vector, label) for vector, label in zip(vectors, labels) if split_function(vector, column, value)]
set_2 = [(vector, label) for vector, label in zip(vectors... | [
"def",
"divide_set",
"(",
"vectors",
",",
"labels",
",",
"column",
",",
"value",
")",
":",
"set_1",
"=",
"[",
"(",
"vector",
",",
"label",
")",
"for",
"vector",
",",
"label",
"in",
"zip",
"(",
"vectors",
",",
"labels",
")",
"if",
"split_function",
"(... | [
19,
0
] | [
31,
65
] | python | en | ['en', 'error', 'th'] | False |
split_function | (vector, column, value) |
Split function
|
Split function
| def split_function(vector, column, value):
"""
Split function
"""
return vector[column] >= value | [
"def",
"split_function",
"(",
"vector",
",",
"column",
",",
"value",
")",
":",
"return",
"vector",
"[",
"column",
"]",
">=",
"value"
] | [
34,
0
] | [
38,
34
] | python | en | ['en', 'error', 'th'] | False |
log2 | (x) |
Log2 function
|
Log2 function
| def log2(x):
"""
Log2 function
"""
return log(x) / log(2) | [
"def",
"log2",
"(",
"x",
")",
":",
"return",
"log",
"(",
"x",
")",
"/",
"log",
"(",
"2",
")"
] | [
41,
0
] | [
45,
26
] | python | en | ['en', 'error', 'th'] | False |
sample_vectors | (vectors, labels, nb_samples) |
Sample vectors and labels uniformly.
|
Sample vectors and labels uniformly.
| def sample_vectors(vectors, labels, nb_samples):
"""
Sample vectors and labels uniformly.
"""
sampled_indices = torch.LongTensor(random.sample(range(len(vectors)), nb_samples))
sampled_vectors = torch.index_select(vectors,0, sampled_indices)
sampled_labels = torch.index_select(labels,0, sampled_... | [
"def",
"sample_vectors",
"(",
"vectors",
",",
"labels",
",",
"nb_samples",
")",
":",
"sampled_indices",
"=",
"torch",
".",
"LongTensor",
"(",
"random",
".",
"sample",
"(",
"range",
"(",
"len",
"(",
"vectors",
")",
")",
",",
"nb_samples",
")",
")",
"sampl... | [
48,
0
] | [
56,
42
] | python | en | ['en', 'error', 'th'] | False |
sample_dimensions | (vectors) |
Sample vectors along dimension uniformly.
|
Sample vectors along dimension uniformly.
| def sample_dimensions(vectors):
"""
Sample vectors along dimension uniformly.
"""
sample_dimension = torch.LongTensor(random.sample(range(len(vectors[0])), int(sqrt(len(vectors[0])))))
return sample_dimension | [
"def",
"sample_dimensions",
"(",
"vectors",
")",
":",
"sample_dimension",
"=",
"torch",
".",
"LongTensor",
"(",
"random",
".",
"sample",
"(",
"range",
"(",
"len",
"(",
"vectors",
"[",
"0",
"]",
")",
")",
",",
"int",
"(",
"sqrt",
"(",
"len",
"(",
"vec... | [
59,
0
] | [
65,
27
] | python | en | ['en', 'error', 'th'] | False |
entropy | (labels) |
Entropy function.
|
Entropy function.
| def entropy(labels):
"""
Entropy function.
"""
results = unique_counts(labels)
ent = 0.0
for r in results.keys():
p = float(results[r]) / len(labels)
ent = ent - p * log2(p)
return ent | [
"def",
"entropy",
"(",
"labels",
")",
":",
"results",
"=",
"unique_counts",
"(",
"labels",
")",
"ent",
"=",
"0.0",
"for",
"r",
"in",
"results",
".",
"keys",
"(",
")",
":",
"p",
"=",
"float",
"(",
"results",
"[",
"r",
"]",
")",
"/",
"len",
"(",
... | [
68,
0
] | [
77,
14
] | python | en | ['en', 'error', 'th'] | False |
variance | (values) |
Variance function.
|
Variance function.
| def variance(values):
"""
Variance function.
"""
mean_value = mean(values)
var = 0.0
for value in values:
var = var + torch.sum(torch.sqrt(torch.pow(value-mean_value,2))).item()/len(values)
return var | [
"def",
"variance",
"(",
"values",
")",
":",
"mean_value",
"=",
"mean",
"(",
"values",
")",
"var",
"=",
"0.0",
"for",
"value",
"in",
"values",
":",
"var",
"=",
"var",
"+",
"torch",
".",
"sum",
"(",
"torch",
".",
"sqrt",
"(",
"torch",
".",
"pow",
"... | [
80,
0
] | [
88,
14
] | python | en | ['en', 'error', 'th'] | False |
mean | (values) |
Mean function.
|
Mean function.
| def mean(values):
"""
Mean function.
"""
m = 0.0
for value in values:
m = m + value/len(values)
return m | [
"def",
"mean",
"(",
"values",
")",
":",
"m",
"=",
"0.0",
"for",
"value",
"in",
"values",
":",
"m",
"=",
"m",
"+",
"value",
"/",
"len",
"(",
"values",
")",
"return",
"m"
] | [
91,
0
] | [
98,
12
] | python | en | ['en', 'error', 'th'] | False |
RequestMethods.request | (self, method, url, fields=None, headers=None, **urlopen_kw) |
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be used in most situations, while still having the
option to drop down to more spe... |
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used. | def request(self, method, url, fields=None, headers=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be use... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"method",
"=",
"method",
".",
"upper",
"(",
")",
"urlopen_kw",
"[",
"\"request_url\"",
"]",
"=",... | [
58,
4
] | [
80,
13
] | python | en | ['en', 'error', 'th'] | False |
RequestMethods.request_encode_url | (self, method, url, fields=None, headers=None, **urlopen_kw) |
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
|
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
| def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if headers is None:
headers = self.... | [
"def",
"request_encode_url",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"self",
".",
"headers",
"extra_kw",... | [
82,
4
] | [
96,
52
] | python | en | ['en', 'error', 'th'] | False |
RequestMethods.request_encode_body | (
self,
method,
url,
fields=None,
headers=None,
encode_multipart=True,
multipart_boundary=None,
**urlopen_kw
) |
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:meth:`urllib3.filepost.encode_multipart_formdata` is used to encode
the payload with the ... |
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc. | def request_encode_body(
self,
method,
url,
fields=None,
headers=None,
encode_multipart=True,
multipart_boundary=None,
**urlopen_kw
):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is use... | [
"def",
"request_encode_body",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"encode_multipart",
"=",
"True",
",",
"multipart_boundary",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"if",
"hea... | [
98,
4
] | [
170,
52
] | python | en | ['en', 'error', 'th'] | False |
_melody_transition_distribution | (rest_prob, interval_prob_fn) | Compute the transition distribution between melody pitches (and rest).
Args:
rest_prob: Probability that a note will be followed by a rest.
interval_prob_fn: Function from pitch interval (value between -127 and 127)
to weight. Will be normalized so that outgoing probabilities (including
rest)... | Compute the transition distribution between melody pitches (and rest). | def _melody_transition_distribution(rest_prob, interval_prob_fn):
"""Compute the transition distribution between melody pitches (and rest).
Args:
rest_prob: Probability that a note will be followed by a rest.
interval_prob_fn: Function from pitch interval (value between -127 and 127)
to weight. Wil... | [
"def",
"_melody_transition_distribution",
"(",
"rest_prob",
",",
"interval_prob_fn",
")",
":",
"pitches",
"=",
"np",
".",
"arange",
"(",
"constants",
".",
"MIN_MIDI_PITCH",
",",
"constants",
".",
"MAX_MIDI_PITCH",
"+",
"1",
")",
"num_pitches",
"=",
"len",
"(",
... | [
30,
0
] | [
85,
12
] | python | en | ['en', 'en', 'en'] | True |
sequence_note_frames | (sequence) | Split a NoteSequence into frame summaries separated by onsets/offsets.
Args:
sequence: The NoteSequence for which to compute frame summaries.
Returns:
pitches: A list of MIDI pitches present in `sequence`, in ascending order.
has_onsets: A Boolean matrix with shape `[num_frames, num_pitches]` where
... | Split a NoteSequence into frame summaries separated by onsets/offsets. | def sequence_note_frames(sequence):
"""Split a NoteSequence into frame summaries separated by onsets/offsets.
Args:
sequence: The NoteSequence for which to compute frame summaries.
Returns:
pitches: A list of MIDI pitches present in `sequence`, in ascending order.
has_onsets: A Boolean matrix with s... | [
"def",
"sequence_note_frames",
"(",
"sequence",
")",
":",
"notes",
"=",
"[",
"note",
"for",
"note",
"in",
"sequence",
".",
"notes",
"if",
"not",
"note",
".",
"is_drum",
"and",
"note",
".",
"program",
"not",
"in",
"constants",
".",
"UNPITCHED_PROGRAMS",
"]"... | [
88,
0
] | [
132,
52
] | python | en | ['en', 'en', 'en'] | True |
_melody_frame_log_likelihood | (pitches, has_onsets, has_notes, durations,
instantaneous_non_max_pitch_prob,
instantaneous_non_empty_rest_prob,
instantaneous_missing_pitch_prob) | Compute the log-likelihood of each frame given each melody state. | Compute the log-likelihood of each frame given each melody state. | def _melody_frame_log_likelihood(pitches, has_onsets, has_notes, durations,
instantaneous_non_max_pitch_prob,
instantaneous_non_empty_rest_prob,
instantaneous_missing_pitch_prob):
"""Compute the log-likelihood of each f... | [
"def",
"_melody_frame_log_likelihood",
"(",
"pitches",
",",
"has_onsets",
",",
"has_notes",
",",
"durations",
",",
"instantaneous_non_max_pitch_prob",
",",
"instantaneous_non_empty_rest_prob",
",",
"instantaneous_missing_pitch_prob",
")",
":",
"num_frames",
"=",
"len",
"(",... | [
135,
0
] | [
185,
12
] | python | en | ['en', 'en', 'en'] | True |
_melody_viterbi | (pitches, melody_frame_loglik, melody_transition_loglik) | Use the Viterbi algorithm to infer a sequence of melody events. | Use the Viterbi algorithm to infer a sequence of melody events. | def _melody_viterbi(pitches, melody_frame_loglik, melody_transition_loglik):
"""Use the Viterbi algorithm to infer a sequence of melody events."""
num_frames, num_melody_events = melody_frame_loglik.shape
assert num_melody_events == 2 * len(pitches) + 1
loglik_matrix = np.zeros([num_frames, num_melody_events])... | [
"def",
"_melody_viterbi",
"(",
"pitches",
",",
"melody_frame_loglik",
",",
"melody_transition_loglik",
")",
":",
"num_frames",
",",
"num_melody_events",
"=",
"melody_frame_loglik",
".",
"shape",
"assert",
"num_melody_events",
"==",
"2",
"*",
"len",
"(",
"pitches",
"... | [
188,
0
] | [
228,
56
] | python | en | ['en', 'en', 'en'] | True |
infer_melody_for_sequence | (sequence,
melody_interval_scale=2.0,
rest_prob=0.1,
instantaneous_non_max_pitch_prob=1e-15,
instantaneous_non_empty_rest_prob=0.0,
instantaneous_missing_pitch_prob=1e-15... | Infer melody for a NoteSequence.
This is a work in progress and should not necessarily be expected to return
reasonable results. It operates under two main assumptions:
1) Melody onsets always coincide with actual note onsets from the polyphonic
NoteSequence.
2) When multiple notes are active, the melody... | Infer melody for a NoteSequence. | def infer_melody_for_sequence(sequence,
melody_interval_scale=2.0,
rest_prob=0.1,
instantaneous_non_max_pitch_prob=1e-15,
instantaneous_non_empty_rest_prob=0.0,
instantan... | [
"def",
"infer_melody_for_sequence",
"(",
"sequence",
",",
"melody_interval_scale",
"=",
"2.0",
",",
"rest_prob",
"=",
"0.1",
",",
"instantaneous_non_max_pitch_prob",
"=",
"1e-15",
",",
"instantaneous_non_empty_rest_prob",
"=",
"0.0",
",",
"instantaneous_missing_pitch_prob",... | [
235,
0
] | [
365,
26
] | python | en | ['en', 'en', 'en'] | True |
normalize_version_info | (py_version_info) |
Convert a tuple of ints representing a Python version to one of length
three.
:param py_version_info: a tuple of ints representing a Python version,
or None to specify no version. The tuple can have any length.
:return: a tuple of length three if `py_version_info` is non-None.
Otherwi... |
Convert a tuple of ints representing a Python version to one of length
three. | def normalize_version_info(py_version_info):
# type: (Tuple[int, ...]) -> Tuple[int, int, int]
"""
Convert a tuple of ints representing a Python version to one of length
three.
:param py_version_info: a tuple of ints representing a Python version,
or None to specify no version. The tuple ca... | [
"def",
"normalize_version_info",
"(",
"py_version_info",
")",
":",
"# type: (Tuple[int, ...]) -> Tuple[int, int, int]",
"if",
"len",
"(",
"py_version_info",
")",
"<",
"3",
":",
"py_version_info",
"+=",
"(",
"3",
"-",
"len",
"(",
"py_version_info",
")",
")",
"*",
"... | [
89,
0
] | [
106,
47
] | python | en | ['en', 'error', 'th'] | False |
ensure_dir | (path) | os.path.makedirs without EEXIST. | os.path.makedirs without EEXIST. | def ensure_dir(path):
# type: (AnyStr) -> None
"""os.path.makedirs without EEXIST."""
try:
os.makedirs(path)
except OSError as e:
# Windows can raise spurious ENOTEMPTY errors. See #6426.
if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
raise | [
"def",
"ensure_dir",
"(",
"path",
")",
":",
"# type: (AnyStr) -> None",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"# Windows can raise spurious ENOTEMPTY errors. See #6426.",
"if",
"e",
".",
"errno",
"!=",
"errno",
... | [
109,
0
] | [
117,
17
] | python | en | ['en', 'en', 'en'] | True |
rmtree_errorhandler | (func, path, exc_info) | On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems. | On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems. | def rmtree_errorhandler(func, path, exc_info):
"""On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems."""
try:
has_attr_readonly = not (os.stat(pat... | [
"def",
"rmtree_errorhandler",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"try",
":",
"has_attr_readonly",
"=",
"not",
"(",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
"&",
"stat",
".",
"S_IWRITE",
")",
"except",
"(",
"IOError",
",",
... | [
141,
0
] | [
158,
13
] | python | en | ['en', 'en', 'en'] | True |
path_to_display | (path) |
Convert a bytes (or text) path to text (unicode in Python 2) for display
and logging purposes.
This function should never error out. Also, this function is mainly needed
for Python 2 since in Python 3 str paths are already text.
|
Convert a bytes (or text) path to text (unicode in Python 2) for display
and logging purposes. | def path_to_display(path):
# type: (Optional[Union[str, Text]]) -> Optional[Text]
"""
Convert a bytes (or text) path to text (unicode in Python 2) for display
and logging purposes.
This function should never error out. Also, this function is mainly needed
for Python 2 since in Python 3 str path... | [
"def",
"path_to_display",
"(",
"path",
")",
":",
"# type: (Optional[Union[str, Text]]) -> Optional[Text]",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"path",
",",
"text_type",
")",
":",
"return",
"path",
"# Otherwise, path is a bytes o... | [
161,
0
] | [
192,
23
] | python | en | ['en', 'error', 'th'] | False |
display_path | (path) | Gives the display value for a given path, making it relative to cwd
if possible. | Gives the display value for a given path, making it relative to cwd
if possible. | def display_path(path):
# type: (Union[str, Text]) -> str
"""Gives the display value for a given path, making it relative to cwd
if possible."""
path = os.path.normcase(os.path.abspath(path))
if sys.version_info[0] == 2:
path = path.decode(sys.getfilesystemencoding(), 'replace')
path... | [
"def",
"display_path",
"(",
"path",
")",
":",
"# type: (Union[str, Text]) -> str",
"path",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2... | [
195,
0
] | [
205,
15
] | python | en | ['en', 'en', 'en'] | True |
backup_dir | (dir, ext='.bak') | Figure out the name of a directory to back up the given dir to
(adding .bak, .bak2, etc) | Figure out the name of a directory to back up the given dir to
(adding .bak, .bak2, etc) | def backup_dir(dir, ext='.bak'):
# type: (str, str) -> str
"""Figure out the name of a directory to back up the given dir to
(adding .bak, .bak2, etc)"""
n = 1
extension = ext
while os.path.exists(dir + extension):
n += 1
extension = ext + str(n)
return dir + extension | [
"def",
"backup_dir",
"(",
"dir",
",",
"ext",
"=",
"'.bak'",
")",
":",
"# type: (str, str) -> str",
"n",
"=",
"1",
"extension",
"=",
"ext",
"while",
"os",
".",
"path",
".",
"exists",
"(",
"dir",
"+",
"extension",
")",
":",
"n",
"+=",
"1",
"extension",
... | [
208,
0
] | [
217,
26
] | python | en | ['en', 'en', 'en'] | True |
_check_no_input | (message) | Raise an error if no input is allowed. | Raise an error if no input is allowed. | def _check_no_input(message):
# type: (str) -> None
"""Raise an error if no input is allowed."""
if os.environ.get('PIP_NO_INPUT'):
raise Exception(
'No input was expected ($PIP_NO_INPUT set); question: {}'.format(
message)
) | [
"def",
"_check_no_input",
"(",
"message",
")",
":",
"# type: (str) -> None",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'PIP_NO_INPUT'",
")",
":",
"raise",
"Exception",
"(",
"'No input was expected ($PIP_NO_INPUT set); question: {}'",
".",
"format",
"(",
"message",... | [
228,
0
] | [
235,
9
] | python | en | ['en', 'lb', 'en'] | True |
ask | (message, options) | Ask the message interactively, with the given possible responses | Ask the message interactively, with the given possible responses | def ask(message, options):
# type: (str, Iterable[str]) -> str
"""Ask the message interactively, with the given possible responses"""
while 1:
_check_no_input(message)
response = input(message)
response = response.strip().lower()
if response not in options:
print(... | [
"def",
"ask",
"(",
"message",
",",
"options",
")",
":",
"# type: (str, Iterable[str]) -> str",
"while",
"1",
":",
"_check_no_input",
"(",
"message",
")",
"response",
"=",
"input",
"(",
"message",
")",
"response",
"=",
"response",
".",
"strip",
"(",
")",
".",... | [
238,
0
] | [
251,
27
] | python | en | ['en', 'en', 'en'] | True |
ask_input | (message) | Ask for input interactively. | Ask for input interactively. | def ask_input(message):
# type: (str) -> str
"""Ask for input interactively."""
_check_no_input(message)
return input(message) | [
"def",
"ask_input",
"(",
"message",
")",
":",
"# type: (str) -> str",
"_check_no_input",
"(",
"message",
")",
"return",
"input",
"(",
"message",
")"
] | [
254,
0
] | [
258,
25
] | python | en | ['en', 'en', 'en'] | True |
ask_password | (message) | Ask for a password interactively. | Ask for a password interactively. | def ask_password(message):
# type: (str) -> str
"""Ask for a password interactively."""
_check_no_input(message)
return getpass.getpass(message) | [
"def",
"ask_password",
"(",
"message",
")",
":",
"# type: (str) -> str",
"_check_no_input",
"(",
"message",
")",
"return",
"getpass",
".",
"getpass",
"(",
"message",
")"
] | [
261,
0
] | [
265,
35
] | python | en | ['en', 'en', 'en'] | True |
tabulate | (rows) | Return a list of formatted rows and a list of column sizes.
For example::
>>> tabulate([['foobar', 2000], [0xdeadbeef]])
(['foobar 2000', '3735928559'], [10, 4])
| Return a list of formatted rows and a list of column sizes. | def tabulate(rows):
# type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]
"""Return a list of formatted rows and a list of column sizes.
For example::
>>> tabulate([['foobar', 2000], [0xdeadbeef]])
(['foobar 2000', '3735928559'], [10, 4])
"""
rows = [tuple(map(str, row)) for... | [
"def",
"tabulate",
"(",
"rows",
")",
":",
"# type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]",
"rows",
"=",
"[",
"tuple",
"(",
"map",
"(",
"str",
",",
"row",
")",
")",
"for",
"row",
"in",
"rows",
"]",
"sizes",
"=",
"[",
"max",
"(",
"map",
"(... | [
280,
0
] | [
292,
23
] | python | en | ['en', 'en', 'en'] | True |
is_installable_dir | (path) | Is path is a directory containing setup.py or pyproject.toml?
| Is path is a directory containing setup.py or pyproject.toml?
| def is_installable_dir(path):
# type: (str) -> bool
"""Is path is a directory containing setup.py or pyproject.toml?
"""
if not os.path.isdir(path):
return False
setup_py = os.path.join(path, 'setup.py')
if os.path.isfile(setup_py):
return True
pyproject_toml = os.path.join(p... | [
"def",
"is_installable_dir",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"False",
"setup_py",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'setup.py'",
")",
"... | [
295,
0
] | [
307,
16
] | python | en | ['en', 'en', 'en'] | True |
read_chunks | (file, size=io.DEFAULT_BUFFER_SIZE) | Yield pieces of data from a file-like object until EOF. | Yield pieces of data from a file-like object until EOF. | def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
"""Yield pieces of data from a file-like object until EOF."""
while True:
chunk = file.read(size)
if not chunk:
break
yield chunk | [
"def",
"read_chunks",
"(",
"file",
",",
"size",
"=",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"file",
".",
"read",
"(",
"size",
")",
"if",
"not",
"chunk",
":",
"break",
"yield",
"chunk"
] | [
310,
0
] | [
316,
19
] | python | en | ['en', 'en', 'en'] | True |
normalize_path | (path, resolve_symlinks=True) |
Convert a path to its canonical, case-normalized, absolute version.
|
Convert a path to its canonical, case-normalized, absolute version. | def normalize_path(path, resolve_symlinks=True):
# type: (str, bool) -> str
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
path = expanduser(path)
if resolve_symlinks:
path = os.path.realpath(path)
else:
path = os.path.abspath(path)
return os... | [
"def",
"normalize_path",
"(",
"path",
",",
"resolve_symlinks",
"=",
"True",
")",
":",
"# type: (str, bool) -> str",
"path",
"=",
"expanduser",
"(",
"path",
")",
"if",
"resolve_symlinks",
":",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",... | [
319,
0
] | [
330,
33
] | python | en | ['en', 'error', 'th'] | False |
splitext | (path) | Like os.path.splitext, but take off .tar too | Like os.path.splitext, but take off .tar too | def splitext(path):
# type: (str) -> Tuple[str, str]
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | [
"def",
"splitext",
"(",
"path",
")",
":",
"# type: (str) -> Tuple[str, str]",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"path",
")",
"if",
"base",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.tar'",
")",
":",
"ext",
"=",
"base",
"... | [
333,
0
] | [
340,
20
] | python | en | ['en', 'en', 'en'] | True |
renames | (old, new) | Like os.renames(), but handles renaming across devices. | Like os.renames(), but handles renaming across devices. | def renames(old, new):
# type: (str, str) -> None
"""Like os.renames(), but handles renaming across devices."""
# Implementation borrowed from os.renames().
head, tail = os.path.split(new)
if head and tail and not os.path.exists(head):
os.makedirs(head)
shutil.move(old, new)
head, ... | [
"def",
"renames",
"(",
"old",
",",
"new",
")",
":",
"# type: (str, str) -> None",
"# Implementation borrowed from os.renames().",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"new",
")",
"if",
"head",
"and",
"tail",
"and",
"not",
"os",
"."... | [
343,
0
] | [
358,
16
] | python | en | ['en', 'en', 'en'] | True |
is_local | (path) |
Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local."
Caution: this function assumes the head of path has been normalized
with normalize_path.
|
Return True if path is within sys.prefix, if we're running in a virtualenv. | def is_local(path):
# type: (str) -> bool
"""
Return True if path is within sys.prefix, if we're running in a virtualenv.
If we're not in a virtualenv, all paths are considered "local."
Caution: this function assumes the head of path has been normalized
with normalize_path.
"""
if not ... | [
"def",
"is_local",
"(",
"path",
")",
":",
"# type: (str) -> bool",
"if",
"not",
"running_under_virtualenv",
"(",
")",
":",
"return",
"True",
"return",
"path",
".",
"startswith",
"(",
"normalize_path",
"(",
"sys",
".",
"prefix",
")",
")"
] | [
361,
0
] | [
373,
54
] | python | en | ['en', 'error', 'th'] | False |
dist_is_local | (dist) |
Return True if given Distribution object is installed locally
(i.e. within current virtualenv).
Always True if we're not in a virtualenv.
|
Return True if given Distribution object is installed locally
(i.e. within current virtualenv). | def dist_is_local(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution object is installed locally
(i.e. within current virtualenv).
Always True if we're not in a virtualenv.
"""
return is_local(dist_location(dist)) | [
"def",
"dist_is_local",
"(",
"dist",
")",
":",
"# type: (Distribution) -> bool",
"return",
"is_local",
"(",
"dist_location",
"(",
"dist",
")",
")"
] | [
376,
0
] | [
385,
40
] | python | en | ['en', 'error', 'th'] | False |
dist_in_usersite | (dist) |
Return True if given Distribution is installed in user site.
|
Return True if given Distribution is installed in user site.
| def dist_in_usersite(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is installed in user site.
"""
return dist_location(dist).startswith(normalize_path(user_site)) | [
"def",
"dist_in_usersite",
"(",
"dist",
")",
":",
"# type: (Distribution) -> bool",
"return",
"dist_location",
"(",
"dist",
")",
".",
"startswith",
"(",
"normalize_path",
"(",
"user_site",
")",
")"
] | [
388,
0
] | [
393,
68
] | python | en | ['en', 'error', 'th'] | False |
dist_in_site_packages | (dist) |
Return True if given Distribution is installed in
sysconfig.get_python_lib().
|
Return True if given Distribution is installed in
sysconfig.get_python_lib().
| def dist_in_site_packages(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is installed in
sysconfig.get_python_lib().
"""
return dist_location(dist).startswith(normalize_path(site_packages)) | [
"def",
"dist_in_site_packages",
"(",
"dist",
")",
":",
"# type: (Distribution) -> bool",
"return",
"dist_location",
"(",
"dist",
")",
".",
"startswith",
"(",
"normalize_path",
"(",
"site_packages",
")",
")"
] | [
396,
0
] | [
402,
72
] | python | en | ['en', 'error', 'th'] | False |
dist_is_editable | (dist) |
Return True if given Distribution is an editable install.
|
Return True if given Distribution is an editable install.
| def dist_is_editable(dist):
# type: (Distribution) -> bool
"""
Return True if given Distribution is an editable install.
"""
for path_item in sys.path:
egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
if os.path.isfile(egg_link):
return True
return ... | [
"def",
"dist_is_editable",
"(",
"dist",
")",
":",
"# type: (Distribution) -> bool",
"for",
"path_item",
"in",
"sys",
".",
"path",
":",
"egg_link",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"dist",
".",
"project_name",
"+",
"'.egg-link'",
")... | [
405,
0
] | [
414,
16
] | python | en | ['en', 'error', 'th'] | False |
get_installed_distributions | (
local_only=True, # type: bool
skip=stdlib_pkgs, # type: Container[str]
include_editables=True, # type: bool
editables_only=False, # type: bool
user_only=False, # type: bool
paths=None # type: Optional[List[str]]
) |
Return a list of installed Distribution objects.
If ``local_only`` is True (default), only return installations
local to the current virtualenv, if in a virtualenv.
``skip`` argument is an iterable of lower-case project names to
ignore; defaults to stdlib_pkgs
If ``include_editables`` is Fal... |
Return a list of installed Distribution objects. | def get_installed_distributions(
local_only=True, # type: bool
skip=stdlib_pkgs, # type: Container[str]
include_editables=True, # type: bool
editables_only=False, # type: bool
user_only=False, # type: bool
paths=None # type: Optional[List[str]]
):
# type: (...) ... | [
"def",
"get_installed_distributions",
"(",
"local_only",
"=",
"True",
",",
"# type: bool",
"skip",
"=",
"stdlib_pkgs",
",",
"# type: Container[str]",
"include_editables",
"=",
"True",
",",
"# type: bool",
"editables_only",
"=",
"False",
",",
"# type: bool",
"user_only",... | [
417,
0
] | [
482,
13
] | python | en | ['en', 'error', 'th'] | False |
_search_distribution | (req_name) | Find a distribution matching the ``req_name`` in the environment.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
| Find a distribution matching the ``req_name`` in the environment. | def _search_distribution(req_name):
# type: (str) -> Optional[Distribution]
"""Find a distribution matching the ``req_name`` in the environment.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
"""
# Canonicalize... | [
"def",
"_search_distribution",
"(",
"req_name",
")",
":",
"# type: (str) -> Optional[Distribution]",
"# Canonicalize the name before searching in the list of",
"# installed distributions and also while creating the package",
"# dictionary to get the Distribution object",
"req_name",
"=",
"ca... | [
485,
0
] | [
505,
33
] | python | en | ['en', 'en', 'en'] | True |
get_distribution | (req_name) | Given a requirement name, return the installed Distribution object.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
| Given a requirement name, return the installed Distribution object. | def get_distribution(req_name):
# type: (str) -> Optional[Distribution]
"""Given a requirement name, return the installed Distribution object.
This searches from *all* distributions available in the environment, to
match the behavior of ``pkg_resources.get_distribution()``.
"""
# Search the di... | [
"def",
"get_distribution",
"(",
"req_name",
")",
":",
"# type: (str) -> Optional[Distribution]",
"# Search the distribution by looking through the working set",
"dist",
"=",
"_search_distribution",
"(",
"req_name",
")",
"# If distribution could not be found, call working_set.require",
... | [
508,
0
] | [
533,
41
] | python | en | ['en', 'en', 'en'] | True |
egg_link_path | (dist) |
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
3) in a yes-global virtualenv
try to find in site_packa... |
Return the path for the .egg-link file if it exists, otherwise, None. | def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site... | [
"def",
"egg_link_path",
"(",
"dist",
")",
":",
"# type: (Distribution) -> Optional[str]",
"sites",
"=",
"[",
"]",
"if",
"running_under_virtualenv",
"(",
")",
":",
"sites",
".",
"append",
"(",
"site_packages",
")",
"if",
"not",
"virtualenv_no_global",
"(",
")",
"... | [
536,
0
] | [
569,
15
] | python | en | ['en', 'error', 'th'] | False |
dist_location | (dist) |
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
The returned location is normalized (in particular, with symlinks... |
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. | def dist_location(dist):
# type: (Distribution) -> str
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
... | [
"def",
"dist_location",
"(",
"dist",
")",
":",
"# type: (Distribution) -> str",
"egg_link",
"=",
"egg_link_path",
"(",
"dist",
")",
"if",
"egg_link",
":",
"return",
"normalize_path",
"(",
"egg_link",
")",
"return",
"normalize_path",
"(",
"dist",
".",
"location",
... | [
572,
0
] | [
585,
40
] | python | en | ['en', 'error', 'th'] | False |
captured_output | (stream_name) | Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.
Taken from Lib/support/__init__.py in the CPython repo.
| Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO. | def captured_output(stream_name):
"""Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.
Taken from Lib/support/__init__.py in the CPython repo.
"""
orig_stdout = getattr(sys, stream_name)
setattr(sys, stream_name... | [
"def",
"captured_output",
"(",
"stream_name",
")",
":",
"orig_stdout",
"=",
"getattr",
"(",
"sys",
",",
"stream_name",
")",
"setattr",
"(",
"sys",
",",
"stream_name",
",",
"StreamWrapper",
".",
"from_stream",
"(",
"orig_stdout",
")",
")",
"try",
":",
"yield"... | [
623,
0
] | [
634,
46
] | python | en | ['en', 'en', 'en'] | True |
captured_stdout | () | Capture the output of sys.stdout:
with captured_stdout() as stdout:
print('hello')
self.assertEqual(stdout.getvalue(), 'hello\n')
Taken from Lib/support/__init__.py in the CPython repo.
| Capture the output of sys.stdout: | def captured_stdout():
"""Capture the output of sys.stdout:
with captured_stdout() as stdout:
print('hello')
self.assertEqual(stdout.getvalue(), 'hello\n')
Taken from Lib/support/__init__.py in the CPython repo.
"""
return captured_output('stdout') | [
"def",
"captured_stdout",
"(",
")",
":",
"return",
"captured_output",
"(",
"'stdout'",
")"
] | [
637,
0
] | [
646,
36
] | python | en | ['en', 'en', 'en'] | True |
captured_stderr | () |
See captured_stdout().
|
See captured_stdout().
| def captured_stderr():
"""
See captured_stdout().
"""
return captured_output('stderr') | [
"def",
"captured_stderr",
"(",
")",
":",
"return",
"captured_output",
"(",
"'stderr'",
")"
] | [
649,
0
] | [
653,
36
] | python | en | ['en', 'error', 'th'] | False |
get_installed_version | (dist_name, working_set=None) | Get the installed version of dist_name avoiding pkg_resources cache | Get the installed version of dist_name avoiding pkg_resources cache | def get_installed_version(dist_name, working_set=None):
"""Get the installed version of dist_name avoiding pkg_resources cache"""
# Create a requirement that we'll look for inside of setuptools.
req = pkg_resources.Requirement.parse(dist_name)
if working_set is None:
# We want to avoid having t... | [
"def",
"get_installed_version",
"(",
"dist_name",
",",
"working_set",
"=",
"None",
")",
":",
"# Create a requirement that we'll look for inside of setuptools.",
"req",
"=",
"pkg_resources",
".",
"Requirement",
".",
"parse",
"(",
"dist_name",
")",
"if",
"working_set",
"i... | [
656,
0
] | [
671,
41
] | python | en | ['en', 'en', 'en'] | True |
consume | (iterator) | Consume an iterable at C speed. | Consume an iterable at C speed. | def consume(iterator):
"""Consume an iterable at C speed."""
deque(iterator, maxlen=0) | [
"def",
"consume",
"(",
"iterator",
")",
":",
"deque",
"(",
"iterator",
",",
"maxlen",
"=",
"0",
")"
] | [
674,
0
] | [
676,
29
] | python | en | ['en', 'en', 'en'] | True |
build_netloc | (host, port) |
Build a netloc from a host-port pair
|
Build a netloc from a host-port pair
| def build_netloc(host, port):
# type: (str, Optional[int]) -> str
"""
Build a netloc from a host-port pair
"""
if port is None:
return host
if ':' in host:
# Only wrap host with square brackets when it is IPv6
host = '[{}]'.format(host)
return '{}:{}'.format(host, por... | [
"def",
"build_netloc",
"(",
"host",
",",
"port",
")",
":",
"# type: (str, Optional[int]) -> str",
"if",
"port",
"is",
"None",
":",
"return",
"host",
"if",
"':'",
"in",
"host",
":",
"# Only wrap host with square brackets when it is IPv6",
"host",
"=",
"'[{}]'",
".",
... | [
687,
0
] | [
697,
37
] | python | en | ['en', 'error', 'th'] | False |
build_url_from_netloc | (netloc, scheme='https') |
Build a full URL from a netloc.
|
Build a full URL from a netloc.
| def build_url_from_netloc(netloc, scheme='https'):
# type: (str, str) -> str
"""
Build a full URL from a netloc.
"""
if netloc.count(':') >= 2 and '@' not in netloc and '[' not in netloc:
# It must be a bare IPv6 address, so wrap it with brackets.
netloc = '[{}]'.format(netloc)
r... | [
"def",
"build_url_from_netloc",
"(",
"netloc",
",",
"scheme",
"=",
"'https'",
")",
":",
"# type: (str, str) -> str",
"if",
"netloc",
".",
"count",
"(",
"':'",
")",
">=",
"2",
"and",
"'@'",
"not",
"in",
"netloc",
"and",
"'['",
"not",
"in",
"netloc",
":",
... | [
700,
0
] | [
708,
43
] | python | en | ['en', 'error', 'th'] | False |
parse_netloc | (netloc) |
Return the host-port pair from a netloc.
|
Return the host-port pair from a netloc.
| def parse_netloc(netloc):
# type: (str) -> Tuple[str, Optional[int]]
"""
Return the host-port pair from a netloc.
"""
url = build_url_from_netloc(netloc)
parsed = urllib_parse.urlparse(url)
return parsed.hostname, parsed.port | [
"def",
"parse_netloc",
"(",
"netloc",
")",
":",
"# type: (str) -> Tuple[str, Optional[int]]",
"url",
"=",
"build_url_from_netloc",
"(",
"netloc",
")",
"parsed",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"url",
")",
"return",
"parsed",
".",
"hostname",
",",
"parse... | [
711,
0
] | [
718,
39
] | python | en | ['en', 'error', 'th'] | False |
split_auth_from_netloc | (netloc) |
Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)).
|
Parse out and remove the auth information from a netloc. | def split_auth_from_netloc(netloc):
"""
Parse out and remove the auth information from a netloc.
Returns: (netloc, (username, password)).
"""
if '@' not in netloc:
return netloc, (None, None)
# Split from the right because that's how urllib.parse.urlsplit()
# behaves if more than o... | [
"def",
"split_auth_from_netloc",
"(",
"netloc",
")",
":",
"if",
"'@'",
"not",
"in",
"netloc",
":",
"return",
"netloc",
",",
"(",
"None",
",",
"None",
")",
"# Split from the right because that's how urllib.parse.urlsplit()",
"# behaves if more than one @ is present (which ca... | [
721,
0
] | [
746,
28
] | python | en | ['en', 'error', 'th'] | False |
redact_netloc | (netloc) |
Replace the sensitive data in a netloc with "****", if it exists.
For example:
- "user:pass@example.com" returns "user:****@example.com"
- "accesstoken@example.com" returns "****@example.com"
|
Replace the sensitive data in a netloc with "****", if it exists. | def redact_netloc(netloc):
# type: (str) -> str
"""
Replace the sensitive data in a netloc with "****", if it exists.
For example:
- "user:pass@example.com" returns "user:****@example.com"
- "accesstoken@example.com" returns "****@example.com"
"""
netloc, (user, password) = spli... | [
"def",
"redact_netloc",
"(",
"netloc",
")",
":",
"# type: (str) -> str",
"netloc",
",",
"(",
"user",
",",
"password",
")",
"=",
"split_auth_from_netloc",
"(",
"netloc",
")",
"if",
"user",
"is",
"None",
":",
"return",
"netloc",
"if",
"password",
"is",
"None",... | [
749,
0
] | [
769,
60
] | python | en | ['en', 'error', 'th'] | False |
_transform_url | (url, transform_netloc) | Transform and replace netloc in a url.
transform_netloc is a function taking the netloc and returning a
tuple. The first element of this tuple is the new netloc. The
entire tuple is returned.
Returns a tuple containing the transformed url as item 0 and the
original tuple returned by transform_netl... | Transform and replace netloc in a url. | def _transform_url(url, transform_netloc):
"""Transform and replace netloc in a url.
transform_netloc is a function taking the netloc and returning a
tuple. The first element of this tuple is the new netloc. The
entire tuple is returned.
Returns a tuple containing the transformed url as item 0 and... | [
"def",
"_transform_url",
"(",
"url",
",",
"transform_netloc",
")",
":",
"purl",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"netloc_tuple",
"=",
"transform_netloc",
"(",
"purl",
".",
"netloc",
")",
"# stripped url",
"url_pieces",
"=",
"(",
"purl",
... | [
772,
0
] | [
789,
29
] | python | en | ['en', 'en', 'en'] | True |
split_auth_netloc_from_url | (url) |
Parse a url into separate netloc, auth, and url with no auth.
Returns: (url_without_auth, netloc, (username, password))
|
Parse a url into separate netloc, auth, and url with no auth. | def split_auth_netloc_from_url(url):
# type: (str) -> Tuple[str, str, Tuple[str, str]]
"""
Parse a url into separate netloc, auth, and url with no auth.
Returns: (url_without_auth, netloc, (username, password))
"""
url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
return u... | [
"def",
"split_auth_netloc_from_url",
"(",
"url",
")",
":",
"# type: (str) -> Tuple[str, str, Tuple[str, str]]",
"url_without_auth",
",",
"(",
"netloc",
",",
"auth",
")",
"=",
"_transform_url",
"(",
"url",
",",
"_get_netloc",
")",
"return",
"url_without_auth",
",",
"ne... | [
800,
0
] | [
808,
41
] | python | en | ['en', 'error', 'th'] | False |
remove_auth_from_url | (url) | Return a copy of url with 'username:password@' removed. | Return a copy of url with 'username:password | def remove_auth_from_url(url):
# type: (str) -> str
"""Return a copy of url with 'username:password@' removed."""
# username/pass params are passed to subversion through flags
# and are not recognized in the url.
return _transform_url(url, _get_netloc)[0] | [
"def",
"remove_auth_from_url",
"(",
"url",
")",
":",
"# type: (str) -> str",
"# username/pass params are passed to subversion through flags",
"# and are not recognized in the url.",
"return",
"_transform_url",
"(",
"url",
",",
"_get_netloc",
")",
"[",
"0",
"]"
] | [
811,
0
] | [
816,
46
] | python | en | ['en', 'en', 'en'] | True |
redact_auth_from_url | (url) | Replace the password in a given url with ****. | Replace the password in a given url with ****. | def redact_auth_from_url(url):
# type: (str) -> str
"""Replace the password in a given url with ****."""
return _transform_url(url, _redact_netloc)[0] | [
"def",
"redact_auth_from_url",
"(",
"url",
")",
":",
"# type: (str) -> str",
"return",
"_transform_url",
"(",
"url",
",",
"_redact_netloc",
")",
"[",
"0",
"]"
] | [
819,
0
] | [
822,
49
] | python | en | ['en', 'en', 'en'] | True |
protect_pip_from_modification_on_windows | (modifying_pip) | Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ...
| Protection of pip.exe from modification on Windows | def protect_pip_from_modification_on_windows(modifying_pip):
# type: (bool) -> None
"""Protection of pip.exe from modification on Windows
On Windows, any operation modifying pip should be run as:
python -m pip ...
"""
pip_names = [
"pip.exe",
"pip{}.exe".format(sys.version_i... | [
"def",
"protect_pip_from_modification_on_windows",
"(",
"modifying_pip",
")",
":",
"# type: (bool) -> None",
"pip_names",
"=",
"[",
"\"pip.exe\"",
",",
"\"pip{}.exe\"",
".",
"format",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
",",
"\"pip{}.{}.exe\"",
".",... | [
871,
0
] | [
898,
9
] | python | en | ['en', 'en', 'en'] | True |
is_console_interactive | () | Is this console interactive?
| Is this console interactive?
| def is_console_interactive():
# type: () -> bool
"""Is this console interactive?
"""
return sys.stdin is not None and sys.stdin.isatty() | [
"def",
"is_console_interactive",
"(",
")",
":",
"# type: () -> bool",
"return",
"sys",
".",
"stdin",
"is",
"not",
"None",
"and",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")"
] | [
901,
0
] | [
905,
55
] | python | en | ['en', 'en', 'en'] | True |
hash_file | (path, blocksize=1 << 20) | Return (hash, length) for path using hashlib.sha256()
| Return (hash, length) for path using hashlib.sha256()
| def hash_file(path, blocksize=1 << 20):
# type: (Text, int) -> Tuple[Any, int]
"""Return (hash, length) for path using hashlib.sha256()
"""
h = hashlib.sha256()
length = 0
with open(path, 'rb') as f:
for block in read_chunks(f, size=blocksize):
length += len(block)
... | [
"def",
"hash_file",
"(",
"path",
",",
"blocksize",
"=",
"1",
"<<",
"20",
")",
":",
"# type: (Text, int) -> Tuple[Any, int]",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"length",
"=",
"0",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"f",
":"... | [
908,
0
] | [
919,
20
] | python | en | ['en', 'hi-Latn', 'en'] | True |
is_wheel_installed | () |
Return whether the wheel package is installed.
|
Return whether the wheel package is installed.
| def is_wheel_installed():
"""
Return whether the wheel package is installed.
"""
try:
import wheel # noqa: F401
except ImportError:
return False
return True | [
"def",
"is_wheel_installed",
"(",
")",
":",
"try",
":",
"import",
"wheel",
"# noqa: F401",
"except",
"ImportError",
":",
"return",
"False",
"return",
"True"
] | [
922,
0
] | [
931,
15
] | python | en | ['en', 'error', 'th'] | False |
pairwise | (iterable) |
Return paired elements.
For example:
s -> (s0, s1), (s2, s3), (s4, s5), ...
|
Return paired elements. | def pairwise(iterable):
# type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]
"""
Return paired elements.
For example:
s -> (s0, s1), (s2, s3), (s4, s5), ...
"""
iterable = iter(iterable)
return zip_longest(iterable, iterable) | [
"def",
"pairwise",
"(",
"iterable",
")",
":",
"# type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"return",
"zip_longest",
"(",
"iterable",
",",
"iterable",
")"
] | [
934,
0
] | [
943,
42
] | python | en | ['en', 'error', 'th'] | False |
partition | (
pred, # type: Callable[[T], bool]
iterable, # type: Iterable[T]
) |
Use a predicate to partition entries into false entries and true entries,
like
partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
|
Use a predicate to partition entries into false entries and true entries,
like | def partition(
pred, # type: Callable[[T], bool]
iterable, # type: Iterable[T]
):
# type: (...) -> Tuple[Iterable[T], Iterable[T]]
"""
Use a predicate to partition entries into false entries and true entries,
like
partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
"""
... | [
"def",
"partition",
"(",
"pred",
",",
"# type: Callable[[T], bool]",
"iterable",
",",
"# type: Iterable[T]",
")",
":",
"# type: (...) -> Tuple[Iterable[T], Iterable[T]]",
"t1",
",",
"t2",
"=",
"tee",
"(",
"iterable",
")",
"return",
"filterfalse",
"(",
"pred",
",",
"... | [
946,
0
] | [
958,
50
] | python | en | ['en', 'error', 'th'] | False |
_get_gid | (name) | Returns a gid, given a group name. | Returns a gid, given a group name. | def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | [
"def",
"_get_gid",
"(",
"name",
")",
":",
"if",
"getgrnam",
"is",
"None",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"try",
":",
"result",
"=",
"getgrnam",
"(",
"name",
")",
"except",
"KeyError",
":",
"result",
"=",
"None",
"if",
"result",
"i... | [
30,
0
] | [
40,
15
] | python | en | ['en', 'en', 'en'] | True |
_get_uid | (name) | Returns an uid, given a user name. | Returns an uid, given a user name. | def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None | [
"def",
"_get_uid",
"(",
"name",
")",
":",
"if",
"getpwnam",
"is",
"None",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"try",
":",
"result",
"=",
"getpwnam",
"(",
"name",
")",
"except",
"KeyError",
":",
"result",
"=",
"None",
"if",
"result",
"i... | [
42,
0
] | [
52,
15
] | python | en | ['en', 'en', 'en'] | True |
make_tarball | (base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None) | Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", "xz", "compress", or
None. ("compress" will be deprecated in Python 3.2)
'owner' and 'group' can be used to define an owner and a group for the
archive that is being buil... | Create a (possibly compressed) tar file from all the files under
'base_dir'. | def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", "xz", "compress", or
None. ("compress" will be deprec... | [
"def",
"make_tarball",
"(",
"base_name",
",",
"base_dir",
",",
"compress",
"=",
"\"gzip\"",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"owner",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"tar_compression",
"=",
"{",
"'gzip'",
":",
... | [
54,
0
] | [
124,
23
] | python | en | ['en', 'en', 'en'] | True |
make_zipfile | (base_name, base_dir, verbose=0, dry_run=0) | Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises DistutilsExecErr... | Create a zip file from all the files under 'base_dir'. | def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default sear... | [
"def",
"make_zipfile",
"(",
"base_name",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
")",
":",
"zip_filename",
"=",
"base_name",
"+",
"\".zip\"",
"mkpath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"zip_filename",
")",
",",
... | [
126,
0
] | [
184,
23
] | python | en | ['en', 'en', 'en'] | True |
check_archive_formats | (formats) | Returns the first format from the 'format' list that is unknown.
If all formats are known, returns None
| Returns the first format from the 'format' list that is unknown. | def check_archive_formats(formats):
"""Returns the first format from the 'format' list that is unknown.
If all formats are known, returns None
"""
for format in formats:
if format not in ARCHIVE_FORMATS:
return format
return None | [
"def",
"check_archive_formats",
"(",
"formats",
")",
":",
"for",
"format",
"in",
"formats",
":",
"if",
"format",
"not",
"in",
"ARCHIVE_FORMATS",
":",
"return",
"format",
"return",
"None"
] | [
195,
0
] | [
203,
15
] | python | en | ['en', 'en', 'en'] | True |
make_archive | (base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None) | Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "gztar",
"bztar", "xztar", or "ztar".
'root_dir' is a directory that will be the root directory of the
archive; ie. we t... | Create an archive file (eg. zip or tar). | def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "ta... | [
"def",
"make_archive",
"(",
"base_name",
",",
"format",
",",
"root_dir",
"=",
"None",
",",
"base_dir",
"=",
"None",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"owner",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"save_cwd",
"=",
... | [
205,
0
] | [
255,
19
] | python | en | ['en', 'gd', 'en'] | True |
Breadcrumb.render | (self) | Renders the table using the template from the table options. | Renders the table using the template from the table options. | def render(self):
"""Renders the table using the template from the table options."""
breadcrumb_template = template.loader.get_template(self.template)
extra_context = {"breadcrumb": self}
return breadcrumb_template.render(extra_context, self.request) | [
"def",
"render",
"(",
"self",
")",
":",
"breadcrumb_template",
"=",
"template",
".",
"loader",
".",
"get_template",
"(",
"self",
".",
"template",
")",
"extra_context",
"=",
"{",
"\"breadcrumb\"",
":",
"self",
"}",
"return",
"breadcrumb_template",
".",
"render"... | [
40,
4
] | [
44,
70
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.__init__ | (self,
X,
y,
output_directory,
feature_descriptions_dict=None,
already_transformed_columns=None,
classification_pos_label=None,
force_classification_pos_label_multiclass=False,
random_... | Create Dashboard object.
Provided X and y are checked and converted to pandas object for easier analysis and eventually split and
transformed. classification_pos_label is checked if the label is present in y target variable. X is assessed
for the number of features and appropriate flags are set... | Create Dashboard object. | def __init__(self,
X,
y,
output_directory,
feature_descriptions_dict=None,
already_transformed_columns=None,
classification_pos_label=None,
force_classification_pos_label_multiclass=False,
... | [
"def",
"__init__",
"(",
"self",
",",
"X",
",",
"y",
",",
"output_directory",
",",
"feature_descriptions_dict",
"=",
"None",
",",
"already_transformed_columns",
"=",
"None",
",",
"classification_pos_label",
"=",
"None",
",",
"force_classification_pos_label_multiclass",
... | [
66,
4
] | [
161,
43
] | python | en | ['en', 'ha', 'en'] | True |
Dashboard.create_dashboard | (self,
models=None,
scoring=None,
mode="quick",
logging=True,
disable_pairplots=False,
force_pairplot=False
) | Create several Views (Subpages) and join them together to form an interactive WebPage/Dashboard.
Models can be:
- list of initialized models
- dict of 'Model Class': param_grid of a given model to do the GridSearch on
- None - default Models collection will be used
... | Create several Views (Subpages) and join them together to form an interactive WebPage/Dashboard. | def create_dashboard(self,
models=None,
scoring=None,
mode="quick",
logging=True,
disable_pairplots=False,
force_pairplot=False
):
"""Cre... | [
"def",
"create_dashboard",
"(",
"self",
",",
"models",
"=",
"None",
",",
"scoring",
"=",
"None",
",",
"mode",
"=",
"\"quick\"",
",",
"logging",
"=",
"True",
",",
"disable_pairplots",
"=",
"False",
",",
"force_pairplot",
"=",
"False",
")",
":",
"clf",
"="... | [
163,
4
] | [
229,
56
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.search_and_fit | (self, models=None, scoring=None, mode="quick") | Search for the best scoring Model, fit it with all data and return it.
Models can be:
- list of initialized models
- dict of 'Model Class': param_grid of a given model to do the GridSearch on
- None - default Models collection will be used
scoring should be a sklearn scoring fu... | Search for the best scoring Model, fit it with all data and return it. | def search_and_fit(self, models=None, scoring=None, mode="quick"):
"""Search for the best scoring Model, fit it with all data and return it.
Models can be:
- list of initialized models
- dict of 'Model Class': param_grid of a given model to do the GridSearch on
- None - default ... | [
"def",
"search_and_fit",
"(",
"self",
",",
"models",
"=",
"None",
",",
"scoring",
"=",
"None",
",",
"mode",
"=",
"\"quick\"",
")",
":",
"if",
"scoring",
"is",
"None",
":",
"scoring",
"=",
"self",
".",
"model_finder",
".",
"default_scoring",
"clf",
"=",
... | [
231,
4
] | [
263,
18
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.set_and_fit | (self, model) | Set provided Model as a best scoring Model and fit it to all X and y data.
Args:
model (sklearn.Model): instance of ML Model
| Set provided Model as a best scoring Model and fit it to all X and y data. | def set_and_fit(self, model):
"""Set provided Model as a best scoring Model and fit it to all X and y data.
Args:
model (sklearn.Model): instance of ML Model
"""
self.model_finder.set_model_and_fit(model) | [
"def",
"set_and_fit",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"model_finder",
".",
"set_model_and_fit",
"(",
"model",
")"
] | [
265,
4
] | [
271,
50
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.transform | (self, X) | Transform provided X data with Transformer.
Returns:
numpy.ndarray, scipy.csr_matrix: transformed X
| Transform provided X data with Transformer. | def transform(self, X):
"""Transform provided X data with Transformer.
Returns:
numpy.ndarray, scipy.csr_matrix: transformed X
"""
return self.transformer.transform(X) | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"return",
"self",
".",
"transformer",
".",
"transform",
"(",
"X",
")"
] | [
273,
4
] | [
279,
44
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.predict | (self, transformed_X) | Predict target from provided X with the best scoring Model.
Args:
transformed_X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): transformed X feature space to predict
target variable from
Returns:
numpy.ndarray: predicted y target variable
| Predict target from provided X with the best scoring Model. | def predict(self, transformed_X):
"""Predict target from provided X with the best scoring Model.
Args:
transformed_X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): transformed X feature space to predict
target variable from
Returns:
numpy.ndarray... | [
"def",
"predict",
"(",
"self",
",",
"transformed_X",
")",
":",
"output",
"=",
"self",
".",
"model_finder",
".",
"predict",
"(",
"transformed_X",
")",
"return",
"output"
] | [
281,
4
] | [
292,
21
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.transform_predict | (self, X) | Transform and then predict X data.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): X data
Returns:
numpy.ndarray: predicted y target variable
| Transform and then predict X data. | def transform_predict(self, X):
"""Transform and then predict X data.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): X data
Returns:
numpy.ndarray: predicted y target variable
"""
transformed = self.transform(X)
return self.predi... | [
"def",
"transform_predict",
"(",
"self",
",",
"X",
")",
":",
"transformed",
"=",
"self",
".",
"transform",
"(",
"X",
")",
"return",
"self",
".",
"predict",
"(",
"transformed",
")"
] | [
294,
4
] | [
304,
40
] | python | en | ['en', 'it', 'en'] | True |
Dashboard.best_model | (self) | Return best (chosen) Model used in predictions.
Returns:
sklearn.Model: best scoring Model
| Return best (chosen) Model used in predictions. | def best_model(self):
"""Return best (chosen) Model used in predictions.
Returns:
sklearn.Model: best scoring Model
"""
return self.model_finder.best_model() | [
"def",
"best_model",
"(",
"self",
")",
":",
"return",
"self",
".",
"model_finder",
".",
"best_model",
"(",
")"
] | [
306,
4
] | [
312,
45
] | python | en | ['en', 'af', 'en'] | True |
Dashboard.set_custom_transformers | (self, categorical_transformers=None, numerical_transformers=None, y_transformer=None) | Set custom Transformers to be used in the problem pipeline.
Provided arguments should be a list of Transformers to be used with given type of features. Only one type
of transformers can be provided.
Transformers are updated in both transformer and transformer_eval instances. ModelFinder and Ou... | Set custom Transformers to be used in the problem pipeline. | def set_custom_transformers(self, categorical_transformers=None, numerical_transformers=None, y_transformer=None):
"""Set custom Transformers to be used in the problem pipeline.
Provided arguments should be a list of Transformers to be used with given type of features. Only one type
of transfor... | [
"def",
"set_custom_transformers",
"(",
"self",
",",
"categorical_transformers",
"=",
"None",
",",
"numerical_transformers",
"=",
"None",
",",
"y_transformer",
"=",
"None",
")",
":",
"for",
"tr",
"in",
"[",
"self",
".",
"transformer",
",",
"self",
".",
"transfo... | [
314,
4
] | [
337,
43
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._do_transformations | (self) | Fit transformer_eval to train data, transform train/test splits; fit transformer to all data, transform
all data.
transformed_X and transformed_y attributes are populated with transformed X and y data.
| Fit transformer_eval to train data, transform train/test splits; fit transformer to all data, transform
all data. | def _do_transformations(self):
"""Fit transformer_eval to train data, transform train/test splits; fit transformer to all data, transform
all data.
transformed_X and transformed_y attributes are populated with transformed X and y data.
"""
self._fit_transform_test_splits()
... | [
"def",
"_do_transformations",
"(",
"self",
")",
":",
"self",
".",
"_fit_transform_test_splits",
"(",
")",
"self",
".",
"_fit_transformer",
"(",
")",
"self",
".",
"transformed_X",
"=",
"self",
".",
"transformer",
".",
"transform",
"(",
"self",
".",
"X",
")",
... | [
339,
4
] | [
348,
65
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._initialize_model_and_output | (self) | Create ModelFinder and Output objects and assign them to model_finder and output attributes appropriately. | Create ModelFinder and Output objects and assign them to model_finder and output attributes appropriately. | def _initialize_model_and_output(self):
"""Create ModelFinder and Output objects and assign them to model_finder and output attributes appropriately."""
self.model_finder = ModelFinder(
X=self.transformed_X,
y=self.transformed_y,
X_train=self.transformed_X_train,
... | [
"def",
"_initialize_model_and_output",
"(",
"self",
")",
":",
"self",
".",
"model_finder",
"=",
"ModelFinder",
"(",
"X",
"=",
"self",
".",
"transformed_X",
",",
"y",
"=",
"self",
".",
"transformed_y",
",",
"X_train",
"=",
"self",
".",
"transformed_X_train",
... | [
350,
4
] | [
380,
9
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._create_test_splits | (self) | Create train/test splits from X and y data.
X_train, X_test, y_train and y_test attributes are populated with the appropriate splits.
Note:
Every split DataFrame has its index reset and the old index dropped just so there is consistency between
train and test splits.
| Create train/test splits from X and y data. | def _create_test_splits(self):
"""Create train/test splits from X and y data.
X_train, X_test, y_train and y_test attributes are populated with the appropriate splits.
Note:
Every split DataFrame has its index reset and the old index dropped just so there is consistency between
... | [
"def",
"_create_test_splits",
"(",
"self",
")",
":",
"X_train",
",",
"X_test",
",",
"y_train",
",",
"y_test",
"=",
"train_test_split",
"(",
"self",
".",
"X",
",",
"self",
".",
"y",
",",
"random_state",
"=",
"self",
".",
"random_state",
")",
"# resetting in... | [
382,
4
] | [
399,
69
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._fit_transform_test_splits | (self) | Fit transformer_eval with train splits and transform both train and test splits.
Splits to be used are in X_train, X_test, y_train and y_test attributes. Created transformed splits are put
in transformed_X_train, transformed_X_test, transformed_y_train and transformed_y_test attributes.
| Fit transformer_eval with train splits and transform both train and test splits. | def _fit_transform_test_splits(self):
"""Fit transformer_eval with train splits and transform both train and test splits.
Splits to be used are in X_train, X_test, y_train and y_test attributes. Created transformed splits are put
in transformed_X_train, transformed_X_test, transformed_y_train a... | [
"def",
"_fit_transform_test_splits",
"(",
"self",
")",
":",
"# fitting only on train data",
"self",
".",
"transformer_eval",
".",
"fit",
"(",
"self",
".",
"X_train",
")",
"self",
".",
"transformer_eval",
".",
"fit_y",
"(",
"self",
".",
"y_train",
")",
"t",
"="... | [
401,
4
] | [
418,
112
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._fit_transformer | (self, X=None, y=None) | Fit transformer with provided data.
If provided X or y are None, appropriate X or y attributes are used.
transformer is fit for both X and y.
| Fit transformer with provided data. | def _fit_transformer(self, X=None, y=None):
"""Fit transformer with provided data.
If provided X or y are None, appropriate X or y attributes are used.
transformer is fit for both X and y.
"""
if X is None:
X = self.X
if y is None:
y = self.y
... | [
"def",
"_fit_transformer",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"if",
"X",
"is",
"None",
":",
"X",
"=",
"self",
".",
"X",
"if",
"y",
"is",
"None",
":",
"y",
"=",
"self",
".",
"y",
"self",
".",
"transformer",
".... | [
420,
4
] | [
433,
33
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._check_provided_data | (self, X, y) | Convert X and y to pandas object and change their column names to be JS friendly.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): X data
y (pd.Series, numpy.ndarray): target variable
Returns:
tuple: (converted X, converted y)
| Convert X and y to pandas object and change their column names to be JS friendly. | def _check_provided_data(self, X, y):
"""Convert X and y to pandas object and change their column names to be JS friendly.
Args:
X (pandas.DataFrame, numpy.ndarray, scipy.csr_matrix): X data
y (pd.Series, numpy.ndarray): target variable
Returns:
tuple: (conv... | [
"def",
"_check_provided_data",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"new_X",
"=",
"make_pandas_data",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
"new_y",
"=",
"make_pandas_data",
"(",
"y",
",",
"pd",
".",
"Series",
")",
"new_X",
".",
"columns",
... | [
435,
4
] | [
451,
27
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._check_classification_pos_label | (self, label) | Check if label is in unique target variable values.
Label is returned if it's in unique values and problem type is classification. If the problem is multiclass,
then _force_classification_pos_label_multiclass_flag attribute is checked - if the flag is False, label is
changed to None (as it woul... | Check if label is in unique target variable values. | def _check_classification_pos_label(self, label):
"""Check if label is in unique target variable values.
Label is returned if it's in unique values and problem type is classification. If the problem is multiclass,
then _force_classification_pos_label_multiclass_flag attribute is checked - if th... | [
"def",
"_check_classification_pos_label",
"(",
"self",
",",
"label",
")",
":",
"unique",
"=",
"set",
"(",
"np",
".",
"unique",
"(",
"self",
".",
"y",
")",
")",
"if",
"label",
"not",
"in",
"unique",
":",
"raise",
"ValueError",
"(",
"\"label '{label}' not in... | [
453,
4
] | [
481,
24
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._assess_n_features | (self, df) | Check number of features in df and set _create_pairplots_flag accordingly.
If the number of features is more than _n_features_pairplots_limit class attribute, then _create_pairplots_flag
is set to False (to prevent long creation time and/or MemoryError in case of huge feature space).
Args:
... | Check number of features in df and set _create_pairplots_flag accordingly. | def _assess_n_features(self, df):
"""Check number of features in df and set _create_pairplots_flag accordingly.
If the number of features is more than _n_features_pairplots_limit class attribute, then _create_pairplots_flag
is set to False (to prevent long creation time and/or MemoryError in ca... | [
"def",
"_assess_n_features",
"(",
"self",
",",
"df",
")",
":",
"n",
"=",
"df",
".",
"shape",
"[",
"1",
"]",
"if",
"n",
">",
"self",
".",
"_n_features_pairplots_limit",
":",
"self",
".",
"_create_pairplots_flag",
"=",
"False",
"warnings",
".",
"warn",
"("... | [
483,
4
] | [
498,
52
] | python | en | ['en', 'en', 'en'] | True |
Dashboard._check_transformed_cols | (self, transformed_columns) | Check list of transformed columns if every column name is in X features names.
If transformed_columns is a proper subset of X columns, then sorted list of unique transformed columns is
returned. Otherwise, ValueError is raised.
If transformed_columns is None, then empty list is returned.
... | Check list of transformed columns if every column name is in X features names. | def _check_transformed_cols(self, transformed_columns):
"""Check list of transformed columns if every column name is in X features names.
If transformed_columns is a proper subset of X columns, then sorted list of unique transformed columns is
returned. Otherwise, ValueError is raised.
... | [
"def",
"_check_transformed_cols",
"(",
"self",
",",
"transformed_columns",
")",
":",
"if",
"transformed_columns",
"is",
"not",
"None",
":",
"transformed_columns",
"=",
"sanitize_input",
"(",
"transformed_columns",
")",
"cols_in_data",
"=",
"set",
"(",
"self",
".",
... | [
500,
4
] | [
535,
21
] | python | en | ['en', 'en', 'en'] | True |
extract_cookies_to_jar | (jar, request, response) | Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
| Extract the cookies from the response into a CookieJar. | def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(r... | [
"def",
"extract_cookies_to_jar",
"(",
"jar",
",",
"request",
",",
"response",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"response",
",",
"'_original_response'",
")",
"and",
"response",
".",
"_original_response",
")",
":",
"return",
"# the _original_response fiel... | [
117,
0
] | [
131,
33
] | python | en | ['en', 'en', 'en'] | True |
get_cookie_header | (jar, request) |
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
|
Produce an appropriate Cookie header string to be sent with `request`, or None. | def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie') | [
"def",
"get_cookie_header",
"(",
"jar",
",",
"request",
")",
":",
"r",
"=",
"MockRequest",
"(",
"request",
")",
"jar",
".",
"add_cookie_header",
"(",
"r",
")",
"return",
"r",
".",
"get_new_headers",
"(",
")",
".",
"get",
"(",
"'Cookie'",
")"
] | [
134,
0
] | [
142,
44
] | python | en | ['en', 'error', 'th'] | False |
remove_cookie_by_name | (cookiejar, name, domain=None, path=None) | Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
| Unsets a cookie by name, by default over all domains and paths. | def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None an... | [
"def",
"remove_cookie_by_name",
"(",
"cookiejar",
",",
"name",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"clearables",
"=",
"[",
"]",
"for",
"cookie",
"in",
"cookiejar",
":",
"if",
"cookie",
".",
"name",
"!=",
"name",
":",
"contin... | [
145,
0
] | [
161,
43
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.