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 |
---|---|---|---|---|---|---|---|---|---|---|---|
Marker.opacity | (self) |
Sets the marker opacity. The default value is `1` (fully
opaque). If the markers are not fully opaque and there are
hundreds of thousands of points, it may cause slower zooming
and panning. Opacity fades the color even if `blend` is left on
`false` even if there is no translucency effect in that case.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
|
Sets the marker opacity. The default value is `1` (fully
opaque). If the markers are not fully opaque and there are
hundreds of thousands of points, it may cause slower zooming
and panning. Opacity fades the color even if `blend` is left on
`false` even if there is no translucency effect in that case.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1] | def opacity(self):
"""
Sets the marker opacity. The default value is `1` (fully
opaque). If the markers are not fully opaque and there are
hundreds of thousands of points, it may cause slower zooming
and panning. Opacity fades the color even if `blend` is left on
`false` even if there is no translucency effect in that case.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["opacity"] | [
"def",
"opacity",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"opacity\"",
"]"
] | [
131,
4
] | [
146,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.sizemax | (self) |
Sets the maximum size (in px) of the rendered marker points.
Effective when the `pointcloud` shows only few points.
The 'sizemax' property is a number and may be specified as:
- An int or float in the interval [0.1, inf]
Returns
-------
int|float
|
Sets the maximum size (in px) of the rendered marker points.
Effective when the `pointcloud` shows only few points.
The 'sizemax' property is a number and may be specified as:
- An int or float in the interval [0.1, inf] | def sizemax(self):
"""
Sets the maximum size (in px) of the rendered marker points.
Effective when the `pointcloud` shows only few points.
The 'sizemax' property is a number and may be specified as:
- An int or float in the interval [0.1, inf]
Returns
-------
int|float
"""
return self["sizemax"] | [
"def",
"sizemax",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizemax\"",
"]"
] | [
155,
4
] | [
167,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.sizemin | (self) |
Sets the minimum size (in px) of the rendered marker points,
effective when the `pointcloud` shows a million or more points.
The 'sizemin' property is a number and may be specified as:
- An int or float in the interval [0.1, 2]
Returns
-------
int|float
|
Sets the minimum size (in px) of the rendered marker points,
effective when the `pointcloud` shows a million or more points.
The 'sizemin' property is a number and may be specified as:
- An int or float in the interval [0.1, 2] | def sizemin(self):
"""
Sets the minimum size (in px) of the rendered marker points,
effective when the `pointcloud` shows a million or more points.
The 'sizemin' property is a number and may be specified as:
- An int or float in the interval [0.1, 2]
Returns
-------
int|float
"""
return self["sizemin"] | [
"def",
"sizemin",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizemin\"",
"]"
] | [
176,
4
] | [
188,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.__init__ | (
self,
arg=None,
blend=None,
border=None,
color=None,
opacity=None,
sizemax=None,
sizemin=None,
**kwargs
) |
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.pointcloud.Marker`
blend
Determines if colors are blended together for a
translucency effect in case `opacity` is specified as a
value less then `1`. Setting `blend` to `true` reduces
zoom/pan speed if used with large numbers of points.
border
:class:`plotly.graph_objects.pointcloud.marker.Border`
instance or dict with compatible properties
color
Sets the marker fill color. It accepts a specific
color.If the color is not fully opaque and there are
hundreds of thousandsof points, it may cause slower
zooming and panning.
opacity
Sets the marker opacity. The default value is `1`
(fully opaque). If the markers are not fully opaque and
there are hundreds of thousands of points, it may cause
slower zooming and panning. Opacity fades the color
even if `blend` is left on `false` even if there is no
translucency effect in that case.
sizemax
Sets the maximum size (in px) of the rendered marker
points. Effective when the `pointcloud` shows only few
points.
sizemin
Sets the minimum size (in px) of the rendered marker
points, effective when the `pointcloud` shows a million
or more points.
Returns
-------
Marker
|
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.pointcloud.Marker`
blend
Determines if colors are blended together for a
translucency effect in case `opacity` is specified as a
value less then `1`. Setting `blend` to `true` reduces
zoom/pan speed if used with large numbers of points.
border
:class:`plotly.graph_objects.pointcloud.marker.Border`
instance or dict with compatible properties
color
Sets the marker fill color. It accepts a specific
color.If the color is not fully opaque and there are
hundreds of thousandsof points, it may cause slower
zooming and panning.
opacity
Sets the marker opacity. The default value is `1`
(fully opaque). If the markers are not fully opaque and
there are hundreds of thousands of points, it may cause
slower zooming and panning. Opacity fades the color
even if `blend` is left on `false` even if there is no
translucency effect in that case.
sizemax
Sets the maximum size (in px) of the rendered marker
points. Effective when the `pointcloud` shows only few
points.
sizemin
Sets the minimum size (in px) of the rendered marker
points, effective when the `pointcloud` shows a million
or more points. | def __init__(
self,
arg=None,
blend=None,
border=None,
color=None,
opacity=None,
sizemax=None,
sizemin=None,
**kwargs
):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.pointcloud.Marker`
blend
Determines if colors are blended together for a
translucency effect in case `opacity` is specified as a
value less then `1`. Setting `blend` to `true` reduces
zoom/pan speed if used with large numbers of points.
border
:class:`plotly.graph_objects.pointcloud.marker.Border`
instance or dict with compatible properties
color
Sets the marker fill color. It accepts a specific
color.If the color is not fully opaque and there are
hundreds of thousandsof points, it may cause slower
zooming and panning.
opacity
Sets the marker opacity. The default value is `1`
(fully opaque). If the markers are not fully opaque and
there are hundreds of thousands of points, it may cause
slower zooming and panning. Opacity fades the color
even if `blend` is left on `false` even if there is no
translucency effect in that case.
sizemax
Sets the maximum size (in px) of the rendered marker
points. Effective when the `pointcloud` shows only few
points.
sizemin
Sets the minimum size (in px) of the rendered marker
points, effective when the `pointcloud` shows a million
or more points.
Returns
-------
Marker
"""
super(Marker, self).__init__("marker")
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.pointcloud.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.pointcloud.Marker`"""
)
# 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("blend", None)
_v = blend if blend is not None else _v
if _v is not None:
self["blend"] = _v
_v = arg.pop("border", None)
_v = border if border is not None else _v
if _v is not None:
self["border"] = _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("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("sizemax", None)
_v = sizemax if sizemax is not None else _v
if _v is not None:
self["sizemax"] = _v
_v = arg.pop("sizemin", None)
_v = sizemin if sizemin is not None else _v
if _v is not None:
self["sizemin"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"blend",
"=",
"None",
",",
"border",
"=",
"None",
",",
"color",
"=",
"None",
",",
"opacity",
"=",
"None",
",",
"sizemax",
"=",
"None",
",",
"sizemin",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Marker",
",",
"self",
")",
".",
"__init__",
"(",
"\"marker\"",
")",
"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.pointcloud.Marker \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.pointcloud.Marker`\"\"\"",
")",
"# 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",
"(",
"\"blend\"",
",",
"None",
")",
"_v",
"=",
"blend",
"if",
"blend",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"blend\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"border\"",
",",
"None",
")",
"_v",
"=",
"border",
"if",
"border",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"border\"",
"]",
"=",
"_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",
"(",
"\"opacity\"",
",",
"None",
")",
"_v",
"=",
"opacity",
"if",
"opacity",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"opacity\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizemax\"",
",",
"None",
")",
"_v",
"=",
"sizemax",
"if",
"sizemax",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizemax\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizemin\"",
",",
"None",
")",
"_v",
"=",
"sizemin",
"if",
"sizemin",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizemin\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
229,
4
] | [
342,
34
] | python | en | ['en', 'error', 'th'] | False |
BaseModelChatBlueprint.assert_task_args | (
cls, args: "DictConfig", shared_state: "SharedTaskState"
) |
Ensure that arguments are properly configured to launch this task.
|
Ensure that arguments are properly configured to launch this task.
| def assert_task_args(
cls, args: "DictConfig", shared_state: "SharedTaskState"
) -> None:
"""
Ensure that arguments are properly configured to launch this task.
"""
super().assert_task_args(args, shared_state)
assert (
args.blueprint.get("task_description_file", None) is not None
), "Must provide a task description file"
full_path = os.path.expanduser(args.blueprint.task_description_file)
assert os.path.exists(
full_path
), f"Target task description path {full_path} doesn't exist"
assert (
args.blueprint.get("left_pane_text_path", None) is not None
), "Must provide a left pane text file"
full_path = os.path.expanduser(args.blueprint.left_pane_text_path)
assert os.path.exists(
full_path
), f"Target left pane text path {full_path} doesn't exist"
if args.blueprint.get("chat_data_folder") == '':
raise ValueError('Must provide a valid chat data folder')
assert '~' not in args.blueprint.chat_data_folder, (
f'"~" can\'t currently be parsed in the chat data folder path '
f'{args.blueprint.chat_data_folder}'
)
# TODO: allow ~ to be parsed correctly
if args.blueprint.get("annotations_config_path", "") != "":
full_path = os.path.expanduser(args.blueprint.annotations_config_path)
assert os.path.exists(
full_path
), f"Target annotation config path {full_path} doesn't exist" | [
"def",
"assert_task_args",
"(",
"cls",
",",
"args",
":",
"\"DictConfig\"",
",",
"shared_state",
":",
"\"SharedTaskState\"",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"assert_task_args",
"(",
"args",
",",
"shared_state",
")",
"assert",
"(",
"args",
".",
"blueprint",
".",
"get",
"(",
"\"task_description_file\"",
",",
"None",
")",
"is",
"not",
"None",
")",
",",
"\"Must provide a task description file\"",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"args",
".",
"blueprint",
".",
"task_description_file",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
",",
"f\"Target task description path {full_path} doesn't exist\"",
"assert",
"(",
"args",
".",
"blueprint",
".",
"get",
"(",
"\"left_pane_text_path\"",
",",
"None",
")",
"is",
"not",
"None",
")",
",",
"\"Must provide a left pane text file\"",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"args",
".",
"blueprint",
".",
"left_pane_text_path",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
",",
"f\"Target left pane text path {full_path} doesn't exist\"",
"if",
"args",
".",
"blueprint",
".",
"get",
"(",
"\"chat_data_folder\"",
")",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"'Must provide a valid chat data folder'",
")",
"assert",
"'~'",
"not",
"in",
"args",
".",
"blueprint",
".",
"chat_data_folder",
",",
"(",
"f'\"~\" can\\'t currently be parsed in the chat data folder path '",
"f'{args.blueprint.chat_data_folder}'",
")",
"# TODO: allow ~ to be parsed correctly",
"if",
"args",
".",
"blueprint",
".",
"get",
"(",
"\"annotations_config_path\"",
",",
"\"\"",
")",
"!=",
"\"\"",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"args",
".",
"blueprint",
".",
"annotations_config_path",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
",",
"f\"Target annotation config path {full_path} doesn't exist\""
] | [
167,
4
] | [
202,
73
] | python | en | ['en', 'error', 'th'] | False |
BaseModelChatBlueprint._get_shared_models | (self, args: "DictConfig") |
Return a dictionary whose values are the shared models.
|
Return a dictionary whose values are the shared models.
| def _get_shared_models(self, args: "DictConfig") -> Dict[str, dict]:
"""
Return a dictionary whose values are the shared models.
""" | [
"def",
"_get_shared_models",
"(",
"self",
",",
"args",
":",
"\"DictConfig\"",
")",
"->",
"Dict",
"[",
"str",
",",
"dict",
"]",
":"
] | [
254,
4
] | [
257,
11
] | python | en | ['en', 'error', 'th'] | False |
BaseModelChatBlueprint.get_frontend_args | (self) |
Specifies what options within a task_config should be forwarded to the client
for use by the task's frontend.
|
Specifies what options within a task_config should be forwarded to the client
for use by the task's frontend.
| def get_frontend_args(self) -> Dict[str, Any]:
"""
Specifies what options within a task_config should be forwarded to the client
for use by the task's frontend.
"""
if self.args.blueprint.get('annotations_config_path', '') != '':
with open(
self.args.blueprint.annotations_config_path, "r", encoding="utf-8-sig"
) as f:
annotation_buckets = json.loads(f.read())
else:
annotation_buckets = None
return {
"min_num_turns": self.args.blueprint.num_turns,
"task_description": self.full_task_description,
"task_title": self.args.task.get('task_title', None),
"annotation_question": self.args.blueprint.annotation_question,
"annotation_buckets": annotation_buckets,
"onboarding_data": getattr(self, 'onboard_task_data', None),
"left_pane_text": self.left_pane_text,
"frame_height": '650px',
"final_rating_question": self.args.blueprint.final_rating_question,
"block_mobile": True,
} | [
"def",
"get_frontend_args",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"self",
".",
"args",
".",
"blueprint",
".",
"get",
"(",
"'annotations_config_path'",
",",
"''",
")",
"!=",
"''",
":",
"with",
"open",
"(",
"self",
".",
"args",
".",
"blueprint",
".",
"annotations_config_path",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8-sig\"",
")",
"as",
"f",
":",
"annotation_buckets",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
"else",
":",
"annotation_buckets",
"=",
"None",
"return",
"{",
"\"min_num_turns\"",
":",
"self",
".",
"args",
".",
"blueprint",
".",
"num_turns",
",",
"\"task_description\"",
":",
"self",
".",
"full_task_description",
",",
"\"task_title\"",
":",
"self",
".",
"args",
".",
"task",
".",
"get",
"(",
"'task_title'",
",",
"None",
")",
",",
"\"annotation_question\"",
":",
"self",
".",
"args",
".",
"blueprint",
".",
"annotation_question",
",",
"\"annotation_buckets\"",
":",
"annotation_buckets",
",",
"\"onboarding_data\"",
":",
"getattr",
"(",
"self",
",",
"'onboard_task_data'",
",",
"None",
")",
",",
"\"left_pane_text\"",
":",
"self",
".",
"left_pane_text",
",",
"\"frame_height\"",
":",
"'650px'",
",",
"\"final_rating_question\"",
":",
"self",
".",
"args",
".",
"blueprint",
".",
"final_rating_question",
",",
"\"block_mobile\"",
":",
"True",
",",
"}"
] | [
259,
4
] | [
283,
9
] | python | en | ['en', 'error', 'th'] | False |
Stream.maxpoints | (self) |
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000]
Returns
-------
int|float
|
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000] | def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000]
Returns
-------
int|float
"""
return self["maxpoints"] | [
"def",
"maxpoints",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"maxpoints\"",
"]"
] | [
15,
4
] | [
28,
32
] | python | en | ['en', 'error', 'th'] | False |
Stream.token | (self) |
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string | def token(self):
"""
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["token"] | [
"def",
"token",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"token\"",
"]"
] | [
37,
4
] | [
50,
28
] | python | en | ['en', 'error', 'th'] | False |
Stream.__init__ | (self, arg=None, maxpoints=None, token=None, **kwargs) |
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterternary.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
|
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterternary.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details. | def __init__(self, arg=None, maxpoints=None, token=None, **kwargs):
"""
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterternary.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
"""
super(Stream, self).__init__("stream")
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.scatterternary.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterternary.Stream`"""
)
# 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("maxpoints", None)
_v = maxpoints if maxpoints is not None else _v
if _v is not None:
self["maxpoints"] = _v
_v = arg.pop("token", None)
_v = token if token is not None else _v
if _v is not None:
self["token"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"maxpoints",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Stream",
",",
"self",
")",
".",
"__init__",
"(",
"\"stream\"",
")",
"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.scatterternary.Stream \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatterternary.Stream`\"\"\"",
")",
"# 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",
"(",
"\"maxpoints\"",
",",
"None",
")",
"_v",
"=",
"maxpoints",
"if",
"maxpoints",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"maxpoints\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"token\"",
",",
"None",
")",
"_v",
"=",
"token",
"if",
"token",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"token\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
72,
4
] | [
140,
34
] | python | en | ['en', 'error', 'th'] | False |
Marker.autocolorscale | (self) |
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in `marker.color`is
set to a numerical array. In case `colorscale` is unspecified
or `autocolorscale` is true, the default palette will be
chosen according to whether numbers in the `color` array are
all positive, all negative or mixed.
The 'autocolorscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in `marker.color`is
set to a numerical array. In case `colorscale` is unspecified
or `autocolorscale` is true, the default palette will be
chosen according to whether numbers in the `color` array are
all positive, all negative or mixed.
The 'autocolorscale' property must be specified as a bool
(either True, or False) | def autocolorscale(self):
"""
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in `marker.color`is
set to a numerical array. In case `colorscale` is unspecified
or `autocolorscale` is true, the default palette will be
chosen according to whether numbers in the `color` array are
all positive, all negative or mixed.
The 'autocolorscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["autocolorscale"] | [
"def",
"autocolorscale",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"autocolorscale\"",
"]"
] | [
40,
4
] | [
57,
37
] | python | en | ['en', 'error', 'th'] | False |
Marker.cauto | (self) |
Determines whether or not the color domain is computed with
respect to the input data (here in `marker.color`) or the
bounds set in `marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color`is set to a numerical array. Defaults
to `false` when `marker.cmin` and `marker.cmax` are set by the
user.
The 'cauto' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether or not the color domain is computed with
respect to the input data (here in `marker.color`) or the
bounds set in `marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color`is set to a numerical array. Defaults
to `false` when `marker.cmin` and `marker.cmax` are set by the
user.
The 'cauto' property must be specified as a bool
(either True, or False) | def cauto(self):
"""
Determines whether or not the color domain is computed with
respect to the input data (here in `marker.color`) or the
bounds set in `marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color`is set to a numerical array. Defaults
to `false` when `marker.cmin` and `marker.cmax` are set by the
user.
The 'cauto' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["cauto"] | [
"def",
"cauto",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"cauto\"",
"]"
] | [
66,
4
] | [
82,
28
] | python | en | ['en', 'error', 'th'] | False |
Marker.cmax | (self) |
Sets the upper bound of the color domain. Has an effect only if
in `marker.color`is set to a numerical array. Value should have
the same units as in `marker.color` and if set, `marker.cmin`
must be set as well.
The 'cmax' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Sets the upper bound of the color domain. Has an effect only if
in `marker.color`is set to a numerical array. Value should have
the same units as in `marker.color` and if set, `marker.cmin`
must be set as well.
The 'cmax' property is a number and may be specified as:
- An int or float | def cmax(self):
"""
Sets the upper bound of the color domain. Has an effect only if
in `marker.color`is set to a numerical array. Value should have
the same units as in `marker.color` and if set, `marker.cmin`
must be set as well.
The 'cmax' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmax"] | [
"def",
"cmax",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"cmax\"",
"]"
] | [
91,
4
] | [
105,
27
] | python | en | ['en', 'error', 'th'] | False |
Marker.cmid | (self) |
Sets the mid-point of the color domain by scaling `marker.cmin`
and/or `marker.cmax` to be equidistant to this point. Has an
effect only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`. Has no
effect when `marker.cauto` is `false`.
The 'cmid' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Sets the mid-point of the color domain by scaling `marker.cmin`
and/or `marker.cmax` to be equidistant to this point. Has an
effect only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`. Has no
effect when `marker.cauto` is `false`.
The 'cmid' property is a number and may be specified as:
- An int or float | def cmid(self):
"""
Sets the mid-point of the color domain by scaling `marker.cmin`
and/or `marker.cmax` to be equidistant to this point. Has an
effect only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`. Has no
effect when `marker.cauto` is `false`.
The 'cmid' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmid"] | [
"def",
"cmid",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"cmid\"",
"]"
] | [
114,
4
] | [
129,
27
] | python | en | ['en', 'error', 'th'] | False |
Marker.cmin | (self) |
Sets the lower bound of the color domain. Has an effect only if
in `marker.color`is set to a numerical array. Value should have
the same units as in `marker.color` and if set, `marker.cmax`
must be set as well.
The 'cmin' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Sets the lower bound of the color domain. Has an effect only if
in `marker.color`is set to a numerical array. Value should have
the same units as in `marker.color` and if set, `marker.cmax`
must be set as well.
The 'cmin' property is a number and may be specified as:
- An int or float | def cmin(self):
"""
Sets the lower bound of the color domain. Has an effect only if
in `marker.color`is set to a numerical array. Value should have
the same units as in `marker.color` and if set, `marker.cmax`
must be set as well.
The 'cmin' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["cmin"] | [
"def",
"cmin",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"cmin\"",
"]"
] | [
138,
4
] | [
152,
27
] | python | en | ['en', 'error', 'th'] | False |
Marker.color | (self) |
Sets themarkercolor. It accepts either a specific color or an
array of numbers that are mapped to the colorscale relative to
the max and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A number that will be interpreted as a color
according to scatterpolar.marker.colorscale
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
|
Sets themarkercolor. It accepts either a specific color or an
array of numbers that are mapped to the colorscale relative to
the max and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A number that will be interpreted as a color
according to scatterpolar.marker.colorscale
- A list or array of any of the above | def color(self):
"""
Sets themarkercolor. It accepts either a specific color or an
array of numbers that are mapped to the colorscale relative to
the max and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A number that will be interpreted as a color
according to scatterpolar.marker.colorscale
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
161,
4
] | [
217,
28
] | python | en | ['en', 'error', 'th'] | False |
Marker.coloraxis | (self) |
Sets a reference to a shared color axis. References to these
shared color axes are "coloraxis", "coloraxis2", "coloraxis3",
etc. Settings for these shared color axes are set in the
layout, under `layout.coloraxis`, `layout.coloraxis2`, etc.
Note that multiple color scales can be linked to the same color
axis.
The 'coloraxis' property is an identifier of a particular
subplot, of type 'coloraxis', that may be specified as the string 'coloraxis'
optionally followed by an integer >= 1
(e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.)
Returns
-------
str
|
Sets a reference to a shared color axis. References to these
shared color axes are "coloraxis", "coloraxis2", "coloraxis3",
etc. Settings for these shared color axes are set in the
layout, under `layout.coloraxis`, `layout.coloraxis2`, etc.
Note that multiple color scales can be linked to the same color
axis.
The 'coloraxis' property is an identifier of a particular
subplot, of type 'coloraxis', that may be specified as the string 'coloraxis'
optionally followed by an integer >= 1
(e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.) | def coloraxis(self):
"""
Sets a reference to a shared color axis. References to these
shared color axes are "coloraxis", "coloraxis2", "coloraxis3",
etc. Settings for these shared color axes are set in the
layout, under `layout.coloraxis`, `layout.coloraxis2`, etc.
Note that multiple color scales can be linked to the same color
axis.
The 'coloraxis' property is an identifier of a particular
subplot, of type 'coloraxis', that may be specified as the string 'coloraxis'
optionally followed by an integer >= 1
(e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.)
Returns
-------
str
"""
return self["coloraxis"] | [
"def",
"coloraxis",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"coloraxis\"",
"]"
] | [
226,
4
] | [
244,
32
] | python | en | ['en', 'error', 'th'] | False |
Marker.colorbar | (self) |
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Formatting.md#d3_format
And for dates see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Time-Formatting.md#format
We add one item to d3's date formatter: "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter
polar.marker.colorbar.Tickformatstop` instances
or dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.dat
a.scatterpolar.marker.colorbar.tickformatstopde
faults), sets the default property values to
use for elements of
scatterpolar.marker.colorbar.tickformatstops
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for ticktext .
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for tickvals .
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatterpolar.marke
r.colorbar.Title` instance or dict with
compatible properties
titlefont
Deprecated: Please use
scatterpolar.marker.colorbar.title.font
instead. Sets this color bar's title font. Note
that the title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
scatterpolar.marker.colorbar.title.side
instead. Determines the location of color bar's
title with respect to the color bar. Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position of the color bar (in plot
fraction).
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar.
xpad
Sets the amount of padding (in px) along the x
direction.
y
Sets the y position of the color bar (in plot
fraction).
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
ypad
Sets the amount of padding (in px) along the y
direction.
Returns
-------
plotly.graph_objs.scatterpolar.marker.ColorBar
|
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Formatting.md#d3_format
And for dates see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Time-Formatting.md#format
We add one item to d3's date formatter: "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter
polar.marker.colorbar.Tickformatstop` instances
or dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.dat
a.scatterpolar.marker.colorbar.tickformatstopde
faults), sets the default property values to
use for elements of
scatterpolar.marker.colorbar.tickformatstops
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for ticktext .
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for tickvals .
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatterpolar.marke
r.colorbar.Title` instance or dict with
compatible properties
titlefont
Deprecated: Please use
scatterpolar.marker.colorbar.title.font
instead. Sets this color bar's title font. Note
that the title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
scatterpolar.marker.colorbar.title.side
instead. Determines the location of color bar's
title with respect to the color bar. Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position of the color bar (in plot
fraction).
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar.
xpad
Sets the amount of padding (in px) along the x
direction.
y
Sets the y position of the color bar (in plot
fraction).
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
ypad
Sets the amount of padding (in px) along the y
direction. | def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Formatting.md#d3_format
And for dates see:
https://github.com/d3/d3-3.x-api-
reference/blob/master/Time-Formatting.md#format
We add one item to d3's date formatter: "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter
polar.marker.colorbar.Tickformatstop` instances
or dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.dat
a.scatterpolar.marker.colorbar.tickformatstopde
faults), sets the default property values to
use for elements of
scatterpolar.marker.colorbar.tickformatstops
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for ticktext .
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for tickvals .
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatterpolar.marke
r.colorbar.Title` instance or dict with
compatible properties
titlefont
Deprecated: Please use
scatterpolar.marker.colorbar.title.font
instead. Sets this color bar's title font. Note
that the title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
scatterpolar.marker.colorbar.title.side
instead. Determines the location of color bar's
title with respect to the color bar. Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position of the color bar (in plot
fraction).
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar.
xpad
Sets the amount of padding (in px) along the x
direction.
y
Sets the y position of the color bar (in plot
fraction).
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
ypad
Sets the amount of padding (in px) along the y
direction.
Returns
-------
plotly.graph_objs.scatterpolar.marker.ColorBar
"""
return self["colorbar"] | [
"def",
"colorbar",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorbar\"",
"]"
] | [
253,
4
] | [
480,
31
] | python | en | ['en', 'error', 'th'] | False |
Marker.colorscale | (self) |
Sets the colorscale. Has an effect only if in `marker.color`is
set to a numerical array. The colorscale must be an array
containing arrays mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At minimum, a mapping for
the lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To
control the bounds of the colorscale in color space,
use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale`
may be a palette name string of the following list: Greys,YlGnB
u,Greens,YlOrRd,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland
,Jet,Hot,Blackbody,Earth,Electric,Viridis,Cividis.
The 'colorscale' property is a colorscale and may be
specified as:
- A list of colors that will be spaced evenly to create the colorscale.
Many predefined colorscale lists are included in the sequential, diverging,
and cyclical modules in the plotly.colors package.
- A list of 2-element lists where the first element is the
normalized color level value (starting at 0 and ending at 1),
and the second item is a valid color string.
(e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg',
'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor',
'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy',
'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral',
'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose',
'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight',
'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd'].
Appending '_r' to a named colorscale reverses it.
Returns
-------
str
|
Sets the colorscale. Has an effect only if in `marker.color`is
set to a numerical array. The colorscale must be an array
containing arrays mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At minimum, a mapping for
the lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To
control the bounds of the colorscale in color space,
use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale`
may be a palette name string of the following list: Greys,YlGnB
u,Greens,YlOrRd,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland
,Jet,Hot,Blackbody,Earth,Electric,Viridis,Cividis.
The 'colorscale' property is a colorscale and may be
specified as:
- A list of colors that will be spaced evenly to create the colorscale.
Many predefined colorscale lists are included in the sequential, diverging,
and cyclical modules in the plotly.colors package.
- A list of 2-element lists where the first element is the
normalized color level value (starting at 0 and ending at 1),
and the second item is a valid color string.
(e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg',
'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor',
'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy',
'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral',
'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose',
'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight',
'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd'].
Appending '_r' to a named colorscale reverses it. | def colorscale(self):
"""
Sets the colorscale. Has an effect only if in `marker.color`is
set to a numerical array. The colorscale must be an array
containing arrays mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At minimum, a mapping for
the lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To
control the bounds of the colorscale in color space,
use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale`
may be a palette name string of the following list: Greys,YlGnB
u,Greens,YlOrRd,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland
,Jet,Hot,Blackbody,Earth,Electric,Viridis,Cividis.
The 'colorscale' property is a colorscale and may be
specified as:
- A list of colors that will be spaced evenly to create the colorscale.
Many predefined colorscale lists are included in the sequential, diverging,
and cyclical modules in the plotly.colors package.
- A list of 2-element lists where the first element is the
normalized color level value (starting at 0 and ending at 1),
and the second item is a valid color string.
(e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']])
- One of the following named colorscales:
['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance',
'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg',
'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl',
'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric',
'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys',
'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet',
'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges',
'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg',
'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor',
'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy',
'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral',
'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose',
'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight',
'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd'].
Appending '_r' to a named colorscale reverses it.
Returns
-------
str
"""
return self["colorscale"] | [
"def",
"colorscale",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorscale\"",
"]"
] | [
489,
4
] | [
533,
33
] | python | en | ['en', 'error', 'th'] | False |
Marker.colorsrc | (self) |
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"] | [
"def",
"colorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorsrc\"",
"]"
] | [
542,
4
] | [
553,
31
] | python | en | ['en', 'error', 'th'] | False |
Marker.gradient | (self) |
The 'gradient' property is an instance of Gradient
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.Gradient`
- A dict of string/value properties that will be passed
to the Gradient constructor
Supported dict properties:
color
Sets the final color of the gradient fill: the
center color for radial, the right for
horizontal, or the bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
type
Sets the type of gradient used to fill the
markers
typesrc
Sets the source reference on Chart Studio Cloud
for type .
Returns
-------
plotly.graph_objs.scatterpolar.marker.Gradient
|
The 'gradient' property is an instance of Gradient
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.Gradient`
- A dict of string/value properties that will be passed
to the Gradient constructor
Supported dict properties:
color
Sets the final color of the gradient fill: the
center color for radial, the right for
horizontal, or the bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
type
Sets the type of gradient used to fill the
markers
typesrc
Sets the source reference on Chart Studio Cloud
for type . | def gradient(self):
"""
The 'gradient' property is an instance of Gradient
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.Gradient`
- A dict of string/value properties that will be passed
to the Gradient constructor
Supported dict properties:
color
Sets the final color of the gradient fill: the
center color for radial, the right for
horizontal, or the bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
type
Sets the type of gradient used to fill the
markers
typesrc
Sets the source reference on Chart Studio Cloud
for type .
Returns
-------
plotly.graph_objs.scatterpolar.marker.Gradient
"""
return self["gradient"] | [
"def",
"gradient",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"gradient\"",
"]"
] | [
562,
4
] | [
590,
31
] | python | en | ['en', 'error', 'th'] | False |
Marker.line | (self) |
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.line.colorscale`. Has an
effect only if in `marker.line.color`is set to
a numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.line.color`) or the bounds set in
`marker.line.cmin` and `marker.line.cmax` Has
an effect only if in `marker.line.color`is set
to a numerical array. Defaults to `false` when
`marker.line.cmin` and `marker.line.cmax` are
set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.line.cmin` and/or
`marker.line.cmax` to be equidistant to this
point. Has an effect only if in
`marker.line.color`is set to a numerical array.
Value should have the same units as in
`marker.line.color`. Has no effect when
`marker.line.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmax` must be set as well.
color
Sets themarker.linecolor. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.line.cmin` and `marker.line.cmax` if
set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorscale
Sets the colorscale. Has an effect only if in
`marker.line.color`is set to a numerical array.
The colorscale must be an array containing
arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use`marker.line.cmin` and
`marker.line.cmax`. Alternatively, `colorscale`
may be a palette name string of the following
list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,R
eds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Black
body,Earth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.line.color`is set to
a numerical array. If true, `marker.line.cmin`
will correspond to the last color in the array
and `marker.line.cmax` will correspond to the
first color.
width
Sets the width (in px) of the lines bounding
the marker points.
widthsrc
Sets the source reference on Chart Studio Cloud
for width .
Returns
-------
plotly.graph_objs.scatterpolar.marker.Line
|
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.line.colorscale`. Has an
effect only if in `marker.line.color`is set to
a numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.line.color`) or the bounds set in
`marker.line.cmin` and `marker.line.cmax` Has
an effect only if in `marker.line.color`is set
to a numerical array. Defaults to `false` when
`marker.line.cmin` and `marker.line.cmax` are
set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.line.cmin` and/or
`marker.line.cmax` to be equidistant to this
point. Has an effect only if in
`marker.line.color`is set to a numerical array.
Value should have the same units as in
`marker.line.color`. Has no effect when
`marker.line.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmax` must be set as well.
color
Sets themarker.linecolor. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.line.cmin` and `marker.line.cmax` if
set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorscale
Sets the colorscale. Has an effect only if in
`marker.line.color`is set to a numerical array.
The colorscale must be an array containing
arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use`marker.line.cmin` and
`marker.line.cmax`. Alternatively, `colorscale`
may be a palette name string of the following
list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,R
eds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Black
body,Earth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.line.color`is set to
a numerical array. If true, `marker.line.cmin`
will correspond to the last color in the array
and `marker.line.cmax` will correspond to the
first color.
width
Sets the width (in px) of the lines bounding
the marker points.
widthsrc
Sets the source reference on Chart Studio Cloud
for width . | def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.marker.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.line.colorscale`. Has an
effect only if in `marker.line.color`is set to
a numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.line.color`) or the bounds set in
`marker.line.cmin` and `marker.line.cmax` Has
an effect only if in `marker.line.color`is set
to a numerical array. Defaults to `false` when
`marker.line.cmin` and `marker.line.cmax` are
set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.line.cmin` and/or
`marker.line.cmax` to be equidistant to this
point. Has an effect only if in
`marker.line.color`is set to a numerical array.
Value should have the same units as in
`marker.line.color`. Has no effect when
`marker.line.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmax` must be set as well.
color
Sets themarker.linecolor. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.line.cmin` and `marker.line.cmax` if
set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorscale
Sets the colorscale. Has an effect only if in
`marker.line.color`is set to a numerical array.
The colorscale must be an array containing
arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use`marker.line.cmin` and
`marker.line.cmax`. Alternatively, `colorscale`
may be a palette name string of the following
list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,R
eds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Black
body,Earth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.line.color`is set to
a numerical array. If true, `marker.line.cmin`
will correspond to the last color in the array
and `marker.line.cmax` will correspond to the
first color.
width
Sets the width (in px) of the lines bounding
the marker points.
widthsrc
Sets the source reference on Chart Studio Cloud
for width .
Returns
-------
plotly.graph_objs.scatterpolar.marker.Line
"""
return self["line"] | [
"def",
"line",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"line\"",
"]"
] | [
599,
4
] | [
702,
27
] | python | en | ['en', 'error', 'th'] | False |
Marker.maxdisplayed | (self) |
Sets a maximum number of points to be drawn on the graph. 0
corresponds to no limit.
The 'maxdisplayed' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
|
Sets a maximum number of points to be drawn on the graph. 0
corresponds to no limit.
The 'maxdisplayed' property is a number and may be specified as:
- An int or float in the interval [0, inf] | def maxdisplayed(self):
"""
Sets a maximum number of points to be drawn on the graph. 0
corresponds to no limit.
The 'maxdisplayed' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["maxdisplayed"] | [
"def",
"maxdisplayed",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"maxdisplayed\"",
"]"
] | [
711,
4
] | [
723,
35
] | python | en | ['en', 'error', 'th'] | False |
Marker.opacity | (self) |
Sets the marker opacity.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
|
Sets the marker opacity.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
- A tuple, list, or one-dimensional numpy array of the above | def opacity(self):
"""
Sets the marker opacity.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["opacity"] | [
"def",
"opacity",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"opacity\"",
"]"
] | [
732,
4
] | [
744,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.opacitysrc | (self) |
Sets the source reference on Chart Studio Cloud for opacity .
The 'opacitysrc' 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 opacity .
The 'opacitysrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def opacitysrc(self):
"""
Sets the source reference on Chart Studio Cloud for opacity .
The 'opacitysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["opacitysrc"] | [
"def",
"opacitysrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"opacitysrc\"",
"]"
] | [
753,
4
] | [
764,
33
] | python | en | ['en', 'error', 'th'] | False |
Marker.reversescale | (self) |
Reverses the color mapping if true. Has an effect only if in
`marker.color`is set to a numerical array. If true,
`marker.cmin` will correspond to the last color in the array
and `marker.cmax` will correspond to the first color.
The 'reversescale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Reverses the color mapping if true. Has an effect only if in
`marker.color`is set to a numerical array. If true,
`marker.cmin` will correspond to the last color in the array
and `marker.cmax` will correspond to the first color.
The 'reversescale' property must be specified as a bool
(either True, or False) | def reversescale(self):
"""
Reverses the color mapping if true. Has an effect only if in
`marker.color`is set to a numerical array. If true,
`marker.cmin` will correspond to the last color in the array
and `marker.cmax` will correspond to the first color.
The 'reversescale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["reversescale"] | [
"def",
"reversescale",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"reversescale\"",
"]"
] | [
773,
4
] | [
787,
35
] | python | en | ['en', 'error', 'th'] | False |
Marker.showscale | (self) |
Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color`is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color`is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False) | def showscale(self):
"""
Determines whether or not a colorbar is displayed for this
trace. Has an effect only if in `marker.color`is set to a
numerical array.
The 'showscale' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showscale"] | [
"def",
"showscale",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"showscale\"",
"]"
] | [
796,
4
] | [
809,
32
] | python | en | ['en', 'error', 'th'] | False |
Marker.size | (self) |
Sets the marker size (in px).
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
|
Sets the marker size (in px).
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above | def size(self):
"""
Sets the marker size (in px).
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
818,
4
] | [
830,
27
] | python | en | ['en', 'error', 'th'] | False |
Marker.sizemin | (self) |
Has an effect only if `marker.size` is set to a numerical
array. Sets the minimum size (in px) of the rendered marker
points.
The 'sizemin' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
|
Has an effect only if `marker.size` is set to a numerical
array. Sets the minimum size (in px) of the rendered marker
points.
The 'sizemin' property is a number and may be specified as:
- An int or float in the interval [0, inf] | def sizemin(self):
"""
Has an effect only if `marker.size` is set to a numerical
array. Sets the minimum size (in px) of the rendered marker
points.
The 'sizemin' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["sizemin"] | [
"def",
"sizemin",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizemin\"",
"]"
] | [
839,
4
] | [
852,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.sizemode | (self) |
Has an effect only if `marker.size` is set to a numerical
array. Sets the rule for which the data in `size` is converted
to pixels.
The 'sizemode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['diameter', 'area']
Returns
-------
Any
|
Has an effect only if `marker.size` is set to a numerical
array. Sets the rule for which the data in `size` is converted
to pixels.
The 'sizemode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['diameter', 'area'] | def sizemode(self):
"""
Has an effect only if `marker.size` is set to a numerical
array. Sets the rule for which the data in `size` is converted
to pixels.
The 'sizemode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['diameter', 'area']
Returns
-------
Any
"""
return self["sizemode"] | [
"def",
"sizemode",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizemode\"",
"]"
] | [
861,
4
] | [
875,
31
] | python | en | ['en', 'error', 'th'] | False |
Marker.sizeref | (self) |
Has an effect only if `marker.size` is set to a numerical
array. Sets the scale factor used to determine the rendered
size of marker points. Use with `sizemin` and `sizemode`.
The 'sizeref' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Has an effect only if `marker.size` is set to a numerical
array. Sets the scale factor used to determine the rendered
size of marker points. Use with `sizemin` and `sizemode`.
The 'sizeref' property is a number and may be specified as:
- An int or float | def sizeref(self):
"""
Has an effect only if `marker.size` is set to a numerical
array. Sets the scale factor used to determine the rendered
size of marker points. Use with `sizemin` and `sizemode`.
The 'sizeref' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["sizeref"] | [
"def",
"sizeref",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizeref\"",
"]"
] | [
884,
4
] | [
897,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.sizesrc | (self) |
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"] | [
"def",
"sizesrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizesrc\"",
"]"
] | [
906,
4
] | [
917,
30
] | python | en | ['en', 'error', 'th'] | False |
Marker.symbol | (self) |
Sets the marker symbol type. Adding 100 is equivalent to
appending "-open" to a symbol name. Adding 200 is equivalent to
appending "-dot" to a symbol name. Adding 300 is equivalent to
appending "-open-dot" or "dot-open" to a symbol name.
The 'symbol' property is an enumeration that may be specified as:
- One of the following enumeration values:
[0, 'circle', 100, 'circle-open', 200, 'circle-dot', 300,
'circle-open-dot', 1, 'square', 101, 'square-open', 201,
'square-dot', 301, 'square-open-dot', 2, 'diamond', 102,
'diamond-open', 202, 'diamond-dot', 302,
'diamond-open-dot', 3, 'cross', 103, 'cross-open', 203,
'cross-dot', 303, 'cross-open-dot', 4, 'x', 104, 'x-open',
204, 'x-dot', 304, 'x-open-dot', 5, 'triangle-up', 105,
'triangle-up-open', 205, 'triangle-up-dot', 305,
'triangle-up-open-dot', 6, 'triangle-down', 106,
'triangle-down-open', 206, 'triangle-down-dot', 306,
'triangle-down-open-dot', 7, 'triangle-left', 107,
'triangle-left-open', 207, 'triangle-left-dot', 307,
'triangle-left-open-dot', 8, 'triangle-right', 108,
'triangle-right-open', 208, 'triangle-right-dot', 308,
'triangle-right-open-dot', 9, 'triangle-ne', 109,
'triangle-ne-open', 209, 'triangle-ne-dot', 309,
'triangle-ne-open-dot', 10, 'triangle-se', 110,
'triangle-se-open', 210, 'triangle-se-dot', 310,
'triangle-se-open-dot', 11, 'triangle-sw', 111,
'triangle-sw-open', 211, 'triangle-sw-dot', 311,
'triangle-sw-open-dot', 12, 'triangle-nw', 112,
'triangle-nw-open', 212, 'triangle-nw-dot', 312,
'triangle-nw-open-dot', 13, 'pentagon', 113,
'pentagon-open', 213, 'pentagon-dot', 313,
'pentagon-open-dot', 14, 'hexagon', 114, 'hexagon-open',
214, 'hexagon-dot', 314, 'hexagon-open-dot', 15,
'hexagon2', 115, 'hexagon2-open', 215, 'hexagon2-dot',
315, 'hexagon2-open-dot', 16, 'octagon', 116,
'octagon-open', 216, 'octagon-dot', 316,
'octagon-open-dot', 17, 'star', 117, 'star-open', 217,
'star-dot', 317, 'star-open-dot', 18, 'hexagram', 118,
'hexagram-open', 218, 'hexagram-dot', 318,
'hexagram-open-dot', 19, 'star-triangle-up', 119,
'star-triangle-up-open', 219, 'star-triangle-up-dot', 319,
'star-triangle-up-open-dot', 20, 'star-triangle-down',
120, 'star-triangle-down-open', 220,
'star-triangle-down-dot', 320,
'star-triangle-down-open-dot', 21, 'star-square', 121,
'star-square-open', 221, 'star-square-dot', 321,
'star-square-open-dot', 22, 'star-diamond', 122,
'star-diamond-open', 222, 'star-diamond-dot', 322,
'star-diamond-open-dot', 23, 'diamond-tall', 123,
'diamond-tall-open', 223, 'diamond-tall-dot', 323,
'diamond-tall-open-dot', 24, 'diamond-wide', 124,
'diamond-wide-open', 224, 'diamond-wide-dot', 324,
'diamond-wide-open-dot', 25, 'hourglass', 125,
'hourglass-open', 26, 'bowtie', 126, 'bowtie-open', 27,
'circle-cross', 127, 'circle-cross-open', 28, 'circle-x',
128, 'circle-x-open', 29, 'square-cross', 129,
'square-cross-open', 30, 'square-x', 130, 'square-x-open',
31, 'diamond-cross', 131, 'diamond-cross-open', 32,
'diamond-x', 132, 'diamond-x-open', 33, 'cross-thin', 133,
'cross-thin-open', 34, 'x-thin', 134, 'x-thin-open', 35,
'asterisk', 135, 'asterisk-open', 36, 'hash', 136,
'hash-open', 236, 'hash-dot', 336, 'hash-open-dot', 37,
'y-up', 137, 'y-up-open', 38, 'y-down', 138,
'y-down-open', 39, 'y-left', 139, 'y-left-open', 40,
'y-right', 140, 'y-right-open', 41, 'line-ew', 141,
'line-ew-open', 42, 'line-ns', 142, 'line-ns-open', 43,
'line-ne', 143, 'line-ne-open', 44, 'line-nw', 144,
'line-nw-open']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
|
Sets the marker symbol type. Adding 100 is equivalent to
appending "-open" to a symbol name. Adding 200 is equivalent to
appending "-dot" to a symbol name. Adding 300 is equivalent to
appending "-open-dot" or "dot-open" to a symbol name.
The 'symbol' property is an enumeration that may be specified as:
- One of the following enumeration values:
[0, 'circle', 100, 'circle-open', 200, 'circle-dot', 300,
'circle-open-dot', 1, 'square', 101, 'square-open', 201,
'square-dot', 301, 'square-open-dot', 2, 'diamond', 102,
'diamond-open', 202, 'diamond-dot', 302,
'diamond-open-dot', 3, 'cross', 103, 'cross-open', 203,
'cross-dot', 303, 'cross-open-dot', 4, 'x', 104, 'x-open',
204, 'x-dot', 304, 'x-open-dot', 5, 'triangle-up', 105,
'triangle-up-open', 205, 'triangle-up-dot', 305,
'triangle-up-open-dot', 6, 'triangle-down', 106,
'triangle-down-open', 206, 'triangle-down-dot', 306,
'triangle-down-open-dot', 7, 'triangle-left', 107,
'triangle-left-open', 207, 'triangle-left-dot', 307,
'triangle-left-open-dot', 8, 'triangle-right', 108,
'triangle-right-open', 208, 'triangle-right-dot', 308,
'triangle-right-open-dot', 9, 'triangle-ne', 109,
'triangle-ne-open', 209, 'triangle-ne-dot', 309,
'triangle-ne-open-dot', 10, 'triangle-se', 110,
'triangle-se-open', 210, 'triangle-se-dot', 310,
'triangle-se-open-dot', 11, 'triangle-sw', 111,
'triangle-sw-open', 211, 'triangle-sw-dot', 311,
'triangle-sw-open-dot', 12, 'triangle-nw', 112,
'triangle-nw-open', 212, 'triangle-nw-dot', 312,
'triangle-nw-open-dot', 13, 'pentagon', 113,
'pentagon-open', 213, 'pentagon-dot', 313,
'pentagon-open-dot', 14, 'hexagon', 114, 'hexagon-open',
214, 'hexagon-dot', 314, 'hexagon-open-dot', 15,
'hexagon2', 115, 'hexagon2-open', 215, 'hexagon2-dot',
315, 'hexagon2-open-dot', 16, 'octagon', 116,
'octagon-open', 216, 'octagon-dot', 316,
'octagon-open-dot', 17, 'star', 117, 'star-open', 217,
'star-dot', 317, 'star-open-dot', 18, 'hexagram', 118,
'hexagram-open', 218, 'hexagram-dot', 318,
'hexagram-open-dot', 19, 'star-triangle-up', 119,
'star-triangle-up-open', 219, 'star-triangle-up-dot', 319,
'star-triangle-up-open-dot', 20, 'star-triangle-down',
120, 'star-triangle-down-open', 220,
'star-triangle-down-dot', 320,
'star-triangle-down-open-dot', 21, 'star-square', 121,
'star-square-open', 221, 'star-square-dot', 321,
'star-square-open-dot', 22, 'star-diamond', 122,
'star-diamond-open', 222, 'star-diamond-dot', 322,
'star-diamond-open-dot', 23, 'diamond-tall', 123,
'diamond-tall-open', 223, 'diamond-tall-dot', 323,
'diamond-tall-open-dot', 24, 'diamond-wide', 124,
'diamond-wide-open', 224, 'diamond-wide-dot', 324,
'diamond-wide-open-dot', 25, 'hourglass', 125,
'hourglass-open', 26, 'bowtie', 126, 'bowtie-open', 27,
'circle-cross', 127, 'circle-cross-open', 28, 'circle-x',
128, 'circle-x-open', 29, 'square-cross', 129,
'square-cross-open', 30, 'square-x', 130, 'square-x-open',
31, 'diamond-cross', 131, 'diamond-cross-open', 32,
'diamond-x', 132, 'diamond-x-open', 33, 'cross-thin', 133,
'cross-thin-open', 34, 'x-thin', 134, 'x-thin-open', 35,
'asterisk', 135, 'asterisk-open', 36, 'hash', 136,
'hash-open', 236, 'hash-dot', 336, 'hash-open-dot', 37,
'y-up', 137, 'y-up-open', 38, 'y-down', 138,
'y-down-open', 39, 'y-left', 139, 'y-left-open', 40,
'y-right', 140, 'y-right-open', 41, 'line-ew', 141,
'line-ew-open', 42, 'line-ns', 142, 'line-ns-open', 43,
'line-ne', 143, 'line-ne-open', 44, 'line-nw', 144,
'line-nw-open']
- A tuple, list, or one-dimensional numpy array of the above | def symbol(self):
"""
Sets the marker symbol type. Adding 100 is equivalent to
appending "-open" to a symbol name. Adding 200 is equivalent to
appending "-dot" to a symbol name. Adding 300 is equivalent to
appending "-open-dot" or "dot-open" to a symbol name.
The 'symbol' property is an enumeration that may be specified as:
- One of the following enumeration values:
[0, 'circle', 100, 'circle-open', 200, 'circle-dot', 300,
'circle-open-dot', 1, 'square', 101, 'square-open', 201,
'square-dot', 301, 'square-open-dot', 2, 'diamond', 102,
'diamond-open', 202, 'diamond-dot', 302,
'diamond-open-dot', 3, 'cross', 103, 'cross-open', 203,
'cross-dot', 303, 'cross-open-dot', 4, 'x', 104, 'x-open',
204, 'x-dot', 304, 'x-open-dot', 5, 'triangle-up', 105,
'triangle-up-open', 205, 'triangle-up-dot', 305,
'triangle-up-open-dot', 6, 'triangle-down', 106,
'triangle-down-open', 206, 'triangle-down-dot', 306,
'triangle-down-open-dot', 7, 'triangle-left', 107,
'triangle-left-open', 207, 'triangle-left-dot', 307,
'triangle-left-open-dot', 8, 'triangle-right', 108,
'triangle-right-open', 208, 'triangle-right-dot', 308,
'triangle-right-open-dot', 9, 'triangle-ne', 109,
'triangle-ne-open', 209, 'triangle-ne-dot', 309,
'triangle-ne-open-dot', 10, 'triangle-se', 110,
'triangle-se-open', 210, 'triangle-se-dot', 310,
'triangle-se-open-dot', 11, 'triangle-sw', 111,
'triangle-sw-open', 211, 'triangle-sw-dot', 311,
'triangle-sw-open-dot', 12, 'triangle-nw', 112,
'triangle-nw-open', 212, 'triangle-nw-dot', 312,
'triangle-nw-open-dot', 13, 'pentagon', 113,
'pentagon-open', 213, 'pentagon-dot', 313,
'pentagon-open-dot', 14, 'hexagon', 114, 'hexagon-open',
214, 'hexagon-dot', 314, 'hexagon-open-dot', 15,
'hexagon2', 115, 'hexagon2-open', 215, 'hexagon2-dot',
315, 'hexagon2-open-dot', 16, 'octagon', 116,
'octagon-open', 216, 'octagon-dot', 316,
'octagon-open-dot', 17, 'star', 117, 'star-open', 217,
'star-dot', 317, 'star-open-dot', 18, 'hexagram', 118,
'hexagram-open', 218, 'hexagram-dot', 318,
'hexagram-open-dot', 19, 'star-triangle-up', 119,
'star-triangle-up-open', 219, 'star-triangle-up-dot', 319,
'star-triangle-up-open-dot', 20, 'star-triangle-down',
120, 'star-triangle-down-open', 220,
'star-triangle-down-dot', 320,
'star-triangle-down-open-dot', 21, 'star-square', 121,
'star-square-open', 221, 'star-square-dot', 321,
'star-square-open-dot', 22, 'star-diamond', 122,
'star-diamond-open', 222, 'star-diamond-dot', 322,
'star-diamond-open-dot', 23, 'diamond-tall', 123,
'diamond-tall-open', 223, 'diamond-tall-dot', 323,
'diamond-tall-open-dot', 24, 'diamond-wide', 124,
'diamond-wide-open', 224, 'diamond-wide-dot', 324,
'diamond-wide-open-dot', 25, 'hourglass', 125,
'hourglass-open', 26, 'bowtie', 126, 'bowtie-open', 27,
'circle-cross', 127, 'circle-cross-open', 28, 'circle-x',
128, 'circle-x-open', 29, 'square-cross', 129,
'square-cross-open', 30, 'square-x', 130, 'square-x-open',
31, 'diamond-cross', 131, 'diamond-cross-open', 32,
'diamond-x', 132, 'diamond-x-open', 33, 'cross-thin', 133,
'cross-thin-open', 34, 'x-thin', 134, 'x-thin-open', 35,
'asterisk', 135, 'asterisk-open', 36, 'hash', 136,
'hash-open', 236, 'hash-dot', 336, 'hash-open-dot', 37,
'y-up', 137, 'y-up-open', 38, 'y-down', 138,
'y-down-open', 39, 'y-left', 139, 'y-left-open', 40,
'y-right', 140, 'y-right-open', 41, 'line-ew', 141,
'line-ew-open', 42, 'line-ns', 142, 'line-ns-open', 43,
'line-ne', 143, 'line-ne-open', 44, 'line-nw', 144,
'line-nw-open']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["symbol"] | [
"def",
"symbol",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"symbol\"",
"]"
] | [
926,
4
] | [
1002,
29
] | python | en | ['en', 'error', 'th'] | False |
Marker.symbolsrc | (self) |
Sets the source reference on Chart Studio Cloud for symbol .
The 'symbolsrc' 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 symbol .
The 'symbolsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def symbolsrc(self):
"""
Sets the source reference on Chart Studio Cloud for symbol .
The 'symbolsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["symbolsrc"] | [
"def",
"symbolsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"symbolsrc\"",
"]"
] | [
1011,
4
] | [
1022,
32
] | python | en | ['en', 'error', 'th'] | False |
Marker.__init__ | (
self,
arg=None,
autocolorscale=None,
cauto=None,
cmax=None,
cmid=None,
cmin=None,
color=None,
coloraxis=None,
colorbar=None,
colorscale=None,
colorsrc=None,
gradient=None,
line=None,
maxdisplayed=None,
opacity=None,
opacitysrc=None,
reversescale=None,
showscale=None,
size=None,
sizemin=None,
sizemode=None,
sizeref=None,
sizesrc=None,
symbol=None,
symbolsrc=None,
**kwargs
) |
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterpolar.Marker`
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in
`marker.color`is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in `marker.color`)
or the bounds set in `marker.cmin` and `marker.cmax`
Has an effect only if in `marker.color`is set to a
numerical array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.cmin` and/or `marker.cmax` to be equidistant to
this point. Has an effect only if in `marker.color`is
set to a numerical array. Value should have the same
units as in `marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmax` must be set as well.
color
Sets themarkercolor. It accepts either a specific color
or an array of numbers that are mapped to the
colorscale relative to the max and min values of the
array or relative to `marker.cmin` and `marker.cmax` if
set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorbar
:class:`plotly.graph_objects.scatterpolar.marker.ColorB
ar` instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color`is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use`marker.cmin` and `marker.cmax`. Alternatively,
`colorscale` may be a palette name string of the
following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu
,Reds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,E
arth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
gradient
:class:`plotly.graph_objects.scatterpolar.marker.Gradie
nt` instance or dict with compatible properties
line
:class:`plotly.graph_objects.scatterpolar.marker.Line`
instance or dict with compatible properties
maxdisplayed
Sets a maximum number of points to be drawn on the
graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud for
opacity .
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.color`is set to a numerical array. If
true, `marker.cmin` will correspond to the last color
in the array and `marker.cmax` will correspond to the
first color.
showscale
Determines whether or not a colorbar is displayed for
this trace. Has an effect only if in `marker.color`is
set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px) of the
rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the data in
`size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points. Use with
`sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
symbol
Sets the marker symbol type. Adding 100 is equivalent
to appending "-open" to a symbol name. Adding 200 is
equivalent to appending "-dot" to a symbol name. Adding
300 is equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud for
symbol .
Returns
-------
Marker
|
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterpolar.Marker`
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in
`marker.color`is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in `marker.color`)
or the bounds set in `marker.cmin` and `marker.cmax`
Has an effect only if in `marker.color`is set to a
numerical array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.cmin` and/or `marker.cmax` to be equidistant to
this point. Has an effect only if in `marker.color`is
set to a numerical array. Value should have the same
units as in `marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmax` must be set as well.
color
Sets themarkercolor. It accepts either a specific color
or an array of numbers that are mapped to the
colorscale relative to the max and min values of the
array or relative to `marker.cmin` and `marker.cmax` if
set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorbar
:class:`plotly.graph_objects.scatterpolar.marker.ColorB
ar` instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color`is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use`marker.cmin` and `marker.cmax`. Alternatively,
`colorscale` may be a palette name string of the
following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu
,Reds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,E
arth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
gradient
:class:`plotly.graph_objects.scatterpolar.marker.Gradie
nt` instance or dict with compatible properties
line
:class:`plotly.graph_objects.scatterpolar.marker.Line`
instance or dict with compatible properties
maxdisplayed
Sets a maximum number of points to be drawn on the
graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud for
opacity .
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.color`is set to a numerical array. If
true, `marker.cmin` will correspond to the last color
in the array and `marker.cmax` will correspond to the
first color.
showscale
Determines whether or not a colorbar is displayed for
this trace. Has an effect only if in `marker.color`is
set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px) of the
rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the data in
`size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points. Use with
`sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
symbol
Sets the marker symbol type. Adding 100 is equivalent
to appending "-open" to a symbol name. Adding 200 is
equivalent to appending "-dot" to a symbol name. Adding
300 is equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud for
symbol . | def __init__(
self,
arg=None,
autocolorscale=None,
cauto=None,
cmax=None,
cmid=None,
cmin=None,
color=None,
coloraxis=None,
colorbar=None,
colorscale=None,
colorsrc=None,
gradient=None,
line=None,
maxdisplayed=None,
opacity=None,
opacitysrc=None,
reversescale=None,
showscale=None,
size=None,
sizemin=None,
sizemode=None,
sizeref=None,
sizesrc=None,
symbol=None,
symbolsrc=None,
**kwargs
):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterpolar.Marker`
autocolorscale
Determines whether the colorscale is a default palette
(`autocolorscale: true`) or the palette determined by
`marker.colorscale`. Has an effect only if in
`marker.color`is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is
true, the default palette will be chosen according to
whether numbers in the `color` array are all positive,
all negative or mixed.
cauto
Determines whether or not the color domain is computed
with respect to the input data (here in `marker.color`)
or the bounds set in `marker.cmin` and `marker.cmax`
Has an effect only if in `marker.color`is set to a
numerical array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has an effect
only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by scaling
`marker.cmin` and/or `marker.cmax` to be equidistant to
this point. Has an effect only if in `marker.color`is
set to a numerical array. Value should have the same
units as in `marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has an effect
only if in `marker.color`is set to a numerical array.
Value should have the same units as in `marker.color`
and if set, `marker.cmax` must be set as well.
color
Sets themarkercolor. It accepts either a specific color
or an array of numbers that are mapped to the
colorscale relative to the max and min values of the
array or relative to `marker.cmin` and `marker.cmax` if
set.
coloraxis
Sets a reference to a shared color axis. References to
these shared color axes are "coloraxis", "coloraxis2",
"coloraxis3", etc. Settings for these shared color axes
are set in the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple color
scales can be linked to the same color axis.
colorbar
:class:`plotly.graph_objects.scatterpolar.marker.ColorB
ar` instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color`is set to a numerical array. The
colorscale must be an array containing arrays mapping a
normalized value to an rgb, rgba, hex, hsl, hsv, or
named color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required. For
example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in color space,
use`marker.cmin` and `marker.cmax`. Alternatively,
`colorscale` may be a palette name string of the
following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu
,Reds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,E
arth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
gradient
:class:`plotly.graph_objects.scatterpolar.marker.Gradie
nt` instance or dict with compatible properties
line
:class:`plotly.graph_objects.scatterpolar.marker.Line`
instance or dict with compatible properties
maxdisplayed
Sets a maximum number of points to be drawn on the
graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud for
opacity .
reversescale
Reverses the color mapping if true. Has an effect only
if in `marker.color`is set to a numerical array. If
true, `marker.cmin` will correspond to the last color
in the array and `marker.cmax` will correspond to the
first color.
showscale
Determines whether or not a colorbar is displayed for
this trace. Has an effect only if in `marker.color`is
set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px) of the
rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the data in
`size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points. Use with
`sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
symbol
Sets the marker symbol type. Adding 100 is equivalent
to appending "-open" to a symbol name. Adding 200 is
equivalent to appending "-dot" to a symbol name. Adding
300 is equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud for
symbol .
Returns
-------
Marker
"""
super(Marker, self).__init__("marker")
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.scatterpolar.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterpolar.Marker`"""
)
# 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("autocolorscale", None)
_v = autocolorscale if autocolorscale is not None else _v
if _v is not None:
self["autocolorscale"] = _v
_v = arg.pop("cauto", None)
_v = cauto if cauto is not None else _v
if _v is not None:
self["cauto"] = _v
_v = arg.pop("cmax", None)
_v = cmax if cmax is not None else _v
if _v is not None:
self["cmax"] = _v
_v = arg.pop("cmid", None)
_v = cmid if cmid is not None else _v
if _v is not None:
self["cmid"] = _v
_v = arg.pop("cmin", None)
_v = cmin if cmin is not None else _v
if _v is not None:
self["cmin"] = _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("coloraxis", None)
_v = coloraxis if coloraxis is not None else _v
if _v is not None:
self["coloraxis"] = _v
_v = arg.pop("colorbar", None)
_v = colorbar if colorbar is not None else _v
if _v is not None:
self["colorbar"] = _v
_v = arg.pop("colorscale", None)
_v = colorscale if colorscale is not None else _v
if _v is not None:
self["colorscale"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("gradient", None)
_v = gradient if gradient is not None else _v
if _v is not None:
self["gradient"] = _v
_v = arg.pop("line", None)
_v = line if line is not None else _v
if _v is not None:
self["line"] = _v
_v = arg.pop("maxdisplayed", None)
_v = maxdisplayed if maxdisplayed is not None else _v
if _v is not None:
self["maxdisplayed"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("opacitysrc", None)
_v = opacitysrc if opacitysrc is not None else _v
if _v is not None:
self["opacitysrc"] = _v
_v = arg.pop("reversescale", None)
_v = reversescale if reversescale is not None else _v
if _v is not None:
self["reversescale"] = _v
_v = arg.pop("showscale", None)
_v = showscale if showscale is not None else _v
if _v is not None:
self["showscale"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizemin", None)
_v = sizemin if sizemin is not None else _v
if _v is not None:
self["sizemin"] = _v
_v = arg.pop("sizemode", None)
_v = sizemode if sizemode is not None else _v
if _v is not None:
self["sizemode"] = _v
_v = arg.pop("sizeref", None)
_v = sizeref if sizeref is not None else _v
if _v is not None:
self["sizeref"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
_v = arg.pop("symbol", None)
_v = symbol if symbol is not None else _v
if _v is not None:
self["symbol"] = _v
_v = arg.pop("symbolsrc", None)
_v = symbolsrc if symbolsrc is not None else _v
if _v is not None:
self["symbolsrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"autocolorscale",
"=",
"None",
",",
"cauto",
"=",
"None",
",",
"cmax",
"=",
"None",
",",
"cmid",
"=",
"None",
",",
"cmin",
"=",
"None",
",",
"color",
"=",
"None",
",",
"coloraxis",
"=",
"None",
",",
"colorbar",
"=",
"None",
",",
"colorscale",
"=",
"None",
",",
"colorsrc",
"=",
"None",
",",
"gradient",
"=",
"None",
",",
"line",
"=",
"None",
",",
"maxdisplayed",
"=",
"None",
",",
"opacity",
"=",
"None",
",",
"opacitysrc",
"=",
"None",
",",
"reversescale",
"=",
"None",
",",
"showscale",
"=",
"None",
",",
"size",
"=",
"None",
",",
"sizemin",
"=",
"None",
",",
"sizemode",
"=",
"None",
",",
"sizeref",
"=",
"None",
",",
"sizesrc",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"symbolsrc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Marker",
",",
"self",
")",
".",
"__init__",
"(",
"\"marker\"",
")",
"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.scatterpolar.Marker \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatterpolar.Marker`\"\"\"",
")",
"# 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",
"(",
"\"autocolorscale\"",
",",
"None",
")",
"_v",
"=",
"autocolorscale",
"if",
"autocolorscale",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"autocolorscale\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"cauto\"",
",",
"None",
")",
"_v",
"=",
"cauto",
"if",
"cauto",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"cauto\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"cmax\"",
",",
"None",
")",
"_v",
"=",
"cmax",
"if",
"cmax",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"cmax\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"cmid\"",
",",
"None",
")",
"_v",
"=",
"cmid",
"if",
"cmid",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"cmid\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"cmin\"",
",",
"None",
")",
"_v",
"=",
"cmin",
"if",
"cmin",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"cmin\"",
"]",
"=",
"_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",
"(",
"\"coloraxis\"",
",",
"None",
")",
"_v",
"=",
"coloraxis",
"if",
"coloraxis",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"coloraxis\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"colorbar\"",
",",
"None",
")",
"_v",
"=",
"colorbar",
"if",
"colorbar",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"colorbar\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"colorscale\"",
",",
"None",
")",
"_v",
"=",
"colorscale",
"if",
"colorscale",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"colorscale\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"colorsrc\"",
",",
"None",
")",
"_v",
"=",
"colorsrc",
"if",
"colorsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"colorsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"gradient\"",
",",
"None",
")",
"_v",
"=",
"gradient",
"if",
"gradient",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"gradient\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"line\"",
",",
"None",
")",
"_v",
"=",
"line",
"if",
"line",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"line\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"maxdisplayed\"",
",",
"None",
")",
"_v",
"=",
"maxdisplayed",
"if",
"maxdisplayed",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"maxdisplayed\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"opacity\"",
",",
"None",
")",
"_v",
"=",
"opacity",
"if",
"opacity",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"opacity\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"opacitysrc\"",
",",
"None",
")",
"_v",
"=",
"opacitysrc",
"if",
"opacitysrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"opacitysrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"reversescale\"",
",",
"None",
")",
"_v",
"=",
"reversescale",
"if",
"reversescale",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"reversescale\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"showscale\"",
",",
"None",
")",
"_v",
"=",
"showscale",
"if",
"showscale",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"showscale\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizemin\"",
",",
"None",
")",
"_v",
"=",
"sizemin",
"if",
"sizemin",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizemin\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizemode\"",
",",
"None",
")",
"_v",
"=",
"sizemode",
"if",
"sizemode",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizemode\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizeref\"",
",",
"None",
")",
"_v",
"=",
"sizeref",
"if",
"sizeref",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizeref\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizesrc\"",
",",
"None",
")",
"_v",
"=",
"sizesrc",
"if",
"sizesrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizesrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"symbol\"",
",",
"None",
")",
"_v",
"=",
"symbol",
"if",
"symbol",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"symbol\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"symbolsrc\"",
",",
"None",
")",
"_v",
"=",
"symbolsrc",
"if",
"symbolsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"symbolsrc\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
1152,
4
] | [
1444,
34
] | python | en | ['en', 'error', 'th'] | False |
Seq2SeqModel.get_batch | (self, data, decoding=False) |
:param data:
:param decoding: set this parameter to True to output dummy
data for the decoder side (using the maximum output size)
:return:
|
:param data:
:param decoding: set this parameter to True to output dummy
data for the decoder side (using the maximum output size)
:return:
| def get_batch(self, data, decoding=False):
"""
:param data:
:param decoding: set this parameter to True to output dummy
data for the decoder side (using the maximum output size)
:return:
"""
inputs = [[] for _ in self.encoders]
targets = [[] for _ in self.decoders]
input_length = [[] for _ in self.encoders]
# maximum input length of each encoder in this batch
max_input_len = [max(len(data_[i]) for data_ in data) for i in range(len(self.encoders))]
if self.max_input_len is not None:
max_input_len = [min(len_, max_len) for len_, max_len in zip(max_input_len, self.max_input_len)]
# maximum output length in this batch
if decoding:
max_output_len = self.max_output_len
else:
max_output_len = [max(len(data_[i]) for data_ in data)
for i in range(len(self.encoders), len(self.encoders) + len(self.decoders))]
if self.max_output_len is not None:
max_output_len = [min(len_, max_len) for len_, max_len in zip(max_output_len, self.max_output_len)]
for sentences in data:
src_sentences = sentences[:len(self.encoders)]
trg_sentences = sentences[len(self.encoders):]
for i, (encoder, src_sentence) in enumerate(zip(self.encoders, src_sentences)):
src_sentence = src_sentence[:max_input_len[i]]
pad_symbol = np.zeros(encoder.embedding_size, dtype=np.float32) if encoder.binary else utils.EOS_ID
# pad sequences so that all sequences in the same batch have the same length
eos = 0 if encoder.binary else 1 # end of sentence marker for non-binary input
encoder_pad = [pad_symbol] * (eos + max_input_len[i] - len(src_sentence))
if self.reverse_input:
src_sentence = src_sentence[::-1]
inputs[i].append(src_sentence + encoder_pad)
input_length[i].append(len(src_sentence) + eos)
for i in range(len(self.decoders)):
if decoding:
targets[i].append([utils.BOS_ID] * self.max_output_len[i] + [utils.EOS_ID])
else:
trg_sentence = trg_sentences[i][:max_output_len[i]]
decoder_pad_size = max_output_len[i] - len(trg_sentence) + 1
trg_sentence = [utils.BOS_ID] + trg_sentence + [utils.EOS_ID] * decoder_pad_size
targets[i].append(trg_sentence)
# convert lists to numpy arrays
inputs = [np.array(inputs_, dtype=np.float32 if encoder.binary else np.int32)
for encoder, inputs_ in zip(self.encoders, inputs)]
# starts with BOS and ends with EOS
targets = [np.array(targets_, dtype=np.int32) for targets_ in targets]
input_length = [np.array(input_length_, dtype=np.int32) for input_length_ in input_length]
return inputs, targets, input_length | [
"def",
"get_batch",
"(",
"self",
",",
"data",
",",
"decoding",
"=",
"False",
")",
":",
"inputs",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"self",
".",
"encoders",
"]",
"targets",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"self",
".",
"decoders",
"]",
"input_length",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"self",
".",
"encoders",
"]",
"# maximum input length of each encoder in this batch",
"max_input_len",
"=",
"[",
"max",
"(",
"len",
"(",
"data_",
"[",
"i",
"]",
")",
"for",
"data_",
"in",
"data",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"encoders",
")",
")",
"]",
"if",
"self",
".",
"max_input_len",
"is",
"not",
"None",
":",
"max_input_len",
"=",
"[",
"min",
"(",
"len_",
",",
"max_len",
")",
"for",
"len_",
",",
"max_len",
"in",
"zip",
"(",
"max_input_len",
",",
"self",
".",
"max_input_len",
")",
"]",
"# maximum output length in this batch",
"if",
"decoding",
":",
"max_output_len",
"=",
"self",
".",
"max_output_len",
"else",
":",
"max_output_len",
"=",
"[",
"max",
"(",
"len",
"(",
"data_",
"[",
"i",
"]",
")",
"for",
"data_",
"in",
"data",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"encoders",
")",
",",
"len",
"(",
"self",
".",
"encoders",
")",
"+",
"len",
"(",
"self",
".",
"decoders",
")",
")",
"]",
"if",
"self",
".",
"max_output_len",
"is",
"not",
"None",
":",
"max_output_len",
"=",
"[",
"min",
"(",
"len_",
",",
"max_len",
")",
"for",
"len_",
",",
"max_len",
"in",
"zip",
"(",
"max_output_len",
",",
"self",
".",
"max_output_len",
")",
"]",
"for",
"sentences",
"in",
"data",
":",
"src_sentences",
"=",
"sentences",
"[",
":",
"len",
"(",
"self",
".",
"encoders",
")",
"]",
"trg_sentences",
"=",
"sentences",
"[",
"len",
"(",
"self",
".",
"encoders",
")",
":",
"]",
"for",
"i",
",",
"(",
"encoder",
",",
"src_sentence",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"self",
".",
"encoders",
",",
"src_sentences",
")",
")",
":",
"src_sentence",
"=",
"src_sentence",
"[",
":",
"max_input_len",
"[",
"i",
"]",
"]",
"pad_symbol",
"=",
"np",
".",
"zeros",
"(",
"encoder",
".",
"embedding_size",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"if",
"encoder",
".",
"binary",
"else",
"utils",
".",
"EOS_ID",
"# pad sequences so that all sequences in the same batch have the same length",
"eos",
"=",
"0",
"if",
"encoder",
".",
"binary",
"else",
"1",
"# end of sentence marker for non-binary input",
"encoder_pad",
"=",
"[",
"pad_symbol",
"]",
"*",
"(",
"eos",
"+",
"max_input_len",
"[",
"i",
"]",
"-",
"len",
"(",
"src_sentence",
")",
")",
"if",
"self",
".",
"reverse_input",
":",
"src_sentence",
"=",
"src_sentence",
"[",
":",
":",
"-",
"1",
"]",
"inputs",
"[",
"i",
"]",
".",
"append",
"(",
"src_sentence",
"+",
"encoder_pad",
")",
"input_length",
"[",
"i",
"]",
".",
"append",
"(",
"len",
"(",
"src_sentence",
")",
"+",
"eos",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"decoders",
")",
")",
":",
"if",
"decoding",
":",
"targets",
"[",
"i",
"]",
".",
"append",
"(",
"[",
"utils",
".",
"BOS_ID",
"]",
"*",
"self",
".",
"max_output_len",
"[",
"i",
"]",
"+",
"[",
"utils",
".",
"EOS_ID",
"]",
")",
"else",
":",
"trg_sentence",
"=",
"trg_sentences",
"[",
"i",
"]",
"[",
":",
"max_output_len",
"[",
"i",
"]",
"]",
"decoder_pad_size",
"=",
"max_output_len",
"[",
"i",
"]",
"-",
"len",
"(",
"trg_sentence",
")",
"+",
"1",
"trg_sentence",
"=",
"[",
"utils",
".",
"BOS_ID",
"]",
"+",
"trg_sentence",
"+",
"[",
"utils",
".",
"EOS_ID",
"]",
"*",
"decoder_pad_size",
"targets",
"[",
"i",
"]",
".",
"append",
"(",
"trg_sentence",
")",
"# convert lists to numpy arrays",
"inputs",
"=",
"[",
"np",
".",
"array",
"(",
"inputs_",
",",
"dtype",
"=",
"np",
".",
"float32",
"if",
"encoder",
".",
"binary",
"else",
"np",
".",
"int32",
")",
"for",
"encoder",
",",
"inputs_",
"in",
"zip",
"(",
"self",
".",
"encoders",
",",
"inputs",
")",
"]",
"# starts with BOS and ends with EOS",
"targets",
"=",
"[",
"np",
".",
"array",
"(",
"targets_",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"for",
"targets_",
"in",
"targets",
"]",
"input_length",
"=",
"[",
"np",
".",
"array",
"(",
"input_length_",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"for",
"input_length_",
"in",
"input_length",
"]",
"return",
"inputs",
",",
"targets",
",",
"input_length"
] | [
274,
4
] | [
334,
44
] | python | en | ['en', 'error', 'th'] | False |
presentation | () |
Template that increases the size of text and markers/lines for certain
trace types
|
Template that increases the size of text and markers/lines for certain
trace types
| def presentation():
"""
Template that increases the size of text and markers/lines for certain
trace types
"""
# Create blank template
template = Template()
template.layout.xaxis.title.standoff = 15
template.layout.yaxis.title.standoff = 15
# Increase global font size by 1.5x (12->18)
template.layout.font.size = 18
# Increase scatter markers and lines by 1.5x
opts = {"marker": {"size": 9}, "line": {"width": 3}}
template.data.scatter = [opts]
template.data.scattergl = [opts]
template.data.scatter3d = [opts]
template.data.scatterpolar = [opts]
template.data.scatterpolargl = [opts]
template.data.scatterternary = [opts]
template.data.scattergeo = [opts]
# Increase default height of table cells
template.data.table = [{"header": {"height": 36}, "cells": {"height": 30}}]
# Automargin for pie chart
template.data.pie = [{"automargin": True}]
return template | [
"def",
"presentation",
"(",
")",
":",
"# Create blank template",
"template",
"=",
"Template",
"(",
")",
"template",
".",
"layout",
".",
"xaxis",
".",
"title",
".",
"standoff",
"=",
"15",
"template",
".",
"layout",
".",
"yaxis",
".",
"title",
".",
"standoff",
"=",
"15",
"# Increase global font size by 1.5x (12->18)",
"template",
".",
"layout",
".",
"font",
".",
"size",
"=",
"18",
"# Increase scatter markers and lines by 1.5x",
"opts",
"=",
"{",
"\"marker\"",
":",
"{",
"\"size\"",
":",
"9",
"}",
",",
"\"line\"",
":",
"{",
"\"width\"",
":",
"3",
"}",
"}",
"template",
".",
"data",
".",
"scatter",
"=",
"[",
"opts",
"]",
"template",
".",
"data",
".",
"scattergl",
"=",
"[",
"opts",
"]",
"template",
".",
"data",
".",
"scatter3d",
"=",
"[",
"opts",
"]",
"template",
".",
"data",
".",
"scatterpolar",
"=",
"[",
"opts",
"]",
"template",
".",
"data",
".",
"scatterpolargl",
"=",
"[",
"opts",
"]",
"template",
".",
"data",
".",
"scatterternary",
"=",
"[",
"opts",
"]",
"template",
".",
"data",
".",
"scattergeo",
"=",
"[",
"opts",
"]",
"# Increase default height of table cells",
"template",
".",
"data",
".",
"table",
"=",
"[",
"{",
"\"header\"",
":",
"{",
"\"height\"",
":",
"36",
"}",
",",
"\"cells\"",
":",
"{",
"\"height\"",
":",
"30",
"}",
"}",
"]",
"# Automargin for pie chart",
"template",
".",
"data",
".",
"pie",
"=",
"[",
"{",
"\"automargin\"",
":",
"True",
"}",
"]",
"return",
"template"
] | [
592,
0
] | [
622,
19
] | python | en | ['en', 'error', 'th'] | False |
xgridoff | () |
Template to disable x-grid by default
|
Template to disable x-grid by default
| def xgridoff():
"""
Template to disable x-grid by default
"""
# Create blank template
template = Template()
template.layout.xaxis.showgrid = False
template.layout.xaxis.title.standoff = 15
template.layout.yaxis.title.standoff = 15
# Automargin for pie chart
template.data.pie = [{"automargin": True}]
return template | [
"def",
"xgridoff",
"(",
")",
":",
"# Create blank template",
"template",
"=",
"Template",
"(",
")",
"template",
".",
"layout",
".",
"xaxis",
".",
"showgrid",
"=",
"False",
"template",
".",
"layout",
".",
"xaxis",
".",
"title",
".",
"standoff",
"=",
"15",
"template",
".",
"layout",
".",
"yaxis",
".",
"title",
".",
"standoff",
"=",
"15",
"# Automargin for pie chart",
"template",
".",
"data",
".",
"pie",
"=",
"[",
"{",
"\"automargin\"",
":",
"True",
"}",
"]",
"return",
"template"
] | [
628,
0
] | [
641,
19
] | python | en | ['en', 'error', 'th'] | False |
ygridoff | () |
Template to disable y-grid by default
|
Template to disable y-grid by default
| def ygridoff():
"""
Template to disable y-grid by default
"""
# Create blank template
template = Template()
template.layout.yaxis.showgrid = False
# Automargin for pie chart
template.data.pie = [{"automargin": True}]
return template | [
"def",
"ygridoff",
"(",
")",
":",
"# Create blank template",
"template",
"=",
"Template",
"(",
")",
"template",
".",
"layout",
".",
"yaxis",
".",
"showgrid",
"=",
"False",
"# Automargin for pie chart",
"template",
".",
"data",
".",
"pie",
"=",
"[",
"{",
"\"automargin\"",
":",
"True",
"}",
"]",
"return",
"template"
] | [
647,
0
] | [
658,
19
] | python | en | ['en', 'error', 'th'] | False |
gridon | () |
Template to enable x and y-grid by default
|
Template to enable x and y-grid by default
| def gridon():
"""
Template to enable x and y-grid by default
"""
# Create blank template
template = Template()
template.layout.xaxis.showgrid = True
template.layout.xaxis.title.standoff = 15
template.layout.yaxis.showgrid = True
template.layout.yaxis.title.standoff = 15
# Automargin for pie chart
template.data.pie = [{"automargin": True}]
return template | [
"def",
"gridon",
"(",
")",
":",
"# Create blank template",
"template",
"=",
"Template",
"(",
")",
"template",
".",
"layout",
".",
"xaxis",
".",
"showgrid",
"=",
"True",
"template",
".",
"layout",
".",
"xaxis",
".",
"title",
".",
"standoff",
"=",
"15",
"template",
".",
"layout",
".",
"yaxis",
".",
"showgrid",
"=",
"True",
"template",
".",
"layout",
".",
"yaxis",
".",
"title",
".",
"standoff",
"=",
"15",
"# Automargin for pie chart",
"template",
".",
"data",
".",
"pie",
"=",
"[",
"{",
"\"automargin\"",
":",
"True",
"}",
"]",
"return",
"template"
] | [
664,
0
] | [
678,
19
] | python | en | ['en', 'error', 'th'] | False |
TestUpdateMethod.test_update_uninitialized_list_with_list | (self) |
If the original list is undefined, the updated list should be
accepted in full.
See GH1072
|
If the original list is undefined, the updated list should be
accepted in full. | def test_update_uninitialized_list_with_list(self):
"""
If the original list is undefined, the updated list should be
accepted in full.
See GH1072
"""
layout = go.Layout()
layout.update(
annotations=[
go.layout.Annotation(text="one"),
go.layout.Annotation(text="two"),
]
)
expected = {"annotations": [{"text": "one"}, {"text": "two"}]}
self.assertEqual(len(layout.annotations), 2)
self.assertEqual(layout.to_plotly_json(), expected) | [
"def",
"test_update_uninitialized_list_with_list",
"(",
"self",
")",
":",
"layout",
"=",
"go",
".",
"Layout",
"(",
")",
"layout",
".",
"update",
"(",
"annotations",
"=",
"[",
"go",
".",
"layout",
".",
"Annotation",
"(",
"text",
"=",
"\"one\"",
")",
",",
"go",
".",
"layout",
".",
"Annotation",
"(",
"text",
"=",
"\"two\"",
")",
",",
"]",
")",
"expected",
"=",
"{",
"\"annotations\"",
":",
"[",
"{",
"\"text\"",
":",
"\"one\"",
"}",
",",
"{",
"\"text\"",
":",
"\"two\"",
"}",
"]",
"}",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"layout",
".",
"annotations",
")",
",",
"2",
")",
"self",
".",
"assertEqual",
"(",
"layout",
".",
"to_plotly_json",
"(",
")",
",",
"expected",
")"
] | [
69,
4
] | [
87,
59
] | python | en | ['en', 'error', 'th'] | False |
TestUpdateMethod.test_update_initialized_empty_list_with_list | (self) |
If the original list is empty, treat is just as if it's undefined.
This is a change in behavior from version 2
(where the input list would just be completly ignored), because
in version 3 the difference between an uninitialized and empty list
is not obvious to the user.
|
If the original list is empty, treat is just as if it's undefined.
This is a change in behavior from version 2
(where the input list would just be completly ignored), because
in version 3 the difference between an uninitialized and empty list
is not obvious to the user.
| def test_update_initialized_empty_list_with_list(self):
"""
If the original list is empty, treat is just as if it's undefined.
This is a change in behavior from version 2
(where the input list would just be completly ignored), because
in version 3 the difference between an uninitialized and empty list
is not obvious to the user.
"""
layout = go.Layout(annotations=[])
layout.update(
annotations=[
go.layout.Annotation(text="one"),
go.layout.Annotation(text="two"),
]
)
expected = {"annotations": [{"text": "one"}, {"text": "two"}]}
self.assertEqual(len(layout.annotations), 2)
self.assertEqual(layout.to_plotly_json(), expected) | [
"def",
"test_update_initialized_empty_list_with_list",
"(",
"self",
")",
":",
"layout",
"=",
"go",
".",
"Layout",
"(",
"annotations",
"=",
"[",
"]",
")",
"layout",
".",
"update",
"(",
"annotations",
"=",
"[",
"go",
".",
"layout",
".",
"Annotation",
"(",
"text",
"=",
"\"one\"",
")",
",",
"go",
".",
"layout",
".",
"Annotation",
"(",
"text",
"=",
"\"two\"",
")",
",",
"]",
")",
"expected",
"=",
"{",
"\"annotations\"",
":",
"[",
"{",
"\"text\"",
":",
"\"one\"",
"}",
",",
"{",
"\"text\"",
":",
"\"two\"",
"}",
"]",
"}",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"layout",
".",
"annotations",
")",
",",
"2",
")",
"self",
".",
"assertEqual",
"(",
"layout",
".",
"to_plotly_json",
"(",
")",
",",
"expected",
")"
] | [
89,
4
] | [
108,
59
] | python | en | ['en', 'error', 'th'] | False |
TestUpdateMethod.test_update_initialized_nonempty_list_with_dict | (self) |
If the original list is defined, a dict from
index numbers to property dicts may be used to update select
elements of the existing list
|
If the original list is defined, a dict from
index numbers to property dicts may be used to update select
elements of the existing list
| def test_update_initialized_nonempty_list_with_dict(self):
"""
If the original list is defined, a dict from
index numbers to property dicts may be used to update select
elements of the existing list
"""
layout = go.Layout(
annotations=[
go.layout.Annotation(text="one"),
go.layout.Annotation(text="two"),
]
)
layout.update(annotations={1: go.layout.Annotation(width=30)})
expected = {"annotations": [{"text": "one"}, {"text": "two", "width": 30}]}
self.assertEqual(len(layout.annotations), 2)
self.assertEqual(layout.to_plotly_json(), expected) | [
"def",
"test_update_initialized_nonempty_list_with_dict",
"(",
"self",
")",
":",
"layout",
"=",
"go",
".",
"Layout",
"(",
"annotations",
"=",
"[",
"go",
".",
"layout",
".",
"Annotation",
"(",
"text",
"=",
"\"one\"",
")",
",",
"go",
".",
"layout",
".",
"Annotation",
"(",
"text",
"=",
"\"two\"",
")",
",",
"]",
")",
"layout",
".",
"update",
"(",
"annotations",
"=",
"{",
"1",
":",
"go",
".",
"layout",
".",
"Annotation",
"(",
"width",
"=",
"30",
")",
"}",
")",
"expected",
"=",
"{",
"\"annotations\"",
":",
"[",
"{",
"\"text\"",
":",
"\"one\"",
"}",
",",
"{",
"\"text\"",
":",
"\"two\"",
",",
"\"width\"",
":",
"30",
"}",
"]",
"}",
"self",
".",
"assertEqual",
"(",
"len",
"(",
"layout",
".",
"annotations",
")",
",",
"2",
")",
"self",
".",
"assertEqual",
"(",
"layout",
".",
"to_plotly_json",
"(",
")",
",",
"expected",
")"
] | [
110,
4
] | [
128,
59
] | python | en | ['en', 'error', 'th'] | False |
main | (opt) |
Converts a Fbdialog file of episodes into two self-feeding files (split by topic)
All conversations including a word in the provided topic's bag of words will be
separated from conversations without those words.
|
Converts a Fbdialog file of episodes into two self-feeding files (split by topic) | def main(opt):
"""
Converts a Fbdialog file of episodes into two self-feeding files (split by topic)
All conversations including a word in the provided topic's bag of words will be
separated from conversations without those words.
"""
on_topic_exs = []
off_topic_exs = []
num_episodes = 0
for episode in extract_fb_episodes(opt['infile']):
num_episodes += 1
if opt['min_unit'] == 'episode':
if includes_topic(episode, TOPIC):
on_topic_exs.extend(episode_to_examples(episode, opt['history_size']))
else:
off_topic_exs.extend(episode_to_examples(episode, opt['history_size']))
elif opt['min_unit'] == 'example':
for example in episode_to_examples(episode, opt['history_size']):
if includes_topic([example], TOPIC):
on_topic_exs.append(example)
else:
off_topic_exs.append(example)
if opt['shuffle']:
random.shuffle(on_topic_exs)
random.shuffle(off_topic_exs)
total = len(on_topic_exs) + len(off_topic_exs)
on_pct = len(on_topic_exs) / total
print(
f"Separated {total} examples (from {num_episodes} episodes) into "
f"{len(off_topic_exs)} off-topic and {len(on_topic_exs)} "
f"({on_pct * 100:.1f}%) on-topic"
)
outfile_base, outfile_ext = os.path.splitext(opt['outfile'])
unit_prefix = opt['min_unit'][:3]
topic_prefix = TOPIC_NAME[:3]
on_topic_filename = f"{outfile_base}_{unit_prefix}_{topic_prefix}{outfile_ext}"
with PathManager.open(on_topic_filename, 'w') as outfile:
for ex in on_topic_exs:
outfile.write(json.dumps(ex.to_dict()) + '\n')
off_topic_filename = f"{outfile_base}_{unit_prefix}_no{topic_prefix}{outfile_ext}"
with PathManager.open(off_topic_filename, 'w') as outfile:
for ex in off_topic_exs:
outfile.write(json.dumps(ex.to_dict()) + '\n') | [
"def",
"main",
"(",
"opt",
")",
":",
"on_topic_exs",
"=",
"[",
"]",
"off_topic_exs",
"=",
"[",
"]",
"num_episodes",
"=",
"0",
"for",
"episode",
"in",
"extract_fb_episodes",
"(",
"opt",
"[",
"'infile'",
"]",
")",
":",
"num_episodes",
"+=",
"1",
"if",
"opt",
"[",
"'min_unit'",
"]",
"==",
"'episode'",
":",
"if",
"includes_topic",
"(",
"episode",
",",
"TOPIC",
")",
":",
"on_topic_exs",
".",
"extend",
"(",
"episode_to_examples",
"(",
"episode",
",",
"opt",
"[",
"'history_size'",
"]",
")",
")",
"else",
":",
"off_topic_exs",
".",
"extend",
"(",
"episode_to_examples",
"(",
"episode",
",",
"opt",
"[",
"'history_size'",
"]",
")",
")",
"elif",
"opt",
"[",
"'min_unit'",
"]",
"==",
"'example'",
":",
"for",
"example",
"in",
"episode_to_examples",
"(",
"episode",
",",
"opt",
"[",
"'history_size'",
"]",
")",
":",
"if",
"includes_topic",
"(",
"[",
"example",
"]",
",",
"TOPIC",
")",
":",
"on_topic_exs",
".",
"append",
"(",
"example",
")",
"else",
":",
"off_topic_exs",
".",
"append",
"(",
"example",
")",
"if",
"opt",
"[",
"'shuffle'",
"]",
":",
"random",
".",
"shuffle",
"(",
"on_topic_exs",
")",
"random",
".",
"shuffle",
"(",
"off_topic_exs",
")",
"total",
"=",
"len",
"(",
"on_topic_exs",
")",
"+",
"len",
"(",
"off_topic_exs",
")",
"on_pct",
"=",
"len",
"(",
"on_topic_exs",
")",
"/",
"total",
"print",
"(",
"f\"Separated {total} examples (from {num_episodes} episodes) into \"",
"f\"{len(off_topic_exs)} off-topic and {len(on_topic_exs)} \"",
"f\"({on_pct * 100:.1f}%) on-topic\"",
")",
"outfile_base",
",",
"outfile_ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"opt",
"[",
"'outfile'",
"]",
")",
"unit_prefix",
"=",
"opt",
"[",
"'min_unit'",
"]",
"[",
":",
"3",
"]",
"topic_prefix",
"=",
"TOPIC_NAME",
"[",
":",
"3",
"]",
"on_topic_filename",
"=",
"f\"{outfile_base}_{unit_prefix}_{topic_prefix}{outfile_ext}\"",
"with",
"PathManager",
".",
"open",
"(",
"on_topic_filename",
",",
"'w'",
")",
"as",
"outfile",
":",
"for",
"ex",
"in",
"on_topic_exs",
":",
"outfile",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"ex",
".",
"to_dict",
"(",
")",
")",
"+",
"'\\n'",
")",
"off_topic_filename",
"=",
"f\"{outfile_base}_{unit_prefix}_no{topic_prefix}{outfile_ext}\"",
"with",
"PathManager",
".",
"open",
"(",
"off_topic_filename",
",",
"'w'",
")",
"as",
"outfile",
":",
"for",
"ex",
"in",
"off_topic_exs",
":",
"outfile",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"ex",
".",
"to_dict",
"(",
")",
")",
"+",
"'\\n'",
")"
] | [
115,
0
] | [
161,
58
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.dtickrange | (self) |
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
|
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type | def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
"""
return self["dtickrange"] | [
"def",
"dtickrange",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"dtickrange\"",
"]"
] | [
15,
4
] | [
31,
33
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.enabled | (self) |
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False) | def enabled(self):
"""
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["enabled"] | [
"def",
"enabled",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"enabled\"",
"]"
] | [
40,
4
] | [
52,
30
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.name | (self) |
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def name(self):
"""
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"] | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"name\"",
"]"
] | [
61,
4
] | [
79,
27
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.templateitemname | (self) |
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def templateitemname(self):
"""
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["templateitemname"] | [
"def",
"templateitemname",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"templateitemname\"",
"]"
] | [
88,
4
] | [
107,
39
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.value | (self) |
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def value(self):
"""
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["value"] | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"value\"",
"]"
] | [
116,
4
] | [
129,
28
] | python | en | ['en', 'error', 'th'] | False |
Tickformatstop.__init__ | (
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs
) |
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterpolargl
.marker.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
|
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterpolargl
.marker.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat" | def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterpolargl
.marker.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super(Tickformatstop, self).__init__("tickformatstops")
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.scatterpolargl.marker.colorbar.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop`"""
)
# 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("dtickrange", None)
_v = dtickrange if dtickrange is not None else _v
if _v is not None:
self["dtickrange"] = _v
_v = arg.pop("enabled", None)
_v = enabled if enabled is not None else _v
if _v is not None:
self["enabled"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("value", None)
_v = value if value is not None else _v
if _v is not None:
self["value"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"dtickrange",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"name",
"=",
"None",
",",
"templateitemname",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Tickformatstop",
",",
"self",
")",
".",
"__init__",
"(",
"\"tickformatstops\"",
")",
"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.scatterpolargl.marker.colorbar.Tickformatstop \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop`\"\"\"",
")",
"# 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",
"(",
"\"dtickrange\"",
",",
"None",
")",
"_v",
"=",
"dtickrange",
"if",
"dtickrange",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"dtickrange\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"enabled\"",
",",
"None",
")",
"_v",
"=",
"enabled",
"if",
"enabled",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"enabled\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"name\"",
",",
"None",
")",
"_v",
"=",
"name",
"if",
"name",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"name\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"templateitemname\"",
",",
"None",
")",
"_v",
"=",
"templateitemname",
"if",
"templateitemname",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"templateitemname\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"value\"",
",",
"None",
")",
"_v",
"=",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"value\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
172,
4
] | [
282,
34
] | python | en | ['en', 'error', 'th'] | False |
is_iter | (iterable) |
Checks if an object behaves iterably.
Args:
iterable (any): Entity to check for iterability.
Returns:
is_iterable (bool): If `iterable` is iterable or not.
Notes:
Strings are *not* accepted as iterable (although they are
actually iterable), since string iterations are usually not
what we want to do with a string.
|
Checks if an object behaves iterably. | def is_iter(iterable):
"""
Checks if an object behaves iterably.
Args:
iterable (any): Entity to check for iterability.
Returns:
is_iterable (bool): If `iterable` is iterable or not.
Notes:
Strings are *not* accepted as iterable (although they are
actually iterable), since string iterations are usually not
what we want to do with a string.
"""
return hasattr(iterable, '__iter__') | [
"def",
"is_iter",
"(",
"iterable",
")",
":",
"return",
"hasattr",
"(",
"iterable",
",",
"'__iter__'",
")"
] | [
47,
0
] | [
63,
40
] | python | en | ['en', 'error', 'th'] | False |
make_iter | (obj) |
Makes sure that the object is always iterable.
Args:
obj (any): Object to make iterable.
Returns:
iterable (list or iterable): The same object
passed-through or made iterable.
|
Makes sure that the object is always iterable. | def make_iter(obj):
"""
Makes sure that the object is always iterable.
Args:
obj (any): Object to make iterable.
Returns:
iterable (list or iterable): The same object
passed-through or made iterable.
"""
return not hasattr(obj, '__iter__') and [obj] or obj | [
"def",
"make_iter",
"(",
"obj",
")",
":",
"return",
"not",
"hasattr",
"(",
"obj",
",",
"'__iter__'",
")",
"and",
"[",
"obj",
"]",
"or",
"obj"
] | [
66,
0
] | [
78,
56
] | python | en | ['en', 'error', 'th'] | False |
wrap | (text, width=None, indent=0) |
Safely wrap text to a certain number of characters.
Args:
text (str): The text to wrap.
width (int, optional): The number of characters to wrap to.
indent (int): How much to indent each line (with whitespace).
Returns:
text (str): Properly wrapped text.
|
Safely wrap text to a certain number of characters. | def wrap(text, width=None, indent=0):
"""
Safely wrap text to a certain number of characters.
Args:
text (str): The text to wrap.
width (int, optional): The number of characters to wrap to.
indent (int): How much to indent each line (with whitespace).
Returns:
text (str): Properly wrapped text.
"""
width = width if width else settings.CLIENT_DEFAULT_WIDTH
if not text:
return ""
text = to_unicode(text)
indent = " " * indent
return to_str(textwrap.fill(text, width, initial_indent=indent, subsequent_indent=indent)) | [
"def",
"wrap",
"(",
"text",
",",
"width",
"=",
"None",
",",
"indent",
"=",
"0",
")",
":",
"width",
"=",
"width",
"if",
"width",
"else",
"settings",
".",
"CLIENT_DEFAULT_WIDTH",
"if",
"not",
"text",
":",
"return",
"\"\"",
"text",
"=",
"to_unicode",
"(",
"text",
")",
"indent",
"=",
"\" \"",
"*",
"indent",
"return",
"to_str",
"(",
"textwrap",
".",
"fill",
"(",
"text",
",",
"width",
",",
"initial_indent",
"=",
"indent",
",",
"subsequent_indent",
"=",
"indent",
")",
")"
] | [
81,
0
] | [
99,
94
] | python | en | ['en', 'error', 'th'] | False |
pad | (text, width=None, align="c", fillchar=" ") |
Pads to a given width.
Args:
text (str): Text to pad.
width (int, optional): The width to pad to, in characters.
align (str, optional): This is one of 'c', 'l' or 'r' (center,
left or right).
fillchar (str, optional): The character to fill with.
Returns:
text (str): The padded text.
|
Pads to a given width. | def pad(text, width=None, align="c", fillchar=" "):
"""
Pads to a given width.
Args:
text (str): Text to pad.
width (int, optional): The width to pad to, in characters.
align (str, optional): This is one of 'c', 'l' or 'r' (center,
left or right).
fillchar (str, optional): The character to fill with.
Returns:
text (str): The padded text.
"""
width = width if width else settings.CLIENT_DEFAULT_WIDTH
align = align if align in ('c', 'l', 'r') else 'c'
fillchar = fillchar[0] if fillchar else " "
if align == 'l':
return text.ljust(width, fillchar)
elif align == 'r':
return text.rjust(width, fillchar)
else:
return text.center(width, fillchar) | [
"def",
"pad",
"(",
"text",
",",
"width",
"=",
"None",
",",
"align",
"=",
"\"c\"",
",",
"fillchar",
"=",
"\" \"",
")",
":",
"width",
"=",
"width",
"if",
"width",
"else",
"settings",
".",
"CLIENT_DEFAULT_WIDTH",
"align",
"=",
"align",
"if",
"align",
"in",
"(",
"'c'",
",",
"'l'",
",",
"'r'",
")",
"else",
"'c'",
"fillchar",
"=",
"fillchar",
"[",
"0",
"]",
"if",
"fillchar",
"else",
"\" \"",
"if",
"align",
"==",
"'l'",
":",
"return",
"text",
".",
"ljust",
"(",
"width",
",",
"fillchar",
")",
"elif",
"align",
"==",
"'r'",
":",
"return",
"text",
".",
"rjust",
"(",
"width",
",",
"fillchar",
")",
"else",
":",
"return",
"text",
".",
"center",
"(",
"width",
",",
"fillchar",
")"
] | [
106,
0
] | [
129,
43
] | python | en | ['en', 'error', 'th'] | False |
crop | (text, width=None, suffix="[...]") |
Crop text to a certain width, throwing away text from too-long
lines.
Args:
text (str): Text to crop.
width (int, optional): Width of line to crop, in characters.
suffix (str, optional): This is appended to the end of cropped
lines to show that the line actually continues. Cropping
will be done so that the suffix will also fit within the
given width. If width is too small to fit both crop and
suffix, the suffix will be dropped.
Returns:
text (str): The cropped text.
|
Crop text to a certain width, throwing away text from too-long
lines. | def crop(text, width=None, suffix="[...]"):
"""
Crop text to a certain width, throwing away text from too-long
lines.
Args:
text (str): Text to crop.
width (int, optional): Width of line to crop, in characters.
suffix (str, optional): This is appended to the end of cropped
lines to show that the line actually continues. Cropping
will be done so that the suffix will also fit within the
given width. If width is too small to fit both crop and
suffix, the suffix will be dropped.
Returns:
text (str): The cropped text.
"""
width = width if width else settings.CLIENT_DEFAULT_WIDTH
utext = to_unicode(text)
ltext = len(utext)
if ltext <= width:
return text
else:
lsuffix = len(suffix)
utext = utext[:width] if lsuffix >= width else "%s%s" % (utext[:width - lsuffix], suffix)
return to_str(utext) | [
"def",
"crop",
"(",
"text",
",",
"width",
"=",
"None",
",",
"suffix",
"=",
"\"[...]\"",
")",
":",
"width",
"=",
"width",
"if",
"width",
"else",
"settings",
".",
"CLIENT_DEFAULT_WIDTH",
"utext",
"=",
"to_unicode",
"(",
"text",
")",
"ltext",
"=",
"len",
"(",
"utext",
")",
"if",
"ltext",
"<=",
"width",
":",
"return",
"text",
"else",
":",
"lsuffix",
"=",
"len",
"(",
"suffix",
")",
"utext",
"=",
"utext",
"[",
":",
"width",
"]",
"if",
"lsuffix",
">=",
"width",
"else",
"\"%s%s\"",
"%",
"(",
"utext",
"[",
":",
"width",
"-",
"lsuffix",
"]",
",",
"suffix",
")",
"return",
"to_str",
"(",
"utext",
")"
] | [
132,
0
] | [
158,
28
] | python | en | ['en', 'error', 'th'] | False |
dedent | (text, baseline_index=None) |
Safely clean all whitespace at the left of a paragraph.
Args:
text (str): The text to dedent.
baseline_index (int or None, optional): Which row to use as a 'base'
for the indentation. Lines will be dedented to this level but
no further. If None, indent so as to completely deindent the
least indented text.
Returns:
text (str): Dedented string.
Notes:
This is useful for preserving triple-quoted string indentation
while still shifting it all to be next to the left edge of the
display.
|
Safely clean all whitespace at the left of a paragraph. | def dedent(text, baseline_index=None):
"""
Safely clean all whitespace at the left of a paragraph.
Args:
text (str): The text to dedent.
baseline_index (int or None, optional): Which row to use as a 'base'
for the indentation. Lines will be dedented to this level but
no further. If None, indent so as to completely deindent the
least indented text.
Returns:
text (str): Dedented string.
Notes:
This is useful for preserving triple-quoted string indentation
while still shifting it all to be next to the left edge of the
display.
"""
if not text:
return ""
if baseline_index is None:
return textwrap.dedent(text)
else:
lines = text.split('\n')
baseline = lines[baseline_index]
spaceremove = len(baseline) - len(baseline.lstrip(' '))
return "\n".join(line[min(spaceremove, len(line) - len(line.lstrip(' '))):]
for line in lines) | [
"def",
"dedent",
"(",
"text",
",",
"baseline_index",
"=",
"None",
")",
":",
"if",
"not",
"text",
":",
"return",
"\"\"",
"if",
"baseline_index",
"is",
"None",
":",
"return",
"textwrap",
".",
"dedent",
"(",
"text",
")",
"else",
":",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"baseline",
"=",
"lines",
"[",
"baseline_index",
"]",
"spaceremove",
"=",
"len",
"(",
"baseline",
")",
"-",
"len",
"(",
"baseline",
".",
"lstrip",
"(",
"' '",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"line",
"[",
"min",
"(",
"spaceremove",
",",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
"' '",
")",
")",
")",
":",
"]",
"for",
"line",
"in",
"lines",
")"
] | [
161,
0
] | [
190,
43
] | python | en | ['en', 'error', 'th'] | False |
justify | (text, width=None, align="f", indent=0) |
Fully justify a text so that it fits inside `width`. When using
full justification (default) this will be done by padding between
words with extra whitespace where necessary. Paragraphs will
be retained.
Args:
text (str): Text to justify.
width (int, optional): The length of each line, in characters.
align (str, optional): The alignment, 'l', 'c', 'r' or 'f'
for left, center, right or full justification respectively.
indent (int, optional): Number of characters indentation of
entire justified text block.
Returns:
justified (str): The justified and indented block of text.
|
Fully justify a text so that it fits inside `width`. When using
full justification (default) this will be done by padding between
words with extra whitespace where necessary. Paragraphs will
be retained. | def justify(text, width=None, align="f", indent=0):
"""
Fully justify a text so that it fits inside `width`. When using
full justification (default) this will be done by padding between
words with extra whitespace where necessary. Paragraphs will
be retained.
Args:
text (str): Text to justify.
width (int, optional): The length of each line, in characters.
align (str, optional): The alignment, 'l', 'c', 'r' or 'f'
for left, center, right or full justification respectively.
indent (int, optional): Number of characters indentation of
entire justified text block.
Returns:
justified (str): The justified and indented block of text.
"""
width = width if width else settings.CLIENT_DEFAULT_WIDTH
def _process_line(line):
"""
helper function that distributes extra spaces between words. The number
of gaps is nwords - 1 but must be at least 1 for single-word lines. We
distribute odd spaces randomly to one of the gaps.
"""
line_rest = width - (wlen + ngaps)
gap = " " # minimum gap between words
if line_rest > 0:
if align == 'l':
if line[-1] == "\n\n":
line[-1] = " " * (line_rest-1) + "\n" + " " * width + "\n" + " " * width
else:
line[-1] += " " * line_rest
elif align == 'r':
line[0] = " " * line_rest + line[0]
elif align == 'c':
pad = " " * (line_rest // 2)
line[0] = pad + line[0]
if line[-1] == "\n\n":
line[-1] += pad + " " * (line_rest % 2 - 1) + \
"\n" + " " * width + "\n" + " " * width
else:
line[-1] = line[-1] + pad + " " * (line_rest % 2)
else: # align 'f'
gap += " " * (line_rest // max(1, ngaps))
rest_gap = line_rest % max(1, ngaps)
for i in range(rest_gap):
line[i] += " "
elif not any(line):
return [" " * width]
return gap.join(line)
# split into paragraphs and words
paragraphs = re.split("\n\s*?\n", text, re.MULTILINE)
words = []
for ip, paragraph in enumerate(paragraphs):
if ip > 0:
words.append(("\n\n", 0))
words.extend((word, len(word)) for word in paragraph.split())
ngaps, wlen, line = 0, 0, []
lines = []
while words:
if not line:
# start a new line
word = words.pop(0)
wlen = word[1]
line.append(word[0])
elif (words[0][1] + wlen + ngaps) >= width:
# next word would exceed word length of line + smallest gaps
lines.append(_process_line(line))
ngaps, wlen, line = 0, 0, []
else:
# put a new word on the line
word = words.pop(0)
line.append(word[0])
if word[1] == 0:
# a new paragraph, process immediately
lines.append(_process_line(line))
ngaps, wlen, line = 0, 0, []
else:
wlen += word[1]
ngaps += 1
if line: # catch any line left behind
lines.append(_process_line(line))
indentstring = " " * indent
return "\n".join([indentstring + line for line in lines]) | [
"def",
"justify",
"(",
"text",
",",
"width",
"=",
"None",
",",
"align",
"=",
"\"f\"",
",",
"indent",
"=",
"0",
")",
":",
"width",
"=",
"width",
"if",
"width",
"else",
"settings",
".",
"CLIENT_DEFAULT_WIDTH",
"def",
"_process_line",
"(",
"line",
")",
":",
"\"\"\"\n helper function that distributes extra spaces between words. The number\n of gaps is nwords - 1 but must be at least 1 for single-word lines. We\n distribute odd spaces randomly to one of the gaps.\n \"\"\"",
"line_rest",
"=",
"width",
"-",
"(",
"wlen",
"+",
"ngaps",
")",
"gap",
"=",
"\" \"",
"# minimum gap between words",
"if",
"line_rest",
">",
"0",
":",
"if",
"align",
"==",
"'l'",
":",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"\"\\n\\n\"",
":",
"line",
"[",
"-",
"1",
"]",
"=",
"\" \"",
"*",
"(",
"line_rest",
"-",
"1",
")",
"+",
"\"\\n\"",
"+",
"\" \"",
"*",
"width",
"+",
"\"\\n\"",
"+",
"\" \"",
"*",
"width",
"else",
":",
"line",
"[",
"-",
"1",
"]",
"+=",
"\" \"",
"*",
"line_rest",
"elif",
"align",
"==",
"'r'",
":",
"line",
"[",
"0",
"]",
"=",
"\" \"",
"*",
"line_rest",
"+",
"line",
"[",
"0",
"]",
"elif",
"align",
"==",
"'c'",
":",
"pad",
"=",
"\" \"",
"*",
"(",
"line_rest",
"//",
"2",
")",
"line",
"[",
"0",
"]",
"=",
"pad",
"+",
"line",
"[",
"0",
"]",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"\"\\n\\n\"",
":",
"line",
"[",
"-",
"1",
"]",
"+=",
"pad",
"+",
"\" \"",
"*",
"(",
"line_rest",
"%",
"2",
"-",
"1",
")",
"+",
"\"\\n\"",
"+",
"\" \"",
"*",
"width",
"+",
"\"\\n\"",
"+",
"\" \"",
"*",
"width",
"else",
":",
"line",
"[",
"-",
"1",
"]",
"=",
"line",
"[",
"-",
"1",
"]",
"+",
"pad",
"+",
"\" \"",
"*",
"(",
"line_rest",
"%",
"2",
")",
"else",
":",
"# align 'f'",
"gap",
"+=",
"\" \"",
"*",
"(",
"line_rest",
"//",
"max",
"(",
"1",
",",
"ngaps",
")",
")",
"rest_gap",
"=",
"line_rest",
"%",
"max",
"(",
"1",
",",
"ngaps",
")",
"for",
"i",
"in",
"range",
"(",
"rest_gap",
")",
":",
"line",
"[",
"i",
"]",
"+=",
"\" \"",
"elif",
"not",
"any",
"(",
"line",
")",
":",
"return",
"[",
"\" \"",
"*",
"width",
"]",
"return",
"gap",
".",
"join",
"(",
"line",
")",
"# split into paragraphs and words",
"paragraphs",
"=",
"re",
".",
"split",
"(",
"\"\\n\\s*?\\n\"",
",",
"text",
",",
"re",
".",
"MULTILINE",
")",
"words",
"=",
"[",
"]",
"for",
"ip",
",",
"paragraph",
"in",
"enumerate",
"(",
"paragraphs",
")",
":",
"if",
"ip",
">",
"0",
":",
"words",
".",
"append",
"(",
"(",
"\"\\n\\n\"",
",",
"0",
")",
")",
"words",
".",
"extend",
"(",
"(",
"word",
",",
"len",
"(",
"word",
")",
")",
"for",
"word",
"in",
"paragraph",
".",
"split",
"(",
")",
")",
"ngaps",
",",
"wlen",
",",
"line",
"=",
"0",
",",
"0",
",",
"[",
"]",
"lines",
"=",
"[",
"]",
"while",
"words",
":",
"if",
"not",
"line",
":",
"# start a new line",
"word",
"=",
"words",
".",
"pop",
"(",
"0",
")",
"wlen",
"=",
"word",
"[",
"1",
"]",
"line",
".",
"append",
"(",
"word",
"[",
"0",
"]",
")",
"elif",
"(",
"words",
"[",
"0",
"]",
"[",
"1",
"]",
"+",
"wlen",
"+",
"ngaps",
")",
">=",
"width",
":",
"# next word would exceed word length of line + smallest gaps",
"lines",
".",
"append",
"(",
"_process_line",
"(",
"line",
")",
")",
"ngaps",
",",
"wlen",
",",
"line",
"=",
"0",
",",
"0",
",",
"[",
"]",
"else",
":",
"# put a new word on the line",
"word",
"=",
"words",
".",
"pop",
"(",
"0",
")",
"line",
".",
"append",
"(",
"word",
"[",
"0",
"]",
")",
"if",
"word",
"[",
"1",
"]",
"==",
"0",
":",
"# a new paragraph, process immediately",
"lines",
".",
"append",
"(",
"_process_line",
"(",
"line",
")",
")",
"ngaps",
",",
"wlen",
",",
"line",
"=",
"0",
",",
"0",
",",
"[",
"]",
"else",
":",
"wlen",
"+=",
"word",
"[",
"1",
"]",
"ngaps",
"+=",
"1",
"if",
"line",
":",
"# catch any line left behind",
"lines",
".",
"append",
"(",
"_process_line",
"(",
"line",
")",
")",
"indentstring",
"=",
"\" \"",
"*",
"indent",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"indentstring",
"+",
"line",
"for",
"line",
"in",
"lines",
"]",
")"
] | [
193,
0
] | [
282,
61
] | python | en | ['en', 'error', 'th'] | False |
columnize | (string, columns=2, spacing=4, align='l', width=None) |
Break a string into a number of columns, using as little
vertical space as possible.
Args:
string (str): The string to columnize.
columns (int, optional): The number of columns to use.
spacing (int, optional): How much space to have between columns.
width (int, optional): The max width of the columns.
Defaults to client's default width.
Returns:
columns (str): Text divided into columns.
Raises:
RuntimeError: If given invalid values.
|
Break a string into a number of columns, using as little
vertical space as possible. | def columnize(string, columns=2, spacing=4, align='l', width=None):
"""
Break a string into a number of columns, using as little
vertical space as possible.
Args:
string (str): The string to columnize.
columns (int, optional): The number of columns to use.
spacing (int, optional): How much space to have between columns.
width (int, optional): The max width of the columns.
Defaults to client's default width.
Returns:
columns (str): Text divided into columns.
Raises:
RuntimeError: If given invalid values.
"""
columns = max(1, columns)
spacing = max(1, spacing)
width = width if width else settings.CLIENT_DEFAULT_WIDTH
w_spaces = (columns - 1) * spacing
w_txt = max(1, width - w_spaces)
if w_spaces + columns > width: # require at least 1 char per column
raise RuntimeError("Width too small to fit columns")
colwidth = int(w_txt / (1.0 * columns))
# first make a single column which we then split
onecol = justify(string, width=colwidth, align=align)
onecol = onecol.split("\n")
nrows, dangling = divmod(len(onecol), columns)
nrows = [nrows + 1 if i < dangling else nrows for i in range(columns)]
height = max(nrows)
cols = []
istart = 0
for irows in nrows:
cols.append(onecol[istart:istart+irows])
istart = istart + irows
for col in cols:
if len(col) < height:
col.append(" " * colwidth)
sep = " " * spacing
rows = []
for irow in range(height):
rows.append(sep.join(col[irow] for col in cols))
return "\n".join(rows) | [
"def",
"columnize",
"(",
"string",
",",
"columns",
"=",
"2",
",",
"spacing",
"=",
"4",
",",
"align",
"=",
"'l'",
",",
"width",
"=",
"None",
")",
":",
"columns",
"=",
"max",
"(",
"1",
",",
"columns",
")",
"spacing",
"=",
"max",
"(",
"1",
",",
"spacing",
")",
"width",
"=",
"width",
"if",
"width",
"else",
"settings",
".",
"CLIENT_DEFAULT_WIDTH",
"w_spaces",
"=",
"(",
"columns",
"-",
"1",
")",
"*",
"spacing",
"w_txt",
"=",
"max",
"(",
"1",
",",
"width",
"-",
"w_spaces",
")",
"if",
"w_spaces",
"+",
"columns",
">",
"width",
":",
"# require at least 1 char per column",
"raise",
"RuntimeError",
"(",
"\"Width too small to fit columns\"",
")",
"colwidth",
"=",
"int",
"(",
"w_txt",
"/",
"(",
"1.0",
"*",
"columns",
")",
")",
"# first make a single column which we then split",
"onecol",
"=",
"justify",
"(",
"string",
",",
"width",
"=",
"colwidth",
",",
"align",
"=",
"align",
")",
"onecol",
"=",
"onecol",
".",
"split",
"(",
"\"\\n\"",
")",
"nrows",
",",
"dangling",
"=",
"divmod",
"(",
"len",
"(",
"onecol",
")",
",",
"columns",
")",
"nrows",
"=",
"[",
"nrows",
"+",
"1",
"if",
"i",
"<",
"dangling",
"else",
"nrows",
"for",
"i",
"in",
"range",
"(",
"columns",
")",
"]",
"height",
"=",
"max",
"(",
"nrows",
")",
"cols",
"=",
"[",
"]",
"istart",
"=",
"0",
"for",
"irows",
"in",
"nrows",
":",
"cols",
".",
"append",
"(",
"onecol",
"[",
"istart",
":",
"istart",
"+",
"irows",
"]",
")",
"istart",
"=",
"istart",
"+",
"irows",
"for",
"col",
"in",
"cols",
":",
"if",
"len",
"(",
"col",
")",
"<",
"height",
":",
"col",
".",
"append",
"(",
"\" \"",
"*",
"colwidth",
")",
"sep",
"=",
"\" \"",
"*",
"spacing",
"rows",
"=",
"[",
"]",
"for",
"irow",
"in",
"range",
"(",
"height",
")",
":",
"rows",
".",
"append",
"(",
"sep",
".",
"join",
"(",
"col",
"[",
"irow",
"]",
"for",
"col",
"in",
"cols",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"rows",
")"
] | [
285,
0
] | [
338,
26
] | python | en | ['en', 'error', 'th'] | False |
list_to_string | (inlist, endsep="and", addquote=False) |
This pretty-formats a list as string output, adding an optional
alternative separator to the second to last entry. If `addquote`
is `True`, the outgoing strings will be surrounded by quotes.
Args:
inlist (list): The list to print.
endsep (str, optional): If set, the last item separator will
be replaced with this value.
addquote (bool, optional): This will surround all outgoing
values with double quotes.
Returns:
liststr (str): The list represented as a string.
Examples:
```python
# no endsep:
[1,2,3] -> '1, 2, 3'
# with endsep=='and':
[1,2,3] -> '1, 2 and 3'
# with addquote and endsep
[1,2,3] -> '"1", "2" and "3"'
```
|
This pretty-formats a list as string output, adding an optional
alternative separator to the second to last entry. If `addquote`
is `True`, the outgoing strings will be surrounded by quotes. | def list_to_string(inlist, endsep="and", addquote=False):
"""
This pretty-formats a list as string output, adding an optional
alternative separator to the second to last entry. If `addquote`
is `True`, the outgoing strings will be surrounded by quotes.
Args:
inlist (list): The list to print.
endsep (str, optional): If set, the last item separator will
be replaced with this value.
addquote (bool, optional): This will surround all outgoing
values with double quotes.
Returns:
liststr (str): The list represented as a string.
Examples:
```python
# no endsep:
[1,2,3] -> '1, 2, 3'
# with endsep=='and':
[1,2,3] -> '1, 2 and 3'
# with addquote and endsep
[1,2,3] -> '"1", "2" and "3"'
```
"""
if not endsep:
endsep = ","
else:
endsep = " " + endsep
if not inlist:
return ""
if addquote:
if len(inlist) == 1:
return "\"%s\"" % inlist[0]
return ", ".join("\"%s\"" % v for v in inlist[:-1]) + "%s %s" % (endsep, "\"%s\"" % inlist[-1])
else:
if len(inlist) == 1:
return str(inlist[0])
return ", ".join(str(v) for v in inlist[:-1]) + "%s %s" % (endsep, inlist[-1]) | [
"def",
"list_to_string",
"(",
"inlist",
",",
"endsep",
"=",
"\"and\"",
",",
"addquote",
"=",
"False",
")",
":",
"if",
"not",
"endsep",
":",
"endsep",
"=",
"\",\"",
"else",
":",
"endsep",
"=",
"\" \"",
"+",
"endsep",
"if",
"not",
"inlist",
":",
"return",
"\"\"",
"if",
"addquote",
":",
"if",
"len",
"(",
"inlist",
")",
"==",
"1",
":",
"return",
"\"\\\"%s\\\"\"",
"%",
"inlist",
"[",
"0",
"]",
"return",
"\", \"",
".",
"join",
"(",
"\"\\\"%s\\\"\"",
"%",
"v",
"for",
"v",
"in",
"inlist",
"[",
":",
"-",
"1",
"]",
")",
"+",
"\"%s %s\"",
"%",
"(",
"endsep",
",",
"\"\\\"%s\\\"\"",
"%",
"inlist",
"[",
"-",
"1",
"]",
")",
"else",
":",
"if",
"len",
"(",
"inlist",
")",
"==",
"1",
":",
"return",
"str",
"(",
"inlist",
"[",
"0",
"]",
")",
"return",
"\", \"",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"inlist",
"[",
":",
"-",
"1",
"]",
")",
"+",
"\"%s %s\"",
"%",
"(",
"endsep",
",",
"inlist",
"[",
"-",
"1",
"]",
")"
] | [
341,
0
] | [
382,
86
] | python | en | ['en', 'error', 'th'] | False |
wildcard_to_regexp | (instring) |
Converts a player-supplied string that may have wildcards in it to
regular expressions. This is useful for name matching.
Args:
instring (string): A string that may potentially contain
wildcards (`*` or `?`).
Returns:
regex (str): A string where wildcards were replaced with
regular expressions.
|
Converts a player-supplied string that may have wildcards in it to
regular expressions. This is useful for name matching. | def wildcard_to_regexp(instring):
"""
Converts a player-supplied string that may have wildcards in it to
regular expressions. This is useful for name matching.
Args:
instring (string): A string that may potentially contain
wildcards (`*` or `?`).
Returns:
regex (str): A string where wildcards were replaced with
regular expressions.
"""
regexp_string = ""
# If the string starts with an asterisk, we can't impose the beginning of
# string (^) limiter.
if instring[0] != "*":
regexp_string += "^"
# Replace any occurances of * or ? with the appropriate groups.
regexp_string += instring.replace("*", "(.*)").replace("?", "(.{1})")
# If there's an asterisk at the end of the string, we can't impose the
# end of string ($) limiter.
if instring[-1] != "*":
regexp_string += "$"
return regexp_string | [
"def",
"wildcard_to_regexp",
"(",
"instring",
")",
":",
"regexp_string",
"=",
"\"\"",
"# If the string starts with an asterisk, we can't impose the beginning of",
"# string (^) limiter.",
"if",
"instring",
"[",
"0",
"]",
"!=",
"\"*\"",
":",
"regexp_string",
"+=",
"\"^\"",
"# Replace any occurances of * or ? with the appropriate groups.",
"regexp_string",
"+=",
"instring",
".",
"replace",
"(",
"\"*\"",
",",
"\"(.*)\"",
")",
".",
"replace",
"(",
"\"?\"",
",",
"\"(.{1})\"",
")",
"# If there's an asterisk at the end of the string, we can't impose the",
"# end of string ($) limiter.",
"if",
"instring",
"[",
"-",
"1",
"]",
"!=",
"\"*\"",
":",
"regexp_string",
"+=",
"\"$\"",
"return",
"regexp_string"
] | [
385,
0
] | [
414,
24
] | python | en | ['en', 'error', 'th'] | False |
time_format | (seconds, style=0) |
Function to return a 'prettified' version of a value in seconds.
Args:
seconds (int): Number if seconds to format.
style (int): One of the following styles:
0. "1d 08:30"
1. "1d"
2. "1 day, 8 hours, 30 minutes"
3. "1 day, 8 hours, 30 minutes, 10 seconds"
4. highest unit (like "3 years" or "8 months" or "1 second")
Returns:
timeformatted (str): A pretty time string.
|
Function to return a 'prettified' version of a value in seconds. | def time_format(seconds, style=0):
"""
Function to return a 'prettified' version of a value in seconds.
Args:
seconds (int): Number if seconds to format.
style (int): One of the following styles:
0. "1d 08:30"
1. "1d"
2. "1 day, 8 hours, 30 minutes"
3. "1 day, 8 hours, 30 minutes, 10 seconds"
4. highest unit (like "3 years" or "8 months" or "1 second")
Returns:
timeformatted (str): A pretty time string.
"""
if seconds < 0:
seconds = 0
else:
# We'll just use integer math, no need for decimal precision.
seconds = int(seconds)
days = seconds // 86400
seconds -= days * 86400
hours = seconds // 3600
seconds -= hours * 3600
minutes = seconds // 60
seconds -= minutes * 60
retval = ""
if style == 0:
"""
Standard colon-style output.
"""
if days > 0:
retval = '%id %02i:%02i' % (days, hours, minutes,)
else:
retval = '%02i:%02i' % (hours, minutes,)
return retval
elif style == 1:
"""
Simple, abbreviated form that only shows the highest time amount.
"""
if days > 0:
return '%id' % (days,)
elif hours > 0:
return '%ih' % (hours,)
elif minutes > 0:
return '%im' % (minutes,)
else:
return '%is' % (seconds,)
elif style == 2:
"""
Full-detailed, long-winded format. We ignore seconds.
"""
days_str = hours_str = ''
minutes_str = '0 minutes'
if days > 0:
if days == 1:
days_str = '%i day, ' % days
else:
days_str = '%i days, ' % days
if days or hours > 0:
if hours == 1:
hours_str = '%i hour, ' % hours
else:
hours_str = '%i hours, ' % hours
if hours or minutes > 0:
if minutes == 1:
minutes_str = '%i minute ' % minutes
else:
minutes_str = '%i minutes ' % minutes
retval = '%s%s%s' % (days_str, hours_str, minutes_str)
elif style == 3:
"""
Full-detailed, long-winded format. Includes seconds.
"""
days_str = hours_str = minutes_str = seconds_str = ''
if days > 0:
if days == 1:
days_str = '%i day, ' % days
else:
days_str = '%i days, ' % days
if days or hours > 0:
if hours == 1:
hours_str = '%i hour, ' % hours
else:
hours_str = '%i hours, ' % hours
if hours or minutes > 0:
if minutes == 1:
minutes_str = '%i minute ' % minutes
else:
minutes_str = '%i minutes ' % minutes
if minutes or seconds > 0:
if seconds == 1:
seconds_str = '%i second ' % seconds
else:
seconds_str = '%i seconds ' % seconds
retval = '%s%s%s%s' % (days_str, hours_str, minutes_str, seconds_str)
elif style == 4:
"""
Only return the highest unit.
"""
if days >= 730: # Several years
return "{} years".format(days // 365)
elif days >= 365: # One year
return "a year"
elif days >= 62: # Several months
return "{} months".format(days // 31)
elif days >= 31: # One month
return "a month"
elif days >= 2: # Several days
return "{} days".format(days)
elif days > 0:
return "a day"
elif hours >= 2: # Several hours
return "{} hours".format(hours)
elif hours > 0: # One hour
return "an hour"
elif minutes >= 2: # Several minutes
return "{} minutes".format(minutes)
elif minutes > 0: # One minute
return "a minute"
elif seconds >= 2: # Several seconds
return "{} seconds".format(seconds)
elif seconds == 1:
return "a second"
else:
return "0 seconds"
else:
raise ValueError("Unknown style for time format: %s" % style)
return retval.strip() | [
"def",
"time_format",
"(",
"seconds",
",",
"style",
"=",
"0",
")",
":",
"if",
"seconds",
"<",
"0",
":",
"seconds",
"=",
"0",
"else",
":",
"# We'll just use integer math, no need for decimal precision.",
"seconds",
"=",
"int",
"(",
"seconds",
")",
"days",
"=",
"seconds",
"//",
"86400",
"seconds",
"-=",
"days",
"*",
"86400",
"hours",
"=",
"seconds",
"//",
"3600",
"seconds",
"-=",
"hours",
"*",
"3600",
"minutes",
"=",
"seconds",
"//",
"60",
"seconds",
"-=",
"minutes",
"*",
"60",
"retval",
"=",
"\"\"",
"if",
"style",
"==",
"0",
":",
"\"\"\"\n Standard colon-style output.\n \"\"\"",
"if",
"days",
">",
"0",
":",
"retval",
"=",
"'%id %02i:%02i'",
"%",
"(",
"days",
",",
"hours",
",",
"minutes",
",",
")",
"else",
":",
"retval",
"=",
"'%02i:%02i'",
"%",
"(",
"hours",
",",
"minutes",
",",
")",
"return",
"retval",
"elif",
"style",
"==",
"1",
":",
"\"\"\"\n Simple, abbreviated form that only shows the highest time amount.\n \"\"\"",
"if",
"days",
">",
"0",
":",
"return",
"'%id'",
"%",
"(",
"days",
",",
")",
"elif",
"hours",
">",
"0",
":",
"return",
"'%ih'",
"%",
"(",
"hours",
",",
")",
"elif",
"minutes",
">",
"0",
":",
"return",
"'%im'",
"%",
"(",
"minutes",
",",
")",
"else",
":",
"return",
"'%is'",
"%",
"(",
"seconds",
",",
")",
"elif",
"style",
"==",
"2",
":",
"\"\"\"\n Full-detailed, long-winded format. We ignore seconds.\n \"\"\"",
"days_str",
"=",
"hours_str",
"=",
"''",
"minutes_str",
"=",
"'0 minutes'",
"if",
"days",
">",
"0",
":",
"if",
"days",
"==",
"1",
":",
"days_str",
"=",
"'%i day, '",
"%",
"days",
"else",
":",
"days_str",
"=",
"'%i days, '",
"%",
"days",
"if",
"days",
"or",
"hours",
">",
"0",
":",
"if",
"hours",
"==",
"1",
":",
"hours_str",
"=",
"'%i hour, '",
"%",
"hours",
"else",
":",
"hours_str",
"=",
"'%i hours, '",
"%",
"hours",
"if",
"hours",
"or",
"minutes",
">",
"0",
":",
"if",
"minutes",
"==",
"1",
":",
"minutes_str",
"=",
"'%i minute '",
"%",
"minutes",
"else",
":",
"minutes_str",
"=",
"'%i minutes '",
"%",
"minutes",
"retval",
"=",
"'%s%s%s'",
"%",
"(",
"days_str",
",",
"hours_str",
",",
"minutes_str",
")",
"elif",
"style",
"==",
"3",
":",
"\"\"\"\n Full-detailed, long-winded format. Includes seconds.\n \"\"\"",
"days_str",
"=",
"hours_str",
"=",
"minutes_str",
"=",
"seconds_str",
"=",
"''",
"if",
"days",
">",
"0",
":",
"if",
"days",
"==",
"1",
":",
"days_str",
"=",
"'%i day, '",
"%",
"days",
"else",
":",
"days_str",
"=",
"'%i days, '",
"%",
"days",
"if",
"days",
"or",
"hours",
">",
"0",
":",
"if",
"hours",
"==",
"1",
":",
"hours_str",
"=",
"'%i hour, '",
"%",
"hours",
"else",
":",
"hours_str",
"=",
"'%i hours, '",
"%",
"hours",
"if",
"hours",
"or",
"minutes",
">",
"0",
":",
"if",
"minutes",
"==",
"1",
":",
"minutes_str",
"=",
"'%i minute '",
"%",
"minutes",
"else",
":",
"minutes_str",
"=",
"'%i minutes '",
"%",
"minutes",
"if",
"minutes",
"or",
"seconds",
">",
"0",
":",
"if",
"seconds",
"==",
"1",
":",
"seconds_str",
"=",
"'%i second '",
"%",
"seconds",
"else",
":",
"seconds_str",
"=",
"'%i seconds '",
"%",
"seconds",
"retval",
"=",
"'%s%s%s%s'",
"%",
"(",
"days_str",
",",
"hours_str",
",",
"minutes_str",
",",
"seconds_str",
")",
"elif",
"style",
"==",
"4",
":",
"\"\"\"\n Only return the highest unit.\n \"\"\"",
"if",
"days",
">=",
"730",
":",
"# Several years",
"return",
"\"{} years\"",
".",
"format",
"(",
"days",
"//",
"365",
")",
"elif",
"days",
">=",
"365",
":",
"# One year",
"return",
"\"a year\"",
"elif",
"days",
">=",
"62",
":",
"# Several months",
"return",
"\"{} months\"",
".",
"format",
"(",
"days",
"//",
"31",
")",
"elif",
"days",
">=",
"31",
":",
"# One month",
"return",
"\"a month\"",
"elif",
"days",
">=",
"2",
":",
"# Several days",
"return",
"\"{} days\"",
".",
"format",
"(",
"days",
")",
"elif",
"days",
">",
"0",
":",
"return",
"\"a day\"",
"elif",
"hours",
">=",
"2",
":",
"# Several hours",
"return",
"\"{} hours\"",
".",
"format",
"(",
"hours",
")",
"elif",
"hours",
">",
"0",
":",
"# One hour",
"return",
"\"an hour\"",
"elif",
"minutes",
">=",
"2",
":",
"# Several minutes",
"return",
"\"{} minutes\"",
".",
"format",
"(",
"minutes",
")",
"elif",
"minutes",
">",
"0",
":",
"# One minute",
"return",
"\"a minute\"",
"elif",
"seconds",
">=",
"2",
":",
"# Several seconds",
"return",
"\"{} seconds\"",
".",
"format",
"(",
"seconds",
")",
"elif",
"seconds",
"==",
"1",
":",
"return",
"\"a second\"",
"else",
":",
"return",
"\"0 seconds\"",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown style for time format: %s\"",
"%",
"style",
")",
"return",
"retval",
".",
"strip",
"(",
")"
] | [
417,
0
] | [
550,
25
] | python | en | ['en', 'error', 'th'] | False |
datetime_format | (dtobj) |
Pretty-prints the time since a given time.
Args:
dtobj (datetime): An datetime object, e.g. from Django's
`DateTimeField`.
Returns:
deltatime (str): A string describing how long ago `dtobj`
took place.
|
Pretty-prints the time since a given time. | def datetime_format(dtobj):
"""
Pretty-prints the time since a given time.
Args:
dtobj (datetime): An datetime object, e.g. from Django's
`DateTimeField`.
Returns:
deltatime (str): A string describing how long ago `dtobj`
took place.
"""
year, month, day = dtobj.year, dtobj.month, dtobj.day
hour, minute, second = dtobj.hour, dtobj.minute, dtobj.second
now = timezone.now()
if year < now.year:
# another year
timestring = str(dtobj.date())
elif dtobj.date() < now.date():
# another date, same year
timestring = "%02i-%02i" % (day, month)
elif hour < now.hour - 1:
# same day, more than 1 hour ago
timestring = "%02i:%02i" % (hour, minute)
else:
# same day, less than 1 hour ago
timestring = "%02i:%02i:%02i" % (hour, minute, second)
return timestring | [
"def",
"datetime_format",
"(",
"dtobj",
")",
":",
"year",
",",
"month",
",",
"day",
"=",
"dtobj",
".",
"year",
",",
"dtobj",
".",
"month",
",",
"dtobj",
".",
"day",
"hour",
",",
"minute",
",",
"second",
"=",
"dtobj",
".",
"hour",
",",
"dtobj",
".",
"minute",
",",
"dtobj",
".",
"second",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"year",
"<",
"now",
".",
"year",
":",
"# another year",
"timestring",
"=",
"str",
"(",
"dtobj",
".",
"date",
"(",
")",
")",
"elif",
"dtobj",
".",
"date",
"(",
")",
"<",
"now",
".",
"date",
"(",
")",
":",
"# another date, same year",
"timestring",
"=",
"\"%02i-%02i\"",
"%",
"(",
"day",
",",
"month",
")",
"elif",
"hour",
"<",
"now",
".",
"hour",
"-",
"1",
":",
"# same day, more than 1 hour ago",
"timestring",
"=",
"\"%02i:%02i\"",
"%",
"(",
"hour",
",",
"minute",
")",
"else",
":",
"# same day, less than 1 hour ago",
"timestring",
"=",
"\"%02i:%02i:%02i\"",
"%",
"(",
"hour",
",",
"minute",
",",
"second",
")",
"return",
"timestring"
] | [
553,
0
] | [
583,
21
] | python | en | ['en', 'error', 'th'] | False |
host_os_is | (osname) |
Check to see if the host OS matches the query.
Args:
osname (str): Common names are "posix" (linux/unix/mac) and
"nt" (windows).
Args:
is_os (bool): If the os matches or not.
|
Check to see if the host OS matches the query. | def host_os_is(osname):
"""
Check to see if the host OS matches the query.
Args:
osname (str): Common names are "posix" (linux/unix/mac) and
"nt" (windows).
Args:
is_os (bool): If the os matches or not.
"""
return os.name == osname | [
"def",
"host_os_is",
"(",
"osname",
")",
":",
"return",
"os",
".",
"name",
"==",
"osname"
] | [
586,
0
] | [
598,
28
] | python | en | ['en', 'error', 'th'] | False |
get_evennia_version | () |
Helper method for getting the current evennia version.
Returns:
version (str): The version string.
|
Helper method for getting the current evennia version. | def get_evennia_version():
"""
Helper method for getting the current evennia version.
Returns:
version (str): The version string.
"""
import evennia
return evennia.__version__ | [
"def",
"get_evennia_version",
"(",
")",
":",
"import",
"evennia",
"return",
"evennia",
".",
"__version__"
] | [
601,
0
] | [
610,
30
] | python | en | ['en', 'error', 'th'] | False |
pypath_to_realpath | (python_path, file_ending='.py', pypath_prefixes=None) |
Converts a dotted Python path to an absolute path under the
Evennia library directory or under the current game directory.
Args:
python_path (str): A dot-python path
file_ending (str): A file ending, including the period.
pypath_prefixes (list): A list of paths to test for existence. These
should be on python.path form. EVENNIA_DIR and GAME_DIR are automatically
checked, they need not be added to this list.
Returns:
abspaths (list): All existing, absolute paths created by
converting `python_path` to an absolute paths and/or
prepending `python_path` by `settings.EVENNIA_DIR`,
`settings.GAME_DIR` and by`pypath_prefixes` respectively.
Notes:
This will also try a few combinations of paths to allow cases
where pypath is given including the "evennia." or "mygame."
prefixes.
|
Converts a dotted Python path to an absolute path under the
Evennia library directory or under the current game directory. | def pypath_to_realpath(python_path, file_ending='.py', pypath_prefixes=None):
"""
Converts a dotted Python path to an absolute path under the
Evennia library directory or under the current game directory.
Args:
python_path (str): A dot-python path
file_ending (str): A file ending, including the period.
pypath_prefixes (list): A list of paths to test for existence. These
should be on python.path form. EVENNIA_DIR and GAME_DIR are automatically
checked, they need not be added to this list.
Returns:
abspaths (list): All existing, absolute paths created by
converting `python_path` to an absolute paths and/or
prepending `python_path` by `settings.EVENNIA_DIR`,
`settings.GAME_DIR` and by`pypath_prefixes` respectively.
Notes:
This will also try a few combinations of paths to allow cases
where pypath is given including the "evennia." or "mygame."
prefixes.
"""
path = python_path.strip().split('.')
plong = osjoin(*path) + file_ending
pshort = osjoin(*path[1:]) + file_ending if len(path) > 1 else plong # in case we had evennia. or mygame.
prefixlong = [osjoin(*ppath.strip().split('.'))
for ppath in make_iter(pypath_prefixes)] \
if pypath_prefixes else []
prefixshort = [osjoin(*ppath.strip().split('.')[1:])
for ppath in make_iter(pypath_prefixes) if len(ppath.strip().split('.')) > 1]\
if pypath_prefixes else []
paths = [plong] + \
[osjoin(_EVENNIA_DIR, prefix, plong) for prefix in prefixlong] + \
[osjoin(_GAME_DIR, prefix, plong) for prefix in prefixlong] + \
[osjoin(_EVENNIA_DIR, prefix, plong) for prefix in prefixshort] + \
[osjoin(_GAME_DIR, prefix, plong) for prefix in prefixshort] + \
[osjoin(_EVENNIA_DIR, plong), osjoin(_GAME_DIR, plong)] + \
[osjoin(_EVENNIA_DIR, prefix, pshort) for prefix in prefixshort] + \
[osjoin(_GAME_DIR, prefix, pshort) for prefix in prefixshort] + \
[osjoin(_EVENNIA_DIR, prefix, pshort) for prefix in prefixlong] + \
[osjoin(_GAME_DIR, prefix, pshort) for prefix in prefixlong] + \
[osjoin(_EVENNIA_DIR, pshort), osjoin(_GAME_DIR, pshort)]
# filter out non-existing paths
return list(set(p for p in paths if os.path.isfile(p))) | [
"def",
"pypath_to_realpath",
"(",
"python_path",
",",
"file_ending",
"=",
"'.py'",
",",
"pypath_prefixes",
"=",
"None",
")",
":",
"path",
"=",
"python_path",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"plong",
"=",
"osjoin",
"(",
"*",
"path",
")",
"+",
"file_ending",
"pshort",
"=",
"osjoin",
"(",
"*",
"path",
"[",
"1",
":",
"]",
")",
"+",
"file_ending",
"if",
"len",
"(",
"path",
")",
">",
"1",
"else",
"plong",
"# in case we had evennia. or mygame.",
"prefixlong",
"=",
"[",
"osjoin",
"(",
"*",
"ppath",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'.'",
")",
")",
"for",
"ppath",
"in",
"make_iter",
"(",
"pypath_prefixes",
")",
"]",
"if",
"pypath_prefixes",
"else",
"[",
"]",
"prefixshort",
"=",
"[",
"osjoin",
"(",
"*",
"ppath",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
")",
"for",
"ppath",
"in",
"make_iter",
"(",
"pypath_prefixes",
")",
"if",
"len",
"(",
"ppath",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'.'",
")",
")",
">",
"1",
"]",
"if",
"pypath_prefixes",
"else",
"[",
"]",
"paths",
"=",
"[",
"plong",
"]",
"+",
"[",
"osjoin",
"(",
"_EVENNIA_DIR",
",",
"prefix",
",",
"plong",
")",
"for",
"prefix",
"in",
"prefixlong",
"]",
"+",
"[",
"osjoin",
"(",
"_GAME_DIR",
",",
"prefix",
",",
"plong",
")",
"for",
"prefix",
"in",
"prefixlong",
"]",
"+",
"[",
"osjoin",
"(",
"_EVENNIA_DIR",
",",
"prefix",
",",
"plong",
")",
"for",
"prefix",
"in",
"prefixshort",
"]",
"+",
"[",
"osjoin",
"(",
"_GAME_DIR",
",",
"prefix",
",",
"plong",
")",
"for",
"prefix",
"in",
"prefixshort",
"]",
"+",
"[",
"osjoin",
"(",
"_EVENNIA_DIR",
",",
"plong",
")",
",",
"osjoin",
"(",
"_GAME_DIR",
",",
"plong",
")",
"]",
"+",
"[",
"osjoin",
"(",
"_EVENNIA_DIR",
",",
"prefix",
",",
"pshort",
")",
"for",
"prefix",
"in",
"prefixshort",
"]",
"+",
"[",
"osjoin",
"(",
"_GAME_DIR",
",",
"prefix",
",",
"pshort",
")",
"for",
"prefix",
"in",
"prefixshort",
"]",
"+",
"[",
"osjoin",
"(",
"_EVENNIA_DIR",
",",
"prefix",
",",
"pshort",
")",
"for",
"prefix",
"in",
"prefixlong",
"]",
"+",
"[",
"osjoin",
"(",
"_GAME_DIR",
",",
"prefix",
",",
"pshort",
")",
"for",
"prefix",
"in",
"prefixlong",
"]",
"+",
"[",
"osjoin",
"(",
"_EVENNIA_DIR",
",",
"pshort",
")",
",",
"osjoin",
"(",
"_GAME_DIR",
",",
"pshort",
")",
"]",
"# filter out non-existing paths",
"return",
"list",
"(",
"set",
"(",
"p",
"for",
"p",
"in",
"paths",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"p",
")",
")",
")"
] | [
613,
0
] | [
658,
59
] | python | en | ['en', 'error', 'th'] | False |
dbref | (inp, reqhash=True) |
Converts/checks if input is a valid dbref.
Args:
inp (int, str): A database ref on the form N or #N.
reqhash (bool, optional): Require the #N form to accept
input as a valid dbref.
Returns:
dbref (int or None): The integer part of the dbref or `None`
if input was not a valid dbref.
|
Converts/checks if input is a valid dbref. | def dbref(inp, reqhash=True):
"""
Converts/checks if input is a valid dbref.
Args:
inp (int, str): A database ref on the form N or #N.
reqhash (bool, optional): Require the #N form to accept
input as a valid dbref.
Returns:
dbref (int or None): The integer part of the dbref or `None`
if input was not a valid dbref.
"""
if reqhash:
num = (int(inp.lstrip('#')) if (isinstance(inp, basestring) and
inp.startswith("#") and
inp.lstrip('#').isdigit())
else None)
return num if num > 0 else None
elif isinstance(inp, basestring):
inp = inp.lstrip('#')
return int(inp) if inp.isdigit() and int(inp) > 0 else None
else:
return inp if isinstance(inp, int) else None | [
"def",
"dbref",
"(",
"inp",
",",
"reqhash",
"=",
"True",
")",
":",
"if",
"reqhash",
":",
"num",
"=",
"(",
"int",
"(",
"inp",
".",
"lstrip",
"(",
"'#'",
")",
")",
"if",
"(",
"isinstance",
"(",
"inp",
",",
"basestring",
")",
"and",
"inp",
".",
"startswith",
"(",
"\"#\"",
")",
"and",
"inp",
".",
"lstrip",
"(",
"'#'",
")",
".",
"isdigit",
"(",
")",
")",
"else",
"None",
")",
"return",
"num",
"if",
"num",
">",
"0",
"else",
"None",
"elif",
"isinstance",
"(",
"inp",
",",
"basestring",
")",
":",
"inp",
"=",
"inp",
".",
"lstrip",
"(",
"'#'",
")",
"return",
"int",
"(",
"inp",
")",
"if",
"inp",
".",
"isdigit",
"(",
")",
"and",
"int",
"(",
"inp",
")",
">",
"0",
"else",
"None",
"else",
":",
"return",
"inp",
"if",
"isinstance",
"(",
"inp",
",",
"int",
")",
"else",
"None"
] | [
661,
0
] | [
685,
52
] | python | en | ['en', 'error', 'th'] | False |
dbref_to_obj | (inp, objclass, raise_errors=True) |
Convert a #dbref to a valid object.
Args:
inp (str or int): A valid #dbref.
objclass (class): A valid django model to filter against.
raise_errors (bool, optional): Whether to raise errors
or return `None` on errors.
Returns:
obj (Object or None): An entity loaded from the dbref.
Raises:
Exception: If `raise_errors` is `True` and
`objclass.objects.get(id=dbref)` did not return a valid
object.
|
Convert a #dbref to a valid object. | def dbref_to_obj(inp, objclass, raise_errors=True):
"""
Convert a #dbref to a valid object.
Args:
inp (str or int): A valid #dbref.
objclass (class): A valid django model to filter against.
raise_errors (bool, optional): Whether to raise errors
or return `None` on errors.
Returns:
obj (Object or None): An entity loaded from the dbref.
Raises:
Exception: If `raise_errors` is `True` and
`objclass.objects.get(id=dbref)` did not return a valid
object.
"""
dbid = dbref(inp)
if not dbid:
# we only convert #dbrefs
return inp
try:
if dbid < 0:
return None
except ValueError:
return None
# if we get to this point, inp is an integer dbref; get the matching object
try:
return objclass.objects.get(id=dbid)
except Exception:
if raise_errors:
raise
return inp | [
"def",
"dbref_to_obj",
"(",
"inp",
",",
"objclass",
",",
"raise_errors",
"=",
"True",
")",
":",
"dbid",
"=",
"dbref",
"(",
"inp",
")",
"if",
"not",
"dbid",
":",
"# we only convert #dbrefs",
"return",
"inp",
"try",
":",
"if",
"dbid",
"<",
"0",
":",
"return",
"None",
"except",
"ValueError",
":",
"return",
"None",
"# if we get to this point, inp is an integer dbref; get the matching object",
"try",
":",
"return",
"objclass",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"dbid",
")",
"except",
"Exception",
":",
"if",
"raise_errors",
":",
"raise",
"return",
"inp"
] | [
688,
0
] | [
723,
18
] | python | en | ['en', 'error', 'th'] | False |
latinify | (unicode_string, default='?', pure_ascii=False) |
Convert a unicode string to "safe" ascii/latin-1 characters.
This is used as a last resort when normal decoding does not work.
Arguments:
unicode_string (unicode): A string to convert to an ascii
or latin-1 string.
default (str, optional): Characters resisting mapping will be replaced
with this character or string.
Notes:
This is inspired by the gist by Ricardo Murri:
https://gist.github.com/riccardomurri/3c3ccec30f037be174d3
|
Convert a unicode string to "safe" ascii/latin-1 characters.
This is used as a last resort when normal decoding does not work. | def latinify(unicode_string, default='?', pure_ascii=False):
"""
Convert a unicode string to "safe" ascii/latin-1 characters.
This is used as a last resort when normal decoding does not work.
Arguments:
unicode_string (unicode): A string to convert to an ascii
or latin-1 string.
default (str, optional): Characters resisting mapping will be replaced
with this character or string.
Notes:
This is inspired by the gist by Ricardo Murri:
https://gist.github.com/riccardomurri/3c3ccec30f037be174d3
"""
from unicodedata import name
converted = []
for unich in iter(unicode_string):
try:
ch = unich.decode('ascii')
except UnicodeDecodeError:
# deduce a latin letter equivalent from the Unicode data
# point name; e.g., since `name(u'á') == 'LATIN SMALL
# LETTER A WITH ACUTE'` translate `á` to `a`. However, in
# some cases the unicode name is still "LATIN LETTER"
# although no direct equivalent in the Latin alphabet
# exists (e.g., Þ, "LATIN CAPITAL LETTER THORN") -- we can
# avoid these cases by checking that the letter name is
# composed of one letter only.
# We also supply some direct-translations for some particular
# common cases.
what = name(unich)
if what in _UNICODE_MAP:
ch = _UNICODE_MAP[what]
else:
what = what.split()
if what[0] == 'LATIN' and what[2] == 'LETTER' and len(what[3]) == 1:
ch = what[3].lower() if what[1] == 'SMALL' else what[3].upper()
else:
ch = default
converted.append(chr(ord(ch)))
return ''.join(converted) | [
"def",
"latinify",
"(",
"unicode_string",
",",
"default",
"=",
"'?'",
",",
"pure_ascii",
"=",
"False",
")",
":",
"from",
"unicodedata",
"import",
"name",
"converted",
"=",
"[",
"]",
"for",
"unich",
"in",
"iter",
"(",
"unicode_string",
")",
":",
"try",
":",
"ch",
"=",
"unich",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"UnicodeDecodeError",
":",
"# deduce a latin letter equivalent from the Unicode data",
"# point name; e.g., since `name(u'á') == 'LATIN SMALL",
"# LETTER A WITH ACUTE'` translate `á` to `a`. However, in",
"# some cases the unicode name is still \"LATIN LETTER\"",
"# although no direct equivalent in the Latin alphabet",
"# exists (e.g., Þ, \"LATIN CAPITAL LETTER THORN\") -- we can",
"# avoid these cases by checking that the letter name is",
"# composed of one letter only.",
"# We also supply some direct-translations for some particular",
"# common cases.",
"what",
"=",
"name",
"(",
"unich",
")",
"if",
"what",
"in",
"_UNICODE_MAP",
":",
"ch",
"=",
"_UNICODE_MAP",
"[",
"what",
"]",
"else",
":",
"what",
"=",
"what",
".",
"split",
"(",
")",
"if",
"what",
"[",
"0",
"]",
"==",
"'LATIN'",
"and",
"what",
"[",
"2",
"]",
"==",
"'LETTER'",
"and",
"len",
"(",
"what",
"[",
"3",
"]",
")",
"==",
"1",
":",
"ch",
"=",
"what",
"[",
"3",
"]",
".",
"lower",
"(",
")",
"if",
"what",
"[",
"1",
"]",
"==",
"'SMALL'",
"else",
"what",
"[",
"3",
"]",
".",
"upper",
"(",
")",
"else",
":",
"ch",
"=",
"default",
"converted",
".",
"append",
"(",
"chr",
"(",
"ord",
"(",
"ch",
")",
")",
")",
"return",
"''",
".",
"join",
"(",
"converted",
")"
] | [
735,
0
] | [
778,
29
] | python | en | ['en', 'error', 'th'] | False |
to_unicode | (obj, encoding='utf-8', force_string=False) |
This decodes a suitable object to the unicode format.
Args:
obj (any): Object to decode to unicode.
encoding (str, optional): The encoding type to use for the
dedoding.
force_string (bool, optional): Always convert to string, no
matter what type `obj` is initially.
Returns:
result (unicode or any): Will return a unicode object if input
was a string. If input was not a string, the original will be
returned unchanged unless `force_string` is also set.
Notes:
One needs to encode the obj back to utf-8 before writing to disk
or printing. That non-string objects are let through without
conversion is important for e.g. Attributes.
|
This decodes a suitable object to the unicode format. | def to_unicode(obj, encoding='utf-8', force_string=False):
"""
This decodes a suitable object to the unicode format.
Args:
obj (any): Object to decode to unicode.
encoding (str, optional): The encoding type to use for the
dedoding.
force_string (bool, optional): Always convert to string, no
matter what type `obj` is initially.
Returns:
result (unicode or any): Will return a unicode object if input
was a string. If input was not a string, the original will be
returned unchanged unless `force_string` is also set.
Notes:
One needs to encode the obj back to utf-8 before writing to disk
or printing. That non-string objects are let through without
conversion is important for e.g. Attributes.
"""
if force_string and not isinstance(obj, basestring):
# some sort of other object. Try to
# convert it to a string representation.
if hasattr(obj, '__str__'):
obj = obj.__str__()
elif hasattr(obj, '__unicode__'):
obj = obj.__unicode__()
else:
# last resort
obj = str(obj)
if isinstance(obj, basestring) and not isinstance(obj, unicode):
try:
obj = unicode(obj, encoding)
return obj
except UnicodeDecodeError:
for alt_encoding in ENCODINGS:
try:
obj = unicode(obj, alt_encoding)
return obj
except UnicodeDecodeError:
# if we still have an error, give up
pass
raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding))
return obj | [
"def",
"to_unicode",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"force_string",
"=",
"False",
")",
":",
"if",
"force_string",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
":",
"# some sort of other object. Try to",
"# convert it to a string representation.",
"if",
"hasattr",
"(",
"obj",
",",
"'__str__'",
")",
":",
"obj",
"=",
"obj",
".",
"__str__",
"(",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'__unicode__'",
")",
":",
"obj",
"=",
"obj",
".",
"__unicode__",
"(",
")",
"else",
":",
"# last resort",
"obj",
"=",
"str",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"unicode",
")",
":",
"try",
":",
"obj",
"=",
"unicode",
"(",
"obj",
",",
"encoding",
")",
"return",
"obj",
"except",
"UnicodeDecodeError",
":",
"for",
"alt_encoding",
"in",
"ENCODINGS",
":",
"try",
":",
"obj",
"=",
"unicode",
"(",
"obj",
",",
"alt_encoding",
")",
"return",
"obj",
"except",
"UnicodeDecodeError",
":",
"# if we still have an error, give up",
"pass",
"raise",
"Exception",
"(",
"\"Error: '%s' contains invalid character(s) not in %s.\"",
"%",
"(",
"obj",
",",
"encoding",
")",
")",
"return",
"obj"
] | [
781,
0
] | [
828,
14
] | python | en | ['en', 'error', 'th'] | False |
to_str | (obj, encoding='utf-8', force_string=False) |
This encodes a unicode string back to byte-representation,
for printing, writing to disk etc.
Args:
obj (any): Object to encode to bytecode.
encoding (str, optional): The encoding type to use for the
encoding.
force_string (bool, optional): Always convert to string, no
matter what type `obj` is initially.
Notes:
Non-string objects are let through without modification - this
is required e.g. for Attributes. Use `force_string` to force
conversion of objects to strings.
|
This encodes a unicode string back to byte-representation,
for printing, writing to disk etc. | def to_str(obj, encoding='utf-8', force_string=False):
"""
This encodes a unicode string back to byte-representation,
for printing, writing to disk etc.
Args:
obj (any): Object to encode to bytecode.
encoding (str, optional): The encoding type to use for the
encoding.
force_string (bool, optional): Always convert to string, no
matter what type `obj` is initially.
Notes:
Non-string objects are let through without modification - this
is required e.g. for Attributes. Use `force_string` to force
conversion of objects to strings.
"""
if force_string and not isinstance(obj, basestring):
# some sort of other object. Try to
# convert it to a string representation.
try:
obj = str(obj)
except Exception:
obj = unicode(obj)
if isinstance(obj, basestring) and isinstance(obj, unicode):
try:
obj = obj.encode(encoding)
return obj
except UnicodeEncodeError:
for alt_encoding in ENCODINGS:
try:
obj = obj.encode(alt_encoding)
return obj
except UnicodeEncodeError:
# if we still have an error, give up
pass
# if we get to this point we have not found any way to convert this string. Try to parse it manually,
try:
return latinify(obj, '?')
except Exception as err:
raise Exception("%s, Error: Unicode could not encode unicode string '%s'(%s) to a bytestring. " % (err, obj, encoding))
return obj | [
"def",
"to_str",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"force_string",
"=",
"False",
")",
":",
"if",
"force_string",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
":",
"# some sort of other object. Try to",
"# convert it to a string representation.",
"try",
":",
"obj",
"=",
"str",
"(",
"obj",
")",
"except",
"Exception",
":",
"obj",
"=",
"unicode",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"and",
"isinstance",
"(",
"obj",
",",
"unicode",
")",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"encode",
"(",
"encoding",
")",
"return",
"obj",
"except",
"UnicodeEncodeError",
":",
"for",
"alt_encoding",
"in",
"ENCODINGS",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"encode",
"(",
"alt_encoding",
")",
"return",
"obj",
"except",
"UnicodeEncodeError",
":",
"# if we still have an error, give up",
"pass",
"# if we get to this point we have not found any way to convert this string. Try to parse it manually,",
"try",
":",
"return",
"latinify",
"(",
"obj",
",",
"'?'",
")",
"except",
"Exception",
"as",
"err",
":",
"raise",
"Exception",
"(",
"\"%s, Error: Unicode could not encode unicode string '%s'(%s) to a bytestring. \"",
"%",
"(",
"err",
",",
"obj",
",",
"encoding",
")",
")",
"return",
"obj"
] | [
831,
0
] | [
875,
14
] | python | en | ['en', 'error', 'th'] | False |
validate_email_address | (emailaddress) |
Checks if an email address is syntactically correct.
Args:
emailaddress (str): Email address to validate.
Returns:
is_valid (bool): If this is a valid email or not.
Notes.
(This snippet was adapted from
http://commandline.org.uk/python/email-syntax-check.)
|
Checks if an email address is syntactically correct. | def validate_email_address(emailaddress):
"""
Checks if an email address is syntactically correct.
Args:
emailaddress (str): Email address to validate.
Returns:
is_valid (bool): If this is a valid email or not.
Notes.
(This snippet was adapted from
http://commandline.org.uk/python/email-syntax-check.)
"""
emailaddress = r"%s" % emailaddress
domains = ("aero", "asia", "biz", "cat", "com", "coop",
"edu", "gov", "info", "int", "jobs", "mil", "mobi", "museum",
"name", "net", "org", "pro", "tel", "travel")
# Email address must be more than 7 characters in total.
if len(emailaddress) < 7:
return False # Address too short.
# Split up email address into parts.
try:
localpart, domainname = emailaddress.rsplit('@', 1)
host, toplevel = domainname.rsplit('.', 1)
except ValueError:
return False # Address does not have enough parts.
# Check for Country code or Generic Domain.
if len(toplevel) != 2 and toplevel not in domains:
return False # Not a domain name.
for i in '-_.%+.':
localpart = localpart.replace(i, "")
for i in '-_.':
host = host.replace(i, "")
if localpart.isalnum() and host.isalnum():
return True # Email address is fine.
else:
return False | [
"def",
"validate_email_address",
"(",
"emailaddress",
")",
":",
"emailaddress",
"=",
"r\"%s\"",
"%",
"emailaddress",
"domains",
"=",
"(",
"\"aero\"",
",",
"\"asia\"",
",",
"\"biz\"",
",",
"\"cat\"",
",",
"\"com\"",
",",
"\"coop\"",
",",
"\"edu\"",
",",
"\"gov\"",
",",
"\"info\"",
",",
"\"int\"",
",",
"\"jobs\"",
",",
"\"mil\"",
",",
"\"mobi\"",
",",
"\"museum\"",
",",
"\"name\"",
",",
"\"net\"",
",",
"\"org\"",
",",
"\"pro\"",
",",
"\"tel\"",
",",
"\"travel\"",
")",
"# Email address must be more than 7 characters in total.",
"if",
"len",
"(",
"emailaddress",
")",
"<",
"7",
":",
"return",
"False",
"# Address too short.",
"# Split up email address into parts.",
"try",
":",
"localpart",
",",
"domainname",
"=",
"emailaddress",
".",
"rsplit",
"(",
"'@'",
",",
"1",
")",
"host",
",",
"toplevel",
"=",
"domainname",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"return",
"False",
"# Address does not have enough parts.",
"# Check for Country code or Generic Domain.",
"if",
"len",
"(",
"toplevel",
")",
"!=",
"2",
"and",
"toplevel",
"not",
"in",
"domains",
":",
"return",
"False",
"# Not a domain name.",
"for",
"i",
"in",
"'-_.%+.'",
":",
"localpart",
"=",
"localpart",
".",
"replace",
"(",
"i",
",",
"\"\"",
")",
"for",
"i",
"in",
"'-_.'",
":",
"host",
"=",
"host",
".",
"replace",
"(",
"i",
",",
"\"\"",
")",
"if",
"localpart",
".",
"isalnum",
"(",
")",
"and",
"host",
".",
"isalnum",
"(",
")",
":",
"return",
"True",
"# Email address is fine.",
"else",
":",
"return",
"False"
] | [
878,
0
] | [
923,
20
] | python | en | ['en', 'error', 'th'] | False |
inherits_from | (obj, parent) |
Takes an object and tries to determine if it inherits at *any*
distance from parent.
Args:
obj (any): Object to analyze. This may be either an instance
or a class.
parent (any): Can be either instance, class or python path to class.
Returns:
inherits_from (bool): If `parent` is a parent to `obj` or not.
Notes:
What differs this function from e.g. `isinstance()` is that `obj`
may be both an instance and a class, and parent may be an
instance, a class, or the python path to a class (counting from
the evennia root directory).
|
Takes an object and tries to determine if it inherits at *any*
distance from parent. | def inherits_from(obj, parent):
"""
Takes an object and tries to determine if it inherits at *any*
distance from parent.
Args:
obj (any): Object to analyze. This may be either an instance
or a class.
parent (any): Can be either instance, class or python path to class.
Returns:
inherits_from (bool): If `parent` is a parent to `obj` or not.
Notes:
What differs this function from e.g. `isinstance()` is that `obj`
may be both an instance and a class, and parent may be an
instance, a class, or the python path to a class (counting from
the evennia root directory).
"""
if callable(obj):
# this is a class
obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.mro()]
else:
obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.__class__.mro()]
if isinstance(parent, basestring):
# a given string path, for direct matching
parent_path = parent
elif callable(parent):
# this is a class
parent_path = "%s.%s" % (parent.__module__, parent.__name__)
else:
parent_path = "%s.%s" % (parent.__class__.__module__, parent.__class__.__name__)
return any(1 for obj_path in obj_paths if obj_path == parent_path) | [
"def",
"inherits_from",
"(",
"obj",
",",
"parent",
")",
":",
"if",
"callable",
"(",
"obj",
")",
":",
"# this is a class",
"obj_paths",
"=",
"[",
"\"%s.%s\"",
"%",
"(",
"mod",
".",
"__module__",
",",
"mod",
".",
"__name__",
")",
"for",
"mod",
"in",
"obj",
".",
"mro",
"(",
")",
"]",
"else",
":",
"obj_paths",
"=",
"[",
"\"%s.%s\"",
"%",
"(",
"mod",
".",
"__module__",
",",
"mod",
".",
"__name__",
")",
"for",
"mod",
"in",
"obj",
".",
"__class__",
".",
"mro",
"(",
")",
"]",
"if",
"isinstance",
"(",
"parent",
",",
"basestring",
")",
":",
"# a given string path, for direct matching",
"parent_path",
"=",
"parent",
"elif",
"callable",
"(",
"parent",
")",
":",
"# this is a class",
"parent_path",
"=",
"\"%s.%s\"",
"%",
"(",
"parent",
".",
"__module__",
",",
"parent",
".",
"__name__",
")",
"else",
":",
"parent_path",
"=",
"\"%s.%s\"",
"%",
"(",
"parent",
".",
"__class__",
".",
"__module__",
",",
"parent",
".",
"__class__",
".",
"__name__",
")",
"return",
"any",
"(",
"1",
"for",
"obj_path",
"in",
"obj_paths",
"if",
"obj_path",
"==",
"parent_path",
")"
] | [
926,
0
] | [
961,
70
] | python | en | ['en', 'error', 'th'] | False |
server_services | () |
Lists all services active on the Server. Observe that since
services are launched in memory, this function will only return
any results if called from inside the game.
Returns:
services (dict): A dict of available services.
|
Lists all services active on the Server. Observe that since
services are launched in memory, this function will only return
any results if called from inside the game. | def server_services():
"""
Lists all services active on the Server. Observe that since
services are launched in memory, this function will only return
any results if called from inside the game.
Returns:
services (dict): A dict of available services.
"""
from evennia.server.sessionhandler import SESSIONS
if hasattr(SESSIONS, "server") and hasattr(SESSIONS.server, "services"):
server = SESSIONS.server.services.namedServices
else:
# This function must be called from inside the evennia process.
server = {}
del SESSIONS
return server | [
"def",
"server_services",
"(",
")",
":",
"from",
"evennia",
".",
"server",
".",
"sessionhandler",
"import",
"SESSIONS",
"if",
"hasattr",
"(",
"SESSIONS",
",",
"\"server\"",
")",
"and",
"hasattr",
"(",
"SESSIONS",
".",
"server",
",",
"\"services\"",
")",
":",
"server",
"=",
"SESSIONS",
".",
"server",
".",
"services",
".",
"namedServices",
"else",
":",
"# This function must be called from inside the evennia process.",
"server",
"=",
"{",
"}",
"del",
"SESSIONS",
"return",
"server"
] | [
964,
0
] | [
981,
17
] | python | en | ['en', 'error', 'th'] | False |
uses_database | (name="sqlite3") |
Checks if the game is currently using a given database. This is a
shortcut to having to use the full backend name.
Args:
name (str): One of 'sqlite3', 'mysql', 'postgresql_psycopg2'
or 'oracle'.
Returns:
uses (bool): If the given database is used or not.
|
Checks if the game is currently using a given database. This is a
shortcut to having to use the full backend name. | def uses_database(name="sqlite3"):
"""
Checks if the game is currently using a given database. This is a
shortcut to having to use the full backend name.
Args:
name (str): One of 'sqlite3', 'mysql', 'postgresql_psycopg2'
or 'oracle'.
Returns:
uses (bool): If the given database is used or not.
"""
try:
engine = settings.DATABASES["default"]["ENGINE"]
except KeyError:
engine = settings.DATABASE_ENGINE
return engine == "django.db.backends.%s" % name | [
"def",
"uses_database",
"(",
"name",
"=",
"\"sqlite3\"",
")",
":",
"try",
":",
"engine",
"=",
"settings",
".",
"DATABASES",
"[",
"\"default\"",
"]",
"[",
"\"ENGINE\"",
"]",
"except",
"KeyError",
":",
"engine",
"=",
"settings",
".",
"DATABASE_ENGINE",
"return",
"engine",
"==",
"\"django.db.backends.%s\"",
"%",
"name"
] | [
984,
0
] | [
1001,
51
] | python | en | ['en', 'error', 'th'] | False |
delay | (timedelay, callback, *args, **kwargs) |
Delay the return of a value.
Args:
timedelay (int or float): The delay in seconds
callback (callable): Will be called as `callback(*args, **kwargs)`
after `timedelay` seconds.
args (any, optional): Will be used as arguments to callback
Kwargs:
persistent (bool, optional): should make the delay persistent
over a reboot or reload
any (any): Will be used as keyword arguments to callback.
Returns:
deferred (deferred): Will fire with callback after
`timedelay` seconds. Note that if `timedelay()` is used in the
commandhandler callback chain, the callback chain can be
defined directly in the command body and don't need to be
specified here.
Note:
The task handler (`evennia.scripts.taskhandler.TASK_HANDLER`) will
be called for persistent or non-persistent tasks.
If persistent is set to True, the callback, its arguments
and other keyword arguments will be saved in the database,
assuming they can be. The callback will be executed even after
a server restart/reload, taking into account the specified delay
(and server down time).
|
Delay the return of a value. | def delay(timedelay, callback, *args, **kwargs):
"""
Delay the return of a value.
Args:
timedelay (int or float): The delay in seconds
callback (callable): Will be called as `callback(*args, **kwargs)`
after `timedelay` seconds.
args (any, optional): Will be used as arguments to callback
Kwargs:
persistent (bool, optional): should make the delay persistent
over a reboot or reload
any (any): Will be used as keyword arguments to callback.
Returns:
deferred (deferred): Will fire with callback after
`timedelay` seconds. Note that if `timedelay()` is used in the
commandhandler callback chain, the callback chain can be
defined directly in the command body and don't need to be
specified here.
Note:
The task handler (`evennia.scripts.taskhandler.TASK_HANDLER`) will
be called for persistent or non-persistent tasks.
If persistent is set to True, the callback, its arguments
and other keyword arguments will be saved in the database,
assuming they can be. The callback will be executed even after
a server restart/reload, taking into account the specified delay
(and server down time).
"""
global _TASK_HANDLER
# Do some imports here to avoid circular import and speed things up
if _TASK_HANDLER is None:
from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER
return _TASK_HANDLER.add(timedelay, callback, *args, **kwargs) | [
"def",
"delay",
"(",
"timedelay",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_TASK_HANDLER",
"# Do some imports here to avoid circular import and speed things up",
"if",
"_TASK_HANDLER",
"is",
"None",
":",
"from",
"evennia",
".",
"scripts",
".",
"taskhandler",
"import",
"TASK_HANDLER",
"as",
"_TASK_HANDLER",
"return",
"_TASK_HANDLER",
".",
"add",
"(",
"timedelay",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
1007,
0
] | [
1042,
66
] | python | en | ['en', 'error', 'th'] | False |
clean_object_caches | (obj) |
Clean all object caches on the given object.
Args:
obj (Object instace): An object whose caches to clean.
Notes:
This is only the contents cache these days.
|
Clean all object caches on the given object. | def clean_object_caches(obj):
"""
Clean all object caches on the given object.
Args:
obj (Object instace): An object whose caches to clean.
Notes:
This is only the contents cache these days.
"""
global _TYPECLASSMODELS, _OBJECTMODELS
if not _TYPECLASSMODELS:
from evennia.typeclasses import models as _TYPECLASSMODELS
if not obj:
return
# contents cache
try:
_SA(obj, "_contents_cache", None)
except AttributeError:
# if the cache cannot be reached, move on anyway
pass
# on-object property cache
[_DA(obj, cname) for cname in viewkeys(obj.__dict__)
if cname.startswith("_cached_db_")]
try:
hashid = _GA(obj, "hashid")
_TYPECLASSMODELS._ATTRIBUTE_CACHE[hashid] = {}
except AttributeError:
# skip caching
pass | [
"def",
"clean_object_caches",
"(",
"obj",
")",
":",
"global",
"_TYPECLASSMODELS",
",",
"_OBJECTMODELS",
"if",
"not",
"_TYPECLASSMODELS",
":",
"from",
"evennia",
".",
"typeclasses",
"import",
"models",
"as",
"_TYPECLASSMODELS",
"if",
"not",
"obj",
":",
"return",
"# contents cache",
"try",
":",
"_SA",
"(",
"obj",
",",
"\"_contents_cache\"",
",",
"None",
")",
"except",
"AttributeError",
":",
"# if the cache cannot be reached, move on anyway",
"pass",
"# on-object property cache",
"[",
"_DA",
"(",
"obj",
",",
"cname",
")",
"for",
"cname",
"in",
"viewkeys",
"(",
"obj",
".",
"__dict__",
")",
"if",
"cname",
".",
"startswith",
"(",
"\"_cached_db_\"",
")",
"]",
"try",
":",
"hashid",
"=",
"_GA",
"(",
"obj",
",",
"\"hashid\"",
")",
"_TYPECLASSMODELS",
".",
"_ATTRIBUTE_CACHE",
"[",
"hashid",
"]",
"=",
"{",
"}",
"except",
"AttributeError",
":",
"# skip caching",
"pass"
] | [
1049,
0
] | [
1081,
12
] | python | en | ['en', 'error', 'th'] | False |
run_async | (to_execute, *args, **kwargs) |
Runs a function or executes a code snippet asynchronously.
Args:
to_execute (callable): If this is a callable, it will be
executed with *args and non-reserved *kwargs as arguments.
The callable will be executed using ProcPool, or in a thread
if ProcPool is not available.
Kwargs:
at_return (callable): Should point to a callable with one
argument. It will be called with the return value from
to_execute.
at_return_kwargs (dict): This dictionary will be used as
keyword arguments to the at_return callback.
at_err (callable): This will be called with a Failure instance
if there is an error in to_execute.
at_err_kwargs (dict): This dictionary will be used as keyword
arguments to the at_err errback.
Notes:
All other `*args` and `**kwargs` will be passed on to
`to_execute`. Run_async will relay executed code to a thread
or procpool.
Use this function with restrain and only for features/commands
that you know has no influence on the cause-and-effect order of your
game (commands given after the async function might be executed before
it has finished). Accessing the same property from different threads
can lead to unpredicted behaviour if you are not careful (this is called a
"race condition").
Also note that some databases, notably sqlite3, don't support access from
multiple threads simultaneously, so if you do heavy database access from
your `to_execute` under sqlite3 you will probably run very slow or even get
tracebacks.
|
Runs a function or executes a code snippet asynchronously. | def run_async(to_execute, *args, **kwargs):
"""
Runs a function or executes a code snippet asynchronously.
Args:
to_execute (callable): If this is a callable, it will be
executed with *args and non-reserved *kwargs as arguments.
The callable will be executed using ProcPool, or in a thread
if ProcPool is not available.
Kwargs:
at_return (callable): Should point to a callable with one
argument. It will be called with the return value from
to_execute.
at_return_kwargs (dict): This dictionary will be used as
keyword arguments to the at_return callback.
at_err (callable): This will be called with a Failure instance
if there is an error in to_execute.
at_err_kwargs (dict): This dictionary will be used as keyword
arguments to the at_err errback.
Notes:
All other `*args` and `**kwargs` will be passed on to
`to_execute`. Run_async will relay executed code to a thread
or procpool.
Use this function with restrain and only for features/commands
that you know has no influence on the cause-and-effect order of your
game (commands given after the async function might be executed before
it has finished). Accessing the same property from different threads
can lead to unpredicted behaviour if you are not careful (this is called a
"race condition").
Also note that some databases, notably sqlite3, don't support access from
multiple threads simultaneously, so if you do heavy database access from
your `to_execute` under sqlite3 you will probably run very slow or even get
tracebacks.
"""
# handle special reserved input kwargs
callback = kwargs.pop("at_return", None)
errback = kwargs.pop("at_err", None)
callback_kwargs = kwargs.pop("at_return_kwargs", {})
errback_kwargs = kwargs.pop("at_err_kwargs", {})
if callable(to_execute):
# no process pool available, fall back to old deferToThread mechanism.
deferred = threads.deferToThread(to_execute, *args, **kwargs)
else:
# no appropriate input for this server setup
raise RuntimeError("'%s' could not be handled by run_async" % to_execute)
# attach callbacks
if callback:
deferred.addCallback(callback, **callback_kwargs)
deferred.addErrback(errback, **errback_kwargs) | [
"def",
"run_async",
"(",
"to_execute",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# handle special reserved input kwargs",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"\"at_return\"",
",",
"None",
")",
"errback",
"=",
"kwargs",
".",
"pop",
"(",
"\"at_err\"",
",",
"None",
")",
"callback_kwargs",
"=",
"kwargs",
".",
"pop",
"(",
"\"at_return_kwargs\"",
",",
"{",
"}",
")",
"errback_kwargs",
"=",
"kwargs",
".",
"pop",
"(",
"\"at_err_kwargs\"",
",",
"{",
"}",
")",
"if",
"callable",
"(",
"to_execute",
")",
":",
"# no process pool available, fall back to old deferToThread mechanism.",
"deferred",
"=",
"threads",
".",
"deferToThread",
"(",
"to_execute",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"# no appropriate input for this server setup",
"raise",
"RuntimeError",
"(",
"\"'%s' could not be handled by run_async\"",
"%",
"to_execute",
")",
"# attach callbacks",
"if",
"callback",
":",
"deferred",
".",
"addCallback",
"(",
"callback",
",",
"*",
"*",
"callback_kwargs",
")",
"deferred",
".",
"addErrback",
"(",
"errback",
",",
"*",
"*",
"errback_kwargs",
")"
] | [
1089,
0
] | [
1145,
50
] | python | en | ['en', 'error', 'th'] | False |
check_evennia_dependencies | () |
Checks the versions of Evennia's dependencies including making
some checks for runtime libraries.
Returns:
result (bool): `False` if a show-stopping version mismatch is
found.
|
Checks the versions of Evennia's dependencies including making
some checks for runtime libraries. | def check_evennia_dependencies():
"""
Checks the versions of Evennia's dependencies including making
some checks for runtime libraries.
Returns:
result (bool): `False` if a show-stopping version mismatch is
found.
"""
# check main dependencies
from evennia.server.evennia_launcher import check_main_evennia_dependencies
not_error = check_main_evennia_dependencies()
errstring = ""
# South is no longer used ...
if 'south' in settings.INSTALLED_APPS:
errstring += "\n ERROR: 'south' found in settings.INSTALLED_APPS. " \
"\n South is no longer used. If this was added manually, remove it."
not_error = False
# IRC support
if settings.IRC_ENABLED:
try:
import twisted.words
twisted.words # set to avoid debug info about not-used import
except ImportError:
errstring += "\n ERROR: IRC is enabled, but twisted.words is not installed. Please install it." \
"\n Linux Debian/Ubuntu users should install package 'python-twisted-words', others" \
"\n can get it from http://twistedmatrix.com/trac/wiki/TwistedWords."
not_error = False
errstring = errstring.strip()
if errstring:
mlen = max(len(line) for line in errstring.split("\n"))
logger.log_err("%s\n%s\n%s" % ("-" * mlen, errstring, '-' * mlen))
return not_error | [
"def",
"check_evennia_dependencies",
"(",
")",
":",
"# check main dependencies",
"from",
"evennia",
".",
"server",
".",
"evennia_launcher",
"import",
"check_main_evennia_dependencies",
"not_error",
"=",
"check_main_evennia_dependencies",
"(",
")",
"errstring",
"=",
"\"\"",
"# South is no longer used ...",
"if",
"'south'",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"errstring",
"+=",
"\"\\n ERROR: 'south' found in settings.INSTALLED_APPS. \"",
"\"\\n South is no longer used. If this was added manually, remove it.\"",
"not_error",
"=",
"False",
"# IRC support",
"if",
"settings",
".",
"IRC_ENABLED",
":",
"try",
":",
"import",
"twisted",
".",
"words",
"twisted",
".",
"words",
"# set to avoid debug info about not-used import",
"except",
"ImportError",
":",
"errstring",
"+=",
"\"\\n ERROR: IRC is enabled, but twisted.words is not installed. Please install it.\"",
"\"\\n Linux Debian/Ubuntu users should install package 'python-twisted-words', others\"",
"\"\\n can get it from http://twistedmatrix.com/trac/wiki/TwistedWords.\"",
"not_error",
"=",
"False",
"errstring",
"=",
"errstring",
".",
"strip",
"(",
")",
"if",
"errstring",
":",
"mlen",
"=",
"max",
"(",
"len",
"(",
"line",
")",
"for",
"line",
"in",
"errstring",
".",
"split",
"(",
"\"\\n\"",
")",
")",
"logger",
".",
"log_err",
"(",
"\"%s\\n%s\\n%s\"",
"%",
"(",
"\"-\"",
"*",
"mlen",
",",
"errstring",
",",
"'-'",
"*",
"mlen",
")",
")",
"return",
"not_error"
] | [
1148,
0
] | [
1183,
20
] | python | en | ['en', 'error', 'th'] | False |
has_parent | (basepath, obj) |
Checks if `basepath` is somewhere in `obj`s parent tree.
Args:
basepath (str): Python dotpath to compare against obj path.
obj (any): Object whose path is to be checked.
Returns:
has_parent (bool): If the check was successful or not.
|
Checks if `basepath` is somewhere in `obj`s parent tree. | def has_parent(basepath, obj):
"""
Checks if `basepath` is somewhere in `obj`s parent tree.
Args:
basepath (str): Python dotpath to compare against obj path.
obj (any): Object whose path is to be checked.
Returns:
has_parent (bool): If the check was successful or not.
"""
try:
return any(cls for cls in obj.__class__.mro()
if basepath == "%s.%s" % (cls.__module__, cls.__name__))
except (TypeError, AttributeError):
# this can occur if we tried to store a class object, not an
# instance. Not sure if one should defend against this.
return False | [
"def",
"has_parent",
"(",
"basepath",
",",
"obj",
")",
":",
"try",
":",
"return",
"any",
"(",
"cls",
"for",
"cls",
"in",
"obj",
".",
"__class__",
".",
"mro",
"(",
")",
"if",
"basepath",
"==",
"\"%s.%s\"",
"%",
"(",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
")",
")",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"# this can occur if we tried to store a class object, not an",
"# instance. Not sure if one should defend against this.",
"return",
"False"
] | [
1186,
0
] | [
1204,
20
] | python | en | ['en', 'error', 'th'] | False |
mod_import | (module) |
A generic Python module loader.
Args:
module (str, module): This can be either a Python path
(dot-notation like `evennia.objects.models`), an absolute path
(e.g. `/home/eve/evennia/evennia/objects.models.py`) or an
already imported module object (e.g. `models`)
Returns:
module (module or None): An imported module. If the input argument was
already a module, this is returned as-is, otherwise the path is
parsed and imported. Returns `None` and logs error if import failed.
|
A generic Python module loader. | def mod_import(module):
"""
A generic Python module loader.
Args:
module (str, module): This can be either a Python path
(dot-notation like `evennia.objects.models`), an absolute path
(e.g. `/home/eve/evennia/evennia/objects.models.py`) or an
already imported module object (e.g. `models`)
Returns:
module (module or None): An imported module. If the input argument was
already a module, this is returned as-is, otherwise the path is
parsed and imported. Returns `None` and logs error if import failed.
"""
if not module:
return None
if isinstance(module, types.ModuleType):
# if this is already a module, we are done
mod = module
else:
# first try to import as a python path
try:
mod = __import__(module, fromlist=["None"])
except ImportError as ex:
# check just where the ImportError happened (it could have been
# an erroneous import inside the module as well). This is the
# trivial way to do it ...
if str(ex) != "Import by filename is not supported.":
raise
# error in this module. Try absolute path import instead
if not os.path.isabs(module):
module = os.path.abspath(module)
path, filename = module.rsplit(os.path.sep, 1)
modname = re.sub(r"\.py$", "", filename)
try:
result = imp.find_module(modname, [path])
except ImportError:
logger.log_trace("Could not find module '%s' (%s.py) at path '%s'" % (modname, modname, path))
return None
try:
mod = imp.load_module(modname, *result)
except ImportError:
logger.log_trace("Could not find or import module %s at path '%s'" % (modname, path))
mod = None
# we have to close the file handle manually
result[0].close()
return mod | [
"def",
"mod_import",
"(",
"module",
")",
":",
"if",
"not",
"module",
":",
"return",
"None",
"if",
"isinstance",
"(",
"module",
",",
"types",
".",
"ModuleType",
")",
":",
"# if this is already a module, we are done",
"mod",
"=",
"module",
"else",
":",
"# first try to import as a python path",
"try",
":",
"mod",
"=",
"__import__",
"(",
"module",
",",
"fromlist",
"=",
"[",
"\"None\"",
"]",
")",
"except",
"ImportError",
"as",
"ex",
":",
"# check just where the ImportError happened (it could have been",
"# an erroneous import inside the module as well). This is the",
"# trivial way to do it ...",
"if",
"str",
"(",
"ex",
")",
"!=",
"\"Import by filename is not supported.\"",
":",
"raise",
"# error in this module. Try absolute path import instead",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"module",
")",
":",
"module",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"module",
")",
"path",
",",
"filename",
"=",
"module",
".",
"rsplit",
"(",
"os",
".",
"path",
".",
"sep",
",",
"1",
")",
"modname",
"=",
"re",
".",
"sub",
"(",
"r\"\\.py$\"",
",",
"\"\"",
",",
"filename",
")",
"try",
":",
"result",
"=",
"imp",
".",
"find_module",
"(",
"modname",
",",
"[",
"path",
"]",
")",
"except",
"ImportError",
":",
"logger",
".",
"log_trace",
"(",
"\"Could not find module '%s' (%s.py) at path '%s'\"",
"%",
"(",
"modname",
",",
"modname",
",",
"path",
")",
")",
"return",
"None",
"try",
":",
"mod",
"=",
"imp",
".",
"load_module",
"(",
"modname",
",",
"*",
"result",
")",
"except",
"ImportError",
":",
"logger",
".",
"log_trace",
"(",
"\"Could not find or import module %s at path '%s'\"",
"%",
"(",
"modname",
",",
"path",
")",
")",
"mod",
"=",
"None",
"# we have to close the file handle manually",
"result",
"[",
"0",
"]",
".",
"close",
"(",
")",
"return",
"mod"
] | [
1207,
0
] | [
1259,
14
] | python | en | ['en', 'error', 'th'] | False |
all_from_module | (module) |
Return all global-level variables defined in a module.
Args:
module (str, module): This can be either a Python path
(dot-notation like `evennia.objects.models`), an absolute path
(e.g. `/home/eve/evennia/evennia/objects.models.py`) or an
already imported module object (e.g. `models`)
Returns:
variables (dict): A dict of {variablename: variable} for all
variables in the given module.
Notes:
Ignores modules and variable names starting with an underscore.
|
Return all global-level variables defined in a module. | def all_from_module(module):
"""
Return all global-level variables defined in a module.
Args:
module (str, module): This can be either a Python path
(dot-notation like `evennia.objects.models`), an absolute path
(e.g. `/home/eve/evennia/evennia/objects.models.py`) or an
already imported module object (e.g. `models`)
Returns:
variables (dict): A dict of {variablename: variable} for all
variables in the given module.
Notes:
Ignores modules and variable names starting with an underscore.
"""
mod = mod_import(module)
if not mod:
return {}
# make sure to only return variables actually defined in this
# module if available (try to avoid not imports)
members = getmembers(mod, predicate=lambda obj: getmodule(obj) in (mod, None))
return dict((key, val) for key, val in members if not key.startswith("_")) | [
"def",
"all_from_module",
"(",
"module",
")",
":",
"mod",
"=",
"mod_import",
"(",
"module",
")",
"if",
"not",
"mod",
":",
"return",
"{",
"}",
"# make sure to only return variables actually defined in this",
"# module if available (try to avoid not imports)",
"members",
"=",
"getmembers",
"(",
"mod",
",",
"predicate",
"=",
"lambda",
"obj",
":",
"getmodule",
"(",
"obj",
")",
"in",
"(",
"mod",
",",
"None",
")",
")",
"return",
"dict",
"(",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"members",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"_\"",
")",
")"
] | [
1262,
0
] | [
1286,
78
] | python | en | ['en', 'error', 'th'] | False |
callables_from_module | (module) |
Return all global-level callables defined in a module.
Args:
module (str, module): A python-path to a module or an actual
module object.
Returns:
callables (dict): A dict of {name: callable, ...} from the module.
Notes:
Will ignore callables whose names start with underscore "_".
|
Return all global-level callables defined in a module. | def callables_from_module(module):
"""
Return all global-level callables defined in a module.
Args:
module (str, module): A python-path to a module or an actual
module object.
Returns:
callables (dict): A dict of {name: callable, ...} from the module.
Notes:
Will ignore callables whose names start with underscore "_".
"""
mod = mod_import(module)
if not mod:
return {}
# make sure to only return callables actually defined in this module (not imports)
members = getmembers(mod, predicate=lambda obj: callable(obj) and getmodule(obj) == mod)
return dict((key, val) for key, val in members if not key.startswith("_")) | [
"def",
"callables_from_module",
"(",
"module",
")",
":",
"mod",
"=",
"mod_import",
"(",
"module",
")",
"if",
"not",
"mod",
":",
"return",
"{",
"}",
"# make sure to only return callables actually defined in this module (not imports)",
"members",
"=",
"getmembers",
"(",
"mod",
",",
"predicate",
"=",
"lambda",
"obj",
":",
"callable",
"(",
"obj",
")",
"and",
"getmodule",
"(",
"obj",
")",
"==",
"mod",
")",
"return",
"dict",
"(",
"(",
"key",
",",
"val",
")",
"for",
"key",
",",
"val",
"in",
"members",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"_\"",
")",
")"
] | [
1289,
0
] | [
1309,
78
] | python | en | ['en', 'error', 'th'] | False |
variable_from_module | (module, variable=None, default=None) |
Retrieve a variable or list of variables from a module. The
variable(s) must be defined globally in the module. If no variable
is given (or a list entry is `None`), all global variables are
extracted from the module.
Args:
module (string or module): Python path, absolute path or a module.
variable (string or iterable, optional): Single variable name or iterable
of variable names to extract. If not given, all variables in
the module will be returned.
default (string, optional): Default value to use if a variable fails to
be extracted. Ignored if `variable` is not given.
Returns:
variables (value or list): A single value or a list of values
depending on if `variable` is given or not. Errors in lists
are replaced by the `default` argument.
|
Retrieve a variable or list of variables from a module. The
variable(s) must be defined globally in the module. If no variable
is given (or a list entry is `None`), all global variables are
extracted from the module. | def variable_from_module(module, variable=None, default=None):
"""
Retrieve a variable or list of variables from a module. The
variable(s) must be defined globally in the module. If no variable
is given (or a list entry is `None`), all global variables are
extracted from the module.
Args:
module (string or module): Python path, absolute path or a module.
variable (string or iterable, optional): Single variable name or iterable
of variable names to extract. If not given, all variables in
the module will be returned.
default (string, optional): Default value to use if a variable fails to
be extracted. Ignored if `variable` is not given.
Returns:
variables (value or list): A single value or a list of values
depending on if `variable` is given or not. Errors in lists
are replaced by the `default` argument.
"""
if not module:
return default
mod = mod_import(module)
if variable:
result = []
for var in make_iter(variable):
if var:
# try to pick a named variable
result.append(mod.__dict__.get(var, default))
else:
# get all
result = [val for key, val in mod.__dict__.items()
if not (key.startswith("_") or ismodule(val))]
if len(result) == 1:
return result[0]
return result | [
"def",
"variable_from_module",
"(",
"module",
",",
"variable",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"module",
":",
"return",
"default",
"mod",
"=",
"mod_import",
"(",
"module",
")",
"if",
"variable",
":",
"result",
"=",
"[",
"]",
"for",
"var",
"in",
"make_iter",
"(",
"variable",
")",
":",
"if",
"var",
":",
"# try to pick a named variable",
"result",
".",
"append",
"(",
"mod",
".",
"__dict__",
".",
"get",
"(",
"var",
",",
"default",
")",
")",
"else",
":",
"# get all",
"result",
"=",
"[",
"val",
"for",
"key",
",",
"val",
"in",
"mod",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"not",
"(",
"key",
".",
"startswith",
"(",
"\"_\"",
")",
"or",
"ismodule",
"(",
"val",
")",
")",
"]",
"if",
"len",
"(",
"result",
")",
"==",
"1",
":",
"return",
"result",
"[",
"0",
"]",
"return",
"result"
] | [
1312,
0
] | [
1352,
17
] | python | en | ['en', 'error', 'th'] | False |
string_from_module | (module, variable=None, default=None) |
This is a wrapper for `variable_from_module` that requires return
value to be a string to pass. It's primarily used by login screen.
Args:
module (string or module): Python path, absolute path or a module.
variable (string or iterable, optional): Single variable name or iterable
of variable names to extract. If not given, all variables in
the module will be returned.
default (string, optional): Default value to use if a variable fails to
be extracted. Ignored if `variable` is not given.
Returns:
variables (value or list): A single (string) value or a list of values
depending on if `variable` is given or not. Errors in lists (such
as the value not being a string) are replaced by the `default` argument.
|
This is a wrapper for `variable_from_module` that requires return
value to be a string to pass. It's primarily used by login screen. | def string_from_module(module, variable=None, default=None):
"""
This is a wrapper for `variable_from_module` that requires return
value to be a string to pass. It's primarily used by login screen.
Args:
module (string or module): Python path, absolute path or a module.
variable (string or iterable, optional): Single variable name or iterable
of variable names to extract. If not given, all variables in
the module will be returned.
default (string, optional): Default value to use if a variable fails to
be extracted. Ignored if `variable` is not given.
Returns:
variables (value or list): A single (string) value or a list of values
depending on if `variable` is given or not. Errors in lists (such
as the value not being a string) are replaced by the `default` argument.
"""
val = variable_from_module(module, variable=variable, default=default)
if val:
if variable:
return val
else:
result = [v for v in make_iter(val) if isinstance(v, basestring)]
return result if result else default
return default | [
"def",
"string_from_module",
"(",
"module",
",",
"variable",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"variable_from_module",
"(",
"module",
",",
"variable",
"=",
"variable",
",",
"default",
"=",
"default",
")",
"if",
"val",
":",
"if",
"variable",
":",
"return",
"val",
"else",
":",
"result",
"=",
"[",
"v",
"for",
"v",
"in",
"make_iter",
"(",
"val",
")",
"if",
"isinstance",
"(",
"v",
",",
"basestring",
")",
"]",
"return",
"result",
"if",
"result",
"else",
"default",
"return",
"default"
] | [
1355,
0
] | [
1381,
18
] | python | en | ['en', 'error', 'th'] | False |
random_string_from_module | (module) |
Returns a random global string from a module.
Args:
module (string or module): Python path, absolute path or a module.
Returns:
random (string): A random stribg variable from `module`.
|
Returns a random global string from a module. | def random_string_from_module(module):
"""
Returns a random global string from a module.
Args:
module (string or module): Python path, absolute path or a module.
Returns:
random (string): A random stribg variable from `module`.
"""
return random.choice(string_from_module(module)) | [
"def",
"random_string_from_module",
"(",
"module",
")",
":",
"return",
"random",
".",
"choice",
"(",
"string_from_module",
"(",
"module",
")",
")"
] | [
1384,
0
] | [
1394,
52
] | python | en | ['en', 'error', 'th'] | False |
fuzzy_import_from_module | (path, variable, default=None, defaultpaths=None) |
Import a variable based on a fuzzy path. First the literal
`path` will be tried, then all given `defaultpaths` will be
prepended to see a match is found.
Args:
path (str): Full or partial python path.
variable (str): Name of variable to import from module.
default (string, optional): Default value to use if a variable fails to
be extracted. Ignored if `variable` is not given.
defaultpaths (iterable, options): Python paths to attempt in order if
importing directly from `path` doesn't work.
Returns:
value (any): The variable imported from the module, or `default`, if
not found.
|
Import a variable based on a fuzzy path. First the literal
`path` will be tried, then all given `defaultpaths` will be
prepended to see a match is found. | def fuzzy_import_from_module(path, variable, default=None, defaultpaths=None):
"""
Import a variable based on a fuzzy path. First the literal
`path` will be tried, then all given `defaultpaths` will be
prepended to see a match is found.
Args:
path (str): Full or partial python path.
variable (str): Name of variable to import from module.
default (string, optional): Default value to use if a variable fails to
be extracted. Ignored if `variable` is not given.
defaultpaths (iterable, options): Python paths to attempt in order if
importing directly from `path` doesn't work.
Returns:
value (any): The variable imported from the module, or `default`, if
not found.
"""
paths = [path] + make_iter(defaultpaths)
for modpath in paths:
try:
mod = import_module(modpath)
except ImportError as ex:
if not str(ex).startswith("No module named %s" % modpath):
# this means the module was found but it
# triggers an ImportError on import.
raise ex
return getattr(mod, variable, default)
return default | [
"def",
"fuzzy_import_from_module",
"(",
"path",
",",
"variable",
",",
"default",
"=",
"None",
",",
"defaultpaths",
"=",
"None",
")",
":",
"paths",
"=",
"[",
"path",
"]",
"+",
"make_iter",
"(",
"defaultpaths",
")",
"for",
"modpath",
"in",
"paths",
":",
"try",
":",
"mod",
"=",
"import_module",
"(",
"modpath",
")",
"except",
"ImportError",
"as",
"ex",
":",
"if",
"not",
"str",
"(",
"ex",
")",
".",
"startswith",
"(",
"\"No module named %s\"",
"%",
"modpath",
")",
":",
"# this means the module was found but it",
"# triggers an ImportError on import.",
"raise",
"ex",
"return",
"getattr",
"(",
"mod",
",",
"variable",
",",
"default",
")",
"return",
"default"
] | [
1397,
0
] | [
1426,
18
] | python | en | ['en', 'error', 'th'] | False |
class_from_module | (path, defaultpaths=None) |
Return a class from a module, given the module's path. This is
primarily used to convert db_typeclass_path:s to classes.
Args:
path (str): Full Python dot-path to module.
defaultpaths (iterable, optional): If a direc import from `path` fails,
try subsequent imports by prepending those paths to `path`.
Returns:
class (Class): An uninstatiated class recovered from path.
Raises:
ImportError: If all loading failed.
|
Return a class from a module, given the module's path. This is
primarily used to convert db_typeclass_path:s to classes. | def class_from_module(path, defaultpaths=None):
"""
Return a class from a module, given the module's path. This is
primarily used to convert db_typeclass_path:s to classes.
Args:
path (str): Full Python dot-path to module.
defaultpaths (iterable, optional): If a direc import from `path` fails,
try subsequent imports by prepending those paths to `path`.
Returns:
class (Class): An uninstatiated class recovered from path.
Raises:
ImportError: If all loading failed.
"""
cls = None
if defaultpaths:
paths = [path] + ["%s.%s" % (dpath, path) for dpath in make_iter(defaultpaths)] if defaultpaths else []
else:
paths = [path]
for testpath in paths:
if "." in path:
testpath, clsname = testpath.rsplit(".", 1)
else:
raise ImportError("the path '%s' is not on the form modulepath.Classname." % path)
try:
mod = import_module(testpath, package="evennia")
except ImportError:
if len(trace()) > 2:
# this means the error happened within the called module and
# we must not hide it.
exc = sys.exc_info()
raise_(exc[1], None, exc[2])
else:
# otherwise, try the next suggested path
continue
try:
cls = getattr(mod, clsname)
break
except AttributeError:
if len(trace()) > 2:
# AttributeError within the module, don't hide it
exc = sys.exc_info()
raise_(exc[1], None, exc[2])
if not cls:
err = "Could not load typeclass '%s'" % path
if defaultpaths:
err += "\nPaths searched:\n %s" % "\n ".join(paths)
else:
err += "."
raise ImportError(err)
return cls | [
"def",
"class_from_module",
"(",
"path",
",",
"defaultpaths",
"=",
"None",
")",
":",
"cls",
"=",
"None",
"if",
"defaultpaths",
":",
"paths",
"=",
"[",
"path",
"]",
"+",
"[",
"\"%s.%s\"",
"%",
"(",
"dpath",
",",
"path",
")",
"for",
"dpath",
"in",
"make_iter",
"(",
"defaultpaths",
")",
"]",
"if",
"defaultpaths",
"else",
"[",
"]",
"else",
":",
"paths",
"=",
"[",
"path",
"]",
"for",
"testpath",
"in",
"paths",
":",
"if",
"\".\"",
"in",
"path",
":",
"testpath",
",",
"clsname",
"=",
"testpath",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"else",
":",
"raise",
"ImportError",
"(",
"\"the path '%s' is not on the form modulepath.Classname.\"",
"%",
"path",
")",
"try",
":",
"mod",
"=",
"import_module",
"(",
"testpath",
",",
"package",
"=",
"\"evennia\"",
")",
"except",
"ImportError",
":",
"if",
"len",
"(",
"trace",
"(",
")",
")",
">",
"2",
":",
"# this means the error happened within the called module and",
"# we must not hide it.",
"exc",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise_",
"(",
"exc",
"[",
"1",
"]",
",",
"None",
",",
"exc",
"[",
"2",
"]",
")",
"else",
":",
"# otherwise, try the next suggested path",
"continue",
"try",
":",
"cls",
"=",
"getattr",
"(",
"mod",
",",
"clsname",
")",
"break",
"except",
"AttributeError",
":",
"if",
"len",
"(",
"trace",
"(",
")",
")",
">",
"2",
":",
"# AttributeError within the module, don't hide it",
"exc",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise_",
"(",
"exc",
"[",
"1",
"]",
",",
"None",
",",
"exc",
"[",
"2",
"]",
")",
"if",
"not",
"cls",
":",
"err",
"=",
"\"Could not load typeclass '%s'\"",
"%",
"path",
"if",
"defaultpaths",
":",
"err",
"+=",
"\"\\nPaths searched:\\n %s\"",
"%",
"\"\\n \"",
".",
"join",
"(",
"paths",
")",
"else",
":",
"err",
"+=",
"\".\"",
"raise",
"ImportError",
"(",
"err",
")",
"return",
"cls"
] | [
1429,
0
] | [
1483,
14
] | python | en | ['en', 'error', 'th'] | False |
init_new_account | (account) |
Deprecated.
|
Deprecated.
| def init_new_account(account):
"""
Deprecated.
"""
from evennia.utils import logger
logger.log_dep("evennia.utils.utils.init_new_account is DEPRECATED and should not be used.") | [
"def",
"init_new_account",
"(",
"account",
")",
":",
"from",
"evennia",
".",
"utils",
"import",
"logger",
"logger",
".",
"log_dep",
"(",
"\"evennia.utils.utils.init_new_account is DEPRECATED and should not be used.\"",
")"
] | [
1490,
0
] | [
1495,
96
] | python | en | ['en', 'error', 'th'] | False |
string_similarity | (string1, string2) |
This implements a "cosine-similarity" algorithm as described for example in
*Proceedings of the 22nd International Conference on Computation
Linguistics* (Coling 2008), pages 593-600, Manchester, August 2008.
The measure-vectors used is simply a "bag of words" type histogram
(but for letters).
Args:
string1 (str): String to compare (may contain any number of words).
string2 (str): Second string to compare (any number of words).
Returns:
similarity (float): A value 0...1 rating how similar the two
strings are.
|
This implements a "cosine-similarity" algorithm as described for example in
*Proceedings of the 22nd International Conference on Computation
Linguistics* (Coling 2008), pages 593-600, Manchester, August 2008.
The measure-vectors used is simply a "bag of words" type histogram
(but for letters). | def string_similarity(string1, string2):
"""
This implements a "cosine-similarity" algorithm as described for example in
*Proceedings of the 22nd International Conference on Computation
Linguistics* (Coling 2008), pages 593-600, Manchester, August 2008.
The measure-vectors used is simply a "bag of words" type histogram
(but for letters).
Args:
string1 (str): String to compare (may contain any number of words).
string2 (str): Second string to compare (any number of words).
Returns:
similarity (float): A value 0...1 rating how similar the two
strings are.
"""
vocabulary = set(list(string1 + string2))
vec1 = [string1.count(v) for v in vocabulary]
vec2 = [string2.count(v) for v in vocabulary]
try:
return float(sum(vec1[i] * vec2[i] for i in range(len(vocabulary)))) / \
(math.sqrt(sum(v1**2 for v1 in vec1)) * math.sqrt(sum(v2**2 for v2 in vec2)))
except ZeroDivisionError:
# can happen if empty-string cmdnames appear for some reason.
# This is a no-match.
return 0 | [
"def",
"string_similarity",
"(",
"string1",
",",
"string2",
")",
":",
"vocabulary",
"=",
"set",
"(",
"list",
"(",
"string1",
"+",
"string2",
")",
")",
"vec1",
"=",
"[",
"string1",
".",
"count",
"(",
"v",
")",
"for",
"v",
"in",
"vocabulary",
"]",
"vec2",
"=",
"[",
"string2",
".",
"count",
"(",
"v",
")",
"for",
"v",
"in",
"vocabulary",
"]",
"try",
":",
"return",
"float",
"(",
"sum",
"(",
"vec1",
"[",
"i",
"]",
"*",
"vec2",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"vocabulary",
")",
")",
")",
")",
"/",
"(",
"math",
".",
"sqrt",
"(",
"sum",
"(",
"v1",
"**",
"2",
"for",
"v1",
"in",
"vec1",
")",
")",
"*",
"math",
".",
"sqrt",
"(",
"sum",
"(",
"v2",
"**",
"2",
"for",
"v2",
"in",
"vec2",
")",
")",
")",
"except",
"ZeroDivisionError",
":",
"# can happen if empty-string cmdnames appear for some reason.",
"# This is a no-match.",
"return",
"0"
] | [
1498,
0
] | [
1524,
16
] | python | en | ['en', 'error', 'th'] | False |
string_suggestions | (string, vocabulary, cutoff=0.6, maxnum=3) |
Given a `string` and a `vocabulary`, return a match or a list of
suggestions based on string similarity.
Args:
string (str): A string to search for.
vocabulary (iterable): A list of available strings.
cutoff (int, 0-1): Limit the similarity matches (the higher
the value, the more exact a match is required).
maxnum (int): Maximum number of suggestions to return.
Returns:
suggestions (list): Suggestions from `vocabulary` with a
similarity-rating that higher than or equal to `cutoff`.
Could be empty if there are no matches.
|
Given a `string` and a `vocabulary`, return a match or a list of
suggestions based on string similarity. | def string_suggestions(string, vocabulary, cutoff=0.6, maxnum=3):
"""
Given a `string` and a `vocabulary`, return a match or a list of
suggestions based on string similarity.
Args:
string (str): A string to search for.
vocabulary (iterable): A list of available strings.
cutoff (int, 0-1): Limit the similarity matches (the higher
the value, the more exact a match is required).
maxnum (int): Maximum number of suggestions to return.
Returns:
suggestions (list): Suggestions from `vocabulary` with a
similarity-rating that higher than or equal to `cutoff`.
Could be empty if there are no matches.
"""
return [tup[1] for tup in sorted([(string_similarity(string, sugg), sugg)
for sugg in vocabulary],
key=lambda tup: tup[0], reverse=True)
if tup[0] >= cutoff][:maxnum] | [
"def",
"string_suggestions",
"(",
"string",
",",
"vocabulary",
",",
"cutoff",
"=",
"0.6",
",",
"maxnum",
"=",
"3",
")",
":",
"return",
"[",
"tup",
"[",
"1",
"]",
"for",
"tup",
"in",
"sorted",
"(",
"[",
"(",
"string_similarity",
"(",
"string",
",",
"sugg",
")",
",",
"sugg",
")",
"for",
"sugg",
"in",
"vocabulary",
"]",
",",
"key",
"=",
"lambda",
"tup",
":",
"tup",
"[",
"0",
"]",
",",
"reverse",
"=",
"True",
")",
"if",
"tup",
"[",
"0",
"]",
">=",
"cutoff",
"]",
"[",
":",
"maxnum",
"]"
] | [
1527,
0
] | [
1548,
41
] | python | en | ['en', 'error', 'th'] | False |
string_partial_matching | (alternatives, inp, ret_index=True) |
Partially matches a string based on a list of `alternatives`.
Matching is made from the start of each subword in each
alternative. Case is not important. So e.g. "bi sh sw" or just
"big" or "shiny" or "sw" will match "Big shiny sword". Scoring is
done to allow to separate by most common demoninator. You will get
multiple matches returned if appropriate.
Args:
alternatives (list of str): A list of possible strings to
match.
inp (str): Search criterion.
ret_index (bool, optional): Return list of indices (from alternatives
array) instead of strings.
Returns:
matches (list): String-matches or indices if `ret_index` is `True`.
|
Partially matches a string based on a list of `alternatives`.
Matching is made from the start of each subword in each
alternative. Case is not important. So e.g. "bi sh sw" or just
"big" or "shiny" or "sw" will match "Big shiny sword". Scoring is
done to allow to separate by most common demoninator. You will get
multiple matches returned if appropriate. | def string_partial_matching(alternatives, inp, ret_index=True):
"""
Partially matches a string based on a list of `alternatives`.
Matching is made from the start of each subword in each
alternative. Case is not important. So e.g. "bi sh sw" or just
"big" or "shiny" or "sw" will match "Big shiny sword". Scoring is
done to allow to separate by most common demoninator. You will get
multiple matches returned if appropriate.
Args:
alternatives (list of str): A list of possible strings to
match.
inp (str): Search criterion.
ret_index (bool, optional): Return list of indices (from alternatives
array) instead of strings.
Returns:
matches (list): String-matches or indices if `ret_index` is `True`.
"""
if not alternatives or not inp:
return []
matches = defaultdict(list)
inp_words = inp.lower().split()
for altindex, alt in enumerate(alternatives):
alt_words = alt.lower().split()
last_index = 0
score = 0
for inp_word in inp_words:
# loop over parts, making sure only to visit each part once
# (this will invalidate input in the wrong word order)
submatch = [last_index + alt_num for alt_num, alt_word
in enumerate(alt_words[last_index:])
if alt_word.startswith(inp_word)]
if submatch:
last_index = min(submatch) + 1
score += 1
else:
score = 0
break
if score:
if ret_index:
matches[score].append(altindex)
else:
matches[score].append(alt)
if matches:
return matches[max(matches)]
return [] | [
"def",
"string_partial_matching",
"(",
"alternatives",
",",
"inp",
",",
"ret_index",
"=",
"True",
")",
":",
"if",
"not",
"alternatives",
"or",
"not",
"inp",
":",
"return",
"[",
"]",
"matches",
"=",
"defaultdict",
"(",
"list",
")",
"inp_words",
"=",
"inp",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
"for",
"altindex",
",",
"alt",
"in",
"enumerate",
"(",
"alternatives",
")",
":",
"alt_words",
"=",
"alt",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
"last_index",
"=",
"0",
"score",
"=",
"0",
"for",
"inp_word",
"in",
"inp_words",
":",
"# loop over parts, making sure only to visit each part once",
"# (this will invalidate input in the wrong word order)",
"submatch",
"=",
"[",
"last_index",
"+",
"alt_num",
"for",
"alt_num",
",",
"alt_word",
"in",
"enumerate",
"(",
"alt_words",
"[",
"last_index",
":",
"]",
")",
"if",
"alt_word",
".",
"startswith",
"(",
"inp_word",
")",
"]",
"if",
"submatch",
":",
"last_index",
"=",
"min",
"(",
"submatch",
")",
"+",
"1",
"score",
"+=",
"1",
"else",
":",
"score",
"=",
"0",
"break",
"if",
"score",
":",
"if",
"ret_index",
":",
"matches",
"[",
"score",
"]",
".",
"append",
"(",
"altindex",
")",
"else",
":",
"matches",
"[",
"score",
"]",
".",
"append",
"(",
"alt",
")",
"if",
"matches",
":",
"return",
"matches",
"[",
"max",
"(",
"matches",
")",
"]",
"return",
"[",
"]"
] | [
1551,
0
] | [
1598,
13
] | python | en | ['en', 'error', 'th'] | False |
format_table | (table, extra_space=1) |
Note: `evennia.utils.evtable` is more powerful than this, but this
function can be useful when the number of columns and rows are
unknown and must be calculated on the fly.
Args.
table (list): A list of lists to represent columns in the
table: `[[val,val,val,...], [val,val,val,...], ...]`, where
each val will be placed on a separate row in the
column. All columns must have the same number of rows (some
positions may be empty though).
extra_space (int, optional): Sets how much *minimum* extra
padding (in characters) should be left between columns.
Returns:
table (list): A list of lists representing the rows to print
out one by one.
Notes:
The function formats the columns to be as wide as the widest member
of each column.
Examples:
```python
ftable = format_table([[...], [...], ...])
for ir, row in enumarate(ftable):
if ir == 0:
# make first row white
string += "\n|w" + ""join(row) + "|n"
else:
string += "\n" + "".join(row)
print string
```
|
Note: `evennia.utils.evtable` is more powerful than this, but this
function can be useful when the number of columns and rows are
unknown and must be calculated on the fly. | def format_table(table, extra_space=1):
"""
Note: `evennia.utils.evtable` is more powerful than this, but this
function can be useful when the number of columns and rows are
unknown and must be calculated on the fly.
Args.
table (list): A list of lists to represent columns in the
table: `[[val,val,val,...], [val,val,val,...], ...]`, where
each val will be placed on a separate row in the
column. All columns must have the same number of rows (some
positions may be empty though).
extra_space (int, optional): Sets how much *minimum* extra
padding (in characters) should be left between columns.
Returns:
table (list): A list of lists representing the rows to print
out one by one.
Notes:
The function formats the columns to be as wide as the widest member
of each column.
Examples:
```python
ftable = format_table([[...], [...], ...])
for ir, row in enumarate(ftable):
if ir == 0:
# make first row white
string += "\n|w" + ""join(row) + "|n"
else:
string += "\n" + "".join(row)
print string
```
"""
if not table:
return [[]]
max_widths = [max([len(str(val)) for val in col]) for col in table]
ftable = []
for irow in range(len(table[0])):
ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " * extra_space
for icol, col in enumerate(table)])
return ftable | [
"def",
"format_table",
"(",
"table",
",",
"extra_space",
"=",
"1",
")",
":",
"if",
"not",
"table",
":",
"return",
"[",
"[",
"]",
"]",
"max_widths",
"=",
"[",
"max",
"(",
"[",
"len",
"(",
"str",
"(",
"val",
")",
")",
"for",
"val",
"in",
"col",
"]",
")",
"for",
"col",
"in",
"table",
"]",
"ftable",
"=",
"[",
"]",
"for",
"irow",
"in",
"range",
"(",
"len",
"(",
"table",
"[",
"0",
"]",
")",
")",
":",
"ftable",
".",
"append",
"(",
"[",
"str",
"(",
"col",
"[",
"irow",
"]",
")",
".",
"ljust",
"(",
"max_widths",
"[",
"icol",
"]",
")",
"+",
"\" \"",
"*",
"extra_space",
"for",
"icol",
",",
"col",
"in",
"enumerate",
"(",
"table",
")",
"]",
")",
"return",
"ftable"
] | [
1601,
0
] | [
1645,
17
] | python | en | ['en', 'error', 'th'] | False |
get_evennia_pids | () |
Get the currently valid PIDs (Process IDs) of the Portal and
Server by trying to access a PID file.
Returns:
server, portal (tuple): The PIDs of the respective processes,
or two `None` values if not found.
Examples:
This can be used to determine if we are in a subprocess by
something like:
```python
self_pid = os.getpid()
server_pid, portal_pid = get_evennia_pids()
is_subprocess = self_pid not in (server_pid, portal_pid)
```
|
Get the currently valid PIDs (Process IDs) of the Portal and
Server by trying to access a PID file. | def get_evennia_pids():
"""
Get the currently valid PIDs (Process IDs) of the Portal and
Server by trying to access a PID file.
Returns:
server, portal (tuple): The PIDs of the respective processes,
or two `None` values if not found.
Examples:
This can be used to determine if we are in a subprocess by
something like:
```python
self_pid = os.getpid()
server_pid, portal_pid = get_evennia_pids()
is_subprocess = self_pid not in (server_pid, portal_pid)
```
"""
server_pidfile = os.path.join(settings.GAME_DIR, 'server.pid')
portal_pidfile = os.path.join(settings.GAME_DIR, 'portal.pid')
server_pid, portal_pid = None, None
if os.path.exists(server_pidfile):
with open(server_pidfile, 'r') as f:
server_pid = f.read()
if os.path.exists(portal_pidfile):
with open(portal_pidfile, 'r') as f:
portal_pid = f.read()
if server_pid and portal_pid:
return int(server_pid), int(portal_pid)
return None, None | [
"def",
"get_evennia_pids",
"(",
")",
":",
"server_pidfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"GAME_DIR",
",",
"'server.pid'",
")",
"portal_pidfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"GAME_DIR",
",",
"'portal.pid'",
")",
"server_pid",
",",
"portal_pid",
"=",
"None",
",",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"server_pidfile",
")",
":",
"with",
"open",
"(",
"server_pidfile",
",",
"'r'",
")",
"as",
"f",
":",
"server_pid",
"=",
"f",
".",
"read",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"portal_pidfile",
")",
":",
"with",
"open",
"(",
"portal_pidfile",
",",
"'r'",
")",
"as",
"f",
":",
"portal_pid",
"=",
"f",
".",
"read",
"(",
")",
"if",
"server_pid",
"and",
"portal_pid",
":",
"return",
"int",
"(",
"server_pid",
")",
",",
"int",
"(",
"portal_pid",
")",
"return",
"None",
",",
"None"
] | [
1648,
0
] | [
1678,
21
] | python | en | ['en', 'error', 'th'] | False |
deepsize | (obj, max_depth=4) |
Get not only size of the given object, but also the size of
objects referenced by the object, down to `max_depth` distance
from the object.
Args:
obj (object): the object to be measured.
max_depth (int, optional): maximum referential distance
from `obj` that `deepsize()` should cover for
measuring objects referenced by `obj`.
Returns:
size (int): deepsize of `obj` in Bytes.
Notes:
This measure is necessarily approximate since some
memory is shared between objects. The `max_depth` of 4 is roughly
tested to give reasonable size information about database models
and their handlers.
|
Get not only size of the given object, but also the size of
objects referenced by the object, down to `max_depth` distance
from the object. | def deepsize(obj, max_depth=4):
"""
Get not only size of the given object, but also the size of
objects referenced by the object, down to `max_depth` distance
from the object.
Args:
obj (object): the object to be measured.
max_depth (int, optional): maximum referential distance
from `obj` that `deepsize()` should cover for
measuring objects referenced by `obj`.
Returns:
size (int): deepsize of `obj` in Bytes.
Notes:
This measure is necessarily approximate since some
memory is shared between objects. The `max_depth` of 4 is roughly
tested to give reasonable size information about database models
and their handlers.
"""
def _recurse(o, dct, depth):
if 0 <= max_depth < depth:
return
for ref in get_referents(o):
idr = id(ref)
if idr not in dct:
dct[idr] = (ref, getsizeof(ref, default=0))
_recurse(ref, dct, depth + 1)
sizedict = {}
_recurse(obj, sizedict, 0)
size = getsizeof(obj) + sum([p[1] for p in sizedict.values()])
return size | [
"def",
"deepsize",
"(",
"obj",
",",
"max_depth",
"=",
"4",
")",
":",
"def",
"_recurse",
"(",
"o",
",",
"dct",
",",
"depth",
")",
":",
"if",
"0",
"<=",
"max_depth",
"<",
"depth",
":",
"return",
"for",
"ref",
"in",
"get_referents",
"(",
"o",
")",
":",
"idr",
"=",
"id",
"(",
"ref",
")",
"if",
"idr",
"not",
"in",
"dct",
":",
"dct",
"[",
"idr",
"]",
"=",
"(",
"ref",
",",
"getsizeof",
"(",
"ref",
",",
"default",
"=",
"0",
")",
")",
"_recurse",
"(",
"ref",
",",
"dct",
",",
"depth",
"+",
"1",
")",
"sizedict",
"=",
"{",
"}",
"_recurse",
"(",
"obj",
",",
"sizedict",
",",
"0",
")",
"size",
"=",
"getsizeof",
"(",
"obj",
")",
"+",
"sum",
"(",
"[",
"p",
"[",
"1",
"]",
"for",
"p",
"in",
"sizedict",
".",
"values",
"(",
")",
"]",
")",
"return",
"size"
] | [
1685,
0
] | [
1718,
15
] | python | en | ['en', 'error', 'th'] | False |
strip_control_sequences | (string) |
Remove non-print text sequences.
Args:
string (str): Text to strip.
Returns.
text (str): Stripped text.
|
Remove non-print text sequences. | def strip_control_sequences(string):
"""
Remove non-print text sequences.
Args:
string (str): Text to strip.
Returns.
text (str): Stripped text.
"""
global _STRIP_ANSI
if not _STRIP_ANSI:
from evennia.utils.ansi import strip_raw_ansi as _STRIP_ANSI
return _RE_CONTROL_CHAR.sub('', _STRIP_ANSI(string)) | [
"def",
"strip_control_sequences",
"(",
"string",
")",
":",
"global",
"_STRIP_ANSI",
"if",
"not",
"_STRIP_ANSI",
":",
"from",
"evennia",
".",
"utils",
".",
"ansi",
"import",
"strip_raw_ansi",
"as",
"_STRIP_ANSI",
"return",
"_RE_CONTROL_CHAR",
".",
"sub",
"(",
"''",
",",
"_STRIP_ANSI",
"(",
"string",
")",
")"
] | [
1767,
0
] | [
1781,
56
] | python | en | ['en', 'error', 'th'] | False |
calledby | (callerdepth=1) |
Only to be used for debug purposes. Insert this debug function in
another function; it will print which function called it.
Args:
callerdepth (int): Must be larger than 0. When > 1, it will
print the caller of the caller etc.
Returns:
calledby (str): A debug string detailing which routine called
us.
|
Only to be used for debug purposes. Insert this debug function in
another function; it will print which function called it. | def calledby(callerdepth=1):
"""
Only to be used for debug purposes. Insert this debug function in
another function; it will print which function called it.
Args:
callerdepth (int): Must be larger than 0. When > 1, it will
print the caller of the caller etc.
Returns:
calledby (str): A debug string detailing which routine called
us.
"""
import inspect
stack = inspect.stack()
# we must step one extra level back in stack since we don't want
# to include the call of this function itself.
callerdepth = min(max(2, callerdepth + 1), len(stack) - 1)
frame = inspect.stack()[callerdepth]
path = os.path.sep.join(frame[1].rsplit(os.path.sep, 2)[-2:])
return "[called by '%s': %s:%s %s]" % (frame[3], path, frame[2], frame[4]) | [
"def",
"calledby",
"(",
"callerdepth",
"=",
"1",
")",
":",
"import",
"inspect",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"# we must step one extra level back in stack since we don't want",
"# to include the call of this function itself.",
"callerdepth",
"=",
"min",
"(",
"max",
"(",
"2",
",",
"callerdepth",
"+",
"1",
")",
",",
"len",
"(",
"stack",
")",
"-",
"1",
")",
"frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"callerdepth",
"]",
"path",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"frame",
"[",
"1",
"]",
".",
"rsplit",
"(",
"os",
".",
"path",
".",
"sep",
",",
"2",
")",
"[",
"-",
"2",
":",
"]",
")",
"return",
"\"[called by '%s': %s:%s %s]\"",
"%",
"(",
"frame",
"[",
"3",
"]",
",",
"path",
",",
"frame",
"[",
"2",
"]",
",",
"frame",
"[",
"4",
"]",
")"
] | [
1784,
0
] | [
1805,
78
] | python | en | ['en', 'error', 'th'] | False |
m_len | (target) |
Provides length checking for strings with MXP patterns, and falls
back to normal len for other objects.
Args:
target (string): A string with potential MXP components
to search.
Returns:
length (int): The length of `target`, ignoring MXP components.
|
Provides length checking for strings with MXP patterns, and falls
back to normal len for other objects. | def m_len(target):
"""
Provides length checking for strings with MXP patterns, and falls
back to normal len for other objects.
Args:
target (string): A string with potential MXP components
to search.
Returns:
length (int): The length of `target`, ignoring MXP components.
"""
# Would create circular import if in module root.
from evennia.utils.ansi import ANSI_PARSER
if inherits_from(target, basestring) and "|lt" in target:
return len(ANSI_PARSER.strip_mxp(target))
return len(target) | [
"def",
"m_len",
"(",
"target",
")",
":",
"# Would create circular import if in module root.",
"from",
"evennia",
".",
"utils",
".",
"ansi",
"import",
"ANSI_PARSER",
"if",
"inherits_from",
"(",
"target",
",",
"basestring",
")",
"and",
"\"|lt\"",
"in",
"target",
":",
"return",
"len",
"(",
"ANSI_PARSER",
".",
"strip_mxp",
"(",
"target",
")",
")",
"return",
"len",
"(",
"target",
")"
] | [
1808,
0
] | [
1825,
22
] | python | en | ['en', 'error', 'th'] | False |
at_search_result | (matches, caller, query="", quiet=False, **kwargs) |
This is a generic hook for handling all processing of a search
result, including error reporting. This is also called by the cmdhandler
to manage errors in command lookup.
Args:
matches (list): This is a list of 0, 1 or more typeclass
instances or Command instances, the matched result of the
search. If 0, a nomatch error should be echoed, and if >1,
multimatch errors should be given. Only if a single match
should the result pass through.
caller (Object): The object performing the search and/or which should
receive error messages.
query (str, optional): The search query used to produce `matches`.
quiet (bool, optional): If `True`, no messages will be echoed to caller
on errors.
Kwargs:
nofound_string (str): Replacement string to echo on a notfound error.
multimatch_string (str): Replacement string to echo on a multimatch error.
Returns:
processed_result (Object or None): This is always a single result
or `None`. If `None`, any error reporting/handling should
already have happened.
|
This is a generic hook for handling all processing of a search
result, including error reporting. This is also called by the cmdhandler
to manage errors in command lookup. | def at_search_result(matches, caller, query="", quiet=False, **kwargs):
"""
This is a generic hook for handling all processing of a search
result, including error reporting. This is also called by the cmdhandler
to manage errors in command lookup.
Args:
matches (list): This is a list of 0, 1 or more typeclass
instances or Command instances, the matched result of the
search. If 0, a nomatch error should be echoed, and if >1,
multimatch errors should be given. Only if a single match
should the result pass through.
caller (Object): The object performing the search and/or which should
receive error messages.
query (str, optional): The search query used to produce `matches`.
quiet (bool, optional): If `True`, no messages will be echoed to caller
on errors.
Kwargs:
nofound_string (str): Replacement string to echo on a notfound error.
multimatch_string (str): Replacement string to echo on a multimatch error.
Returns:
processed_result (Object or None): This is always a single result
or `None`. If `None`, any error reporting/handling should
already have happened.
"""
error = ""
if not matches:
# no results.
error = kwargs.get("nofound_string") or _("Could not find '%s'." % query)
matches = None
elif len(matches) > 1:
multimatch_string = kwargs.get("multimatch_string")
if multimatch_string:
error = "%s\n" % multimatch_string
else:
error = _("More than one match for '%s' (please narrow target):\n" % query)
for num, result in enumerate(matches):
# we need to consider Commands, where .aliases is a list
aliases = result.aliases.all() if hasattr(result.aliases, "all") else result.aliases
error += _MULTIMATCH_TEMPLATE.format(
number=num + 1,
name=result.get_display_name(caller) if hasattr(result, "get_display_name") else query,
aliases=" [%s]" % ";".join(aliases) if aliases else "",
info=result.get_extra_info(caller))
matches = None
else:
# exactly one match
matches = matches[0]
if error and not quiet:
caller.msg(error.strip())
return matches | [
"def",
"at_search_result",
"(",
"matches",
",",
"caller",
",",
"query",
"=",
"\"\"",
",",
"quiet",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"error",
"=",
"\"\"",
"if",
"not",
"matches",
":",
"# no results.",
"error",
"=",
"kwargs",
".",
"get",
"(",
"\"nofound_string\"",
")",
"or",
"_",
"(",
"\"Could not find '%s'.\"",
"%",
"query",
")",
"matches",
"=",
"None",
"elif",
"len",
"(",
"matches",
")",
">",
"1",
":",
"multimatch_string",
"=",
"kwargs",
".",
"get",
"(",
"\"multimatch_string\"",
")",
"if",
"multimatch_string",
":",
"error",
"=",
"\"%s\\n\"",
"%",
"multimatch_string",
"else",
":",
"error",
"=",
"_",
"(",
"\"More than one match for '%s' (please narrow target):\\n\"",
"%",
"query",
")",
"for",
"num",
",",
"result",
"in",
"enumerate",
"(",
"matches",
")",
":",
"# we need to consider Commands, where .aliases is a list",
"aliases",
"=",
"result",
".",
"aliases",
".",
"all",
"(",
")",
"if",
"hasattr",
"(",
"result",
".",
"aliases",
",",
"\"all\"",
")",
"else",
"result",
".",
"aliases",
"error",
"+=",
"_MULTIMATCH_TEMPLATE",
".",
"format",
"(",
"number",
"=",
"num",
"+",
"1",
",",
"name",
"=",
"result",
".",
"get_display_name",
"(",
"caller",
")",
"if",
"hasattr",
"(",
"result",
",",
"\"get_display_name\"",
")",
"else",
"query",
",",
"aliases",
"=",
"\" [%s]\"",
"%",
"\";\"",
".",
"join",
"(",
"aliases",
")",
"if",
"aliases",
"else",
"\"\"",
",",
"info",
"=",
"result",
".",
"get_extra_info",
"(",
"caller",
")",
")",
"matches",
"=",
"None",
"else",
":",
"# exactly one match",
"matches",
"=",
"matches",
"[",
"0",
"]",
"if",
"error",
"and",
"not",
"quiet",
":",
"caller",
".",
"msg",
"(",
"error",
".",
"strip",
"(",
")",
")",
"return",
"matches"
] | [
1834,
0
] | [
1889,
18
] | python | en | ['en', 'error', 'th'] | False |
get_game_dir_path | () |
This is called by settings_default in order to determine the path
of the game directory.
Returns:
path (str): Full OS path to the game dir
|
This is called by settings_default in order to determine the path
of the game directory. | def get_game_dir_path():
"""
This is called by settings_default in order to determine the path
of the game directory.
Returns:
path (str): Full OS path to the game dir
"""
# current working directory, assumed to be somewhere inside gamedir.
for _ in range(10):
gpath = os.getcwd()
if "server" in os.listdir(gpath):
if os.path.isfile(os.path.join("server", "conf", "settings.py")):
return gpath
else:
os.chdir(os.pardir)
raise RuntimeError("server/conf/settings.py not found: Must start from inside game dir.") | [
"def",
"get_game_dir_path",
"(",
")",
":",
"# current working directory, assumed to be somewhere inside gamedir.",
"for",
"_",
"in",
"range",
"(",
"10",
")",
":",
"gpath",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"\"server\"",
"in",
"os",
".",
"listdir",
"(",
"gpath",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"server\"",
",",
"\"conf\"",
",",
"\"settings.py\"",
")",
")",
":",
"return",
"gpath",
"else",
":",
"os",
".",
"chdir",
"(",
"os",
".",
"pardir",
")",
"raise",
"RuntimeError",
"(",
"\"server/conf/settings.py not found: Must start from inside game dir.\"",
")"
] | [
1943,
0
] | [
1960,
93
] | python | en | ['en', 'error', 'th'] | False |
get_all_typeclasses | (parent=None) |
List available typeclasses from all available modules.
Args:
parent (str, optional): If given, only return typeclasses inheriting (at any distance)
from this parent.
Returns:
typeclasses (dict): On the form {"typeclass.path": typeclass, ...}
Notes:
This will dynamicall retrieve all abstract django models inheriting at any distance
from the TypedObject base (aka a Typeclass) so it will work fine with any custom
classes being added.
|
List available typeclasses from all available modules. | def get_all_typeclasses(parent=None):
"""
List available typeclasses from all available modules.
Args:
parent (str, optional): If given, only return typeclasses inheriting (at any distance)
from this parent.
Returns:
typeclasses (dict): On the form {"typeclass.path": typeclass, ...}
Notes:
This will dynamicall retrieve all abstract django models inheriting at any distance
from the TypedObject base (aka a Typeclass) so it will work fine with any custom
classes being added.
"""
from evennia.typeclasses.models import TypedObject
typeclasses = {"{}.{}".format(model.__module__, model.__name__): model
for model in apps.get_models() if TypedObject in getmro(model)}
if parent:
typeclasses = {name: typeclass for name, typeclass in typeclasses.items()
if inherits_from(typeclass, parent)}
return typeclasses | [
"def",
"get_all_typeclasses",
"(",
"parent",
"=",
"None",
")",
":",
"from",
"evennia",
".",
"typeclasses",
".",
"models",
"import",
"TypedObject",
"typeclasses",
"=",
"{",
"\"{}.{}\"",
".",
"format",
"(",
"model",
".",
"__module__",
",",
"model",
".",
"__name__",
")",
":",
"model",
"for",
"model",
"in",
"apps",
".",
"get_models",
"(",
")",
"if",
"TypedObject",
"in",
"getmro",
"(",
"model",
")",
"}",
"if",
"parent",
":",
"typeclasses",
"=",
"{",
"name",
":",
"typeclass",
"for",
"name",
",",
"typeclass",
"in",
"typeclasses",
".",
"items",
"(",
")",
"if",
"inherits_from",
"(",
"typeclass",
",",
"parent",
")",
"}",
"return",
"typeclasses"
] | [
1963,
0
] | [
1986,
22
] | 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.