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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ErrorX.traceref | (self) |
The 'traceref' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
|
The 'traceref' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807] | def traceref(self):
"""
The 'traceref' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["traceref"] | [
"def",
"traceref",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"traceref\"",
"]"
] | [
234,
4
] | [
244,
31
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.tracerefminus | (self) |
The 'tracerefminus' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
|
The 'tracerefminus' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807] | def tracerefminus(self):
"""
The 'tracerefminus' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["tracerefminus"] | [
"def",
"tracerefminus",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"tracerefminus\"",
"]"
] | [
253,
4
] | [
263,
36
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.type | (self) |
Determines the rule used to generate the error bars. If
*constant`, the bar lengths are of a constant value. Set this
constant in `value`. If "percent", the bar lengths correspond
to a percentage of underlying data. Set this percentage in
`value`. If "sqrt", the bar lengths correspond to the sqaure of
the underlying data. If "data", the bar lengths are set with
data set `array`.
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['percent', 'constant', 'sqrt', 'data']
Returns
-------
Any
|
Determines the rule used to generate the error bars. If
*constant`, the bar lengths are of a constant value. Set this
constant in `value`. If "percent", the bar lengths correspond
to a percentage of underlying data. Set this percentage in
`value`. If "sqrt", the bar lengths correspond to the sqaure of
the underlying data. If "data", the bar lengths are set with
data set `array`.
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['percent', 'constant', 'sqrt', 'data'] | def type(self):
"""
Determines the rule used to generate the error bars. If
*constant`, the bar lengths are of a constant value. Set this
constant in `value`. If "percent", the bar lengths correspond
to a percentage of underlying data. Set this percentage in
`value`. If "sqrt", the bar lengths correspond to the sqaure of
the underlying data. If "data", the bar lengths are set with
data set `array`.
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['percent', 'constant', 'sqrt', 'data']
Returns
-------
Any
"""
return self["type"] | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"type\"",
"]"
] | [
272,
4
] | [
290,
27
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.value | (self) |
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars.
The 'value' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
|
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars.
The 'value' property is a number and may be specified as:
- An int or float in the interval [0, inf] | def value(self):
"""
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars.
The 'value' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["value"] | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"value\"",
"]"
] | [
299,
4
] | [
312,
28
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.valueminus | (self) |
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
The 'valueminus' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
|
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
The 'valueminus' property is a number and may be specified as:
- An int or float in the interval [0, inf] | def valueminus(self):
"""
Sets the value of either the percentage (if `type` is set to
"percent") or the constant (if `type` is set to "constant")
corresponding to the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
The 'valueminus' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["valueminus"] | [
"def",
"valueminus",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"valueminus\"",
"]"
] | [
321,
4
] | [
335,
33
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.visible | (self) |
Determines whether or not this set of error bars is visible.
The 'visible' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether or not this set of error bars is visible.
The 'visible' property must be specified as a bool
(either True, or False) | def visible(self):
"""
Determines whether or not this set of error bars is visible.
The 'visible' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["visible"] | [
"def",
"visible",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"visible\"",
"]"
] | [
344,
4
] | [
355,
30
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.width | (self) |
Sets the width (in px) of the cross-bar at both ends of the
error bars.
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 width (in px) of the cross-bar at both ends of the
error bars.
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 width (in px) of the cross-bar at both ends of the
error bars.
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\"",
"]"
] | [
364,
4
] | [
376,
28
] | python | en | ['en', 'error', 'th'] | False |
ErrorX.__init__ | (
self,
arg=None,
array=None,
arrayminus=None,
arrayminussrc=None,
arraysrc=None,
color=None,
copy_zstyle=None,
symmetric=None,
thickness=None,
traceref=None,
tracerefminus=None,
type=None,
value=None,
valueminus=None,
visible=None,
width=None,
**kwargs
) |
Construct a new ErrorX object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.ErrorX`
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
arrayminus .
arraysrc
Sets the source reference on Chart Studio Cloud for
array .
color
Sets the stoke color of the error bars.
copy_zstyle
symmetric
Determines whether or not the error bars have the same
length in both direction (top/bottom for vertical bars,
left/right for horizontal bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error bars. If
*constant`, the bar lengths are of a constant value.
Set this constant in `value`. If "percent", the bar
lengths correspond to a percentage of underlying data.
Set this percentage in `value`. If "sqrt", the bar
lengths correspond to the sqaure of the underlying
data. If "data", the bar lengths are set with data set
`array`.
value
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars.
valueminus
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars in the bottom (left) direction for vertical
(horizontal) bars
visible
Determines whether or not this set of error bars is
visible.
width
Sets the width (in px) of the cross-bar at both ends of
the error bars.
Returns
-------
ErrorX
|
Construct a new ErrorX object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.ErrorX`
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
arrayminus .
arraysrc
Sets the source reference on Chart Studio Cloud for
array .
color
Sets the stoke color of the error bars.
copy_zstyle | def __init__(
self,
arg=None,
array=None,
arrayminus=None,
arrayminussrc=None,
arraysrc=None,
color=None,
copy_zstyle=None,
symmetric=None,
thickness=None,
traceref=None,
tracerefminus=None,
type=None,
value=None,
valueminus=None,
visible=None,
width=None,
**kwargs
):
"""
Construct a new ErrorX object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.ErrorX`
array
Sets the data corresponding the length of each error
bar. Values are plotted relative to the underlying
data.
arrayminus
Sets the data corresponding the length of each error
bar in the bottom (left) direction for vertical
(horizontal) bars Values are plotted relative to the
underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud for
arrayminus .
arraysrc
Sets the source reference on Chart Studio Cloud for
array .
color
Sets the stoke color of the error bars.
copy_zstyle
symmetric
Determines whether or not the error bars have the same
length in both direction (top/bottom for vertical bars,
left/right for horizontal bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error bars. If
*constant`, the bar lengths are of a constant value.
Set this constant in `value`. If "percent", the bar
lengths correspond to a percentage of underlying data.
Set this percentage in `value`. If "sqrt", the bar
lengths correspond to the sqaure of the underlying
data. If "data", the bar lengths are set with data set
`array`.
value
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars.
valueminus
Sets the value of either the percentage (if `type` is
set to "percent") or the constant (if `type` is set to
"constant") corresponding to the lengths of the error
bars in the bottom (left) direction for vertical
(horizontal) bars
visible
Determines whether or not this set of error bars is
visible.
width
Sets the width (in px) of the cross-bar at both ends of
the error bars.
Returns
-------
ErrorX
"""
super(ErrorX, self).__init__("error_x")
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.scatter3d.ErrorX
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter3d.ErrorX`"""
)
# 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("array", None)
_v = array if array is not None else _v
if _v is not None:
self["array"] = _v
_v = arg.pop("arrayminus", None)
_v = arrayminus if arrayminus is not None else _v
if _v is not None:
self["arrayminus"] = _v
_v = arg.pop("arrayminussrc", None)
_v = arrayminussrc if arrayminussrc is not None else _v
if _v is not None:
self["arrayminussrc"] = _v
_v = arg.pop("arraysrc", None)
_v = arraysrc if arraysrc is not None else _v
if _v is not None:
self["arraysrc"] = _v
_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("copy_zstyle", None)
_v = copy_zstyle if copy_zstyle is not None else _v
if _v is not None:
self["copy_zstyle"] = _v
_v = arg.pop("symmetric", None)
_v = symmetric if symmetric is not None else _v
if _v is not None:
self["symmetric"] = _v
_v = arg.pop("thickness", None)
_v = thickness if thickness is not None else _v
if _v is not None:
self["thickness"] = _v
_v = arg.pop("traceref", None)
_v = traceref if traceref is not None else _v
if _v is not None:
self["traceref"] = _v
_v = arg.pop("tracerefminus", None)
_v = tracerefminus if tracerefminus is not None else _v
if _v is not None:
self["tracerefminus"] = _v
_v = arg.pop("type", None)
_v = type if type is not None else _v
if _v is not None:
self["type"] = _v
_v = arg.pop("value", None)
_v = value if value is not None else _v
if _v is not None:
self["value"] = _v
_v = arg.pop("valueminus", None)
_v = valueminus if valueminus is not None else _v
if _v is not None:
self["valueminus"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _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",
",",
"array",
"=",
"None",
",",
"arrayminus",
"=",
"None",
",",
"arrayminussrc",
"=",
"None",
",",
"arraysrc",
"=",
"None",
",",
"color",
"=",
"None",
",",
"copy_zstyle",
"=",
"None",
",",
"symmetric",
"=",
"None",
",",
"thickness",
"=",
"None",
",",
"traceref",
"=",
"None",
",",
"tracerefminus",
"=",
"None",
",",
"type",
"=",
"None",
",",
"value",
"=",
"None",
",",
"valueminus",
"=",
"None",
",",
"visible",
"=",
"None",
",",
"width",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ErrorX",
",",
"self",
")",
".",
"__init__",
"(",
"\"error_x\"",
")",
"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.scatter3d.ErrorX \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatter3d.ErrorX`\"\"\"",
")",
"# 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",
"(",
"\"array\"",
",",
"None",
")",
"_v",
"=",
"array",
"if",
"array",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"array\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"arrayminus\"",
",",
"None",
")",
"_v",
"=",
"arrayminus",
"if",
"arrayminus",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"arrayminus\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"arrayminussrc\"",
",",
"None",
")",
"_v",
"=",
"arrayminussrc",
"if",
"arrayminussrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"arrayminussrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"arraysrc\"",
",",
"None",
")",
"_v",
"=",
"arraysrc",
"if",
"arraysrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"arraysrc\"",
"]",
"=",
"_v",
"_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",
"(",
"\"copy_zstyle\"",
",",
"None",
")",
"_v",
"=",
"copy_zstyle",
"if",
"copy_zstyle",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"copy_zstyle\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"symmetric\"",
",",
"None",
")",
"_v",
"=",
"symmetric",
"if",
"symmetric",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"symmetric\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"thickness\"",
",",
"None",
")",
"_v",
"=",
"thickness",
"if",
"thickness",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"thickness\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"traceref\"",
",",
"None",
")",
"_v",
"=",
"traceref",
"if",
"traceref",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"traceref\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"tracerefminus\"",
",",
"None",
")",
"_v",
"=",
"tracerefminus",
"if",
"tracerefminus",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"tracerefminus\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"type\"",
",",
"None",
")",
"_v",
"=",
"type",
"if",
"type",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"type\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"value\"",
",",
"None",
")",
"_v",
"=",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"value\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"valueminus\"",
",",
"None",
")",
"_v",
"=",
"valueminus",
"if",
"valueminus",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"valueminus\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"visible\"",
",",
"None",
")",
"_v",
"=",
"visible",
"if",
"visible",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"visible\"",
"]",
"=",
"_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"
] | [
444,
4
] | [
629,
34
] | python | en | ['en', 'error', 'th'] | False |
iou_loss | (pred, target, eps=1e-6) | IoU loss.
Computing the IoU loss between a set of predicted bboxes and target bboxes.
The loss is calculated as negative log of IoU.
Args:
pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2),
shape (n, 4).
target (torch.Tensor): Corresponding gt bboxes, shape (n, 4).
eps (float): Eps to avoid log(0).
Return:
torch.Tensor: Loss tensor.
| IoU loss. | def iou_loss(pred, target, eps=1e-6):
"""IoU loss.
Computing the IoU loss between a set of predicted bboxes and target bboxes.
The loss is calculated as negative log of IoU.
Args:
pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2),
shape (n, 4).
target (torch.Tensor): Corresponding gt bboxes, shape (n, 4).
eps (float): Eps to avoid log(0).
Return:
torch.Tensor: Loss tensor.
"""
ious = bbox_overlaps(pred, target, is_aligned=True).clamp(min=eps)
loss = -ious.log()
return loss | [
"def",
"iou_loss",
"(",
"pred",
",",
"target",
",",
"eps",
"=",
"1e-6",
")",
":",
"ious",
"=",
"bbox_overlaps",
"(",
"pred",
",",
"target",
",",
"is_aligned",
"=",
"True",
")",
".",
"clamp",
"(",
"min",
"=",
"eps",
")",
"loss",
"=",
"-",
"ious",
".",
"log",
"(",
")",
"return",
"loss"
] | [
9,
0
] | [
26,
15
] | python | es | ['es', 'hmn', 'it'] | False |
bounded_iou_loss | (pred, target, beta=0.2, eps=1e-3) | `Improving Object Localization with Fitness NMS and Bounded IoU Loss.
<https://arxiv.org/abs/1711.00164>`_.
Args:
pred (torch.Tensor): Predicted bboxes.
target (torch.Tensor): Target bboxes.
beta (float): beta parameter in smoothl1.
eps (float): eps to avoid NaN.
| `Improving Object Localization with Fitness NMS and Bounded IoU Loss. | def bounded_iou_loss(pred, target, beta=0.2, eps=1e-3):
"""`Improving Object Localization with Fitness NMS and Bounded IoU Loss.
<https://arxiv.org/abs/1711.00164>`_.
Args:
pred (torch.Tensor): Predicted bboxes.
target (torch.Tensor): Target bboxes.
beta (float): beta parameter in smoothl1.
eps (float): eps to avoid NaN.
"""
pred_ctrx = (pred[:, 0] + pred[:, 2]) * 0.5
pred_ctry = (pred[:, 1] + pred[:, 3]) * 0.5
pred_w = pred[:, 2] - pred[:, 0]
pred_h = pred[:, 3] - pred[:, 1]
with torch.no_grad():
target_ctrx = (target[:, 0] + target[:, 2]) * 0.5
target_ctry = (target[:, 1] + target[:, 3]) * 0.5
target_w = target[:, 2] - target[:, 0]
target_h = target[:, 3] - target[:, 1]
dx = target_ctrx - pred_ctrx
dy = target_ctry - pred_ctry
loss_dx = 1 - torch.max(
(target_w - 2 * dx.abs()) /
(target_w + 2 * dx.abs() + eps), torch.zeros_like(dx))
loss_dy = 1 - torch.max(
(target_h - 2 * dy.abs()) /
(target_h + 2 * dy.abs() + eps), torch.zeros_like(dy))
loss_dw = 1 - torch.min(target_w / (pred_w + eps), pred_w /
(target_w + eps))
loss_dh = 1 - torch.min(target_h / (pred_h + eps), pred_h /
(target_h + eps))
loss_comb = torch.stack([loss_dx, loss_dy, loss_dw, loss_dh],
dim=-1).view(loss_dx.size(0), -1)
loss = torch.where(loss_comb < beta, 0.5 * loss_comb * loss_comb / beta,
loss_comb - 0.5 * beta)
return loss | [
"def",
"bounded_iou_loss",
"(",
"pred",
",",
"target",
",",
"beta",
"=",
"0.2",
",",
"eps",
"=",
"1e-3",
")",
":",
"pred_ctrx",
"=",
"(",
"pred",
"[",
":",
",",
"0",
"]",
"+",
"pred",
"[",
":",
",",
"2",
"]",
")",
"*",
"0.5",
"pred_ctry",
"=",
"(",
"pred",
"[",
":",
",",
"1",
"]",
"+",
"pred",
"[",
":",
",",
"3",
"]",
")",
"*",
"0.5",
"pred_w",
"=",
"pred",
"[",
":",
",",
"2",
"]",
"-",
"pred",
"[",
":",
",",
"0",
"]",
"pred_h",
"=",
"pred",
"[",
":",
",",
"3",
"]",
"-",
"pred",
"[",
":",
",",
"1",
"]",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"target_ctrx",
"=",
"(",
"target",
"[",
":",
",",
"0",
"]",
"+",
"target",
"[",
":",
",",
"2",
"]",
")",
"*",
"0.5",
"target_ctry",
"=",
"(",
"target",
"[",
":",
",",
"1",
"]",
"+",
"target",
"[",
":",
",",
"3",
"]",
")",
"*",
"0.5",
"target_w",
"=",
"target",
"[",
":",
",",
"2",
"]",
"-",
"target",
"[",
":",
",",
"0",
"]",
"target_h",
"=",
"target",
"[",
":",
",",
"3",
"]",
"-",
"target",
"[",
":",
",",
"1",
"]",
"dx",
"=",
"target_ctrx",
"-",
"pred_ctrx",
"dy",
"=",
"target_ctry",
"-",
"pred_ctry",
"loss_dx",
"=",
"1",
"-",
"torch",
".",
"max",
"(",
"(",
"target_w",
"-",
"2",
"*",
"dx",
".",
"abs",
"(",
")",
")",
"/",
"(",
"target_w",
"+",
"2",
"*",
"dx",
".",
"abs",
"(",
")",
"+",
"eps",
")",
",",
"torch",
".",
"zeros_like",
"(",
"dx",
")",
")",
"loss_dy",
"=",
"1",
"-",
"torch",
".",
"max",
"(",
"(",
"target_h",
"-",
"2",
"*",
"dy",
".",
"abs",
"(",
")",
")",
"/",
"(",
"target_h",
"+",
"2",
"*",
"dy",
".",
"abs",
"(",
")",
"+",
"eps",
")",
",",
"torch",
".",
"zeros_like",
"(",
"dy",
")",
")",
"loss_dw",
"=",
"1",
"-",
"torch",
".",
"min",
"(",
"target_w",
"/",
"(",
"pred_w",
"+",
"eps",
")",
",",
"pred_w",
"/",
"(",
"target_w",
"+",
"eps",
")",
")",
"loss_dh",
"=",
"1",
"-",
"torch",
".",
"min",
"(",
"target_h",
"/",
"(",
"pred_h",
"+",
"eps",
")",
",",
"pred_h",
"/",
"(",
"target_h",
"+",
"eps",
")",
")",
"loss_comb",
"=",
"torch",
".",
"stack",
"(",
"[",
"loss_dx",
",",
"loss_dy",
",",
"loss_dw",
",",
"loss_dh",
"]",
",",
"dim",
"=",
"-",
"1",
")",
".",
"view",
"(",
"loss_dx",
".",
"size",
"(",
"0",
")",
",",
"-",
"1",
")",
"loss",
"=",
"torch",
".",
"where",
"(",
"loss_comb",
"<",
"beta",
",",
"0.5",
"*",
"loss_comb",
"*",
"loss_comb",
"/",
"beta",
",",
"loss_comb",
"-",
"0.5",
"*",
"beta",
")",
"return",
"loss"
] | [
30,
0
] | [
69,
15
] | python | en | ['en', 'en', 'en'] | True |
giou_loss | (pred, target, eps=1e-7) | r"""`Generalized Intersection over Union: A Metric and A Loss for Bounding
Box Regression <https://arxiv.org/abs/1902.09630>`_.
Args:
pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2),
shape (n, 4).
target (torch.Tensor): Corresponding gt bboxes, shape (n, 4).
eps (float): Eps to avoid log(0).
Return:
Tensor: Loss tensor.
| r"""`Generalized Intersection over Union: A Metric and A Loss for Bounding
Box Regression <https://arxiv.org/abs/1902.09630>`_. | def giou_loss(pred, target, eps=1e-7):
r"""`Generalized Intersection over Union: A Metric and A Loss for Bounding
Box Regression <https://arxiv.org/abs/1902.09630>`_.
Args:
pred (torch.Tensor): Predicted bboxes of format (x1, y1, x2, y2),
shape (n, 4).
target (torch.Tensor): Corresponding gt bboxes, shape (n, 4).
eps (float): Eps to avoid log(0).
Return:
Tensor: Loss tensor.
"""
# overlap
lt = torch.max(pred[:, :2], target[:, :2])
rb = torch.min(pred[:, 2:], target[:, 2:])
wh = (rb - lt).clamp(min=0)
overlap = wh[:, 0] * wh[:, 1]
# union
ap = (pred[:, 2] - pred[:, 0]) * (pred[:, 3] - pred[:, 1])
ag = (target[:, 2] - target[:, 0]) * (target[:, 3] - target[:, 1])
union = ap + ag - overlap + eps
# IoU
ious = overlap / union
# enclose area
enclose_x1y1 = torch.min(pred[:, :2], target[:, :2])
enclose_x2y2 = torch.max(pred[:, 2:], target[:, 2:])
enclose_wh = (enclose_x2y2 - enclose_x1y1).clamp(min=0)
enclose_area = enclose_wh[:, 0] * enclose_wh[:, 1] + eps
# GIoU
gious = ious - (enclose_area - union) / enclose_area
loss = 1 - gious
return loss | [
"def",
"giou_loss",
"(",
"pred",
",",
"target",
",",
"eps",
"=",
"1e-7",
")",
":",
"# overlap",
"lt",
"=",
"torch",
".",
"max",
"(",
"pred",
"[",
":",
",",
":",
"2",
"]",
",",
"target",
"[",
":",
",",
":",
"2",
"]",
")",
"rb",
"=",
"torch",
".",
"min",
"(",
"pred",
"[",
":",
",",
"2",
":",
"]",
",",
"target",
"[",
":",
",",
"2",
":",
"]",
")",
"wh",
"=",
"(",
"rb",
"-",
"lt",
")",
".",
"clamp",
"(",
"min",
"=",
"0",
")",
"overlap",
"=",
"wh",
"[",
":",
",",
"0",
"]",
"*",
"wh",
"[",
":",
",",
"1",
"]",
"# union",
"ap",
"=",
"(",
"pred",
"[",
":",
",",
"2",
"]",
"-",
"pred",
"[",
":",
",",
"0",
"]",
")",
"*",
"(",
"pred",
"[",
":",
",",
"3",
"]",
"-",
"pred",
"[",
":",
",",
"1",
"]",
")",
"ag",
"=",
"(",
"target",
"[",
":",
",",
"2",
"]",
"-",
"target",
"[",
":",
",",
"0",
"]",
")",
"*",
"(",
"target",
"[",
":",
",",
"3",
"]",
"-",
"target",
"[",
":",
",",
"1",
"]",
")",
"union",
"=",
"ap",
"+",
"ag",
"-",
"overlap",
"+",
"eps",
"# IoU",
"ious",
"=",
"overlap",
"/",
"union",
"# enclose area",
"enclose_x1y1",
"=",
"torch",
".",
"min",
"(",
"pred",
"[",
":",
",",
":",
"2",
"]",
",",
"target",
"[",
":",
",",
":",
"2",
"]",
")",
"enclose_x2y2",
"=",
"torch",
".",
"max",
"(",
"pred",
"[",
":",
",",
"2",
":",
"]",
",",
"target",
"[",
":",
",",
"2",
":",
"]",
")",
"enclose_wh",
"=",
"(",
"enclose_x2y2",
"-",
"enclose_x1y1",
")",
".",
"clamp",
"(",
"min",
"=",
"0",
")",
"enclose_area",
"=",
"enclose_wh",
"[",
":",
",",
"0",
"]",
"*",
"enclose_wh",
"[",
":",
",",
"1",
"]",
"+",
"eps",
"# GIoU",
"gious",
"=",
"ious",
"-",
"(",
"enclose_area",
"-",
"union",
")",
"/",
"enclose_area",
"loss",
"=",
"1",
"-",
"gious",
"return",
"loss"
] | [
73,
0
] | [
109,
15
] | python | en | ['en', 'en', 'en'] | True |
roll_init | (character) |
Rolls a number between 1-1000 to determine initiative.
Args:
character (obj): The character to determine initiative for
Returns:
initiative (int): The character's place in initiative - higher
numbers go first.
Notes:
By default, does not reference the character and simply returns
a random integer from 1 to 1000.
Since the character is passed to this function, you can easily reference
a character's stats to determine an initiative roll - for example, if your
character has a 'dexterity' attribute, you can use it to give that character
an advantage in turn order, like so:
return (randint(1,20)) + character.db.dexterity
This way, characters with a higher dexterity will go first more often.
|
Rolls a number between 1-1000 to determine initiative. | def roll_init(character):
"""
Rolls a number between 1-1000 to determine initiative.
Args:
character (obj): The character to determine initiative for
Returns:
initiative (int): The character's place in initiative - higher
numbers go first.
Notes:
By default, does not reference the character and simply returns
a random integer from 1 to 1000.
Since the character is passed to this function, you can easily reference
a character's stats to determine an initiative roll - for example, if your
character has a 'dexterity' attribute, you can use it to give that character
an advantage in turn order, like so:
return (randint(1,20)) + character.db.dexterity
This way, characters with a higher dexterity will go first more often.
"""
return randint(1, 1000) | [
"def",
"roll_init",
"(",
"character",
")",
":",
"return",
"randint",
"(",
"1",
",",
"1000",
")"
] | [
75,
0
] | [
99,
27
] | python | en | ['en', 'error', 'th'] | False |
get_attack | (attacker, defender) |
Returns a value for an attack roll.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Returns:
attack_value (int): Attack roll value, compared against a defense value
to determine whether an attack hits or misses.
Notes:
In this example, a weapon's accuracy bonus is factored into the attack
roll. Lighter weapons are more accurate but less damaging, and heavier
weapons are less accurate but deal more damage. Of course, you can
change this paradigm completely in your own game.
|
Returns a value for an attack roll. | def get_attack(attacker, defender):
"""
Returns a value for an attack roll.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Returns:
attack_value (int): Attack roll value, compared against a defense value
to determine whether an attack hits or misses.
Notes:
In this example, a weapon's accuracy bonus is factored into the attack
roll. Lighter weapons are more accurate but less damaging, and heavier
weapons are less accurate but deal more damage. Of course, you can
change this paradigm completely in your own game.
"""
# Start with a roll from 1 to 100.
attack_value = randint(1, 100)
accuracy_bonus = 0
# If armed, add weapon's accuracy bonus.
if attacker.db.wielded_weapon:
weapon = attacker.db.wielded_weapon
accuracy_bonus += weapon.db.accuracy_bonus
# If unarmed, use character's unarmed accuracy bonus.
else:
accuracy_bonus += attacker.db.unarmed_accuracy
# Add the accuracy bonus to the attack roll.
attack_value += accuracy_bonus
return attack_value | [
"def",
"get_attack",
"(",
"attacker",
",",
"defender",
")",
":",
"# Start with a roll from 1 to 100.",
"attack_value",
"=",
"randint",
"(",
"1",
",",
"100",
")",
"accuracy_bonus",
"=",
"0",
"# If armed, add weapon's accuracy bonus.",
"if",
"attacker",
".",
"db",
".",
"wielded_weapon",
":",
"weapon",
"=",
"attacker",
".",
"db",
".",
"wielded_weapon",
"accuracy_bonus",
"+=",
"weapon",
".",
"db",
".",
"accuracy_bonus",
"# If unarmed, use character's unarmed accuracy bonus.",
"else",
":",
"accuracy_bonus",
"+=",
"attacker",
".",
"db",
".",
"unarmed_accuracy",
"# Add the accuracy bonus to the attack roll.",
"attack_value",
"+=",
"accuracy_bonus",
"return",
"attack_value"
] | [
102,
0
] | [
132,
23
] | python | en | ['en', 'error', 'th'] | False |
get_defense | (attacker, defender) |
Returns a value for defense, which an attack roll must equal or exceed in order
for an attack to hit.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Returns:
defense_value (int): Defense value, compared against an attack roll
to determine whether an attack hits or misses.
Notes:
Characters are given a default defense value of 50 which can be
modified up or down by armor. In this example, wearing armor actually
makes you a little easier to hit, but reduces incoming damage.
|
Returns a value for defense, which an attack roll must equal or exceed in order
for an attack to hit. | def get_defense(attacker, defender):
"""
Returns a value for defense, which an attack roll must equal or exceed in order
for an attack to hit.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Returns:
defense_value (int): Defense value, compared against an attack roll
to determine whether an attack hits or misses.
Notes:
Characters are given a default defense value of 50 which can be
modified up or down by armor. In this example, wearing armor actually
makes you a little easier to hit, but reduces incoming damage.
"""
# Start with a defense value of 50 for a 50/50 chance to hit.
defense_value = 50
# Modify this value based on defender's armor.
if defender.db.worn_armor:
armor = defender.db.worn_armor
defense_value += armor.db.defense_modifier
return defense_value | [
"def",
"get_defense",
"(",
"attacker",
",",
"defender",
")",
":",
"# Start with a defense value of 50 for a 50/50 chance to hit.",
"defense_value",
"=",
"50",
"# Modify this value based on defender's armor.",
"if",
"defender",
".",
"db",
".",
"worn_armor",
":",
"armor",
"=",
"defender",
".",
"db",
".",
"worn_armor",
"defense_value",
"+=",
"armor",
".",
"db",
".",
"defense_modifier",
"return",
"defense_value"
] | [
135,
0
] | [
159,
24
] | python | en | ['en', 'error', 'th'] | False |
get_damage | (attacker, defender) |
Returns a value for damage to be deducted from the defender's HP after abilities
successful hit.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being damaged
Returns:
damage_value (int): Damage value, which is to be deducted from the defending
character's HP.
Notes:
Damage is determined by the attacker's wielded weapon, or the attacker's
unarmed damage range if no weapon is wielded. Incoming damage is reduced
by the defender's armor.
|
Returns a value for damage to be deducted from the defender's HP after abilities
successful hit. | def get_damage(attacker, defender):
"""
Returns a value for damage to be deducted from the defender's HP after abilities
successful hit.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being damaged
Returns:
damage_value (int): Damage value, which is to be deducted from the defending
character's HP.
Notes:
Damage is determined by the attacker's wielded weapon, or the attacker's
unarmed damage range if no weapon is wielded. Incoming damage is reduced
by the defender's armor.
"""
damage_value = 0
# Generate a damage value from wielded weapon if armed
if attacker.db.wielded_weapon:
weapon = attacker.db.wielded_weapon
# Roll between minimum and maximum damage
damage_value = randint(weapon.db.damage_range[0], weapon.db.damage_range[1])
# Use attacker's unarmed damage otherwise
else:
damage_value = randint(attacker.db.unarmed_damage_range[0], attacker.db.unarmed_damage_range[1])
# If defender is armored, reduce incoming damage
if defender.db.worn_armor:
armor = defender.db.worn_armor
damage_value -= armor.db.damage_reduction
# Make sure minimum damage is 0
if damage_value < 0:
damage_value = 0
return damage_value | [
"def",
"get_damage",
"(",
"attacker",
",",
"defender",
")",
":",
"damage_value",
"=",
"0",
"# Generate a damage value from wielded weapon if armed",
"if",
"attacker",
".",
"db",
".",
"wielded_weapon",
":",
"weapon",
"=",
"attacker",
".",
"db",
".",
"wielded_weapon",
"# Roll between minimum and maximum damage",
"damage_value",
"=",
"randint",
"(",
"weapon",
".",
"db",
".",
"damage_range",
"[",
"0",
"]",
",",
"weapon",
".",
"db",
".",
"damage_range",
"[",
"1",
"]",
")",
"# Use attacker's unarmed damage otherwise",
"else",
":",
"damage_value",
"=",
"randint",
"(",
"attacker",
".",
"db",
".",
"unarmed_damage_range",
"[",
"0",
"]",
",",
"attacker",
".",
"db",
".",
"unarmed_damage_range",
"[",
"1",
"]",
")",
"# If defender is armored, reduce incoming damage",
"if",
"defender",
".",
"db",
".",
"worn_armor",
":",
"armor",
"=",
"defender",
".",
"db",
".",
"worn_armor",
"damage_value",
"-=",
"armor",
".",
"db",
".",
"damage_reduction",
"# Make sure minimum damage is 0",
"if",
"damage_value",
"<",
"0",
":",
"damage_value",
"=",
"0",
"return",
"damage_value"
] | [
162,
0
] | [
196,
23
] | python | en | ['en', 'error', 'th'] | False |
apply_damage | (defender, damage) |
Applies damage to a target, reducing their HP by the damage amount to a
minimum of 0.
Args:
defender (obj): Character taking damage
damage (int): Amount of damage being taken
|
Applies damage to a target, reducing their HP by the damage amount to a
minimum of 0. | def apply_damage(defender, damage):
"""
Applies damage to a target, reducing their HP by the damage amount to a
minimum of 0.
Args:
defender (obj): Character taking damage
damage (int): Amount of damage being taken
"""
defender.db.hp -= damage # Reduce defender's HP by the damage dealt.
# If this reduces it to 0 or less, set HP to 0.
if defender.db.hp <= 0:
defender.db.hp = 0 | [
"def",
"apply_damage",
"(",
"defender",
",",
"damage",
")",
":",
"defender",
".",
"db",
".",
"hp",
"-=",
"damage",
"# Reduce defender's HP by the damage dealt.",
"# If this reduces it to 0 or less, set HP to 0.",
"if",
"defender",
".",
"db",
".",
"hp",
"<=",
"0",
":",
"defender",
".",
"db",
".",
"hp",
"=",
"0"
] | [
199,
0
] | [
211,
26
] | python | en | ['en', 'error', 'th'] | False |
at_defeat | (defeated) |
Announces the defeat of a fighter in combat.
Args:
defeated (obj): Fighter that's been defeated.
Notes:
All this does is announce a defeat message by default, but if you
want anything else to happen to defeated fighters (like putting them
into a dying state or something similar) then this is the place to
do it.
|
Announces the defeat of a fighter in combat.
Args:
defeated (obj): Fighter that's been defeated.
Notes:
All this does is announce a defeat message by default, but if you
want anything else to happen to defeated fighters (like putting them
into a dying state or something similar) then this is the place to
do it.
| def at_defeat(defeated):
"""
Announces the defeat of a fighter in combat.
Args:
defeated (obj): Fighter that's been defeated.
Notes:
All this does is announce a defeat message by default, but if you
want anything else to happen to defeated fighters (like putting them
into a dying state or something similar) then this is the place to
do it.
"""
defeated.location.msg_contents("%s has been defeated!" % defeated) | [
"def",
"at_defeat",
"(",
"defeated",
")",
":",
"defeated",
".",
"location",
".",
"msg_contents",
"(",
"\"%s has been defeated!\"",
"%",
"defeated",
")"
] | [
213,
0
] | [
226,
70
] | python | en | ['en', 'error', 'th'] | False |
resolve_attack | (attacker, defender, attack_value=None, defense_value=None) |
Resolves an attack and outputs the result.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Notes:
Even though the attack and defense values are calculated
extremely simply, they are separated out into their own functions
so that they are easier to expand upon.
|
Resolves an attack and outputs the result. | def resolve_attack(attacker, defender, attack_value=None, defense_value=None):
"""
Resolves an attack and outputs the result.
Args:
attacker (obj): Character doing the attacking
defender (obj): Character being attacked
Notes:
Even though the attack and defense values are calculated
extremely simply, they are separated out into their own functions
so that they are easier to expand upon.
"""
# Get the attacker's weapon type to reference in combat messages.
attackers_weapon = "attack"
if attacker.db.wielded_weapon:
weapon = attacker.db.wielded_weapon
attackers_weapon = weapon.db.weapon_type_name
# Get an attack roll from the attacker.
if not attack_value:
attack_value = get_attack(attacker, defender)
# Get a defense value from the defender.
if not defense_value:
defense_value = get_defense(attacker, defender)
# If the attack value is lower than the defense value, miss. Otherwise, hit.
if attack_value < defense_value:
attacker.location.msg_contents("%s's %s misses %s!" % (attacker, attackers_weapon, defender))
else:
damage_value = get_damage(attacker, defender) # Calculate damage value.
# Announce damage dealt and apply damage.
if damage_value > 0:
attacker.location.msg_contents("%s's %s strikes %s for %i damage!" % (attacker, attackers_weapon, defender, damage_value))
else:
attacker.location.msg_contents("%s's %s bounces harmlessly off %s!" % (attacker, attackers_weapon, defender))
apply_damage(defender, damage_value)
# If defender HP is reduced to 0 or less, call at_defeat.
if defender.db.hp <= 0:
at_defeat(defender) | [
"def",
"resolve_attack",
"(",
"attacker",
",",
"defender",
",",
"attack_value",
"=",
"None",
",",
"defense_value",
"=",
"None",
")",
":",
"# Get the attacker's weapon type to reference in combat messages.",
"attackers_weapon",
"=",
"\"attack\"",
"if",
"attacker",
".",
"db",
".",
"wielded_weapon",
":",
"weapon",
"=",
"attacker",
".",
"db",
".",
"wielded_weapon",
"attackers_weapon",
"=",
"weapon",
".",
"db",
".",
"weapon_type_name",
"# Get an attack roll from the attacker.",
"if",
"not",
"attack_value",
":",
"attack_value",
"=",
"get_attack",
"(",
"attacker",
",",
"defender",
")",
"# Get a defense value from the defender.",
"if",
"not",
"defense_value",
":",
"defense_value",
"=",
"get_defense",
"(",
"attacker",
",",
"defender",
")",
"# If the attack value is lower than the defense value, miss. Otherwise, hit.",
"if",
"attack_value",
"<",
"defense_value",
":",
"attacker",
".",
"location",
".",
"msg_contents",
"(",
"\"%s's %s misses %s!\"",
"%",
"(",
"attacker",
",",
"attackers_weapon",
",",
"defender",
")",
")",
"else",
":",
"damage_value",
"=",
"get_damage",
"(",
"attacker",
",",
"defender",
")",
"# Calculate damage value.",
"# Announce damage dealt and apply damage.",
"if",
"damage_value",
">",
"0",
":",
"attacker",
".",
"location",
".",
"msg_contents",
"(",
"\"%s's %s strikes %s for %i damage!\"",
"%",
"(",
"attacker",
",",
"attackers_weapon",
",",
"defender",
",",
"damage_value",
")",
")",
"else",
":",
"attacker",
".",
"location",
".",
"msg_contents",
"(",
"\"%s's %s bounces harmlessly off %s!\"",
"%",
"(",
"attacker",
",",
"attackers_weapon",
",",
"defender",
")",
")",
"apply_damage",
"(",
"defender",
",",
"damage_value",
")",
"# If defender HP is reduced to 0 or less, call at_defeat.",
"if",
"defender",
".",
"db",
".",
"hp",
"<=",
"0",
":",
"at_defeat",
"(",
"defender",
")"
] | [
228,
0
] | [
265,
31
] | python | en | ['en', 'error', 'th'] | False |
combat_cleanup | (character) |
Cleans up all the temporary combat-related attributes on a character.
Args:
character (obj): Character to have their combat attributes removed
Notes:
Any attribute whose key begins with 'combat_' is temporary and no
longer needed once a fight ends.
|
Cleans up all the temporary combat-related attributes on a character. | def combat_cleanup(character):
"""
Cleans up all the temporary combat-related attributes on a character.
Args:
character (obj): Character to have their combat attributes removed
Notes:
Any attribute whose key begins with 'combat_' is temporary and no
longer needed once a fight ends.
"""
for attr in character.attributes.all():
if attr.key[:7] == "combat_": # If the attribute name starts with 'combat_'...
character.attributes.remove(key=attr.key) | [
"def",
"combat_cleanup",
"(",
"character",
")",
":",
"for",
"attr",
"in",
"character",
".",
"attributes",
".",
"all",
"(",
")",
":",
"if",
"attr",
".",
"key",
"[",
":",
"7",
"]",
"==",
"\"combat_\"",
":",
"# If the attribute name starts with 'combat_'...",
"character",
".",
"attributes",
".",
"remove",
"(",
"key",
"=",
"attr",
".",
"key",
")"
] | [
268,
0
] | [
281,
53
] | python | en | ['en', 'error', 'th'] | False |
is_in_combat | (character) |
Returns true if the given character is in combat.
Args:
character (obj): Character to determine if is in combat or not
Returns:
(bool): True if in combat or False if not in combat
|
Returns true if the given character is in combat. | def is_in_combat(character):
"""
Returns true if the given character is in combat.
Args:
character (obj): Character to determine if is in combat or not
Returns:
(bool): True if in combat or False if not in combat
"""
return bool(character.db.combat_turnhandler) | [
"def",
"is_in_combat",
"(",
"character",
")",
":",
"return",
"bool",
"(",
"character",
".",
"db",
".",
"combat_turnhandler",
")"
] | [
284,
0
] | [
294,
48
] | python | en | ['en', 'error', 'th'] | False |
is_turn | (character) |
Returns true if it's currently the given character's turn in combat.
Args:
character (obj): Character to determine if it is their turn or not
Returns:
(bool): True if it is their turn or False otherwise
|
Returns true if it's currently the given character's turn in combat. | def is_turn(character):
"""
Returns true if it's currently the given character's turn in combat.
Args:
character (obj): Character to determine if it is their turn or not
Returns:
(bool): True if it is their turn or False otherwise
"""
turnhandler = character.db.combat_turnhandler
currentchar = turnhandler.db.fighters[turnhandler.db.turn]
return bool(character == currentchar) | [
"def",
"is_turn",
"(",
"character",
")",
":",
"turnhandler",
"=",
"character",
".",
"db",
".",
"combat_turnhandler",
"currentchar",
"=",
"turnhandler",
".",
"db",
".",
"fighters",
"[",
"turnhandler",
".",
"db",
".",
"turn",
"]",
"return",
"bool",
"(",
"character",
"==",
"currentchar",
")"
] | [
297,
0
] | [
309,
41
] | python | en | ['en', 'error', 'th'] | False |
spend_action | (character, actions, action_name=None) |
Spends a character's available combat actions and checks for end of turn.
Args:
character (obj): Character spending the action
actions (int) or 'all': Number of actions to spend, or 'all' to spend all actions
Kwargs:
action_name (str or None): If a string is given, sets character's last action in
combat to provided string
|
Spends a character's available combat actions and checks for end of turn. | def spend_action(character, actions, action_name=None):
"""
Spends a character's available combat actions and checks for end of turn.
Args:
character (obj): Character spending the action
actions (int) or 'all': Number of actions to spend, or 'all' to spend all actions
Kwargs:
action_name (str or None): If a string is given, sets character's last action in
combat to provided string
"""
if action_name:
character.db.combat_lastaction = action_name
if actions == 'all': # If spending all actions
character.db.combat_actionsleft = 0 # Set actions to 0
else:
character.db.combat_actionsleft -= actions # Use up actions.
if character.db.combat_actionsleft < 0:
character.db.combat_actionsleft = 0 # Can't have fewer than 0 actions
character.db.combat_turnhandler.turn_end_check(character) | [
"def",
"spend_action",
"(",
"character",
",",
"actions",
",",
"action_name",
"=",
"None",
")",
":",
"if",
"action_name",
":",
"character",
".",
"db",
".",
"combat_lastaction",
"=",
"action_name",
"if",
"actions",
"==",
"'all'",
":",
"# If spending all actions",
"character",
".",
"db",
".",
"combat_actionsleft",
"=",
"0",
"# Set actions to 0",
"else",
":",
"character",
".",
"db",
".",
"combat_actionsleft",
"-=",
"actions",
"# Use up actions.",
"if",
"character",
".",
"db",
".",
"combat_actionsleft",
"<",
"0",
":",
"character",
".",
"db",
".",
"combat_actionsleft",
"=",
"0",
"# Can't have fewer than 0 actions",
"character",
".",
"db",
".",
"combat_turnhandler",
".",
"turn_end_check",
"(",
"character",
")"
] | [
312,
0
] | [
332,
61
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.at_script_creation | (self) |
Called once, when the script is created.
|
Called once, when the script is created.
| def at_script_creation(self):
"""
Called once, when the script is created.
"""
self.key = "Combat Turn Handler"
self.interval = 5 # Once every 5 seconds
self.persistent = True
self.db.fighters = []
# Add all fighters in the room with at least 1 HP to the combat."
for thing in self.obj.contents:
if thing.db.hp:
self.db.fighters.append(thing)
# Initialize each fighter for combat
for fighter in self.db.fighters:
self.initialize_for_combat(fighter)
# Add a reference to this script to the room
self.obj.db.combat_turnhandler = self
# Roll initiative and sort the list of fighters depending on who rolls highest to determine turn order.
# The initiative roll is determined by the roll_init function and can be customized easily.
ordered_by_roll = sorted(self.db.fighters, key=roll_init, reverse=True)
self.db.fighters = ordered_by_roll
# Announce the turn order.
self.obj.msg_contents("Turn order is: %s " % ", ".join(obj.key for obj in self.db.fighters))
# Start first fighter's turn.
self.start_turn(self.db.fighters[0])
# Set up the current turn and turn timeout delay.
self.db.turn = 0
self.db.timer = TURN_TIMEOUT | [
"def",
"at_script_creation",
"(",
"self",
")",
":",
"self",
".",
"key",
"=",
"\"Combat Turn Handler\"",
"self",
".",
"interval",
"=",
"5",
"# Once every 5 seconds",
"self",
".",
"persistent",
"=",
"True",
"self",
".",
"db",
".",
"fighters",
"=",
"[",
"]",
"# Add all fighters in the room with at least 1 HP to the combat.\"",
"for",
"thing",
"in",
"self",
".",
"obj",
".",
"contents",
":",
"if",
"thing",
".",
"db",
".",
"hp",
":",
"self",
".",
"db",
".",
"fighters",
".",
"append",
"(",
"thing",
")",
"# Initialize each fighter for combat",
"for",
"fighter",
"in",
"self",
".",
"db",
".",
"fighters",
":",
"self",
".",
"initialize_for_combat",
"(",
"fighter",
")",
"# Add a reference to this script to the room",
"self",
".",
"obj",
".",
"db",
".",
"combat_turnhandler",
"=",
"self",
"# Roll initiative and sort the list of fighters depending on who rolls highest to determine turn order.",
"# The initiative roll is determined by the roll_init function and can be customized easily.",
"ordered_by_roll",
"=",
"sorted",
"(",
"self",
".",
"db",
".",
"fighters",
",",
"key",
"=",
"roll_init",
",",
"reverse",
"=",
"True",
")",
"self",
".",
"db",
".",
"fighters",
"=",
"ordered_by_roll",
"# Announce the turn order.",
"self",
".",
"obj",
".",
"msg_contents",
"(",
"\"Turn order is: %s \"",
"%",
"\", \"",
".",
"join",
"(",
"obj",
".",
"key",
"for",
"obj",
"in",
"self",
".",
"db",
".",
"fighters",
")",
")",
"# Start first fighter's turn.",
"self",
".",
"start_turn",
"(",
"self",
".",
"db",
".",
"fighters",
"[",
"0",
"]",
")",
"# Set up the current turn and turn timeout delay.",
"self",
".",
"db",
".",
"turn",
"=",
"0",
"self",
".",
"db",
".",
"timer",
"=",
"TURN_TIMEOUT"
] | [
353,
4
] | [
387,
36
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.at_stop | (self) |
Called at script termination.
|
Called at script termination.
| def at_stop(self):
"""
Called at script termination.
"""
for fighter in self.db.fighters:
combat_cleanup(fighter) # Clean up the combat attributes for every fighter.
self.obj.db.combat_turnhandler = None | [
"def",
"at_stop",
"(",
"self",
")",
":",
"for",
"fighter",
"in",
"self",
".",
"db",
".",
"fighters",
":",
"combat_cleanup",
"(",
"fighter",
")",
"# Clean up the combat attributes for every fighter.",
"self",
".",
"obj",
".",
"db",
".",
"combat_turnhandler",
"=",
"None"
] | [
389,
4
] | [
395,
45
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.at_repeat | (self) |
Called once every self.interval seconds.
|
Called once every self.interval seconds.
| def at_repeat(self):
"""
Called once every self.interval seconds.
"""
currentchar = self.db.fighters[self.db.turn] # Note the current character in the turn order.
self.db.timer -= self.interval # Count down the timer.
if self.db.timer <= 0:
# Force current character to disengage if timer runs out.
self.obj.msg_contents("%s's turn timed out!" % currentchar)
spend_action(currentchar, 'all', action_name="disengage") # Spend all remaining actions.
return
elif self.db.timer <= 10 and not self.db.timeout_warning_given: # 10 seconds left
# Warn the current character if they're about to time out.
currentchar.msg("WARNING: About to time out!")
self.db.timeout_warning_given = True | [
"def",
"at_repeat",
"(",
"self",
")",
":",
"currentchar",
"=",
"self",
".",
"db",
".",
"fighters",
"[",
"self",
".",
"db",
".",
"turn",
"]",
"# Note the current character in the turn order.",
"self",
".",
"db",
".",
"timer",
"-=",
"self",
".",
"interval",
"# Count down the timer.",
"if",
"self",
".",
"db",
".",
"timer",
"<=",
"0",
":",
"# Force current character to disengage if timer runs out.",
"self",
".",
"obj",
".",
"msg_contents",
"(",
"\"%s's turn timed out!\"",
"%",
"currentchar",
")",
"spend_action",
"(",
"currentchar",
",",
"'all'",
",",
"action_name",
"=",
"\"disengage\"",
")",
"# Spend all remaining actions.",
"return",
"elif",
"self",
".",
"db",
".",
"timer",
"<=",
"10",
"and",
"not",
"self",
".",
"db",
".",
"timeout_warning_given",
":",
"# 10 seconds left",
"# Warn the current character if they're about to time out.",
"currentchar",
".",
"msg",
"(",
"\"WARNING: About to time out!\"",
")",
"self",
".",
"db",
".",
"timeout_warning_given",
"=",
"True"
] | [
397,
4
] | [
412,
48
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.initialize_for_combat | (self, character) |
Prepares a character for combat when starting or entering a fight.
Args:
character (obj): Character to initialize for combat.
|
Prepares a character for combat when starting or entering a fight. | def initialize_for_combat(self, character):
"""
Prepares a character for combat when starting or entering a fight.
Args:
character (obj): Character to initialize for combat.
"""
combat_cleanup(character) # Clean up leftover combat attributes beforehand, just in case.
character.db.combat_actionsleft = 0 # Actions remaining - start of turn adds to this, turn ends when it reaches 0
character.db.combat_turnhandler = self # Add a reference to this turn handler script to the character
character.db.combat_lastaction = "null" | [
"def",
"initialize_for_combat",
"(",
"self",
",",
"character",
")",
":",
"combat_cleanup",
"(",
"character",
")",
"# Clean up leftover combat attributes beforehand, just in case.",
"character",
".",
"db",
".",
"combat_actionsleft",
"=",
"0",
"# Actions remaining - start of turn adds to this, turn ends when it reaches 0",
"character",
".",
"db",
".",
"combat_turnhandler",
"=",
"self",
"# Add a reference to this turn handler script to the character",
"character",
".",
"db",
".",
"combat_lastaction",
"=",
"\"null\""
] | [
414,
4
] | [
424,
47
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.start_turn | (self, character) |
Readies a character for the start of their turn by replenishing their
available actions and notifying them that their turn has come up.
Args:
character (obj): Character to be readied.
Notes:
Here, you only get one action per turn, but you might want to allow more than
one per turn, or even grant a number of actions based on a character's
attributes. You can even add multiple different kinds of actions, I.E. actions
separated for movement, by adding "character.db.combat_movesleft = 3" or
something similar.
|
Readies a character for the start of their turn by replenishing their
available actions and notifying them that their turn has come up. | def start_turn(self, character):
"""
Readies a character for the start of their turn by replenishing their
available actions and notifying them that their turn has come up.
Args:
character (obj): Character to be readied.
Notes:
Here, you only get one action per turn, but you might want to allow more than
one per turn, or even grant a number of actions based on a character's
attributes. You can even add multiple different kinds of actions, I.E. actions
separated for movement, by adding "character.db.combat_movesleft = 3" or
something similar.
"""
character.db.combat_actionsleft = ACTIONS_PER_TURN # Replenish actions
# Prompt the character for their turn and give some information.
character.msg("|wIt's your turn! You have %i HP remaining.|n" % character.db.hp) | [
"def",
"start_turn",
"(",
"self",
",",
"character",
")",
":",
"character",
".",
"db",
".",
"combat_actionsleft",
"=",
"ACTIONS_PER_TURN",
"# Replenish actions",
"# Prompt the character for their turn and give some information.",
"character",
".",
"msg",
"(",
"\"|wIt's your turn! You have %i HP remaining.|n\"",
"%",
"character",
".",
"db",
".",
"hp",
")"
] | [
426,
4
] | [
443,
88
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.next_turn | (self) |
Advances to the next character in the turn order.
|
Advances to the next character in the turn order.
| def next_turn(self):
"""
Advances to the next character in the turn order.
"""
# Check to see if every character disengaged as their last action. If so, end combat.
disengage_check = True
for fighter in self.db.fighters:
if fighter.db.combat_lastaction != "disengage": # If a character has done anything but disengage
disengage_check = False
if disengage_check: # All characters have disengaged
self.obj.msg_contents("All fighters have disengaged! Combat is over!")
self.stop() # Stop this script and end combat.
return
# Check to see if only one character is left standing. If so, end combat.
defeated_characters = 0
for fighter in self.db.fighters:
if fighter.db.HP == 0:
defeated_characters += 1 # Add 1 for every fighter with 0 HP left (defeated)
if defeated_characters == (len(self.db.fighters) - 1): # If only one character isn't defeated
for fighter in self.db.fighters:
if fighter.db.HP != 0:
LastStanding = fighter # Pick the one fighter left with HP remaining
self.obj.msg_contents("Only %s remains! Combat is over!" % LastStanding)
self.stop() # Stop this script and end combat.
return
# Cycle to the next turn.
currentchar = self.db.fighters[self.db.turn]
self.db.turn += 1 # Go to the next in the turn order.
if self.db.turn > len(self.db.fighters) - 1:
self.db.turn = 0 # Go back to the first in the turn order once you reach the end.
newchar = self.db.fighters[self.db.turn] # Note the new character
self.db.timer = TURN_TIMEOUT + self.time_until_next_repeat() # Reset the timer.
self.db.timeout_warning_given = False # Reset the timeout warning.
self.obj.msg_contents("%s's turn ends - %s's turn begins!" % (currentchar, newchar))
self.start_turn(newchar) | [
"def",
"next_turn",
"(",
"self",
")",
":",
"# Check to see if every character disengaged as their last action. If so, end combat.",
"disengage_check",
"=",
"True",
"for",
"fighter",
"in",
"self",
".",
"db",
".",
"fighters",
":",
"if",
"fighter",
".",
"db",
".",
"combat_lastaction",
"!=",
"\"disengage\"",
":",
"# If a character has done anything but disengage",
"disengage_check",
"=",
"False",
"if",
"disengage_check",
":",
"# All characters have disengaged",
"self",
".",
"obj",
".",
"msg_contents",
"(",
"\"All fighters have disengaged! Combat is over!\"",
")",
"self",
".",
"stop",
"(",
")",
"# Stop this script and end combat.",
"return",
"# Check to see if only one character is left standing. If so, end combat.",
"defeated_characters",
"=",
"0",
"for",
"fighter",
"in",
"self",
".",
"db",
".",
"fighters",
":",
"if",
"fighter",
".",
"db",
".",
"HP",
"==",
"0",
":",
"defeated_characters",
"+=",
"1",
"# Add 1 for every fighter with 0 HP left (defeated)",
"if",
"defeated_characters",
"==",
"(",
"len",
"(",
"self",
".",
"db",
".",
"fighters",
")",
"-",
"1",
")",
":",
"# If only one character isn't defeated",
"for",
"fighter",
"in",
"self",
".",
"db",
".",
"fighters",
":",
"if",
"fighter",
".",
"db",
".",
"HP",
"!=",
"0",
":",
"LastStanding",
"=",
"fighter",
"# Pick the one fighter left with HP remaining",
"self",
".",
"obj",
".",
"msg_contents",
"(",
"\"Only %s remains! Combat is over!\"",
"%",
"LastStanding",
")",
"self",
".",
"stop",
"(",
")",
"# Stop this script and end combat.",
"return",
"# Cycle to the next turn.",
"currentchar",
"=",
"self",
".",
"db",
".",
"fighters",
"[",
"self",
".",
"db",
".",
"turn",
"]",
"self",
".",
"db",
".",
"turn",
"+=",
"1",
"# Go to the next in the turn order.",
"if",
"self",
".",
"db",
".",
"turn",
">",
"len",
"(",
"self",
".",
"db",
".",
"fighters",
")",
"-",
"1",
":",
"self",
".",
"db",
".",
"turn",
"=",
"0",
"# Go back to the first in the turn order once you reach the end.",
"newchar",
"=",
"self",
".",
"db",
".",
"fighters",
"[",
"self",
".",
"db",
".",
"turn",
"]",
"# Note the new character",
"self",
".",
"db",
".",
"timer",
"=",
"TURN_TIMEOUT",
"+",
"self",
".",
"time_until_next_repeat",
"(",
")",
"# Reset the timer.",
"self",
".",
"db",
".",
"timeout_warning_given",
"=",
"False",
"# Reset the timeout warning.",
"self",
".",
"obj",
".",
"msg_contents",
"(",
"\"%s's turn ends - %s's turn begins!\"",
"%",
"(",
"currentchar",
",",
"newchar",
")",
")",
"self",
".",
"start_turn",
"(",
"newchar",
")"
] | [
445,
4
] | [
482,
32
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.turn_end_check | (self, character) |
Tests to see if a character's turn is over, and cycles to the next turn if it is.
Args:
character (obj): Character to test for end of turn
|
Tests to see if a character's turn is over, and cycles to the next turn if it is. | def turn_end_check(self, character):
"""
Tests to see if a character's turn is over, and cycles to the next turn if it is.
Args:
character (obj): Character to test for end of turn
"""
if not character.db.combat_actionsleft: # Character has no actions remaining
self.next_turn()
return | [
"def",
"turn_end_check",
"(",
"self",
",",
"character",
")",
":",
"if",
"not",
"character",
".",
"db",
".",
"combat_actionsleft",
":",
"# Character has no actions remaining",
"self",
".",
"next_turn",
"(",
")",
"return"
] | [
484,
4
] | [
493,
18
] | python | en | ['en', 'error', 'th'] | False |
TBEquipTurnHandler.join_fight | (self, character) |
Adds a new character to a fight already in progress.
Args:
character (obj): Character to be added to the fight.
|
Adds a new character to a fight already in progress. | def join_fight(self, character):
"""
Adds a new character to a fight already in progress.
Args:
character (obj): Character to be added to the fight.
"""
# Inserts the fighter to the turn order, right behind whoever's turn it currently is.
self.db.fighters.insert(self.db.turn, character)
# Tick the turn counter forward one to compensate.
self.db.turn += 1
# Initialize the character like you do at the start.
self.initialize_for_combat(character) | [
"def",
"join_fight",
"(",
"self",
",",
"character",
")",
":",
"# Inserts the fighter to the turn order, right behind whoever's turn it currently is.",
"self",
".",
"db",
".",
"fighters",
".",
"insert",
"(",
"self",
".",
"db",
".",
"turn",
",",
"character",
")",
"# Tick the turn counter forward one to compensate.",
"self",
".",
"db",
".",
"turn",
"+=",
"1",
"# Initialize the character like you do at the start.",
"self",
".",
"initialize_for_combat",
"(",
"character",
")"
] | [
495,
4
] | [
507,
45
] | python | en | ['en', 'error', 'th'] | False |
TBEWeapon.at_object_creation | (self) |
Called once, when this object is first created. This is the
normal hook to overload for most object types.
|
Called once, when this object is first created. This is the
normal hook to overload for most object types.
| def at_object_creation(self):
"""
Called once, when this object is first created. This is the
normal hook to overload for most object types.
"""
self.db.damage_range = (15, 25) # Minimum and maximum damage on hit
self.db.accuracy_bonus = 0 # Bonus to attack rolls (or penalty if negative)
self.db.weapon_type_name = "weapon" # Single word for weapon - I.E. "dagger", "staff", "scimitar" | [
"def",
"at_object_creation",
"(",
"self",
")",
":",
"self",
".",
"db",
".",
"damage_range",
"=",
"(",
"15",
",",
"25",
")",
"# Minimum and maximum damage on hit",
"self",
".",
"db",
".",
"accuracy_bonus",
"=",
"0",
"# Bonus to attack rolls (or penalty if negative)",
"self",
".",
"db",
".",
"weapon_type_name",
"=",
"\"weapon\"",
"# Single word for weapon - I.E. \"dagger\", \"staff\", \"scimitar\""
] | [
519,
4
] | [
526,
105
] | python | en | ['en', 'error', 'th'] | False |
TBEWeapon.at_drop | (self, dropper) |
Stop being wielded if dropped.
|
Stop being wielded if dropped.
| def at_drop(self, dropper):
"""
Stop being wielded if dropped.
"""
if dropper.db.wielded_weapon == self:
dropper.db.wielded_weapon = None
dropper.location.msg_contents("%s stops wielding %s." % (dropper, self)) | [
"def",
"at_drop",
"(",
"self",
",",
"dropper",
")",
":",
"if",
"dropper",
".",
"db",
".",
"wielded_weapon",
"==",
"self",
":",
"dropper",
".",
"db",
".",
"wielded_weapon",
"=",
"None",
"dropper",
".",
"location",
".",
"msg_contents",
"(",
"\"%s stops wielding %s.\"",
"%",
"(",
"dropper",
",",
"self",
")",
")"
] | [
527,
4
] | [
533,
84
] | python | en | ['en', 'error', 'th'] | False |
TBEWeapon.at_give | (self, giver, getter) |
Stop being wielded if given.
|
Stop being wielded if given.
| def at_give(self, giver, getter):
"""
Stop being wielded if given.
"""
if giver.db.wielded_weapon == self:
giver.db.wielded_weapon = None
giver.location.msg_contents("%s stops wielding %s." % (giver, self)) | [
"def",
"at_give",
"(",
"self",
",",
"giver",
",",
"getter",
")",
":",
"if",
"giver",
".",
"db",
".",
"wielded_weapon",
"==",
"self",
":",
"giver",
".",
"db",
".",
"wielded_weapon",
"=",
"None",
"giver",
".",
"location",
".",
"msg_contents",
"(",
"\"%s stops wielding %s.\"",
"%",
"(",
"giver",
",",
"self",
")",
")"
] | [
534,
4
] | [
540,
80
] | python | en | ['en', 'error', 'th'] | False |
TBEArmor.at_object_creation | (self) |
Called once, when this object is first created. This is the
normal hook to overload for most object types.
|
Called once, when this object is first created. This is the
normal hook to overload for most object types.
| def at_object_creation(self):
"""
Called once, when this object is first created. This is the
normal hook to overload for most object types.
"""
self.db.damage_reduction = 4 # Amount of incoming damage reduced by armor
self.db.defense_modifier = -4 # Amount to modify defense value (pos = harder to hit, neg = easier) | [
"def",
"at_object_creation",
"(",
"self",
")",
":",
"self",
".",
"db",
".",
"damage_reduction",
"=",
"4",
"# Amount of incoming damage reduced by armor",
"self",
".",
"db",
".",
"defense_modifier",
"=",
"-",
"4",
"# Amount to modify defense value (pos = harder to hit, neg = easier)"
] | [
546,
4
] | [
552,
106
] | python | en | ['en', 'error', 'th'] | False |
TBEArmor.at_before_drop | (self, dropper) |
Can't drop in combat.
|
Can't drop in combat.
| def at_before_drop(self, dropper):
"""
Can't drop in combat.
"""
if is_in_combat(dropper):
dropper.msg("You can't doff armor in a fight!")
return False
return True | [
"def",
"at_before_drop",
"(",
"self",
",",
"dropper",
")",
":",
"if",
"is_in_combat",
"(",
"dropper",
")",
":",
"dropper",
".",
"msg",
"(",
"\"You can't doff armor in a fight!\"",
")",
"return",
"False",
"return",
"True"
] | [
553,
4
] | [
560,
19
] | python | en | ['en', 'error', 'th'] | False |
TBEArmor.at_drop | (self, dropper) |
Stop being wielded if dropped.
|
Stop being wielded if dropped.
| def at_drop(self, dropper):
"""
Stop being wielded if dropped.
"""
if dropper.db.worn_armor == self:
dropper.db.worn_armor = None
dropper.location.msg_contents("%s removes %s." % (dropper, self)) | [
"def",
"at_drop",
"(",
"self",
",",
"dropper",
")",
":",
"if",
"dropper",
".",
"db",
".",
"worn_armor",
"==",
"self",
":",
"dropper",
".",
"db",
".",
"worn_armor",
"=",
"None",
"dropper",
".",
"location",
".",
"msg_contents",
"(",
"\"%s removes %s.\"",
"%",
"(",
"dropper",
",",
"self",
")",
")"
] | [
561,
4
] | [
567,
77
] | python | en | ['en', 'error', 'th'] | False |
TBEArmor.at_before_give | (self, giver, getter) |
Can't give away in combat.
|
Can't give away in combat.
| def at_before_give(self, giver, getter):
"""
Can't give away in combat.
"""
if is_in_combat(giver):
dropper.msg("You can't doff armor in a fight!")
return False
return True | [
"def",
"at_before_give",
"(",
"self",
",",
"giver",
",",
"getter",
")",
":",
"if",
"is_in_combat",
"(",
"giver",
")",
":",
"dropper",
".",
"msg",
"(",
"\"You can't doff armor in a fight!\"",
")",
"return",
"False",
"return",
"True"
] | [
568,
4
] | [
575,
19
] | python | en | ['en', 'error', 'th'] | False |
TBEArmor.at_give | (self, giver, getter) |
Stop being wielded if given.
|
Stop being wielded if given.
| def at_give(self, giver, getter):
"""
Stop being wielded if given.
"""
if giver.db.worn_armor == self:
giver.db.worn_armor = None
giver.location.msg_contents("%s removes %s." % (giver, self)) | [
"def",
"at_give",
"(",
"self",
",",
"giver",
",",
"getter",
")",
":",
"if",
"giver",
".",
"db",
".",
"worn_armor",
"==",
"self",
":",
"giver",
".",
"db",
".",
"worn_armor",
"=",
"None",
"giver",
".",
"location",
".",
"msg_contents",
"(",
"\"%s removes %s.\"",
"%",
"(",
"giver",
",",
"self",
")",
")"
] | [
576,
4
] | [
582,
73
] | python | en | ['en', 'error', 'th'] | False |
TBEquipCharacter.at_object_creation | (self) |
Called once, when this object is first created. This is the
normal hook to overload for most object types.
|
Called once, when this object is first created. This is the
normal hook to overload for most object types.
| def at_object_creation(self):
"""
Called once, when this object is first created. This is the
normal hook to overload for most object types.
"""
self.db.max_hp = 100 # Set maximum HP to 100
self.db.hp = self.db.max_hp # Set current HP to maximum
self.db.wielded_weapon = None # Currently used weapon
self.db.worn_armor = None # Currently worn armor
self.db.unarmed_damage_range = (5, 15) # Minimum and maximum unarmed damage
self.db.unarmed_accuracy = 30 # Accuracy bonus for unarmed attacks
"""
Adds attributes for a character's current and maximum HP.
We're just going to set this value at '100' by default.
You may want to expand this to include various 'stats' that
can be changed at creation and factor into combat calculations.
""" | [
"def",
"at_object_creation",
"(",
"self",
")",
":",
"self",
".",
"db",
".",
"max_hp",
"=",
"100",
"# Set maximum HP to 100",
"self",
".",
"db",
".",
"hp",
"=",
"self",
".",
"db",
".",
"max_hp",
"# Set current HP to maximum",
"self",
".",
"db",
".",
"wielded_weapon",
"=",
"None",
"# Currently used weapon",
"self",
".",
"db",
".",
"worn_armor",
"=",
"None",
"# Currently worn armor",
"self",
".",
"db",
".",
"unarmed_damage_range",
"=",
"(",
"5",
",",
"15",
")",
"# Minimum and maximum unarmed damage",
"self",
".",
"db",
".",
"unarmed_accuracy",
"=",
"30",
"# Accuracy bonus for unarmed attacks",
"\"\"\"\n Adds attributes for a character's current and maximum HP.\n We're just going to set this value at '100' by default.\n\n You may want to expand this to include various 'stats' that\n can be changed at creation and factor into combat calculations.\n \"\"\""
] | [
590,
4
] | [
608,
11
] | python | en | ['en', 'error', 'th'] | False |
TBEquipCharacter.at_before_move | (self, destination) |
Called just before starting to move this object to
destination.
Args:
destination (Object): The object we are moving to
Returns:
shouldmove (bool): If we should move or not.
Notes:
If this method returns False/None, the move is cancelled
before it is even started.
|
Called just before starting to move this object to
destination. | def at_before_move(self, destination):
"""
Called just before starting to move this object to
destination.
Args:
destination (Object): The object we are moving to
Returns:
shouldmove (bool): If we should move or not.
Notes:
If this method returns False/None, the move is cancelled
before it is even started.
"""
# Keep the character from moving if at 0 HP or in combat.
if is_in_combat(self):
self.msg("You can't exit a room while in combat!")
return False # Returning false keeps the character from moving.
if self.db.HP <= 0:
self.msg("You can't move, you've been defeated!")
return False
return True | [
"def",
"at_before_move",
"(",
"self",
",",
"destination",
")",
":",
"# Keep the character from moving if at 0 HP or in combat.",
"if",
"is_in_combat",
"(",
"self",
")",
":",
"self",
".",
"msg",
"(",
"\"You can't exit a room while in combat!\"",
")",
"return",
"False",
"# Returning false keeps the character from moving.",
"if",
"self",
".",
"db",
".",
"HP",
"<=",
"0",
":",
"self",
".",
"msg",
"(",
"\"You can't move, you've been defeated!\"",
")",
"return",
"False",
"return",
"True"
] | [
610,
4
] | [
633,
19
] | python | en | ['en', 'error', 'th'] | False |
CmdFight.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
here = self.caller.location
fighters = []
if not self.caller.db.hp: # If you don't have any hp
self.caller.msg("You can't start a fight if you've been defeated!")
return
if is_in_combat(self.caller): # Already in a fight
self.caller.msg("You're already in a fight!")
return
for thing in here.contents: # Test everything in the room to add it to the fight.
if thing.db.HP: # If the object has HP...
fighters.append(thing) # ...then add it to the fight.
if len(fighters) <= 1: # If you're the only able fighter in the room
self.caller.msg("There's nobody here to fight!")
return
if here.db.combat_turnhandler: # If there's already a fight going on...
here.msg_contents("%s joins the fight!" % self.caller)
here.db.combat_turnhandler.join_fight(self.caller) # Join the fight!
return
here.msg_contents("%s starts a fight!" % self.caller)
# Add a turn handler script to the room, which starts combat.
here.scripts.add("contrib.turnbattle.tb_equip.TBEquipTurnHandler") | [
"def",
"func",
"(",
"self",
")",
":",
"here",
"=",
"self",
".",
"caller",
".",
"location",
"fighters",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"caller",
".",
"db",
".",
"hp",
":",
"# If you don't have any hp",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't start a fight if you've been defeated!\"",
")",
"return",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"# Already in a fight",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You're already in a fight!\"",
")",
"return",
"for",
"thing",
"in",
"here",
".",
"contents",
":",
"# Test everything in the room to add it to the fight.",
"if",
"thing",
".",
"db",
".",
"HP",
":",
"# If the object has HP...",
"fighters",
".",
"append",
"(",
"thing",
")",
"# ...then add it to the fight.",
"if",
"len",
"(",
"fighters",
")",
"<=",
"1",
":",
"# If you're the only able fighter in the room",
"self",
".",
"caller",
".",
"msg",
"(",
"\"There's nobody here to fight!\"",
")",
"return",
"if",
"here",
".",
"db",
".",
"combat_turnhandler",
":",
"# If there's already a fight going on...",
"here",
".",
"msg_contents",
"(",
"\"%s joins the fight!\"",
"%",
"self",
".",
"caller",
")",
"here",
".",
"db",
".",
"combat_turnhandler",
".",
"join_fight",
"(",
"self",
".",
"caller",
")",
"# Join the fight!",
"return",
"here",
".",
"msg_contents",
"(",
"\"%s starts a fight!\"",
"%",
"self",
".",
"caller",
")",
"# Add a turn handler script to the room, which starts combat.",
"here",
".",
"scripts",
".",
"add",
"(",
"\"contrib.turnbattle.tb_equip.TBEquipTurnHandler\"",
")"
] | [
657,
4
] | [
682,
74
] | python | en | ['en', 'error', 'th'] | False |
CmdAttack.func | (self) | This performs the actual command. | This performs the actual command. | def func(self):
"This performs the actual command."
"Set the attacker to the caller and the defender to the target."
if not is_in_combat(self.caller): # If not in combat, can't attack.
self.caller.msg("You can only do that in combat. (see: help fight)")
return
if not is_turn(self.caller): # If it's not your turn, can't attack.
self.caller.msg("You can only do that on your turn.")
return
if not self.caller.db.hp: # Can't attack if you have no HP.
self.caller.msg("You can't attack, you've been defeated.")
return
attacker = self.caller
defender = self.caller.search(self.args)
if not defender: # No valid target given.
return
if not defender.db.hp: # Target object has no HP left or to begin with
self.caller.msg("You can't fight that!")
return
if attacker == defender: # Target and attacker are the same
self.caller.msg("You can't attack yourself!")
return
"If everything checks out, call the attack resolving function."
resolve_attack(attacker, defender)
spend_action(self.caller, 1, action_name="attack") | [
"def",
"func",
"(",
"self",
")",
":",
"\"Set the attacker to the caller and the defender to the target.\"",
"if",
"not",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"# If not in combat, can't attack.",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that in combat. (see: help fight)\"",
")",
"return",
"if",
"not",
"is_turn",
"(",
"self",
".",
"caller",
")",
":",
"# If it's not your turn, can't attack.",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that on your turn.\"",
")",
"return",
"if",
"not",
"self",
".",
"caller",
".",
"db",
".",
"hp",
":",
"# Can't attack if you have no HP.",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't attack, you've been defeated.\"",
")",
"return",
"attacker",
"=",
"self",
".",
"caller",
"defender",
"=",
"self",
".",
"caller",
".",
"search",
"(",
"self",
".",
"args",
")",
"if",
"not",
"defender",
":",
"# No valid target given.",
"return",
"if",
"not",
"defender",
".",
"db",
".",
"hp",
":",
"# Target object has no HP left or to begin with",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't fight that!\"",
")",
"return",
"if",
"attacker",
"==",
"defender",
":",
"# Target and attacker are the same",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't attack yourself!\"",
")",
"return",
"\"If everything checks out, call the attack resolving function.\"",
"resolve_attack",
"(",
"attacker",
",",
"defender",
")",
"spend_action",
"(",
"self",
".",
"caller",
",",
"1",
",",
"action_name",
"=",
"\"attack\"",
")"
] | [
700,
4
] | [
732,
58
] | python | en | ['en', 'en', 'en'] | True |
CmdPass.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
if not is_in_combat(self.caller): # Can only pass a turn in combat.
self.caller.msg("You can only do that in combat. (see: help fight)")
return
if not is_turn(self.caller): # Can only pass if it's your turn.
self.caller.msg("You can only do that on your turn.")
return
self.caller.location.msg_contents("%s takes no further action, passing the turn." % self.caller)
spend_action(self.caller, 'all', action_name="pass") | [
"def",
"func",
"(",
"self",
")",
":",
"if",
"not",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"# Can only pass a turn in combat.",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that in combat. (see: help fight)\"",
")",
"return",
"if",
"not",
"is_turn",
"(",
"self",
".",
"caller",
")",
":",
"# Can only pass if it's your turn.",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that on your turn.\"",
")",
"return",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s takes no further action, passing the turn.\"",
"%",
"self",
".",
"caller",
")",
"spend_action",
"(",
"self",
".",
"caller",
",",
"'all'",
",",
"action_name",
"=",
"\"pass\"",
")"
] | [
750,
4
] | [
763,
60
] | python | en | ['en', 'error', 'th'] | False |
CmdDisengage.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
if not is_in_combat(self.caller): # If you're not in combat
self.caller.msg("You can only do that in combat. (see: help fight)")
return
if not is_turn(self.caller): # If it's not your turn
self.caller.msg("You can only do that on your turn.")
return
self.caller.location.msg_contents("%s disengages, ready to stop fighting." % self.caller)
spend_action(self.caller, 'all', action_name="disengage") # Spend all remaining actions.
"""
The action_name kwarg sets the character's last action to "disengage", which is checked by
the turn handler script to see if all fighters have disengaged.
""" | [
"def",
"func",
"(",
"self",
")",
":",
"if",
"not",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"# If you're not in combat",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that in combat. (see: help fight)\"",
")",
"return",
"if",
"not",
"is_turn",
"(",
"self",
".",
"caller",
")",
":",
"# If it's not your turn",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that on your turn.\"",
")",
"return",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s disengages, ready to stop fighting.\"",
"%",
"self",
".",
"caller",
")",
"spend_action",
"(",
"self",
".",
"caller",
",",
"'all'",
",",
"action_name",
"=",
"\"disengage\"",
")",
"# Spend all remaining actions.",
"\"\"\"\n The action_name kwarg sets the character's last action to \"disengage\", which is checked by\n the turn handler script to see if all fighters have disengaged.\n \"\"\""
] | [
782,
4
] | [
799,
11
] | python | en | ['en', 'error', 'th'] | False |
CmdRest.func | (self) | This performs the actual command. | This performs the actual command. | def func(self):
"This performs the actual command."
if is_in_combat(self.caller): # If you're in combat
self.caller.msg("You can't rest while you're in combat.")
return
self.caller.db.hp = self.caller.db.max_hp # Set current HP to maximum
self.caller.location.msg_contents("%s rests to recover HP." % self.caller)
"""
You'll probably want to replace this with your own system for recovering HP.
""" | [
"def",
"func",
"(",
"self",
")",
":",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"# If you're in combat",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't rest while you're in combat.\"",
")",
"return",
"self",
".",
"caller",
".",
"db",
".",
"hp",
"=",
"self",
".",
"caller",
".",
"db",
".",
"max_hp",
"# Set current HP to maximum",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s rests to recover HP.\"",
"%",
"self",
".",
"caller",
")",
"\"\"\"\n You'll probably want to replace this with your own system for recovering HP.\n \"\"\""
] | [
816,
4
] | [
827,
11
] | python | en | ['en', 'en', 'en'] | True |
CmdWield.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
# If in combat, check to see if it's your turn.
if is_in_combat(self.caller):
if not is_turn(self.caller):
self.caller.msg("You can only do that on your turn.")
return
if not self.args:
self.caller.msg("Usage: wield <obj>")
return
weapon = self.caller.search(self.args, candidates=self.caller.contents)
if not weapon:
return
if not weapon.is_typeclass("evennia.contrib.turnbattle.tb_equip.TBEWeapon"):
self.caller.msg("That's not a weapon!")
# Remember to update the path to the weapon typeclass if you move this module!
return
if not self.caller.db.wielded_weapon:
self.caller.db.wielded_weapon = weapon
self.caller.location.msg_contents("%s wields %s." % (self.caller, weapon))
else:
old_weapon = self.caller.db.wielded_weapon
self.caller.db.wielded_weapon = weapon
self.caller.location.msg_contents("%s lowers %s and wields %s." % (self.caller, old_weapon, weapon))
# Spend an action if in combat.
if is_in_combat(self.caller):
spend_action(self.caller, 1, action_name="wield") | [
"def",
"func",
"(",
"self",
")",
":",
"# If in combat, check to see if it's your turn.",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"if",
"not",
"is_turn",
"(",
"self",
".",
"caller",
")",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that on your turn.\"",
")",
"return",
"if",
"not",
"self",
".",
"args",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"Usage: wield <obj>\"",
")",
"return",
"weapon",
"=",
"self",
".",
"caller",
".",
"search",
"(",
"self",
".",
"args",
",",
"candidates",
"=",
"self",
".",
"caller",
".",
"contents",
")",
"if",
"not",
"weapon",
":",
"return",
"if",
"not",
"weapon",
".",
"is_typeclass",
"(",
"\"evennia.contrib.turnbattle.tb_equip.TBEWeapon\"",
")",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"That's not a weapon!\"",
")",
"# Remember to update the path to the weapon typeclass if you move this module!",
"return",
"if",
"not",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
":",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
"=",
"weapon",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s wields %s.\"",
"%",
"(",
"self",
".",
"caller",
",",
"weapon",
")",
")",
"else",
":",
"old_weapon",
"=",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
"=",
"weapon",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s lowers %s and wields %s.\"",
"%",
"(",
"self",
".",
"caller",
",",
"old_weapon",
",",
"weapon",
")",
")",
"# Spend an action if in combat.",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"spend_action",
"(",
"self",
".",
"caller",
",",
"1",
",",
"action_name",
"=",
"\"wield\"",
")"
] | [
872,
4
] | [
901,
61
] | python | en | ['en', 'error', 'th'] | False |
CmdUnwield.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
# If in combat, check to see if it's your turn.
if is_in_combat(self.caller):
if not is_turn(self.caller):
self.caller.msg("You can only do that on your turn.")
return
if not self.caller.db.wielded_weapon:
self.caller.msg("You aren't wielding a weapon!")
else:
old_weapon = self.caller.db.wielded_weapon
self.caller.db.wielded_weapon = None
self.caller.location.msg_contents("%s lowers %s." % (self.caller, old_weapon)) | [
"def",
"func",
"(",
"self",
")",
":",
"# If in combat, check to see if it's your turn.",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"if",
"not",
"is_turn",
"(",
"self",
".",
"caller",
")",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can only do that on your turn.\"",
")",
"return",
"if",
"not",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You aren't wielding a weapon!\"",
")",
"else",
":",
"old_weapon",
"=",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
"self",
".",
"caller",
".",
"db",
".",
"wielded_weapon",
"=",
"None",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s lowers %s.\"",
"%",
"(",
"self",
".",
"caller",
",",
"old_weapon",
")",
")"
] | [
917,
4
] | [
931,
90
] | python | en | ['en', 'error', 'th'] | False |
CmdDon.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
# Can't do this in combat
if is_in_combat(self.caller):
self.caller.msg("You can't don armor in a fight!")
return
if not self.args:
self.caller.msg("Usage: don <obj>")
return
armor = self.caller.search(self.args, candidates=self.caller.contents)
if not armor:
return
if not armor.is_typeclass("evennia.contrib.turnbattle.tb_equip.TBEArmor"):
self.caller.msg("That's not armor!")
# Remember to update the path to the armor typeclass if you move this module!
return
if not self.caller.db.worn_armor:
self.caller.db.worn_armor = armor
self.caller.location.msg_contents("%s dons %s." % (self.caller, armor))
else:
old_armor = self.caller.db.worn_armor
self.caller.db.worn_armor = armor
self.caller.location.msg_contents("%s removes %s and dons %s." % (self.caller, old_armor, armor)) | [
"def",
"func",
"(",
"self",
")",
":",
"# Can't do this in combat",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't don armor in a fight!\"",
")",
"return",
"if",
"not",
"self",
".",
"args",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"Usage: don <obj>\"",
")",
"return",
"armor",
"=",
"self",
".",
"caller",
".",
"search",
"(",
"self",
".",
"args",
",",
"candidates",
"=",
"self",
".",
"caller",
".",
"contents",
")",
"if",
"not",
"armor",
":",
"return",
"if",
"not",
"armor",
".",
"is_typeclass",
"(",
"\"evennia.contrib.turnbattle.tb_equip.TBEArmor\"",
")",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"That's not armor!\"",
")",
"# Remember to update the path to the armor typeclass if you move this module!",
"return",
"if",
"not",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
":",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
"=",
"armor",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s dons %s.\"",
"%",
"(",
"self",
".",
"caller",
",",
"armor",
")",
")",
"else",
":",
"old_armor",
"=",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
"=",
"armor",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s removes %s and dons %s.\"",
"%",
"(",
"self",
".",
"caller",
",",
"old_armor",
",",
"armor",
")",
")"
] | [
948,
4
] | [
973,
109
] | python | en | ['en', 'error', 'th'] | False |
CmdDoff.func | (self) |
This performs the actual command.
|
This performs the actual command.
| def func(self):
"""
This performs the actual command.
"""
# Can't do this in combat
if is_in_combat(self.caller):
self.caller.msg("You can't doff armor in a fight!")
return
if not self.caller.db.worn_armor:
self.caller.msg("You aren't wearing any armor!")
else:
old_armor = self.caller.db.worn_armor
self.caller.db.worn_armor = None
self.caller.location.msg_contents("%s removes %s." % (self.caller, old_armor)) | [
"def",
"func",
"(",
"self",
")",
":",
"# Can't do this in combat",
"if",
"is_in_combat",
"(",
"self",
".",
"caller",
")",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You can't doff armor in a fight!\"",
")",
"return",
"if",
"not",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
":",
"self",
".",
"caller",
".",
"msg",
"(",
"\"You aren't wearing any armor!\"",
")",
"else",
":",
"old_armor",
"=",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
"self",
".",
"caller",
".",
"db",
".",
"worn_armor",
"=",
"None",
"self",
".",
"caller",
".",
"location",
".",
"msg_contents",
"(",
"\"%s removes %s.\"",
"%",
"(",
"self",
".",
"caller",
",",
"old_armor",
")",
")"
] | [
990,
4
] | [
1003,
90
] | python | en | ['en', 'error', 'th'] | False |
BattleCmdSet.at_cmdset_creation | (self) |
Populates the cmdset
|
Populates the cmdset
| def at_cmdset_creation(self):
"""
Populates the cmdset
"""
self.add(CmdFight())
self.add(CmdAttack())
self.add(CmdRest())
self.add(CmdPass())
self.add(CmdDisengage())
self.add(CmdCombatHelp())
self.add(CmdWield())
self.add(CmdUnwield())
self.add(CmdDon())
self.add(CmdDoff()) | [
"def",
"at_cmdset_creation",
"(",
"self",
")",
":",
"self",
".",
"add",
"(",
"CmdFight",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdAttack",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdRest",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdPass",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdDisengage",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdCombatHelp",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdWield",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdUnwield",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdDon",
"(",
")",
")",
"self",
".",
"add",
"(",
"CmdDoff",
"(",
")",
")"
] | [
1013,
4
] | [
1026,
27
] | python | en | ['en', 'error', 'th'] | False |
dewpoint | (rh: float, t: float) |
Calculate the dewpoint from relative_humidity
Ref: https://www.omnicalculator.com/physics/dew-point#howto
|
Calculate the dewpoint from relative_humidity
Ref: https://www.omnicalculator.com/physics/dew-point#howto
| def dewpoint(rh: float, t: float) -> float:
"""
Calculate the dewpoint from relative_humidity
Ref: https://www.omnicalculator.com/physics/dew-point#howto
"""
a, b = 17.62, 243.12
alpha = log(rh) + a * t / (b + t)
return b * alpha / (a - alpha) | [
"def",
"dewpoint",
"(",
"rh",
":",
"float",
",",
"t",
":",
"float",
")",
"->",
"float",
":",
"a",
",",
"b",
"=",
"17.62",
",",
"243.12",
"alpha",
"=",
"log",
"(",
"rh",
")",
"+",
"a",
"*",
"t",
"/",
"(",
"b",
"+",
"t",
")",
"return",
"b",
"*",
"alpha",
"/",
"(",
"a",
"-",
"alpha",
")"
] | [
30,
0
] | [
37,
34
] | python | en | ['en', 'error', 'th'] | False |
GeneratesRequest.ledgerRequest | (self) |
Generates a Request object to be submitted to the ledger.
:return: a Request to be submitted, or None if it shouldn't be written
|
Generates a Request object to be submitted to the ledger.
:return: a Request to be submitted, or None if it shouldn't be written
| def ledgerRequest(self):
"""
Generates a Request object to be submitted to the ledger.
:return: a Request to be submitted, or None if it shouldn't be written
""" | [
"def",
"ledgerRequest",
"(",
"self",
")",
":"
] | [
9,
4
] | [
13,
11
] | python | en | ['en', 'error', 'th'] | False |
HredAgent.add_cmdline_args | (
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) |
Add command-line arguments specifically for this agent.
|
Add command-line arguments specifically for this agent.
| def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
"""
Add command-line arguments specifically for this agent.
"""
agent = parser.add_argument_group("HRED Arguments")
agent.add_argument(
"-hs",
"--hiddensize",
type=int,
default=128,
help="size of the hidden layers",
)
agent.add_argument(
"-esz",
"--embeddingsize",
type=int,
default=128,
help="size of the token embeddings",
)
agent.add_argument(
"-nl", "--numlayers", type=int, default=2, help="number of hidden layers"
)
agent.add_argument(
"-dr", "--dropout", type=float, default=0.1, help="dropout rate"
)
agent.add_argument(
"-lt",
"--lookuptable",
default="unique",
choices=["unique", "enc_dec", "dec_out", "all"],
help="The encoder, decoder, and output modules can "
"share weights, or not. "
"Unique has independent embeddings for each. "
"Enc_dec shares the embedding for the encoder "
"and decoder. "
"Dec_out shares decoder embedding and output "
"weights. "
"All shares all three weights.",
)
agent.add_argument(
"-idr",
"--input-dropout",
type=float,
default=0.0,
help="Probability of replacing tokens with UNK in training.",
)
super().add_cmdline_args(parser, partial_opt=partial_opt)
return agent | [
"def",
"add_cmdline_args",
"(",
"cls",
",",
"parser",
":",
"ParlaiParser",
",",
"partial_opt",
":",
"Optional",
"[",
"Opt",
"]",
"=",
"None",
")",
"->",
"ParlaiParser",
":",
"agent",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"HRED Arguments\"",
")",
"agent",
".",
"add_argument",
"(",
"\"-hs\"",
",",
"\"--hiddensize\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"128",
",",
"help",
"=",
"\"size of the hidden layers\"",
",",
")",
"agent",
".",
"add_argument",
"(",
"\"-esz\"",
",",
"\"--embeddingsize\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"128",
",",
"help",
"=",
"\"size of the token embeddings\"",
",",
")",
"agent",
".",
"add_argument",
"(",
"\"-nl\"",
",",
"\"--numlayers\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"2",
",",
"help",
"=",
"\"number of hidden layers\"",
")",
"agent",
".",
"add_argument",
"(",
"\"-dr\"",
",",
"\"--dropout\"",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.1",
",",
"help",
"=",
"\"dropout rate\"",
")",
"agent",
".",
"add_argument",
"(",
"\"-lt\"",
",",
"\"--lookuptable\"",
",",
"default",
"=",
"\"unique\"",
",",
"choices",
"=",
"[",
"\"unique\"",
",",
"\"enc_dec\"",
",",
"\"dec_out\"",
",",
"\"all\"",
"]",
",",
"help",
"=",
"\"The encoder, decoder, and output modules can \"",
"\"share weights, or not. \"",
"\"Unique has independent embeddings for each. \"",
"\"Enc_dec shares the embedding for the encoder \"",
"\"and decoder. \"",
"\"Dec_out shares decoder embedding and output \"",
"\"weights. \"",
"\"All shares all three weights.\"",
",",
")",
"agent",
".",
"add_argument",
"(",
"\"-idr\"",
",",
"\"--input-dropout\"",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.0",
",",
"help",
"=",
"\"Probability of replacing tokens with UNK in training.\"",
",",
")",
"super",
"(",
")",
".",
"add_cmdline_args",
"(",
"parser",
",",
"partial_opt",
"=",
"partial_opt",
")",
"return",
"agent"
] | [
18,
4
] | [
68,
20
] | python | en | ['en', 'error', 'th'] | False |
HredAgent.__init__ | (self, opt, shared=None) |
Set up model.
|
Set up model.
| def __init__(self, opt, shared=None):
"""
Set up model.
"""
if torch.cuda.is_available():
self.device = torch.device("cuda:0")
else:
self.device = torch.device("cpu")
super().__init__(opt, shared)
self.id = "Hred" | [
"def",
"__init__",
"(",
"self",
",",
"opt",
",",
"shared",
"=",
"None",
")",
":",
"if",
"torch",
".",
"cuda",
".",
"is_available",
"(",
")",
":",
"self",
".",
"device",
"=",
"torch",
".",
"device",
"(",
"\"cuda:0\"",
")",
"else",
":",
"self",
".",
"device",
"=",
"torch",
".",
"device",
"(",
"\"cpu\"",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"opt",
",",
"shared",
")",
"self",
".",
"id",
"=",
"\"Hred\""
] | [
70,
4
] | [
79,
24
] | python | en | ['en', 'error', 'th'] | False |
HredAgent.batchify | (self, obs_batch, sort=True) |
Add action and attribute supervision for batches.
Store history vec as context_vec.
|
Add action and attribute supervision for batches. | def batchify(self, obs_batch, sort=True):
"""
Add action and attribute supervision for batches.
Store history vec as context_vec.
"""
batch = super().batchify(obs_batch, sort)
batch["context_vec"], batch["hist_lens"] = self.parse_context_vec(batch)
return batch | [
"def",
"batchify",
"(",
"self",
",",
"obs_batch",
",",
"sort",
"=",
"True",
")",
":",
"batch",
"=",
"super",
"(",
")",
".",
"batchify",
"(",
"obs_batch",
",",
"sort",
")",
"batch",
"[",
"\"context_vec\"",
"]",
",",
"batch",
"[",
"\"hist_lens\"",
"]",
"=",
"self",
".",
"parse_context_vec",
"(",
"batch",
")",
"return",
"batch"
] | [
124,
4
] | [
132,
20
] | python | en | ['en', 'error', 'th'] | False |
HredAgent._set_text_vec | (self, obs, history, truncate) |
Set the 'text_vec' field in the observation.
Overridden to include both local utterance (text_vec) and full history
(context_vec)
|
Set the 'text_vec' field in the observation. | def _set_text_vec(self, obs, history, truncate):
"""
Set the 'text_vec' field in the observation.
Overridden to include both local utterance (text_vec) and full history
(context_vec)
"""
if "text" not in obs:
return obs
if "text_vec" not in obs:
# text vec is not precomputed, so we set it using the history
history_string = history.get_history_str()
# when text not exist, we get text_vec from history string
# history could be none if it is an image task and 'text'
# filed is be empty. We don't want this
if history_string is None:
return obs
obs["full_text"] = history_string
if history_string:
history_vec = history.get_history_vec_list()
obs["text_vec"] = history_vec[-1]
obs["context_vec"] = history_vec
# check truncation
if obs.get("text_vec") is not None:
truncated_vec = self._check_truncate(obs["text_vec"], truncate, True)
obs.force_set("text_vec", torch.LongTensor(truncated_vec))
return obs | [
"def",
"_set_text_vec",
"(",
"self",
",",
"obs",
",",
"history",
",",
"truncate",
")",
":",
"if",
"\"text\"",
"not",
"in",
"obs",
":",
"return",
"obs",
"if",
"\"text_vec\"",
"not",
"in",
"obs",
":",
"# text vec is not precomputed, so we set it using the history",
"history_string",
"=",
"history",
".",
"get_history_str",
"(",
")",
"# when text not exist, we get text_vec from history string",
"# history could be none if it is an image task and 'text'",
"# filed is be empty. We don't want this",
"if",
"history_string",
"is",
"None",
":",
"return",
"obs",
"obs",
"[",
"\"full_text\"",
"]",
"=",
"history_string",
"if",
"history_string",
":",
"history_vec",
"=",
"history",
".",
"get_history_vec_list",
"(",
")",
"obs",
"[",
"\"text_vec\"",
"]",
"=",
"history_vec",
"[",
"-",
"1",
"]",
"obs",
"[",
"\"context_vec\"",
"]",
"=",
"history_vec",
"# check truncation",
"if",
"obs",
".",
"get",
"(",
"\"text_vec\"",
")",
"is",
"not",
"None",
":",
"truncated_vec",
"=",
"self",
".",
"_check_truncate",
"(",
"obs",
"[",
"\"text_vec\"",
"]",
",",
"truncate",
",",
"True",
")",
"obs",
".",
"force_set",
"(",
"\"text_vec\"",
",",
"torch",
".",
"LongTensor",
"(",
"truncated_vec",
")",
")",
"return",
"obs"
] | [
155,
4
] | [
183,
18
] | python | en | ['en', 'error', 'th'] | False |
HredAgent._dummy_batch | (self, batchsize, maxlen) |
Overridden to add dummy context vec and hist lens.
|
Overridden to add dummy context vec and hist lens.
| def _dummy_batch(self, batchsize, maxlen):
"""
Overridden to add dummy context vec and hist lens.
"""
batch = super()._dummy_batch(batchsize, maxlen)
batch["context_vec"] = batch["text_vec"]
batch["hist_lens"] = torch.ones(batchsize, dtype=torch.long)
return batch | [
"def",
"_dummy_batch",
"(",
"self",
",",
"batchsize",
",",
"maxlen",
")",
":",
"batch",
"=",
"super",
"(",
")",
".",
"_dummy_batch",
"(",
"batchsize",
",",
"maxlen",
")",
"batch",
"[",
"\"context_vec\"",
"]",
"=",
"batch",
"[",
"\"text_vec\"",
"]",
"batch",
"[",
"\"hist_lens\"",
"]",
"=",
"torch",
".",
"ones",
"(",
"batchsize",
",",
"dtype",
"=",
"torch",
".",
"long",
")",
"return",
"batch"
] | [
185,
4
] | [
192,
20
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.align | (self) |
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
|
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above | def align(self):
"""
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["align"] | [
"def",
"align",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"align\"",
"]"
] | [
26,
4
] | [
41,
28
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.alignsrc | (self) |
Sets the source reference on Chart Studio Cloud for align .
The 'alignsrc' 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 align .
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def alignsrc(self):
"""
Sets the source reference on Chart Studio Cloud for align .
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["alignsrc"] | [
"def",
"alignsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"alignsrc\"",
"]"
] | [
50,
4
] | [
61,
31
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.bgcolor | (self) |
Sets the background color of the hover labels for this trace
The 'bgcolor' 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
|
Sets the background color of the hover labels for this trace
The 'bgcolor' 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 bgcolor(self):
"""
Sets the background color of the hover labels for this trace
The 'bgcolor' 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["bgcolor"] | [
"def",
"bgcolor",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"bgcolor\"",
"]"
] | [
70,
4
] | [
121,
30
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.bgcolorsrc | (self) |
Sets the source reference on Chart Studio Cloud for bgcolor .
The 'bgcolorsrc' 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 bgcolor .
The 'bgcolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def bgcolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for bgcolor .
The 'bgcolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bgcolorsrc"] | [
"def",
"bgcolorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"bgcolorsrc\"",
"]"
] | [
130,
4
] | [
141,
33
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.bordercolor | (self) |
Sets the border color of the hover labels for this trace.
The 'bordercolor' 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
|
Sets the border color of the hover labels for this trace.
The 'bordercolor' 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 bordercolor(self):
"""
Sets the border color of the hover labels for this trace.
The 'bordercolor' 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["bordercolor"] | [
"def",
"bordercolor",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"bordercolor\"",
"]"
] | [
150,
4
] | [
201,
34
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.bordercolorsrc | (self) |
Sets the source reference on Chart Studio Cloud for
bordercolor .
The 'bordercolorsrc' 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
bordercolor .
The 'bordercolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def bordercolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
bordercolor .
The 'bordercolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bordercolorsrc"] | [
"def",
"bordercolorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"bordercolorsrc\"",
"]"
] | [
210,
4
] | [
222,
37
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.font | (self) |
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.candlestick.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Supported dict properties:
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
-------
plotly.graph_objs.candlestick.hoverlabel.Font
|
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.candlestick.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Supported dict properties:
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 . | def font(self):
"""
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.candlestick.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Supported dict properties:
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
-------
plotly.graph_objs.candlestick.hoverlabel.Font
"""
return self["font"] | [
"def",
"font",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"font\"",
"]"
] | [
231,
4
] | [
278,
27
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.namelength | (self) |
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
|
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above | def namelength(self):
"""
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["namelength"] | [
"def",
"namelength",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"namelength\"",
"]"
] | [
287,
4
] | [
305,
33
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.namelengthsrc | (self) |
Sets the source reference on Chart Studio Cloud for namelength
.
The 'namelengthsrc' 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 namelength
.
The 'namelengthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def namelengthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for namelength
.
The 'namelengthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["namelengthsrc"] | [
"def",
"namelengthsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"namelengthsrc\"",
"]"
] | [
314,
4
] | [
326,
36
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.split | (self) |
Show hover information (open, close, high, low) in separate
labels.
The 'split' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Show hover information (open, close, high, low) in separate
labels.
The 'split' property must be specified as a bool
(either True, or False) | def split(self):
"""
Show hover information (open, close, high, low) in separate
labels.
The 'split' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["split"] | [
"def",
"split",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"split\"",
"]"
] | [
335,
4
] | [
347,
28
] | python | en | ['en', 'error', 'th'] | False |
Hoverlabel.__init__ | (
self,
arg=None,
align=None,
alignsrc=None,
bgcolor=None,
bgcolorsrc=None,
bordercolor=None,
bordercolorsrc=None,
font=None,
namelength=None,
namelengthsrc=None,
split=None,
**kwargs
) |
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.candlestick.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
align .
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
bgcolor .
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
bordercolor .
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
namelength .
split
Show hover information (open, close, high, low) in
separate labels.
Returns
-------
Hoverlabel
|
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.candlestick.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
align .
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
bgcolor .
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
bordercolor .
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
namelength .
split
Show hover information (open, close, high, low) in
separate labels. | def __init__(
self,
arg=None,
align=None,
alignsrc=None,
bgcolor=None,
bgcolorsrc=None,
bordercolor=None,
bordercolorsrc=None,
font=None,
namelength=None,
namelengthsrc=None,
split=None,
**kwargs
):
"""
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.candlestick.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
align .
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
bgcolor .
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
bordercolor .
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
namelength .
split
Show hover information (open, close, high, low) in
separate labels.
Returns
-------
Hoverlabel
"""
super(Hoverlabel, self).__init__("hoverlabel")
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.candlestick.Hoverlabel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.candlestick.Hoverlabel`"""
)
# 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("align", None)
_v = align if align is not None else _v
if _v is not None:
self["align"] = _v
_v = arg.pop("alignsrc", None)
_v = alignsrc if alignsrc is not None else _v
if _v is not None:
self["alignsrc"] = _v
_v = arg.pop("bgcolor", None)
_v = bgcolor if bgcolor is not None else _v
if _v is not None:
self["bgcolor"] = _v
_v = arg.pop("bgcolorsrc", None)
_v = bgcolorsrc if bgcolorsrc is not None else _v
if _v is not None:
self["bgcolorsrc"] = _v
_v = arg.pop("bordercolor", None)
_v = bordercolor if bordercolor is not None else _v
if _v is not None:
self["bordercolor"] = _v
_v = arg.pop("bordercolorsrc", None)
_v = bordercolorsrc if bordercolorsrc is not None else _v
if _v is not None:
self["bordercolorsrc"] = _v
_v = arg.pop("font", None)
_v = font if font is not None else _v
if _v is not None:
self["font"] = _v
_v = arg.pop("namelength", None)
_v = namelength if namelength is not None else _v
if _v is not None:
self["namelength"] = _v
_v = arg.pop("namelengthsrc", None)
_v = namelengthsrc if namelengthsrc is not None else _v
if _v is not None:
self["namelengthsrc"] = _v
_v = arg.pop("split", None)
_v = split if split is not None else _v
if _v is not None:
self["split"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"align",
"=",
"None",
",",
"alignsrc",
"=",
"None",
",",
"bgcolor",
"=",
"None",
",",
"bgcolorsrc",
"=",
"None",
",",
"bordercolor",
"=",
"None",
",",
"bordercolorsrc",
"=",
"None",
",",
"font",
"=",
"None",
",",
"namelength",
"=",
"None",
",",
"namelengthsrc",
"=",
"None",
",",
"split",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Hoverlabel",
",",
"self",
")",
".",
"__init__",
"(",
"\"hoverlabel\"",
")",
"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.candlestick.Hoverlabel \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.candlestick.Hoverlabel`\"\"\"",
")",
"# 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",
"(",
"\"align\"",
",",
"None",
")",
"_v",
"=",
"align",
"if",
"align",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"align\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"alignsrc\"",
",",
"None",
")",
"_v",
"=",
"alignsrc",
"if",
"alignsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"alignsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"bgcolor\"",
",",
"None",
")",
"_v",
"=",
"bgcolor",
"if",
"bgcolor",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"bgcolor\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"bgcolorsrc\"",
",",
"None",
")",
"_v",
"=",
"bgcolorsrc",
"if",
"bgcolorsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"bgcolorsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"bordercolor\"",
",",
"None",
")",
"_v",
"=",
"bordercolor",
"if",
"bordercolor",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"bordercolor\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"bordercolorsrc\"",
",",
"None",
")",
"_v",
"=",
"bordercolorsrc",
"if",
"bordercolorsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"bordercolorsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"font\"",
",",
"None",
")",
"_v",
"=",
"font",
"if",
"font",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"font\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"namelength\"",
",",
"None",
")",
"_v",
"=",
"namelength",
"if",
"namelength",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"namelength\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"namelengthsrc\"",
",",
"None",
")",
"_v",
"=",
"namelengthsrc",
"if",
"namelengthsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"namelengthsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"split\"",
",",
"None",
")",
"_v",
"=",
"split",
"if",
"split",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"split\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
395,
4
] | [
535,
34
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.__init__ | (self, did: str = None) |
Initialize the DIDDoc instance.
Retain DID ('id' in DIDDoc context); initialize verification keys
and services to empty lists.
Args:
did: DID for current DIDdoc
Raises:
ValueError: for bad input DID.
|
Initialize the DIDDoc instance. | def __init__(self, did: str = None) -> None:
"""
Initialize the DIDDoc instance.
Retain DID ('id' in DIDDoc context); initialize verification keys
and services to empty lists.
Args:
did: DID for current DIDdoc
Raises:
ValueError: for bad input DID.
"""
self._did = canon_did(did) if did else None # allow specification post-hoc
self._pubkey = {}
self._service = {} | [
"def",
"__init__",
"(",
"self",
",",
"did",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"_did",
"=",
"canon_did",
"(",
"did",
")",
"if",
"did",
"else",
"None",
"# allow specification post-hoc",
"self",
".",
"_pubkey",
"=",
"{",
"}",
"self",
".",
"_service",
"=",
"{",
"}"
] | [
43,
4
] | [
60,
26
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.did | (self) | Accessor for DID. | Accessor for DID. | def did(self) -> str:
"""Accessor for DID."""
return self._did | [
"def",
"did",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_did"
] | [
63,
4
] | [
66,
24
] | python | en | ['da', 'en', 'en'] | True |
DIDDoc.did | (self, value: str) |
Set DID ('id' in DIDDoc context).
Args:
value: DID
Raises:
ValueError: for bad input DID.
|
Set DID ('id' in DIDDoc context). | def did(self, value: str) -> None:
"""
Set DID ('id' in DIDDoc context).
Args:
value: DID
Raises:
ValueError: for bad input DID.
"""
self._did = canon_did(value) if value else None | [
"def",
"did",
"(",
"self",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_did",
"=",
"canon_did",
"(",
"value",
")",
"if",
"value",
"else",
"None"
] | [
69,
4
] | [
81,
55
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.pubkey | (self) | Accessor for public keys by identifier. | Accessor for public keys by identifier. | def pubkey(self) -> dict:
"""Accessor for public keys by identifier."""
return self._pubkey | [
"def",
"pubkey",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_pubkey"
] | [
84,
4
] | [
87,
27
] | python | en | ['en', 'fy', 'en'] | True |
DIDDoc.authnkey | (self) | Accessor for public keys marked as authentication keys, by identifier. | Accessor for public keys marked as authentication keys, by identifier. | def authnkey(self) -> dict:
"""Accessor for public keys marked as authentication keys, by identifier."""
return {k: self._pubkey[k] for k in self._pubkey if self._pubkey[k].authn} | [
"def",
"authnkey",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"k",
":",
"self",
".",
"_pubkey",
"[",
"k",
"]",
"for",
"k",
"in",
"self",
".",
"_pubkey",
"if",
"self",
".",
"_pubkey",
"[",
"k",
"]",
".",
"authn",
"}"
] | [
90,
4
] | [
93,
82
] | python | en | ['en', 'fy', 'en'] | True |
DIDDoc.service | (self) | Accessor for services by identifier. | Accessor for services by identifier. | def service(self) -> dict:
"""Accessor for services by identifier."""
return self._service | [
"def",
"service",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_service"
] | [
96,
4
] | [
99,
28
] | python | en | ['en', 'en', 'en'] | True |
DIDDoc.set | (self, item: Union[Service, PublicKey]) |
Add or replace service or public key; return current DIDDoc.
Raises:
ValueError: if input item is neither service nor public key.
Args:
item: service or public key to set
Returns: the current DIDDoc
|
Add or replace service or public key; return current DIDDoc. | def set(self, item: Union[Service, PublicKey]) -> "DIDDoc":
"""
Add or replace service or public key; return current DIDDoc.
Raises:
ValueError: if input item is neither service nor public key.
Args:
item: service or public key to set
Returns: the current DIDDoc
"""
if isinstance(item, Service):
self.service[item.id] = item
elif isinstance(item, PublicKey):
self.pubkey[item.id] = item
else:
raise ValueError(
"Cannot add item {} to DIDDoc on DID {}".format(item, self.did)
) | [
"def",
"set",
"(",
"self",
",",
"item",
":",
"Union",
"[",
"Service",
",",
"PublicKey",
"]",
")",
"->",
"\"DIDDoc\"",
":",
"if",
"isinstance",
"(",
"item",
",",
"Service",
")",
":",
"self",
".",
"service",
"[",
"item",
".",
"id",
"]",
"=",
"item",
"elif",
"isinstance",
"(",
"item",
",",
"PublicKey",
")",
":",
"self",
".",
"pubkey",
"[",
"item",
".",
"id",
"]",
"=",
"item",
"else",
":",
"raise",
"ValueError",
"(",
"\"Cannot add item {} to DIDDoc on DID {}\"",
".",
"format",
"(",
"item",
",",
"self",
".",
"did",
")",
")"
] | [
101,
4
] | [
122,
13
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.serialize | (self) |
Dump current object to a JSON-compatible dictionary.
Returns:
dict representation of current DIDDoc
|
Dump current object to a JSON-compatible dictionary. | def serialize(self) -> str:
"""
Dump current object to a JSON-compatible dictionary.
Returns:
dict representation of current DIDDoc
"""
return {
"@context": DIDDoc.CONTEXT,
"id": canon_ref(self.did, self.did),
"publicKey": [pubkey.to_dict() for pubkey in self.pubkey.values()],
"authentication": [
{
"type": pubkey.type.authn_type,
"publicKey": canon_ref(self.did, pubkey.id),
}
for pubkey in self.pubkey.values()
if pubkey.authn
],
"service": [service.to_dict() for service in self.service.values()],
} | [
"def",
"serialize",
"(",
"self",
")",
"->",
"str",
":",
"return",
"{",
"\"@context\"",
":",
"DIDDoc",
".",
"CONTEXT",
",",
"\"id\"",
":",
"canon_ref",
"(",
"self",
".",
"did",
",",
"self",
".",
"did",
")",
",",
"\"publicKey\"",
":",
"[",
"pubkey",
".",
"to_dict",
"(",
")",
"for",
"pubkey",
"in",
"self",
".",
"pubkey",
".",
"values",
"(",
")",
"]",
",",
"\"authentication\"",
":",
"[",
"{",
"\"type\"",
":",
"pubkey",
".",
"type",
".",
"authn_type",
",",
"\"publicKey\"",
":",
"canon_ref",
"(",
"self",
".",
"did",
",",
"pubkey",
".",
"id",
")",
",",
"}",
"for",
"pubkey",
"in",
"self",
".",
"pubkey",
".",
"values",
"(",
")",
"if",
"pubkey",
".",
"authn",
"]",
",",
"\"service\"",
":",
"[",
"service",
".",
"to_dict",
"(",
")",
"for",
"service",
"in",
"self",
".",
"service",
".",
"values",
"(",
")",
"]",
",",
"}"
] | [
124,
4
] | [
146,
9
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.to_json | (self) |
Dump current object as json (JSON-LD).
Returns:
json representation of current DIDDoc
|
Dump current object as json (JSON-LD). | def to_json(self) -> str:
"""
Dump current object as json (JSON-LD).
Returns:
json representation of current DIDDoc
"""
return json.dumps(self.serialize()) | [
"def",
"to_json",
"(",
"self",
")",
"->",
"str",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"serialize",
"(",
")",
")"
] | [
148,
4
] | [
157,
43
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.add_service_pubkeys | (
self, service: dict, tags: Union[Sequence[str], str]
) |
Add public keys specified in service. Return public keys so discovered.
Args:
service: service from DID document
tags: potential tags marking public keys of type of interest
(the standard is still coalescing)
Raises:
ValueError: for public key reference not present in DID document.
Returns: list of public keys from the document service specification
|
Add public keys specified in service. Return public keys so discovered. | def add_service_pubkeys(
self, service: dict, tags: Union[Sequence[str], str]
) -> List[PublicKey]:
"""
Add public keys specified in service. Return public keys so discovered.
Args:
service: service from DID document
tags: potential tags marking public keys of type of interest
(the standard is still coalescing)
Raises:
ValueError: for public key reference not present in DID document.
Returns: list of public keys from the document service specification
"""
rv = []
for tag in [tags] if isinstance(tags, str) else list(tags):
for svc_key in service.get(tag, {}):
canon_key = canon_ref(self.did, svc_key)
pubkey = None
if "#" in svc_key:
if canon_key in self.pubkey:
pubkey = self.pubkey[canon_key]
else: # service key refers to another DID doc
LOGGER.debug(
"DID document %s has no public key %s", self.did, svc_key
)
raise ValueError(
"DID document {} has no public key {}".format(
self.did, svc_key
)
)
else:
for existing_pubkey in self.pubkey.values():
if existing_pubkey.value == svc_key:
pubkey = existing_pubkey
break
else:
pubkey = PublicKey(
self.did,
ident=svc_key[-9:-1], # industrial-grade uniqueness
value=svc_key,
)
self._pubkey[pubkey.id] = pubkey
if (
pubkey and pubkey not in rv
): # perverse case: could specify same key multiple ways; append once
rv.append(pubkey)
return rv | [
"def",
"add_service_pubkeys",
"(",
"self",
",",
"service",
":",
"dict",
",",
"tags",
":",
"Union",
"[",
"Sequence",
"[",
"str",
"]",
",",
"str",
"]",
")",
"->",
"List",
"[",
"PublicKey",
"]",
":",
"rv",
"=",
"[",
"]",
"for",
"tag",
"in",
"[",
"tags",
"]",
"if",
"isinstance",
"(",
"tags",
",",
"str",
")",
"else",
"list",
"(",
"tags",
")",
":",
"for",
"svc_key",
"in",
"service",
".",
"get",
"(",
"tag",
",",
"{",
"}",
")",
":",
"canon_key",
"=",
"canon_ref",
"(",
"self",
".",
"did",
",",
"svc_key",
")",
"pubkey",
"=",
"None",
"if",
"\"#\"",
"in",
"svc_key",
":",
"if",
"canon_key",
"in",
"self",
".",
"pubkey",
":",
"pubkey",
"=",
"self",
".",
"pubkey",
"[",
"canon_key",
"]",
"else",
":",
"# service key refers to another DID doc",
"LOGGER",
".",
"debug",
"(",
"\"DID document %s has no public key %s\"",
",",
"self",
".",
"did",
",",
"svc_key",
")",
"raise",
"ValueError",
"(",
"\"DID document {} has no public key {}\"",
".",
"format",
"(",
"self",
".",
"did",
",",
"svc_key",
")",
")",
"else",
":",
"for",
"existing_pubkey",
"in",
"self",
".",
"pubkey",
".",
"values",
"(",
")",
":",
"if",
"existing_pubkey",
".",
"value",
"==",
"svc_key",
":",
"pubkey",
"=",
"existing_pubkey",
"break",
"else",
":",
"pubkey",
"=",
"PublicKey",
"(",
"self",
".",
"did",
",",
"ident",
"=",
"svc_key",
"[",
"-",
"9",
":",
"-",
"1",
"]",
",",
"# industrial-grade uniqueness",
"value",
"=",
"svc_key",
",",
")",
"self",
".",
"_pubkey",
"[",
"pubkey",
".",
"id",
"]",
"=",
"pubkey",
"if",
"(",
"pubkey",
"and",
"pubkey",
"not",
"in",
"rv",
")",
":",
"# perverse case: could specify same key multiple ways; append once",
"rv",
".",
"append",
"(",
"pubkey",
")",
"return",
"rv"
] | [
159,
4
] | [
214,
17
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.deserialize | (cls, did_doc: dict) |
Construct DIDDoc object from dict representation.
Args:
did_doc: DIDDoc dict representation
Raises:
ValueError: for bad DID or missing mandatory item.
Returns: DIDDoc from input json
|
Construct DIDDoc object from dict representation. | def deserialize(cls, did_doc: dict) -> "DIDDoc":
"""
Construct DIDDoc object from dict representation.
Args:
did_doc: DIDDoc dict representation
Raises:
ValueError: for bad DID or missing mandatory item.
Returns: DIDDoc from input json
"""
rv = None
if "id" in did_doc:
rv = DIDDoc(did_doc["id"])
else:
# heuristic: get DID to serve as DID document identifier from
# the first OK-looking public key
for section in ("publicKey", "authentication"):
if rv is None and section in did_doc:
for key_spec in did_doc[section]:
try:
pubkey_did = canon_did(resource(key_spec.get("id", "")))
if ok_did(pubkey_did):
rv = DIDDoc(pubkey_did)
break
except ValueError: # no identifier here, move on to next
break
if rv is None:
LOGGER.debug("no identifier in DID document")
raise ValueError("No identifier in DID document")
for pubkey in did_doc.get(
"publicKey", {}
): # include all public keys, authentication pubkeys by reference
pubkey_type = PublicKeyType.get(pubkey["type"])
authn = any(
canon_ref(rv.did, ak.get("publicKey", ""))
== canon_ref(rv.did, pubkey["id"])
for ak in did_doc.get("authentication", {})
if isinstance(ak.get("publicKey", None), str)
)
key = PublicKey( # initialization canonicalizes id
rv.did,
pubkey["id"],
pubkey[pubkey_type.specifier],
pubkey_type,
canon_did(pubkey["controller"]),
authn,
)
rv.pubkey[key.id] = key
for akey in did_doc.get(
"authentication", {}
): # include embedded authentication keys
if "publicKey" not in akey: # not yet got it with public keys
pubkey_type = PublicKeyType.get(akey["type"])
key = PublicKey( # initialization canonicalized id
rv.did,
akey["id"],
akey[pubkey_type.specifier],
pubkey_type,
canon_did(akey["controller"]),
True,
)
rv.pubkey[key.id] = key
for service in did_doc.get("service", {}):
endpoint = service["serviceEndpoint"]
svc = Service( # initialization canonicalizes id
rv.did,
service.get(
"id",
canon_ref(
rv.did, "assigned-service-{}".format(len(rv.service)), ";"
),
),
service["type"],
rv.add_service_pubkeys(service, "recipientKeys"),
rv.add_service_pubkeys(service, ["mediatorKeys", "routingKeys"]),
canon_ref(rv.did, endpoint, ";") if ";" in endpoint else endpoint,
service.get("priority", None),
)
rv.service[svc.id] = svc
return rv | [
"def",
"deserialize",
"(",
"cls",
",",
"did_doc",
":",
"dict",
")",
"->",
"\"DIDDoc\"",
":",
"rv",
"=",
"None",
"if",
"\"id\"",
"in",
"did_doc",
":",
"rv",
"=",
"DIDDoc",
"(",
"did_doc",
"[",
"\"id\"",
"]",
")",
"else",
":",
"# heuristic: get DID to serve as DID document identifier from",
"# the first OK-looking public key",
"for",
"section",
"in",
"(",
"\"publicKey\"",
",",
"\"authentication\"",
")",
":",
"if",
"rv",
"is",
"None",
"and",
"section",
"in",
"did_doc",
":",
"for",
"key_spec",
"in",
"did_doc",
"[",
"section",
"]",
":",
"try",
":",
"pubkey_did",
"=",
"canon_did",
"(",
"resource",
"(",
"key_spec",
".",
"get",
"(",
"\"id\"",
",",
"\"\"",
")",
")",
")",
"if",
"ok_did",
"(",
"pubkey_did",
")",
":",
"rv",
"=",
"DIDDoc",
"(",
"pubkey_did",
")",
"break",
"except",
"ValueError",
":",
"# no identifier here, move on to next",
"break",
"if",
"rv",
"is",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"\"no identifier in DID document\"",
")",
"raise",
"ValueError",
"(",
"\"No identifier in DID document\"",
")",
"for",
"pubkey",
"in",
"did_doc",
".",
"get",
"(",
"\"publicKey\"",
",",
"{",
"}",
")",
":",
"# include all public keys, authentication pubkeys by reference",
"pubkey_type",
"=",
"PublicKeyType",
".",
"get",
"(",
"pubkey",
"[",
"\"type\"",
"]",
")",
"authn",
"=",
"any",
"(",
"canon_ref",
"(",
"rv",
".",
"did",
",",
"ak",
".",
"get",
"(",
"\"publicKey\"",
",",
"\"\"",
")",
")",
"==",
"canon_ref",
"(",
"rv",
".",
"did",
",",
"pubkey",
"[",
"\"id\"",
"]",
")",
"for",
"ak",
"in",
"did_doc",
".",
"get",
"(",
"\"authentication\"",
",",
"{",
"}",
")",
"if",
"isinstance",
"(",
"ak",
".",
"get",
"(",
"\"publicKey\"",
",",
"None",
")",
",",
"str",
")",
")",
"key",
"=",
"PublicKey",
"(",
"# initialization canonicalizes id",
"rv",
".",
"did",
",",
"pubkey",
"[",
"\"id\"",
"]",
",",
"pubkey",
"[",
"pubkey_type",
".",
"specifier",
"]",
",",
"pubkey_type",
",",
"canon_did",
"(",
"pubkey",
"[",
"\"controller\"",
"]",
")",
",",
"authn",
",",
")",
"rv",
".",
"pubkey",
"[",
"key",
".",
"id",
"]",
"=",
"key",
"for",
"akey",
"in",
"did_doc",
".",
"get",
"(",
"\"authentication\"",
",",
"{",
"}",
")",
":",
"# include embedded authentication keys",
"if",
"\"publicKey\"",
"not",
"in",
"akey",
":",
"# not yet got it with public keys",
"pubkey_type",
"=",
"PublicKeyType",
".",
"get",
"(",
"akey",
"[",
"\"type\"",
"]",
")",
"key",
"=",
"PublicKey",
"(",
"# initialization canonicalized id",
"rv",
".",
"did",
",",
"akey",
"[",
"\"id\"",
"]",
",",
"akey",
"[",
"pubkey_type",
".",
"specifier",
"]",
",",
"pubkey_type",
",",
"canon_did",
"(",
"akey",
"[",
"\"controller\"",
"]",
")",
",",
"True",
",",
")",
"rv",
".",
"pubkey",
"[",
"key",
".",
"id",
"]",
"=",
"key",
"for",
"service",
"in",
"did_doc",
".",
"get",
"(",
"\"service\"",
",",
"{",
"}",
")",
":",
"endpoint",
"=",
"service",
"[",
"\"serviceEndpoint\"",
"]",
"svc",
"=",
"Service",
"(",
"# initialization canonicalizes id",
"rv",
".",
"did",
",",
"service",
".",
"get",
"(",
"\"id\"",
",",
"canon_ref",
"(",
"rv",
".",
"did",
",",
"\"assigned-service-{}\"",
".",
"format",
"(",
"len",
"(",
"rv",
".",
"service",
")",
")",
",",
"\";\"",
")",
",",
")",
",",
"service",
"[",
"\"type\"",
"]",
",",
"rv",
".",
"add_service_pubkeys",
"(",
"service",
",",
"\"recipientKeys\"",
")",
",",
"rv",
".",
"add_service_pubkeys",
"(",
"service",
",",
"[",
"\"mediatorKeys\"",
",",
"\"routingKeys\"",
"]",
")",
",",
"canon_ref",
"(",
"rv",
".",
"did",
",",
"endpoint",
",",
"\";\"",
")",
"if",
"\";\"",
"in",
"endpoint",
"else",
"endpoint",
",",
"service",
".",
"get",
"(",
"\"priority\"",
",",
"None",
")",
",",
")",
"rv",
".",
"service",
"[",
"svc",
".",
"id",
"]",
"=",
"svc",
"return",
"rv"
] | [
217,
4
] | [
304,
17
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.from_json | (cls, did_doc_json: str) |
Construct DIDDoc object from json representation.
Args:
did_doc_json: DIDDoc json representation
Returns: DIDDoc from input json
|
Construct DIDDoc object from json representation. | def from_json(cls, did_doc_json: str) -> "DIDDoc":
"""
Construct DIDDoc object from json representation.
Args:
did_doc_json: DIDDoc json representation
Returns: DIDDoc from input json
"""
return cls.deserialize(json.loads(did_doc_json)) | [
"def",
"from_json",
"(",
"cls",
",",
"did_doc_json",
":",
"str",
")",
"->",
"\"DIDDoc\"",
":",
"return",
"cls",
".",
"deserialize",
"(",
"json",
".",
"loads",
"(",
"did_doc_json",
")",
")"
] | [
307,
4
] | [
318,
56
] | python | en | ['en', 'error', 'th'] | False |
DIDDoc.__str__ | (self) | Return string representation for abbreviated display. | Return string representation for abbreviated display. | def __str__(self) -> str:
"""Return string representation for abbreviated display."""
return f"DIDDoc({self.did})" | [
"def",
"__str__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"DIDDoc({self.did})\""
] | [
320,
4
] | [
323,
36
] | python | en | ['en', 'en', 'en'] | True |
DIDDoc.__repr__ | (self) | Format DIDDoc for logging. | Format DIDDoc for logging. | def __repr__(self) -> str:
"""Format DIDDoc for logging."""
return f"<DIDDoc did={self.did}>" | [
"def",
"__repr__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"<DIDDoc did={self.did}>\""
] | [
325,
4
] | [
328,
41
] | python | en | ['en', 'da', 'en'] | True |
color_parser | (colors, function) |
Takes color(s) and a function and applies the function on the color(s)
In particular, this function identifies whether the given color object
is an iterable or not and applies the given color-parsing function to
the color or iterable of colors. If given an iterable, it will only be
able to work with it if all items in the iterable are of the same type
- rgb string, hex string or tuple
|
Takes color(s) and a function and applies the function on the color(s) | def color_parser(colors, function):
"""
Takes color(s) and a function and applies the function on the color(s)
In particular, this function identifies whether the given color object
is an iterable or not and applies the given color-parsing function to
the color or iterable of colors. If given an iterable, it will only be
able to work with it if all items in the iterable are of the same type
- rgb string, hex string or tuple
"""
if isinstance(colors, str):
return function(colors)
if isinstance(colors, tuple) and isinstance(colors[0], Number):
return function(colors)
if hasattr(colors, "__iter__"):
if isinstance(colors, tuple):
new_color_tuple = tuple(function(item) for item in colors)
return new_color_tuple
else:
new_color_list = [function(item) for item in colors]
return new_color_list | [
"def",
"color_parser",
"(",
"colors",
",",
"function",
")",
":",
"if",
"isinstance",
"(",
"colors",
",",
"str",
")",
":",
"return",
"function",
"(",
"colors",
")",
"if",
"isinstance",
"(",
"colors",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"colors",
"[",
"0",
"]",
",",
"Number",
")",
":",
"return",
"function",
"(",
"colors",
")",
"if",
"hasattr",
"(",
"colors",
",",
"\"__iter__\"",
")",
":",
"if",
"isinstance",
"(",
"colors",
",",
"tuple",
")",
":",
"new_color_tuple",
"=",
"tuple",
"(",
"function",
"(",
"item",
")",
"for",
"item",
"in",
"colors",
")",
"return",
"new_color_tuple",
"else",
":",
"new_color_list",
"=",
"[",
"function",
"(",
"item",
")",
"for",
"item",
"in",
"colors",
"]",
"return",
"new_color_list"
] | [
284,
0
] | [
307,
33
] | python | en | ['en', 'error', 'th'] | False |
validate_colors | (colors, colortype="tuple") |
Validates color(s) and returns a list of color(s) of a specified type
|
Validates color(s) and returns a list of color(s) of a specified type
| def validate_colors(colors, colortype="tuple"):
"""
Validates color(s) and returns a list of color(s) of a specified type
"""
from numbers import Number
if colors is None:
colors = DEFAULT_PLOTLY_COLORS
if isinstance(colors, str):
if colors in PLOTLY_SCALES:
colors_list = colorscale_to_colors(PLOTLY_SCALES[colors])
# TODO: fix _gantt.py/_scatter.py so that they can accept the
# actual colorscale and not just a list of the first and last
# color in the plotly colorscale. In resolving this issue we
# will be removing the immediate line below
colors = [colors_list[0]] + [colors_list[-1]]
elif "rgb" in colors or "#" in colors:
colors = [colors]
else:
raise exceptions.PlotlyError(
"If your colors variable is a string, it must be a "
"Plotly scale, an rgb color or a hex color."
)
elif isinstance(colors, tuple):
if isinstance(colors[0], Number):
colors = [colors]
else:
colors = list(colors)
# convert color elements in list to tuple color
for j, each_color in enumerate(colors):
if "rgb" in each_color:
each_color = color_parser(each_color, unlabel_rgb)
for value in each_color:
if value > 255.0:
raise exceptions.PlotlyError(
"Whoops! The elements in your rgb colors "
"tuples cannot exceed 255.0."
)
each_color = color_parser(each_color, unconvert_from_RGB_255)
colors[j] = each_color
if "#" in each_color:
each_color = color_parser(each_color, hex_to_rgb)
each_color = color_parser(each_color, unconvert_from_RGB_255)
colors[j] = each_color
if isinstance(each_color, tuple):
for value in each_color:
if value > 1.0:
raise exceptions.PlotlyError(
"Whoops! The elements in your colors tuples "
"cannot exceed 1.0."
)
colors[j] = each_color
if colortype == "rgb" and not isinstance(colors, six.string_types):
for j, each_color in enumerate(colors):
rgb_color = color_parser(each_color, convert_to_RGB_255)
colors[j] = color_parser(rgb_color, label_rgb)
return colors | [
"def",
"validate_colors",
"(",
"colors",
",",
"colortype",
"=",
"\"tuple\"",
")",
":",
"from",
"numbers",
"import",
"Number",
"if",
"colors",
"is",
"None",
":",
"colors",
"=",
"DEFAULT_PLOTLY_COLORS",
"if",
"isinstance",
"(",
"colors",
",",
"str",
")",
":",
"if",
"colors",
"in",
"PLOTLY_SCALES",
":",
"colors_list",
"=",
"colorscale_to_colors",
"(",
"PLOTLY_SCALES",
"[",
"colors",
"]",
")",
"# TODO: fix _gantt.py/_scatter.py so that they can accept the",
"# actual colorscale and not just a list of the first and last",
"# color in the plotly colorscale. In resolving this issue we",
"# will be removing the immediate line below",
"colors",
"=",
"[",
"colors_list",
"[",
"0",
"]",
"]",
"+",
"[",
"colors_list",
"[",
"-",
"1",
"]",
"]",
"elif",
"\"rgb\"",
"in",
"colors",
"or",
"\"#\"",
"in",
"colors",
":",
"colors",
"=",
"[",
"colors",
"]",
"else",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"If your colors variable is a string, it must be a \"",
"\"Plotly scale, an rgb color or a hex color.\"",
")",
"elif",
"isinstance",
"(",
"colors",
",",
"tuple",
")",
":",
"if",
"isinstance",
"(",
"colors",
"[",
"0",
"]",
",",
"Number",
")",
":",
"colors",
"=",
"[",
"colors",
"]",
"else",
":",
"colors",
"=",
"list",
"(",
"colors",
")",
"# convert color elements in list to tuple color",
"for",
"j",
",",
"each_color",
"in",
"enumerate",
"(",
"colors",
")",
":",
"if",
"\"rgb\"",
"in",
"each_color",
":",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"unlabel_rgb",
")",
"for",
"value",
"in",
"each_color",
":",
"if",
"value",
">",
"255.0",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Whoops! The elements in your rgb colors \"",
"\"tuples cannot exceed 255.0.\"",
")",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"unconvert_from_RGB_255",
")",
"colors",
"[",
"j",
"]",
"=",
"each_color",
"if",
"\"#\"",
"in",
"each_color",
":",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"hex_to_rgb",
")",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"unconvert_from_RGB_255",
")",
"colors",
"[",
"j",
"]",
"=",
"each_color",
"if",
"isinstance",
"(",
"each_color",
",",
"tuple",
")",
":",
"for",
"value",
"in",
"each_color",
":",
"if",
"value",
">",
"1.0",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Whoops! The elements in your colors tuples \"",
"\"cannot exceed 1.0.\"",
")",
"colors",
"[",
"j",
"]",
"=",
"each_color",
"if",
"colortype",
"==",
"\"rgb\"",
"and",
"not",
"isinstance",
"(",
"colors",
",",
"six",
".",
"string_types",
")",
":",
"for",
"j",
",",
"each_color",
"in",
"enumerate",
"(",
"colors",
")",
":",
"rgb_color",
"=",
"color_parser",
"(",
"each_color",
",",
"convert_to_RGB_255",
")",
"colors",
"[",
"j",
"]",
"=",
"color_parser",
"(",
"rgb_color",
",",
"label_rgb",
")",
"return",
"colors"
] | [
310,
0
] | [
374,
17
] | python | en | ['en', 'error', 'th'] | False |
validate_colors_dict | (colors, colortype="tuple") |
Validates dictioanry of color(s)
|
Validates dictioanry of color(s)
| def validate_colors_dict(colors, colortype="tuple"):
"""
Validates dictioanry of color(s)
"""
# validate each color element in the dictionary
for key in colors:
if "rgb" in colors[key]:
colors[key] = color_parser(colors[key], unlabel_rgb)
for value in colors[key]:
if value > 255.0:
raise exceptions.PlotlyError(
"Whoops! The elements in your rgb colors "
"tuples cannot exceed 255.0."
)
colors[key] = color_parser(colors[key], unconvert_from_RGB_255)
if "#" in colors[key]:
colors[key] = color_parser(colors[key], hex_to_rgb)
colors[key] = color_parser(colors[key], unconvert_from_RGB_255)
if isinstance(colors[key], tuple):
for value in colors[key]:
if value > 1.0:
raise exceptions.PlotlyError(
"Whoops! The elements in your colors tuples "
"cannot exceed 1.0."
)
if colortype == "rgb":
for key in colors:
colors[key] = color_parser(colors[key], convert_to_RGB_255)
colors[key] = color_parser(colors[key], label_rgb)
return colors | [
"def",
"validate_colors_dict",
"(",
"colors",
",",
"colortype",
"=",
"\"tuple\"",
")",
":",
"# validate each color element in the dictionary",
"for",
"key",
"in",
"colors",
":",
"if",
"\"rgb\"",
"in",
"colors",
"[",
"key",
"]",
":",
"colors",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors",
"[",
"key",
"]",
",",
"unlabel_rgb",
")",
"for",
"value",
"in",
"colors",
"[",
"key",
"]",
":",
"if",
"value",
">",
"255.0",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Whoops! The elements in your rgb colors \"",
"\"tuples cannot exceed 255.0.\"",
")",
"colors",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors",
"[",
"key",
"]",
",",
"unconvert_from_RGB_255",
")",
"if",
"\"#\"",
"in",
"colors",
"[",
"key",
"]",
":",
"colors",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors",
"[",
"key",
"]",
",",
"hex_to_rgb",
")",
"colors",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors",
"[",
"key",
"]",
",",
"unconvert_from_RGB_255",
")",
"if",
"isinstance",
"(",
"colors",
"[",
"key",
"]",
",",
"tuple",
")",
":",
"for",
"value",
"in",
"colors",
"[",
"key",
"]",
":",
"if",
"value",
">",
"1.0",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Whoops! The elements in your colors tuples \"",
"\"cannot exceed 1.0.\"",
")",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"for",
"key",
"in",
"colors",
":",
"colors",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors",
"[",
"key",
"]",
",",
"convert_to_RGB_255",
")",
"colors",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors",
"[",
"key",
"]",
",",
"label_rgb",
")",
"return",
"colors"
] | [
377,
0
] | [
410,
17
] | python | en | ['en', 'error', 'th'] | False |
convert_colors_to_same_type | (
colors,
colortype="rgb",
scale=None,
return_default_colors=False,
num_of_defualt_colors=2,
) |
Converts color(s) to the specified color type
Takes a single color or an iterable of colors, as well as a list of scale
values, and outputs a 2-pair of the list of color(s) converted all to an
rgb or tuple color type, aswell as the scale as the second element. If
colors is a Plotly Scale name, then 'scale' will be forced to the scale
from the respective colorscale and the colors in that colorscale will also
be coverted to the selected colortype. If colors is None, then there is an
option to return portion of the DEFAULT_PLOTLY_COLORS
:param (str|tuple|list) colors: either a plotly scale name, an rgb or hex
color, a color tuple or a list/tuple of colors
:param (list) scale: see docs for validate_scale_values()
:rtype (tuple) (colors_list, scale) if scale is None in the function call,
then scale will remain None in the returned tuple
|
Converts color(s) to the specified color type | def convert_colors_to_same_type(
colors,
colortype="rgb",
scale=None,
return_default_colors=False,
num_of_defualt_colors=2,
):
"""
Converts color(s) to the specified color type
Takes a single color or an iterable of colors, as well as a list of scale
values, and outputs a 2-pair of the list of color(s) converted all to an
rgb or tuple color type, aswell as the scale as the second element. If
colors is a Plotly Scale name, then 'scale' will be forced to the scale
from the respective colorscale and the colors in that colorscale will also
be coverted to the selected colortype. If colors is None, then there is an
option to return portion of the DEFAULT_PLOTLY_COLORS
:param (str|tuple|list) colors: either a plotly scale name, an rgb or hex
color, a color tuple or a list/tuple of colors
:param (list) scale: see docs for validate_scale_values()
:rtype (tuple) (colors_list, scale) if scale is None in the function call,
then scale will remain None in the returned tuple
"""
colors_list = []
if colors is None and return_default_colors is True:
colors_list = DEFAULT_PLOTLY_COLORS[0:num_of_defualt_colors]
if isinstance(colors, str):
if colors in PLOTLY_SCALES:
colors_list = colorscale_to_colors(PLOTLY_SCALES[colors])
if scale is None:
scale = colorscale_to_scale(PLOTLY_SCALES[colors])
elif "rgb" in colors or "#" in colors:
colors_list = [colors]
elif isinstance(colors, tuple):
if isinstance(colors[0], Number):
colors_list = [colors]
else:
colors_list = list(colors)
elif isinstance(colors, list):
colors_list = colors
# validate scale
if scale is not None:
validate_scale_values(scale)
if len(colors_list) != len(scale):
raise exceptions.PlotlyError(
"Make sure that the length of your scale matches the length "
"of your list of colors which is {}.".format(len(colors_list))
)
# convert all colors to rgb
for j, each_color in enumerate(colors_list):
if "#" in each_color:
each_color = color_parser(each_color, hex_to_rgb)
each_color = color_parser(each_color, label_rgb)
colors_list[j] = each_color
elif isinstance(each_color, tuple):
each_color = color_parser(each_color, convert_to_RGB_255)
each_color = color_parser(each_color, label_rgb)
colors_list[j] = each_color
if colortype == "rgb":
return (colors_list, scale)
elif colortype == "tuple":
for j, each_color in enumerate(colors_list):
each_color = color_parser(each_color, unlabel_rgb)
each_color = color_parser(each_color, unconvert_from_RGB_255)
colors_list[j] = each_color
return (colors_list, scale)
else:
raise exceptions.PlotlyError(
"You must select either rgb or tuple " "for your colortype variable."
) | [
"def",
"convert_colors_to_same_type",
"(",
"colors",
",",
"colortype",
"=",
"\"rgb\"",
",",
"scale",
"=",
"None",
",",
"return_default_colors",
"=",
"False",
",",
"num_of_defualt_colors",
"=",
"2",
",",
")",
":",
"colors_list",
"=",
"[",
"]",
"if",
"colors",
"is",
"None",
"and",
"return_default_colors",
"is",
"True",
":",
"colors_list",
"=",
"DEFAULT_PLOTLY_COLORS",
"[",
"0",
":",
"num_of_defualt_colors",
"]",
"if",
"isinstance",
"(",
"colors",
",",
"str",
")",
":",
"if",
"colors",
"in",
"PLOTLY_SCALES",
":",
"colors_list",
"=",
"colorscale_to_colors",
"(",
"PLOTLY_SCALES",
"[",
"colors",
"]",
")",
"if",
"scale",
"is",
"None",
":",
"scale",
"=",
"colorscale_to_scale",
"(",
"PLOTLY_SCALES",
"[",
"colors",
"]",
")",
"elif",
"\"rgb\"",
"in",
"colors",
"or",
"\"#\"",
"in",
"colors",
":",
"colors_list",
"=",
"[",
"colors",
"]",
"elif",
"isinstance",
"(",
"colors",
",",
"tuple",
")",
":",
"if",
"isinstance",
"(",
"colors",
"[",
"0",
"]",
",",
"Number",
")",
":",
"colors_list",
"=",
"[",
"colors",
"]",
"else",
":",
"colors_list",
"=",
"list",
"(",
"colors",
")",
"elif",
"isinstance",
"(",
"colors",
",",
"list",
")",
":",
"colors_list",
"=",
"colors",
"# validate scale",
"if",
"scale",
"is",
"not",
"None",
":",
"validate_scale_values",
"(",
"scale",
")",
"if",
"len",
"(",
"colors_list",
")",
"!=",
"len",
"(",
"scale",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Make sure that the length of your scale matches the length \"",
"\"of your list of colors which is {}.\"",
".",
"format",
"(",
"len",
"(",
"colors_list",
")",
")",
")",
"# convert all colors to rgb",
"for",
"j",
",",
"each_color",
"in",
"enumerate",
"(",
"colors_list",
")",
":",
"if",
"\"#\"",
"in",
"each_color",
":",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"hex_to_rgb",
")",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"label_rgb",
")",
"colors_list",
"[",
"j",
"]",
"=",
"each_color",
"elif",
"isinstance",
"(",
"each_color",
",",
"tuple",
")",
":",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"convert_to_RGB_255",
")",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"label_rgb",
")",
"colors_list",
"[",
"j",
"]",
"=",
"each_color",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"return",
"(",
"colors_list",
",",
"scale",
")",
"elif",
"colortype",
"==",
"\"tuple\"",
":",
"for",
"j",
",",
"each_color",
"in",
"enumerate",
"(",
"colors_list",
")",
":",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"unlabel_rgb",
")",
"each_color",
"=",
"color_parser",
"(",
"each_color",
",",
"unconvert_from_RGB_255",
")",
"colors_list",
"[",
"j",
"]",
"=",
"each_color",
"return",
"(",
"colors_list",
",",
"scale",
")",
"else",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"You must select either rgb or tuple \"",
"\"for your colortype variable.\"",
")"
] | [
413,
0
] | [
494,
9
] | python | en | ['en', 'error', 'th'] | False |
convert_dict_colors_to_same_type | (colors_dict, colortype="rgb") |
Converts a colors in a dictioanry of colors to the specified color type
:param (dict) colors_dict: a dictioanry whose values are single colors
|
Converts a colors in a dictioanry of colors to the specified color type | def convert_dict_colors_to_same_type(colors_dict, colortype="rgb"):
"""
Converts a colors in a dictioanry of colors to the specified color type
:param (dict) colors_dict: a dictioanry whose values are single colors
"""
for key in colors_dict:
if "#" in colors_dict[key]:
colors_dict[key] = color_parser(colors_dict[key], hex_to_rgb)
colors_dict[key] = color_parser(colors_dict[key], label_rgb)
elif isinstance(colors_dict[key], tuple):
colors_dict[key] = color_parser(colors_dict[key], convert_to_RGB_255)
colors_dict[key] = color_parser(colors_dict[key], label_rgb)
if colortype == "rgb":
return colors_dict
elif colortype == "tuple":
for key in colors_dict:
colors_dict[key] = color_parser(colors_dict[key], unlabel_rgb)
colors_dict[key] = color_parser(colors_dict[key], unconvert_from_RGB_255)
return colors_dict
else:
raise exceptions.PlotlyError(
"You must select either rgb or tuple " "for your colortype variable."
) | [
"def",
"convert_dict_colors_to_same_type",
"(",
"colors_dict",
",",
"colortype",
"=",
"\"rgb\"",
")",
":",
"for",
"key",
"in",
"colors_dict",
":",
"if",
"\"#\"",
"in",
"colors_dict",
"[",
"key",
"]",
":",
"colors_dict",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"hex_to_rgb",
")",
"colors_dict",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"label_rgb",
")",
"elif",
"isinstance",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"tuple",
")",
":",
"colors_dict",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"convert_to_RGB_255",
")",
"colors_dict",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"label_rgb",
")",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"return",
"colors_dict",
"elif",
"colortype",
"==",
"\"tuple\"",
":",
"for",
"key",
"in",
"colors_dict",
":",
"colors_dict",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"unlabel_rgb",
")",
"colors_dict",
"[",
"key",
"]",
"=",
"color_parser",
"(",
"colors_dict",
"[",
"key",
"]",
",",
"unconvert_from_RGB_255",
")",
"return",
"colors_dict",
"else",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"You must select either rgb or tuple \"",
"\"for your colortype variable.\"",
")"
] | [
497,
0
] | [
522,
9
] | python | en | ['en', 'error', 'th'] | False |
validate_scale_values | (scale) |
Validates scale values from a colorscale
:param (list) scale: a strictly increasing list of floats that begins
with 0 and ends with 1. Its usage derives from a colorscale which is
a list of two-lists (a list with two elements) of the form
[value, color] which are used to determine how interpolation weighting
works between the colors in the colorscale. Therefore scale is just
the extraction of these values from the two-lists in order
|
Validates scale values from a colorscale | def validate_scale_values(scale):
"""
Validates scale values from a colorscale
:param (list) scale: a strictly increasing list of floats that begins
with 0 and ends with 1. Its usage derives from a colorscale which is
a list of two-lists (a list with two elements) of the form
[value, color] which are used to determine how interpolation weighting
works between the colors in the colorscale. Therefore scale is just
the extraction of these values from the two-lists in order
"""
if len(scale) < 2:
raise exceptions.PlotlyError(
"You must input a list of scale values " "that has at least two values."
)
if (scale[0] != 0) or (scale[-1] != 1):
raise exceptions.PlotlyError(
"The first and last number in your scale must be 0.0 and 1.0 "
"respectively."
)
if not all(x < y for x, y in zip(scale, scale[1:])):
raise exceptions.PlotlyError(
"'scale' must be a list that contains a strictly increasing "
"sequence of numbers."
) | [
"def",
"validate_scale_values",
"(",
"scale",
")",
":",
"if",
"len",
"(",
"scale",
")",
"<",
"2",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"You must input a list of scale values \"",
"\"that has at least two values.\"",
")",
"if",
"(",
"scale",
"[",
"0",
"]",
"!=",
"0",
")",
"or",
"(",
"scale",
"[",
"-",
"1",
"]",
"!=",
"1",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"The first and last number in your scale must be 0.0 and 1.0 \"",
"\"respectively.\"",
")",
"if",
"not",
"all",
"(",
"x",
"<",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"scale",
",",
"scale",
"[",
"1",
":",
"]",
")",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"'scale' must be a list that contains a strictly increasing \"",
"\"sequence of numbers.\"",
")"
] | [
525,
0
] | [
551,
9
] | python | en | ['en', 'error', 'th'] | False |
validate_colorscale | (colorscale) | Validate the structure, scale values and colors of colorscale. | Validate the structure, scale values and colors of colorscale. | def validate_colorscale(colorscale):
"""Validate the structure, scale values and colors of colorscale."""
if not isinstance(colorscale, list):
# TODO Write tests for these exceptions
raise exceptions.PlotlyError("A valid colorscale must be a list.")
if not all(isinstance(innerlist, list) for innerlist in colorscale):
raise exceptions.PlotlyError("A valid colorscale must be a list of lists.")
colorscale_colors = colorscale_to_colors(colorscale)
scale_values = colorscale_to_scale(colorscale)
validate_scale_values(scale_values)
validate_colors(colorscale_colors) | [
"def",
"validate_colorscale",
"(",
"colorscale",
")",
":",
"if",
"not",
"isinstance",
"(",
"colorscale",
",",
"list",
")",
":",
"# TODO Write tests for these exceptions",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"A valid colorscale must be a list.\"",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"innerlist",
",",
"list",
")",
"for",
"innerlist",
"in",
"colorscale",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"A valid colorscale must be a list of lists.\"",
")",
"colorscale_colors",
"=",
"colorscale_to_colors",
"(",
"colorscale",
")",
"scale_values",
"=",
"colorscale_to_scale",
"(",
"colorscale",
")",
"validate_scale_values",
"(",
"scale_values",
")",
"validate_colors",
"(",
"colorscale_colors",
")"
] | [
554,
0
] | [
565,
38
] | python | en | ['en', 'en', 'en'] | True |
make_colorscale | (colors, scale=None) |
Makes a colorscale from a list of colors and a scale
Takes a list of colors and scales and constructs a colorscale based
on the colors in sequential order. If 'scale' is left empty, a linear-
interpolated colorscale will be generated. If 'scale' is a specificed
list, it must be the same legnth as colors and must contain all floats
For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
:param (list) colors: a list of single colors
|
Makes a colorscale from a list of colors and a scale | def make_colorscale(colors, scale=None):
"""
Makes a colorscale from a list of colors and a scale
Takes a list of colors and scales and constructs a colorscale based
on the colors in sequential order. If 'scale' is left empty, a linear-
interpolated colorscale will be generated. If 'scale' is a specificed
list, it must be the same legnth as colors and must contain all floats
For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
:param (list) colors: a list of single colors
"""
colorscale = []
# validate minimum colors length of 2
if len(colors) < 2:
raise exceptions.PlotlyError(
"You must input a list of colors that " "has at least two colors."
)
if scale is None:
scale_incr = 1.0 / (len(colors) - 1)
return [[i * scale_incr, color] for i, color in enumerate(colors)]
else:
if len(colors) != len(scale):
raise exceptions.PlotlyError(
"The length of colors and scale " "must be the same."
)
validate_scale_values(scale)
colorscale = [list(tup) for tup in zip(scale, colors)]
return colorscale | [
"def",
"make_colorscale",
"(",
"colors",
",",
"scale",
"=",
"None",
")",
":",
"colorscale",
"=",
"[",
"]",
"# validate minimum colors length of 2",
"if",
"len",
"(",
"colors",
")",
"<",
"2",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"You must input a list of colors that \"",
"\"has at least two colors.\"",
")",
"if",
"scale",
"is",
"None",
":",
"scale_incr",
"=",
"1.0",
"/",
"(",
"len",
"(",
"colors",
")",
"-",
"1",
")",
"return",
"[",
"[",
"i",
"*",
"scale_incr",
",",
"color",
"]",
"for",
"i",
",",
"color",
"in",
"enumerate",
"(",
"colors",
")",
"]",
"else",
":",
"if",
"len",
"(",
"colors",
")",
"!=",
"len",
"(",
"scale",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"The length of colors and scale \"",
"\"must be the same.\"",
")",
"validate_scale_values",
"(",
"scale",
")",
"colorscale",
"=",
"[",
"list",
"(",
"tup",
")",
"for",
"tup",
"in",
"zip",
"(",
"scale",
",",
"colors",
")",
"]",
"return",
"colorscale"
] | [
568,
0
] | [
602,
25
] | python | en | ['en', 'error', 'th'] | False |
find_intermediate_color | (lowcolor, highcolor, intermed, colortype="tuple") |
Returns the color at a given distance between two colors
This function takes two color tuples, where each element is between 0
and 1, along with a value 0 < intermed < 1 and returns a color that is
intermed-percent from lowcolor to highcolor. If colortype is set to 'rgb',
the function will automatically convert the rgb type to a tuple, find the
intermediate color and return it as an rgb color.
|
Returns the color at a given distance between two colors | def find_intermediate_color(lowcolor, highcolor, intermed, colortype="tuple"):
"""
Returns the color at a given distance between two colors
This function takes two color tuples, where each element is between 0
and 1, along with a value 0 < intermed < 1 and returns a color that is
intermed-percent from lowcolor to highcolor. If colortype is set to 'rgb',
the function will automatically convert the rgb type to a tuple, find the
intermediate color and return it as an rgb color.
"""
if colortype == "rgb":
# convert to tuple color, eg. (1, 0.45, 0.7)
lowcolor = unlabel_rgb(lowcolor)
highcolor = unlabel_rgb(highcolor)
diff_0 = float(highcolor[0] - lowcolor[0])
diff_1 = float(highcolor[1] - lowcolor[1])
diff_2 = float(highcolor[2] - lowcolor[2])
inter_med_tuple = (
lowcolor[0] + intermed * diff_0,
lowcolor[1] + intermed * diff_1,
lowcolor[2] + intermed * diff_2,
)
if colortype == "rgb":
# back to an rgb string, e.g. rgb(30, 20, 10)
inter_med_rgb = label_rgb(inter_med_tuple)
return inter_med_rgb
return inter_med_tuple | [
"def",
"find_intermediate_color",
"(",
"lowcolor",
",",
"highcolor",
",",
"intermed",
",",
"colortype",
"=",
"\"tuple\"",
")",
":",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"# convert to tuple color, eg. (1, 0.45, 0.7)",
"lowcolor",
"=",
"unlabel_rgb",
"(",
"lowcolor",
")",
"highcolor",
"=",
"unlabel_rgb",
"(",
"highcolor",
")",
"diff_0",
"=",
"float",
"(",
"highcolor",
"[",
"0",
"]",
"-",
"lowcolor",
"[",
"0",
"]",
")",
"diff_1",
"=",
"float",
"(",
"highcolor",
"[",
"1",
"]",
"-",
"lowcolor",
"[",
"1",
"]",
")",
"diff_2",
"=",
"float",
"(",
"highcolor",
"[",
"2",
"]",
"-",
"lowcolor",
"[",
"2",
"]",
")",
"inter_med_tuple",
"=",
"(",
"lowcolor",
"[",
"0",
"]",
"+",
"intermed",
"*",
"diff_0",
",",
"lowcolor",
"[",
"1",
"]",
"+",
"intermed",
"*",
"diff_1",
",",
"lowcolor",
"[",
"2",
"]",
"+",
"intermed",
"*",
"diff_2",
",",
")",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"# back to an rgb string, e.g. rgb(30, 20, 10)",
"inter_med_rgb",
"=",
"label_rgb",
"(",
"inter_med_tuple",
")",
"return",
"inter_med_rgb",
"return",
"inter_med_tuple"
] | [
605,
0
] | [
635,
26
] | python | en | ['en', 'error', 'th'] | False |
unconvert_from_RGB_255 | (colors) |
Return a tuple where each element gets divided by 255
Takes a (list of) color tuple(s) where each element is between 0 and
255. Returns the same tuples where each tuple element is normalized to
a value between 0 and 1
|
Return a tuple where each element gets divided by 255 | def unconvert_from_RGB_255(colors):
"""
Return a tuple where each element gets divided by 255
Takes a (list of) color tuple(s) where each element is between 0 and
255. Returns the same tuples where each tuple element is normalized to
a value between 0 and 1
"""
return (colors[0] / (255.0), colors[1] / (255.0), colors[2] / (255.0)) | [
"def",
"unconvert_from_RGB_255",
"(",
"colors",
")",
":",
"return",
"(",
"colors",
"[",
"0",
"]",
"/",
"(",
"255.0",
")",
",",
"colors",
"[",
"1",
"]",
"/",
"(",
"255.0",
")",
",",
"colors",
"[",
"2",
"]",
"/",
"(",
"255.0",
")",
")"
] | [
638,
0
] | [
646,
74
] | python | en | ['en', 'error', 'th'] | False |
convert_to_RGB_255 | (colors) |
Multiplies each element of a triplet by 255
Each coordinate of the color tuple is rounded to the nearest float and
then is turned into an integer. If a number is of the form x.5, then
if x is odd, the number rounds up to (x+1). Otherwise, it rounds down
to just x. This is the way rounding works in Python 3 and in current
statistical analysis to avoid rounding bias
:param (list) rgb_components: grabs the three R, G and B values to be
returned as computed in the function
|
Multiplies each element of a triplet by 255 | def convert_to_RGB_255(colors):
"""
Multiplies each element of a triplet by 255
Each coordinate of the color tuple is rounded to the nearest float and
then is turned into an integer. If a number is of the form x.5, then
if x is odd, the number rounds up to (x+1). Otherwise, it rounds down
to just x. This is the way rounding works in Python 3 and in current
statistical analysis to avoid rounding bias
:param (list) rgb_components: grabs the three R, G and B values to be
returned as computed in the function
"""
rgb_components = []
for component in colors:
rounded_num = decimal.Decimal(str(component * 255.0)).quantize(
decimal.Decimal("1"), rounding=decimal.ROUND_HALF_EVEN
)
# convert rounded number to an integer from 'Decimal' form
rounded_num = int(rounded_num)
rgb_components.append(rounded_num)
return (rgb_components[0], rgb_components[1], rgb_components[2]) | [
"def",
"convert_to_RGB_255",
"(",
"colors",
")",
":",
"rgb_components",
"=",
"[",
"]",
"for",
"component",
"in",
"colors",
":",
"rounded_num",
"=",
"decimal",
".",
"Decimal",
"(",
"str",
"(",
"component",
"*",
"255.0",
")",
")",
".",
"quantize",
"(",
"decimal",
".",
"Decimal",
"(",
"\"1\"",
")",
",",
"rounding",
"=",
"decimal",
".",
"ROUND_HALF_EVEN",
")",
"# convert rounded number to an integer from 'Decimal' form",
"rounded_num",
"=",
"int",
"(",
"rounded_num",
")",
"rgb_components",
".",
"append",
"(",
"rounded_num",
")",
"return",
"(",
"rgb_components",
"[",
"0",
"]",
",",
"rgb_components",
"[",
"1",
"]",
",",
"rgb_components",
"[",
"2",
"]",
")"
] | [
649,
0
] | [
672,
68
] | python | en | ['en', 'error', 'th'] | False |
n_colors | (lowcolor, highcolor, n_colors, colortype="tuple") |
Splits a low and high color into a list of n_colors colors in it
Accepts two color tuples and returns a list of n_colors colors
which form the intermediate colors between lowcolor and highcolor
from linearly interpolating through RGB space. If colortype is 'rgb'
the function will return a list of colors in the same form.
|
Splits a low and high color into a list of n_colors colors in it | def n_colors(lowcolor, highcolor, n_colors, colortype="tuple"):
"""
Splits a low and high color into a list of n_colors colors in it
Accepts two color tuples and returns a list of n_colors colors
which form the intermediate colors between lowcolor and highcolor
from linearly interpolating through RGB space. If colortype is 'rgb'
the function will return a list of colors in the same form.
"""
if colortype == "rgb":
# convert to tuple
lowcolor = unlabel_rgb(lowcolor)
highcolor = unlabel_rgb(highcolor)
diff_0 = float(highcolor[0] - lowcolor[0])
incr_0 = diff_0 / (n_colors - 1)
diff_1 = float(highcolor[1] - lowcolor[1])
incr_1 = diff_1 / (n_colors - 1)
diff_2 = float(highcolor[2] - lowcolor[2])
incr_2 = diff_2 / (n_colors - 1)
list_of_colors = []
for index in range(n_colors):
new_tuple = (
lowcolor[0] + (index * incr_0),
lowcolor[1] + (index * incr_1),
lowcolor[2] + (index * incr_2),
)
list_of_colors.append(new_tuple)
if colortype == "rgb":
# back to an rgb string
list_of_colors = color_parser(list_of_colors, label_rgb)
return list_of_colors | [
"def",
"n_colors",
"(",
"lowcolor",
",",
"highcolor",
",",
"n_colors",
",",
"colortype",
"=",
"\"tuple\"",
")",
":",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"# convert to tuple",
"lowcolor",
"=",
"unlabel_rgb",
"(",
"lowcolor",
")",
"highcolor",
"=",
"unlabel_rgb",
"(",
"highcolor",
")",
"diff_0",
"=",
"float",
"(",
"highcolor",
"[",
"0",
"]",
"-",
"lowcolor",
"[",
"0",
"]",
")",
"incr_0",
"=",
"diff_0",
"/",
"(",
"n_colors",
"-",
"1",
")",
"diff_1",
"=",
"float",
"(",
"highcolor",
"[",
"1",
"]",
"-",
"lowcolor",
"[",
"1",
"]",
")",
"incr_1",
"=",
"diff_1",
"/",
"(",
"n_colors",
"-",
"1",
")",
"diff_2",
"=",
"float",
"(",
"highcolor",
"[",
"2",
"]",
"-",
"lowcolor",
"[",
"2",
"]",
")",
"incr_2",
"=",
"diff_2",
"/",
"(",
"n_colors",
"-",
"1",
")",
"list_of_colors",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"n_colors",
")",
":",
"new_tuple",
"=",
"(",
"lowcolor",
"[",
"0",
"]",
"+",
"(",
"index",
"*",
"incr_0",
")",
",",
"lowcolor",
"[",
"1",
"]",
"+",
"(",
"index",
"*",
"incr_1",
")",
",",
"lowcolor",
"[",
"2",
"]",
"+",
"(",
"index",
"*",
"incr_2",
")",
",",
")",
"list_of_colors",
".",
"append",
"(",
"new_tuple",
")",
"if",
"colortype",
"==",
"\"rgb\"",
":",
"# back to an rgb string",
"list_of_colors",
"=",
"color_parser",
"(",
"list_of_colors",
",",
"label_rgb",
")",
"return",
"list_of_colors"
] | [
675,
0
] | [
709,
25
] | python | en | ['en', 'error', 'th'] | False |
label_rgb | (colors) |
Takes tuple (a, b, c) and returns an rgb color 'rgb(a, b, c)'
|
Takes tuple (a, b, c) and returns an rgb color 'rgb(a, b, c)'
| def label_rgb(colors):
"""
Takes tuple (a, b, c) and returns an rgb color 'rgb(a, b, c)'
"""
return "rgb(%s, %s, %s)" % (colors[0], colors[1], colors[2]) | [
"def",
"label_rgb",
"(",
"colors",
")",
":",
"return",
"\"rgb(%s, %s, %s)\"",
"%",
"(",
"colors",
"[",
"0",
"]",
",",
"colors",
"[",
"1",
"]",
",",
"colors",
"[",
"2",
"]",
")"
] | [
712,
0
] | [
716,
64
] | python | en | ['en', 'error', 'th'] | False |
unlabel_rgb | (colors) |
Takes rgb color(s) 'rgb(a, b, c)' and returns tuple(s) (a, b, c)
This function takes either an 'rgb(a, b, c)' color or a list of
such colors and returns the color tuples in tuple(s) (a, b, c)
|
Takes rgb color(s) 'rgb(a, b, c)' and returns tuple(s) (a, b, c) | def unlabel_rgb(colors):
"""
Takes rgb color(s) 'rgb(a, b, c)' and returns tuple(s) (a, b, c)
This function takes either an 'rgb(a, b, c)' color or a list of
such colors and returns the color tuples in tuple(s) (a, b, c)
"""
str_vals = ""
for index in range(len(colors)):
try:
float(colors[index])
str_vals = str_vals + colors[index]
except ValueError:
if colors[index] == "," or colors[index] == ".":
str_vals = str_vals + colors[index]
str_vals = str_vals + ","
numbers = []
str_num = ""
for char in str_vals:
if char != ",":
str_num = str_num + char
else:
numbers.append(float(str_num))
str_num = ""
return (numbers[0], numbers[1], numbers[2]) | [
"def",
"unlabel_rgb",
"(",
"colors",
")",
":",
"str_vals",
"=",
"\"\"",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"colors",
")",
")",
":",
"try",
":",
"float",
"(",
"colors",
"[",
"index",
"]",
")",
"str_vals",
"=",
"str_vals",
"+",
"colors",
"[",
"index",
"]",
"except",
"ValueError",
":",
"if",
"colors",
"[",
"index",
"]",
"==",
"\",\"",
"or",
"colors",
"[",
"index",
"]",
"==",
"\".\"",
":",
"str_vals",
"=",
"str_vals",
"+",
"colors",
"[",
"index",
"]",
"str_vals",
"=",
"str_vals",
"+",
"\",\"",
"numbers",
"=",
"[",
"]",
"str_num",
"=",
"\"\"",
"for",
"char",
"in",
"str_vals",
":",
"if",
"char",
"!=",
"\",\"",
":",
"str_num",
"=",
"str_num",
"+",
"char",
"else",
":",
"numbers",
".",
"append",
"(",
"float",
"(",
"str_num",
")",
")",
"str_num",
"=",
"\"\"",
"return",
"(",
"numbers",
"[",
"0",
"]",
",",
"numbers",
"[",
"1",
"]",
",",
"numbers",
"[",
"2",
"]",
")"
] | [
719,
0
] | [
744,
47
] | python | en | ['en', 'error', 'th'] | False |
hex_to_rgb | (value) |
Calculates rgb values from a hex color code.
:param (string) value: Hex color string
:rtype (tuple) (r_value, g_value, b_value): tuple of rgb values
|
Calculates rgb values from a hex color code. | def hex_to_rgb(value):
"""
Calculates rgb values from a hex color code.
:param (string) value: Hex color string
:rtype (tuple) (r_value, g_value, b_value): tuple of rgb values
"""
value = value.lstrip("#")
hex_total_length = len(value)
rgb_section_length = hex_total_length // 3
return tuple(
int(value[i : i + rgb_section_length], 16)
for i in range(0, hex_total_length, rgb_section_length)
) | [
"def",
"hex_to_rgb",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"lstrip",
"(",
"\"#\"",
")",
"hex_total_length",
"=",
"len",
"(",
"value",
")",
"rgb_section_length",
"=",
"hex_total_length",
"//",
"3",
"return",
"tuple",
"(",
"int",
"(",
"value",
"[",
"i",
":",
"i",
"+",
"rgb_section_length",
"]",
",",
"16",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"hex_total_length",
",",
"rgb_section_length",
")",
")"
] | [
747,
0
] | [
761,
5
] | python | en | ['en', 'error', 'th'] | False |
colorscale_to_colors | (colorscale) |
Extracts the colors from colorscale as a list
|
Extracts the colors from colorscale as a list
| def colorscale_to_colors(colorscale):
"""
Extracts the colors from colorscale as a list
"""
color_list = []
for item in colorscale:
color_list.append(item[1])
return color_list | [
"def",
"colorscale_to_colors",
"(",
"colorscale",
")",
":",
"color_list",
"=",
"[",
"]",
"for",
"item",
"in",
"colorscale",
":",
"color_list",
".",
"append",
"(",
"item",
"[",
"1",
"]",
")",
"return",
"color_list"
] | [
764,
0
] | [
771,
21
] | python | en | ['en', 'error', 'th'] | False |
colorscale_to_scale | (colorscale) |
Extracts the interpolation scale values from colorscale as a list
|
Extracts the interpolation scale values from colorscale as a list
| def colorscale_to_scale(colorscale):
"""
Extracts the interpolation scale values from colorscale as a list
"""
scale_list = []
for item in colorscale:
scale_list.append(item[0])
return scale_list | [
"def",
"colorscale_to_scale",
"(",
"colorscale",
")",
":",
"scale_list",
"=",
"[",
"]",
"for",
"item",
"in",
"colorscale",
":",
"scale_list",
".",
"append",
"(",
"item",
"[",
"0",
"]",
")",
"return",
"scale_list"
] | [
774,
0
] | [
781,
21
] | python | en | ['en', 'error', 'th'] | False |
convert_colorscale_to_rgb | (colorscale) |
Converts the colors in a colorscale to rgb colors
A colorscale is an array of arrays, each with a numeric value as the
first item and a color as the second. This function specifically is
converting a colorscale with tuple colors (each coordinate between 0
and 1) into a colorscale with the colors transformed into rgb colors
|
Converts the colors in a colorscale to rgb colors | def convert_colorscale_to_rgb(colorscale):
"""
Converts the colors in a colorscale to rgb colors
A colorscale is an array of arrays, each with a numeric value as the
first item and a color as the second. This function specifically is
converting a colorscale with tuple colors (each coordinate between 0
and 1) into a colorscale with the colors transformed into rgb colors
"""
for color in colorscale:
color[1] = convert_to_RGB_255(color[1])
for color in colorscale:
color[1] = label_rgb(color[1])
return colorscale | [
"def",
"convert_colorscale_to_rgb",
"(",
"colorscale",
")",
":",
"for",
"color",
"in",
"colorscale",
":",
"color",
"[",
"1",
"]",
"=",
"convert_to_RGB_255",
"(",
"color",
"[",
"1",
"]",
")",
"for",
"color",
"in",
"colorscale",
":",
"color",
"[",
"1",
"]",
"=",
"label_rgb",
"(",
"color",
"[",
"1",
"]",
")",
"return",
"colorscale"
] | [
784,
0
] | [
798,
21
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.