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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
TransresnetMultimodalModel._build_context_encoder | (self) |
Build the context (i.e. dialogue history) encoder.
|
Build the context (i.e. dialogue history) encoder.
| def _build_context_encoder(self):
"""
Build the context (i.e. dialogue history) encoder.
"""
if self.opt.get("share_encoder"):
self.context_encoder = self.label_encoder
else:
if (
self.opt["load_context_encoder_from"] is None
... | [
"def",
"_build_context_encoder",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
".",
"get",
"(",
"\"share_encoder\"",
")",
":",
"self",
".",
"context_encoder",
"=",
"self",
".",
"label_encoder",
"else",
":",
"if",
"(",
"self",
".",
"opt",
"[",
"\"load_... | [
159,
4
] | [
196,
50
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.forward | (
self,
image_features,
personalities,
dialogue_histories,
labels,
batchsize=None,
personalities_tensor=None,
) |
Model forward pass.
:param image_features:
list of tensors of image features, one per example
:param personalities:
list of personalities, one per example
:param dialogue_histories:
list of dialogue histories, one per example
:param labels:
... |
Model forward pass. | def forward(
self,
image_features,
personalities,
dialogue_histories,
labels,
batchsize=None,
personalities_tensor=None,
):
"""
Model forward pass.
:param image_features:
list of tensors of image features, one per example
... | [
"def",
"forward",
"(",
"self",
",",
"image_features",
",",
"personalities",
",",
"dialogue_histories",
",",
"labels",
",",
"batchsize",
"=",
"None",
",",
"personalities_tensor",
"=",
"None",
",",
")",
":",
"# labels",
"labels_encoded",
"=",
"self",
".",
"forwa... | [
198,
4
] | [
240,
41
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.forward_personality | (self, personalities, personalities_tensor) |
Encode personalities.
:param personalities:
list of personalities, one per example
:param personalities_tensor:
(optional) list of personality representations, usually a one-hot
vector if specified
:return:
encoded representation of the ... |
Encode personalities. | def forward_personality(self, personalities, personalities_tensor):
"""
Encode personalities.
:param personalities:
list of personalities, one per example
:param personalities_tensor:
(optional) list of personality representations, usually a one-hot
v... | [
"def",
"forward_personality",
"(",
"self",
",",
"personalities",
",",
"personalities_tensor",
")",
":",
"pers_encoded",
"=",
"None",
"if",
"not",
"self",
".",
"encode_personality",
":",
"if",
"self",
".",
"multimodal",
"and",
"self",
".",
"multimodal_combo",
"==... | [
242,
4
] | [
263,
27
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.forward_text_encoder | (self, texts, dialogue_history=False, batchsize=None) |
Forward pass for a text encoder.
:param texts:
text to encode
:param dialogue_history:
flag that indicates whether the text is dialogue history; if False,
text is a response candidate
:param batchsize:
size of the batch
:return:
... |
Forward pass for a text encoder. | def forward_text_encoder(self, texts, dialogue_history=False, batchsize=None):
"""
Forward pass for a text encoder.
:param texts:
text to encode
:param dialogue_history:
flag that indicates whether the text is dialogue history; if False,
text is a res... | [
"def",
"forward_text_encoder",
"(",
"self",
",",
"texts",
",",
"dialogue_history",
"=",
"False",
",",
"batchsize",
"=",
"None",
")",
":",
"texts_encoded",
"=",
"None",
"if",
"texts",
"is",
"None",
"or",
"(",
"dialogue_history",
"and",
"not",
"self",
".",
"... | [
265,
4
] | [
298,
28
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.forward_image | (self, image_features) |
Encode image features.
:param image_features:
list of image features
:return:
encoded representation of the image features
|
Encode image features. | def forward_image(self, image_features):
"""
Encode image features.
:param image_features:
list of image features
:return:
encoded representation of the image features
"""
img_encoded = None
if image_features is None or not self.encode_im... | [
"def",
"forward_image",
"(",
"self",
",",
"image_features",
")",
":",
"img_encoded",
"=",
"None",
"if",
"image_features",
"is",
"None",
"or",
"not",
"self",
".",
"encode_image",
":",
"if",
"self",
".",
"multimodal",
"and",
"self",
".",
"multimodal_combo",
"=... | [
300,
4
] | [
317,
26
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.get_rep | (self, encodings, batchsize=None) |
Get the multimodal representation of the encodings.
:param encodings:
list of encodings
:param batchsize:
size of batch
:return:
final multimodal representations
|
Get the multimodal representation of the encodings. | def get_rep(self, encodings, batchsize=None):
"""
Get the multimodal representation of the encodings.
:param encodings:
list of encodings
:param batchsize:
size of batch
:return:
final multimodal representations
"""
if not sel... | [
"def",
"get_rep",
"(",
"self",
",",
"encodings",
",",
"batchsize",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"multimodal",
":",
"rep",
"=",
"self",
".",
"sum_encodings",
"(",
"encodings",
")",
"else",
":",
"if",
"self",
".",
"multimodal_combo",
... | [
319,
4
] | [
344,
18
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.choose_best_response | (
self,
image_features,
personalities,
dialogue_histories,
candidates,
candidates_encoded=None,
k=1,
batchsize=None,
) |
Choose the best response for each example.
:param image_features:
list of tensors of image features
:param personalities:
list of personalities
:param dialogue_histories:
list of dialogue histories, one per example
:param candidates:
... |
Choose the best response for each example. | def choose_best_response(
self,
image_features,
personalities,
dialogue_histories,
candidates,
candidates_encoded=None,
k=1,
batchsize=None,
):
"""
Choose the best response for each example.
:param image_features:
l... | [
"def",
"choose_best_response",
"(",
"self",
",",
"image_features",
",",
"personalities",
",",
"dialogue_histories",
",",
"candidates",
",",
"candidates_encoded",
"=",
"None",
",",
"k",
"=",
"1",
",",
"batchsize",
"=",
"None",
",",
")",
":",
"self",
".",
"eva... | [
346,
4
] | [
399,
21
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.choose_topk | (
self, idx, encoded, candidates, candidates_encoded, one_cand_set, k
) |
Choose top k best responses for a single example.
:param idx:
idx of example in encoded
:param encoded:
full matrix of encoded representations (for the whole batch)
:param candidates:
list of candidates
:param candidates_encoded:
... |
Choose top k best responses for a single example. | def choose_topk(
self, idx, encoded, candidates, candidates_encoded, one_cand_set, k
):
"""
Choose top k best responses for a single example.
:param idx:
idx of example in encoded
:param encoded:
full matrix of encoded representations (for the whole b... | [
"def",
"choose_topk",
"(",
"self",
",",
"idx",
",",
"encoded",
",",
"candidates",
",",
"candidates_encoded",
",",
"one_cand_set",
",",
"k",
")",
":",
"encoding",
"=",
"encoded",
"[",
"idx",
":",
"idx",
"+",
"1",
",",
":",
"]",
"scores",
"=",
"torch",
... | [
401,
4
] | [
435,
9
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.get_loss | (self, total_encoded, labels_encoded) |
Compute loss over batch.
:param total_encoded:
encoding of the examples
:param labels_encoded:
encoding of the labels
:return:
total batch loss, and number of correct examples
|
Compute loss over batch. | def get_loss(self, total_encoded, labels_encoded):
"""
Compute loss over batch.
:param total_encoded:
encoding of the examples
:param labels_encoded:
encoding of the labels
:return:
total batch loss, and number of correct examples
"""... | [
"def",
"get_loss",
"(",
"self",
",",
"total_encoded",
",",
"labels_encoded",
")",
":",
"loss",
"=",
"None",
"num_correct",
"=",
"None",
"if",
"labels_encoded",
"is",
"not",
"None",
":",
"dot_products",
"=",
"total_encoded",
".",
"mm",
"(",
"labels_encoded",
... | [
437,
4
] | [
461,
32
] | python | en | ['en', 'error', 'th'] | False |
TransresnetMultimodalModel.cat_encodings | (self, tensors) |
Concatenate non-`None` encodings.
:param tensors:
list tensors to concatenate
:return:
concatenated tensors
|
Concatenate non-`None` encodings. | def cat_encodings(self, tensors):
"""
Concatenate non-`None` encodings.
:param tensors:
list tensors to concatenate
:return:
concatenated tensors
"""
tensors = [t for t in tensors if t is not None]
return torch.cat([t.unsqueeze(1) for t i... | [
"def",
"cat_encodings",
"(",
"self",
",",
"tensors",
")",
":",
"tensors",
"=",
"[",
"t",
"for",
"t",
"in",
"tensors",
"if",
"t",
"is",
"not",
"None",
"]",
"return",
"torch",
".",
"cat",
"(",
"[",
"t",
".",
"unsqueeze",
"(",
"1",
")",
"for",
"t",
... | [
463,
4
] | [
474,
66
] | python | en | ['en', 'error', 'th'] | False |
MultimodalCombiner.forward | (self, tensor, mask) |
Forward pass.
:param tensor:
a [bsz, seq_len, hidden_dim] FloatTensor
:param mask:
a [bsz, seq_len] ByteTensor filled with 1 when inside the sequence and 0 outside.
:return:
output: a [bsz, hidden_dim] FloatTensor of encodings
mask: the ... |
Forward pass. | def forward(self, tensor, mask):
"""
Forward pass.
:param tensor:
a [bsz, seq_len, hidden_dim] FloatTensor
:param mask:
a [bsz, seq_len] ByteTensor filled with 1 when inside the sequence and 0 outside.
:return:
output: a [bsz, hidden_dim] Flo... | [
"def",
"forward",
"(",
"self",
",",
"tensor",
",",
"mask",
")",
":",
"seq_len",
"=",
"tensor",
".",
"size",
"(",
"1",
")",
"positions",
"=",
"tensor",
".",
"new",
"(",
"seq_len",
")",
".",
"long",
"(",
")",
"positions",
"=",
"torch",
".",
"arange",... | [
548,
4
] | [
576,
31
] | python | en | ['en', 'error', 'th'] | False |
my_lcs | (string, sub) |
Calculates longest common subsequence for a pair of tokenized strings
:param string : list of str : tokens from a string split using whitespace
:param sub : list of str : shorter string, also split using whitespace
:returns: length (list of int): length of the longest common subsequence between the two... |
Calculates longest common subsequence for a pair of tokenized strings
:param string : list of str : tokens from a string split using whitespace
:param sub : list of str : shorter string, also split using whitespace
:returns: length (list of int): length of the longest common subsequence between the two... | def my_lcs(string, sub):
"""
Calculates longest common subsequence for a pair of tokenized strings
:param string : list of str : tokens from a string split using whitespace
:param sub : list of str : shorter string, also split using whitespace
:returns: length (list of int): length of the longest co... | [
"def",
"my_lcs",
"(",
"string",
",",
"sub",
")",
":",
"if",
"len",
"(",
"string",
")",
"<",
"len",
"(",
"sub",
")",
":",
"sub",
",",
"string",
"=",
"string",
",",
"sub",
"lengths",
"=",
"[",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",... | [
13,
0
] | [
34,
41
] | python | en | ['en', 'error', 'th'] | False |
Rouge.calc_score | (self, candidate, refs) |
Compute ROUGE-L score given one candidate and references for an image
:param candidate: str : candidate sentence to be evaluated
:param refs: list of str : COCO reference sentences for the particular image to be evaluated
:returns score: int (ROUGE-L score for the candidate evaluated ag... |
Compute ROUGE-L score given one candidate and references for an image
:param candidate: str : candidate sentence to be evaluated
:param refs: list of str : COCO reference sentences for the particular image to be evaluated
:returns score: int (ROUGE-L score for the candidate evaluated ag... | def calc_score(self, candidate, refs):
"""
Compute ROUGE-L score given one candidate and references for an image
:param candidate: str : candidate sentence to be evaluated
:param refs: list of str : COCO reference sentences for the particular image to be evaluated
:returns score:... | [
"def",
"calc_score",
"(",
"self",
",",
"candidate",
",",
"refs",
")",
":",
"assert",
"len",
"(",
"candidate",
")",
"==",
"1",
"assert",
"len",
"(",
"refs",
")",
">",
"0",
"prec",
"=",
"[",
"]",
"rec",
"=",
"[",
"]",
"# split into tokens",
"token_c",
... | [
47,
4
] | [
79,
20
] | python | en | ['en', 'error', 'th'] | False |
Rouge.compute_score | (self, gts, res) |
Computes Rouge-L score given a set of reference and candidate sentences for the dataset
Invoked by evaluate_captions.py
:param hypo_for_image: dict : candidate / test sentences with "image name" key and "tokenized sentences" as values
:param ref_for_image: dict : reference MS-COCO sente... |
Computes Rouge-L score given a set of reference and candidate sentences for the dataset
Invoked by evaluate_captions.py
:param hypo_for_image: dict : candidate / test sentences with "image name" key and "tokenized sentences" as values
:param ref_for_image: dict : reference MS-COCO sente... | def compute_score(self, gts, res):
"""
Computes Rouge-L score given a set of reference and candidate sentences for the dataset
Invoked by evaluate_captions.py
:param hypo_for_image: dict : candidate / test sentences with "image name" key and "tokenized sentences" as values
:param... | [
"def",
"compute_score",
"(",
"self",
",",
"gts",
",",
"res",
")",
":",
"assert",
"list",
"(",
"gts",
".",
"keys",
"(",
")",
")",
"==",
"list",
"(",
"res",
".",
"keys",
"(",
")",
")",
"imgIds",
"=",
"list",
"(",
"gts",
".",
"keys",
"(",
")",
"... | [
81,
4
] | [
106,
45
] | python | en | ['en', 'error', 'th'] | False |
post_save | (sender, instance, created, **kwargs) |
Receives a signal just after the object is saved.
|
Receives a signal just after the object is saved.
| def post_save(sender, instance, created, **kwargs):
"""
Receives a signal just after the object is saved.
"""
if created:
instance.at_first_save() | [
"def",
"post_save",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"instance",
".",
"at_first_save",
"(",
")"
] | [
3,
0
] | [
8,
32
] | python | en | ['en', 'error', 'th'] | False |
Gradient.color | (self) |
Sets the final color of the gradient fill: the center color for
radial, the right for horizontal, or the bottom for vertical.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- ... |
Sets the final color of the gradient fill: the center color for
radial, the right for horizontal, or the bottom for vertical.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- ... | def color(self):
"""
Sets the final color of the gradient fill: the center color for
radial, the right for horizontal, or the bottom for vertical.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. ... | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
67,
28
] | python | en | ['en', 'error', 'th'] | False |
Gradient.colorsrc | (self) |
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"] | [
"def",
"colorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorsrc\"",
"]"
] | [
76,
4
] | [
87,
31
] | python | en | ['en', 'error', 'th'] | False |
Gradient.type | (self) |
Sets the type of gradient used to fill the markers
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['radial', 'horizontal', 'vertical', 'none']
- A tuple, list, or one-dimensional numpy array of the abov... |
Sets the type of gradient used to fill the markers
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['radial', 'horizontal', 'vertical', 'none']
- A tuple, list, or one-dimensional numpy array of the abov... | def type(self):
"""
Sets the type of gradient used to fill the markers
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['radial', 'horizontal', 'vertical', 'none']
- A tuple, list, or one-dimensio... | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"type\"",
"]"
] | [
96,
4
] | [
109,
27
] | python | en | ['en', 'error', 'th'] | False |
Gradient.typesrc | (self) |
Sets the source reference on Chart Studio Cloud for type .
The 'typesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for type .
The 'typesrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def typesrc(self):
"""
Sets the source reference on Chart Studio Cloud for type .
The 'typesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["typesrc"] | [
"def",
"typesrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"typesrc\"",
"]"
] | [
118,
4
] | [
129,
30
] | python | en | ['en', 'error', 'th'] | False |
Gradient.__init__ | (
self, arg=None, color=None, colorsrc=None, type=None, typesrc=None, **kwargs
) |
Construct a new Gradient object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattercarpet.
marker.Gradient`
color
Sets the final color of the gr... |
Construct a new Gradient object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattercarpet.
marker.Gradient`
color
Sets the final color of the gr... | def __init__(
self, arg=None, color=None, colorsrc=None, type=None, typesrc=None, **kwargs
):
"""
Construct a new Gradient object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`p... | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"colorsrc",
"=",
"None",
",",
"type",
"=",
"None",
",",
"typesrc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Gradient",
",",
"self",
")"... | [
154,
4
] | [
235,
34
] | python | en | ['en', 'error', 'th'] | False |
_ternary_layout | (
title="Ternary contour plot", width=550, height=525, pole_labels=["a", "b", "c"]
) |
Layout of ternary contour plot, to be passed to ``go.FigureWidget``
object.
Parameters
==========
title : str or None
Title of ternary plot
width : int
Figure width.
height : int
Figure height.
pole_labels : str, default ['a', 'b', 'c']
Names of the thre... |
Layout of ternary contour plot, to be passed to ``go.FigureWidget``
object. | def _ternary_layout(
title="Ternary contour plot", width=550, height=525, pole_labels=["a", "b", "c"]
):
"""
Layout of ternary contour plot, to be passed to ``go.FigureWidget``
object.
Parameters
==========
title : str or None
Title of ternary plot
width : int
Figure wid... | [
"def",
"_ternary_layout",
"(",
"title",
"=",
"\"Ternary contour plot\"",
",",
"width",
"=",
"550",
",",
"height",
"=",
"525",
",",
"pole_labels",
"=",
"[",
"\"a\"",
",",
"\"b\"",
",",
"\"c\"",
"]",
")",
":",
"return",
"dict",
"(",
"title",
"=",
"title",
... | [
15,
0
] | [
50,
5
] | python | en | ['en', 'error', 'th'] | False |
_replace_zero_coords | (ternary_data, delta=0.0005) |
Replaces zero ternary coordinates with delta and normalize the new
triplets (a, b, c).
Parameters
----------
ternary_data : ndarray of shape (N, 3)
delta : float
Small float to regularize logarithm.
Notes
-----
Implements a method
by J. A. Martin-Fernandez, C. Barce... |
Replaces zero ternary coordinates with delta and normalize the new
triplets (a, b, c). | def _replace_zero_coords(ternary_data, delta=0.0005):
"""
Replaces zero ternary coordinates with delta and normalize the new
triplets (a, b, c).
Parameters
----------
ternary_data : ndarray of shape (N, 3)
delta : float
Small float to regularize logarithm.
Notes
-----
... | [
"def",
"_replace_zero_coords",
"(",
"ternary_data",
",",
"delta",
"=",
"0.0005",
")",
":",
"zero_mask",
"=",
"ternary_data",
"==",
"0",
"is_any_coord_zero",
"=",
"np",
".",
"any",
"(",
"zero_mask",
",",
"axis",
"=",
"0",
")",
"unity_complement",
"=",
"1",
... | [
56,
0
] | [
87,
23
] | python | en | ['en', 'error', 'th'] | False |
_ilr_transform | (barycentric) |
Perform Isometric Log-Ratio on barycentric (compositional) data.
Parameters
----------
barycentric: ndarray of shape (3, N)
Barycentric coordinates.
References
----------
"An algebraic method to compute isometric logratio transformation and
back transformation of compositional... |
Perform Isometric Log-Ratio on barycentric (compositional) data. | def _ilr_transform(barycentric):
"""
Perform Isometric Log-Ratio on barycentric (compositional) data.
Parameters
----------
barycentric: ndarray of shape (3, N)
Barycentric coordinates.
References
----------
"An algebraic method to compute isometric logratio transformation and
... | [
"def",
"_ilr_transform",
"(",
"barycentric",
")",
":",
"barycentric",
"=",
"np",
".",
"asarray",
"(",
"barycentric",
")",
"x_0",
"=",
"np",
".",
"log",
"(",
"barycentric",
"[",
"0",
"]",
"/",
"barycentric",
"[",
"1",
"]",
")",
"/",
"np",
".",
"sqrt",... | [
90,
0
] | [
112,
20
] | python | en | ['en', 'error', 'th'] | False |
_ilr_inverse | (x) |
Perform inverse Isometric Log-Ratio (ILR) transform to retrieve
barycentric (compositional) data.
Parameters
----------
x : array of shape (2, N)
Coordinates in ILR space.
References
----------
"An algebraic method to compute isometric logratio transformation and
back tran... |
Perform inverse Isometric Log-Ratio (ILR) transform to retrieve
barycentric (compositional) data. | def _ilr_inverse(x):
"""
Perform inverse Isometric Log-Ratio (ILR) transform to retrieve
barycentric (compositional) data.
Parameters
----------
x : array of shape (2, N)
Coordinates in ILR space.
References
----------
"An algebraic method to compute isometric logratio tran... | [
"def",
"_ilr_inverse",
"(",
"x",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.5",
",",
"1",
",",
"1.0",
"]",
",",
"[",
"-",
"0.5",
",",
"1",
",",
"1.0",
"]",
",",
"[",
"0.0",
... | [
115,
0
] | [
142,
21
] | python | en | ['en', 'error', 'th'] | False |
_transform_barycentric_cartesian | () |
Returns the transformation matrix from barycentric to Cartesian
coordinates and conversely.
|
Returns the transformation matrix from barycentric to Cartesian
coordinates and conversely.
| def _transform_barycentric_cartesian():
"""
Returns the transformation matrix from barycentric to Cartesian
coordinates and conversely.
"""
# reference triangle
tri_verts = np.array([[0.5, np.sqrt(3) / 2], [0, 0], [1, 0]])
M = np.array([tri_verts[:, 0], tri_verts[:, 1], np.ones(3)])
retu... | [
"def",
"_transform_barycentric_cartesian",
"(",
")",
":",
"# reference triangle",
"tri_verts",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.5",
",",
"np",
".",
"sqrt",
"(",
"3",
")",
"/",
"2",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"1",
",",
... | [
145,
0
] | [
153,
30
] | python | en | ['en', 'error', 'th'] | False |
_prepare_barycentric_coord | (b_coords) |
Check ternary coordinates and return the right barycentric coordinates.
|
Check ternary coordinates and return the right barycentric coordinates.
| def _prepare_barycentric_coord(b_coords):
"""
Check ternary coordinates and return the right barycentric coordinates.
"""
if not isinstance(b_coords, (list, np.ndarray)):
raise ValueError(
"Data should be either an array of shape (n,m),"
"or a list of n m-lists, m=2 or 3... | [
"def",
"_prepare_barycentric_coord",
"(",
"b_coords",
")",
":",
"if",
"not",
"isinstance",
"(",
"b_coords",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Data should be either an array of shape (n,m),\"",
"\"or a list of... | [
156,
0
] | [
185,
30
] | python | en | ['en', 'error', 'th'] | False |
_compute_grid | (coordinates, values, interp_mode="ilr") |
Transform data points with Cartesian or ILR mapping, then Compute
interpolation on a regular grid.
Parameters
==========
coordinates : array-like
Barycentric coordinates of data points.
values : 1-d array-like
Data points, field to be represented as contours.
interp_mode :... |
Transform data points with Cartesian or ILR mapping, then Compute
interpolation on a regular grid. | def _compute_grid(coordinates, values, interp_mode="ilr"):
"""
Transform data points with Cartesian or ILR mapping, then Compute
interpolation on a regular grid.
Parameters
==========
coordinates : array-like
Barycentric coordinates of data points.
values : 1-d array-like
D... | [
"def",
"_compute_grid",
"(",
"coordinates",
",",
"values",
",",
"interp_mode",
"=",
"\"ilr\"",
")",
":",
"if",
"interp_mode",
"==",
"\"cartesian\"",
":",
"M",
",",
"invM",
"=",
"_transform_barycentric_cartesian",
"(",
")",
"coord_points",
"=",
"np",
".",
"eins... | [
188,
0
] | [
228,
29
] | python | en | ['en', 'error', 'th'] | False |
_colors | (ncontours, colormap=None) |
Return a list of ``ncontours`` colors from the ``colormap`` colorscale.
|
Return a list of ``ncontours`` colors from the ``colormap`` colorscale.
| def _colors(ncontours, colormap=None):
"""
Return a list of ``ncontours`` colors from the ``colormap`` colorscale.
"""
if colormap in clrs.PLOTLY_SCALES.keys():
cmap = clrs.PLOTLY_SCALES[colormap]
else:
raise exceptions.PlotlyError(
"Colorscale must be a valid Plotly Colo... | [
"def",
"_colors",
"(",
"ncontours",
",",
"colormap",
"=",
"None",
")",
":",
"if",
"colormap",
"in",
"clrs",
".",
"PLOTLY_SCALES",
".",
"keys",
"(",
")",
":",
"cmap",
"=",
"clrs",
".",
"PLOTLY_SCALES",
"[",
"colormap",
"]",
"else",
":",
"raise",
"except... | [
238,
0
] | [
264,
17
] | python | en | ['en', 'error', 'th'] | False |
_is_invalid_contour | (x, y) |
Utility function for _contour_trace
Contours with an area of the order as 1 pixel are considered spurious.
|
Utility function for _contour_trace | def _is_invalid_contour(x, y):
"""
Utility function for _contour_trace
Contours with an area of the order as 1 pixel are considered spurious.
"""
too_small = np.all(np.abs(x - x[0]) < 2) and np.all(np.abs(y - y[0]) < 2)
return too_small | [
"def",
"_is_invalid_contour",
"(",
"x",
",",
"y",
")",
":",
"too_small",
"=",
"np",
".",
"all",
"(",
"np",
".",
"abs",
"(",
"x",
"-",
"x",
"[",
"0",
"]",
")",
"<",
"2",
")",
"and",
"np",
".",
"all",
"(",
"np",
".",
"abs",
"(",
"y",
"-",
"... | [
267,
0
] | [
274,
20
] | python | en | ['en', 'error', 'th'] | False |
_extract_contours | (im, values, colors) |
Utility function for _contour_trace.
In ``im`` only one part of the domain has valid values (corresponding
to a subdomain where barycentric coordinates are well defined). When
computing contours, we need to assign values outside of this domain.
We can choose a value either smaller than all the val... |
Utility function for _contour_trace. | def _extract_contours(im, values, colors):
"""
Utility function for _contour_trace.
In ``im`` only one part of the domain has valid values (corresponding
to a subdomain where barycentric coordinates are well defined). When
computing contours, we need to assign values outside of this domain.
We ... | [
"def",
"_extract_contours",
"(",
"im",
",",
"values",
",",
"colors",
")",
":",
"mask_nan",
"=",
"np",
".",
"isnan",
"(",
"im",
")",
"im_min",
",",
"im_max",
"=",
"(",
"im",
"[",
"np",
".",
"logical_not",
"(",
"mask_nan",
")",
"]",
".",
"min",
"(",
... | [
277,
0
] | [
324,
66
] | python | en | ['en', 'error', 'th'] | False |
_add_outer_contour | (
all_contours,
all_values,
all_areas,
all_colors,
values,
val_outer,
v_min,
v_max,
colors,
color_min,
color_max,
) |
Utility function for _contour_trace
Adds the background color to fill gaps outside of computed contours.
To compute the background color, the color of the contour with largest
area (``val_outer``) is used. As background color, we choose the next
color value in the direction of the extrema of the ... |
Utility function for _contour_trace | def _add_outer_contour(
all_contours,
all_values,
all_areas,
all_colors,
values,
val_outer,
v_min,
v_max,
colors,
color_min,
color_max,
):
"""
Utility function for _contour_trace
Adds the background color to fill gaps outside of computed contours.
To compute... | [
"def",
"_add_outer_contour",
"(",
"all_contours",
",",
"all_values",
",",
"all_areas",
",",
"all_colors",
",",
"values",
",",
"val_outer",
",",
"v_min",
",",
"v_max",
",",
"colors",
",",
"color_min",
",",
"color_max",
",",
")",
":",
"# The exact value of outer ... | [
327,
0
] | [
381,
71
] | python | en | ['en', 'error', 'th'] | False |
_contour_trace | (
x,
y,
z,
ncontours=None,
colorscale="Electric",
linecolor="rgb(150,150,150)",
interp_mode="llr",
coloring=None,
v_min=0,
v_max=1,
) |
Contour trace in Cartesian coordinates.
Parameters
==========
x, y : array-like
Cartesian coordinates
z : array-like
Field to be represented as contours.
ncontours : int or None
Number of contours to display (determined automatically if None).
colorscale : None or ... |
Contour trace in Cartesian coordinates. | def _contour_trace(
x,
y,
z,
ncontours=None,
colorscale="Electric",
linecolor="rgb(150,150,150)",
interp_mode="llr",
coloring=None,
v_min=0,
v_max=1,
):
"""
Contour trace in Cartesian coordinates.
Parameters
==========
x, y : array-like
Cartesian coo... | [
"def",
"_contour_trace",
"(",
"x",
",",
"y",
",",
"z",
",",
"ncontours",
"=",
"None",
",",
"colorscale",
"=",
"\"Electric\"",
",",
"linecolor",
"=",
"\"rgb(150,150,150)\"",
",",
"interp_mode",
"=",
"\"llr\"",
",",
"coloring",
"=",
"None",
",",
"v_min",
"="... | [
384,
0
] | [
511,
30
] | python | en | ['en', 'error', 'th'] | False |
create_ternary_contour | (
coordinates,
values,
pole_labels=["a", "b", "c"],
width=500,
height=500,
ncontours=None,
showscale=False,
coloring=None,
colorscale="Bluered",
linecolor=None,
title=None,
interp_mode="ilr",
showmarkers=False,
) |
Ternary contour plot.
Parameters
----------
coordinates : list or ndarray
Barycentric coordinates of shape (2, N) or (3, N) where N is the
number of data points. The sum of the 3 coordinates is expected
to be 1 for all data points.
values : array-like
Data points o... |
Ternary contour plot. | def create_ternary_contour(
coordinates,
values,
pole_labels=["a", "b", "c"],
width=500,
height=500,
ncontours=None,
showscale=False,
coloring=None,
colorscale="Bluered",
linecolor=None,
title=None,
interp_mode="ilr",
showmarkers=False,
):
"""
Ternary contour ... | [
"def",
"create_ternary_contour",
"(",
"coordinates",
",",
"values",
",",
"pole_labels",
"=",
"[",
"\"a\"",
",",
"\"b\"",
",",
"\"c\"",
"]",
",",
"width",
"=",
"500",
",",
"height",
"=",
"500",
",",
"ncontours",
"=",
"None",
",",
"showscale",
"=",
"False"... | [
517,
0
] | [
698,
14
] | python | en | ['en', 'error', 'th'] | False |
Marker.color | (self) |
Sets the marker color of unselected points, applied only when a
selection exists.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
... |
Sets the marker color of unselected points, applied only when a
selection exists.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
... | def color(self):
"""
Sets the marker color of unselected points, applied only when a
selection exists.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla stri... | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
66,
28
] | python | en | ['en', 'error', 'th'] | False |
Marker.opacity | (self) |
Sets the marker opacity of unselected points, applied only when
a selection exists.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
|
Sets the marker opacity of unselected points, applied only when
a selection exists.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1] | def opacity(self):
"""
Sets the marker opacity of unselected points, applied only when
a selection exists.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
... | [
"def",
"opacity",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"opacity\"",
"]"
] | [
75,
4
] | [
87,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.size | (self) |
Sets the marker size of unselected points, applied only when a
selection exists.
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
|
Sets the marker size of unselected points, applied only when a
selection exists.
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf] | def size(self):
"""
Sets the marker size of unselected points, applied only when a
selection exists.
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
r... | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
96,
4
] | [
108,
27
] | python | en | ['en', 'error', 'th'] | False |
Marker.__init__ | (self, arg=None, color=None, opacity=None, size=None, **kwargs) |
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.splom.unselected.Marker`
color
Sets the marker color of unselected poi... |
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.splom.unselected.Marker`
color
Sets the marker color of unselected poi... | def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sp... | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"opacity",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Marker",
",",
"self",
")",
".",
"__init__",
"(",
"\"marke... | [
130,
4
] | [
202,
34
] | python | en | ['en', 'error', 'th'] | False |
_adversarial_dialogue_datapath | (opt: Opt) |
Return the filepath for the specified datatype of the specified adversarial dialogue
task.
|
Return the filepath for the specified datatype of the specified adversarial dialogue
task.
| def _adversarial_dialogue_datapath(opt: Opt) -> str:
"""
Return the filepath for the specified datatype of the specified adversarial dialogue
task.
"""
build_dialogue_datasets(opt)
# Build the data if it doesn't exist.
dt = opt['datatype'].split(':')[0]
data_path = os.path.join(
... | [
"def",
"_adversarial_dialogue_datapath",
"(",
"opt",
":",
"Opt",
")",
"->",
"str",
":",
"build_dialogue_datasets",
"(",
"opt",
")",
"# Build the data if it doesn't exist.",
"dt",
"=",
"opt",
"[",
"'datatype'",
"]",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",... | [
28,
0
] | [
41,
20
] | python | en | ['en', 'error', 'th'] | False |
_human_safety_eval_datapath | (opt: Opt) |
Return the filepath for the specified datatype of the specified human evaluation
task on bot adversarial dialogue.
|
Return the filepath for the specified datatype of the specified human evaluation
task on bot adversarial dialogue.
| def _human_safety_eval_datapath(opt: Opt) -> str:
"""
Return the filepath for the specified datatype of the specified human evaluation
task on bot adversarial dialogue.
"""
build_human_safety_eval_dataset(opt)
# Build the data if it doesn't exist.
logging.info(
f'The data for human s... | [
"def",
"_human_safety_eval_datapath",
"(",
"opt",
":",
"Opt",
")",
"->",
"str",
":",
"build_human_safety_eval_dataset",
"(",
"opt",
")",
"# Build the data if it doesn't exist.",
"logging",
".",
"info",
"(",
"f'The data for human safety evaluation is test set only '",
"f'regar... | [
161,
0
] | [
175,
20
] | python | en | ['en', 'error', 'th'] | False |
Title.font | (self) |
Sets this axis' title font. Note that the title's font used to
be set by the now deprecated `titlefont` attribute.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.carpet.aaxis.title.Font`
- A dict o... |
Sets this axis' title font. Note that the title's font used to
be set by the now deprecated `titlefont` attribute.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.carpet.aaxis.title.Font`
- A dict o... | def font(self):
"""
Sets this axis' title font. Note that the title's font used to
be set by the now deprecated `titlefont` attribute.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.carpet.aaxis.title... | [
"def",
"font",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"font\"",
"]"
] | [
15,
4
] | [
53,
27
] | python | en | ['en', 'error', 'th'] | False |
Title.offset | (self) |
An additional amount by which to offset the title from the tick
labels, given in pixels. Note that this used to be set by the
now deprecated `titleoffset` attribute.
The 'offset' property is a number and may be specified as:
- An int or float
Returns
----... |
An additional amount by which to offset the title from the tick
labels, given in pixels. Note that this used to be set by the
now deprecated `titleoffset` attribute.
The 'offset' property is a number and may be specified as:
- An int or float | def offset(self):
"""
An additional amount by which to offset the title from the tick
labels, given in pixels. Note that this used to be set by the
now deprecated `titleoffset` attribute.
The 'offset' property is a number and may be specified as:
- An int or float
... | [
"def",
"offset",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"offset\"",
"]"
] | [
62,
4
] | [
75,
29
] | python | en | ['en', 'error', 'th'] | False |
Title.text | (self) |
Sets the title of this axis. Note that before the existence of
`title.text`, the title's contents used to be defined as the
`title` attribute itself. This behavior has been deprecated.
The 'text' property is a string and must be specified as:
- A string
- A numb... |
Sets the title of this axis. Note that before the existence of
`title.text`, the title's contents used to be defined as the
`title` attribute itself. This behavior has been deprecated.
The 'text' property is a string and must be specified as:
- A string
- A numb... | def text(self):
"""
Sets the title of this axis. Note that before the existence of
`title.text`, the title's contents used to be defined as the
`title` attribute itself. This behavior has been deprecated.
The 'text' property is a string and must be specified as:
- ... | [
"def",
"text",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"text\"",
"]"
] | [
84,
4
] | [
98,
27
] | python | en | ['en', 'error', 'th'] | False |
Title.__init__ | (self, arg=None, font=None, offset=None, text=None, **kwargs) |
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.carpet.aaxis.Title`
font
Sets this axis' title font. Note that the titl... |
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.carpet.aaxis.Title`
font
Sets this axis' title font. Note that the titl... | def __init__(self, arg=None, font=None, offset=None, text=None, **kwargs):
"""
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.carpe... | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"font",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"text",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Title",
",",
"self",
")",
".",
"__init__",
"(",
"\"title\""... | [
125,
4
] | [
202,
34
] | python | en | ['en', 'error', 'th'] | False |
export_onnx_model | (model, inputs, passes) | Trace and export a model to onnx format. Modified from
https://github.com/facebookresearch/detectron2/
Args:
model (nn.Module):
inputs (tuple[args]): the model will be called by `model(*inputs)`
passes (None or list[str]): the optimization passed for ONNX model
Returns:
an ... | Trace and export a model to onnx format. Modified from
https://github.com/facebookresearch/detectron2/ | def export_onnx_model(model, inputs, passes):
"""Trace and export a model to onnx format. Modified from
https://github.com/facebookresearch/detectron2/
Args:
model (nn.Module):
inputs (tuple[args]): the model will be called by `model(*inputs)`
passes (None or list[str]): the optimiz... | [
"def",
"export_onnx_model",
"(",
"model",
",",
"inputs",
",",
"passes",
")",
":",
"assert",
"isinstance",
"(",
"model",
",",
"torch",
".",
"nn",
".",
"Module",
")",
"# make sure all modules are in eval mode, onnx may change the training",
"# state of the module if the sta... | [
14,
0
] | [
54,
21
] | python | en | ['en', 'en', 'en'] | True |
parse_requirements | (fname='requirements.txt', with_version=True) | Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
Returns:
list[str]: list of requirements items
CommandLine:
... | Parse the package dependencies listed in a requirements file but strips
specific versioning information. | def parse_requirements(fname='requirements.txt', with_version=True):
"""Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
... | [
"def",
"parse_requirements",
"(",
"fname",
"=",
"'requirements.txt'",
",",
"with_version",
"=",
"True",
")",
":",
"import",
"re",
"import",
"sys",
"from",
"os",
".",
"path",
"import",
"exists",
"require_fpath",
"=",
"fname",
"def",
"parse_line",
"(",
"line",
... | [
61,
0
] | [
134,
19
] | python | en | ['en', 'en', 'en'] | True |
task_exc_info | (task: asyncio.Task) | Extract exception info from an asyncio task. | Extract exception info from an asyncio task. | def task_exc_info(task: asyncio.Task):
"""Extract exception info from an asyncio task."""
if not task or not task.done():
return
try:
exc_val = task.exception()
except asyncio.CancelledError:
exc_val = asyncio.CancelledError("Task was cancelled")
if exc_val:
return ty... | [
"def",
"task_exc_info",
"(",
"task",
":",
"asyncio",
".",
"Task",
")",
":",
"if",
"not",
"task",
"or",
"not",
"task",
".",
"done",
"(",
")",
":",
"return",
"try",
":",
"exc_val",
"=",
"task",
".",
"exception",
"(",
")",
"except",
"asyncio",
".",
"C... | [
9,
0
] | [
18,
60
] | python | en | ['en', 'en', 'en'] | True |
CompletedTask.__init__ | (self, task: asyncio.Task, exc_info: Tuple) | Initialize the completed task. | Initialize the completed task. | def __init__(self, task: asyncio.Task, exc_info: Tuple):
"""Initialize the completed task."""
self.exc_info = exc_info
self.task = task | [
"def",
"__init__",
"(",
"self",
",",
"task",
":",
"asyncio",
".",
"Task",
",",
"exc_info",
":",
"Tuple",
")",
":",
"self",
".",
"exc_info",
"=",
"exc_info",
"self",
".",
"task",
"=",
"task"
] | [
26,
4
] | [
29,
24
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.__init__ | (self, max_active: int = 0) |
Initialize the task queue.
Args:
max_active: The maximum number of tasks to automatically run
|
Initialize the task queue. | def __init__(self, max_active: int = 0):
"""
Initialize the task queue.
Args:
max_active: The maximum number of tasks to automatically run
"""
self.loop = asyncio.get_event_loop()
self.active_tasks = []
self.pending_tasks = []
self.total_done ... | [
"def",
"__init__",
"(",
"self",
",",
"max_active",
":",
"int",
"=",
"0",
")",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"self",
".",
"active_tasks",
"=",
"[",
"]",
"self",
".",
"pending_tasks",
"=",
"[",
"]",
"self",
... | [
35,
4
] | [
50,
37
] | python | en | ['en', 'error', 'th'] | False |
TaskQueue.cancelled | (self) | Accessor for the cancelled property of the queue. | Accessor for the cancelled property of the queue. | def cancelled(self) -> bool:
"""Accessor for the cancelled property of the queue."""
return self._cancelled | [
"def",
"cancelled",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_cancelled"
] | [
53,
4
] | [
55,
30
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.max_active | (self) | Accessor for the maximum number of active tasks in the queue. | Accessor for the maximum number of active tasks in the queue. | def max_active(self) -> int:
"""Accessor for the maximum number of active tasks in the queue."""
return self._max_active | [
"def",
"max_active",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_max_active"
] | [
58,
4
] | [
60,
31
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.ready | (self) | Accessor for the ready property of the queue. | Accessor for the ready property of the queue. | def ready(self) -> bool:
"""Accessor for the ready property of the queue."""
return (
not self._cancelled
and not self._max_active
or self.current_size < self._max_active
) | [
"def",
"ready",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"(",
"not",
"self",
".",
"_cancelled",
"and",
"not",
"self",
".",
"_max_active",
"or",
"self",
".",
"current_size",
"<",
"self",
".",
"_max_active",
")"
] | [
63,
4
] | [
69,
9
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.current_active | (self) | Accessor for the current number of active tasks in the queue. | Accessor for the current number of active tasks in the queue. | def current_active(self) -> int:
"""Accessor for the current number of active tasks in the queue."""
return len(self.active_tasks) | [
"def",
"current_active",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"active_tasks",
")"
] | [
72,
4
] | [
74,
37
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.current_pending | (self) | Accessor for the current number of pending tasks in the queue. | Accessor for the current number of pending tasks in the queue. | def current_pending(self) -> int:
"""Accessor for the current number of pending tasks in the queue."""
return len(self.pending_tasks) | [
"def",
"current_pending",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"pending_tasks",
")"
] | [
77,
4
] | [
79,
38
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.current_size | (self) | Accessor for the total number of tasks in the queue. | Accessor for the total number of tasks in the queue. | def current_size(self) -> int:
"""Accessor for the total number of tasks in the queue."""
return len(self.active_tasks) + len(self.pending_tasks) | [
"def",
"current_size",
"(",
"self",
")",
"->",
"int",
":",
"return",
"len",
"(",
"self",
".",
"active_tasks",
")",
"+",
"len",
"(",
"self",
".",
"pending_tasks",
")"
] | [
82,
4
] | [
84,
63
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.__len__ | (self) | Support for the len() builtin. | Support for the len() builtin. | def __len__(self) -> int:
"""Support for the len() builtin."""
return self.current_size | [
"def",
"__len__",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"current_size"
] | [
86,
4
] | [
88,
32
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.drain | (self) | Start the process to run queued tasks. | Start the process to run queued tasks. | def drain(self) -> asyncio.Task:
"""Start the process to run queued tasks."""
if self._drain_task and not self._drain_task.done():
self._drain_evt.set()
elif self.pending_tasks:
self._drain_task = self.loop.create_task(self._drain_loop())
self._drain_task.add_... | [
"def",
"drain",
"(",
"self",
")",
"->",
"asyncio",
".",
"Task",
":",
"if",
"self",
".",
"_drain_task",
"and",
"not",
"self",
".",
"_drain_task",
".",
"done",
"(",
")",
":",
"self",
".",
"_drain_evt",
".",
"set",
"(",
")",
"elif",
"self",
".",
"pend... | [
90,
4
] | [
97,
31
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue._drain_done | (self, task: asyncio.Task) | Handle completion of the drain process. | Handle completion of the drain process. | def _drain_done(self, task: asyncio.Task):
"""Handle completion of the drain process."""
exc_info = task_exc_info(task)
if exc_info:
LOGGER.exception("Error draining task queue:", exc_info=exc_info)
if self._drain_task and self._drain_task.done():
self._drain_task... | [
"def",
"_drain_done",
"(",
"self",
",",
"task",
":",
"asyncio",
".",
"Task",
")",
":",
"exc_info",
"=",
"task_exc_info",
"(",
"task",
")",
"if",
"exc_info",
":",
"LOGGER",
".",
"exception",
"(",
"\"Error draining task queue:\"",
",",
"exc_info",
"=",
"exc_in... | [
99,
4
] | [
105,
35
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue._drain_loop | (self) | Run pending tasks while there is room in the queue. | Run pending tasks while there is room in the queue. | async def _drain_loop(self):
"""Run pending tasks while there is room in the queue."""
# Note: this method should not call async methods apart from
# waiting for the updated event, to avoid yielding to other queue methods
while True:
self._drain_evt.clear()
while ... | [
"async",
"def",
"_drain_loop",
"(",
"self",
")",
":",
"# Note: this method should not call async methods apart from",
"# waiting for the updated event, to avoid yielding to other queue methods",
"while",
"True",
":",
"self",
".",
"_drain_evt",
".",
"clear",
"(",
")",
"while",
... | [
107,
4
] | [
123,
21
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.add_pending | (
self,
coro: Coroutine,
task_complete: Callable = None,
fut: asyncio.Future = None,
) |
Add a task to the pending queue.
Args:
coro: The coroutine to run
task_complete: An optional callback when the task has completed
fut: A future that resolves to the task once it is queued
|
Add a task to the pending queue. | def add_pending(
self,
coro: Coroutine,
task_complete: Callable = None,
fut: asyncio.Future = None,
):
"""
Add a task to the pending queue.
Args:
coro: The coroutine to run
task_complete: An optional callback when the task has complete... | [
"def",
"add_pending",
"(",
"self",
",",
"coro",
":",
"Coroutine",
",",
"task_complete",
":",
"Callable",
"=",
"None",
",",
"fut",
":",
"asyncio",
".",
"Future",
"=",
"None",
",",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutine",
"(",
"coro",
")",
... | [
125,
4
] | [
142,
20
] | python | en | ['en', 'error', 'th'] | False |
TaskQueue.add_active | (
self, task: asyncio.Task, task_complete: Callable = None
) |
Register an active async task with an optional completion callback.
Args:
task: The asyncio task instance
task_complete: An optional callback to run on completion
|
Register an active async task with an optional completion callback. | def add_active(
self, task: asyncio.Task, task_complete: Callable = None
) -> asyncio.Task:
"""
Register an active async task with an optional completion callback.
Args:
task: The asyncio task instance
task_complete: An optional callback to run on completion
... | [
"def",
"add_active",
"(",
"self",
",",
"task",
":",
"asyncio",
".",
"Task",
",",
"task_complete",
":",
"Callable",
"=",
"None",
")",
"->",
"asyncio",
".",
"Task",
":",
"self",
".",
"active_tasks",
".",
"append",
"(",
"task",
")",
"task",
".",
"add_done... | [
144,
4
] | [
156,
19
] | python | en | ['en', 'error', 'th'] | False |
TaskQueue.run | (self, coro: Coroutine, task_complete: Callable = None) |
Start executing a coroutine as an async task, bypassing the pending queue.
Args:
coro: The coroutine to run
task_complete: A callback to run on completion
Returns: the new asyncio task instance
|
Start executing a coroutine as an async task, bypassing the pending queue. | def run(self, coro: Coroutine, task_complete: Callable = None) -> asyncio.Task:
"""
Start executing a coroutine as an async task, bypassing the pending queue.
Args:
coro: The coroutine to run
task_complete: A callback to run on completion
Returns: the new asynci... | [
"def",
"run",
"(",
"self",
",",
"coro",
":",
"Coroutine",
",",
"task_complete",
":",
"Callable",
"=",
"None",
")",
"->",
"asyncio",
".",
"Task",
":",
"if",
"self",
".",
"_cancelled",
":",
"raise",
"RuntimeError",
"(",
"\"Task queue has been cancelled\"",
")"... | [
158,
4
] | [
174,
51
] | python | en | ['en', 'error', 'th'] | False |
TaskQueue.put | (self, coro: Coroutine, task_complete: Callable = None) |
Add a new task to the queue, delaying execution if busy.
Args:
coro: The coroutine to run
task_complete: A callback to run on completion
Returns: a future resolving to the asyncio task instance once queued
|
Add a new task to the queue, delaying execution if busy. | def put(self, coro: Coroutine, task_complete: Callable = None) -> asyncio.Future:
"""
Add a new task to the queue, delaying execution if busy.
Args:
coro: The coroutine to run
task_complete: A callback to run on completion
Returns: a future resolving to the asyn... | [
"def",
"put",
"(",
"self",
",",
"coro",
":",
"Coroutine",
",",
"task_complete",
":",
"Callable",
"=",
"None",
")",
"->",
"asyncio",
".",
"Future",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_future",
"(",
")",
"if",
"self",
".",
"_cancelled",
... | [
176,
4
] | [
196,
18
] | python | en | ['en', 'error', 'th'] | False |
TaskQueue.completed_task | (self, task: asyncio.Task, task_complete: Callable) | Clean up after a task has completed and run callbacks. | Clean up after a task has completed and run callbacks. | def completed_task(self, task: asyncio.Task, task_complete: Callable):
"""Clean up after a task has completed and run callbacks."""
exc_info = task_exc_info(task)
if exc_info:
self.total_failed += 1
if not task_complete:
LOGGER.exception("Error running tas... | [
"def",
"completed_task",
"(",
"self",
",",
"task",
":",
"asyncio",
".",
"Task",
",",
"task_complete",
":",
"Callable",
")",
":",
"exc_info",
"=",
"task_exc_info",
"(",
"task",
")",
"if",
"exc_info",
":",
"self",
".",
"total_failed",
"+=",
"1",
"if",
"not... | [
198,
4
] | [
216,
20
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.cancel_pending | (self) | Cancel any pending tasks in the queue. | Cancel any pending tasks in the queue. | def cancel_pending(self):
"""Cancel any pending tasks in the queue."""
if self._drain_task:
self._drain_task.cancel()
self._drain_task = None
for coro, task_complete, fut in self.pending_tasks:
coro.close()
fut.cancel()
self.pending_tasks =... | [
"def",
"cancel_pending",
"(",
"self",
")",
":",
"if",
"self",
".",
"_drain_task",
":",
"self",
".",
"_drain_task",
".",
"cancel",
"(",
")",
"self",
".",
"_drain_task",
"=",
"None",
"for",
"coro",
",",
"task_complete",
",",
"fut",
"in",
"self",
".",
"pe... | [
218,
4
] | [
226,
31
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.cancel | (self) | Cancel any pending or active tasks in the queue. | Cancel any pending or active tasks in the queue. | def cancel(self):
"""Cancel any pending or active tasks in the queue."""
self._cancelled = True
self.cancel_pending()
for task in self.active_tasks:
if not task.done():
task.cancel() | [
"def",
"cancel",
"(",
"self",
")",
":",
"self",
".",
"_cancelled",
"=",
"True",
"self",
".",
"cancel_pending",
"(",
")",
"for",
"task",
"in",
"self",
".",
"active_tasks",
":",
"if",
"not",
"task",
".",
"done",
"(",
")",
":",
"task",
".",
"cancel",
... | [
228,
4
] | [
234,
29
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.complete | (self, timeout: float = None, cleanup: bool = True) | Cancel any pending tasks and wait for, or cancel active tasks. | Cancel any pending tasks and wait for, or cancel active tasks. | async def complete(self, timeout: float = None, cleanup: bool = True):
"""Cancel any pending tasks and wait for, or cancel active tasks."""
self._cancelled = True
self.cancel_pending()
if timeout or timeout is None:
try:
await self.wait_for(timeout)
... | [
"async",
"def",
"complete",
"(",
"self",
",",
"timeout",
":",
"float",
"=",
"None",
",",
"cleanup",
":",
"bool",
"=",
"True",
")",
":",
"self",
".",
"_cancelled",
"=",
"True",
"self",
".",
"cancel_pending",
"(",
")",
"if",
"timeout",
"or",
"timeout",
... | [
236,
4
] | [
253,
27
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.flush | (self) | Wait for any active or pending tasks to be completed. | Wait for any active or pending tasks to be completed. | async def flush(self):
"""Wait for any active or pending tasks to be completed."""
self.drain()
while self.active_tasks or self._drain_task:
if self._drain_task:
await self._drain_task
if self.active_tasks:
await asyncio.wait(self.active_ta... | [
"async",
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"drain",
"(",
")",
"while",
"self",
".",
"active_tasks",
"or",
"self",
".",
"_drain_task",
":",
"if",
"self",
".",
"_drain_task",
":",
"await",
"self",
".",
"_drain_task",
"if",
"self",
".",
... | [
255,
4
] | [
262,
53
] | python | en | ['en', 'en', 'en'] | True |
TaskQueue.__await__ | (self) | Handle the builtin await operator. | Handle the builtin await operator. | def __await__(self):
"""Handle the builtin await operator."""
yield from self.flush().__await__() | [
"def",
"__await__",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"flush",
"(",
")",
".",
"__await__",
"(",
")"
] | [
264,
4
] | [
266,
43
] | python | en | ['en', 'su', 'en'] | True |
TaskQueue.wait_for | (self, timeout: float) | Wait for all queued tasks to complete with a timeout. | Wait for all queued tasks to complete with a timeout. | async def wait_for(self, timeout: float):
"""Wait for all queued tasks to complete with a timeout."""
return await asyncio.wait_for(self.flush(), timeout) | [
"async",
"def",
"wait_for",
"(",
"self",
",",
"timeout",
":",
"float",
")",
":",
"return",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"flush",
"(",
")",
",",
"timeout",
")"
] | [
268,
4
] | [
270,
60
] | python | en | ['en', 'en', 'en'] | True |
AuditingTest.test_mask | (self) |
Make sure the 'mask' function is properly masking potentially sensitive
information from strings.
|
Make sure the 'mask' function is properly masking potentially sensitive
information from strings.
| def test_mask(self):
"""
Make sure the 'mask' function is properly masking potentially sensitive
information from strings.
"""
safe_cmds = (
'/say hello to my little friend',
'@ccreate channel = for channeling',
'@create/drop some stuff',
... | [
"def",
"test_mask",
"(",
"self",
")",
":",
"safe_cmds",
"=",
"(",
"'/say hello to my little friend'",
",",
"'@ccreate channel = for channeling'",
",",
"'@create/drop some stuff'",
",",
"'@create rock'",
",",
"'@create a pretty shirt : evennia.contrib.clothing.Clothing'",
",",
"... | [
20,
4
] | [
74,
63
] | python | en | ['en', 'error', 'th'] | False |
AuditingTest.test_audit | (self) |
Make sure the 'audit' function is returning a dictionary based on values
parsed from the Session object.
|
Make sure the 'audit' function is returning a dictionary based on values
parsed from the Session object.
| def test_audit(self):
"""
Make sure the 'audit' function is returning a dictionary based on values
parsed from the Session object.
"""
log = self.session.audit(src='client', text=[['hello']])
obj = {k:v for k,v in log.iteritems() if k in ('direction', 'protocol', 'applica... | [
"def",
"test_audit",
"(",
"self",
")",
":",
"log",
"=",
"self",
".",
"session",
".",
"audit",
"(",
"src",
"=",
"'client'",
",",
"text",
"=",
"[",
"[",
"'hello'",
"]",
"]",
")",
"obj",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"log"... | [
76,
4
] | [
94,
48
] | python | en | ['en', 'error', 'th'] | False |
HelpEntry.access | (self, accessing_obj, access_type='read', default=False) |
Determines if another object has permission to access.
accessing_obj - object trying to access this one
access_type - type of access sought
default - what to return if no lock of access_type was found
|
Determines if another object has permission to access.
accessing_obj - object trying to access this one
access_type - type of access sought
default - what to return if no lock of access_type was found
| def access(self, accessing_obj, access_type='read', default=False):
"""
Determines if another object has permission to access.
accessing_obj - object trying to access this one
access_type - type of access sought
default - what to return if no lock of access_type was found
... | [
"def",
"access",
"(",
"self",
",",
"accessing_obj",
",",
"access_type",
"=",
"'read'",
",",
"default",
"=",
"False",
")",
":",
"return",
"self",
".",
"locks",
".",
"check",
"(",
"accessing_obj",
",",
"access_type",
"=",
"access_type",
",",
"default",
"=",
... | [
101,
4
] | [
108,
88
] | python | en | ['en', 'error', 'th'] | False |
PoolConfig.handleConfigTxn | (self, txn) |
Handles transaction of type POOL_CONFIG
:param txn:
|
Handles transaction of type POOL_CONFIG | def handleConfigTxn(self, txn) -> None:
"""
Handles transaction of type POOL_CONFIG
:param txn:
"""
if get_type(txn) == POOL_CONFIG:
self.writes = get_payload_data(txn)[WRITES] | [
"def",
"handleConfigTxn",
"(",
"self",
",",
"txn",
")",
"->",
"None",
":",
"if",
"get_type",
"(",
"txn",
")",
"==",
"POOL_CONFIG",
":",
"self",
".",
"writes",
"=",
"get_payload_data",
"(",
"txn",
")",
"[",
"WRITES",
"]"
] | [
16,
4
] | [
23,
55
] | python | en | ['en', 'error', 'th'] | False |
PoolConfig.processLedger | (self) |
Checks ledger config txns and perfomes recent one
:return:
|
Checks ledger config txns and perfomes recent one | def processLedger(self) -> None:
"""
Checks ledger config txns and perfomes recent one
:return:
"""
logger.debug('{} processing config ledger for any POOL_CONFIGs'.format(
self), extra={"tags": ["pool-config"]})
for _, txn in self.ledger.getAllTxn():
... | [
"def",
"processLedger",
"(",
"self",
")",
"->",
"None",
":",
"logger",
".",
"debug",
"(",
"'{} processing config ledger for any POOL_CONFIGs'",
".",
"format",
"(",
"self",
")",
",",
"extra",
"=",
"{",
"\"tags\"",
":",
"[",
"\"pool-config\"",
"]",
"}",
")",
"... | [
27,
4
] | [
37,
41
] | python | en | ['en', 'error', 'th'] | False |
SetEnvVar | (env_var, value) | Sets/unsets an environment variable to a given value. | Sets/unsets an environment variable to a given value. | def SetEnvVar(env_var, value):
"""Sets/unsets an environment variable to a given value."""
if value is not None:
environ[env_var] = value
elif env_var in environ:
del environ[env_var] | [
"def",
"SetEnvVar",
"(",
"env_var",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"environ",
"[",
"env_var",
"]",
"=",
"value",
"elif",
"env_var",
"in",
"environ",
":",
"del",
"environ",
"[",
"env_var",
"]"
] | [
64,
0
] | [
70,
24
] | python | en | ['en', 'en', 'en'] | True |
_ParseAndStripGTestFlags | (argv) | Parses and strips Google Test flags from argv. This is idempotent. | Parses and strips Google Test flags from argv. This is idempotent. | def _ParseAndStripGTestFlags(argv):
"""Parses and strips Google Test flags from argv. This is idempotent."""
# Suppresses the lint complaint about a global variable since we need it
# here to maintain module-wide state.
global _gtest_flags_are_parsed # pylint: disable-msg=W0603
if _gtest_flags_are_parsed:
... | [
"def",
"_ParseAndStripGTestFlags",
"(",
"argv",
")",
":",
"# Suppresses the lint complaint about a global variable since we need it",
"# here to maintain module-wide state.",
"global",
"_gtest_flags_are_parsed",
"# pylint: disable-msg=W0603",
"if",
"_gtest_flags_are_parsed",
":",
"return... | [
85,
0
] | [
111,
14
] | python | en | ['en', 'en', 'en'] | True |
GetFlag | (flag) | Returns the value of the given flag. | Returns the value of the given flag. | def GetFlag(flag):
"""Returns the value of the given flag."""
# In case GetFlag() is called before Main(), we always call
# _ParseAndStripGTestFlags() here to make sure the --gtest_* flags
# are parsed.
_ParseAndStripGTestFlags(sys.argv)
return _flag_map[flag] | [
"def",
"GetFlag",
"(",
"flag",
")",
":",
"# In case GetFlag() is called before Main(), we always call",
"# _ParseAndStripGTestFlags() here to make sure the --gtest_* flags",
"# are parsed.",
"_ParseAndStripGTestFlags",
"(",
"sys",
".",
"argv",
")",
"return",
"_flag_map",
"[",
"fl... | [
114,
0
] | [
122,
24
] | python | en | ['en', 'en', 'en'] | True |
GetSourceDir | () | Returns the absolute path of the directory where the .py files are. | Returns the absolute path of the directory where the .py files are. | def GetSourceDir():
"""Returns the absolute path of the directory where the .py files are."""
return os.path.abspath(GetFlag('source_dir')) | [
"def",
"GetSourceDir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"GetFlag",
"(",
"'source_dir'",
")",
")"
] | [
125,
0
] | [
128,
47
] | python | en | ['en', 'en', 'en'] | True |
GetBuildDir | () | Returns the absolute path of the directory where the test binaries are. | Returns the absolute path of the directory where the test binaries are. | def GetBuildDir():
"""Returns the absolute path of the directory where the test binaries are."""
return os.path.abspath(GetFlag('build_dir')) | [
"def",
"GetBuildDir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"GetFlag",
"(",
"'build_dir'",
")",
")"
] | [
131,
0
] | [
134,
46
] | python | en | ['en', 'en', 'en'] | True |
GetTempDir | () | Returns a directory for temporary files. | Returns a directory for temporary files. | def GetTempDir():
"""Returns a directory for temporary files."""
global _temp_dir
if not _temp_dir:
_temp_dir = tempfile.mkdtemp()
return _temp_dir | [
"def",
"GetTempDir",
"(",
")",
":",
"global",
"_temp_dir",
"if",
"not",
"_temp_dir",
":",
"_temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"return",
"_temp_dir"
] | [
146,
0
] | [
152,
18
] | python | en | ['en', 'en', 'en'] | True |
GetTestExecutablePath | (executable_name, build_dir=None) | Returns the absolute path of the test binary given its name.
The function will print a message and abort the program if the resulting file
doesn't exist.
Args:
executable_name: name of the test binary that the test script runs.
build_dir: directory where to look for executables, by default
... | Returns the absolute path of the test binary given its name. | def GetTestExecutablePath(executable_name, build_dir=None):
"""Returns the absolute path of the test binary given its name.
The function will print a message and abort the program if the resulting file
doesn't exist.
Args:
executable_name: name of the test binary that the test script runs.
build_dir: ... | [
"def",
"GetTestExecutablePath",
"(",
"executable_name",
",",
"build_dir",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"build_dir",
"or",
"GetBuildDir",
"(",
")",
",",
"executable_name",
... | [
155,
0
] | [
183,
13
] | python | en | ['en', 'en', 'en'] | True |
GetExitStatus | (exit_code) | Returns the argument to exit(), or -1 if exit() wasn't called.
Args:
exit_code: the result value of os.system(command).
| Returns the argument to exit(), or -1 if exit() wasn't called. | def GetExitStatus(exit_code):
"""Returns the argument to exit(), or -1 if exit() wasn't called.
Args:
exit_code: the result value of os.system(command).
"""
if os.name == 'nt':
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
# the argument to exit() directly.
return exit_co... | [
"def",
"GetExitStatus",
"(",
"exit_code",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns",
"# the argument to exit() directly.",
"return",
"exit_code",
"else",
":",
"# On Unix, os.WEXITSTATUS() must be ... | [
186,
0
] | [
203,
15
] | python | en | ['en', 'en', 'en'] | True |
Main | () | Runs the unit test. | Runs the unit test. | def Main():
"""Runs the unit test."""
# We must call _ParseAndStripGTestFlags() before calling
# unittest.main(). Otherwise the latter will be confused by the
# --gtest_* flags.
_ParseAndStripGTestFlags(sys.argv)
# The tested binaries should not be writing XML output files unless the
# script explicitly... | [
"def",
"Main",
"(",
")",
":",
"# We must call _ParseAndStripGTestFlags() before calling",
"# unittest.main(). Otherwise the latter will be confused by the",
"# --gtest_* flags.",
"_ParseAndStripGTestFlags",
"(",
"sys",
".",
"argv",
")",
"# The tested binaries should not be writing XML o... | [
305,
0
] | [
319,
21
] | python | en | ['en', 'fr', 'en'] | True |
Subprocess.__init__ | (self, command, working_dir=None, capture_stderr=True, env=None) | Changes into a specified directory, if provided, and executes a command.
Restores the old directory afterwards.
Args:
command: The command to run, in the form of sys.argv.
working_dir: The directory to change into.
capture_stderr: Determines whether to capture stderr in the output ... | Changes into a specified directory, if provided, and executes a command. | def __init__(self, command, working_dir=None, capture_stderr=True, env=None):
"""Changes into a specified directory, if provided, and executes a command.
Restores the old directory afterwards.
Args:
command: The command to run, in the form of sys.argv.
working_dir: The directory to c... | [
"def",
"__init__",
"(",
"self",
",",
"command",
",",
"working_dir",
"=",
"None",
",",
"capture_stderr",
"=",
"True",
",",
"env",
"=",
"None",
")",
":",
"# The subprocess module is the preferrable way of running programs",
"# since it is available and behaves consistently on... | [
207,
2
] | [
302,
40
] | python | en | ['en', 'en', 'en'] | True |
auto_fp16 | (apply_to=None, out_fp32=False) | Decorator to enable fp16 training automatically.
This decorator is useful when you write custom modules and want to support
mixed precision training. If inputs arguments are fp32 tensors, they will
be converted to fp16 automatically. Arguments other than fp32 tensors are
ignored.
Args:
app... | Decorator to enable fp16 training automatically. | def auto_fp16(apply_to=None, out_fp32=False):
"""Decorator to enable fp16 training automatically.
This decorator is useful when you write custom modules and want to support
mixed precision training. If inputs arguments are fp32 tensors, they will
be converted to fp16 automatically. Arguments other than... | [
"def",
"auto_fp16",
"(",
"apply_to",
"=",
"None",
",",
"out_fp32",
"=",
"False",
")",
":",
"def",
"auto_fp16_wrapper",
"(",
"old_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"old_func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
... | [
8,
0
] | [
84,
28
] | python | en | ['en', 'en', 'en'] | True |
force_fp32 | (apply_to=None, out_fp16=False) | Decorator to convert input arguments to fp32 in force.
This decorator is useful when you write custom modules and want to support
mixed precision training. If there are some inputs that must be processed
in fp32 mode, then this decorator can handle it. If inputs arguments are
fp16 tensors, they will be... | Decorator to convert input arguments to fp32 in force. | def force_fp32(apply_to=None, out_fp16=False):
"""Decorator to convert input arguments to fp32 in force.
This decorator is useful when you write custom modules and want to support
mixed precision training. If there are some inputs that must be processed
in fp32 mode, then this decorator can handle it. ... | [
"def",
"force_fp32",
"(",
"apply_to",
"=",
"None",
",",
"out_fp16",
"=",
"False",
")",
":",
"def",
"force_fp32_wrapper",
"(",
"old_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"old_func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*"... | [
87,
0
] | [
163,
29
] | python | en | ['en', 'en', 'en'] | True |
gather | (x, idx, method=2) |
implementation of a custom gather operation for faster backwards.
:param x: input with shape [N, D_1, ... D_d]
:param idx: indexing with shape [n_1, ..., n_m]
:param method: Choice of the method
:return: x[idx] with shape [n_1, ..., n_m, D_1, ... D_d]
|
implementation of a custom gather operation for faster backwards.
:param x: input with shape [N, D_1, ... D_d]
:param idx: indexing with shape [n_1, ..., n_m]
:param method: Choice of the method
:return: x[idx] with shape [n_1, ..., n_m, D_1, ... D_d]
| def gather(x, idx, method=2):
"""
implementation of a custom gather operation for faster backwards.
:param x: input with shape [N, D_1, ... D_d]
:param idx: indexing with shape [n_1, ..., n_m]
:param method: Choice of the method
:return: x[idx] with shape [n_1, ..., n_m, D_1, ... D_d]
"""
... | [
"def",
"gather",
"(",
"x",
",",
"idx",
",",
"method",
"=",
"2",
")",
":",
"if",
"method",
"==",
"0",
":",
"return",
"x",
"[",
"idx",
"]",
"elif",
"method",
"==",
"1",
":",
"x",
"=",
"x",
".",
"unsqueeze",
"(",
"1",
")",
"x",
"=",
"x",
".",
... | [
32,
0
] | [
63,
41
] | python | en | ['en', 'error', 'th'] | False |
radius_gaussian | (sq_r, sig, eps=1e-9) |
Compute a radius gaussian (gaussian of distance)
:param sq_r: input radiuses [dn, ..., d1, d0]
:param sig: extents of gaussians [d1, d0] or [d0] or float
:return: gaussian of sq_r [dn, ..., d1, d0]
|
Compute a radius gaussian (gaussian of distance)
:param sq_r: input radiuses [dn, ..., d1, d0]
:param sig: extents of gaussians [d1, d0] or [d0] or float
:return: gaussian of sq_r [dn, ..., d1, d0]
| def radius_gaussian(sq_r, sig, eps=1e-9):
"""
Compute a radius gaussian (gaussian of distance)
:param sq_r: input radiuses [dn, ..., d1, d0]
:param sig: extents of gaussians [d1, d0] or [d0] or float
:return: gaussian of sq_r [dn, ..., d1, d0]
"""
return torch.exp(-sq_r / (2 * sig**2 + eps)) | [
"def",
"radius_gaussian",
"(",
"sq_r",
",",
"sig",
",",
"eps",
"=",
"1e-9",
")",
":",
"return",
"torch",
".",
"exp",
"(",
"-",
"sq_r",
"/",
"(",
"2",
"*",
"sig",
"**",
"2",
"+",
"eps",
")",
")"
] | [
66,
0
] | [
73,
48
] | python | en | ['en', 'error', 'th'] | False |
closest_pool | (x, inds) |
Pools features from the closest neighbors. WARNING: this function assumes the neighbors are ordered.
:param x: [n1, d] features matrix
:param inds: [n2, max_num] Only the first column is used for pooling
:return: [n2, d] pooled features matrix
|
Pools features from the closest neighbors. WARNING: this function assumes the neighbors are ordered.
:param x: [n1, d] features matrix
:param inds: [n2, max_num] Only the first column is used for pooling
:return: [n2, d] pooled features matrix
| def closest_pool(x, inds):
"""
Pools features from the closest neighbors. WARNING: this function assumes the neighbors are ordered.
:param x: [n1, d] features matrix
:param inds: [n2, max_num] Only the first column is used for pooling
:return: [n2, d] pooled features matrix
"""
# Add a last... | [
"def",
"closest_pool",
"(",
"x",
",",
"inds",
")",
":",
"# Add a last row with minimum features for shadow pools",
"x",
"=",
"torch",
".",
"cat",
"(",
"(",
"x",
",",
"torch",
".",
"zeros_like",
"(",
"x",
"[",
":",
"1",
",",
":",
"]",
")",
")",
",",
"0"... | [
76,
0
] | [
88,
32
] | python | en | ['en', 'error', 'th'] | False |
max_pool | (x, inds) |
Pools features with the maximum values.
:param x: [n1, d] features matrix
:param inds: [n2, max_num] pooling indices
:return: [n2, d] pooled features matrix
|
Pools features with the maximum values.
:param x: [n1, d] features matrix
:param inds: [n2, max_num] pooling indices
:return: [n2, d] pooled features matrix
| def max_pool(x, inds):
"""
Pools features with the maximum values.
:param x: [n1, d] features matrix
:param inds: [n2, max_num] pooling indices
:return: [n2, d] pooled features matrix
"""
# Add a last row with minimum features for shadow pools
x = torch.cat((x, torch.zeros_like(x[:1, :]... | [
"def",
"max_pool",
"(",
"x",
",",
"inds",
")",
":",
"# Add a last row with minimum features for shadow pools",
"x",
"=",
"torch",
".",
"cat",
"(",
"(",
"x",
",",
"torch",
".",
"zeros_like",
"(",
"x",
"[",
":",
"1",
",",
":",
"]",
")",
")",
",",
"0",
... | [
91,
0
] | [
107,
23
] | python | en | ['en', 'error', 'th'] | False |
global_average | (x, batch_lengths) |
Block performing a global average over batch pooling
:param x: [N, D] input features
:param batch_lengths: [B] list of batch lengths
:return: [B, D] averaged features
|
Block performing a global average over batch pooling
:param x: [N, D] input features
:param batch_lengths: [B] list of batch lengths
:return: [B, D] averaged features
| def global_average(x, batch_lengths):
"""
Block performing a global average over batch pooling
:param x: [N, D] input features
:param batch_lengths: [B] list of batch lengths
:return: [B, D] averaged features
"""
# Loop over the clouds of the batch
averaged_features = []
i0 = 0
... | [
"def",
"global_average",
"(",
"x",
",",
"batch_lengths",
")",
":",
"# Loop over the clouds of the batch",
"averaged_features",
"=",
"[",
"]",
"i0",
"=",
"0",
"for",
"b_i",
",",
"length",
"in",
"enumerate",
"(",
"batch_lengths",
")",
":",
"# Average features for ea... | [
110,
0
] | [
130,
41
] | python | en | ['en', 'error', 'th'] | False |
KPConv.__init__ | (self, kernel_size, p_dim, in_channels, out_channels, KP_extent, radius,
fixed_kernel_points='center', KP_influence='linear', aggregation_mode='sum',
deformable=False, modulated=False) |
Initialize parameters for KPConvDeformable.
:param kernel_size: Number of kernel points.
:param p_dim: dimension of the point space.
:param in_channels: dimension of input features.
:param out_channels: dimension of output features.
:param KP_extent: influence radius of ... |
Initialize parameters for KPConvDeformable.
:param kernel_size: Number of kernel points.
:param p_dim: dimension of the point space.
:param in_channels: dimension of input features.
:param out_channels: dimension of output features.
:param KP_extent: influence radius of ... | def __init__(self, kernel_size, p_dim, in_channels, out_channels, KP_extent, radius,
fixed_kernel_points='center', KP_influence='linear', aggregation_mode='sum',
deformable=False, modulated=False):
"""
Initialize parameters for KPConvDeformable.
:param kernel_si... | [
"def",
"__init__",
"(",
"self",
",",
"kernel_size",
",",
"p_dim",
",",
"in_channels",
",",
"out_channels",
",",
"KP_extent",
",",
"radius",
",",
"fixed_kernel_points",
"=",
"'center'",
",",
"KP_influence",
"=",
"'linear'",
",",
"aggregation_mode",
"=",
"'sum'",
... | [
142,
4
] | [
211,
14
] | python | en | ['en', 'error', 'th'] | False |
KPConv.init_KP | (self) |
Initialize the kernel point positions in a sphere
:return: the tensor of kernel points
|
Initialize the kernel point positions in a sphere
:return: the tensor of kernel points
| def init_KP(self):
"""
Initialize the kernel point positions in a sphere
:return: the tensor of kernel points
"""
# Create one kernel disposition (as numpy array). Choose the KP distance to center thanks to the KP extent
K_points_numpy = load_kernels(self.radius,
... | [
"def",
"init_KP",
"(",
"self",
")",
":",
"# Create one kernel disposition (as numpy array). Choose the KP distance to center thanks to the KP extent",
"K_points_numpy",
"=",
"load_kernels",
"(",
"self",
".",
"radius",
",",
"self",
".",
"K",
",",
"dimension",
"=",
"self",
... | [
219,
4
] | [
232,
45
] | python | en | ['en', 'error', 'th'] | False |
BatchNormBlock.__init__ | (self, in_dim, use_bn, bn_momentum) |
Initialize a batch normalization block. If network does not use batch normalization, replace with biases.
:param in_dim: dimension input features
:param use_bn: boolean indicating if we use Batch Norm
:param bn_momentum: Batch norm momentum
|
Initialize a batch normalization block. If network does not use batch normalization, replace with biases.
:param in_dim: dimension input features
:param use_bn: boolean indicating if we use Batch Norm
:param bn_momentum: Batch norm momentum
| def __init__(self, in_dim, use_bn, bn_momentum):
"""
Initialize a batch normalization block. If network does not use batch normalization, replace with biases.
:param in_dim: dimension input features
:param use_bn: boolean indicating if we use Batch Norm
:param bn_momentum: Batch ... | [
"def",
"__init__",
"(",
"self",
",",
"in_dim",
",",
"use_bn",
",",
"bn_momentum",
")",
":",
"super",
"(",
"BatchNormBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"bn_momentum",
"=",
"bn_momentum",
"self",
".",
"use_bn",
"=",
"use_bn",... | [
428,
4
] | [
444,
14
] | python | en | ['en', 'error', 'th'] | False |
UnaryBlock.__init__ | (self, in_dim, out_dim, use_bn, bn_momentum, no_relu=False) |
Initialize a standard unary block with its ReLU and BatchNorm.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param use_bn: boolean indicating if we use Batch Norm
:param bn_momentum: Batch norm momentum
|
Initialize a standard unary block with its ReLU and BatchNorm.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param use_bn: boolean indicating if we use Batch Norm
:param bn_momentum: Batch norm momentum
| def __init__(self, in_dim, out_dim, use_bn, bn_momentum, no_relu=False):
"""
Initialize a standard unary block with its ReLU and BatchNorm.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param use_bn: boolean indicating if we use Batch Norm
... | [
"def",
"__init__",
"(",
"self",
",",
"in_dim",
",",
"out_dim",
",",
"use_bn",
",",
"bn_momentum",
",",
"no_relu",
"=",
"False",
")",
":",
"super",
"(",
"UnaryBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"bn_momentum",
"=",
"bn_mome... | [
468,
4
] | [
487,
14
] | python | en | ['en', 'error', 'th'] | False |
SimpleBlock.__init__ | (self, block_name, in_dim, out_dim, radius, layer_ind, config) |
Initialize a simple convolution block with its ReLU and BatchNorm.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param radius: current radius of convolution
:param config: parameters
|
Initialize a simple convolution block with its ReLU and BatchNorm.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param radius: current radius of convolution
:param config: parameters
| def __init__(self, block_name, in_dim, out_dim, radius, layer_ind, config):
"""
Initialize a simple convolution block with its ReLU and BatchNorm.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param radius: current radius of convolution
... | [
"def",
"__init__",
"(",
"self",
",",
"block_name",
",",
"in_dim",
",",
"out_dim",
",",
"radius",
",",
"layer_ind",
",",
"config",
")",
":",
"super",
"(",
"SimpleBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"# get KP_extent from current radius",
"curr... | [
505,
4
] | [
543,
14
] | python | en | ['en', 'error', 'th'] | False |
ResnetBottleneckBlock.__init__ | (self, block_name, in_dim, out_dim, radius, layer_ind, config) |
Initialize a resnet bottleneck block.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param radius: current radius of convolution
:param config: parameters
|
Initialize a resnet bottleneck block.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param radius: current radius of convolution
:param config: parameters
| def __init__(self, block_name, in_dim, out_dim, radius, layer_ind, config):
"""
Initialize a resnet bottleneck block.
:param in_dim: dimension input features
:param out_dim: dimension input features
:param radius: current radius of convolution
:param config: parameters
... | [
"def",
"__init__",
"(",
"self",
",",
"block_name",
",",
"in_dim",
",",
"out_dim",
",",
"radius",
",",
"layer_ind",
",",
"config",
")",
":",
"super",
"(",
"ResnetBottleneckBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"# get KP_extent from current radius... | [
562,
4
] | [
615,
14
] | python | en | ['en', 'error', 'th'] | False |
GlobalAverageBlock.__init__ | (self) |
Initialize a global average block with its ReLU and BatchNorm.
|
Initialize a global average block with its ReLU and BatchNorm.
| def __init__(self):
"""
Initialize a global average block with its ReLU and BatchNorm.
"""
super(GlobalAverageBlock, self).__init__()
return | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"GlobalAverageBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"return"
] | [
650,
4
] | [
655,
14
] | python | en | ['en', 'error', 'th'] | False |
NearestUpsampleBlock.__init__ | (self, layer_ind) |
Initialize a nearest upsampling block with its ReLU and BatchNorm.
|
Initialize a nearest upsampling block with its ReLU and BatchNorm.
| def __init__(self, layer_ind):
"""
Initialize a nearest upsampling block with its ReLU and BatchNorm.
"""
super(NearestUpsampleBlock, self).__init__()
self.layer_ind = layer_ind
return | [
"def",
"__init__",
"(",
"self",
",",
"layer_ind",
")",
":",
"super",
"(",
"NearestUpsampleBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"layer_ind",
"=",
"layer_ind",
"return"
] | [
663,
4
] | [
669,
14
] | python | en | ['en', 'error', 'th'] | False |
MaxPoolBlock.__init__ | (self, layer_ind) |
Initialize a max pooling block with its ReLU and BatchNorm.
|
Initialize a max pooling block with its ReLU and BatchNorm.
| def __init__(self, layer_ind):
"""
Initialize a max pooling block with its ReLU and BatchNorm.
"""
super(MaxPoolBlock, self).__init__()
self.layer_ind = layer_ind
return | [
"def",
"__init__",
"(",
"self",
",",
"layer_ind",
")",
":",
"super",
"(",
"MaxPoolBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"layer_ind",
"=",
"layer_ind",
"return"
] | [
681,
4
] | [
687,
14
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.