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
named_colorscales
()
Returns lowercased names of built-in continuous colorscales.
Returns lowercased names of built-in continuous colorscales.
def named_colorscales(): """ Returns lowercased names of built-in continuous colorscales. """ from _plotly_utils.basevalidators import ColorscaleValidator return [c for c in ColorscaleValidator("", "").named_colorscales]
[ "def", "named_colorscales", "(", ")", ":", "from", "_plotly_utils", ".", "basevalidators", "import", "ColorscaleValidator", "return", "[", "c", "for", "c", "in", "ColorscaleValidator", "(", "\"\"", ",", "\"\"", ")", ".", "named_colorscales", "]" ]
[ 801, 0 ]
[ 807, 69 ]
python
en
['en', 'error', 'th']
False
_normalize
(tensor, norm_layer)
Broadcast layer norm.
Broadcast layer norm.
def _normalize(tensor, norm_layer): """ Broadcast layer norm. """ is_cpu = tensor.device == 'cpu' or tensor.device.type == 'cpu' if APEX_LAYER_NORM and not is_cpu: # fused_layer_norm has a bug around multi-device networks. # https://github.com/NVIDIA/apex/issues/770 # https://github.com/NVIDIA/apex/issues/371 with torch.cuda.device(tensor.device): return norm_layer(tensor) else: return norm_layer(tensor)
[ "def", "_normalize", "(", "tensor", ",", "norm_layer", ")", ":", "is_cpu", "=", "tensor", ".", "device", "==", "'cpu'", "or", "tensor", ".", "device", ".", "type", "==", "'cpu'", "if", "APEX_LAYER_NORM", "and", "not", "is_cpu", ":", "# fused_layer_norm has a bug around multi-device networks.", "# https://github.com/NVIDIA/apex/issues/770", "# https://github.com/NVIDIA/apex/issues/371", "with", "torch", ".", "cuda", ".", "device", "(", "tensor", ".", "device", ")", ":", "return", "norm_layer", "(", "tensor", ")", "else", ":", "return", "norm_layer", "(", "tensor", ")" ]
[ 43, 0 ]
[ 55, 33 ]
python
en
['en', 'error', 'th']
False
_create_embeddings
(dictionary, embedding_size, padding_idx)
Create and initialize word embeddings.
Create and initialize word embeddings.
def _create_embeddings(dictionary, embedding_size, padding_idx): """ Create and initialize word embeddings. """ e = nn.Embedding(len(dictionary), embedding_size, padding_idx) nn.init.normal_(e.weight, mean=0, std=embedding_size ** -0.5) nn.init.constant_(e.weight[padding_idx], 0) return e
[ "def", "_create_embeddings", "(", "dictionary", ",", "embedding_size", ",", "padding_idx", ")", ":", "e", "=", "nn", ".", "Embedding", "(", "len", "(", "dictionary", ")", ",", "embedding_size", ",", "padding_idx", ")", "nn", ".", "init", ".", "normal_", "(", "e", ".", "weight", ",", "mean", "=", "0", ",", "std", "=", "embedding_size", "**", "-", "0.5", ")", "nn", ".", "init", ".", "constant_", "(", "e", ".", "weight", "[", "padding_idx", "]", ",", "0", ")", "return", "e" ]
[ 58, 0 ]
[ 65, 12 ]
python
en
['en', 'error', 'th']
False
get_n_positions_from_options
(opt)
Determine n_positions from options dict.
Determine n_positions from options dict.
def get_n_positions_from_options(opt): """ Determine n_positions from options dict. """ if opt.get('n_positions'): # if the number of positions is explicitly provided, use that n_positions = opt['n_positions'] else: # else, use the worst case from truncate n_positions = max( opt.get('truncate') or 0, opt.get('text_truncate') or 0, opt.get('label_truncate') or 0, ) if n_positions == 0: n_positions = 1024 return n_positions
[ "def", "get_n_positions_from_options", "(", "opt", ")", ":", "if", "opt", ".", "get", "(", "'n_positions'", ")", ":", "# if the number of positions is explicitly provided, use that", "n_positions", "=", "opt", "[", "'n_positions'", "]", "else", ":", "# else, use the worst case from truncate", "n_positions", "=", "max", "(", "opt", ".", "get", "(", "'truncate'", ")", "or", "0", ",", "opt", ".", "get", "(", "'text_truncate'", ")", "or", "0", ",", "opt", ".", "get", "(", "'label_truncate'", ")", "or", "0", ",", ")", "if", "n_positions", "==", "0", ":", "n_positions", "=", "1024", "return", "n_positions" ]
[ 68, 0 ]
[ 84, 22 ]
python
en
['en', 'error', 'th']
False
create_position_codes
(n_pos, dim, out)
Create positional codes and store them in ``out``.
Create positional codes and store them in ``out``.
def create_position_codes(n_pos, dim, out): """ Create positional codes and store them in ``out``. """ position_enc = np.array( [ [pos / np.power(10000, 2 * j / dim) for j in range(dim // 2)] for pos in range(n_pos) ] ) out.detach_() out.requires_grad = False out[:, 0::2] = torch.FloatTensor(np.sin(position_enc)).type_as(out) out[:, 1::2] = torch.FloatTensor(np.cos(position_enc)).type_as(out)
[ "def", "create_position_codes", "(", "n_pos", ",", "dim", ",", "out", ")", ":", "position_enc", "=", "np", ".", "array", "(", "[", "[", "pos", "/", "np", ".", "power", "(", "10000", ",", "2", "*", "j", "/", "dim", ")", "for", "j", "in", "range", "(", "dim", "//", "2", ")", "]", "for", "pos", "in", "range", "(", "n_pos", ")", "]", ")", "out", ".", "detach_", "(", ")", "out", ".", "requires_grad", "=", "False", "out", "[", ":", ",", "0", ":", ":", "2", "]", "=", "torch", ".", "FloatTensor", "(", "np", ".", "sin", "(", "position_enc", ")", ")", ".", "type_as", "(", "out", ")", "out", "[", ":", ",", "1", ":", ":", "2", "]", "=", "torch", ".", "FloatTensor", "(", "np", ".", "cos", "(", "position_enc", ")", ")", ".", "type_as", "(", "out", ")" ]
[ 270, 0 ]
[ 284, 71 ]
python
en
['en', 'error', 'th']
False
TransformerMemNetModel.encode_cand
(self, words)
Encode the candidates.
Encode the candidates.
def encode_cand(self, words): """ Encode the candidates. """ if words is None: return None # flatten if there are many candidates if words.dim() == 3: oldshape = words.shape words = words.reshape(oldshape[0] * oldshape[1], oldshape[2]) else: oldshape = None encoded = self.cand_encoder(words) if oldshape is not None: encoded = encoded.reshape(oldshape[0], oldshape[1], -1) return encoded
[ "def", "encode_cand", "(", "self", ",", "words", ")", ":", "if", "words", "is", "None", ":", "return", "None", "# flatten if there are many candidates", "if", "words", ".", "dim", "(", ")", "==", "3", ":", "oldshape", "=", "words", ".", "shape", "words", "=", "words", ".", "reshape", "(", "oldshape", "[", "0", "]", "*", "oldshape", "[", "1", "]", ",", "oldshape", "[", "2", "]", ")", "else", ":", "oldshape", "=", "None", "encoded", "=", "self", ".", "cand_encoder", "(", "words", ")", "if", "oldshape", "is", "not", "None", ":", "encoded", "=", "encoded", ".", "reshape", "(", "oldshape", "[", "0", "]", ",", "oldshape", "[", "1", "]", ",", "-", "1", ")", "return", "encoded" ]
[ 199, 4 ]
[ 218, 22 ]
python
en
['en', 'error', 'th']
False
TransformerMemNetModel.encode_context_memory
(self, context_w, memories_w, context_segments=None)
Encode the context and memories.
Encode the context and memories.
def encode_context_memory(self, context_w, memories_w, context_segments=None): """ Encode the context and memories. """ # [batch, d] if context_w is None: # it's possible that only candidates were passed into the # forward function, return None here for LHS representation return None, None context_h = self.context_encoder(context_w, segments=context_segments) if memories_w is None: return [], context_h bsz = memories_w.size(0) memories_w = memories_w.view(-1, memories_w.size(-1)) memories_h = self.memory_transformer(memories_w) memories_h = memories_h.view(bsz, -1, memories_h.size(-1)) context_h = context_h.unsqueeze(1) context_h, weights = self.attender(context_h, memories_h) return weights, context_h
[ "def", "encode_context_memory", "(", "self", ",", "context_w", ",", "memories_w", ",", "context_segments", "=", "None", ")", ":", "# [batch, d]", "if", "context_w", "is", "None", ":", "# it's possible that only candidates were passed into the", "# forward function, return None here for LHS representation", "return", "None", ",", "None", "context_h", "=", "self", ".", "context_encoder", "(", "context_w", ",", "segments", "=", "context_segments", ")", "if", "memories_w", "is", "None", ":", "return", "[", "]", ",", "context_h", "bsz", "=", "memories_w", ".", "size", "(", "0", ")", "memories_w", "=", "memories_w", ".", "view", "(", "-", "1", ",", "memories_w", ".", "size", "(", "-", "1", ")", ")", "memories_h", "=", "self", ".", "memory_transformer", "(", "memories_w", ")", "memories_h", "=", "memories_h", ".", "view", "(", "bsz", ",", "-", "1", ",", "memories_h", ".", "size", "(", "-", "1", ")", ")", "context_h", "=", "context_h", ".", "unsqueeze", "(", "1", ")", "context_h", ",", "weights", "=", "self", ".", "attender", "(", "context_h", ",", "memories_h", ")", "return", "weights", ",", "context_h" ]
[ 220, 4 ]
[ 243, 33 ]
python
en
['en', 'error', 'th']
False
TransformerMemNetModel.forward
(self, xs, mems, cands, context_segments=None)
Forward pass. :param LongTensor[batch,seqlen] xs: input tokens IDs :param LongTensor[batch,num_mems,seqlen] mems: memory token IDs :param LongTensor[batch,num_cands,seqlen] cands: candidate token IDs :param LongTensor[batch,seqlen] context_segments: segment IDs for xs, used if n_segments is > 0 for the context encoder
Forward pass.
def forward(self, xs, mems, cands, context_segments=None): """ Forward pass. :param LongTensor[batch,seqlen] xs: input tokens IDs :param LongTensor[batch,num_mems,seqlen] mems: memory token IDs :param LongTensor[batch,num_cands,seqlen] cands: candidate token IDs :param LongTensor[batch,seqlen] context_segments: segment IDs for xs, used if n_segments is > 0 for the context encoder """ # encode the context and memories together weights, context_h = self.encode_context_memory( xs, mems, context_segments=context_segments ) # encode the candidates cands_h = self.encode_cand(cands) # possibly normalize the context and candidate representations if self.opt['normalize_sent_emb']: context_h = context_h / context_h.norm(2, dim=1, keepdim=True) cands_h = cands_h / cands_h.norm(2, dim=1, keepdim=True) return context_h, cands_h
[ "def", "forward", "(", "self", ",", "xs", ",", "mems", ",", "cands", ",", "context_segments", "=", "None", ")", ":", "# encode the context and memories together", "weights", ",", "context_h", "=", "self", ".", "encode_context_memory", "(", "xs", ",", "mems", ",", "context_segments", "=", "context_segments", ")", "# encode the candidates", "cands_h", "=", "self", ".", "encode_cand", "(", "cands", ")", "# possibly normalize the context and candidate representations", "if", "self", ".", "opt", "[", "'normalize_sent_emb'", "]", ":", "context_h", "=", "context_h", "/", "context_h", ".", "norm", "(", "2", ",", "dim", "=", "1", ",", "keepdim", "=", "True", ")", "cands_h", "=", "cands_h", "/", "cands_h", ".", "norm", "(", "2", ",", "dim", "=", "1", ",", "keepdim", "=", "True", ")", "return", "context_h", ",", "cands_h" ]
[ 245, 4 ]
[ 267, 33 ]
python
en
['en', 'error', 'th']
False
TransformerResponseWrapper.forward
(self, *args)
Forward pass.
Forward pass.
def forward(self, *args): """ Forward pass. """ return self.mlp(self.transformer(*args))
[ "def", "forward", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "mlp", "(", "self", ".", "transformer", "(", "*", "args", ")", ")" ]
[ 304, 4 ]
[ 308, 48 ]
python
en
['en', 'error', 'th']
False
TransformerLinearWrapper.forward
(self, *args)
Forward pass. Apply transformer, then additional linear layer.
Forward pass.
def forward(self, *args): """ Forward pass. Apply transformer, then additional linear layer. """ context_h = self.transformer(*args) return self.additional_linear_layer(context_h)
[ "def", "forward", "(", "self", ",", "*", "args", ")", ":", "context_h", "=", "self", ".", "transformer", "(", "*", "args", ")", "return", "self", ".", "additional_linear_layer", "(", "context_h", ")" ]
[ 322, 4 ]
[ 329, 54 ]
python
en
['en', 'error', 'th']
False
TransformerEncoder.forward_embedding
( self, input: torch.LongTensor, positions: Optional[torch.LongTensor] = None, segments: Optional[torch.LongTensor] = None, )
Embed tokens prior to feeding into transformer. :param LongTensor[batch,seqlen] input: The input IDs :param LongTensor[batch,seqlen] positions: Positions for input IDs :param LongTensor[batch,seqlen]: If provided, additionally adds ``segments`` as extra embedding features. :return (tensor, mask): return embedded input and mask
Embed tokens prior to feeding into transformer.
def forward_embedding( self, input: torch.LongTensor, positions: Optional[torch.LongTensor] = None, segments: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, torch.BoolTensor]: """ Embed tokens prior to feeding into transformer. :param LongTensor[batch,seqlen] input: The input IDs :param LongTensor[batch,seqlen] positions: Positions for input IDs :param LongTensor[batch,seqlen]: If provided, additionally adds ``segments`` as extra embedding features. :return (tensor, mask): return embedded input and mask """ mask = input != self.padding_idx if positions is None: positions = (mask.cumsum(dim=1, dtype=torch.int64) - 1).clamp_(min=0) tensor = self.embeddings(input) if self.embeddings_scale: tensor = tensor * np.sqrt(self.dim) if positions.max().item() > self.n_positions: warn_once( 'You are inputting a sequence of {x} length, but only have ' '--n-positions {y}. Set --truncate or increase --n-positions'.format( x=positions.max().item(), y=self.n_positions ) ) position_embs = self.position_embeddings(positions).expand_as(tensor) tensor = tensor + position_embs if self.n_segments >= 1: if segments is None: segments = torch.zeros_like(input) # type: ignore tensor = tensor + self.segment_embeddings(segments) return tensor, mask
[ "def", "forward_embedding", "(", "self", ",", "input", ":", "torch", ".", "LongTensor", ",", "positions", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ",", "segments", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ",", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "BoolTensor", "]", ":", "mask", "=", "input", "!=", "self", ".", "padding_idx", "if", "positions", "is", "None", ":", "positions", "=", "(", "mask", ".", "cumsum", "(", "dim", "=", "1", ",", "dtype", "=", "torch", ".", "int64", ")", "-", "1", ")", ".", "clamp_", "(", "min", "=", "0", ")", "tensor", "=", "self", ".", "embeddings", "(", "input", ")", "if", "self", ".", "embeddings_scale", ":", "tensor", "=", "tensor", "*", "np", ".", "sqrt", "(", "self", ".", "dim", ")", "if", "positions", ".", "max", "(", ")", ".", "item", "(", ")", ">", "self", ".", "n_positions", ":", "warn_once", "(", "'You are inputting a sequence of {x} length, but only have '", "'--n-positions {y}. Set --truncate or increase --n-positions'", ".", "format", "(", "x", "=", "positions", ".", "max", "(", ")", ".", "item", "(", ")", ",", "y", "=", "self", ".", "n_positions", ")", ")", "position_embs", "=", "self", ".", "position_embeddings", "(", "positions", ")", ".", "expand_as", "(", "tensor", ")", "tensor", "=", "tensor", "+", "position_embs", "if", "self", ".", "n_segments", ">=", "1", ":", "if", "segments", "is", "None", ":", "segments", "=", "torch", ".", "zeros_like", "(", "input", ")", "# type: ignore", "tensor", "=", "tensor", "+", "self", ".", "segment_embeddings", "(", "segments", ")", "return", "tensor", ",", "mask" ]
[ 471, 4 ]
[ 512, 27 ]
python
en
['en', 'error', 'th']
False
TransformerEncoder.forward_layers
( self, tensor: torch.Tensor, mask: torch.BoolTensor )
Apply transformer layers to input. :param tensor: embedded input :param mask: mask of input :return tensor: return embedding after applying transformer layers
Apply transformer layers to input.
def forward_layers( self, tensor: torch.Tensor, mask: torch.BoolTensor ) -> torch.Tensor: """ Apply transformer layers to input. :param tensor: embedded input :param mask: mask of input :return tensor: return embedding after applying transformer layers """ if getattr(self.layers, 'is_model_parallel', False): # factored out for readability. It is equivalent to the other # condition tensor = self._apply_model_parallel(tensor, mask) else: for i in range(self.n_layers): tensor = self.layers[i](tensor, mask) return tensor
[ "def", "forward_layers", "(", "self", ",", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "BoolTensor", ")", "->", "torch", ".", "Tensor", ":", "if", "getattr", "(", "self", ".", "layers", ",", "'is_model_parallel'", ",", "False", ")", ":", "# factored out for readability. It is equivalent to the other", "# condition", "tensor", "=", "self", ".", "_apply_model_parallel", "(", "tensor", ",", "mask", ")", "else", ":", "for", "i", "in", "range", "(", "self", ".", "n_layers", ")", ":", "tensor", "=", "self", ".", "layers", "[", "i", "]", "(", "tensor", ",", "mask", ")", "return", "tensor" ]
[ 514, 4 ]
[ 536, 21 ]
python
en
['en', 'error', 'th']
False
TransformerEncoder.reduce_output
( self, tensor: torch.Tensor, mask: torch.BoolTensor )
Reduce transformer output at end of forward pass. :param tensor: encoded input :param mask: mask for encoded input :return (tensor, mask): returns the reduced tensor, and mask if appropriate
Reduce transformer output at end of forward pass.
def reduce_output( self, tensor: torch.Tensor, mask: torch.BoolTensor ) -> Tuple[torch.Tensor, Optional[torch.BoolTensor]]: """ Reduce transformer output at end of forward pass. :param tensor: encoded input :param mask: mask for encoded input :return (tensor, mask): returns the reduced tensor, and mask if appropriate """ tensor *= self.output_scaling if self.reduction_type == 'first': return tensor[:, 0, :], None elif self.reduction_type == 'max': return tensor.max(dim=1)[0], None elif self.reduction_type == 'mean': divisor = mask.float().sum(dim=1).unsqueeze(-1).clamp(min=1).type_as(tensor) output = tensor.sum(dim=1) / divisor return output, None elif self.reduction_type is None or 'none' in self.reduction_type: return tensor, mask else: raise ValueError( "Can't handle --reduction-type {}".format(self.reduction_type) )
[ "def", "reduce_output", "(", "self", ",", "tensor", ":", "torch", ".", "Tensor", ",", "mask", ":", "torch", ".", "BoolTensor", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "Optional", "[", "torch", ".", "BoolTensor", "]", "]", ":", "tensor", "*=", "self", ".", "output_scaling", "if", "self", ".", "reduction_type", "==", "'first'", ":", "return", "tensor", "[", ":", ",", "0", ",", ":", "]", ",", "None", "elif", "self", ".", "reduction_type", "==", "'max'", ":", "return", "tensor", ".", "max", "(", "dim", "=", "1", ")", "[", "0", "]", ",", "None", "elif", "self", ".", "reduction_type", "==", "'mean'", ":", "divisor", "=", "mask", ".", "float", "(", ")", ".", "sum", "(", "dim", "=", "1", ")", ".", "unsqueeze", "(", "-", "1", ")", ".", "clamp", "(", "min", "=", "1", ")", ".", "type_as", "(", "tensor", ")", "output", "=", "tensor", ".", "sum", "(", "dim", "=", "1", ")", "/", "divisor", "return", "output", ",", "None", "elif", "self", ".", "reduction_type", "is", "None", "or", "'none'", "in", "self", ".", "reduction_type", ":", "return", "tensor", ",", "mask", "else", ":", "raise", "ValueError", "(", "\"Can't handle --reduction-type {}\"", ".", "format", "(", "self", ".", "reduction_type", ")", ")" ]
[ 538, 4 ]
[ 566, 13 ]
python
en
['en', 'error', 'th']
False
TransformerEncoder.forward
( # type: ignore self, input: torch.LongTensor, positions: Optional[torch.LongTensor] = None, segments: Optional[torch.LongTensor] = None, )
Forward pass. :param LongTensor[batch,seqlen] input: The input IDs :param LongTensor[batch,seqlen] positions: Positions for input IDs :param LongTensor[batch,seqlen] segments: If provided, additionally adds ``segments`` as extra embedding features.
Forward pass.
def forward( # type: ignore self, input: torch.LongTensor, positions: Optional[torch.LongTensor] = None, segments: Optional[torch.LongTensor] = None, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.BoolTensor]]: """ Forward pass. :param LongTensor[batch,seqlen] input: The input IDs :param LongTensor[batch,seqlen] positions: Positions for input IDs :param LongTensor[batch,seqlen] segments: If provided, additionally adds ``segments`` as extra embedding features. """ # embed input tensor, mask = self.forward_embedding(input, positions, segments) if self.variant == 'xlm' or self.variant == 'bart': tensor = _normalize(tensor, self.norm_embeddings) # --dropout on the embeddings tensor = self.dropout(tensor) tensor *= mask.unsqueeze(-1).type_as(tensor) # apply transformer layers tensor = self.forward_layers(tensor, mask) if self.variant == 'prelayernorm': tensor = _normalize(tensor, self.norm_embeddings) # reduce output tensor, out_mask = self.reduce_output(tensor, mask) if out_mask is not None: return tensor, out_mask else: return tensor
[ "def", "forward", "(", "# type: ignore", "self", ",", "input", ":", "torch", ".", "LongTensor", ",", "positions", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ",", "segments", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ",", ")", "->", "Union", "[", "torch", ".", "Tensor", ",", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ".", "BoolTensor", "]", "]", ":", "# embed input", "tensor", ",", "mask", "=", "self", ".", "forward_embedding", "(", "input", ",", "positions", ",", "segments", ")", "if", "self", ".", "variant", "==", "'xlm'", "or", "self", ".", "variant", "==", "'bart'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm_embeddings", ")", "# --dropout on the embeddings", "tensor", "=", "self", ".", "dropout", "(", "tensor", ")", "tensor", "*=", "mask", ".", "unsqueeze", "(", "-", "1", ")", ".", "type_as", "(", "tensor", ")", "# apply transformer layers", "tensor", "=", "self", ".", "forward_layers", "(", "tensor", ",", "mask", ")", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm_embeddings", ")", "# reduce output", "tensor", ",", "out_mask", "=", "self", ".", "reduce_output", "(", "tensor", ",", "mask", ")", "if", "out_mask", "is", "not", "None", ":", "return", "tensor", ",", "out_mask", "else", ":", "return", "tensor" ]
[ 568, 4 ]
[ 606, 25 ]
python
en
['en', 'error', 'th']
False
TransformerEncoder._apply_model_parallel
(self, tensor, mask)
Pipeline application of model parallelism.
Pipeline application of model parallelism.
def _apply_model_parallel(self, tensor, mask): """ Pipeline application of model parallelism. """ chunks = PipelineHelper.split((tensor, mask)) work_items = PipelineHelper.schedule_work_items(self.layers, chunks) for chunk_idx, layer_nos, next_device in work_items: s_tensor, s_mask = chunks[chunk_idx] for layer_no in layer_nos: s_tensor = self.layers[layer_no](s_tensor, s_mask) chunks[chunk_idx] = PipelineHelper.chunk_to((s_tensor, s_mask), next_device) tensor_out, mask_out = PipelineHelper.join(chunks) return tensor_out
[ "def", "_apply_model_parallel", "(", "self", ",", "tensor", ",", "mask", ")", ":", "chunks", "=", "PipelineHelper", ".", "split", "(", "(", "tensor", ",", "mask", ")", ")", "work_items", "=", "PipelineHelper", ".", "schedule_work_items", "(", "self", ".", "layers", ",", "chunks", ")", "for", "chunk_idx", ",", "layer_nos", ",", "next_device", "in", "work_items", ":", "s_tensor", ",", "s_mask", "=", "chunks", "[", "chunk_idx", "]", "for", "layer_no", "in", "layer_nos", ":", "s_tensor", "=", "self", ".", "layers", "[", "layer_no", "]", "(", "s_tensor", ",", "s_mask", ")", "chunks", "[", "chunk_idx", "]", "=", "PipelineHelper", ".", "chunk_to", "(", "(", "s_tensor", ",", "s_mask", ")", ",", "next_device", ")", "tensor_out", ",", "mask_out", "=", "PipelineHelper", ".", "join", "(", "chunks", ")", "return", "tensor_out" ]
[ 608, 4 ]
[ 622, 25 ]
python
en
['en', 'error', 'th']
False
TransformerEncoderLayer.forward
(self, tensor, mask)
Forward pass.
Forward pass.
def forward(self, tensor, mask): """ Forward pass. """ residual = tensor if self.variant == 'prelayernorm': tensor = _normalize(tensor, self.norm1) attended_tensor = self.attention(tensor, mask=mask)[0] tensor = residual + self.dropout(attended_tensor) if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart': tensor = _normalize(tensor, self.norm1) residual = tensor if self.variant == 'prelayernorm': tensor = _normalize(tensor, self.norm2) tensor = residual + self.dropout(self.ffn(tensor)) if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart': tensor = _normalize(tensor, self.norm2) tensor *= mask.unsqueeze(-1).type_as(tensor) return tensor
[ "def", "forward", "(", "self", ",", "tensor", ",", "mask", ")", ":", "residual", "=", "tensor", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm1", ")", "attended_tensor", "=", "self", ".", "attention", "(", "tensor", ",", "mask", "=", "mask", ")", "[", "0", "]", "tensor", "=", "residual", "+", "self", ".", "dropout", "(", "attended_tensor", ")", "if", "self", ".", "variant", "==", "'aiayn'", "or", "self", ".", "variant", "==", "'xlm'", "or", "self", ".", "variant", "==", "'bart'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm1", ")", "residual", "=", "tensor", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm2", ")", "tensor", "=", "residual", "+", "self", ".", "dropout", "(", "self", ".", "ffn", "(", "tensor", ")", ")", "if", "self", ".", "variant", "==", "'aiayn'", "or", "self", ".", "variant", "==", "'xlm'", "or", "self", ".", "variant", "==", "'bart'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm2", ")", "tensor", "*=", "mask", ".", "unsqueeze", "(", "-", "1", ")", ".", "type_as", "(", "tensor", ")", "return", "tensor" ]
[ 659, 4 ]
[ 677, 21 ]
python
en
['en', 'error', 'th']
False
TransformerDecoder.forward_embedding
( self, input: torch.LongTensor, positions: Optional[torch.LongTensor] = None, segments: Optional[torch.LongTensor] = None, )
Embed tokens prior to feeding into transformer. :param LongTensor[batch, seqlen] input: The target input IDs :param LongTensor[batch, seqlen] positions: Positions for input IDs. If None, computes defaults. :param LongTensor[batch, seqlen] segements: Segment IDs for extra embedding features. If None, not used. :return (tensor, mask): embeded input and mask
Embed tokens prior to feeding into transformer.
def forward_embedding( self, input: torch.LongTensor, positions: Optional[torch.LongTensor] = None, segments: Optional[torch.LongTensor] = None, ): """ Embed tokens prior to feeding into transformer. :param LongTensor[batch, seqlen] input: The target input IDs :param LongTensor[batch, seqlen] positions: Positions for input IDs. If None, computes defaults. :param LongTensor[batch, seqlen] segements: Segment IDs for extra embedding features. If None, not used. :return (tensor, mask): embeded input and mask """ tensor = self.embeddings(input) if self.embeddings_scale: tensor = tensor * np.sqrt(self.dim) if self.variant == 'xlm': tensor = _normalize(tensor, self.norm_embeddings) if positions.max().item() > self.n_positions: warn_once( 'You are inputting a sequence of {x} length, but only have ' '--n-positions {y}. Set --truncate or increase --n-positions'.format( x=positions.max().item(), y=self.n_positions ) ) tensor = tensor + self.position_embeddings(positions).expand_as(tensor) if self.variant == 'bart': tensor = _normalize(tensor, self.norm_embeddings) return tensor
[ "def", "forward_embedding", "(", "self", ",", "input", ":", "torch", ".", "LongTensor", ",", "positions", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ",", "segments", ":", "Optional", "[", "torch", ".", "LongTensor", "]", "=", "None", ",", ")", ":", "tensor", "=", "self", ".", "embeddings", "(", "input", ")", "if", "self", ".", "embeddings_scale", ":", "tensor", "=", "tensor", "*", "np", ".", "sqrt", "(", "self", ".", "dim", ")", "if", "self", ".", "variant", "==", "'xlm'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm_embeddings", ")", "if", "positions", ".", "max", "(", ")", ".", "item", "(", ")", ">", "self", ".", "n_positions", ":", "warn_once", "(", "'You are inputting a sequence of {x} length, but only have '", "'--n-positions {y}. Set --truncate or increase --n-positions'", ".", "format", "(", "x", "=", "positions", ".", "max", "(", ")", ".", "item", "(", ")", ",", "y", "=", "self", ".", "n_positions", ")", ")", "tensor", "=", "tensor", "+", "self", ".", "position_embeddings", "(", "positions", ")", ".", "expand_as", "(", "tensor", ")", "if", "self", ".", "variant", "==", "'bart'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm_embeddings", ")", "return", "tensor" ]
[ 785, 4 ]
[ 820, 21 ]
python
en
['en', 'error', 'th']
False
TransformerDecoder.forward_layers
( self, tensor: torch.Tensor, encoder_output: torch.Tensor, encoder_mask: torch.Tensor, incr_state: Dict[int, torch.Tensor], )
Forward pass of decoder layers. :param tensor: embedded input tensor for the decoder :param enc_out: encoder outputs :param enc_mask: encoder output mask :param incr_state: Dict mapping layer_idx to incremental state :return (tensor, new_incr_state): return encoding after applying decoder layers, as well as new incremental decoding state.
Forward pass of decoder layers.
def forward_layers( self, tensor: torch.Tensor, encoder_output: torch.Tensor, encoder_mask: torch.Tensor, incr_state: Dict[int, torch.Tensor], ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]: """ Forward pass of decoder layers. :param tensor: embedded input tensor for the decoder :param enc_out: encoder outputs :param enc_mask: encoder output mask :param incr_state: Dict mapping layer_idx to incremental state :return (tensor, new_incr_state): return encoding after applying decoder layers, as well as new incremental decoding state. """ new_incr_state = {} if getattr(self.layers, 'is_model_parallel', False): tensor, new_incr_state = self._apply_model_parallel( tensor, encoder_output, encoder_mask, incr_state ) else: for idx, layer in enumerate(self.layers): tensor, new_incr_state[idx] = layer( x=tensor, encoder_output=encoder_output, encoder_mask=encoder_mask, incr_state=incr_state.get(idx), ) return tensor, new_incr_state
[ "def", "forward_layers", "(", "self", ",", "tensor", ":", "torch", ".", "Tensor", ",", "encoder_output", ":", "torch", ".", "Tensor", ",", "encoder_mask", ":", "torch", ".", "Tensor", ",", "incr_state", ":", "Dict", "[", "int", ",", "torch", ".", "Tensor", "]", ",", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", ":", "new_incr_state", "=", "{", "}", "if", "getattr", "(", "self", ".", "layers", ",", "'is_model_parallel'", ",", "False", ")", ":", "tensor", ",", "new_incr_state", "=", "self", ".", "_apply_model_parallel", "(", "tensor", ",", "encoder_output", ",", "encoder_mask", ",", "incr_state", ")", "else", ":", "for", "idx", ",", "layer", "in", "enumerate", "(", "self", ".", "layers", ")", ":", "tensor", ",", "new_incr_state", "[", "idx", "]", "=", "layer", "(", "x", "=", "tensor", ",", "encoder_output", "=", "encoder_output", ",", "encoder_mask", "=", "encoder_mask", ",", "incr_state", "=", "incr_state", ".", "get", "(", "idx", ")", ",", ")", "return", "tensor", ",", "new_incr_state" ]
[ 822, 4 ]
[ 859, 37 ]
python
en
['en', 'error', 'th']
False
TransformerDecoder.forward
(self, input, encoder_state, incr_state=None)
Forward pass. :param LongTensor[batch,seqlen] input: The decoder inputs (partial or full decoded token IDs). :param encoder_state: Output from the encoder module forward pass. :param incr_state: The incremental state: a dictionary whose keys index the layers and whose values contain the incremental state for each layer.
Forward pass.
def forward(self, input, encoder_state, incr_state=None): """ Forward pass. :param LongTensor[batch,seqlen] input: The decoder inputs (partial or full decoded token IDs). :param encoder_state: Output from the encoder module forward pass. :param incr_state: The incremental state: a dictionary whose keys index the layers and whose values contain the incremental state for each layer. """ encoder_output, encoder_mask = encoder_state seq_len = input.size(1) positions = input.new(seq_len).long() positions = torch.arange(seq_len, out=positions).unsqueeze(0) if incr_state is not None: # We're doing incremental decoding, so select only the most recent position input = input[:, -1:] if positions is not None: positions = positions[:, -1:] else: incr_state = {} tensor = self.forward_embedding(input, positions) tensor = self.dropout(tensor) # --dropout tensor, new_incr_state = self.forward_layers( tensor, encoder_output, encoder_mask, incr_state ) if self.variant == 'prelayernorm': tensor = _normalize(tensor, self.norm_embeddings) return tensor, new_incr_state
[ "def", "forward", "(", "self", ",", "input", ",", "encoder_state", ",", "incr_state", "=", "None", ")", ":", "encoder_output", ",", "encoder_mask", "=", "encoder_state", "seq_len", "=", "input", ".", "size", "(", "1", ")", "positions", "=", "input", ".", "new", "(", "seq_len", ")", ".", "long", "(", ")", "positions", "=", "torch", ".", "arange", "(", "seq_len", ",", "out", "=", "positions", ")", ".", "unsqueeze", "(", "0", ")", "if", "incr_state", "is", "not", "None", ":", "# We're doing incremental decoding, so select only the most recent position", "input", "=", "input", "[", ":", ",", "-", "1", ":", "]", "if", "positions", "is", "not", "None", ":", "positions", "=", "positions", "[", ":", ",", "-", "1", ":", "]", "else", ":", "incr_state", "=", "{", "}", "tensor", "=", "self", ".", "forward_embedding", "(", "input", ",", "positions", ")", "tensor", "=", "self", ".", "dropout", "(", "tensor", ")", "# --dropout", "tensor", ",", "new_incr_state", "=", "self", ".", "forward_layers", "(", "tensor", ",", "encoder_output", ",", "encoder_mask", ",", "incr_state", ")", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "tensor", "=", "_normalize", "(", "tensor", ",", "self", ".", "norm_embeddings", ")", "return", "tensor", ",", "new_incr_state" ]
[ 861, 4 ]
[ 898, 37 ]
python
en
['en', 'error', 'th']
False
TransformerDecoder._apply_model_parallel
(self, tensor, encoder_output, encoder_mask, incr_state)
Pipeline application of model parallelism.
Pipeline application of model parallelism.
def _apply_model_parallel(self, tensor, encoder_output, encoder_mask, incr_state): """ Pipeline application of model parallelism. """ chunks = PipelineHelper.split( (tensor, encoder_output, encoder_mask, incr_state) ) work_items = PipelineHelper.schedule_work_items(self.layers, chunks) new_incr_state = {i: [] for i, _ in enumerate(self.layers)} for chunk_idx, layer_nos, next_device in work_items: s_tensor, s_enc_out, s_enc_mask, s_incr_state = chunks[chunk_idx] for layer_no in layer_nos: s_tensor, nis = self.layers[layer_no]( x=s_tensor, encoder_output=s_enc_out, encoder_mask=s_enc_mask, incr_state=s_incr_state.get(layer_no), ) new_incr_state[layer_no].append(nis) # don't move incr state, it's always on the correct device s_tensor, s_enc_out, s_enc_mask = PipelineHelper.chunk_to( (s_tensor, s_enc_out, s_enc_mask), next_device ) chunks[chunk_idx] = (s_tensor, s_enc_out, s_enc_mask, s_incr_state) tensor_out = PipelineHelper.join([c[0] for c in chunks]) new_incr_state = { layer_no: PipelineHelper.join(pieces) for layer_no, pieces in new_incr_state.items() } return tensor_out, new_incr_state
[ "def", "_apply_model_parallel", "(", "self", ",", "tensor", ",", "encoder_output", ",", "encoder_mask", ",", "incr_state", ")", ":", "chunks", "=", "PipelineHelper", ".", "split", "(", "(", "tensor", ",", "encoder_output", ",", "encoder_mask", ",", "incr_state", ")", ")", "work_items", "=", "PipelineHelper", ".", "schedule_work_items", "(", "self", ".", "layers", ",", "chunks", ")", "new_incr_state", "=", "{", "i", ":", "[", "]", "for", "i", ",", "_", "in", "enumerate", "(", "self", ".", "layers", ")", "}", "for", "chunk_idx", ",", "layer_nos", ",", "next_device", "in", "work_items", ":", "s_tensor", ",", "s_enc_out", ",", "s_enc_mask", ",", "s_incr_state", "=", "chunks", "[", "chunk_idx", "]", "for", "layer_no", "in", "layer_nos", ":", "s_tensor", ",", "nis", "=", "self", ".", "layers", "[", "layer_no", "]", "(", "x", "=", "s_tensor", ",", "encoder_output", "=", "s_enc_out", ",", "encoder_mask", "=", "s_enc_mask", ",", "incr_state", "=", "s_incr_state", ".", "get", "(", "layer_no", ")", ",", ")", "new_incr_state", "[", "layer_no", "]", ".", "append", "(", "nis", ")", "# don't move incr state, it's always on the correct device", "s_tensor", ",", "s_enc_out", ",", "s_enc_mask", "=", "PipelineHelper", ".", "chunk_to", "(", "(", "s_tensor", ",", "s_enc_out", ",", "s_enc_mask", ")", ",", "next_device", ")", "chunks", "[", "chunk_idx", "]", "=", "(", "s_tensor", ",", "s_enc_out", ",", "s_enc_mask", ",", "s_incr_state", ")", "tensor_out", "=", "PipelineHelper", ".", "join", "(", "[", "c", "[", "0", "]", "for", "c", "in", "chunks", "]", ")", "new_incr_state", "=", "{", "layer_no", ":", "PipelineHelper", ".", "join", "(", "pieces", ")", "for", "layer_no", ",", "pieces", "in", "new_incr_state", ".", "items", "(", ")", "}", "return", "tensor_out", ",", "new_incr_state" ]
[ 900, 4 ]
[ 933, 41 ]
python
en
['en', 'error', 'th']
False
TransformerDecoderLayer.forward
(self, x, encoder_output, encoder_mask, incr_state=None)
Forward pass. The incremental state is a dict with values for self- and encoder-attention states.
Forward pass.
def forward(self, x, encoder_output, encoder_mask, incr_state=None): """ Forward pass. The incremental state is a dict with values for self- and encoder-attention states. """ if incr_state is None: incr_state = {} decoder_mask = self._create_selfattn_mask(x) # first self attn residual = x if self.variant == 'prelayernorm': x = _normalize(x, self.norm1) # don't peak into the future! x, final_self_attn_incr_state = self.self_attention( query=x, mask=decoder_mask, incr_state=incr_state.get('self_attn'), static_kv=False, )[:2] x = self.dropout(x) # --dropout x = x + residual if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart': x = _normalize(x, self.norm1) residual = x # encoder_attn_layer_norm norm 2 if self.variant == 'prelayernorm': x = _normalize(x, self.norm2) x, final_encoder_attn_incr_state = self.encoder_attention( query=x, key=encoder_output, value=encoder_output, mask=encoder_mask, incr_state=incr_state.get('encoder_attn'), static_kv=True, )[:2] x = self.dropout(x) # --dropout x = residual + x if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart': x = _normalize(x, self.norm2) # finally the ffn residual = x if self.variant == 'prelayernorm': x = _normalize(x, self.norm3) x = self.ffn(x) x = self.dropout(x) # --dropout x = residual + x if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart': x = _normalize(x, self.norm3) new_incr_state = { 'self_attn': final_self_attn_incr_state, 'encoder_attn': final_encoder_attn_incr_state, } return x, new_incr_state
[ "def", "forward", "(", "self", ",", "x", ",", "encoder_output", ",", "encoder_mask", ",", "incr_state", "=", "None", ")", ":", "if", "incr_state", "is", "None", ":", "incr_state", "=", "{", "}", "decoder_mask", "=", "self", ".", "_create_selfattn_mask", "(", "x", ")", "# first self attn", "residual", "=", "x", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "x", "=", "_normalize", "(", "x", ",", "self", ".", "norm1", ")", "# don't peak into the future!", "x", ",", "final_self_attn_incr_state", "=", "self", ".", "self_attention", "(", "query", "=", "x", ",", "mask", "=", "decoder_mask", ",", "incr_state", "=", "incr_state", ".", "get", "(", "'self_attn'", ")", ",", "static_kv", "=", "False", ",", ")", "[", ":", "2", "]", "x", "=", "self", ".", "dropout", "(", "x", ")", "# --dropout", "x", "=", "x", "+", "residual", "if", "self", ".", "variant", "==", "'aiayn'", "or", "self", ".", "variant", "==", "'xlm'", "or", "self", ".", "variant", "==", "'bart'", ":", "x", "=", "_normalize", "(", "x", ",", "self", ".", "norm1", ")", "residual", "=", "x", "# encoder_attn_layer_norm norm 2", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "x", "=", "_normalize", "(", "x", ",", "self", ".", "norm2", ")", "x", ",", "final_encoder_attn_incr_state", "=", "self", ".", "encoder_attention", "(", "query", "=", "x", ",", "key", "=", "encoder_output", ",", "value", "=", "encoder_output", ",", "mask", "=", "encoder_mask", ",", "incr_state", "=", "incr_state", ".", "get", "(", "'encoder_attn'", ")", ",", "static_kv", "=", "True", ",", ")", "[", ":", "2", "]", "x", "=", "self", ".", "dropout", "(", "x", ")", "# --dropout", "x", "=", "residual", "+", "x", "if", "self", ".", "variant", "==", "'aiayn'", "or", "self", ".", "variant", "==", "'xlm'", "or", "self", ".", "variant", "==", "'bart'", ":", "x", "=", "_normalize", "(", "x", ",", "self", ".", "norm2", ")", "# finally the ffn", "residual", "=", "x", "if", "self", ".", "variant", "==", "'prelayernorm'", ":", "x", "=", "_normalize", "(", "x", ",", "self", ".", "norm3", ")", "x", "=", "self", ".", "ffn", "(", "x", ")", "x", "=", "self", ".", "dropout", "(", "x", ")", "# --dropout", "x", "=", "residual", "+", "x", "if", "self", ".", "variant", "==", "'aiayn'", "or", "self", ".", "variant", "==", "'xlm'", "or", "self", ".", "variant", "==", "'bart'", ":", "x", "=", "_normalize", "(", "x", ",", "self", ".", "norm3", ")", "new_incr_state", "=", "{", "'self_attn'", ":", "final_self_attn_incr_state", ",", "'encoder_attn'", ":", "final_encoder_attn_incr_state", ",", "}", "return", "x", ",", "new_incr_state" ]
[ 979, 4 ]
[ 1039, 32 ]
python
en
['en', 'error', 'th']
False
TransformerDecoderLayer.reorder_incremental_state
( self, incremental_state: Dict[str, dict], inds: torch.Tensor )
Reorder all incremental-state tensors for this layer.
Reorder all incremental-state tensors for this layer.
def reorder_incremental_state( self, incremental_state: Dict[str, dict], inds: torch.Tensor ) -> Dict[str, dict]: """ Reorder all incremental-state tensors for this layer. """ attn_types = { 'self_attn': self.self_attention, 'encoder_attn': self.encoder_attention, } return { attn_type: attn.reorder_incremental_state( incremental_state[attn_type], inds ) for attn_type, attn in attn_types.items() }
[ "def", "reorder_incremental_state", "(", "self", ",", "incremental_state", ":", "Dict", "[", "str", ",", "dict", "]", ",", "inds", ":", "torch", ".", "Tensor", ")", "->", "Dict", "[", "str", ",", "dict", "]", ":", "attn_types", "=", "{", "'self_attn'", ":", "self", ".", "self_attention", ",", "'encoder_attn'", ":", "self", ".", "encoder_attention", ",", "}", "return", "{", "attn_type", ":", "attn", ".", "reorder_incremental_state", "(", "incremental_state", "[", "attn_type", "]", ",", "inds", ")", "for", "attn_type", ",", "attn", "in", "attn_types", ".", "items", "(", ")", "}" ]
[ 1051, 4 ]
[ 1066, 9 ]
python
en
['en', 'error', 'th']
False
TransformerGeneratorModel.reorder_encoder_states
(self, encoder_states, indices)
Reorder the encoder states. See ``TorchGeneratorModel.reorder_encoder_states`` for a description.
Reorder the encoder states.
def reorder_encoder_states(self, encoder_states, indices): """ Reorder the encoder states. See ``TorchGeneratorModel.reorder_encoder_states`` for a description. """ enc, mask = encoder_states if not torch.is_tensor(indices): indices = torch.LongTensor(indices).to(enc.device) enc = torch.index_select(enc, 0, indices) mask = torch.index_select(mask, 0, indices) return enc, mask
[ "def", "reorder_encoder_states", "(", "self", ",", "encoder_states", ",", "indices", ")", ":", "enc", ",", "mask", "=", "encoder_states", "if", "not", "torch", ".", "is_tensor", "(", "indices", ")", ":", "indices", "=", "torch", ".", "LongTensor", "(", "indices", ")", ".", "to", "(", "enc", ".", "device", ")", "enc", "=", "torch", ".", "index_select", "(", "enc", ",", "0", ",", "indices", ")", "mask", "=", "torch", ".", "index_select", "(", "mask", ",", "0", ",", "indices", ")", "return", "enc", ",", "mask" ]
[ 1185, 4 ]
[ 1196, 24 ]
python
en
['en', 'error', 'th']
False
TransformerGeneratorModel.reorder_decoder_incremental_state
( self, incremental_state: Dict[int, dict], inds: torch.Tensor )
Reorder the decoder incremental state. See ``TorchGeneratorModel.reorder_decoder_incremental_state`` for a description. Here, incremental_state is a dict whose keys are layer indices and whose values are dicts containing the incremental state for that layer.
Reorder the decoder incremental state.
def reorder_decoder_incremental_state( self, incremental_state: Dict[int, dict], inds: torch.Tensor ) -> Dict[int, dict]: """ Reorder the decoder incremental state. See ``TorchGeneratorModel.reorder_decoder_incremental_state`` for a description. Here, incremental_state is a dict whose keys are layer indices and whose values are dicts containing the incremental state for that layer. """ return { idx: layer.reorder_incremental_state(incremental_state[idx], inds) for idx, layer in enumerate(self.decoder.layers) }
[ "def", "reorder_decoder_incremental_state", "(", "self", ",", "incremental_state", ":", "Dict", "[", "int", ",", "dict", "]", ",", "inds", ":", "torch", ".", "Tensor", ")", "->", "Dict", "[", "int", ",", "dict", "]", ":", "return", "{", "idx", ":", "layer", ".", "reorder_incremental_state", "(", "incremental_state", "[", "idx", "]", ",", "inds", ")", "for", "idx", ",", "layer", "in", "enumerate", "(", "self", ".", "decoder", ".", "layers", ")", "}" ]
[ 1198, 4 ]
[ 1212, 9 ]
python
en
['en', 'error', 'th']
False
TransformerGeneratorModel.output
(self, tensor)
Compute output logits.
Compute output logits.
def output(self, tensor): """ Compute output logits. """ # project back to vocabulary output = F.linear(tensor, self.embeddings.weight) # compatibility with fairseq: fairseq sometimes reuses BOS tokens and # we need to force their probability of generation to be 0. output[:, :, self.start_idx] = neginf(output.dtype) return output
[ "def", "output", "(", "self", ",", "tensor", ")", ":", "# project back to vocabulary", "output", "=", "F", ".", "linear", "(", "tensor", ",", "self", ".", "embeddings", ".", "weight", ")", "# compatibility with fairseq: fairseq sometimes reuses BOS tokens and", "# we need to force their probability of generation to be 0.", "output", "[", ":", ",", ":", ",", "self", ".", "start_idx", "]", "=", "neginf", "(", "output", ".", "dtype", ")", "return", "output" ]
[ 1214, 4 ]
[ 1223, 21 ]
python
en
['en', 'error', 'th']
False
BasicAttention.forward
(self, xs, ys, mask_ys=None, values=None)
Compute attention. Attend over ys with query xs to obtain weights, then apply weights to values (ys if yalues is None) Args: xs: B x query_len x dim (queries) ys: B x key_len x dim (keys) mask_ys: B x key_len (mask) values: B x value_len x dim (values); if None, default to ys
Compute attention.
def forward(self, xs, ys, mask_ys=None, values=None): """ Compute attention. Attend over ys with query xs to obtain weights, then apply weights to values (ys if yalues is None) Args: xs: B x query_len x dim (queries) ys: B x key_len x dim (keys) mask_ys: B x key_len (mask) values: B x value_len x dim (values); if None, default to ys """ bsz = xs.size(0) y_len = ys.size(1) x_len = xs.size(1) if self.attn == 'cosine': l1 = self.cosine(xs, ys).unsqueeze(self.dim - 1) else: l1 = torch.bmm(xs, ys.transpose(1, 2)) if self.attn == 'sqrt': d_k = ys.size(-1) l1 = l1 / math.sqrt(d_k) if mask_ys is not None: attn_mask = (mask_ys == 0).view(bsz, 1, y_len) attn_mask = attn_mask.repeat(1, x_len, 1) l1.masked_fill_(attn_mask, neginf(l1.dtype)) l2 = F.softmax(l1, dim=self.dim, dtype=torch.float).type_as(l1) if values is None: values = ys lhs_emb = torch.bmm(l2, values) # # add back the query if self.residual: lhs_emb = lhs_emb.add(xs) if self.get_weights: return lhs_emb.squeeze(self.dim - 1), l2 else: return lhs_emb.squeeze(self.dim - 1)
[ "def", "forward", "(", "self", ",", "xs", ",", "ys", ",", "mask_ys", "=", "None", ",", "values", "=", "None", ")", ":", "bsz", "=", "xs", ".", "size", "(", "0", ")", "y_len", "=", "ys", ".", "size", "(", "1", ")", "x_len", "=", "xs", ".", "size", "(", "1", ")", "if", "self", ".", "attn", "==", "'cosine'", ":", "l1", "=", "self", ".", "cosine", "(", "xs", ",", "ys", ")", ".", "unsqueeze", "(", "self", ".", "dim", "-", "1", ")", "else", ":", "l1", "=", "torch", ".", "bmm", "(", "xs", ",", "ys", ".", "transpose", "(", "1", ",", "2", ")", ")", "if", "self", ".", "attn", "==", "'sqrt'", ":", "d_k", "=", "ys", ".", "size", "(", "-", "1", ")", "l1", "=", "l1", "/", "math", ".", "sqrt", "(", "d_k", ")", "if", "mask_ys", "is", "not", "None", ":", "attn_mask", "=", "(", "mask_ys", "==", "0", ")", ".", "view", "(", "bsz", ",", "1", ",", "y_len", ")", "attn_mask", "=", "attn_mask", ".", "repeat", "(", "1", ",", "x_len", ",", "1", ")", "l1", ".", "masked_fill_", "(", "attn_mask", ",", "neginf", "(", "l1", ".", "dtype", ")", ")", "l2", "=", "F", ".", "softmax", "(", "l1", ",", "dim", "=", "self", ".", "dim", ",", "dtype", "=", "torch", ".", "float", ")", ".", "type_as", "(", "l1", ")", "if", "values", "is", "None", ":", "values", "=", "ys", "lhs_emb", "=", "torch", ".", "bmm", "(", "l2", ",", "values", ")", "# # add back the query", "if", "self", ".", "residual", ":", "lhs_emb", "=", "lhs_emb", ".", "add", "(", "xs", ")", "if", "self", ".", "get_weights", ":", "return", "lhs_emb", ".", "squeeze", "(", "self", ".", "dim", "-", "1", ")", ",", "l2", "else", ":", "return", "lhs_emb", ".", "squeeze", "(", "self", ".", "dim", "-", "1", ")" ]
[ 1240, 4 ]
[ 1279, 48 ]
python
en
['en', 'error', 'th']
False
MultiHeadAttention.forward
( # type: ignore # TODO: remove type ignore with pytorch 1.5: # https://github.com/pytorch/pytorch/pull/31057 self, query: torch.Tensor, key: Optional[torch.Tensor] = None, value: Optional[torch.Tensor] = None, mask: torch.Tensor = None, incr_state: Optional[Dict[str, torch.Tensor]] = None, static_kv: bool = False, )
Forward pass. :param query: attention query :param key: attention key :param value: attention value :param mask: tensor in which True means that we are allowing attention and False means we are blocking it. Mask is: - [B, key_len] (encoder self-attn and decoder enc/dec attn) - [B, query_len, key_len] (decoder self-attn) - [B, 1, key_len] (decoder self-attn with incr_state caching) :param incr_state: dictionary with values representing the previous states of the key, value, and mask :param static_kv: True if the key and value are held constant during decoding (as in encoder/decoder attention) :return: ( final attended tensor, new incremental state, key/value-multiplied tensor before softmax, )
Forward pass.
def forward( # type: ignore # TODO: remove type ignore with pytorch 1.5: # https://github.com/pytorch/pytorch/pull/31057 self, query: torch.Tensor, key: Optional[torch.Tensor] = None, value: Optional[torch.Tensor] = None, mask: torch.Tensor = None, incr_state: Optional[Dict[str, torch.Tensor]] = None, static_kv: bool = False, ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], torch.Tensor]: """ Forward pass. :param query: attention query :param key: attention key :param value: attention value :param mask: tensor in which True means that we are allowing attention and False means we are blocking it. Mask is: - [B, key_len] (encoder self-attn and decoder enc/dec attn) - [B, query_len, key_len] (decoder self-attn) - [B, 1, key_len] (decoder self-attn with incr_state caching) :param incr_state: dictionary with values representing the previous states of the key, value, and mask :param static_kv: True if the key and value are held constant during decoding (as in encoder/decoder attention) :return: ( final attended tensor, new incremental state, key/value-multiplied tensor before softmax, ) """ batch_size, query_len, dim = query.size() assert ( dim == self.dim ), 'Dimensions do not match: {} query vs {} configured'.format(dim, self.dim) assert mask is not None, 'Mask is None, please specify a mask' n_heads = self.n_heads dim_per_head = dim // n_heads scale = math.sqrt(dim_per_head) def prepare_head(tensor): # input is [batch_size, seq_len, n_heads * dim_per_head] # output is [batch_size * n_heads, seq_len, dim_per_head] bsz, seq_len, _ = tensor.size() tensor = tensor.view(batch_size, tensor.size(1), n_heads, dim_per_head) tensor = ( tensor.transpose(1, 2) .contiguous() .view(batch_size * n_heads, seq_len, dim_per_head) ) return tensor # q, k, v are the transformed values if key is None and value is None: # self attention key = value = query _, _key_len, dim = query.size() elif value is None: # key and value are the same, but query differs # self attention value = key assert key is not None # let mypy know we sorted this _, _key_len, dim = key.size() q = prepare_head(self.q_lin(query)) k = prepare_head(self.k_lin(key)) v = prepare_head(self.v_lin(value)) # Prepend incremental states. For each of the key, value, and mask, see if # a previous incremental state exists, and if so, reshape it to match the shape # of the new state. Concatenate the previous and new states to match what the # full state would have been if we had not cached. (If we are using static_kv, # these three states are unchanging, so just re-use the cached states.) if incr_state is None: incr_state = {} if 'prev_key' in incr_state: prev_key = incr_state['prev_key'].view( batch_size * n_heads, -1, dim_per_head ) if static_kv: k = prev_key else: k = torch.cat([prev_key, k], dim=1) if 'prev_value' in incr_state: prev_value = incr_state['prev_value'].view( batch_size * n_heads, -1, dim_per_head ) if static_kv: v = prev_value else: v = torch.cat([prev_value, v], dim=1) if 'prev_mask' in incr_state: if static_kv: mask = incr_state['prev_mask'] else: mask = torch.cat([incr_state['prev_mask'], mask], dim=2) # Prepend along the key_len dimension (analogous to # incr_state['prev_key']) # Save new incremental states. We reshape to allow for reordering along batch # dimension. new_incr_state = { 'prev_key': k.view(batch_size, n_heads, -1, dim_per_head), 'prev_value': v.view(batch_size, n_heads, -1, dim_per_head), 'prev_mask': mask, } full_key_len = k.size(1) dot_prod = q.div_(scale).bmm(k.transpose(1, 2)) # [B * n_heads, query_len, key_len] attn_mask = ( (mask == 0) .view(batch_size, 1, -1, full_key_len) .repeat(1, n_heads, 1, 1) .expand(batch_size, n_heads, query_len, full_key_len) .view(batch_size * n_heads, query_len, full_key_len) ) assert attn_mask.shape == dot_prod.shape dot_prod.masked_fill_(attn_mask, neginf(dot_prod.dtype)) attn_weights = F.softmax( dot_prod, dim=-1, dtype=torch.float # type: ignore ).type_as(query) attn_weights = self.attn_dropout(attn_weights) # --attention-dropout attentioned = attn_weights.bmm(v) attentioned = ( attentioned.type_as(query) .view(batch_size, n_heads, query_len, dim_per_head) .transpose(1, 2) .contiguous() .view(batch_size, query_len, dim) ) out = self.out_lin(attentioned) return out, new_incr_state, dot_prod
[ "def", "forward", "(", "# type: ignore", "# TODO: remove type ignore with pytorch 1.5:", "# https://github.com/pytorch/pytorch/pull/31057", "self", ",", "query", ":", "torch", ".", "Tensor", ",", "key", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ",", "value", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ",", "mask", ":", "torch", ".", "Tensor", "=", "None", ",", "incr_state", ":", "Optional", "[", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", "]", "=", "None", ",", "static_kv", ":", "bool", "=", "False", ",", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ",", "torch", ".", "Tensor", "]", ":", "batch_size", ",", "query_len", ",", "dim", "=", "query", ".", "size", "(", ")", "assert", "(", "dim", "==", "self", ".", "dim", ")", ",", "'Dimensions do not match: {} query vs {} configured'", ".", "format", "(", "dim", ",", "self", ".", "dim", ")", "assert", "mask", "is", "not", "None", ",", "'Mask is None, please specify a mask'", "n_heads", "=", "self", ".", "n_heads", "dim_per_head", "=", "dim", "//", "n_heads", "scale", "=", "math", ".", "sqrt", "(", "dim_per_head", ")", "def", "prepare_head", "(", "tensor", ")", ":", "# input is [batch_size, seq_len, n_heads * dim_per_head]", "# output is [batch_size * n_heads, seq_len, dim_per_head]", "bsz", ",", "seq_len", ",", "_", "=", "tensor", ".", "size", "(", ")", "tensor", "=", "tensor", ".", "view", "(", "batch_size", ",", "tensor", ".", "size", "(", "1", ")", ",", "n_heads", ",", "dim_per_head", ")", "tensor", "=", "(", "tensor", ".", "transpose", "(", "1", ",", "2", ")", ".", "contiguous", "(", ")", ".", "view", "(", "batch_size", "*", "n_heads", ",", "seq_len", ",", "dim_per_head", ")", ")", "return", "tensor", "# q, k, v are the transformed values", "if", "key", "is", "None", "and", "value", "is", "None", ":", "# self attention", "key", "=", "value", "=", "query", "_", ",", "_key_len", ",", "dim", "=", "query", ".", "size", "(", ")", "elif", "value", "is", "None", ":", "# key and value are the same, but query differs", "# self attention", "value", "=", "key", "assert", "key", "is", "not", "None", "# let mypy know we sorted this", "_", ",", "_key_len", ",", "dim", "=", "key", ".", "size", "(", ")", "q", "=", "prepare_head", "(", "self", ".", "q_lin", "(", "query", ")", ")", "k", "=", "prepare_head", "(", "self", ".", "k_lin", "(", "key", ")", ")", "v", "=", "prepare_head", "(", "self", ".", "v_lin", "(", "value", ")", ")", "# Prepend incremental states. For each of the key, value, and mask, see if", "# a previous incremental state exists, and if so, reshape it to match the shape", "# of the new state. Concatenate the previous and new states to match what the", "# full state would have been if we had not cached. (If we are using static_kv,", "# these three states are unchanging, so just re-use the cached states.)", "if", "incr_state", "is", "None", ":", "incr_state", "=", "{", "}", "if", "'prev_key'", "in", "incr_state", ":", "prev_key", "=", "incr_state", "[", "'prev_key'", "]", ".", "view", "(", "batch_size", "*", "n_heads", ",", "-", "1", ",", "dim_per_head", ")", "if", "static_kv", ":", "k", "=", "prev_key", "else", ":", "k", "=", "torch", ".", "cat", "(", "[", "prev_key", ",", "k", "]", ",", "dim", "=", "1", ")", "if", "'prev_value'", "in", "incr_state", ":", "prev_value", "=", "incr_state", "[", "'prev_value'", "]", ".", "view", "(", "batch_size", "*", "n_heads", ",", "-", "1", ",", "dim_per_head", ")", "if", "static_kv", ":", "v", "=", "prev_value", "else", ":", "v", "=", "torch", ".", "cat", "(", "[", "prev_value", ",", "v", "]", ",", "dim", "=", "1", ")", "if", "'prev_mask'", "in", "incr_state", ":", "if", "static_kv", ":", "mask", "=", "incr_state", "[", "'prev_mask'", "]", "else", ":", "mask", "=", "torch", ".", "cat", "(", "[", "incr_state", "[", "'prev_mask'", "]", ",", "mask", "]", ",", "dim", "=", "2", ")", "# Prepend along the key_len dimension (analogous to", "# incr_state['prev_key'])", "# Save new incremental states. We reshape to allow for reordering along batch", "# dimension.", "new_incr_state", "=", "{", "'prev_key'", ":", "k", ".", "view", "(", "batch_size", ",", "n_heads", ",", "-", "1", ",", "dim_per_head", ")", ",", "'prev_value'", ":", "v", ".", "view", "(", "batch_size", ",", "n_heads", ",", "-", "1", ",", "dim_per_head", ")", ",", "'prev_mask'", ":", "mask", ",", "}", "full_key_len", "=", "k", ".", "size", "(", "1", ")", "dot_prod", "=", "q", ".", "div_", "(", "scale", ")", ".", "bmm", "(", "k", ".", "transpose", "(", "1", ",", "2", ")", ")", "# [B * n_heads, query_len, key_len]", "attn_mask", "=", "(", "(", "mask", "==", "0", ")", ".", "view", "(", "batch_size", ",", "1", ",", "-", "1", ",", "full_key_len", ")", ".", "repeat", "(", "1", ",", "n_heads", ",", "1", ",", "1", ")", ".", "expand", "(", "batch_size", ",", "n_heads", ",", "query_len", ",", "full_key_len", ")", ".", "view", "(", "batch_size", "*", "n_heads", ",", "query_len", ",", "full_key_len", ")", ")", "assert", "attn_mask", ".", "shape", "==", "dot_prod", ".", "shape", "dot_prod", ".", "masked_fill_", "(", "attn_mask", ",", "neginf", "(", "dot_prod", ".", "dtype", ")", ")", "attn_weights", "=", "F", ".", "softmax", "(", "dot_prod", ",", "dim", "=", "-", "1", ",", "dtype", "=", "torch", ".", "float", "# type: ignore", ")", ".", "type_as", "(", "query", ")", "attn_weights", "=", "self", ".", "attn_dropout", "(", "attn_weights", ")", "# --attention-dropout", "attentioned", "=", "attn_weights", ".", "bmm", "(", "v", ")", "attentioned", "=", "(", "attentioned", ".", "type_as", "(", "query", ")", ".", "view", "(", "batch_size", ",", "n_heads", ",", "query_len", ",", "dim_per_head", ")", ".", "transpose", "(", "1", ",", "2", ")", ".", "contiguous", "(", ")", ".", "view", "(", "batch_size", ",", "query_len", ",", "dim", ")", ")", "out", "=", "self", ".", "out_lin", "(", "attentioned", ")", "return", "out", ",", "new_incr_state", ",", "dot_prod" ]
[ 1307, 4 ]
[ 1446, 44 ]
python
en
['en', 'error', 'th']
False
MultiHeadAttention.reorder_incremental_state
( self, incremental_state: Dict[str, torch.Tensor], inds: torch.Tensor )
Reorder the input incremental-state tensors.
Reorder the input incremental-state tensors.
def reorder_incremental_state( self, incremental_state: Dict[str, torch.Tensor], inds: torch.Tensor ) -> Dict[str, torch.Tensor]: """ Reorder the input incremental-state tensors. """ return { key: torch.index_select(val, 0, inds.to(val.device)).contiguous() for key, val in incremental_state.items() }
[ "def", "reorder_incremental_state", "(", "self", ",", "incremental_state", ":", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ",", "inds", ":", "torch", ".", "Tensor", ")", "->", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ":", "return", "{", "key", ":", "torch", ".", "index_select", "(", "val", ",", "0", ",", "inds", ".", "to", "(", "val", ".", "device", ")", ")", ".", "contiguous", "(", ")", "for", "key", ",", "val", "in", "incremental_state", ".", "items", "(", ")", "}" ]
[ 1448, 4 ]
[ 1457, 9 ]
python
en
['en', 'error', 'th']
False
TransformerFFN.forward
(self, x)
Forward pass.
Forward pass.
def forward(self, x): """ Forward pass. """ x = self.nonlinear(self.lin1(x)) x = self.relu_dropout(x) # --relu-dropout x = self.lin2(x) return x
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "nonlinear", "(", "self", ".", "lin1", "(", "x", ")", ")", "x", "=", "self", ".", "relu_dropout", "(", "x", ")", "# --relu-dropout", "x", "=", "self", ".", "lin2", "(", "x", ")", "return", "x" ]
[ 1482, 4 ]
[ 1489, 16 ]
python
en
['en', 'error', 'th']
False
polygon_to_bitmap
(polygons, height, width)
Convert masks from the form of polygons to bitmaps. Args: polygons (list[ndarray]): masks in polygon representation height (int): mask height width (int): mask width Return: ndarray: the converted masks in bitmap representation
Convert masks from the form of polygons to bitmaps.
def polygon_to_bitmap(polygons, height, width): """Convert masks from the form of polygons to bitmaps. Args: polygons (list[ndarray]): masks in polygon representation height (int): mask height width (int): mask width Return: ndarray: the converted masks in bitmap representation """ rles = maskUtils.frPyObjects(polygons, height, width) rle = maskUtils.merge(rles) bitmap_mask = maskUtils.decode(rle).astype(np.bool) return bitmap_mask
[ "def", "polygon_to_bitmap", "(", "polygons", ",", "height", ",", "width", ")", ":", "rles", "=", "maskUtils", ".", "frPyObjects", "(", "polygons", ",", "height", ",", "width", ")", "rle", "=", "maskUtils", ".", "merge", "(", "rles", ")", "bitmap_mask", "=", "maskUtils", ".", "decode", "(", "rle", ")", ".", "astype", "(", "np", ".", "bool", ")", "return", "bitmap_mask" ]
[ 560, 0 ]
[ 574, 22 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.rescale
(self, scale, interpolation='nearest')
Rescale masks as large as possible while keeping the aspect ratio. For details can refer to `mmcv.imrescale`. Args: scale (tuple[int]): The maximum size (h, w) of rescaled mask. interpolation (str): Same as :func:`mmcv.imrescale`. Returns: BaseInstanceMasks: The rescaled masks.
Rescale masks as large as possible while keeping the aspect ratio. For details can refer to `mmcv.imrescale`.
def rescale(self, scale, interpolation='nearest'): """Rescale masks as large as possible while keeping the aspect ratio. For details can refer to `mmcv.imrescale`. Args: scale (tuple[int]): The maximum size (h, w) of rescaled mask. interpolation (str): Same as :func:`mmcv.imrescale`. Returns: BaseInstanceMasks: The rescaled masks. """ pass
[ "def", "rescale", "(", "self", ",", "scale", ",", "interpolation", "=", "'nearest'", ")", ":", "pass" ]
[ 13, 4 ]
[ 24, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.resize
(self, out_shape, interpolation='nearest')
Resize masks to the given out_shape. Args: out_shape: Target (h, w) of resized mask. interpolation (str): See :func:`mmcv.imresize`. Returns: BaseInstanceMasks: The resized masks.
Resize masks to the given out_shape.
def resize(self, out_shape, interpolation='nearest'): """Resize masks to the given out_shape. Args: out_shape: Target (h, w) of resized mask. interpolation (str): See :func:`mmcv.imresize`. Returns: BaseInstanceMasks: The resized masks. """ pass
[ "def", "resize", "(", "self", ",", "out_shape", ",", "interpolation", "=", "'nearest'", ")", ":", "pass" ]
[ 27, 4 ]
[ 37, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.flip
(self, flip_direction='horizontal')
Flip masks alone the given direction. Args: flip_direction (str): Either 'horizontal' or 'vertical'. Returns: BaseInstanceMasks: The flipped masks.
Flip masks alone the given direction.
def flip(self, flip_direction='horizontal'): """Flip masks alone the given direction. Args: flip_direction (str): Either 'horizontal' or 'vertical'. Returns: BaseInstanceMasks: The flipped masks. """ pass
[ "def", "flip", "(", "self", ",", "flip_direction", "=", "'horizontal'", ")", ":", "pass" ]
[ 40, 4 ]
[ 49, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.pad
(self, out_shape, pad_val)
Pad masks to the given size of (h, w). Args: out_shape (tuple[int]): Target (h, w) of padded mask. pad_val (int): The padded value. Returns: BaseInstanceMasks: The padded masks.
Pad masks to the given size of (h, w).
def pad(self, out_shape, pad_val): """Pad masks to the given size of (h, w). Args: out_shape (tuple[int]): Target (h, w) of padded mask. pad_val (int): The padded value. Returns: BaseInstanceMasks: The padded masks. """ pass
[ "def", "pad", "(", "self", ",", "out_shape", ",", "pad_val", ")", ":", "pass" ]
[ 52, 4 ]
[ 62, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.crop
(self, bbox)
Crop each mask by the given bbox. Args: bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ). Return: BaseInstanceMasks: The cropped masks.
Crop each mask by the given bbox.
def crop(self, bbox): """Crop each mask by the given bbox. Args: bbox (ndarray): Bbox in format [x1, y1, x2, y2], shape (4, ). Return: BaseInstanceMasks: The cropped masks. """ pass
[ "def", "crop", "(", "self", ",", "bbox", ")", ":", "pass" ]
[ 65, 4 ]
[ 74, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.crop_and_resize
(self, bboxes, out_shape, inds, device, interpolation='bilinear')
Crop and resize masks by the given bboxes. This function is mainly used in mask targets computation. It firstly align mask to bboxes by assigned_inds, then crop mask by the assigned bbox and resize to the size of (mask_h, mask_w) Args: bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4) out_shape (tuple[int]): Target (h, w) of resized mask inds (ndarray): Indexes to assign masks to each bbox device (str): Device of bboxes interpolation (str): See `mmcv.imresize` Return: BaseInstanceMasks: the cropped and resized masks.
Crop and resize masks by the given bboxes.
def crop_and_resize(self, bboxes, out_shape, inds, device, interpolation='bilinear'): """Crop and resize masks by the given bboxes. This function is mainly used in mask targets computation. It firstly align mask to bboxes by assigned_inds, then crop mask by the assigned bbox and resize to the size of (mask_h, mask_w) Args: bboxes (Tensor): Bboxes in format [x1, y1, x2, y2], shape (N, 4) out_shape (tuple[int]): Target (h, w) of resized mask inds (ndarray): Indexes to assign masks to each bbox device (str): Device of bboxes interpolation (str): See `mmcv.imresize` Return: BaseInstanceMasks: the cropped and resized masks. """ pass
[ "def", "crop_and_resize", "(", "self", ",", "bboxes", ",", "out_shape", ",", "inds", ",", "device", ",", "interpolation", "=", "'bilinear'", ")", ":", "pass" ]
[ 77, 4 ]
[ 99, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.expand
(self, expanded_h, expanded_w, top, left)
see :class:`Expand`.
see :class:`Expand`.
def expand(self, expanded_h, expanded_w, top, left): """see :class:`Expand`.""" pass
[ "def", "expand", "(", "self", ",", "expanded_h", ",", "expanded_w", ",", "top", ",", "left", ")", ":", "pass" ]
[ 102, 4 ]
[ 104, 12 ]
python
en
['en', 'en', 'en']
False
BaseInstanceMasks.areas
(self)
ndarray: areas of each instance.
ndarray: areas of each instance.
def areas(self): """ndarray: areas of each instance.""" pass
[ "def", "areas", "(", "self", ")", ":", "pass" ]
[ 108, 4 ]
[ 110, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.to_ndarray
(self)
Convert masks to the format of ndarray. Return: ndarray: Converted masks in the format of ndarray.
Convert masks to the format of ndarray.
def to_ndarray(self): """Convert masks to the format of ndarray. Return: ndarray: Converted masks in the format of ndarray. """ pass
[ "def", "to_ndarray", "(", "self", ")", ":", "pass" ]
[ 113, 4 ]
[ 119, 12 ]
python
en
['en', 'en', 'en']
True
BaseInstanceMasks.to_tensor
(self, dtype, device)
Convert masks to the format of Tensor. Args: dtype (str): Dtype of converted mask. device (torch.device): Device of converted masks. Returns: Tensor: Converted masks in the format of Tensor.
Convert masks to the format of Tensor.
def to_tensor(self, dtype, device): """Convert masks to the format of Tensor. Args: dtype (str): Dtype of converted mask. device (torch.device): Device of converted masks. Returns: Tensor: Converted masks in the format of Tensor. """ pass
[ "def", "to_tensor", "(", "self", ",", "dtype", ",", "device", ")", ":", "pass" ]
[ 122, 4 ]
[ 132, 12 ]
python
en
['en', 'en', 'en']
True
BitmapMasks.__getitem__
(self, index)
Index the BitmapMask. Args: index (int | ndarray): Indices in the format of integer or ndarray. Returns: :obj:`BitmapMasks`: Indexed bitmap masks.
Index the BitmapMask.
def __getitem__(self, index): """Index the BitmapMask. Args: index (int | ndarray): Indices in the format of integer or ndarray. Returns: :obj:`BitmapMasks`: Indexed bitmap masks. """ masks = self.masks[index].reshape(-1, self.height, self.width) return BitmapMasks(masks, self.height, self.width)
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "masks", "=", "self", ".", "masks", "[", "index", "]", ".", "reshape", "(", "-", "1", ",", "self", ".", "height", ",", "self", ".", "width", ")", "return", "BitmapMasks", "(", "masks", ",", "self", ".", "height", ",", "self", ".", "width", ")" ]
[ 162, 4 ]
[ 172, 58 ]
python
en
['en', 'zu', 'en']
True
BitmapMasks.__len__
(self)
Number of masks.
Number of masks.
def __len__(self): """Number of masks.""" return len(self.masks)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "masks", ")" ]
[ 184, 4 ]
[ 186, 30 ]
python
en
['en', 'da', 'en']
True
BitmapMasks.rescale
(self, scale, interpolation='nearest')
See :func:`BaseInstanceMasks.rescale`.
See :func:`BaseInstanceMasks.rescale`.
def rescale(self, scale, interpolation='nearest'): """See :func:`BaseInstanceMasks.rescale`.""" if len(self.masks) == 0: new_w, new_h = mmcv.rescale_size((self.width, self.height), scale) rescaled_masks = np.empty((0, new_h, new_w), dtype=np.uint8) else: rescaled_masks = np.stack([ mmcv.imrescale(mask, scale, interpolation=interpolation) for mask in self.masks ]) height, width = rescaled_masks.shape[1:] return BitmapMasks(rescaled_masks, height, width)
[ "def", "rescale", "(", "self", ",", "scale", ",", "interpolation", "=", "'nearest'", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "new_w", ",", "new_h", "=", "mmcv", ".", "rescale_size", "(", "(", "self", ".", "width", ",", "self", ".", "height", ")", ",", "scale", ")", "rescaled_masks", "=", "np", ".", "empty", "(", "(", "0", ",", "new_h", ",", "new_w", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "else", ":", "rescaled_masks", "=", "np", ".", "stack", "(", "[", "mmcv", ".", "imrescale", "(", "mask", ",", "scale", ",", "interpolation", "=", "interpolation", ")", "for", "mask", "in", "self", ".", "masks", "]", ")", "height", ",", "width", "=", "rescaled_masks", ".", "shape", "[", "1", ":", "]", "return", "BitmapMasks", "(", "rescaled_masks", ",", "height", ",", "width", ")" ]
[ 188, 4 ]
[ 199, 57 ]
python
en
['en', 'en', 'de']
False
BitmapMasks.resize
(self, out_shape, interpolation='nearest')
See :func:`BaseInstanceMasks.resize`.
See :func:`BaseInstanceMasks.resize`.
def resize(self, out_shape, interpolation='nearest'): """See :func:`BaseInstanceMasks.resize`.""" if len(self.masks) == 0: resized_masks = np.empty((0, *out_shape), dtype=np.uint8) else: resized_masks = np.stack([ mmcv.imresize(mask, out_shape, interpolation=interpolation) for mask in self.masks ]) return BitmapMasks(resized_masks, *out_shape)
[ "def", "resize", "(", "self", ",", "out_shape", ",", "interpolation", "=", "'nearest'", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "resized_masks", "=", "np", ".", "empty", "(", "(", "0", ",", "*", "out_shape", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "else", ":", "resized_masks", "=", "np", ".", "stack", "(", "[", "mmcv", ".", "imresize", "(", "mask", ",", "out_shape", ",", "interpolation", "=", "interpolation", ")", "for", "mask", "in", "self", ".", "masks", "]", ")", "return", "BitmapMasks", "(", "resized_masks", ",", "*", "out_shape", ")" ]
[ 201, 4 ]
[ 210, 53 ]
python
de
['en', 'jv', 'de']
False
BitmapMasks.flip
(self, flip_direction='horizontal')
See :func:`BaseInstanceMasks.flip`.
See :func:`BaseInstanceMasks.flip`.
def flip(self, flip_direction='horizontal'): """See :func:`BaseInstanceMasks.flip`.""" assert flip_direction in ('horizontal', 'vertical') if len(self.masks) == 0: flipped_masks = self.masks else: flipped_masks = np.stack([ mmcv.imflip(mask, direction=flip_direction) for mask in self.masks ]) return BitmapMasks(flipped_masks, self.height, self.width)
[ "def", "flip", "(", "self", ",", "flip_direction", "=", "'horizontal'", ")", ":", "assert", "flip_direction", "in", "(", "'horizontal'", ",", "'vertical'", ")", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "flipped_masks", "=", "self", ".", "masks", "else", ":", "flipped_masks", "=", "np", ".", "stack", "(", "[", "mmcv", ".", "imflip", "(", "mask", ",", "direction", "=", "flip_direction", ")", "for", "mask", "in", "self", ".", "masks", "]", ")", "return", "BitmapMasks", "(", "flipped_masks", ",", "self", ".", "height", ",", "self", ".", "width", ")" ]
[ 212, 4 ]
[ 223, 66 ]
python
de
['en', 'de', 'de']
False
BitmapMasks.pad
(self, out_shape, pad_val=0)
See :func:`BaseInstanceMasks.pad`.
See :func:`BaseInstanceMasks.pad`.
def pad(self, out_shape, pad_val=0): """See :func:`BaseInstanceMasks.pad`.""" if len(self.masks) == 0: padded_masks = np.empty((0, *out_shape), dtype=np.uint8) else: padded_masks = np.stack([ mmcv.impad(mask, shape=out_shape, pad_val=pad_val) for mask in self.masks ]) return BitmapMasks(padded_masks, *out_shape)
[ "def", "pad", "(", "self", ",", "out_shape", ",", "pad_val", "=", "0", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "padded_masks", "=", "np", ".", "empty", "(", "(", "0", ",", "*", "out_shape", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "else", ":", "padded_masks", "=", "np", ".", "stack", "(", "[", "mmcv", ".", "impad", "(", "mask", ",", "shape", "=", "out_shape", ",", "pad_val", "=", "pad_val", ")", "for", "mask", "in", "self", ".", "masks", "]", ")", "return", "BitmapMasks", "(", "padded_masks", ",", "*", "out_shape", ")" ]
[ 225, 4 ]
[ 234, 52 ]
python
de
['en', 'fil', 'de']
False
BitmapMasks.crop
(self, bbox)
See :func:`BaseInstanceMasks.crop`.
See :func:`BaseInstanceMasks.crop`.
def crop(self, bbox): """See :func:`BaseInstanceMasks.crop`.""" assert isinstance(bbox, np.ndarray) assert bbox.ndim == 1 # clip the boundary bbox = bbox.copy() bbox[0::2] = np.clip(bbox[0::2], 0, self.width) bbox[1::2] = np.clip(bbox[1::2], 0, self.height) x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) if len(self.masks) == 0: cropped_masks = np.empty((0, h, w), dtype=np.uint8) else: cropped_masks = self.masks[:, y1:y1 + h, x1:x1 + w] return BitmapMasks(cropped_masks, h, w)
[ "def", "crop", "(", "self", ",", "bbox", ")", ":", "assert", "isinstance", "(", "bbox", ",", "np", ".", "ndarray", ")", "assert", "bbox", ".", "ndim", "==", "1", "# clip the boundary", "bbox", "=", "bbox", ".", "copy", "(", ")", "bbox", "[", "0", ":", ":", "2", "]", "=", "np", ".", "clip", "(", "bbox", "[", "0", ":", ":", "2", "]", ",", "0", ",", "self", ".", "width", ")", "bbox", "[", "1", ":", ":", "2", "]", "=", "np", ".", "clip", "(", "bbox", "[", "1", ":", ":", "2", "]", ",", "0", ",", "self", ".", "height", ")", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "bbox", "w", "=", "np", ".", "maximum", "(", "x2", "-", "x1", ",", "1", ")", "h", "=", "np", ".", "maximum", "(", "y2", "-", "y1", ",", "1", ")", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "cropped_masks", "=", "np", ".", "empty", "(", "(", "0", ",", "h", ",", "w", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "else", ":", "cropped_masks", "=", "self", ".", "masks", "[", ":", ",", "y1", ":", "y1", "+", "h", ",", "x1", ":", "x1", "+", "w", "]", "return", "BitmapMasks", "(", "cropped_masks", ",", "h", ",", "w", ")" ]
[ 236, 4 ]
[ 253, 47 ]
python
de
['en', 'de', 'de']
False
BitmapMasks.crop_and_resize
(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear')
See :func:`BaseInstanceMasks.crop_and_resize`.
See :func:`BaseInstanceMasks.crop_and_resize`.
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear'): """See :func:`BaseInstanceMasks.crop_and_resize`.""" if len(self.masks) == 0: empty_masks = np.empty((0, *out_shape), dtype=np.uint8) return BitmapMasks(empty_masks, *out_shape) # convert bboxes to tensor if isinstance(bboxes, np.ndarray): bboxes = torch.from_numpy(bboxes).to(device=device) if isinstance(inds, np.ndarray): inds = torch.from_numpy(inds).to(device=device) num_bbox = bboxes.shape[0] fake_inds = torch.arange( num_bbox, device=device).to(dtype=bboxes.dtype)[:, None] rois = torch.cat([fake_inds, bboxes], dim=1) # Nx5 rois = rois.to(device=device) if num_bbox > 0: gt_masks_th = torch.from_numpy(self.masks).to(device).index_select( 0, inds).to(dtype=rois.dtype) targets = roi_align(gt_masks_th[:, None, :, :], rois, out_shape, 1.0, 0, 'avg', True).squeeze(1) resized_masks = (targets >= 0.5).cpu().numpy() else: resized_masks = [] return BitmapMasks(resized_masks, *out_shape)
[ "def", "crop_and_resize", "(", "self", ",", "bboxes", ",", "out_shape", ",", "inds", ",", "device", "=", "'cpu'", ",", "interpolation", "=", "'bilinear'", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "empty_masks", "=", "np", ".", "empty", "(", "(", "0", ",", "*", "out_shape", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "return", "BitmapMasks", "(", "empty_masks", ",", "*", "out_shape", ")", "# convert bboxes to tensor", "if", "isinstance", "(", "bboxes", ",", "np", ".", "ndarray", ")", ":", "bboxes", "=", "torch", ".", "from_numpy", "(", "bboxes", ")", ".", "to", "(", "device", "=", "device", ")", "if", "isinstance", "(", "inds", ",", "np", ".", "ndarray", ")", ":", "inds", "=", "torch", ".", "from_numpy", "(", "inds", ")", ".", "to", "(", "device", "=", "device", ")", "num_bbox", "=", "bboxes", ".", "shape", "[", "0", "]", "fake_inds", "=", "torch", ".", "arange", "(", "num_bbox", ",", "device", "=", "device", ")", ".", "to", "(", "dtype", "=", "bboxes", ".", "dtype", ")", "[", ":", ",", "None", "]", "rois", "=", "torch", ".", "cat", "(", "[", "fake_inds", ",", "bboxes", "]", ",", "dim", "=", "1", ")", "# Nx5", "rois", "=", "rois", ".", "to", "(", "device", "=", "device", ")", "if", "num_bbox", ">", "0", ":", "gt_masks_th", "=", "torch", ".", "from_numpy", "(", "self", ".", "masks", ")", ".", "to", "(", "device", ")", ".", "index_select", "(", "0", ",", "inds", ")", ".", "to", "(", "dtype", "=", "rois", ".", "dtype", ")", "targets", "=", "roi_align", "(", "gt_masks_th", "[", ":", ",", "None", ",", ":", ",", ":", "]", ",", "rois", ",", "out_shape", ",", "1.0", ",", "0", ",", "'avg'", ",", "True", ")", ".", "squeeze", "(", "1", ")", "resized_masks", "=", "(", "targets", ">=", "0.5", ")", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "else", ":", "resized_masks", "=", "[", "]", "return", "BitmapMasks", "(", "resized_masks", ",", "*", "out_shape", ")" ]
[ 255, 4 ]
[ 285, 53 ]
python
en
['en', 'en', 'de']
False
BitmapMasks.expand
(self, expanded_h, expanded_w, top, left)
See :func:`BaseInstanceMasks.expand`.
See :func:`BaseInstanceMasks.expand`.
def expand(self, expanded_h, expanded_w, top, left): """See :func:`BaseInstanceMasks.expand`.""" if len(self.masks) == 0: expanded_mask = np.empty((0, expanded_h, expanded_w), dtype=np.uint8) else: expanded_mask = np.zeros((len(self), expanded_h, expanded_w), dtype=np.uint8) expanded_mask[:, top:top + self.height, left:left + self.width] = self.masks return BitmapMasks(expanded_mask, expanded_h, expanded_w)
[ "def", "expand", "(", "self", ",", "expanded_h", ",", "expanded_w", ",", "top", ",", "left", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "expanded_mask", "=", "np", ".", "empty", "(", "(", "0", ",", "expanded_h", ",", "expanded_w", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "else", ":", "expanded_mask", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ")", ",", "expanded_h", ",", "expanded_w", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "expanded_mask", "[", ":", ",", "top", ":", "top", "+", "self", ".", "height", ",", "left", ":", "left", "+", "self", ".", "width", "]", "=", "self", ".", "masks", "return", "BitmapMasks", "(", "expanded_mask", ",", "expanded_h", ",", "expanded_w", ")" ]
[ 287, 4 ]
[ 297, 65 ]
python
en
['en', 'en', 'de']
False
BitmapMasks.areas
(self)
See :py:attr:`BaseInstanceMasks.areas`.
See :py:attr:`BaseInstanceMasks.areas`.
def areas(self): """See :py:attr:`BaseInstanceMasks.areas`.""" return self.masks.sum((1, 2))
[ "def", "areas", "(", "self", ")", ":", "return", "self", ".", "masks", ".", "sum", "(", "(", "1", ",", "2", ")", ")" ]
[ 300, 4 ]
[ 302, 37 ]
python
de
['en', 'de', 'de']
False
BitmapMasks.to_ndarray
(self)
See :func:`BaseInstanceMasks.to_ndarray`.
See :func:`BaseInstanceMasks.to_ndarray`.
def to_ndarray(self): """See :func:`BaseInstanceMasks.to_ndarray`.""" return self.masks
[ "def", "to_ndarray", "(", "self", ")", ":", "return", "self", ".", "masks" ]
[ 304, 4 ]
[ 306, 25 ]
python
en
['en', 'en', 'hi']
False
BitmapMasks.to_tensor
(self, dtype, device)
See :func:`BaseInstanceMasks.to_tensor`.
See :func:`BaseInstanceMasks.to_tensor`.
def to_tensor(self, dtype, device): """See :func:`BaseInstanceMasks.to_tensor`.""" return torch.tensor(self.masks, dtype=dtype, device=device)
[ "def", "to_tensor", "(", "self", ",", "dtype", ",", "device", ")", ":", "return", "torch", ".", "tensor", "(", "self", ".", "masks", ",", "dtype", "=", "dtype", ",", "device", "=", "device", ")" ]
[ 308, 4 ]
[ 310, 67 ]
python
en
['en', 'en', 'de']
False
PolygonMasks.__getitem__
(self, index)
Index the polygon masks. Args: index (ndarray | List): The indices. Returns: :obj:`PolygonMasks`: The indexed polygon masks.
Index the polygon masks.
def __getitem__(self, index): """Index the polygon masks. Args: index (ndarray | List): The indices. Returns: :obj:`PolygonMasks`: The indexed polygon masks. """ if isinstance(index, np.ndarray): index = index.tolist() if isinstance(index, list): masks = [self.masks[i] for i in index] else: try: masks = self.masks[index] except Exception: raise ValueError( f'Unsupported input of type {type(index)} for indexing!') if isinstance(masks[0], np.ndarray): masks = [masks] # ensure a list of three levels return PolygonMasks(masks, self.height, self.width)
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "np", ".", "ndarray", ")", ":", "index", "=", "index", ".", "tolist", "(", ")", "if", "isinstance", "(", "index", ",", "list", ")", ":", "masks", "=", "[", "self", ".", "masks", "[", "i", "]", "for", "i", "in", "index", "]", "else", ":", "try", ":", "masks", "=", "self", ".", "masks", "[", "index", "]", "except", "Exception", ":", "raise", "ValueError", "(", "f'Unsupported input of type {type(index)} for indexing!'", ")", "if", "isinstance", "(", "masks", "[", "0", "]", ",", "np", ".", "ndarray", ")", ":", "masks", "=", "[", "masks", "]", "# ensure a list of three levels", "return", "PolygonMasks", "(", "masks", ",", "self", ".", "height", ",", "self", ".", "width", ")" ]
[ 338, 4 ]
[ 359, 59 ]
python
en
['en', 'en', 'en']
True
PolygonMasks.__len__
(self)
Number of masks.
Number of masks.
def __len__(self): """Number of masks.""" return len(self.masks)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "masks", ")" ]
[ 371, 4 ]
[ 373, 30 ]
python
en
['en', 'da', 'en']
True
PolygonMasks.rescale
(self, scale, interpolation=None)
see :func:`BaseInstanceMasks.rescale`
see :func:`BaseInstanceMasks.rescale`
def rescale(self, scale, interpolation=None): """see :func:`BaseInstanceMasks.rescale`""" new_w, new_h = mmcv.rescale_size((self.width, self.height), scale) if len(self.masks) == 0: rescaled_masks = PolygonMasks([], new_h, new_w) else: rescaled_masks = self.resize((new_h, new_w)) return rescaled_masks
[ "def", "rescale", "(", "self", ",", "scale", ",", "interpolation", "=", "None", ")", ":", "new_w", ",", "new_h", "=", "mmcv", ".", "rescale_size", "(", "(", "self", ".", "width", ",", "self", ".", "height", ")", ",", "scale", ")", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "rescaled_masks", "=", "PolygonMasks", "(", "[", "]", ",", "new_h", ",", "new_w", ")", "else", ":", "rescaled_masks", "=", "self", ".", "resize", "(", "(", "new_h", ",", "new_w", ")", ")", "return", "rescaled_masks" ]
[ 375, 4 ]
[ 382, 29 ]
python
en
['en', 'en', 'it']
False
PolygonMasks.resize
(self, out_shape, interpolation=None)
see :func:`BaseInstanceMasks.resize`
see :func:`BaseInstanceMasks.resize`
def resize(self, out_shape, interpolation=None): """see :func:`BaseInstanceMasks.resize`""" if len(self.masks) == 0: resized_masks = PolygonMasks([], *out_shape) else: h_scale = out_shape[0] / self.height w_scale = out_shape[1] / self.width resized_masks = [] for poly_per_obj in self.masks: resized_poly = [] for p in poly_per_obj: p = p.copy() p[0::2] *= w_scale p[1::2] *= h_scale resized_poly.append(p) resized_masks.append(resized_poly) resized_masks = PolygonMasks(resized_masks, *out_shape) return resized_masks
[ "def", "resize", "(", "self", ",", "out_shape", ",", "interpolation", "=", "None", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "resized_masks", "=", "PolygonMasks", "(", "[", "]", ",", "*", "out_shape", ")", "else", ":", "h_scale", "=", "out_shape", "[", "0", "]", "/", "self", ".", "height", "w_scale", "=", "out_shape", "[", "1", "]", "/", "self", ".", "width", "resized_masks", "=", "[", "]", "for", "poly_per_obj", "in", "self", ".", "masks", ":", "resized_poly", "=", "[", "]", "for", "p", "in", "poly_per_obj", ":", "p", "=", "p", ".", "copy", "(", ")", "p", "[", "0", ":", ":", "2", "]", "*=", "w_scale", "p", "[", "1", ":", ":", "2", "]", "*=", "h_scale", "resized_poly", ".", "append", "(", "p", ")", "resized_masks", ".", "append", "(", "resized_poly", ")", "resized_masks", "=", "PolygonMasks", "(", "resized_masks", ",", "*", "out_shape", ")", "return", "resized_masks" ]
[ 384, 4 ]
[ 401, 28 ]
python
en
['en', 'jv', 'it']
False
PolygonMasks.flip
(self, flip_direction='horizontal')
see :func:`BaseInstanceMasks.flip`
see :func:`BaseInstanceMasks.flip`
def flip(self, flip_direction='horizontal'): """see :func:`BaseInstanceMasks.flip`""" assert flip_direction in ('horizontal', 'vertical') if len(self.masks) == 0: flipped_masks = PolygonMasks([], self.height, self.width) else: if flip_direction == 'horizontal': dim = self.width idx = 0 else: dim = self.height idx = 1 flipped_masks = [] for poly_per_obj in self.masks: flipped_poly_per_obj = [] for p in poly_per_obj: p = p.copy() p[idx::2] = dim - p[idx::2] flipped_poly_per_obj.append(p) flipped_masks.append(flipped_poly_per_obj) flipped_masks = PolygonMasks(flipped_masks, self.height, self.width) return flipped_masks
[ "def", "flip", "(", "self", ",", "flip_direction", "=", "'horizontal'", ")", ":", "assert", "flip_direction", "in", "(", "'horizontal'", ",", "'vertical'", ")", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "flipped_masks", "=", "PolygonMasks", "(", "[", "]", ",", "self", ".", "height", ",", "self", ".", "width", ")", "else", ":", "if", "flip_direction", "==", "'horizontal'", ":", "dim", "=", "self", ".", "width", "idx", "=", "0", "else", ":", "dim", "=", "self", ".", "height", "idx", "=", "1", "flipped_masks", "=", "[", "]", "for", "poly_per_obj", "in", "self", ".", "masks", ":", "flipped_poly_per_obj", "=", "[", "]", "for", "p", "in", "poly_per_obj", ":", "p", "=", "p", ".", "copy", "(", ")", "p", "[", "idx", ":", ":", "2", "]", "=", "dim", "-", "p", "[", "idx", ":", ":", "2", "]", "flipped_poly_per_obj", ".", "append", "(", "p", ")", "flipped_masks", ".", "append", "(", "flipped_poly_per_obj", ")", "flipped_masks", "=", "PolygonMasks", "(", "flipped_masks", ",", "self", ".", "height", ",", "self", ".", "width", ")", "return", "flipped_masks" ]
[ 403, 4 ]
[ 425, 28 ]
python
de
['en', 'de', 'it']
False
PolygonMasks.crop
(self, bbox)
see :func:`BaseInstanceMasks.crop`
see :func:`BaseInstanceMasks.crop`
def crop(self, bbox): """see :func:`BaseInstanceMasks.crop`""" assert isinstance(bbox, np.ndarray) assert bbox.ndim == 1 # clip the boundary bbox = bbox.copy() bbox[0::2] = np.clip(bbox[0::2], 0, self.width) bbox[1::2] = np.clip(bbox[1::2], 0, self.height) x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) if len(self.masks) == 0: cropped_masks = PolygonMasks([], h, w) else: cropped_masks = [] for poly_per_obj in self.masks: cropped_poly_per_obj = [] for p in poly_per_obj: # pycocotools will clip the boundary p = p.copy() p[0::2] -= bbox[0] p[1::2] -= bbox[1] cropped_poly_per_obj.append(p) cropped_masks.append(cropped_poly_per_obj) cropped_masks = PolygonMasks(cropped_masks, h, w) return cropped_masks
[ "def", "crop", "(", "self", ",", "bbox", ")", ":", "assert", "isinstance", "(", "bbox", ",", "np", ".", "ndarray", ")", "assert", "bbox", ".", "ndim", "==", "1", "# clip the boundary", "bbox", "=", "bbox", ".", "copy", "(", ")", "bbox", "[", "0", ":", ":", "2", "]", "=", "np", ".", "clip", "(", "bbox", "[", "0", ":", ":", "2", "]", ",", "0", ",", "self", ".", "width", ")", "bbox", "[", "1", ":", ":", "2", "]", "=", "np", ".", "clip", "(", "bbox", "[", "1", ":", ":", "2", "]", ",", "0", ",", "self", ".", "height", ")", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "bbox", "w", "=", "np", ".", "maximum", "(", "x2", "-", "x1", ",", "1", ")", "h", "=", "np", ".", "maximum", "(", "y2", "-", "y1", ",", "1", ")", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "cropped_masks", "=", "PolygonMasks", "(", "[", "]", ",", "h", ",", "w", ")", "else", ":", "cropped_masks", "=", "[", "]", "for", "poly_per_obj", "in", "self", ".", "masks", ":", "cropped_poly_per_obj", "=", "[", "]", "for", "p", "in", "poly_per_obj", ":", "# pycocotools will clip the boundary", "p", "=", "p", ".", "copy", "(", ")", "p", "[", "0", ":", ":", "2", "]", "-=", "bbox", "[", "0", "]", "p", "[", "1", ":", ":", "2", "]", "-=", "bbox", "[", "1", "]", "cropped_poly_per_obj", ".", "append", "(", "p", ")", "cropped_masks", ".", "append", "(", "cropped_poly_per_obj", ")", "cropped_masks", "=", "PolygonMasks", "(", "cropped_masks", ",", "h", ",", "w", ")", "return", "cropped_masks" ]
[ 427, 4 ]
[ 454, 28 ]
python
de
['en', 'de', 'it']
False
PolygonMasks.pad
(self, out_shape, pad_val=0)
padding has no effect on polygons`
padding has no effect on polygons`
def pad(self, out_shape, pad_val=0): """padding has no effect on polygons`""" return PolygonMasks(self.masks, *out_shape)
[ "def", "pad", "(", "self", ",", "out_shape", ",", "pad_val", "=", "0", ")", ":", "return", "PolygonMasks", "(", "self", ".", "masks", ",", "*", "out_shape", ")" ]
[ 456, 4 ]
[ 458, 51 ]
python
en
['en', 'en', 'en']
True
PolygonMasks.expand
(self, *args, **kwargs)
TODO: Add expand for polygon
TODO: Add expand for polygon
def expand(self, *args, **kwargs): """TODO: Add expand for polygon""" raise NotImplementedError
[ "def", "expand", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
[ 460, 4 ]
[ 462, 33 ]
python
en
['en', 'en', 'en']
True
PolygonMasks.crop_and_resize
(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear')
see :func:`BaseInstanceMasks.crop_and_resize`
see :func:`BaseInstanceMasks.crop_and_resize`
def crop_and_resize(self, bboxes, out_shape, inds, device='cpu', interpolation='bilinear'): """see :func:`BaseInstanceMasks.crop_and_resize`""" out_h, out_w = out_shape if len(self.masks) == 0: return PolygonMasks([], out_h, out_w) resized_masks = [] for i in range(len(bboxes)): mask = self.masks[inds[i]] bbox = bboxes[i, :] x1, y1, x2, y2 = bbox w = np.maximum(x2 - x1, 1) h = np.maximum(y2 - y1, 1) h_scale = out_h / max(h, 0.1) # avoid too large scale w_scale = out_w / max(w, 0.1) resized_mask = [] for p in mask: p = p.copy() # crop # pycocotools will clip the boundary p[0::2] -= bbox[0] p[1::2] -= bbox[1] # resize p[0::2] *= w_scale p[1::2] *= h_scale resized_mask.append(p) resized_masks.append(resized_mask) return PolygonMasks(resized_masks, *out_shape)
[ "def", "crop_and_resize", "(", "self", ",", "bboxes", ",", "out_shape", ",", "inds", ",", "device", "=", "'cpu'", ",", "interpolation", "=", "'bilinear'", ")", ":", "out_h", ",", "out_w", "=", "out_shape", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "return", "PolygonMasks", "(", "[", "]", ",", "out_h", ",", "out_w", ")", "resized_masks", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "bboxes", ")", ")", ":", "mask", "=", "self", ".", "masks", "[", "inds", "[", "i", "]", "]", "bbox", "=", "bboxes", "[", "i", ",", ":", "]", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "bbox", "w", "=", "np", ".", "maximum", "(", "x2", "-", "x1", ",", "1", ")", "h", "=", "np", ".", "maximum", "(", "y2", "-", "y1", ",", "1", ")", "h_scale", "=", "out_h", "/", "max", "(", "h", ",", "0.1", ")", "# avoid too large scale", "w_scale", "=", "out_w", "/", "max", "(", "w", ",", "0.1", ")", "resized_mask", "=", "[", "]", "for", "p", "in", "mask", ":", "p", "=", "p", ".", "copy", "(", ")", "# crop", "# pycocotools will clip the boundary", "p", "[", "0", ":", ":", "2", "]", "-=", "bbox", "[", "0", "]", "p", "[", "1", ":", ":", "2", "]", "-=", "bbox", "[", "1", "]", "# resize", "p", "[", "0", ":", ":", "2", "]", "*=", "w_scale", "p", "[", "1", ":", ":", "2", "]", "*=", "h_scale", "resized_mask", ".", "append", "(", "p", ")", "resized_masks", ".", "append", "(", "resized_mask", ")", "return", "PolygonMasks", "(", "resized_masks", ",", "*", "out_shape", ")" ]
[ 464, 4 ]
[ 498, 54 ]
python
en
['en', 'en', 'en']
False
PolygonMasks.to_bitmap
(self)
convert polygon masks to bitmap masks.
convert polygon masks to bitmap masks.
def to_bitmap(self): """convert polygon masks to bitmap masks.""" bitmap_masks = self.to_ndarray() return BitmapMasks(bitmap_masks, self.height, self.width)
[ "def", "to_bitmap", "(", "self", ")", ":", "bitmap_masks", "=", "self", ".", "to_ndarray", "(", ")", "return", "BitmapMasks", "(", "bitmap_masks", ",", "self", ".", "height", ",", "self", ".", "width", ")" ]
[ 500, 4 ]
[ 503, 65 ]
python
en
['en', 'fil', 'en']
True
PolygonMasks.areas
(self)
Compute areas of masks. This func is modified from https://github.com/facebookresearch/detectron2/blob/ffff8acc35ea88ad1cb1806ab0f00b4c1c5dbfd9/detectron2/structures/masks.py#L387 Only works with Polygons, using the shoelace formula Return: ndarray: areas of each instance
Compute areas of masks.
def areas(self): """Compute areas of masks. This func is modified from https://github.com/facebookresearch/detectron2/blob/ffff8acc35ea88ad1cb1806ab0f00b4c1c5dbfd9/detectron2/structures/masks.py#L387 Only works with Polygons, using the shoelace formula Return: ndarray: areas of each instance """ # noqa: W501 area = [] for polygons_per_obj in self.masks: area_per_obj = 0 for p in polygons_per_obj: area_per_obj += self._polygon_area(p[0::2], p[1::2]) area.append(area_per_obj) return np.asarray(area)
[ "def", "areas", "(", "self", ")", ":", "# noqa: W501", "area", "=", "[", "]", "for", "polygons_per_obj", "in", "self", ".", "masks", ":", "area_per_obj", "=", "0", "for", "p", "in", "polygons_per_obj", ":", "area_per_obj", "+=", "self", ".", "_polygon_area", "(", "p", "[", "0", ":", ":", "2", "]", ",", "p", "[", "1", ":", ":", "2", "]", ")", "area", ".", "append", "(", "area_per_obj", ")", "return", "np", ".", "asarray", "(", "area", ")" ]
[ 506, 4 ]
[ 522, 31 ]
python
en
['en', 'en', 'en']
True
PolygonMasks._polygon_area
(self, x, y)
Compute the area of a component of a polygon. Using the shoelace formula: https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates Args: x (ndarray): x coordinates of the component y (ndarray): y coordinates of the component Return: float: the are of the component
Compute the area of a component of a polygon.
def _polygon_area(self, x, y): """Compute the area of a component of a polygon. Using the shoelace formula: https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates Args: x (ndarray): x coordinates of the component y (ndarray): y coordinates of the component Return: float: the are of the component """ # noqa: 501 return 0.5 * np.abs( np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
[ "def", "_polygon_area", "(", "self", ",", "x", ",", "y", ")", ":", "# noqa: 501", "return", "0.5", "*", "np", ".", "abs", "(", "np", ".", "dot", "(", "x", ",", "np", ".", "roll", "(", "y", ",", "1", ")", ")", "-", "np", ".", "dot", "(", "y", ",", "np", ".", "roll", "(", "x", ",", "1", ")", ")", ")" ]
[ 524, 4 ]
[ 538, 64 ]
python
en
['en', 'en', 'en']
True
PolygonMasks.to_ndarray
(self)
Convert masks to the format of ndarray.
Convert masks to the format of ndarray.
def to_ndarray(self): """Convert masks to the format of ndarray.""" if len(self.masks) == 0: return np.empty((0, self.height, self.width), dtype=np.uint8) bitmap_masks = [] for poly_per_obj in self.masks: bitmap_masks.append( polygon_to_bitmap(poly_per_obj, self.height, self.width)) return np.stack(bitmap_masks)
[ "def", "to_ndarray", "(", "self", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "return", "np", ".", "empty", "(", "(", "0", ",", "self", ".", "height", ",", "self", ".", "width", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "bitmap_masks", "=", "[", "]", "for", "poly_per_obj", "in", "self", ".", "masks", ":", "bitmap_masks", ".", "append", "(", "polygon_to_bitmap", "(", "poly_per_obj", ",", "self", ".", "height", ",", "self", ".", "width", ")", ")", "return", "np", ".", "stack", "(", "bitmap_masks", ")" ]
[ 540, 4 ]
[ 548, 37 ]
python
en
['en', 'en', 'en']
True
PolygonMasks.to_tensor
(self, dtype, device)
See :func:`BaseInstanceMasks.to_tensor`.
See :func:`BaseInstanceMasks.to_tensor`.
def to_tensor(self, dtype, device): """See :func:`BaseInstanceMasks.to_tensor`.""" if len(self.masks) == 0: return torch.empty((0, self.height, self.width), dtype=dtype, device=device) ndarray_masks = self.to_ndarray() return torch.tensor(ndarray_masks, dtype=dtype, device=device)
[ "def", "to_tensor", "(", "self", ",", "dtype", ",", "device", ")", ":", "if", "len", "(", "self", ".", "masks", ")", "==", "0", ":", "return", "torch", ".", "empty", "(", "(", "0", ",", "self", ".", "height", ",", "self", ".", "width", ")", ",", "dtype", "=", "dtype", ",", "device", "=", "device", ")", "ndarray_masks", "=", "self", ".", "to_ndarray", "(", ")", "return", "torch", ".", "tensor", "(", "ndarray_masks", ",", "dtype", "=", "dtype", ",", "device", "=", "device", ")" ]
[ 550, 4 ]
[ 557, 70 ]
python
en
['en', 'en', 'de']
False
Font.color
(self)
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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above Returns ------- str|numpy.ndarray
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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above
def color(self): """ 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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 64, 28 ]
python
en
['en', 'error', 'th']
False
Font.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\"", "]" ]
[ 73, 4 ]
[ 84, 31 ]
python
en
['en', 'error', 'th']
False
Font.family
(self)
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above
def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"]
[ "def", "family", "(", "self", ")", ":", "return", "self", "[", "\"family\"", "]" ]
[ 93, 4 ]
[ 116, 29 ]
python
en
['en', 'error', 'th']
False
Font.familysrc
(self)
Sets the source reference on Chart Studio Cloud for family . The 'familysrc' 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 family . The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object
def familysrc(self): """ Sets the source reference on Chart Studio Cloud for family . The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["familysrc"]
[ "def", "familysrc", "(", "self", ")", ":", "return", "self", "[", "\"familysrc\"", "]" ]
[ 125, 4 ]
[ 136, 32 ]
python
en
['en', 'error', 'th']
False
Font.size
(self)
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above
def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"]
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 145, 4 ]
[ 155, 27 ]
python
en
['en', 'error', 'th']
False
Font.sizesrc
(self)
Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' 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 size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object
def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"]
[ "def", "sizesrc", "(", "self", ")", ":", "return", "self", "[", "\"sizesrc\"", "]" ]
[ 164, 4 ]
[ 175, 30 ]
python
en
['en', 'error', 'th']
False
Font.__init__
( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, size=None, sizesrc=None, **kwargs )
Construct a new Font object Sets the font used in hover labels. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.volume.hoverlabel.Font` color colorsrc Sets the source reference on Chart Studio Cloud for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . Returns ------- Font
Construct a new Font object Sets the font used in hover labels.
def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, size=None, sizesrc=None, **kwargs ): """ Construct a new Font object Sets the font used in hover labels. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.volume.hoverlabel.Font` color colorsrc Sets the source reference on Chart Studio Cloud for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . Returns ------- Font """ super(Font, self).__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.volume.hoverlabel.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.volume.hoverlabel.Font`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("colorsrc", None) _v = colorsrc if colorsrc is not None else _v if _v is not None: self["colorsrc"] = _v _v = arg.pop("family", None) _v = family if family is not None else _v if _v is not None: self["family"] = _v _v = arg.pop("familysrc", None) _v = familysrc if familysrc is not None else _v if _v is not None: self["familysrc"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v _v = arg.pop("sizesrc", None) _v = sizesrc if sizesrc is not None else _v if _v is not None: self["sizesrc"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "colorsrc", "=", "None", ",", "family", "=", "None", ",", "familysrc", "=", "None", ",", "size", "=", "None", ",", "sizesrc", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Font", ",", "self", ")", ".", "__init__", "(", "\"font\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.volume.hoverlabel.Font \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.volume.hoverlabel.Font`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"colorsrc\"", ",", "None", ")", "_v", "=", "colorsrc", "if", "colorsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"colorsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"family\"", ",", "None", ")", "_v", "=", "family", "if", "family", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"family\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"familysrc\"", ",", "None", ")", "_v", "=", "familysrc", "if", "familysrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"familysrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"size\"", ",", "None", ")", "_v", "=", "size", "if", "size", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"size\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"sizesrc\"", ",", "None", ")", "_v", "=", "sizesrc", "if", "sizesrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"sizesrc\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 215, 4 ]
[ 329, 34 ]
python
en
['en', 'error', 'th']
False
SplitTeacher.observe
(self, observation)
Process observation for metrics.
Process observation for metrics.
def observe(self, observation): """ Process observation for metrics. """ if self.lastY is not None: if self.asked_question: self.metrics.evaluate_response(observation, self.lastY[0]) else: self.factmetrics.evaluate_response(observation, self.lastY[1]) self.lastY = None return observation
[ "def", "observe", "(", "self", ",", "observation", ")", ":", "if", "self", ".", "lastY", "is", "not", "None", ":", "if", "self", ".", "asked_question", ":", "self", ".", "metrics", ".", "evaluate_response", "(", "observation", ",", "self", ".", "lastY", "[", "0", "]", ")", "else", ":", "self", ".", "factmetrics", ".", "evaluate_response", "(", "observation", ",", "self", ".", "lastY", "[", "1", "]", ")", "self", ".", "lastY", "=", "None", "return", "observation" ]
[ 103, 4 ]
[ 113, 26 ]
python
en
['en', 'error', 'th']
False
mccp_compress
(protocol, data)
Handles zlib compression, if applicable. Args: data (str): Incoming data to compress. Returns: stream (binary): Zlib-compressed data.
Handles zlib compression, if applicable.
def mccp_compress(protocol, data): """ Handles zlib compression, if applicable. Args: data (str): Incoming data to compress. Returns: stream (binary): Zlib-compressed data. """ if hasattr(protocol, 'zlib'): return protocol.zlib.compress(data) + protocol.zlib.flush(FLUSH) return data
[ "def", "mccp_compress", "(", "protocol", ",", "data", ")", ":", "if", "hasattr", "(", "protocol", ",", "'zlib'", ")", ":", "return", "protocol", ".", "zlib", ".", "compress", "(", "data", ")", "+", "protocol", ".", "zlib", ".", "flush", "(", "FLUSH", ")", "return", "data" ]
[ 24, 0 ]
[ 37, 15 ]
python
en
['en', 'error', 'th']
False
Mccp.__init__
(self, protocol)
initialize MCCP by storing protocol on ourselves and calling the client to see if it supports MCCP. Sets callbacks to start zlib compression in that case. Args: protocol (Protocol): The active protocol instance.
initialize MCCP by storing protocol on ourselves and calling the client to see if it supports MCCP. Sets callbacks to start zlib compression in that case.
def __init__(self, protocol): """ initialize MCCP by storing protocol on ourselves and calling the client to see if it supports MCCP. Sets callbacks to start zlib compression in that case. Args: protocol (Protocol): The active protocol instance. """ self.protocol = protocol self.protocol.protocol_flags['MCCP'] = False # ask if client will mccp, connect callbacks to handle answer self.protocol.will(MCCP).addCallbacks(self.do_mccp, self.no_mccp)
[ "def", "__init__", "(", "self", ",", "protocol", ")", ":", "self", ".", "protocol", "=", "protocol", "self", ".", "protocol", ".", "protocol_flags", "[", "'MCCP'", "]", "=", "False", "# ask if client will mccp, connect callbacks to handle answer", "self", ".", "protocol", ".", "will", "(", "MCCP", ")", ".", "addCallbacks", "(", "self", ".", "do_mccp", ",", "self", ".", "no_mccp", ")" ]
[ 47, 4 ]
[ 62, 73 ]
python
en
['en', 'error', 'th']
False
Mccp.no_mccp
(self, option)
Called if client doesn't support mccp or chooses to turn it off. Args: option (Option): Option dict (not used).
Called if client doesn't support mccp or chooses to turn it off.
def no_mccp(self, option): """ Called if client doesn't support mccp or chooses to turn it off. Args: option (Option): Option dict (not used). """ if hasattr(self.protocol, 'zlib'): del self.protocol.zlib self.protocol.protocol_flags['MCCP'] = False self.protocol.handshake_done()
[ "def", "no_mccp", "(", "self", ",", "option", ")", ":", "if", "hasattr", "(", "self", ".", "protocol", ",", "'zlib'", ")", ":", "del", "self", ".", "protocol", ".", "zlib", "self", ".", "protocol", ".", "protocol_flags", "[", "'MCCP'", "]", "=", "False", "self", ".", "protocol", ".", "handshake_done", "(", ")" ]
[ 64, 4 ]
[ 75, 38 ]
python
en
['en', 'error', 'th']
False
Mccp.do_mccp
(self, option)
The client supports MCCP. Set things up by creating a zlib compression stream. Args: option (Option): Option dict (not used).
The client supports MCCP. Set things up by creating a zlib compression stream.
def do_mccp(self, option): """ The client supports MCCP. Set things up by creating a zlib compression stream. Args: option (Option): Option dict (not used). """ self.protocol.protocol_flags['MCCP'] = True self.protocol.requestNegotiation(MCCP, '') self.protocol.zlib = zlib.compressobj(9) self.protocol.handshake_done()
[ "def", "do_mccp", "(", "self", ",", "option", ")", ":", "self", ".", "protocol", ".", "protocol_flags", "[", "'MCCP'", "]", "=", "True", "self", ".", "protocol", ".", "requestNegotiation", "(", "MCCP", ",", "''", ")", "self", ".", "protocol", ".", "zlib", "=", "zlib", ".", "compressobj", "(", "9", ")", "self", ".", "protocol", ".", "handshake_done", "(", ")" ]
[ 77, 4 ]
[ 89, 38 ]
python
en
['en', 'error', 'th']
False
IndyIssuer.__init__
(self, wallet)
Initialize an IndyLedger instance. Args: wallet: IndyWallet instance
Initialize an IndyLedger instance.
def __init__(self, wallet): """ Initialize an IndyLedger instance. Args: wallet: IndyWallet instance """ self.logger = logging.getLogger(__name__) self.wallet = wallet
[ "def", "__init__", "(", "self", ",", "wallet", ")", ":", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "self", ".", "wallet", "=", "wallet" ]
[ 20, 4 ]
[ 29, 28 ]
python
en
['en', 'error', 'th']
False
IndyIssuer.create_credential_offer
(self, credential_definition_id: str)
Create a credential offer for the given credential definition id. Args: credential_definition_id: The credential definition to create an offer for Returns: A credential offer
Create a credential offer for the given credential definition id.
async def create_credential_offer(self, credential_definition_id: str): """ Create a credential offer for the given credential definition id. Args: credential_definition_id: The credential definition to create an offer for Returns: A credential offer """ credential_offer_json = await indy.anoncreds.issuer_create_credential_offer( self.wallet.handle, credential_definition_id ) credential_offer = json.loads(credential_offer_json) return credential_offer
[ "async", "def", "create_credential_offer", "(", "self", ",", "credential_definition_id", ":", "str", ")", ":", "credential_offer_json", "=", "await", "indy", ".", "anoncreds", ".", "issuer_create_credential_offer", "(", "self", ".", "wallet", ".", "handle", ",", "credential_definition_id", ")", "credential_offer", "=", "json", ".", "loads", "(", "credential_offer_json", ")", "return", "credential_offer" ]
[ 31, 4 ]
[ 48, 31 ]
python
en
['en', 'error', 'th']
False
IndyIssuer.create_credential
( self, schema, credential_offer, credential_request, credential_values )
Create a credential. Args schema: Schema to create credential for credential_offer: Credential Offer to create credential for credential_request: Credential request to create credential for credential_values: Values to go in credential Returns: A tuple of created credential, revocation id
Create a credential.
async def create_credential( self, schema, credential_offer, credential_request, credential_values ): """ Create a credential. Args schema: Schema to create credential for credential_offer: Credential Offer to create credential for credential_request: Credential request to create credential for credential_values: Values to go in credential Returns: A tuple of created credential, revocation id """ encoded_values = {} schema_attributes = schema["attrNames"] for attribute in schema_attributes: # Ensure every attribute present in schema to be set. # Extraneous attribute names are ignored. try: credential_value = credential_values[attribute] except KeyError: raise IssuerError( "Provided credential values are missing a value " + f"for the schema attribute '{attribute}'" ) encoded_values[attribute] = {} encoded_values[attribute]["raw"] = str(credential_value) encoded_values[attribute]["encoded"] = encode(credential_value) ( credential_json, credential_revocation_id, _, ) = await indy.anoncreds.issuer_create_credential( self.wallet.handle, json.dumps(credential_offer), json.dumps(credential_request), json.dumps(encoded_values), None, None, ) return json.loads(credential_json), credential_revocation_id
[ "async", "def", "create_credential", "(", "self", ",", "schema", ",", "credential_offer", ",", "credential_request", ",", "credential_values", ")", ":", "encoded_values", "=", "{", "}", "schema_attributes", "=", "schema", "[", "\"attrNames\"", "]", "for", "attribute", "in", "schema_attributes", ":", "# Ensure every attribute present in schema to be set.", "# Extraneous attribute names are ignored.", "try", ":", "credential_value", "=", "credential_values", "[", "attribute", "]", "except", "KeyError", ":", "raise", "IssuerError", "(", "\"Provided credential values are missing a value \"", "+", "f\"for the schema attribute '{attribute}'\"", ")", "encoded_values", "[", "attribute", "]", "=", "{", "}", "encoded_values", "[", "attribute", "]", "[", "\"raw\"", "]", "=", "str", "(", "credential_value", ")", "encoded_values", "[", "attribute", "]", "[", "\"encoded\"", "]", "=", "encode", "(", "credential_value", ")", "(", "credential_json", ",", "credential_revocation_id", ",", "_", ",", ")", "=", "await", "indy", ".", "anoncreds", ".", "issuer_create_credential", "(", "self", ".", "wallet", ".", "handle", ",", "json", ".", "dumps", "(", "credential_offer", ")", ",", "json", ".", "dumps", "(", "credential_request", ")", ",", "json", ".", "dumps", "(", "encoded_values", ")", ",", "None", ",", "None", ",", ")", "return", "json", ".", "loads", "(", "credential_json", ")", ",", "credential_revocation_id" ]
[ 50, 4 ]
[ 97, 68 ]
python
en
['en', 'error', 'th']
False
Line.color
(self)
Sets the color of the contour level. Has no effect if `contours.coloring` is set to "lines". 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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the color of the contour level. Has no effect if `contours.coloring` is set to "lines". 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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
def color(self): """ Sets the color of the contour level. Has no effect if `contours.coloring` is set to "lines". 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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 66, 28 ]
python
en
['en', 'error', 'th']
False
Line.dash
(self)
Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'dash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) Returns ------- str
Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'dash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.)
def dash(self): """ Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'dash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) Returns ------- str """ return self["dash"]
[ "def", "dash", "(", "self", ")", ":", "return", "self", "[", "\"dash\"", "]" ]
[ 75, 4 ]
[ 92, 27 ]
python
en
['en', 'error', 'th']
False
Line.smoothing
(self)
Sets the amount of smoothing for the contour lines, where 0 corresponds to no smoothing. The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3] Returns ------- int|float
Sets the amount of smoothing for the contour lines, where 0 corresponds to no smoothing. The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3]
def smoothing(self): """ Sets the amount of smoothing for the contour lines, where 0 corresponds to no smoothing. The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3] Returns ------- int|float """ return self["smoothing"]
[ "def", "smoothing", "(", "self", ")", ":", "return", "self", "[", "\"smoothing\"", "]" ]
[ 101, 4 ]
[ 113, 32 ]
python
en
['en', 'error', 'th']
False
Line.width
(self)
Sets the contour line width in (in px) Defaults to 0.5 when `contours.type` is "levels". Defaults to 2 when `contour.type` is "constraint". The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the contour line width in (in px) Defaults to 0.5 when `contours.type` is "levels". Defaults to 2 when `contour.type` is "constraint". The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf]
def width(self): """ Sets the contour line width in (in px) Defaults to 0.5 when `contours.type` is "levels". Defaults to 2 when `contour.type` is "constraint". The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["width"]
[ "def", "width", "(", "self", ")", ":", "return", "self", "[", "\"width\"", "]" ]
[ 122, 4 ]
[ 135, 28 ]
python
en
['en', 'error', 'th']
False
Line.__init__
( self, arg=None, color=None, dash=None, smoothing=None, width=None, **kwargs )
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.contourcarpet.Line` color Sets the color of the contour level. Has no effect if `contours.coloring` is set to "lines". dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). smoothing Sets the amount of smoothing for the contour lines, where 0 corresponds to no smoothing. width Sets the contour line width in (in px) Defaults to 0.5 when `contours.type` is "levels". Defaults to 2 when `contour.type` is "constraint". Returns ------- Line
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.contourcarpet.Line` color Sets the color of the contour level. Has no effect if `contours.coloring` is set to "lines". dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). smoothing Sets the amount of smoothing for the contour lines, where 0 corresponds to no smoothing. width Sets the contour line width in (in px) Defaults to 0.5 when `contours.type` is "levels". Defaults to 2 when `contour.type` is "constraint".
def __init__( self, arg=None, color=None, dash=None, smoothing=None, width=None, **kwargs ): """ Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.contourcarpet.Line` color Sets the color of the contour level. Has no effect if `contours.coloring` is set to "lines". dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). smoothing Sets the amount of smoothing for the contour lines, where 0 corresponds to no smoothing. width Sets the contour line width in (in px) Defaults to 0.5 when `contours.type` is "levels". Defaults to 2 when `contour.type` is "constraint". Returns ------- Line """ super(Line, self).__init__("line") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.contourcarpet.Line constructor must be a dict or an instance of :class:`plotly.graph_objs.contourcarpet.Line`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("dash", None) _v = dash if dash is not None else _v if _v is not None: self["dash"] = _v _v = arg.pop("smoothing", None) _v = smoothing if smoothing is not None else _v if _v is not None: self["smoothing"] = _v _v = arg.pop("width", None) _v = width if width is not None else _v if _v is not None: self["width"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "dash", "=", "None", ",", "smoothing", "=", "None", ",", "width", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Line", ",", "self", ")", ".", "__init__", "(", "\"line\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.contourcarpet.Line \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.contourcarpet.Line`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"dash\"", ",", "None", ")", "_v", "=", "dash", "if", "dash", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"dash\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"smoothing\"", ",", "None", ")", "_v", "=", "smoothing", "if", "smoothing", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"smoothing\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"width\"", ",", "None", ")", "_v", "=", "width", "if", "width", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"width\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 163, 4 ]
[ 247, 34 ]
python
en
['en', 'error', 'th']
False
TimeoutUtils.get_timeout_act
( agent: Agent, timeout: int = DEFAULT_TIMEOUT, quick_replies: Optional[List[str]] = None, )
Return an agent's act, with a specified timeout. :param agent: Agent who is acting :param timeout: how long to wait :param quick_replies: If given, agent's message *MUST* be one of the quick replies :return: An act dictionary if no timeout; else, None
Return an agent's act, with a specified timeout.
def get_timeout_act( agent: Agent, timeout: int = DEFAULT_TIMEOUT, quick_replies: Optional[List[str]] = None, ) -> Optional[Message]: """ Return an agent's act, with a specified timeout. :param agent: Agent who is acting :param timeout: how long to wait :param quick_replies: If given, agent's message *MUST* be one of the quick replies :return: An act dictionary if no timeout; else, None """ def _is_valid(act): return act.get("text", "") in quick_replies if quick_replies else True act = None curr_time = time.time() allowed_timeout = timeout while act is None and time.time() - curr_time < allowed_timeout: act = agent.act() if act is not None and not _is_valid(act): agent.observe( { "id": "", "text": "Invalid response. Please choose one of the quick replies", "quick_replies": quick_replies, } ) time.sleep(THREAD_SLEEP) # TODO: use threading.Event() rather than polling return act
[ "def", "get_timeout_act", "(", "agent", ":", "Agent", ",", "timeout", ":", "int", "=", "DEFAULT_TIMEOUT", ",", "quick_replies", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", ")", "->", "Optional", "[", "Message", "]", ":", "def", "_is_valid", "(", "act", ")", ":", "return", "act", ".", "get", "(", "\"text\"", ",", "\"\"", ")", "in", "quick_replies", "if", "quick_replies", "else", "True", "act", "=", "None", "curr_time", "=", "time", ".", "time", "(", ")", "allowed_timeout", "=", "timeout", "while", "act", "is", "None", "and", "time", ".", "time", "(", ")", "-", "curr_time", "<", "allowed_timeout", ":", "act", "=", "agent", ".", "act", "(", ")", "if", "act", "is", "not", "None", "and", "not", "_is_valid", "(", "act", ")", ":", "agent", ".", "observe", "(", "{", "\"id\"", ":", "\"\"", ",", "\"text\"", ":", "\"Invalid response. Please choose one of the quick replies\"", ",", "\"quick_replies\"", ":", "quick_replies", ",", "}", ")", "time", ".", "sleep", "(", "THREAD_SLEEP", ")", "# TODO: use threading.Event() rather than polling", "return", "act" ]
[ 21, 4 ]
[ 57, 18 ]
python
en
['en', 'error', 'th']
False
TimeoutUtils._get_response_timeout_loop
( agent: Agent, world: World, timeout: int = DEFAULT_TIMEOUT, timeout_msg: str = 'You have timed out', )
Get a response from the agent. :param agent: agent who is acting :param world: world in which agent is acting :param timeout: timeout in secs :param timeout_msg: what to say to agent when they timeout :return response: Response if given, else None
Get a response from the agent.
def _get_response_timeout_loop( agent: Agent, world: World, timeout: int = DEFAULT_TIMEOUT, timeout_msg: str = 'You have timed out', ) -> Optional[Message]: """ Get a response from the agent. :param agent: agent who is acting :param world: world in which agent is acting :param timeout: timeout in secs :param timeout_msg: what to say to agent when they timeout :return response: Response if given, else None """ a = TimeoutUtils.get_timeout_act(agent, timeout) if a is None: world.episodeDone = True # type: ignore agent.observe({"id": "", "text": timeout_msg}) return None if (a.get("text", "") or "").upper() == "EXIT": world.episodeDone = True # type: ignore return None return a
[ "def", "_get_response_timeout_loop", "(", "agent", ":", "Agent", ",", "world", ":", "World", ",", "timeout", ":", "int", "=", "DEFAULT_TIMEOUT", ",", "timeout_msg", ":", "str", "=", "'You have timed out'", ",", ")", "->", "Optional", "[", "Message", "]", ":", "a", "=", "TimeoutUtils", ".", "get_timeout_act", "(", "agent", ",", "timeout", ")", "if", "a", "is", "None", ":", "world", ".", "episodeDone", "=", "True", "# type: ignore", "agent", ".", "observe", "(", "{", "\"id\"", ":", "\"\"", ",", "\"text\"", ":", "timeout_msg", "}", ")", "return", "None", "if", "(", "a", ".", "get", "(", "\"text\"", ",", "\"\"", ")", "or", "\"\"", ")", ".", "upper", "(", ")", "==", "\"EXIT\"", ":", "world", ".", "episodeDone", "=", "True", "# type: ignore", "return", "None", "return", "a" ]
[ 60, 4 ]
[ 90, 16 ]
python
en
['en', 'error', 'th']
False
test_Figure
()
if the fig is not associated with a canvas, FakeRenderer shall not fail.
if the fig is not associated with a canvas, FakeRenderer shall not fail.
def test_Figure(): """ if the fig is not associated with a canvas, FakeRenderer shall not fail. """ fig = plt.Figure() ax = fig.add_subplot(111) ax.add_patch(plt.Circle((0, 0), 1)) ax.add_patch(plt.Rectangle((0, 0), 1, 2)) _assert_output_equal(fake_renderer_output(fig, FakeRenderer), """ opening figure opening axes draw path with 25 vertices draw path with 4 vertices closing axes closing figure """)
[ "def", "test_Figure", "(", ")", ":", "fig", "=", "plt", ".", "Figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "ax", ".", "add_patch", "(", "plt", ".", "Circle", "(", "(", "0", ",", "0", ")", ",", "1", ")", ")", "ax", ".", "add_patch", "(", "plt", ".", "Rectangle", "(", "(", "0", ",", "0", ")", ",", "1", ",", "2", ")", ")", "_assert_output_equal", "(", "fake_renderer_output", "(", "fig", ",", "FakeRenderer", ")", ",", "\"\"\"\n opening figure\n opening axes\n draw path with 25 vertices\n draw path with 4 vertices\n closing axes\n closing figure\n \"\"\"", ")" ]
[ 130, 0 ]
[ 146, 29 ]
python
en
['en', 'en', 'en']
True
test_new_DID_cannot_update_another_DID
(looper, sdk_pool_handle, sdk_wallet_trustee, sdk_wallet_handle)
Create trustee
Create trustee
def test_new_DID_cannot_update_another_DID(looper, sdk_pool_handle, sdk_wallet_trustee, sdk_wallet_handle): """Create trustee""" trustee_did, trustee_verkey = looper.loop.run_until_complete( did.create_and_store_my_did(sdk_wallet_trustee[0], "{}")) """Add trustee to ledger""" sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee, 'newTrustee', TRUSTEE_STRING, verkey=trustee_verkey, dest=trustee_did) """new DID (no role)""" new_no_role_did, new_no_role_verkey = looper.loop.run_until_complete( did.create_and_store_my_did(sdk_wallet_trustee[0], "{}")) """Adding new DID (no role) to ledger""" sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee, 'noRole', verkey=new_no_role_verkey, dest=new_no_role_did) """Nym transaction to update Trustee DID that makes no change to verkey or role""" op = {'type': '1', 'dest': trustee_did } """Submitting the transaction fails""" with pytest.raises(RequestRejectedException): req = sdk_sign_and_submit_op(looper, sdk_pool_handle, sdk_wallet_trustee, op) sdk_get_and_check_replies(looper, [req])
[ "def", "test_new_DID_cannot_update_another_DID", "(", "looper", ",", "sdk_pool_handle", ",", "sdk_wallet_trustee", ",", "sdk_wallet_handle", ")", ":", "trustee_did", ",", "trustee_verkey", "=", "looper", ".", "loop", ".", "run_until_complete", "(", "did", ".", "create_and_store_my_did", "(", "sdk_wallet_trustee", "[", "0", "]", ",", "\"{}\"", ")", ")", "\"\"\"Add trustee to ledger\"\"\"", "sdk_add_new_nym", "(", "looper", ",", "sdk_pool_handle", ",", "sdk_wallet_trustee", ",", "'newTrustee'", ",", "TRUSTEE_STRING", ",", "verkey", "=", "trustee_verkey", ",", "dest", "=", "trustee_did", ")", "\"\"\"new DID (no role)\"\"\"", "new_no_role_did", ",", "new_no_role_verkey", "=", "looper", ".", "loop", ".", "run_until_complete", "(", "did", ".", "create_and_store_my_did", "(", "sdk_wallet_trustee", "[", "0", "]", ",", "\"{}\"", ")", ")", "\"\"\"Adding new DID (no role) to ledger\"\"\"", "sdk_add_new_nym", "(", "looper", ",", "sdk_pool_handle", ",", "sdk_wallet_trustee", ",", "'noRole'", ",", "verkey", "=", "new_no_role_verkey", ",", "dest", "=", "new_no_role_did", ")", "\"\"\"Nym transaction to update Trustee DID that makes no change to verkey or role\"\"\"", "op", "=", "{", "'type'", ":", "'1'", ",", "'dest'", ":", "trustee_did", "}", "\"\"\"Submitting the transaction fails\"\"\"", "with", "pytest", ".", "raises", "(", "RequestRejectedException", ")", ":", "req", "=", "sdk_sign_and_submit_op", "(", "looper", ",", "sdk_pool_handle", ",", "sdk_wallet_trustee", ",", "op", ")", "sdk_get_and_check_replies", "(", "looper", ",", "[", "req", "]", ")" ]
[ 9, 0 ]
[ 39, 48 ]
python
en
['et', 'ro', 'en']
False
Font.color
(self)
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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
def color(self): """ 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%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 63, 28 ]
python
en
['en', 'error', 'th']
False
Font.family
(self)
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string
def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"]
[ "def", "family", "(", "self", ")", ":", "return", "self", "[", "\"family\"", "]" ]
[ 72, 4 ]
[ 94, 29 ]
python
en
['en', 'error', 'th']
False
Font.size
(self)
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf]
def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"]
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 103, 4 ]
[ 112, 27 ]
python
en
['en', 'error', 'th']
False
Font.__init__
(self, arg=None, color=None, family=None, size=None, **kwargs)
Construct a new Font object Sets this legend's title font. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.legend.title.Font` color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- Font
Construct a new Font object Sets this legend's title font.
def __init__(self, arg=None, color=None, family=None, size=None, **kwargs): """ Construct a new Font object Sets this legend's title font. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.legend.title.Font` color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- Font """ super(Font, self).__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.layout.legend.title.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.legend.title.Font`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("family", None) _v = family if family is not None else _v if _v is not None: self["family"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "family", "=", "None", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Font", ",", "self", ")", ".", "__init__", "(", "\"font\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.layout.legend.title.Font \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.legend.title.Font`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"family\"", ",", "None", ")", "_v", "=", "family", "if", "family", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"family\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"size\"", ",", "None", ")", "_v", "=", "size", "if", "size", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"size\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 143, 4 ]
[ 226, 34 ]
python
en
['en', 'error', 'th']
False
load_json
(*path)
Convenience function to load a JSON file from DEFS_DIR.
Convenience function to load a JSON file from DEFS_DIR.
def load_json(*path): """Convenience function to load a JSON file from DEFS_DIR.""" if len(path) == 1 and path[0].startswith("/"): filename = path[0] else: filename = os.path.join(DEFS_DIR, *path) with open(filename) as f: return json.load(f, object_pairs_hook=OrderedDict)
[ "def", "load_json", "(", "*", "path", ")", ":", "if", "len", "(", "path", ")", "==", "1", "and", "path", "[", "0", "]", ".", "startswith", "(", "\"/\"", ")", ":", "filename", "=", "path", "[", "0", "]", "else", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "DEFS_DIR", ",", "*", "path", ")", "with", "open", "(", "filename", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ",", "object_pairs_hook", "=", "OrderedDict", ")" ]
[ 20, 0 ]
[ 28, 58 ]
python
en
['en', 'en', 'en']
True
_load_btc_coins
()
Load btc-like coins from `bitcoin/*.json`
Load btc-like coins from `bitcoin/*.json`
def _load_btc_coins(): """Load btc-like coins from `bitcoin/*.json`""" coins = [] for filename in glob.glob(os.path.join(DEFS_DIR, "bitcoin", "*.json")): coin = load_json(filename) coin.update( name=coin["coin_label"], shortcut=coin["coin_shortcut"], key="bitcoin:{}".format(coin["coin_shortcut"]), icon=filename.replace(".json", ".png"), ) coins.append(coin) return coins
[ "def", "_load_btc_coins", "(", ")", ":", "coins", "=", "[", "]", "for", "filename", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "DEFS_DIR", ",", "\"bitcoin\"", ",", "\"*.json\"", ")", ")", ":", "coin", "=", "load_json", "(", "filename", ")", "coin", ".", "update", "(", "name", "=", "coin", "[", "\"coin_label\"", "]", ",", "shortcut", "=", "coin", "[", "\"coin_shortcut\"", "]", ",", "key", "=", "\"bitcoin:{}\"", ".", "format", "(", "coin", "[", "\"coin_shortcut\"", "]", ")", ",", "icon", "=", "filename", ".", "replace", "(", "\".json\"", ",", "\".png\"", ")", ",", ")", "coins", ".", "append", "(", "coin", ")", "return", "coins" ]
[ 213, 0 ]
[ 226, 16 ]
python
en
['en', 'en', 'en']
True
_load_ethereum_networks
()
Load ethereum networks from `ethereum/networks.json`
Load ethereum networks from `ethereum/networks.json`
def _load_ethereum_networks(): """Load ethereum networks from `ethereum/networks.json`""" networks = load_json("ethereum", "networks.json") for network in networks: network.update(key="eth:{}".format(network["shortcut"])) return networks
[ "def", "_load_ethereum_networks", "(", ")", ":", "networks", "=", "load_json", "(", "\"ethereum\"", ",", "\"networks.json\"", ")", "for", "network", "in", "networks", ":", "network", ".", "update", "(", "key", "=", "\"eth:{}\"", ".", "format", "(", "network", "[", "\"shortcut\"", "]", ")", ")", "return", "networks" ]
[ 229, 0 ]
[ 234, 19 ]
python
en
['en', 'en', 'en']
True
_load_erc20_tokens
()
Load ERC20 tokens from `ethereum/tokens` submodule.
Load ERC20 tokens from `ethereum/tokens` submodule.
def _load_erc20_tokens(): """Load ERC20 tokens from `ethereum/tokens` submodule.""" networks = _load_ethereum_networks() tokens = [] for network in networks: chain = network["chain"] chain_path = os.path.join(DEFS_DIR, "ethereum", "tokens", "tokens", chain) for filename in sorted(glob.glob(os.path.join(chain_path, "*.json"))): token = load_json(filename) token.update( chain=chain, chain_id=network["chain_id"], address_bytes=bytes.fromhex(token["address"][2:]), shortcut=token["symbol"], key="erc20:{}:{}".format(chain, token["symbol"]), ) tokens.append(token) return tokens
[ "def", "_load_erc20_tokens", "(", ")", ":", "networks", "=", "_load_ethereum_networks", "(", ")", "tokens", "=", "[", "]", "for", "network", "in", "networks", ":", "chain", "=", "network", "[", "\"chain\"", "]", "chain_path", "=", "os", ".", "path", ".", "join", "(", "DEFS_DIR", ",", "\"ethereum\"", ",", "\"tokens\"", ",", "\"tokens\"", ",", "chain", ")", "for", "filename", "in", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "chain_path", ",", "\"*.json\"", ")", ")", ")", ":", "token", "=", "load_json", "(", "filename", ")", "token", ".", "update", "(", "chain", "=", "chain", ",", "chain_id", "=", "network", "[", "\"chain_id\"", "]", ",", "address_bytes", "=", "bytes", ".", "fromhex", "(", "token", "[", "\"address\"", "]", "[", "2", ":", "]", ")", ",", "shortcut", "=", "token", "[", "\"symbol\"", "]", ",", "key", "=", "\"erc20:{}:{}\"", ".", "format", "(", "chain", ",", "token", "[", "\"symbol\"", "]", ")", ",", ")", "tokens", ".", "append", "(", "token", ")", "return", "tokens" ]
[ 237, 0 ]
[ 256, 17 ]
python
en
['en', 'en', 'en']
True
_load_nem_mosaics
()
Loads NEM mosaics from `nem/nem_mosaics.json`
Loads NEM mosaics from `nem/nem_mosaics.json`
def _load_nem_mosaics(): """Loads NEM mosaics from `nem/nem_mosaics.json`""" mosaics = load_json("nem", "nem_mosaics.json") for mosaic in mosaics: shortcut = mosaic["ticker"].strip() mosaic.update(shortcut=shortcut, key="nem:{}".format(shortcut)) return mosaics
[ "def", "_load_nem_mosaics", "(", ")", ":", "mosaics", "=", "load_json", "(", "\"nem\"", ",", "\"nem_mosaics.json\"", ")", "for", "mosaic", "in", "mosaics", ":", "shortcut", "=", "mosaic", "[", "\"ticker\"", "]", ".", "strip", "(", ")", "mosaic", ".", "update", "(", "shortcut", "=", "shortcut", ",", "key", "=", "\"nem:{}\"", ".", "format", "(", "shortcut", ")", ")", "return", "mosaics" ]
[ 259, 0 ]
[ 265, 18 ]
python
en
['en', 'fr', 'en']
True
_load_misc
()
Loads miscellaneous networks from `misc/misc.json`
Loads miscellaneous networks from `misc/misc.json`
def _load_misc(): """Loads miscellaneous networks from `misc/misc.json`""" others = load_json("misc/misc.json") for other in others: other.update(key="misc:{}".format(other["shortcut"])) return others
[ "def", "_load_misc", "(", ")", ":", "others", "=", "load_json", "(", "\"misc/misc.json\"", ")", "for", "other", "in", "others", ":", "other", ".", "update", "(", "key", "=", "\"misc:{}\"", ".", "format", "(", "other", "[", "\"shortcut\"", "]", ")", ")", "return", "others" ]
[ 268, 0 ]
[ 273, 17 ]
python
en
['en', 'en', 'en']
True