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
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
axis_aligned_iou_loss | (pred, target) | Calculate the IoU loss (1-IoU) of two set of axis aligned bounding
boxes. Note that predictions and targets are one-to-one corresponded.
Args:
pred (torch.Tensor): Bbox predictions with shape [..., 3].
target (torch.Tensor): Bbox targets (gt) with shape [..., 3].
Returns:
torch.Tensor: IoU loss between predictions and targets.
| Calculate the IoU loss (1-IoU) of two set of axis aligned bounding
boxes. Note that predictions and targets are one-to-one corresponded. | def axis_aligned_iou_loss(pred, target):
"""Calculate the IoU loss (1-IoU) of two set of axis aligned bounding
boxes. Note that predictions and targets are one-to-one corresponded.
Args:
pred (torch.Tensor): Bbox predictions with shape [..., 3].
target (torch.Tensor): Bbox targets (gt) with shape [..., 3].
Returns:
torch.Tensor: IoU loss between predictions and targets.
"""
axis_aligned_iou = AxisAlignedBboxOverlaps3D()(
pred, target, is_aligned=True)
iou_loss = 1 - axis_aligned_iou
return iou_loss | [
"def",
"axis_aligned_iou_loss",
"(",
"pred",
",",
"target",
")",
":",
"axis_aligned_iou",
"=",
"AxisAlignedBboxOverlaps3D",
"(",
")",
"(",
"pred",
",",
"target",
",",
"is_aligned",
"=",
"True",
")",
"iou_loss",
"=",
"1",
"-",
"axis_aligned_iou",
"return",
"iou_loss"
] | [
9,
0
] | [
24,
19
] | python | en | ['en', 'en', 'en'] | True |
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.densitymapbox.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.densitymapbox.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.densitymapbox.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.densitymapbox.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.densitymapbox.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.densitymapbox.Stream \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.densitymapbox.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 |
ContextBuilder.__init__ | (self, settings: Mapping[str, object] = None) |
Initialize an instance of the context builder.
Args:
settings: Mapping of configuration settings
|
Initialize an instance of the context builder. | def __init__(self, settings: Mapping[str, object] = None):
"""
Initialize an instance of the context builder.
Args:
settings: Mapping of configuration settings
"""
self.settings = Settings(settings) | [
"def",
"__init__",
"(",
"self",
",",
"settings",
":",
"Mapping",
"[",
"str",
",",
"object",
"]",
"=",
"None",
")",
":",
"self",
".",
"settings",
"=",
"Settings",
"(",
"settings",
")"
] | [
12,
4
] | [
20,
42
] | python | en | ['en', 'error', 'th'] | False |
ContextBuilder.build | (self) | Build the new injection context. | Build the new injection context. | async def build(self) -> InjectionContext:
"""Build the new injection context.""" | [
"async",
"def",
"build",
"(",
"self",
")",
"->",
"InjectionContext",
":"
] | [
23,
4
] | [
24,
46
] | python | en | ['en', 'en', 'en'] | True |
ContextBuilder.update_settings | (self, settings: Mapping[str, object]) | Update the context builder with additional settings. | Update the context builder with additional settings. | def update_settings(self, settings: Mapping[str, object]):
"""Update the context builder with additional settings."""
if settings:
self.settings = self.settings.extend(settings) | [
"def",
"update_settings",
"(",
"self",
",",
"settings",
":",
"Mapping",
"[",
"str",
",",
"object",
"]",
")",
":",
"if",
"settings",
":",
"self",
".",
"settings",
"=",
"self",
".",
"settings",
".",
"extend",
"(",
"settings",
")"
] | [
26,
4
] | [
29,
58
] | python | en | ['en', 'en', 'en'] | True |
WsTransport.__init__ | (self) | Initialize an `WsTransport` instance. | Initialize an `WsTransport` instance. | def __init__(self) -> None:
"""Initialize an `WsTransport` instance."""
super(WsTransport, self).__init__()
self.logger = logging.getLogger(__name__) | [
"def",
"__init__",
"(",
"self",
")",
"->",
"None",
":",
"super",
"(",
"WsTransport",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")"
] | [
15,
4
] | [
18,
49
] | python | en | ['en', 'en', 'nl'] | True |
WsTransport.start | (self) | Start the outbound transport. | Start the outbound transport. | async def start(self):
"""Start the outbound transport."""
self.client_session = ClientSession(cookie_jar=DummyCookieJar())
return self | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"client_session",
"=",
"ClientSession",
"(",
"cookie_jar",
"=",
"DummyCookieJar",
"(",
")",
")",
"return",
"self"
] | [
20,
4
] | [
23,
19
] | python | en | ['en', 'en', 'en'] | True |
WsTransport.stop | (self) | Stop the outbound transport. | Stop the outbound transport. | async def stop(self):
"""Stop the outbound transport."""
await self.client_session.close()
self.client_session = None | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"await",
"self",
".",
"client_session",
".",
"close",
"(",
")",
"self",
".",
"client_session",
"=",
"None"
] | [
25,
4
] | [
28,
34
] | python | en | ['en', 'en', 'en'] | True |
WsTransport.handle_message | (self, payload: Union[str, bytes], endpoint: str) |
Handle message from queue.
Args:
message: `OutboundMessage` to send over transport implementation
|
Handle message from queue. | async def handle_message(self, payload: Union[str, bytes], endpoint: str):
"""
Handle message from queue.
Args:
message: `OutboundMessage` to send over transport implementation
"""
# aiohttp should automatically handle websocket sessions
async with self.client_session.ws_connect(endpoint) as ws:
if isinstance(payload, bytes):
await ws.send_bytes(payload)
else:
await ws.send_str(payload) | [
"async",
"def",
"handle_message",
"(",
"self",
",",
"payload",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"endpoint",
":",
"str",
")",
":",
"# aiohttp should automatically handle websocket sessions",
"async",
"with",
"self",
".",
"client_session",
".",
"ws_connect",
"(",
"endpoint",
")",
"as",
"ws",
":",
"if",
"isinstance",
"(",
"payload",
",",
"bytes",
")",
":",
"await",
"ws",
".",
"send_bytes",
"(",
"payload",
")",
"else",
":",
"await",
"ws",
".",
"send_str",
"(",
"payload",
")"
] | [
30,
4
] | [
42,
42
] | python | en | ['en', 'error', 'th'] | False |
Button.args | (self) |
Sets the arguments values to be passed to the Plotly method set
in `method` on click.
The 'args' property is an info array that may be specified as:
* a list or tuple of up to 3 elements where:
(0) The 'args[0]' property accepts values of any type
(1) The 'args[1]' property accepts values of any type
(2) The 'args[2]' property accepts values of any type
Returns
-------
list
|
Sets the arguments values to be passed to the Plotly method set
in `method` on click.
The 'args' property is an info array that may be specified as:
* a list or tuple of up to 3 elements where:
(0) The 'args[0]' property accepts values of any type
(1) The 'args[1]' property accepts values of any type
(2) The 'args[2]' property accepts values of any type | def args(self):
"""
Sets the arguments values to be passed to the Plotly method set
in `method` on click.
The 'args' property is an info array that may be specified as:
* a list or tuple of up to 3 elements where:
(0) The 'args[0]' property accepts values of any type
(1) The 'args[1]' property accepts values of any type
(2) The 'args[2]' property accepts values of any type
Returns
-------
list
"""
return self["args"] | [
"def",
"args",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"args\"",
"]"
] | [
24,
4
] | [
40,
27
] | python | en | ['en', 'error', 'th'] | False |
Button.args2 | (self) |
Sets a 2nd set of `args`, these arguments values are passed to
the Plotly method set in `method` when clicking this button
while in the active state. Use this to create toggle buttons.
The 'args2' property is an info array that may be specified as:
* a list or tuple of up to 3 elements where:
(0) The 'args2[0]' property accepts values of any type
(1) The 'args2[1]' property accepts values of any type
(2) The 'args2[2]' property accepts values of any type
Returns
-------
list
|
Sets a 2nd set of `args`, these arguments values are passed to
the Plotly method set in `method` when clicking this button
while in the active state. Use this to create toggle buttons.
The 'args2' property is an info array that may be specified as:
* a list or tuple of up to 3 elements where:
(0) The 'args2[0]' property accepts values of any type
(1) The 'args2[1]' property accepts values of any type
(2) The 'args2[2]' property accepts values of any type | def args2(self):
"""
Sets a 2nd set of `args`, these arguments values are passed to
the Plotly method set in `method` when clicking this button
while in the active state. Use this to create toggle buttons.
The 'args2' property is an info array that may be specified as:
* a list or tuple of up to 3 elements where:
(0) The 'args2[0]' property accepts values of any type
(1) The 'args2[1]' property accepts values of any type
(2) The 'args2[2]' property accepts values of any type
Returns
-------
list
"""
return self["args2"] | [
"def",
"args2",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"args2\"",
"]"
] | [
49,
4
] | [
66,
28
] | python | en | ['en', 'error', 'th'] | False |
Button.execute | (self) |
When true, the API method is executed. When false, all other
behaviors are the same and command execution is skipped. This
may be useful when hooking into, for example, the
`plotly_buttonclicked` method and executing the API command
manually without losing the benefit of the updatemenu
automatically binding to the state of the plot through the
specification of `method` and `args`.
The 'execute' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
When true, the API method is executed. When false, all other
behaviors are the same and command execution is skipped. This
may be useful when hooking into, for example, the
`plotly_buttonclicked` method and executing the API command
manually without losing the benefit of the updatemenu
automatically binding to the state of the plot through the
specification of `method` and `args`.
The 'execute' property must be specified as a bool
(either True, or False) | def execute(self):
"""
When true, the API method is executed. When false, all other
behaviors are the same and command execution is skipped. This
may be useful when hooking into, for example, the
`plotly_buttonclicked` method and executing the API command
manually without losing the benefit of the updatemenu
automatically binding to the state of the plot through the
specification of `method` and `args`.
The 'execute' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["execute"] | [
"def",
"execute",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"execute\"",
"]"
] | [
75,
4
] | [
92,
30
] | python | en | ['en', 'error', 'th'] | False |
Button.label | (self) |
Sets the text label to appear on the button.
The 'label' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
|
Sets the text label to appear on the button.
The 'label' property is a string and must be specified as:
- A string
- A number that will be converted to a string | def label(self):
"""
Sets the text label to appear on the button.
The 'label' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["label"] | [
"def",
"label",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"label\"",
"]"
] | [
101,
4
] | [
113,
28
] | python | en | ['en', 'error', 'th'] | False |
Button.method | (self) |
Sets the Plotly method to be called on click. If the `skip`
method is used, the API updatemenu will function as normal but
will perform no API calls and will not bind automatically to
state updates. This may be used to create a component interface
and attach to updatemenu events manually via JavaScript.
The 'method' property is an enumeration that may be specified as:
- One of the following enumeration values:
['restyle', 'relayout', 'animate', 'update', 'skip']
Returns
-------
Any
|
Sets the Plotly method to be called on click. If the `skip`
method is used, the API updatemenu will function as normal but
will perform no API calls and will not bind automatically to
state updates. This may be used to create a component interface
and attach to updatemenu events manually via JavaScript.
The 'method' property is an enumeration that may be specified as:
- One of the following enumeration values:
['restyle', 'relayout', 'animate', 'update', 'skip'] | def method(self):
"""
Sets the Plotly method to be called on click. If the `skip`
method is used, the API updatemenu will function as normal but
will perform no API calls and will not bind automatically to
state updates. This may be used to create a component interface
and attach to updatemenu events manually via JavaScript.
The 'method' property is an enumeration that may be specified as:
- One of the following enumeration values:
['restyle', 'relayout', 'animate', 'update', 'skip']
Returns
-------
Any
"""
return self["method"] | [
"def",
"method",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"method\"",
"]"
] | [
122,
4
] | [
138,
29
] | python | en | ['en', 'error', 'th'] | False |
Button.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\"",
"]"
] | [
147,
4
] | [
165,
27
] | python | en | ['en', 'error', 'th'] | False |
Button.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\"",
"]"
] | [
174,
4
] | [
193,
39
] | python | en | ['en', 'error', 'th'] | False |
Button.visible | (self) |
Determines whether or not this button is visible.
The 'visible' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Determines whether or not this button is visible.
The 'visible' property must be specified as a bool
(either True, or False) | def visible(self):
"""
Determines whether or not this button is visible.
The 'visible' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["visible"] | [
"def",
"visible",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"visible\"",
"]"
] | [
202,
4
] | [
213,
30
] | python | en | ['en', 'error', 'th'] | False |
Button.__init__ | (
self,
arg=None,
args=None,
args2=None,
execute=None,
label=None,
method=None,
name=None,
templateitemname=None,
visible=None,
**kwargs
) |
Construct a new Button object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.updatemenu.Button`
args
Sets the arguments values to be passed to the Plotly
method set in `method` on click.
args2
Sets a 2nd set of `args`, these arguments values are
passed to the Plotly method set in `method` when
clicking this button while in the active state. Use
this to create toggle buttons.
execute
When true, the API method is executed. When false, all
other behaviors are the same and command execution is
skipped. This may be useful when hooking into, for
example, the `plotly_buttonclicked` method and
executing the API command manually without losing the
benefit of the updatemenu automatically binding to the
state of the plot through the specification of `method`
and `args`.
label
Sets the text label to appear on the button.
method
Sets the Plotly method to be called on click. If the
`skip` method is used, the API updatemenu will function
as normal but will perform no API calls and will not
bind automatically to state updates. This may be used
to create a component interface and attach to
updatemenu events manually via JavaScript.
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`.
visible
Determines whether or not this button is visible.
Returns
-------
Button
|
Construct a new Button object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.updatemenu.Button`
args
Sets the arguments values to be passed to the Plotly
method set in `method` on click.
args2
Sets a 2nd set of `args`, these arguments values are
passed to the Plotly method set in `method` when
clicking this button while in the active state. Use
this to create toggle buttons.
execute
When true, the API method is executed. When false, all
other behaviors are the same and command execution is
skipped. This may be useful when hooking into, for
example, the `plotly_buttonclicked` method and
executing the API command manually without losing the
benefit of the updatemenu automatically binding to the
state of the plot through the specification of `method`
and `args`.
label
Sets the text label to appear on the button.
method
Sets the Plotly method to be called on click. If the
`skip` method is used, the API updatemenu will function
as normal but will perform no API calls and will not
bind automatically to state updates. This may be used
to create a component interface and attach to
updatemenu events manually via JavaScript.
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`.
visible
Determines whether or not this button is visible. | def __init__(
self,
arg=None,
args=None,
args2=None,
execute=None,
label=None,
method=None,
name=None,
templateitemname=None,
visible=None,
**kwargs
):
"""
Construct a new Button object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.updatemenu.Button`
args
Sets the arguments values to be passed to the Plotly
method set in `method` on click.
args2
Sets a 2nd set of `args`, these arguments values are
passed to the Plotly method set in `method` when
clicking this button while in the active state. Use
this to create toggle buttons.
execute
When true, the API method is executed. When false, all
other behaviors are the same and command execution is
skipped. This may be useful when hooking into, for
example, the `plotly_buttonclicked` method and
executing the API command manually without losing the
benefit of the updatemenu automatically binding to the
state of the plot through the specification of `method`
and `args`.
label
Sets the text label to appear on the button.
method
Sets the Plotly method to be called on click. If the
`skip` method is used, the API updatemenu will function
as normal but will perform no API calls and will not
bind automatically to state updates. This may be used
to create a component interface and attach to
updatemenu events manually via JavaScript.
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`.
visible
Determines whether or not this button is visible.
Returns
-------
Button
"""
super(Button, self).__init__("buttons")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.updatemenu.Button
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.updatemenu.Button`"""
)
# 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("args", None)
_v = args if args is not None else _v
if _v is not None:
self["args"] = _v
_v = arg.pop("args2", None)
_v = args2 if args2 is not None else _v
if _v is not None:
self["args2"] = _v
_v = arg.pop("execute", None)
_v = execute if execute is not None else _v
if _v is not None:
self["execute"] = _v
_v = arg.pop("label", None)
_v = label if label is not None else _v
if _v is not None:
self["label"] = _v
_v = arg.pop("method", None)
_v = method if method is not None else _v
if _v is not None:
self["method"] = _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("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"args",
"=",
"None",
",",
"args2",
"=",
"None",
",",
"execute",
"=",
"None",
",",
"label",
"=",
"None",
",",
"method",
"=",
"None",
",",
"name",
"=",
"None",
",",
"templateitemname",
"=",
"None",
",",
"visible",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Button",
",",
"self",
")",
".",
"__init__",
"(",
"\"buttons\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.layout.updatemenu.Button \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.updatemenu.Button`\"\"\"",
")",
"# 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",
"(",
"\"args\"",
",",
"None",
")",
"_v",
"=",
"args",
"if",
"args",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"args\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"args2\"",
",",
"None",
")",
"_v",
"=",
"args2",
"if",
"args2",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"args2\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"execute\"",
",",
"None",
")",
"_v",
"=",
"execute",
"if",
"execute",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"execute\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"label\"",
",",
"None",
")",
"_v",
"=",
"label",
"if",
"label",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"label\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"method\"",
",",
"None",
")",
"_v",
"=",
"method",
"if",
"method",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"method\"",
"]",
"=",
"_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",
"(",
"\"visible\"",
",",
"None",
")",
"_v",
"=",
"visible",
"if",
"visible",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"visible\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
273,
4
] | [
415,
34
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
63,
28
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
72,
4
] | [
94,
29
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf] | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
103,
4
] | [
112,
27
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.__init__ | (self, arg=None, color=None, family=None, size=None, **kwargs) |
Construct a new Tickfont object
Sets the tick font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.scene.zaxis.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Tickfont
|
Construct a new Tickfont object
Sets the tick font. | def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Tickfont object
Sets the tick font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.scene.zaxis.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Tickfont
"""
super(Tickfont, self).__init__("tickfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.scene.zaxis.Tickfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.scene.zaxis.Tickfont`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"family",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Tickfont",
",",
"self",
")",
".",
"__init__",
"(",
"\"tickfont\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.layout.scene.zaxis.Tickfont \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.scene.zaxis.Tickfont`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
143,
4
] | [
226,
34
] | python | en | ['en', 'error', 'th'] | False |
AccountCmdSet.at_cmdset_creation | (self) | Populates the cmdset | Populates the cmdset | def at_cmdset_creation(self):
"Populates the cmdset"
# Account-specific commands
self.add(account.CmdOOCLook())
self.add(account.CmdIC())
self.add(account.CmdOOC())
self.add(account.CmdCharCreate())
self.add(account.CmdCharDelete())
# self.add(account.CmdSessions())
self.add(account.CmdWho())
self.add(account.CmdOption())
self.add(account.CmdQuit())
self.add(account.CmdPassword())
self.add(account.CmdColorTest())
self.add(account.CmdQuell())
# nicks
self.add(general.CmdNick())
# testing
self.add(building.CmdExamine())
# Help command
self.add(help.CmdHelp())
# system commands
self.add(system.CmdReload())
self.add(system.CmdReset())
self.add(system.CmdShutdown())
self.add(system.CmdPy())
# Admin commands
self.add(admin.CmdDelAccount())
self.add(admin.CmdNewPassword())
# Comm commands
self.add(comms.CmdAddCom())
self.add(comms.CmdDelCom())
self.add(comms.CmdAllCom())
self.add(comms.CmdChannels())
self.add(comms.CmdCdestroy())
self.add(comms.CmdChannelCreate())
self.add(comms.CmdClock())
self.add(comms.CmdCBoot())
self.add(comms.CmdCemit())
self.add(comms.CmdCWho())
self.add(comms.CmdCdesc())
self.add(comms.CmdPage())
self.add(comms.CmdIRC2Chan())
self.add(comms.CmdIRCStatus())
self.add(comms.CmdRSS2Chan()) | [
"def",
"at_cmdset_creation",
"(",
"self",
")",
":",
"# Account-specific commands",
"self",
".",
"add",
"(",
"account",
".",
"CmdOOCLook",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdIC",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdOOC",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdCharCreate",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdCharDelete",
"(",
")",
")",
"# self.add(account.CmdSessions())",
"self",
".",
"add",
"(",
"account",
".",
"CmdWho",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdOption",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdQuit",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdPassword",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdColorTest",
"(",
")",
")",
"self",
".",
"add",
"(",
"account",
".",
"CmdQuell",
"(",
")",
")",
"# nicks",
"self",
".",
"add",
"(",
"general",
".",
"CmdNick",
"(",
")",
")",
"# testing",
"self",
".",
"add",
"(",
"building",
".",
"CmdExamine",
"(",
")",
")",
"# Help command",
"self",
".",
"add",
"(",
"help",
".",
"CmdHelp",
"(",
")",
")",
"# system commands",
"self",
".",
"add",
"(",
"system",
".",
"CmdReload",
"(",
")",
")",
"self",
".",
"add",
"(",
"system",
".",
"CmdReset",
"(",
")",
")",
"self",
".",
"add",
"(",
"system",
".",
"CmdShutdown",
"(",
")",
")",
"self",
".",
"add",
"(",
"system",
".",
"CmdPy",
"(",
")",
")",
"# Admin commands",
"self",
".",
"add",
"(",
"admin",
".",
"CmdDelAccount",
"(",
")",
")",
"self",
".",
"add",
"(",
"admin",
".",
"CmdNewPassword",
"(",
")",
")",
"# Comm commands",
"self",
".",
"add",
"(",
"comms",
".",
"CmdAddCom",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdDelCom",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdAllCom",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdChannels",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdCdestroy",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdChannelCreate",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdClock",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdCBoot",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdCemit",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdCWho",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdCdesc",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdPage",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdIRC2Chan",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdIRCStatus",
"(",
")",
")",
"self",
".",
"add",
"(",
"comms",
".",
"CmdRSS2Chan",
"(",
")",
")"
] | [
24,
4
] | [
75,
37
] | python | en | ['en', 'sr', 'en'] | True |
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.isosurface.col
orbar.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.isosurface.col
orbar.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.isosurface.col
orbar.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.isosurface.colorbar.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.isosurface.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.isosurface.colorbar.Tickformatstop \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.isosurface.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 |
Leaf.opacity | (self) |
Sets the opacity of the leaves. With colorscale it is defaulted
to 1; otherwise it is defaulted to 0.7
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 opacity of the leaves. With colorscale it is defaulted
to 1; otherwise it is defaulted to 0.7
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 opacity of the leaves. With colorscale it is defaulted
to 1; otherwise it is defaulted to 0.7
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\"",
"]"
] | [
15,
4
] | [
27,
30
] | python | en | ['en', 'error', 'th'] | False |
Leaf.__init__ | (self, arg=None, opacity=None, **kwargs) |
Construct a new Leaf object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.sunburst.Leaf`
opacity
Sets the opacity of the leaves. With colorscale it is
defaulted to 1; otherwise it is defaulted to 0.7
Returns
-------
Leaf
|
Construct a new Leaf object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.sunburst.Leaf`
opacity
Sets the opacity of the leaves. With colorscale it is
defaulted to 1; otherwise it is defaulted to 0.7 | def __init__(self, arg=None, opacity=None, **kwargs):
"""
Construct a new Leaf object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.sunburst.Leaf`
opacity
Sets the opacity of the leaves. With colorscale it is
defaulted to 1; otherwise it is defaulted to 0.7
Returns
-------
Leaf
"""
super(Leaf, self).__init__("leaf")
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.sunburst.Leaf
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sunburst.Leaf`"""
)
# 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("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"opacity",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Leaf",
",",
"self",
")",
".",
"__init__",
"(",
"\"leaf\"",
")",
"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.sunburst.Leaf \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.sunburst.Leaf`\"\"\"",
")",
"# 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",
"(",
"\"opacity\"",
",",
"None",
")",
"_v",
"=",
"opacity",
"if",
"opacity",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"opacity\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
43,
4
] | [
100,
34
] | python | en | ['en', 'error', 'th'] | False |
TestSeq2Seq.test_generation | (self) |
This test uses a single-turn sequence repitition task.
|
This test uses a single-turn sequence repitition task.
| def test_generation(self):
"""
This test uses a single-turn sequence repitition task.
"""
valid, test = testing_utils.eval_model(
dict(
task='integration_tests:multiturn_nocandidate',
model='seq2seq',
model_file='zoo:unittest/seq2seq/model',
dict_file='zoo:unittest/seq2seq/model.dict',
skip_generation=False,
inference='greedy',
batchsize=8,
num_examples=32,
)
)
self.assertLess(valid['ppl'], 1.2)
self.assertLess(test['ppl'], 1.2) | [
"def",
"test_generation",
"(",
"self",
")",
":",
"valid",
",",
"test",
"=",
"testing_utils",
".",
"eval_model",
"(",
"dict",
"(",
"task",
"=",
"'integration_tests:multiturn_nocandidate'",
",",
"model",
"=",
"'seq2seq'",
",",
"model_file",
"=",
"'zoo:unittest/seq2seq/model'",
",",
"dict_file",
"=",
"'zoo:unittest/seq2seq/model.dict'",
",",
"skip_generation",
"=",
"False",
",",
"inference",
"=",
"'greedy'",
",",
"batchsize",
"=",
"8",
",",
"num_examples",
"=",
"32",
",",
")",
")",
"self",
".",
"assertLess",
"(",
"valid",
"[",
"'ppl'",
"]",
",",
"1.2",
")",
"self",
".",
"assertLess",
"(",
"test",
"[",
"'ppl'",
"]",
",",
"1.2",
")"
] | [
43,
4
] | [
61,
41
] | python | en | ['en', 'error', 'th'] | False |
TestSeq2Seq.test_beamsearch | (self) |
Ensures beam search can generate the correct response.
|
Ensures beam search can generate the correct response.
| def test_beamsearch(self):
"""
Ensures beam search can generate the correct response.
"""
valid, test = testing_utils.eval_model(
dict(
task='integration_tests:multiturn_nocandidate',
model='seq2seq',
model_file='zoo:unittest/seq2seq/model',
dict_file='zoo:unittest/seq2seq/model.dict',
skip_generation=False,
inference='beam',
beam_size=5,
num_examples=16,
)
)
self.assertGreater(valid['accuracy'], 0.95)
self.assertGreater(test['accuracy'], 0.95) | [
"def",
"test_beamsearch",
"(",
"self",
")",
":",
"valid",
",",
"test",
"=",
"testing_utils",
".",
"eval_model",
"(",
"dict",
"(",
"task",
"=",
"'integration_tests:multiturn_nocandidate'",
",",
"model",
"=",
"'seq2seq'",
",",
"model_file",
"=",
"'zoo:unittest/seq2seq/model'",
",",
"dict_file",
"=",
"'zoo:unittest/seq2seq/model.dict'",
",",
"skip_generation",
"=",
"False",
",",
"inference",
"=",
"'beam'",
",",
"beam_size",
"=",
"5",
",",
"num_examples",
"=",
"16",
",",
")",
")",
"self",
".",
"assertGreater",
"(",
"valid",
"[",
"'accuracy'",
"]",
",",
"0.95",
")",
"self",
".",
"assertGreater",
"(",
"test",
"[",
"'accuracy'",
"]",
",",
"0.95",
")"
] | [
63,
4
] | [
80,
50
] | python | en | ['en', 'error', 'th'] | False |
net_photosynthesis_rate | (carbohydrate_amount_Buf, carbohydrate_amount_Leaf, air_co2, canopy_t, PAR_Canopy) |
Equation 9.10
carbohydrate_mass_flow_AirBuf = M_CH2O * carbohydrates_saturation_photosynthesis_rate_inhibition
* (gross_canopy_photosynthesis_rate - photosynthesis_process_photorespiration)
Returns: The photosynthesis rate [mg m^-2 s^-1]
|
Equation 9.10
carbohydrate_mass_flow_AirBuf = M_CH2O * carbohydrates_saturation_photosynthesis_rate_inhibition
* (gross_canopy_photosynthesis_rate - photosynthesis_process_photorespiration)
Returns: The photosynthesis rate [mg m^-2 s^-1]
| def net_photosynthesis_rate(carbohydrate_amount_Buf, carbohydrate_amount_Leaf, air_co2, canopy_t, PAR_Canopy):
"""
Equation 9.10
carbohydrate_mass_flow_AirBuf = M_CH2O * carbohydrates_saturation_photosynthesis_rate_inhibition
* (gross_canopy_photosynthesis_rate - photosynthesis_process_photorespiration)
Returns: The photosynthesis rate [mg m^-2 s^-1]
"""
carbohydrates_saturation_photosynthesis_rate_inhibition_rate = carbohydrates_saturation_photosynthesis_rate_inhibition(
carbohydrate_amount_Buf)
stomata_co2_concentration = co2_concentration_inside_stomata(air_co2)
co2_compensation_point = co2_compensation(carbohydrate_amount_Leaf, canopy_t)
gross_canopy_photosynthesis_rate = canopy_level_photosynthesis_rate(carbohydrate_amount_Leaf, canopy_t,
stomata_co2_concentration,
co2_compensation_point, PAR_Canopy)
return M_CH2O * carbohydrates_saturation_photosynthesis_rate_inhibition_rate \
* (gross_canopy_photosynthesis_rate
- photorespiration_rate(gross_canopy_photosynthesis_rate,
stomata_co2_concentration,
co2_compensation_point)) | [
"def",
"net_photosynthesis_rate",
"(",
"carbohydrate_amount_Buf",
",",
"carbohydrate_amount_Leaf",
",",
"air_co2",
",",
"canopy_t",
",",
"PAR_Canopy",
")",
":",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"=",
"carbohydrates_saturation_photosynthesis_rate_inhibition",
"(",
"carbohydrate_amount_Buf",
")",
"stomata_co2_concentration",
"=",
"co2_concentration_inside_stomata",
"(",
"air_co2",
")",
"co2_compensation_point",
"=",
"co2_compensation",
"(",
"carbohydrate_amount_Leaf",
",",
"canopy_t",
")",
"gross_canopy_photosynthesis_rate",
"=",
"canopy_level_photosynthesis_rate",
"(",
"carbohydrate_amount_Leaf",
",",
"canopy_t",
",",
"stomata_co2_concentration",
",",
"co2_compensation_point",
",",
"PAR_Canopy",
")",
"return",
"M_CH2O",
"*",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"*",
"(",
"gross_canopy_photosynthesis_rate",
"-",
"photorespiration_rate",
"(",
"gross_canopy_photosynthesis_rate",
",",
"stomata_co2_concentration",
",",
"co2_compensation_point",
")",
")"
] | [
7,
0
] | [
25,
62
] | python | en | ['en', 'error', 'th'] | False |
canopy_level_photosynthesis_rate | (carbohydrate_amount_Leaf, canopy_t, stomata_co2_concentration, co2_compensation_point, PAR_Canopy) |
Equations 9.12
canopy_level_photosynthesis_rate = electron_transport_rate * (stomata_CO2_concentration - CO2_compensation_point) / (4 * (stomata_CO2_concentration + 2*CO2_compensation_point))
Returns: gross canopy photosynthesis rate [µmol {CO2} m^-2 s^-1]
|
Equations 9.12
canopy_level_photosynthesis_rate = electron_transport_rate * (stomata_CO2_concentration - CO2_compensation_point) / (4 * (stomata_CO2_concentration + 2*CO2_compensation_point))
Returns: gross canopy photosynthesis rate [µmol {CO2} m^-2 s^-1]
| def canopy_level_photosynthesis_rate(carbohydrate_amount_Leaf, canopy_t, stomata_co2_concentration, co2_compensation_point, PAR_Canopy):
"""
Equations 9.12
canopy_level_photosynthesis_rate = electron_transport_rate * (stomata_CO2_concentration - CO2_compensation_point) / (4 * (stomata_CO2_concentration + 2*CO2_compensation_point))
Returns: gross canopy photosynthesis rate [µmol {CO2} m^-2 s^-1]
"""
electron_transport_rate = electron_transport(carbohydrate_amount_Leaf, canopy_t, PAR_Canopy)
return electron_transport_rate * (stomata_co2_concentration - co2_compensation_point) \
/ (4 * (stomata_co2_concentration + 2 * co2_compensation_point)) | [
"def",
"canopy_level_photosynthesis_rate",
"(",
"carbohydrate_amount_Leaf",
",",
"canopy_t",
",",
"stomata_co2_concentration",
",",
"co2_compensation_point",
",",
"PAR_Canopy",
")",
":",
"electron_transport_rate",
"=",
"electron_transport",
"(",
"carbohydrate_amount_Leaf",
",",
"canopy_t",
",",
"PAR_Canopy",
")",
"return",
"electron_transport_rate",
"*",
"(",
"stomata_co2_concentration",
"-",
"co2_compensation_point",
")",
"/",
"(",
"4",
"*",
"(",
"stomata_co2_concentration",
"+",
"2",
"*",
"co2_compensation_point",
")",
")"
] | [
28,
0
] | [
36,
75
] | python | en | ['en', 'error', 'th'] | False |
photorespiration_rate | (gross_canopy_photosynthesis_rate, stomata_co2_concentration, co2_compensation_point) |
Equations 9.13
photorespiration_rate = gross_canopy_photosynthesis_rate * CO2_compensation_point / stomata_CO2_concentration
Args:
gross_canopy_photosynthesis_rate:
stomata_co2_concentration:
co2_compensation_point:
Returns: photorespiration rate [µmol {CO2} m^-2 s^-1]
|
Equations 9.13
photorespiration_rate = gross_canopy_photosynthesis_rate * CO2_compensation_point / stomata_CO2_concentration
Args:
gross_canopy_photosynthesis_rate:
stomata_co2_concentration:
co2_compensation_point:
Returns: photorespiration rate [µmol {CO2} m^-2 s^-1]
| def photorespiration_rate(gross_canopy_photosynthesis_rate, stomata_co2_concentration, co2_compensation_point):
"""
Equations 9.13
photorespiration_rate = gross_canopy_photosynthesis_rate * CO2_compensation_point / stomata_CO2_concentration
Args:
gross_canopy_photosynthesis_rate:
stomata_co2_concentration:
co2_compensation_point:
Returns: photorespiration rate [µmol {CO2} m^-2 s^-1]
"""
return gross_canopy_photosynthesis_rate * co2_compensation_point / stomata_co2_concentration | [
"def",
"photorespiration_rate",
"(",
"gross_canopy_photosynthesis_rate",
",",
"stomata_co2_concentration",
",",
"co2_compensation_point",
")",
":",
"return",
"gross_canopy_photosynthesis_rate",
"*",
"co2_compensation_point",
"/",
"stomata_co2_concentration"
] | [
39,
0
] | [
49,
96
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_buffer_to_fruits | (carbohydrate_amount_Buf, canopy_t, sum_canopy_t, last_24_canopy_t) |
Equations 9.24
carbohydrate_flow_BufFruits = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_instantaneous_temperature_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* crop_development_stage_inhibition_rate
* growth_rate
* POTENTIAL_FRUIT_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to fruits [mg m^-2 s^-1]
|
Equations 9.24
carbohydrate_flow_BufFruits = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_instantaneous_temperature_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* crop_development_stage_inhibition_rate
* growth_rate
* POTENTIAL_FRUIT_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to fruits [mg m^-2 s^-1]
| def carbohydrate_flow_from_buffer_to_fruits(carbohydrate_amount_Buf, canopy_t, sum_canopy_t, last_24_canopy_t):
"""
Equations 9.24
carbohydrate_flow_BufFruits = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_instantaneous_temperature_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* crop_development_stage_inhibition_rate
* growth_rate
* POTENTIAL_FRUIT_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to fruits [mg m^-2 s^-1]
"""
carbohydrates_saturation_photosynthesis_rate_inhibition_rate = carbohydrates_saturation_photosynthesis_rate_inhibition(carbohydrate_amount_Buf)
non_optimal_instantaneous_temperature_inhibition_rate = non_optimal_instantaneous_temperature_inhibition(canopy_t)
non_optimal_24_hour_canopy_temperatures_inhibition_rate = non_optimal_24_hour_canopy_temperatures_inhibition(last_24_canopy_t)
crop_development_stage_inhibition_rate = crop_development_stage_inhibition(sum_canopy_t)
growth_rate = growth_rate_dependency_to_temperature(last_24_canopy_t)
return carbohydrates_saturation_photosynthesis_rate_inhibition_rate \
* non_optimal_instantaneous_temperature_inhibition_rate \
* non_optimal_24_hour_canopy_temperatures_inhibition_rate \
* crop_development_stage_inhibition_rate \
* growth_rate \
* POTENTIAL_FRUIT_GROWTH_RATE_COEF | [
"def",
"carbohydrate_flow_from_buffer_to_fruits",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
":",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"=",
"carbohydrates_saturation_photosynthesis_rate_inhibition",
"(",
"carbohydrate_amount_Buf",
")",
"non_optimal_instantaneous_temperature_inhibition_rate",
"=",
"non_optimal_instantaneous_temperature_inhibition",
"(",
"canopy_t",
")",
"non_optimal_24_hour_canopy_temperatures_inhibition_rate",
"=",
"non_optimal_24_hour_canopy_temperatures_inhibition",
"(",
"last_24_canopy_t",
")",
"crop_development_stage_inhibition_rate",
"=",
"crop_development_stage_inhibition",
"(",
"sum_canopy_t",
")",
"growth_rate",
"=",
"growth_rate_dependency_to_temperature",
"(",
"last_24_canopy_t",
")",
"return",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"*",
"non_optimal_instantaneous_temperature_inhibition_rate",
"*",
"non_optimal_24_hour_canopy_temperatures_inhibition_rate",
"*",
"crop_development_stage_inhibition_rate",
"*",
"growth_rate",
"*",
"POTENTIAL_FRUIT_GROWTH_RATE_COEF"
] | [
52,
0
] | [
73,
45
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_buffer_to_leaves | (carbohydrate_amount_Buf, last_24_canopy_t) |
Equations 9.25
carbohydrate_flow_BufLeaf = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* growth_rate * POTENTIAL_LEAF_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to leaves [mg m^-2 s^-1]
|
Equations 9.25
carbohydrate_flow_BufLeaf = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* growth_rate * POTENTIAL_LEAF_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to leaves [mg m^-2 s^-1]
| def carbohydrate_flow_from_buffer_to_leaves(carbohydrate_amount_Buf, last_24_canopy_t):
"""
Equations 9.25
carbohydrate_flow_BufLeaf = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* growth_rate * POTENTIAL_LEAF_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to leaves [mg m^-2 s^-1]
"""
carbohydrates_saturation_photosynthesis_rate_inhibition_rate = carbohydrates_saturation_photosynthesis_rate_inhibition(carbohydrate_amount_Buf)
non_optimal_24_hour_canopy_temperatures_inhibition_rate = non_optimal_24_hour_canopy_temperatures_inhibition(last_24_canopy_t)
growth_rate = growth_rate_dependency_to_temperature(last_24_canopy_t)
return carbohydrates_saturation_photosynthesis_rate_inhibition_rate \
* non_optimal_24_hour_canopy_temperatures_inhibition_rate \
* growth_rate \
* POTENTIAL_LEAF_GROWTH_RATE_COEF | [
"def",
"carbohydrate_flow_from_buffer_to_leaves",
"(",
"carbohydrate_amount_Buf",
",",
"last_24_canopy_t",
")",
":",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"=",
"carbohydrates_saturation_photosynthesis_rate_inhibition",
"(",
"carbohydrate_amount_Buf",
")",
"non_optimal_24_hour_canopy_temperatures_inhibition_rate",
"=",
"non_optimal_24_hour_canopy_temperatures_inhibition",
"(",
"last_24_canopy_t",
")",
"growth_rate",
"=",
"growth_rate_dependency_to_temperature",
"(",
"last_24_canopy_t",
")",
"return",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"*",
"non_optimal_24_hour_canopy_temperatures_inhibition_rate",
"*",
"growth_rate",
"*",
"POTENTIAL_LEAF_GROWTH_RATE_COEF"
] | [
76,
0
] | [
90,
44
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_buffer_to_stem | (carbohydrate_amount_Buf, last_24_canopy_t) |
Equations 9.25
carbohydrate_flow_BufStem = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* growth_rate
* POTENTIAL_STEM_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to stem [mg m^-2 s^-1]
|
Equations 9.25
carbohydrate_flow_BufStem = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* growth_rate
* POTENTIAL_STEM_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to stem [mg m^-2 s^-1]
| def carbohydrate_flow_from_buffer_to_stem(carbohydrate_amount_Buf, last_24_canopy_t):
"""
Equations 9.25
carbohydrate_flow_BufStem = carbohydrates_saturation_photosynthesis_rate_inhibition_rate
* non_optimal_24_hour_canopy_temperatures_inhibition_rate
* growth_rate
* POTENTIAL_STEM_GROWTH_RATE_COEF
Returns: carbohydrate flow from buffer to stem [mg m^-2 s^-1]
"""
carbohydrates_saturation_photosynthesis_rate_inhibition_rate = carbohydrates_saturation_photosynthesis_rate_inhibition(carbohydrate_amount_Buf)
non_optimal_24_hour_canopy_temperatures_inhibition_rate = non_optimal_24_hour_canopy_temperatures_inhibition(last_24_canopy_t)
growth_rate = growth_rate_dependency_to_temperature(last_24_canopy_t)
return carbohydrates_saturation_photosynthesis_rate_inhibition_rate \
* non_optimal_24_hour_canopy_temperatures_inhibition_rate \
* growth_rate \
* POTENTIAL_STEM_GROWTH_RATE_COEF | [
"def",
"carbohydrate_flow_from_buffer_to_stem",
"(",
"carbohydrate_amount_Buf",
",",
"last_24_canopy_t",
")",
":",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"=",
"carbohydrates_saturation_photosynthesis_rate_inhibition",
"(",
"carbohydrate_amount_Buf",
")",
"non_optimal_24_hour_canopy_temperatures_inhibition_rate",
"=",
"non_optimal_24_hour_canopy_temperatures_inhibition",
"(",
"last_24_canopy_t",
")",
"growth_rate",
"=",
"growth_rate_dependency_to_temperature",
"(",
"last_24_canopy_t",
")",
"return",
"carbohydrates_saturation_photosynthesis_rate_inhibition_rate",
"*",
"non_optimal_24_hour_canopy_temperatures_inhibition_rate",
"*",
"growth_rate",
"*",
"POTENTIAL_STEM_GROWTH_RATE_COEF"
] | [
93,
0
] | [
108,
44
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_through_fruit_stages | (jth: int, carbohydrate_amount_Fruits, last_24_canopy_t) |
Equations 9.34
carbohydrate_flow_Fruit_j_Fruit_jplus = fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * carbohydrate_amount_Fruit_j
Args:
jth: stage number
Returns: carbohydrates flow from fruit stage j to fruit stage j+1 [mg m^-2 s^-1]
|
Equations 9.34
carbohydrate_flow_Fruit_j_Fruit_jplus = fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * carbohydrate_amount_Fruit_j
Args:
jth: stage number | def carbohydrate_flow_through_fruit_stages(jth: int, carbohydrate_amount_Fruits, last_24_canopy_t):
"""
Equations 9.34
carbohydrate_flow_Fruit_j_Fruit_jplus = fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * carbohydrate_amount_Fruit_j
Args:
jth: stage number
Returns: carbohydrates flow from fruit stage j to fruit stage j+1 [mg m^-2 s^-1]
"""
carbohydrate_amount_Fruit_j = carbohydrate_amount_Fruits[jth - 1]
fruit_development_rate = fruit_development(last_24_canopy_t)
return fruit_development_rate * FRUIT_DEVELOPMENT_STAGES_NUM * carbohydrate_amount_Fruit_j | [
"def",
"carbohydrate_flow_through_fruit_stages",
"(",
"jth",
":",
"int",
",",
"carbohydrate_amount_Fruits",
",",
"last_24_canopy_t",
")",
":",
"carbohydrate_amount_Fruit_j",
"=",
"carbohydrate_amount_Fruits",
"[",
"jth",
"-",
"1",
"]",
"fruit_development_rate",
"=",
"fruit_development",
"(",
"last_24_canopy_t",
")",
"return",
"fruit_development_rate",
"*",
"FRUIT_DEVELOPMENT_STAGES_NUM",
"*",
"carbohydrate_amount_Fruit_j"
] | [
111,
0
] | [
122,
94
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_buffer_to_first_fruit_stage | (carbohydrate_amount_Buf, canopy_t, sum_canopy_t, last_24_canopy_t) |
Equations 9.35
carbohydrate_flow_BufFruit_1 = W_Pot_Fruit_1 * number_flow_BufFruit_1
Returns: carbohydrates flow from buffer to fruit stage 1 [mg m^-2 s^-1]
|
Equations 9.35
carbohydrate_flow_BufFruit_1 = W_Pot_Fruit_1 * number_flow_BufFruit_1
Returns: carbohydrates flow from buffer to fruit stage 1 [mg m^-2 s^-1]
| def carbohydrate_flow_from_buffer_to_first_fruit_stage(carbohydrate_amount_Buf, canopy_t, sum_canopy_t, last_24_canopy_t):
"""
Equations 9.35
carbohydrate_flow_BufFruit_1 = W_Pot_Fruit_1 * number_flow_BufFruit_1
Returns: carbohydrates flow from buffer to fruit stage 1 [mg m^-2 s^-1]
"""
carbohydrate_flow_BufFruits = carbohydrate_flow_from_buffer_to_fruits(carbohydrate_amount_Buf, canopy_t,
sum_canopy_t, last_24_canopy_t)
number_flow_BufFruit_1 = fruit_set_of_first_development_stage(last_24_canopy_t, carbohydrate_flow_BufFruits)
W_Pot_Fruit_1 = fruit_growth(1, last_24_canopy_t) * FRUIT_DEVELOPMENT_STAGES_NUM
return W_Pot_Fruit_1 * number_flow_BufFruit_1 | [
"def",
"carbohydrate_flow_from_buffer_to_first_fruit_stage",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
":",
"carbohydrate_flow_BufFruits",
"=",
"carbohydrate_flow_from_buffer_to_fruits",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
"number_flow_BufFruit_1",
"=",
"fruit_set_of_first_development_stage",
"(",
"last_24_canopy_t",
",",
"carbohydrate_flow_BufFruits",
")",
"W_Pot_Fruit_1",
"=",
"fruit_growth",
"(",
"1",
",",
"last_24_canopy_t",
")",
"*",
"FRUIT_DEVELOPMENT_STAGES_NUM",
"return",
"W_Pot_Fruit_1",
"*",
"number_flow_BufFruit_1"
] | [
125,
0
] | [
135,
49
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_buffer_to_fruit_stages | (jth: int, carbohydrate_amount_Buf, number_Fruits, canopy_t,
sum_canopy_t, last_24_canopy_t) |
Equations 9.36
carbohydrate_flow_BufFruit_j = sum_carbohydrate_flow_BufFruit_conversion_factor * number_fruit_j
* fruit_growth_rate * (carbohydrate_flow_BufFruits - carbohydrate_flow_BufFruit_1)
Returns: carbohydrates flow from buffer to fruit stage j [mg m^-2 s^-1]
|
Equations 9.36
carbohydrate_flow_BufFruit_j = sum_carbohydrate_flow_BufFruit_conversion_factor * number_fruit_j
* fruit_growth_rate * (carbohydrate_flow_BufFruits - carbohydrate_flow_BufFruit_1)
Returns: carbohydrates flow from buffer to fruit stage j [mg m^-2 s^-1]
| def carbohydrate_flow_from_buffer_to_fruit_stages(jth: int, carbohydrate_amount_Buf, number_Fruits, canopy_t,
sum_canopy_t, last_24_canopy_t):
"""
Equations 9.36
carbohydrate_flow_BufFruit_j = sum_carbohydrate_flow_BufFruit_conversion_factor * number_fruit_j
* fruit_growth_rate * (carbohydrate_flow_BufFruits - carbohydrate_flow_BufFruit_1)
Returns: carbohydrates flow from buffer to fruit stage j [mg m^-2 s^-1]
"""
if jth == 1:
return carbohydrate_flow_from_buffer_to_first_fruit_stage(carbohydrate_amount_Buf, canopy_t, sum_canopy_t,
last_24_canopy_t)
sum_carbohydrate_flow_BufFruit_conversion_factor = sum_carbohydrate_flow_BufFruit_conversion(number_Fruits, last_24_canopy_t)
number_fruit_j = number_Fruits[jth]
fruit_growth_rate_j = fruit_growth(jth, last_24_canopy_t)
carbohydrate_flow_BufFruits = carbohydrate_flow_from_buffer_to_fruits(carbohydrate_amount_Buf, canopy_t,
sum_canopy_t, last_24_canopy_t)
carbohydrate_flow_BufFruit_1 = carbohydrate_flow_from_buffer_to_fruit_stages(1, carbohydrate_amount_Buf, None,
canopy_t, sum_canopy_t, last_24_canopy_t)
return sum_carbohydrate_flow_BufFruit_conversion_factor * number_fruit_j \
* fruit_growth_rate_j * (carbohydrate_flow_BufFruits - carbohydrate_flow_BufFruit_1) | [
"def",
"carbohydrate_flow_from_buffer_to_fruit_stages",
"(",
"jth",
":",
"int",
",",
"carbohydrate_amount_Buf",
",",
"number_Fruits",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
":",
"if",
"jth",
"==",
"1",
":",
"return",
"carbohydrate_flow_from_buffer_to_first_fruit_stage",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
"sum_carbohydrate_flow_BufFruit_conversion_factor",
"=",
"sum_carbohydrate_flow_BufFruit_conversion",
"(",
"number_Fruits",
",",
"last_24_canopy_t",
")",
"number_fruit_j",
"=",
"number_Fruits",
"[",
"jth",
"]",
"fruit_growth_rate_j",
"=",
"fruit_growth",
"(",
"jth",
",",
"last_24_canopy_t",
")",
"carbohydrate_flow_BufFruits",
"=",
"carbohydrate_flow_from_buffer_to_fruits",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
"carbohydrate_flow_BufFruit_1",
"=",
"carbohydrate_flow_from_buffer_to_fruit_stages",
"(",
"1",
",",
"carbohydrate_amount_Buf",
",",
"None",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
"return",
"sum_carbohydrate_flow_BufFruit_conversion_factor",
"*",
"number_fruit_j",
"*",
"fruit_growth_rate_j",
"*",
"(",
"carbohydrate_flow_BufFruits",
"-",
"carbohydrate_flow_BufFruit_1",
")"
] | [
138,
0
] | [
158,
95
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_growth_respiration | (carbohydrate_amount_Buf, canopy_t, sum_canopy_t, last_24_canopy_t) |
Equations 9.43
carbohydrate_flow_BufAir =
Returns: carbohydrates flow from growth respiration [mg m^-2 s^-1]
|
Equations 9.43
carbohydrate_flow_BufAir =
Returns: carbohydrates flow from growth respiration [mg m^-2 s^-1]
| def carbohydrate_flow_from_growth_respiration(carbohydrate_amount_Buf, canopy_t, sum_canopy_t, last_24_canopy_t):
"""
Equations 9.43
carbohydrate_flow_BufAir =
Returns: carbohydrates flow from growth respiration [mg m^-2 s^-1]
"""
carbohydrate_flow_BufFruits = carbohydrate_flow_from_buffer_to_fruits(carbohydrate_amount_Buf, canopy_t,
sum_canopy_t, last_24_canopy_t)
carbohydrate_flow_BufLeaf = carbohydrate_flow_from_buffer_to_leaves(carbohydrate_amount_Buf, last_24_canopy_t)
carbohydrate_flow_BufStem = carbohydrate_flow_from_buffer_to_stem(carbohydrate_amount_Buf, last_24_canopy_t)
return FRUIT_GROWTH_RESPIRATION_COEF * carbohydrate_flow_BufFruits \
+ LEAF_GROWTH_RESPIRATION_COEF * carbohydrate_flow_BufLeaf \
+ STEM_GROWTH_RESPIRATION_COEF * carbohydrate_flow_BufStem | [
"def",
"carbohydrate_flow_from_growth_respiration",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
":",
"carbohydrate_flow_BufFruits",
"=",
"carbohydrate_flow_from_buffer_to_fruits",
"(",
"carbohydrate_amount_Buf",
",",
"canopy_t",
",",
"sum_canopy_t",
",",
"last_24_canopy_t",
")",
"carbohydrate_flow_BufLeaf",
"=",
"carbohydrate_flow_from_buffer_to_leaves",
"(",
"carbohydrate_amount_Buf",
",",
"last_24_canopy_t",
")",
"carbohydrate_flow_BufStem",
"=",
"carbohydrate_flow_from_buffer_to_stem",
"(",
"carbohydrate_amount_Buf",
",",
"last_24_canopy_t",
")",
"return",
"FRUIT_GROWTH_RESPIRATION_COEF",
"*",
"carbohydrate_flow_BufFruits",
"+",
"LEAF_GROWTH_RESPIRATION_COEF",
"*",
"carbohydrate_flow_BufLeaf",
"+",
"STEM_GROWTH_RESPIRATION_COEF",
"*",
"carbohydrate_flow_BufStem"
] | [
161,
0
] | [
173,
69
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_fruit_maintenance_respiration | (carbohydrate_amount_Fruit_j, last_24_canopy_t) |
Equations 9.45
carbohydrate_flow_FruitAir_j = FRUIT_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Fruit_j
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from fruit maintenance respiration [mg m^-2 s^-1]
|
Equations 9.45
carbohydrate_flow_FruitAir_j = FRUIT_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Fruit_j
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from fruit maintenance respiration [mg m^-2 s^-1]
| def carbohydrate_flow_from_fruit_maintenance_respiration(carbohydrate_amount_Fruit_j, last_24_canopy_t):
"""
Equations 9.45
carbohydrate_flow_FruitAir_j = FRUIT_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Fruit_j
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from fruit maintenance respiration [mg m^-2 s^-1]
"""
return FRUIT_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Fruit_j \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE)) | [
"def",
"carbohydrate_flow_from_fruit_maintenance_respiration",
"(",
"carbohydrate_amount_Fruit_j",
",",
"last_24_canopy_t",
")",
":",
"return",
"FRUIT_MAINTENANCE_RESPIRATION_COEF",
"*",
"Q10_M",
"**",
"(",
"0.1",
"*",
"(",
"last_24_canopy_t",
"-",
"25",
")",
")",
"*",
"carbohydrate_amount_Fruit_j",
"*",
"(",
"1",
"-",
"math",
".",
"exp",
"(",
"-",
"MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF",
"*",
"RELATIVE_GROWTH_RATE",
")",
")"
] | [
176,
0
] | [
184,
99
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_leaf_maintenance_respiration | (carbohydrate_amount_Leaf, last_24_canopy_t) |
Equations 9.45
carbohydrate_flow_LeafAir = LEAF_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Leaf \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from leaf maintenance respiration [mg m^-2 s^-1]
|
Equations 9.45
carbohydrate_flow_LeafAir = LEAF_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Leaf \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from leaf maintenance respiration [mg m^-2 s^-1]
| def carbohydrate_flow_from_leaf_maintenance_respiration(carbohydrate_amount_Leaf, last_24_canopy_t):
"""
Equations 9.45
carbohydrate_flow_LeafAir = LEAF_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Leaf \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from leaf maintenance respiration [mg m^-2 s^-1]
"""
return LEAF_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Leaf \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE)) | [
"def",
"carbohydrate_flow_from_leaf_maintenance_respiration",
"(",
"carbohydrate_amount_Leaf",
",",
"last_24_canopy_t",
")",
":",
"return",
"LEAF_MAINTENANCE_RESPIRATION_COEF",
"*",
"Q10_M",
"**",
"(",
"0.1",
"*",
"(",
"last_24_canopy_t",
"-",
"25",
")",
")",
"*",
"carbohydrate_amount_Leaf",
"*",
"(",
"1",
"-",
"math",
".",
"exp",
"(",
"-",
"MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF",
"*",
"RELATIVE_GROWTH_RATE",
")",
")"
] | [
187,
0
] | [
195,
99
] | python | en | ['en', 'error', 'th'] | False |
carbohydrate_flow_from_stem_maintenance_respiration | (carbohydrate_amount_Stem, last_24_canopy_t) |
Equations 9.45
carbohydrate_flow_StemAir = STEM_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Stem \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from stem maintenance respiration [mg m^-2 s^-1]
|
Equations 9.45
carbohydrate_flow_StemAir = STEM_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Stem \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from stem maintenance respiration [mg m^-2 s^-1]
| def carbohydrate_flow_from_stem_maintenance_respiration(carbohydrate_amount_Stem, last_24_canopy_t):
"""
Equations 9.45
carbohydrate_flow_StemAir = STEM_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Stem \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE))
Returns: carbohydrates flow from stem maintenance respiration [mg m^-2 s^-1]
"""
return STEM_MAINTENANCE_RESPIRATION_COEF * Q10_M**(0.1*(last_24_canopy_t-25)) * carbohydrate_amount_Stem \
* (1 - math.exp(-MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF*RELATIVE_GROWTH_RATE)) | [
"def",
"carbohydrate_flow_from_stem_maintenance_respiration",
"(",
"carbohydrate_amount_Stem",
",",
"last_24_canopy_t",
")",
":",
"return",
"STEM_MAINTENANCE_RESPIRATION_COEF",
"*",
"Q10_M",
"**",
"(",
"0.1",
"*",
"(",
"last_24_canopy_t",
"-",
"25",
")",
")",
"*",
"carbohydrate_amount_Stem",
"*",
"(",
"1",
"-",
"math",
".",
"exp",
"(",
"-",
"MAINTENANCE_RESPIRATION_FUNCTION_REGRESSION_COEF",
"*",
"RELATIVE_GROWTH_RATE",
")",
")"
] | [
198,
0
] | [
206,
99
] | python | en | ['en', 'error', 'th'] | False |
leaf_harvest_rate | (carbohydrate_amount_Leaf) |
Equations 9.47, B.5
carbohydrate_flow_LeafHar = S_ * (carbohydrate_amount_Leaf - maximum_carbohydrates_stored_in_the_leaves)
Returns: leaf harvest rate [mg m^-2 s^-1]
|
Equations 9.47, B.5
carbohydrate_flow_LeafHar = S_ * (carbohydrate_amount_Leaf - maximum_carbohydrates_stored_in_the_leaves)
Returns: leaf harvest rate [mg m^-2 s^-1]
| def leaf_harvest_rate(carbohydrate_amount_Leaf):
"""
Equations 9.47, B.5
carbohydrate_flow_LeafHar = S_ * (carbohydrate_amount_Leaf - maximum_carbohydrates_stored_in_the_leaves)
Returns: leaf harvest rate [mg m^-2 s^-1]
"""
max_stored_leaves_carbohydrates = maximum_carbohydrates_stored_in_the_leaves()
return smoothed_conditional_function(carbohydrate_amount_Leaf, -5e-5, max_stored_leaves_carbohydrates) \
* (carbohydrate_amount_Leaf - max_stored_leaves_carbohydrates) | [
"def",
"leaf_harvest_rate",
"(",
"carbohydrate_amount_Leaf",
")",
":",
"max_stored_leaves_carbohydrates",
"=",
"maximum_carbohydrates_stored_in_the_leaves",
"(",
")",
"return",
"smoothed_conditional_function",
"(",
"carbohydrate_amount_Leaf",
",",
"-",
"5e-5",
",",
"max_stored_leaves_carbohydrates",
")",
"*",
"(",
"carbohydrate_amount_Leaf",
"-",
"max_stored_leaves_carbohydrates",
")"
] | [
209,
0
] | [
217,
73
] | python | en | ['en', 'error', 'th'] | False |
Injector.__init__ | (
self, settings: Mapping[str, object] = None, enforce_typing: bool = True
) | Initialize an `Injector`. | Initialize an `Injector`. | def __init__(
self, settings: Mapping[str, object] = None, enforce_typing: bool = True
):
"""Initialize an `Injector`."""
self.enforce_typing = enforce_typing
self._providers = {}
self._settings = Settings(settings) | [
"def",
"__init__",
"(",
"self",
",",
"settings",
":",
"Mapping",
"[",
"str",
",",
"object",
"]",
"=",
"None",
",",
"enforce_typing",
":",
"bool",
"=",
"True",
")",
":",
"self",
".",
"enforce_typing",
"=",
"enforce_typing",
"self",
".",
"_providers",
"=",
"{",
"}",
"self",
".",
"_settings",
"=",
"Settings",
"(",
"settings",
")"
] | [
12,
4
] | [
18,
43
] | python | en | ['en', 'en', 'it'] | True |
Injector.settings | (self) | Accessor for scope-specific settings. | Accessor for scope-specific settings. | def settings(self) -> Settings:
"""Accessor for scope-specific settings."""
return self._settings | [
"def",
"settings",
"(",
"self",
")",
"->",
"Settings",
":",
"return",
"self",
".",
"_settings"
] | [
21,
4
] | [
23,
29
] | python | en | ['en', 'en', 'en'] | True |
Injector.settings | (self, settings: Settings) | Setter for scope-specific settings. | Setter for scope-specific settings. | def settings(self, settings: Settings):
"""Setter for scope-specific settings."""
self._settings = settings | [
"def",
"settings",
"(",
"self",
",",
"settings",
":",
"Settings",
")",
":",
"self",
".",
"_settings",
"=",
"settings"
] | [
26,
4
] | [
28,
33
] | python | en | ['en', 'no', 'en'] | True |
Injector.bind_instance | (self, base_cls: type, instance: object) | Add a static instance as a class binding. | Add a static instance as a class binding. | def bind_instance(self, base_cls: type, instance: object):
"""Add a static instance as a class binding."""
self._providers[base_cls] = InstanceProvider(instance) | [
"def",
"bind_instance",
"(",
"self",
",",
"base_cls",
":",
"type",
",",
"instance",
":",
"object",
")",
":",
"self",
".",
"_providers",
"[",
"base_cls",
"]",
"=",
"InstanceProvider",
"(",
"instance",
")"
] | [
30,
4
] | [
32,
62
] | python | en | ['en', 'en', 'en'] | True |
Injector.bind_provider | (
self, base_cls: type, provider: BaseProvider, *, cache: bool = False
) | Add a dynamic instance resolver as a class binding. | Add a dynamic instance resolver as a class binding. | def bind_provider(
self, base_cls: type, provider: BaseProvider, *, cache: bool = False
):
"""Add a dynamic instance resolver as a class binding."""
if not provider:
raise ValueError("Class provider binding must be non-empty")
if cache and not isinstance(provider, CachedProvider):
provider = CachedProvider(provider)
self._providers[base_cls] = provider | [
"def",
"bind_provider",
"(",
"self",
",",
"base_cls",
":",
"type",
",",
"provider",
":",
"BaseProvider",
",",
"*",
",",
"cache",
":",
"bool",
"=",
"False",
")",
":",
"if",
"not",
"provider",
":",
"raise",
"ValueError",
"(",
"\"Class provider binding must be non-empty\"",
")",
"if",
"cache",
"and",
"not",
"isinstance",
"(",
"provider",
",",
"CachedProvider",
")",
":",
"provider",
"=",
"CachedProvider",
"(",
"provider",
")",
"self",
".",
"_providers",
"[",
"base_cls",
"]",
"=",
"provider"
] | [
34,
4
] | [
42,
44
] | python | en | ['en', 'en', 'en'] | True |
Injector.clear_binding | (self, base_cls: type) | Remove a previously-added binding. | Remove a previously-added binding. | def clear_binding(self, base_cls: type):
"""Remove a previously-added binding."""
if base_cls in self._providers:
del self._providers[base_cls] | [
"def",
"clear_binding",
"(",
"self",
",",
"base_cls",
":",
"type",
")",
":",
"if",
"base_cls",
"in",
"self",
".",
"_providers",
":",
"del",
"self",
".",
"_providers",
"[",
"base_cls",
"]"
] | [
44,
4
] | [
47,
41
] | python | en | ['en', 'en', 'en'] | True |
Injector.get_provider | (self, base_cls: type) | Find the provider associated with a class binding. | Find the provider associated with a class binding. | def get_provider(self, base_cls: type):
"""Find the provider associated with a class binding."""
return self._providers.get(base_cls) | [
"def",
"get_provider",
"(",
"self",
",",
"base_cls",
":",
"type",
")",
":",
"return",
"self",
".",
"_providers",
".",
"get",
"(",
"base_cls",
")"
] | [
49,
4
] | [
51,
44
] | python | en | ['en', 'en', 'en'] | True |
Injector.inject | (
self,
base_cls: type,
settings: Mapping[str, object] = None,
*,
required: bool = True,
) |
Get the provided instance of a given class identifier.
Args:
cls: The base class to retrieve an instance of
params: An optional dict providing configuration to the provider
Returns:
An instance of the base class, or None
|
Get the provided instance of a given class identifier. | async def inject(
self,
base_cls: type,
settings: Mapping[str, object] = None,
*,
required: bool = True,
):
"""
Get the provided instance of a given class identifier.
Args:
cls: The base class to retrieve an instance of
params: An optional dict providing configuration to the provider
Returns:
An instance of the base class, or None
"""
if not base_cls:
raise InjectorError("No base class provided for lookup")
provider = self._providers.get(base_cls)
ext_settings = self.settings.extend(settings) if settings else self.settings
if provider:
result = await provider.provide(ext_settings, self)
else:
result = None
if result is None:
if required:
raise InjectorError(
"No instance provided for class: {}".format(base_cls.__name__)
)
elif not isinstance(result, base_cls) and self.enforce_typing:
raise InjectorError(
"Provided instance does not implement the base class: {}".format(
base_cls.__name__
)
)
return result | [
"async",
"def",
"inject",
"(",
"self",
",",
"base_cls",
":",
"type",
",",
"settings",
":",
"Mapping",
"[",
"str",
",",
"object",
"]",
"=",
"None",
",",
"*",
",",
"required",
":",
"bool",
"=",
"True",
",",
")",
":",
"if",
"not",
"base_cls",
":",
"raise",
"InjectorError",
"(",
"\"No base class provided for lookup\"",
")",
"provider",
"=",
"self",
".",
"_providers",
".",
"get",
"(",
"base_cls",
")",
"ext_settings",
"=",
"self",
".",
"settings",
".",
"extend",
"(",
"settings",
")",
"if",
"settings",
"else",
"self",
".",
"settings",
"if",
"provider",
":",
"result",
"=",
"await",
"provider",
".",
"provide",
"(",
"ext_settings",
",",
"self",
")",
"else",
":",
"result",
"=",
"None",
"if",
"result",
"is",
"None",
":",
"if",
"required",
":",
"raise",
"InjectorError",
"(",
"\"No instance provided for class: {}\"",
".",
"format",
"(",
"base_cls",
".",
"__name__",
")",
")",
"elif",
"not",
"isinstance",
"(",
"result",
",",
"base_cls",
")",
"and",
"self",
".",
"enforce_typing",
":",
"raise",
"InjectorError",
"(",
"\"Provided instance does not implement the base class: {}\"",
".",
"format",
"(",
"base_cls",
".",
"__name__",
")",
")",
"return",
"result"
] | [
53,
4
] | [
90,
21
] | python | en | ['en', 'error', 'th'] | False |
Injector.copy | (self) | Produce a copy of the injector instance. | Produce a copy of the injector instance. | def copy(self) -> BaseInjector:
"""Produce a copy of the injector instance."""
result = Injector(self.settings)
result._providers = self._providers.copy()
return result | [
"def",
"copy",
"(",
"self",
")",
"->",
"BaseInjector",
":",
"result",
"=",
"Injector",
"(",
"self",
".",
"settings",
")",
"result",
".",
"_providers",
"=",
"self",
".",
"_providers",
".",
"copy",
"(",
")",
"return",
"result"
] | [
92,
4
] | [
96,
21
] | python | en | ['en', 'en', 'en'] | True |
Injector.__repr__ | (self) | Provide a human readable representation of this object. | Provide a human readable representation of this object. | def __repr__(self) -> str:
"""Provide a human readable representation of this object."""
return f"<{self.__class__.__name__}>" | [
"def",
"__repr__",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"<{self.__class__.__name__}>\""
] | [
98,
4
] | [
100,
45
] | python | en | ['en', 'en', 'en'] | True |
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.indicator.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.indicator.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.indicator.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.indicator.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.indicator.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.indicator.Stream \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.indicator.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 |
is_block | (modules) | Check if is ResNet building block. | Check if is ResNet building block. | def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (BasicBlock, Bottleneck, BottleneckX, Bottle2neck)):
return True
return False | [
"def",
"is_block",
"(",
"modules",
")",
":",
"if",
"isinstance",
"(",
"modules",
",",
"(",
"BasicBlock",
",",
"Bottleneck",
",",
"BottleneckX",
",",
"Bottle2neck",
")",
")",
":",
"return",
"True",
"return",
"False"
] | [
14,
0
] | [
18,
16
] | python | en | ['en', 'en', 'en'] | True |
is_norm | (modules) | Check if is one of the norms. | Check if is one of the norms. | def is_norm(modules):
"""Check if is one of the norms."""
if isinstance(modules, (GroupNorm, _BatchNorm)):
return True
return False | [
"def",
"is_norm",
"(",
"modules",
")",
":",
"if",
"isinstance",
"(",
"modules",
",",
"(",
"GroupNorm",
",",
"_BatchNorm",
")",
")",
":",
"return",
"True",
"return",
"False"
] | [
21,
0
] | [
25,
16
] | python | en | ['en', 'en', 'en'] | True |
all_zeros | (modules) | Check if the weight(and bias) is all zero. | Check if the weight(and bias) is all zero. | def all_zeros(modules):
"""Check if the weight(and bias) is all zero."""
weight_zero = torch.allclose(modules.weight.data,
torch.zeros_like(modules.weight.data))
if hasattr(modules, 'bias'):
bias_zero = torch.allclose(modules.bias.data,
torch.zeros_like(modules.bias.data))
else:
bias_zero = True
return weight_zero and bias_zero | [
"def",
"all_zeros",
"(",
"modules",
")",
":",
"weight_zero",
"=",
"torch",
".",
"allclose",
"(",
"modules",
".",
"weight",
".",
"data",
",",
"torch",
".",
"zeros_like",
"(",
"modules",
".",
"weight",
".",
"data",
")",
")",
"if",
"hasattr",
"(",
"modules",
",",
"'bias'",
")",
":",
"bias_zero",
"=",
"torch",
".",
"allclose",
"(",
"modules",
".",
"bias",
".",
"data",
",",
"torch",
".",
"zeros_like",
"(",
"modules",
".",
"bias",
".",
"data",
")",
")",
"else",
":",
"bias_zero",
"=",
"True",
"return",
"weight_zero",
"and",
"bias_zero"
] | [
28,
0
] | [
38,
36
] | python | en | ['en', 'en', 'en'] | True |
check_norm_state | (modules, train_state) | Check if norm layer is in correct train state. | Check if norm layer is in correct train state. | def check_norm_state(modules, train_state):
"""Check if norm layer is in correct train state."""
for mod in modules:
if isinstance(mod, _BatchNorm):
if mod.training != train_state:
return False
return True | [
"def",
"check_norm_state",
"(",
"modules",
",",
"train_state",
")",
":",
"for",
"mod",
"in",
"modules",
":",
"if",
"isinstance",
"(",
"mod",
",",
"_BatchNorm",
")",
":",
"if",
"mod",
".",
"training",
"!=",
"train_state",
":",
"return",
"False",
"return",
"True"
] | [
41,
0
] | [
47,
15
] | python | en | ['en', 'en', 'en'] | True |
test_resnet_backbone | () | Test resnet backbone. | Test resnet backbone. | def test_resnet_backbone():
"""Test resnet backbone."""
with pytest.raises(KeyError):
# ResNet depth should be in [18, 34, 50, 101, 152]
ResNet(20)
with pytest.raises(AssertionError):
# In ResNet: 1 <= num_stages <= 4
ResNet(50, num_stages=0)
with pytest.raises(AssertionError):
# len(stage_with_dcn) == num_stages
dcn = dict(type='DCN', deform_groups=1, fallback_on_stride=False)
ResNet(50, dcn=dcn, stage_with_dcn=(True, ))
with pytest.raises(AssertionError):
# len(stage_with_plugin) == num_stages
plugins = [
dict(
cfg=dict(type='ContextBlock', ratio=1. / 16),
stages=(False, True, True),
position='after_conv3')
]
ResNet(50, plugins=plugins)
with pytest.raises(AssertionError):
# In ResNet: 1 <= num_stages <= 4
ResNet(50, num_stages=5)
with pytest.raises(AssertionError):
# len(strides) == len(dilations) == num_stages
ResNet(50, strides=(1, ), dilations=(1, 1), num_stages=3)
with pytest.raises(TypeError):
# pretrained must be a string path
model = ResNet(50)
model.init_weights(pretrained=0)
with pytest.raises(AssertionError):
# Style must be in ['pytorch', 'caffe']
ResNet(50, style='tensorflow')
# Test ResNet50 norm_eval=True
model = ResNet(50, norm_eval=True)
model.init_weights()
model.train()
assert check_norm_state(model.modules(), False)
# Test ResNet50 with torchvision pretrained weight
model = ResNet(depth=50, norm_eval=True)
model.init_weights('torchvision://resnet50')
model.train()
assert check_norm_state(model.modules(), False)
# Test ResNet50 with first stage frozen
frozen_stages = 1
model = ResNet(50, frozen_stages=frozen_stages)
model.init_weights()
model.train()
assert model.norm1.training is False
for layer in [model.conv1, model.norm1]:
for param in layer.parameters():
assert param.requires_grad is False
for i in range(1, frozen_stages + 1):
layer = getattr(model, f'layer{i}')
for mod in layer.modules():
if isinstance(mod, _BatchNorm):
assert mod.training is False
for param in layer.parameters():
assert param.requires_grad is False
# Test ResNet50V1d with first stage frozen
model = ResNetV1d(depth=50, frozen_stages=frozen_stages)
assert len(model.stem) == 9
model.init_weights()
model.train()
check_norm_state(model.stem, False)
for param in model.stem.parameters():
assert param.requires_grad is False
for i in range(1, frozen_stages + 1):
layer = getattr(model, f'layer{i}')
for mod in layer.modules():
if isinstance(mod, _BatchNorm):
assert mod.training is False
for param in layer.parameters():
assert param.requires_grad is False
# Test ResNet18 forward
model = ResNet(18)
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 64, 56, 56])
assert feat[1].shape == torch.Size([1, 128, 28, 28])
assert feat[2].shape == torch.Size([1, 256, 14, 14])
assert feat[3].shape == torch.Size([1, 512, 7, 7])
# Test ResNet18 with checkpoint forward
model = ResNet(18, with_cp=True)
for m in model.modules():
if is_block(m):
assert m.with_cp
# Test ResNet50 with BatchNorm forward
model = ResNet(50)
for m in model.modules():
if is_norm(m):
assert isinstance(m, _BatchNorm)
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50 with layers 1, 2, 3 out forward
model = ResNet(50, out_indices=(0, 1, 2))
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 3
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
# Test ResNet50 with checkpoint forward
model = ResNet(50, with_cp=True)
for m in model.modules():
if is_block(m):
assert m.with_cp
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50 with GroupNorm forward
model = ResNet(
50, norm_cfg=dict(type='GN', num_groups=32, requires_grad=True))
for m in model.modules():
if is_norm(m):
assert isinstance(m, GroupNorm)
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50 with 1 GeneralizedAttention after conv2, 1 NonLocal2D
# after conv2, 1 ContextBlock after conv3 in layers 2, 3, 4
plugins = [
dict(
cfg=dict(
type='GeneralizedAttention',
spatial_range=-1,
num_heads=8,
attention_type='0010',
kv_stride=2),
stages=(False, True, True, True),
position='after_conv2'),
dict(cfg=dict(type='NonLocal2d'), position='after_conv2'),
dict(
cfg=dict(type='ContextBlock', ratio=1. / 16),
stages=(False, True, True, False),
position='after_conv3')
]
model = ResNet(50, plugins=plugins)
for m in model.layer1.modules():
if is_block(m):
assert not hasattr(m, 'context_block')
assert not hasattr(m, 'gen_attention_block')
assert m.nonlocal_block.in_channels == 64
for m in model.layer2.modules():
if is_block(m):
assert m.nonlocal_block.in_channels == 128
assert m.gen_attention_block.in_channels == 128
assert m.context_block.in_channels == 512
for m in model.layer3.modules():
if is_block(m):
assert m.nonlocal_block.in_channels == 256
assert m.gen_attention_block.in_channels == 256
assert m.context_block.in_channels == 1024
for m in model.layer4.modules():
if is_block(m):
assert m.nonlocal_block.in_channels == 512
assert m.gen_attention_block.in_channels == 512
assert not hasattr(m, 'context_block')
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50 with 1 ContextBlock after conv2, 1 ContextBlock after
# conv3 in layers 2, 3, 4
plugins = [
dict(
cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=1),
stages=(False, True, True, False),
position='after_conv3'),
dict(
cfg=dict(type='ContextBlock', ratio=1. / 16, postfix=2),
stages=(False, True, True, False),
position='after_conv3')
]
model = ResNet(50, plugins=plugins)
for m in model.layer1.modules():
if is_block(m):
assert not hasattr(m, 'context_block')
assert not hasattr(m, 'context_block1')
assert not hasattr(m, 'context_block2')
for m in model.layer2.modules():
if is_block(m):
assert not hasattr(m, 'context_block')
assert m.context_block1.in_channels == 512
assert m.context_block2.in_channels == 512
for m in model.layer3.modules():
if is_block(m):
assert not hasattr(m, 'context_block')
assert m.context_block1.in_channels == 1024
assert m.context_block2.in_channels == 1024
for m in model.layer4.modules():
if is_block(m):
assert not hasattr(m, 'context_block')
assert not hasattr(m, 'context_block1')
assert not hasattr(m, 'context_block2')
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50 zero initialization of residual
model = ResNet(50, zero_init_residual=True)
model.init_weights()
for m in model.modules():
if isinstance(m, Bottleneck):
assert all_zeros(m.norm3)
elif isinstance(m, BasicBlock):
assert all_zeros(m.norm2)
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNetV1d forward
model = ResNetV1d(depth=50)
model.init_weights()
model.train()
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50 stem_channels
model = ResNet(depth=50, stem_channels=128)
model.init_weights()
model.train()
assert model.conv1.out_channels == 128
assert model.layer1[0].conv1.in_channels == 128
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7])
# Test ResNet50V1d stem_channels
model = ResNetV1d(depth=50, stem_channels=128)
model.init_weights()
model.train()
assert model.stem[0].out_channels == 64
assert model.stem[3].out_channels == 64
assert model.stem[6].out_channels == 128
assert model.layer1[0].conv1.in_channels == 128
imgs = torch.randn(1, 3, 224, 224)
feat = model(imgs)
assert len(feat) == 4
assert feat[0].shape == torch.Size([1, 256, 56, 56])
assert feat[1].shape == torch.Size([1, 512, 28, 28])
assert feat[2].shape == torch.Size([1, 1024, 14, 14])
assert feat[3].shape == torch.Size([1, 2048, 7, 7]) | [
"def",
"test_resnet_backbone",
"(",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"KeyError",
")",
":",
"# ResNet depth should be in [18, 34, 50, 101, 152]",
"ResNet",
"(",
"20",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# In ResNet: 1 <= num_stages <= 4",
"ResNet",
"(",
"50",
",",
"num_stages",
"=",
"0",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# len(stage_with_dcn) == num_stages",
"dcn",
"=",
"dict",
"(",
"type",
"=",
"'DCN'",
",",
"deform_groups",
"=",
"1",
",",
"fallback_on_stride",
"=",
"False",
")",
"ResNet",
"(",
"50",
",",
"dcn",
"=",
"dcn",
",",
"stage_with_dcn",
"=",
"(",
"True",
",",
")",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# len(stage_with_plugin) == num_stages",
"plugins",
"=",
"[",
"dict",
"(",
"cfg",
"=",
"dict",
"(",
"type",
"=",
"'ContextBlock'",
",",
"ratio",
"=",
"1.",
"/",
"16",
")",
",",
"stages",
"=",
"(",
"False",
",",
"True",
",",
"True",
")",
",",
"position",
"=",
"'after_conv3'",
")",
"]",
"ResNet",
"(",
"50",
",",
"plugins",
"=",
"plugins",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# In ResNet: 1 <= num_stages <= 4",
"ResNet",
"(",
"50",
",",
"num_stages",
"=",
"5",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# len(strides) == len(dilations) == num_stages",
"ResNet",
"(",
"50",
",",
"strides",
"=",
"(",
"1",
",",
")",
",",
"dilations",
"=",
"(",
"1",
",",
"1",
")",
",",
"num_stages",
"=",
"3",
")",
"with",
"pytest",
".",
"raises",
"(",
"TypeError",
")",
":",
"# pretrained must be a string path",
"model",
"=",
"ResNet",
"(",
"50",
")",
"model",
".",
"init_weights",
"(",
"pretrained",
"=",
"0",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# Style must be in ['pytorch', 'caffe']",
"ResNet",
"(",
"50",
",",
"style",
"=",
"'tensorflow'",
")",
"# Test ResNet50 norm_eval=True",
"model",
"=",
"ResNet",
"(",
"50",
",",
"norm_eval",
"=",
"True",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"assert",
"check_norm_state",
"(",
"model",
".",
"modules",
"(",
")",
",",
"False",
")",
"# Test ResNet50 with torchvision pretrained weight",
"model",
"=",
"ResNet",
"(",
"depth",
"=",
"50",
",",
"norm_eval",
"=",
"True",
")",
"model",
".",
"init_weights",
"(",
"'torchvision://resnet50'",
")",
"model",
".",
"train",
"(",
")",
"assert",
"check_norm_state",
"(",
"model",
".",
"modules",
"(",
")",
",",
"False",
")",
"# Test ResNet50 with first stage frozen",
"frozen_stages",
"=",
"1",
"model",
"=",
"ResNet",
"(",
"50",
",",
"frozen_stages",
"=",
"frozen_stages",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"assert",
"model",
".",
"norm1",
".",
"training",
"is",
"False",
"for",
"layer",
"in",
"[",
"model",
".",
"conv1",
",",
"model",
".",
"norm1",
"]",
":",
"for",
"param",
"in",
"layer",
".",
"parameters",
"(",
")",
":",
"assert",
"param",
".",
"requires_grad",
"is",
"False",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"frozen_stages",
"+",
"1",
")",
":",
"layer",
"=",
"getattr",
"(",
"model",
",",
"f'layer{i}'",
")",
"for",
"mod",
"in",
"layer",
".",
"modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"mod",
",",
"_BatchNorm",
")",
":",
"assert",
"mod",
".",
"training",
"is",
"False",
"for",
"param",
"in",
"layer",
".",
"parameters",
"(",
")",
":",
"assert",
"param",
".",
"requires_grad",
"is",
"False",
"# Test ResNet50V1d with first stage frozen",
"model",
"=",
"ResNetV1d",
"(",
"depth",
"=",
"50",
",",
"frozen_stages",
"=",
"frozen_stages",
")",
"assert",
"len",
"(",
"model",
".",
"stem",
")",
"==",
"9",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"check_norm_state",
"(",
"model",
".",
"stem",
",",
"False",
")",
"for",
"param",
"in",
"model",
".",
"stem",
".",
"parameters",
"(",
")",
":",
"assert",
"param",
".",
"requires_grad",
"is",
"False",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"frozen_stages",
"+",
"1",
")",
":",
"layer",
"=",
"getattr",
"(",
"model",
",",
"f'layer{i}'",
")",
"for",
"mod",
"in",
"layer",
".",
"modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"mod",
",",
"_BatchNorm",
")",
":",
"assert",
"mod",
".",
"training",
"is",
"False",
"for",
"param",
"in",
"layer",
".",
"parameters",
"(",
")",
":",
"assert",
"param",
".",
"requires_grad",
"is",
"False",
"# Test ResNet18 forward",
"model",
"=",
"ResNet",
"(",
"18",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"64",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"128",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet18 with checkpoint forward",
"model",
"=",
"ResNet",
"(",
"18",
",",
"with_cp",
"=",
"True",
")",
"for",
"m",
"in",
"model",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"m",
".",
"with_cp",
"# Test ResNet50 with BatchNorm forward",
"model",
"=",
"ResNet",
"(",
"50",
")",
"for",
"m",
"in",
"model",
".",
"modules",
"(",
")",
":",
"if",
"is_norm",
"(",
"m",
")",
":",
"assert",
"isinstance",
"(",
"m",
",",
"_BatchNorm",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50 with layers 1, 2, 3 out forward",
"model",
"=",
"ResNet",
"(",
"50",
",",
"out_indices",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"3",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"# Test ResNet50 with checkpoint forward",
"model",
"=",
"ResNet",
"(",
"50",
",",
"with_cp",
"=",
"True",
")",
"for",
"m",
"in",
"model",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"m",
".",
"with_cp",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50 with GroupNorm forward",
"model",
"=",
"ResNet",
"(",
"50",
",",
"norm_cfg",
"=",
"dict",
"(",
"type",
"=",
"'GN'",
",",
"num_groups",
"=",
"32",
",",
"requires_grad",
"=",
"True",
")",
")",
"for",
"m",
"in",
"model",
".",
"modules",
"(",
")",
":",
"if",
"is_norm",
"(",
"m",
")",
":",
"assert",
"isinstance",
"(",
"m",
",",
"GroupNorm",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50 with 1 GeneralizedAttention after conv2, 1 NonLocal2D",
"# after conv2, 1 ContextBlock after conv3 in layers 2, 3, 4",
"plugins",
"=",
"[",
"dict",
"(",
"cfg",
"=",
"dict",
"(",
"type",
"=",
"'GeneralizedAttention'",
",",
"spatial_range",
"=",
"-",
"1",
",",
"num_heads",
"=",
"8",
",",
"attention_type",
"=",
"'0010'",
",",
"kv_stride",
"=",
"2",
")",
",",
"stages",
"=",
"(",
"False",
",",
"True",
",",
"True",
",",
"True",
")",
",",
"position",
"=",
"'after_conv2'",
")",
",",
"dict",
"(",
"cfg",
"=",
"dict",
"(",
"type",
"=",
"'NonLocal2d'",
")",
",",
"position",
"=",
"'after_conv2'",
")",
",",
"dict",
"(",
"cfg",
"=",
"dict",
"(",
"type",
"=",
"'ContextBlock'",
",",
"ratio",
"=",
"1.",
"/",
"16",
")",
",",
"stages",
"=",
"(",
"False",
",",
"True",
",",
"True",
",",
"False",
")",
",",
"position",
"=",
"'after_conv3'",
")",
"]",
"model",
"=",
"ResNet",
"(",
"50",
",",
"plugins",
"=",
"plugins",
")",
"for",
"m",
"in",
"model",
".",
"layer1",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block'",
")",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'gen_attention_block'",
")",
"assert",
"m",
".",
"nonlocal_block",
".",
"in_channels",
"==",
"64",
"for",
"m",
"in",
"model",
".",
"layer2",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"m",
".",
"nonlocal_block",
".",
"in_channels",
"==",
"128",
"assert",
"m",
".",
"gen_attention_block",
".",
"in_channels",
"==",
"128",
"assert",
"m",
".",
"context_block",
".",
"in_channels",
"==",
"512",
"for",
"m",
"in",
"model",
".",
"layer3",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"m",
".",
"nonlocal_block",
".",
"in_channels",
"==",
"256",
"assert",
"m",
".",
"gen_attention_block",
".",
"in_channels",
"==",
"256",
"assert",
"m",
".",
"context_block",
".",
"in_channels",
"==",
"1024",
"for",
"m",
"in",
"model",
".",
"layer4",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"m",
".",
"nonlocal_block",
".",
"in_channels",
"==",
"512",
"assert",
"m",
".",
"gen_attention_block",
".",
"in_channels",
"==",
"512",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block'",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50 with 1 ContextBlock after conv2, 1 ContextBlock after",
"# conv3 in layers 2, 3, 4",
"plugins",
"=",
"[",
"dict",
"(",
"cfg",
"=",
"dict",
"(",
"type",
"=",
"'ContextBlock'",
",",
"ratio",
"=",
"1.",
"/",
"16",
",",
"postfix",
"=",
"1",
")",
",",
"stages",
"=",
"(",
"False",
",",
"True",
",",
"True",
",",
"False",
")",
",",
"position",
"=",
"'after_conv3'",
")",
",",
"dict",
"(",
"cfg",
"=",
"dict",
"(",
"type",
"=",
"'ContextBlock'",
",",
"ratio",
"=",
"1.",
"/",
"16",
",",
"postfix",
"=",
"2",
")",
",",
"stages",
"=",
"(",
"False",
",",
"True",
",",
"True",
",",
"False",
")",
",",
"position",
"=",
"'after_conv3'",
")",
"]",
"model",
"=",
"ResNet",
"(",
"50",
",",
"plugins",
"=",
"plugins",
")",
"for",
"m",
"in",
"model",
".",
"layer1",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block'",
")",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block1'",
")",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block2'",
")",
"for",
"m",
"in",
"model",
".",
"layer2",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block'",
")",
"assert",
"m",
".",
"context_block1",
".",
"in_channels",
"==",
"512",
"assert",
"m",
".",
"context_block2",
".",
"in_channels",
"==",
"512",
"for",
"m",
"in",
"model",
".",
"layer3",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block'",
")",
"assert",
"m",
".",
"context_block1",
".",
"in_channels",
"==",
"1024",
"assert",
"m",
".",
"context_block2",
".",
"in_channels",
"==",
"1024",
"for",
"m",
"in",
"model",
".",
"layer4",
".",
"modules",
"(",
")",
":",
"if",
"is_block",
"(",
"m",
")",
":",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block'",
")",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block1'",
")",
"assert",
"not",
"hasattr",
"(",
"m",
",",
"'context_block2'",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50 zero initialization of residual",
"model",
"=",
"ResNet",
"(",
"50",
",",
"zero_init_residual",
"=",
"True",
")",
"model",
".",
"init_weights",
"(",
")",
"for",
"m",
"in",
"model",
".",
"modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"m",
",",
"Bottleneck",
")",
":",
"assert",
"all_zeros",
"(",
"m",
".",
"norm3",
")",
"elif",
"isinstance",
"(",
"m",
",",
"BasicBlock",
")",
":",
"assert",
"all_zeros",
"(",
"m",
".",
"norm2",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNetV1d forward",
"model",
"=",
"ResNetV1d",
"(",
"depth",
"=",
"50",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50 stem_channels",
"model",
"=",
"ResNet",
"(",
"depth",
"=",
"50",
",",
"stem_channels",
"=",
"128",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"assert",
"model",
".",
"conv1",
".",
"out_channels",
"==",
"128",
"assert",
"model",
".",
"layer1",
"[",
"0",
"]",
".",
"conv1",
".",
"in_channels",
"==",
"128",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")",
"# Test ResNet50V1d stem_channels",
"model",
"=",
"ResNetV1d",
"(",
"depth",
"=",
"50",
",",
"stem_channels",
"=",
"128",
")",
"model",
".",
"init_weights",
"(",
")",
"model",
".",
"train",
"(",
")",
"assert",
"model",
".",
"stem",
"[",
"0",
"]",
".",
"out_channels",
"==",
"64",
"assert",
"model",
".",
"stem",
"[",
"3",
"]",
".",
"out_channels",
"==",
"64",
"assert",
"model",
".",
"stem",
"[",
"6",
"]",
".",
"out_channels",
"==",
"128",
"assert",
"model",
".",
"layer1",
"[",
"0",
"]",
".",
"conv1",
".",
"in_channels",
"==",
"128",
"imgs",
"=",
"torch",
".",
"randn",
"(",
"1",
",",
"3",
",",
"224",
",",
"224",
")",
"feat",
"=",
"model",
"(",
"imgs",
")",
"assert",
"len",
"(",
"feat",
")",
"==",
"4",
"assert",
"feat",
"[",
"0",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"256",
",",
"56",
",",
"56",
"]",
")",
"assert",
"feat",
"[",
"1",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"512",
",",
"28",
",",
"28",
"]",
")",
"assert",
"feat",
"[",
"2",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"1024",
",",
"14",
",",
"14",
"]",
")",
"assert",
"feat",
"[",
"3",
"]",
".",
"shape",
"==",
"torch",
".",
"Size",
"(",
"[",
"1",
",",
"2048",
",",
"7",
",",
"7",
"]",
")"
] | [
291,
0
] | [
618,
55
] | python | en | ['nl', 'no', 'en'] | False |
Font.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
63,
28
] | python | en | ['en', 'error', 'th'] | False |
Font.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
72,
4
] | [
94,
29
] | python | en | ['en', 'error', 'th'] | False |
Font.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf] | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
103,
4
] | [
112,
27
] | python | en | ['en', 'error', 'th'] | False |
Font.__init__ | (self, arg=None, color=None, family=None, size=None, **kwargs) |
Construct a new Font object
Sets this color bar's title font. Note that the title's font
used to be set by the now deprecated `titlefont` attribute.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.colorax
is.colorbar.title.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Font
|
Construct a new Font object
Sets this color bar's title font. Note that the title's font
used to be set by the now deprecated `titlefont` attribute. | def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Font object
Sets this color bar's title font. Note that the title's font
used to be set by the now deprecated `titlefont` attribute.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.colorax
is.colorbar.title.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.coloraxis.colorbar.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.coloraxis.colorbar.title.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"family",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Font",
",",
"self",
")",
".",
"__init__",
"(",
"\"font\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.layout.coloraxis.colorbar.title.Font \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.coloraxis.colorbar.title.Font`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
143,
4
] | [
227,
34
] | python | en | ['en', 'error', 'th'] | False |
TestParlaiParser.test_shortopt | (self) |
Tests whether short opts like -mtw work.
Known to be tricky in python 3.8.
|
Tests whether short opts like -mtw work. | def test_shortopt(self):
"""
Tests whether short opts like -mtw work.
Known to be tricky in python 3.8.
"""
pp = ParlaiParser(False, False)
pp.add_argument("-m", "--model")
pp.add_argument("-mtw", "--multitask-weights")
opt = pp.parse_args(["-m", "memnn"])
print(opt) | [
"def",
"test_shortopt",
"(",
"self",
")",
":",
"pp",
"=",
"ParlaiParser",
"(",
"False",
",",
"False",
")",
"pp",
".",
"add_argument",
"(",
"\"-m\"",
",",
"\"--model\"",
")",
"pp",
".",
"add_argument",
"(",
"\"-mtw\"",
",",
"\"--multitask-weights\"",
")",
"opt",
"=",
"pp",
".",
"parse_args",
"(",
"[",
"\"-m\"",
",",
"\"memnn\"",
"]",
")",
"print",
"(",
"opt",
")"
] | [
37,
4
] | [
47,
18
] | python | en | ['en', 'error', 'th'] | False |
TestParlaiParser.test_upgrade_opt | (self) |
Test whether upgrade_opt works.
|
Test whether upgrade_opt works.
| def test_upgrade_opt(self):
"""
Test whether upgrade_opt works.
"""
with testing_utils.tempdir() as tmp:
modfn = os.path.join(tmp, 'model')
with open(modfn, 'w') as f:
f.write('Test.')
optfn = modfn + '.opt'
base_opt = {
'model': 'tests.test_params:_ExampleUpgradeOptAgent',
'dict_file': modfn + '.dict',
'model_file': modfn,
}
with open(optfn, 'w') as f:
json.dump(base_opt, f)
pp = ParlaiParser(True, True)
opt = pp.parse_args(['--model-file', modfn])
agents.create_agent(opt) | [
"def",
"test_upgrade_opt",
"(",
"self",
")",
":",
"with",
"testing_utils",
".",
"tempdir",
"(",
")",
"as",
"tmp",
":",
"modfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp",
",",
"'model'",
")",
"with",
"open",
"(",
"modfn",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'Test.'",
")",
"optfn",
"=",
"modfn",
"+",
"'.opt'",
"base_opt",
"=",
"{",
"'model'",
":",
"'tests.test_params:_ExampleUpgradeOptAgent'",
",",
"'dict_file'",
":",
"modfn",
"+",
"'.dict'",
",",
"'model_file'",
":",
"modfn",
",",
"}",
"with",
"open",
"(",
"optfn",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"base_opt",
",",
"f",
")",
"pp",
"=",
"ParlaiParser",
"(",
"True",
",",
"True",
")",
"opt",
"=",
"pp",
".",
"parse_args",
"(",
"[",
"'--model-file'",
",",
"modfn",
"]",
")",
"agents",
".",
"create_agent",
"(",
"opt",
")"
] | [
49,
4
] | [
68,
36
] | python | en | ['en', 'error', 'th'] | False |
TestParlaiParser.test_recommendations_single | (self) |
Test whether recommended args work for non-group.
|
Test whether recommended args work for non-group.
| def test_recommendations_single(self):
"""
Test whether recommended args work for non-group.
"""
parser = ParlaiParser(False, False)
parser.add_argument(
'-bs',
'--batchsize',
default=1,
type=int,
help='batch size for minibatch training schemes',
recommended=1337,
)
parser.parse_args([])
help_str = parser.format_help()
assert 'recommended:' in help_str
assert '1337' in help_str | [
"def",
"test_recommendations_single",
"(",
"self",
")",
":",
"parser",
"=",
"ParlaiParser",
"(",
"False",
",",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-bs'",
",",
"'--batchsize'",
",",
"default",
"=",
"1",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'batch size for minibatch training schemes'",
",",
"recommended",
"=",
"1337",
",",
")",
"parser",
".",
"parse_args",
"(",
"[",
"]",
")",
"help_str",
"=",
"parser",
".",
"format_help",
"(",
")",
"assert",
"'recommended:'",
"in",
"help_str",
"assert",
"'1337'",
"in",
"help_str"
] | [
70,
4
] | [
86,
33
] | python | en | ['en', 'error', 'th'] | False |
TestParlaiParser.test_recommendations_group | (self) |
Test whether recommended args work for a group.
|
Test whether recommended args work for a group.
| def test_recommendations_group(self):
"""
Test whether recommended args work for a group.
"""
parser = ParlaiParser(False, False)
parser_grp = parser.add_argument_group('Test Group')
parser_grp.add_argument(
'-bs',
'--batchsize',
default=1,
type=int,
help='batch size for minibatch training schemes',
recommended=1337,
)
parser.parse_args([])
help_str = parser.format_help()
assert 'Test Group' in help_str
_, latter = help_str.split('Test Group')
assert 'recommended:' in latter
assert '1337' in latter | [
"def",
"test_recommendations_group",
"(",
"self",
")",
":",
"parser",
"=",
"ParlaiParser",
"(",
"False",
",",
"False",
")",
"parser_grp",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Test Group'",
")",
"parser_grp",
".",
"add_argument",
"(",
"'-bs'",
",",
"'--batchsize'",
",",
"default",
"=",
"1",
",",
"type",
"=",
"int",
",",
"help",
"=",
"'batch size for minibatch training schemes'",
",",
"recommended",
"=",
"1337",
",",
")",
"parser",
".",
"parse_args",
"(",
"[",
"]",
")",
"help_str",
"=",
"parser",
".",
"format_help",
"(",
")",
"assert",
"'Test Group'",
"in",
"help_str",
"_",
",",
"latter",
"=",
"help_str",
".",
"split",
"(",
"'Test Group'",
")",
"assert",
"'recommended:'",
"in",
"latter",
"assert",
"'1337'",
"in",
"latter"
] | [
88,
4
] | [
108,
31
] | python | en | ['en', 'error', 'th'] | False |
TestParlaiParser.test_bool | (self) |
test add_argument(type=bool)
|
test add_argument(type=bool)
| def test_bool(self):
"""
test add_argument(type=bool)
"""
parser = ParlaiParser(True, True)
parser.add_argument('--foo', type=bool)
opt = parser.parse_args(['--foo', 'true'])
assert opt['foo'] is True
opt = parser.parse_args(['--foo', 'False'])
assert opt['foo'] is False
opt = parser.parse_args(['--foo', '0'])
assert opt['foo'] is False
group = parser.add_argument_group('foo container')
group.add_argument('--bar', type=bool)
opt = parser.parse_args(['--bar', 'true'])
assert opt['bar'] is True
opt = parser.parse_args(['--bar', 'False'])
assert opt['bar'] is False
opt = parser.parse_args(['--bar', '0'])
assert opt['bar'] is False
parser = ParlaiParser(True, True)
parser.add_argument('--foo', type='bool')
opt = parser.parse_args(['--foo', 'true'])
assert opt['foo'] is True
opt = parser.parse_args(['--foo', 'False'])
assert opt['foo'] is False
opt = parser.parse_args(['--foo', '0'])
assert opt['foo'] is False
group = parser.add_argument_group('foo container')
group.add_argument('--bar', type='bool')
opt = parser.parse_args(['--bar', 'true'])
assert opt['bar'] is True
opt = parser.parse_args(['--bar', 'False'])
assert opt['bar'] is False
opt = parser.parse_args(['--bar', '0'])
assert opt['bar'] is False | [
"def",
"test_bool",
"(",
"self",
")",
":",
"parser",
"=",
"ParlaiParser",
"(",
"True",
",",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--foo'",
",",
"type",
"=",
"bool",
")",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--foo'",
",",
"'true'",
"]",
")",
"assert",
"opt",
"[",
"'foo'",
"]",
"is",
"True",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--foo'",
",",
"'False'",
"]",
")",
"assert",
"opt",
"[",
"'foo'",
"]",
"is",
"False",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--foo'",
",",
"'0'",
"]",
")",
"assert",
"opt",
"[",
"'foo'",
"]",
"is",
"False",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'foo container'",
")",
"group",
".",
"add_argument",
"(",
"'--bar'",
",",
"type",
"=",
"bool",
")",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--bar'",
",",
"'true'",
"]",
")",
"assert",
"opt",
"[",
"'bar'",
"]",
"is",
"True",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--bar'",
",",
"'False'",
"]",
")",
"assert",
"opt",
"[",
"'bar'",
"]",
"is",
"False",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--bar'",
",",
"'0'",
"]",
")",
"assert",
"opt",
"[",
"'bar'",
"]",
"is",
"False",
"parser",
"=",
"ParlaiParser",
"(",
"True",
",",
"True",
")",
"parser",
".",
"add_argument",
"(",
"'--foo'",
",",
"type",
"=",
"'bool'",
")",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--foo'",
",",
"'true'",
"]",
")",
"assert",
"opt",
"[",
"'foo'",
"]",
"is",
"True",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--foo'",
",",
"'False'",
"]",
")",
"assert",
"opt",
"[",
"'foo'",
"]",
"is",
"False",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--foo'",
",",
"'0'",
"]",
")",
"assert",
"opt",
"[",
"'foo'",
"]",
"is",
"False",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'foo container'",
")",
"group",
".",
"add_argument",
"(",
"'--bar'",
",",
"type",
"=",
"'bool'",
")",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--bar'",
",",
"'true'",
"]",
")",
"assert",
"opt",
"[",
"'bar'",
"]",
"is",
"True",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--bar'",
",",
"'False'",
"]",
")",
"assert",
"opt",
"[",
"'bar'",
"]",
"is",
"False",
"opt",
"=",
"parser",
".",
"parse_args",
"(",
"[",
"'--bar'",
",",
"'0'",
"]",
")",
"assert",
"opt",
"[",
"'bar'",
"]",
"is",
"False"
] | [
134,
4
] | [
172,
34
] | python | en | ['en', 'error', 'th'] | False |
CredentialOffer.__init__ | (
self,
_id: str = None,
*,
comment: str = None,
credential_preview: CredentialPreview = None,
offers_attach: Sequence[AttachDecorator] = None,
**kwargs,
) |
Initialize credential offer object.
Args:
comment: optional human-readable comment
credential_preview: credential preview
offers_attach: list of offer attachments
|
Initialize credential offer object. | def __init__(
self,
_id: str = None,
*,
comment: str = None,
credential_preview: CredentialPreview = None,
offers_attach: Sequence[AttachDecorator] = None,
**kwargs,
):
"""
Initialize credential offer object.
Args:
comment: optional human-readable comment
credential_preview: credential preview
offers_attach: list of offer attachments
"""
super().__init__(_id=_id, **kwargs)
self.comment = comment
self.credential_preview = (
credential_preview if credential_preview else CredentialPreview()
)
self.offers_attach = list(offers_attach) if offers_attach else [] | [
"def",
"__init__",
"(",
"self",
",",
"_id",
":",
"str",
"=",
"None",
",",
"*",
",",
"comment",
":",
"str",
"=",
"None",
",",
"credential_preview",
":",
"CredentialPreview",
"=",
"None",
",",
"offers_attach",
":",
"Sequence",
"[",
"AttachDecorator",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"_id",
"=",
"_id",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"comment",
"=",
"comment",
"self",
".",
"credential_preview",
"=",
"(",
"credential_preview",
"if",
"credential_preview",
"else",
"CredentialPreview",
"(",
")",
")",
"self",
".",
"offers_attach",
"=",
"list",
"(",
"offers_attach",
")",
"if",
"offers_attach",
"else",
"[",
"]"
] | [
31,
4
] | [
54,
73
] | python | en | ['en', 'error', 'th'] | False |
CredentialOffer.indy_offer | (self, index: int = 0) |
Retrieve and decode indy offer from attachment.
Args:
index: ordinal in attachment list to decode and return
(typically, list has length 1)
|
Retrieve and decode indy offer from attachment. | def indy_offer(self, index: int = 0) -> dict:
"""
Retrieve and decode indy offer from attachment.
Args:
index: ordinal in attachment list to decode and return
(typically, list has length 1)
"""
return self.offers_attach[index].indy_dict | [
"def",
"indy_offer",
"(",
"self",
",",
"index",
":",
"int",
"=",
"0",
")",
"->",
"dict",
":",
"return",
"self",
".",
"offers_attach",
"[",
"index",
"]",
".",
"indy_dict"
] | [
56,
4
] | [
65,
50
] | python | en | ['en', 'error', 'th'] | False |
CredentialOffer.wrap_indy_offer | (cls, indy_offer: dict) | Convert an indy credential offer to an attachment decorator. | Convert an indy credential offer to an attachment decorator. | def wrap_indy_offer(cls, indy_offer: dict) -> AttachDecorator:
"""Convert an indy credential offer to an attachment decorator."""
return AttachDecorator.from_indy_dict(
indy_dict=indy_offer, ident=ATTACH_DECO_IDS[CREDENTIAL_OFFER]
) | [
"def",
"wrap_indy_offer",
"(",
"cls",
",",
"indy_offer",
":",
"dict",
")",
"->",
"AttachDecorator",
":",
"return",
"AttachDecorator",
".",
"from_indy_dict",
"(",
"indy_dict",
"=",
"indy_offer",
",",
"ident",
"=",
"ATTACH_DECO_IDS",
"[",
"CREDENTIAL_OFFER",
"]",
")"
] | [
68,
4
] | [
72,
9
] | python | en | ['en', 'en', 'en'] | True |
_Abstract._h | (self, x) |
Hash function.
|
Hash function.
| def _h(self, x):
"""
Hash function.
"""
h = int(hashlib.sha1(x.encode('utf-8')).hexdigest(), 16) % 10
if h == 0:
return 'valid'
elif h == 1:
return 'test'
else:
return 'train' | [
"def",
"_h",
"(",
"self",
",",
"x",
")",
":",
"h",
"=",
"int",
"(",
"hashlib",
".",
"sha1",
"(",
"x",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"16",
")",
"%",
"10",
"if",
"h",
"==",
"0",
":",
"return",
"'valid'",
"elif",
"h",
"==",
"1",
":",
"return",
"'test'",
"else",
":",
"return",
"'train'"
] | [
75,
4
] | [
85,
26
] | python | en | ['en', 'error', 'th'] | False |
Rotation.lat | (self) |
Rotates the map along meridians (in degrees North).
The 'lat' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Rotates the map along meridians (in degrees North).
The 'lat' property is a number and may be specified as:
- An int or float | def lat(self):
"""
Rotates the map along meridians (in degrees North).
The 'lat' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["lat"] | [
"def",
"lat",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"lat\"",
"]"
] | [
15,
4
] | [
26,
26
] | python | en | ['en', 'error', 'th'] | False |
Rotation.lon | (self) |
Rotates the map along parallels (in degrees East). Defaults to
the center of the `lonaxis.range` values.
The 'lon' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Rotates the map along parallels (in degrees East). Defaults to
the center of the `lonaxis.range` values.
The 'lon' property is a number and may be specified as:
- An int or float | def lon(self):
"""
Rotates the map along parallels (in degrees East). Defaults to
the center of the `lonaxis.range` values.
The 'lon' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["lon"] | [
"def",
"lon",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"lon\"",
"]"
] | [
35,
4
] | [
47,
26
] | python | en | ['en', 'error', 'th'] | False |
Rotation.roll | (self) |
Roll the map (in degrees) For example, a roll of 180 makes the
map appear upside down.
The 'roll' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
|
Roll the map (in degrees) For example, a roll of 180 makes the
map appear upside down.
The 'roll' property is a number and may be specified as:
- An int or float | def roll(self):
"""
Roll the map (in degrees) For example, a roll of 180 makes the
map appear upside down.
The 'roll' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["roll"] | [
"def",
"roll",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"roll\"",
"]"
] | [
56,
4
] | [
68,
27
] | python | en | ['en', 'error', 'th'] | False |
Rotation.__init__ | (self, arg=None, lat=None, lon=None, roll=None, **kwargs) |
Construct a new Rotation object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.geo.pro
jection.Rotation`
lat
Rotates the map along meridians (in degrees North).
lon
Rotates the map along parallels (in degrees East).
Defaults to the center of the `lonaxis.range` values.
roll
Roll the map (in degrees) For example, a roll of 180
makes the map appear upside down.
Returns
-------
Rotation
|
Construct a new Rotation object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.geo.pro
jection.Rotation`
lat
Rotates the map along meridians (in degrees North).
lon
Rotates the map along parallels (in degrees East).
Defaults to the center of the `lonaxis.range` values.
roll
Roll the map (in degrees) For example, a roll of 180
makes the map appear upside down. | def __init__(self, arg=None, lat=None, lon=None, roll=None, **kwargs):
"""
Construct a new Rotation object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.geo.pro
jection.Rotation`
lat
Rotates the map along meridians (in degrees North).
lon
Rotates the map along parallels (in degrees East).
Defaults to the center of the `lonaxis.range` values.
roll
Roll the map (in degrees) For example, a roll of 180
makes the map appear upside down.
Returns
-------
Rotation
"""
super(Rotation, self).__init__("rotation")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.geo.projection.Rotation
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.geo.projection.Rotation`"""
)
# 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("lat", None)
_v = lat if lat is not None else _v
if _v is not None:
self["lat"] = _v
_v = arg.pop("lon", None)
_v = lon if lon is not None else _v
if _v is not None:
self["lon"] = _v
_v = arg.pop("roll", None)
_v = roll if roll is not None else _v
if _v is not None:
self["roll"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"lon",
"=",
"None",
",",
"roll",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Rotation",
",",
"self",
")",
".",
"__init__",
"(",
"\"rotation\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.layout.geo.projection.Rotation \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.geo.projection.Rotation`\"\"\"",
")",
"# 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",
"(",
"\"lat\"",
",",
"None",
")",
"_v",
"=",
"lat",
"if",
"lat",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"lat\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"lon\"",
",",
"None",
")",
"_v",
"=",
"lon",
"if",
"lon",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"lon\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"roll\"",
",",
"None",
")",
"_v",
"=",
"roll",
"if",
"roll",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"roll\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
89,
4
] | [
160,
34
] | python | en | ['en', 'error', 'th'] | False |
list_of_options | (iterable, conj="and", period=True) |
Returns an English listing of objects seperated by commas ','
For example, ['foo', 'bar', 'baz'] becomes 'foo, bar and baz'
if the conjunction 'and' is selected.
|
Returns an English listing of objects seperated by commas ',' | def list_of_options(iterable, conj="and", period=True):
"""
Returns an English listing of objects seperated by commas ','
For example, ['foo', 'bar', 'baz'] becomes 'foo, bar and baz'
if the conjunction 'and' is selected.
"""
if len(iterable) < 2:
raise _plotly_utils.exceptions.PlotlyError(
"Your list or tuple must contain at least 2 items."
)
template = (len(iterable) - 2) * "{}, " + "{} " + conj + " {}" + period * "."
return template.format(*iterable) | [
"def",
"list_of_options",
"(",
"iterable",
",",
"conj",
"=",
"\"and\"",
",",
"period",
"=",
"True",
")",
":",
"if",
"len",
"(",
"iterable",
")",
"<",
"2",
":",
"raise",
"_plotly_utils",
".",
"exceptions",
".",
"PlotlyError",
"(",
"\"Your list or tuple must contain at least 2 items.\"",
")",
"template",
"=",
"(",
"len",
"(",
"iterable",
")",
"-",
"2",
")",
"*",
"\"{}, \"",
"+",
"\"{} \"",
"+",
"conj",
"+",
"\" {}\"",
"+",
"period",
"*",
"\".\"",
"return",
"template",
".",
"format",
"(",
"*",
"iterable",
")"
] | [
72,
0
] | [
84,
37
] | python | en | ['en', 'error', 'th'] | False |
build | (opt) |
Create train and validation data for synthetic shapes described by attributes.
|
Create train and validation data for synthetic shapes described by attributes.
| def build(opt):
"""
Create train and validation data for synthetic shapes described by attributes.
"""
dpath = os.path.join(opt['datapath'], 'taskntalk')
if not build_data.built(dpath):
print('[building data: ' + dpath + ']')
build_data.make_dir(os.path.join(dpath, 'large'))
build_data.make_dir(os.path.join(dpath, 'small'))
# save training and validation data
to_save = {
'attributes': ['color', 'shape', 'style'],
'task_defn': [
['color', 'shape'],
['shape', 'color'],
['color', 'style'],
['style', 'color'],
['shape', 'style'],
['style', 'shape'],
],
}
split_data = {}
# small dataset properties
properties = {
'color': ['red', 'green', 'blue', 'purple'],
'shape': ['square', 'triangle', 'circle', 'star'],
'style': ['dotted', 'solid', 'filled', 'dashed'],
}
to_save['properties'] = properties
# properties.values() not used directly to maintain order
data_verbose = list(
itertools.product(*[properties[key] for key in to_save['attributes']])
)
# randomly select train and rest of it is valid
split_data['valid'] = random.sample(data_verbose, int(0.2 * len(data_verbose)))
split_data['train'] = [s for s in data_verbose if s not in split_data['valid']]
to_save['data'] = split_data['train']
with PathManager.open(
os.path.join(dpath, 'small', 'train.json'), 'w'
) as outfile:
json.dump(
to_save, outfile, indent=4, separators=(',', ': '), sort_keys=True
)
to_save['data'] = split_data['valid']
with PathManager.open(
os.path.join(dpath, 'small', 'valid.json'), 'w'
) as outfile:
json.dump(
to_save, outfile, indent=4, separators=(',', ': '), sort_keys=True
)
# large dataset properties
properties = {
'color': [
'red',
'green',
'blue',
'purple',
'yellow',
'cyan',
'orange',
'teal',
],
'shape': [
'square',
'triangle',
'circle',
'star',
'heart',
'spade',
'club',
'diamond',
],
'style': [
'dotted',
'solid',
'filled',
'dashed',
'hstripe',
'vstripe',
'hgrad',
'vgrad',
],
}
to_save['properties'] = properties
data_verbose = list(
itertools.product(*[properties[key] for key in to_save['attributes']])
)
split_data['valid'] = random.sample(data_verbose, int(0.8 * len(data_verbose)))
split_data['train'] = [s for s in data_verbose if s not in split_data['valid']]
to_save['data'] = split_data['train']
with PathManager.open(
os.path.join(dpath, 'large', 'train.json'), 'w'
) as outfile:
json.dump(
to_save, outfile, indent=4, separators=(',', ': '), sort_keys=True
)
to_save['data'] = split_data['valid']
with PathManager.open(
os.path.join(dpath, 'large', 'valid.json'), 'w'
) as outfile:
json.dump(
to_save, outfile, indent=4, separators=(',', ': '), sort_keys=True
)
# Mark the data as built.
build_data.mark_done(dpath) | [
"def",
"build",
"(",
"opt",
")",
":",
"dpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"opt",
"[",
"'datapath'",
"]",
",",
"'taskntalk'",
")",
"if",
"not",
"build_data",
".",
"built",
"(",
"dpath",
")",
":",
"print",
"(",
"'[building data: '",
"+",
"dpath",
"+",
"']'",
")",
"build_data",
".",
"make_dir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dpath",
",",
"'large'",
")",
")",
"build_data",
".",
"make_dir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dpath",
",",
"'small'",
")",
")",
"# save training and validation data",
"to_save",
"=",
"{",
"'attributes'",
":",
"[",
"'color'",
",",
"'shape'",
",",
"'style'",
"]",
",",
"'task_defn'",
":",
"[",
"[",
"'color'",
",",
"'shape'",
"]",
",",
"[",
"'shape'",
",",
"'color'",
"]",
",",
"[",
"'color'",
",",
"'style'",
"]",
",",
"[",
"'style'",
",",
"'color'",
"]",
",",
"[",
"'shape'",
",",
"'style'",
"]",
",",
"[",
"'style'",
",",
"'shape'",
"]",
",",
"]",
",",
"}",
"split_data",
"=",
"{",
"}",
"# small dataset properties",
"properties",
"=",
"{",
"'color'",
":",
"[",
"'red'",
",",
"'green'",
",",
"'blue'",
",",
"'purple'",
"]",
",",
"'shape'",
":",
"[",
"'square'",
",",
"'triangle'",
",",
"'circle'",
",",
"'star'",
"]",
",",
"'style'",
":",
"[",
"'dotted'",
",",
"'solid'",
",",
"'filled'",
",",
"'dashed'",
"]",
",",
"}",
"to_save",
"[",
"'properties'",
"]",
"=",
"properties",
"# properties.values() not used directly to maintain order",
"data_verbose",
"=",
"list",
"(",
"itertools",
".",
"product",
"(",
"*",
"[",
"properties",
"[",
"key",
"]",
"for",
"key",
"in",
"to_save",
"[",
"'attributes'",
"]",
"]",
")",
")",
"# randomly select train and rest of it is valid",
"split_data",
"[",
"'valid'",
"]",
"=",
"random",
".",
"sample",
"(",
"data_verbose",
",",
"int",
"(",
"0.2",
"*",
"len",
"(",
"data_verbose",
")",
")",
")",
"split_data",
"[",
"'train'",
"]",
"=",
"[",
"s",
"for",
"s",
"in",
"data_verbose",
"if",
"s",
"not",
"in",
"split_data",
"[",
"'valid'",
"]",
"]",
"to_save",
"[",
"'data'",
"]",
"=",
"split_data",
"[",
"'train'",
"]",
"with",
"PathManager",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dpath",
",",
"'small'",
",",
"'train.json'",
")",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"to_save",
",",
"outfile",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
"=",
"True",
")",
"to_save",
"[",
"'data'",
"]",
"=",
"split_data",
"[",
"'valid'",
"]",
"with",
"PathManager",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dpath",
",",
"'small'",
",",
"'valid.json'",
")",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"to_save",
",",
"outfile",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
"=",
"True",
")",
"# large dataset properties",
"properties",
"=",
"{",
"'color'",
":",
"[",
"'red'",
",",
"'green'",
",",
"'blue'",
",",
"'purple'",
",",
"'yellow'",
",",
"'cyan'",
",",
"'orange'",
",",
"'teal'",
",",
"]",
",",
"'shape'",
":",
"[",
"'square'",
",",
"'triangle'",
",",
"'circle'",
",",
"'star'",
",",
"'heart'",
",",
"'spade'",
",",
"'club'",
",",
"'diamond'",
",",
"]",
",",
"'style'",
":",
"[",
"'dotted'",
",",
"'solid'",
",",
"'filled'",
",",
"'dashed'",
",",
"'hstripe'",
",",
"'vstripe'",
",",
"'hgrad'",
",",
"'vgrad'",
",",
"]",
",",
"}",
"to_save",
"[",
"'properties'",
"]",
"=",
"properties",
"data_verbose",
"=",
"list",
"(",
"itertools",
".",
"product",
"(",
"*",
"[",
"properties",
"[",
"key",
"]",
"for",
"key",
"in",
"to_save",
"[",
"'attributes'",
"]",
"]",
")",
")",
"split_data",
"[",
"'valid'",
"]",
"=",
"random",
".",
"sample",
"(",
"data_verbose",
",",
"int",
"(",
"0.8",
"*",
"len",
"(",
"data_verbose",
")",
")",
")",
"split_data",
"[",
"'train'",
"]",
"=",
"[",
"s",
"for",
"s",
"in",
"data_verbose",
"if",
"s",
"not",
"in",
"split_data",
"[",
"'valid'",
"]",
"]",
"to_save",
"[",
"'data'",
"]",
"=",
"split_data",
"[",
"'train'",
"]",
"with",
"PathManager",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dpath",
",",
"'large'",
",",
"'train.json'",
")",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"to_save",
",",
"outfile",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
"=",
"True",
")",
"to_save",
"[",
"'data'",
"]",
"=",
"split_data",
"[",
"'valid'",
"]",
"with",
"PathManager",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dpath",
",",
"'large'",
",",
"'valid.json'",
")",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"to_save",
",",
"outfile",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
"=",
"True",
")",
"# Mark the data as built.",
"build_data",
".",
"mark_done",
"(",
"dpath",
")"
] | [
15,
0
] | [
129,
35
] | python | en | ['en', 'error', 'th'] | False |
validate_proof | (result) |
Validates state proof
|
Validates state proof
| def validate_proof(result):
"""
Validates state proof
"""
state_root_hash = result[STATE_PROOF]['root_hash']
state_root_hash = state_roots_serializer.deserialize(state_root_hash)
proof_nodes = result[STATE_PROOF]['proof_nodes']
if isinstance(proof_nodes, str):
proof_nodes = proof_nodes.encode()
proof_nodes = proof_nodes_serializer.deserialize(proof_nodes)
key, value = prepare_for_state(result)
valid = PruningState.verify_state_proof(state_root_hash,
key,
value,
proof_nodes,
serialized=True)
return valid | [
"def",
"validate_proof",
"(",
"result",
")",
":",
"state_root_hash",
"=",
"result",
"[",
"STATE_PROOF",
"]",
"[",
"'root_hash'",
"]",
"state_root_hash",
"=",
"state_roots_serializer",
".",
"deserialize",
"(",
"state_root_hash",
")",
"proof_nodes",
"=",
"result",
"[",
"STATE_PROOF",
"]",
"[",
"'proof_nodes'",
"]",
"if",
"isinstance",
"(",
"proof_nodes",
",",
"str",
")",
":",
"proof_nodes",
"=",
"proof_nodes",
".",
"encode",
"(",
")",
"proof_nodes",
"=",
"proof_nodes_serializer",
".",
"deserialize",
"(",
"proof_nodes",
")",
"key",
",",
"value",
"=",
"prepare_for_state",
"(",
"result",
")",
"valid",
"=",
"PruningState",
".",
"verify_state_proof",
"(",
"state_root_hash",
",",
"key",
",",
"value",
",",
"proof_nodes",
",",
"serialized",
"=",
"True",
")",
"return",
"valid"
] | [
92,
0
] | [
108,
16
] | python | en | ['en', 'error', 'th'] | False |
score_match | (query_rep, text, length_penalty, dictionary=None) |
Calculate the score match between the query representation the text.
:param query_rep:
base query representation to match text again.
:param text:
string to compare against query_rep for matching tokens
:param length_penalty:
scores are divided by the norm taken to this power
:param dictionary:
optional dictionary to use to tokenize text
:returns:
float score of match
|
Calculate the score match between the query representation the text. | def score_match(query_rep, text, length_penalty, dictionary=None):
"""
Calculate the score match between the query representation the text.
:param query_rep:
base query representation to match text again.
:param text:
string to compare against query_rep for matching tokens
:param length_penalty:
scores are divided by the norm taken to this power
:param dictionary:
optional dictionary to use to tokenize text
:returns:
float score of match
"""
if text == "":
return 0
words = [w for w in dictionary.tokenize(text.lower())]
score = 0
rw = query_rep['words']
used = {}
for w in words:
if w in rw and w not in used:
score += rw[w]
used[w] = True
norm = math.sqrt(len(used))
norm = math.pow(norm * query_rep['norm'], length_penalty)
if norm > 1:
score /= norm
return score | [
"def",
"score_match",
"(",
"query_rep",
",",
"text",
",",
"length_penalty",
",",
"dictionary",
"=",
"None",
")",
":",
"if",
"text",
"==",
"\"\"",
":",
"return",
"0",
"words",
"=",
"[",
"w",
"for",
"w",
"in",
"dictionary",
".",
"tokenize",
"(",
"text",
".",
"lower",
"(",
")",
")",
"]",
"score",
"=",
"0",
"rw",
"=",
"query_rep",
"[",
"'words'",
"]",
"used",
"=",
"{",
"}",
"for",
"w",
"in",
"words",
":",
"if",
"w",
"in",
"rw",
"and",
"w",
"not",
"in",
"used",
":",
"score",
"+=",
"rw",
"[",
"w",
"]",
"used",
"[",
"w",
"]",
"=",
"True",
"norm",
"=",
"math",
".",
"sqrt",
"(",
"len",
"(",
"used",
")",
")",
"norm",
"=",
"math",
".",
"pow",
"(",
"norm",
"*",
"query_rep",
"[",
"'norm'",
"]",
",",
"length_penalty",
")",
"if",
"norm",
">",
"1",
":",
"score",
"/=",
"norm",
"return",
"score"
] | [
151,
0
] | [
181,
16
] | python | en | ['en', 'error', 'th'] | False |
rank_candidates | (query_rep, cands, length_penalty, dictionary) |
Rank candidates given representation of query.
:param query_rep:
base query representation to match text again.
:param cands:
strings to compare against query_rep for matching tokens
:param length_penalty:
scores are divided by the norm taken to this power
:dictionary:
dictionary to use to tokenize text
:returns:
ordered list of candidate strings in score-ranked order
|
Rank candidates given representation of query. | def rank_candidates(query_rep, cands, length_penalty, dictionary):
"""
Rank candidates given representation of query.
:param query_rep:
base query representation to match text again.
:param cands:
strings to compare against query_rep for matching tokens
:param length_penalty:
scores are divided by the norm taken to this power
:dictionary:
dictionary to use to tokenize text
:returns:
ordered list of candidate strings in score-ranked order
"""
if True:
mpq = MaxPriorityQueue(100)
for c in cands:
score = score_match(query_rep, c, length_penalty, dictionary)
mpq.add(c, score)
return list(reversed(mpq))
else:
cands = list(cands)
score = [0] * len(cands)
for i, c in enumerate(cands):
score[i] = -score_match(query_rep, c, length_penalty, dictionary)
r = [i[0] for i in sorted(enumerate(score), key=lambda x: x[1])]
res = []
for i in range(min(100, len(score))):
res.append(cands[r[i]])
return res | [
"def",
"rank_candidates",
"(",
"query_rep",
",",
"cands",
",",
"length_penalty",
",",
"dictionary",
")",
":",
"if",
"True",
":",
"mpq",
"=",
"MaxPriorityQueue",
"(",
"100",
")",
"for",
"c",
"in",
"cands",
":",
"score",
"=",
"score_match",
"(",
"query_rep",
",",
"c",
",",
"length_penalty",
",",
"dictionary",
")",
"mpq",
".",
"add",
"(",
"c",
",",
"score",
")",
"return",
"list",
"(",
"reversed",
"(",
"mpq",
")",
")",
"else",
":",
"cands",
"=",
"list",
"(",
"cands",
")",
"score",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"cands",
")",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"cands",
")",
":",
"score",
"[",
"i",
"]",
"=",
"-",
"score_match",
"(",
"query_rep",
",",
"c",
",",
"length_penalty",
",",
"dictionary",
")",
"r",
"=",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"sorted",
"(",
"enumerate",
"(",
"score",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
"]",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"100",
",",
"len",
"(",
"score",
")",
")",
")",
":",
"res",
".",
"append",
"(",
"cands",
"[",
"r",
"[",
"i",
"]",
"]",
")",
"return",
"res"
] | [
184,
0
] | [
215,
18
] | python | en | ['en', 'error', 'th'] | False |
MaxPriorityQueue.__init__ | (self, max_size) |
Initialize priority queue.
:param max_size: maximum capacity of priority queue.
|
Initialize priority queue. | def __init__(self, max_size):
"""
Initialize priority queue.
:param max_size: maximum capacity of priority queue.
"""
self.capacity = max_size
self.lst = [] | [
"def",
"__init__",
"(",
"self",
",",
"max_size",
")",
":",
"self",
".",
"capacity",
"=",
"max_size",
"self",
".",
"lst",
"=",
"[",
"]"
] | [
41,
4
] | [
48,
21
] | python | en | ['en', 'error', 'th'] | False |
MaxPriorityQueue.add | (self, item, priority) |
Add element to the queue, with a separate priority if desired.
Element will not be added if the queue is at capacity and the element
has lower priority than the lowest currently in the queue.
:param item:
item to add to queue.
:param priority:
priority to use for item.
|
Add element to the queue, with a separate priority if desired. | def add(self, item, priority):
"""
Add element to the queue, with a separate priority if desired.
Element will not be added if the queue is at capacity and the element
has lower priority than the lowest currently in the queue.
:param item:
item to add to queue.
:param priority:
priority to use for item.
"""
if len(self.lst) < self.capacity:
heapq.heappush(self.lst, (priority, item))
elif priority > self.lst[0][0]:
heapq.heapreplace(self.lst, (priority, item)) | [
"def",
"add",
"(",
"self",
",",
"item",
",",
"priority",
")",
":",
"if",
"len",
"(",
"self",
".",
"lst",
")",
"<",
"self",
".",
"capacity",
":",
"heapq",
".",
"heappush",
"(",
"self",
".",
"lst",
",",
"(",
"priority",
",",
"item",
")",
")",
"elif",
"priority",
">",
"self",
".",
"lst",
"[",
"0",
"]",
"[",
"0",
"]",
":",
"heapq",
".",
"heapreplace",
"(",
"self",
".",
"lst",
",",
"(",
"priority",
",",
"item",
")",
")"
] | [
50,
4
] | [
65,
57
] | python | en | ['en', 'error', 'th'] | False |
MaxPriorityQueue.__getitem__ | (self, key) |
Get item at specified index.
:param key: integer index into priority queue, 0 <= index < max_size.
:returns: item stored at the specified index.
|
Get item at specified index. | def __getitem__(self, key):
"""
Get item at specified index.
:param key: integer index into priority queue, 0 <= index < max_size.
:returns: item stored at the specified index.
"""
return sorted(self.lst)[key][1] | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"lst",
")",
"[",
"key",
"]",
"[",
"1",
"]"
] | [
67,
4
] | [
75,
39
] | python | en | ['en', 'error', 'th'] | False |
MaxPriorityQueue.__len__ | (self) |
Return length of priority queue.
|
Return length of priority queue.
| def __len__(self):
"""
Return length of priority queue.
"""
return len(self.lst) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"lst",
")"
] | [
77,
4
] | [
81,
28
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.add_cmdline_args | (
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) |
Add command line args specific to this agent.
|
Add command line args specific to this agent.
| def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
"""
Add command line args specific to this agent.
"""
parser = parser.add_argument_group('IrBaseline Arguments')
parser.add_argument(
'-lp',
'--length_penalty',
type=float,
default=0.5,
help='length penalty for responses',
)
parser.add_argument(
'-hsz',
'--history_size',
type=int,
default=1,
help='number of utterances from the dialogue history to take use '
'as the query',
)
parser.add_argument(
'--label_candidates_file',
type=str,
default=None,
help='file of candidate responses to choose from',
)
cls.dictionary_class().add_cmdline_args(parser, partial_opt=partial_opt)
return parser | [
"def",
"add_cmdline_args",
"(",
"cls",
",",
"parser",
":",
"ParlaiParser",
",",
"partial_opt",
":",
"Optional",
"[",
"Opt",
"]",
"=",
"None",
")",
"->",
"ParlaiParser",
":",
"parser",
"=",
"parser",
".",
"add_argument_group",
"(",
"'IrBaseline Arguments'",
")",
"parser",
".",
"add_argument",
"(",
"'-lp'",
",",
"'--length_penalty'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.5",
",",
"help",
"=",
"'length penalty for responses'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'-hsz'",
",",
"'--history_size'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1",
",",
"help",
"=",
"'number of utterances from the dialogue history to take use '",
"'as the query'",
",",
")",
"parser",
".",
"add_argument",
"(",
"'--label_candidates_file'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'file of candidate responses to choose from'",
",",
")",
"cls",
".",
"dictionary_class",
"(",
")",
".",
"add_cmdline_args",
"(",
"parser",
",",
"partial_opt",
"=",
"partial_opt",
")",
"return",
"parser"
] | [
224,
4
] | [
253,
21
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.__init__ | (self, opt, shared=None) |
Initialize agent.
|
Initialize agent.
| def __init__(self, opt, shared=None):
"""
Initialize agent.
"""
super().__init__(opt)
self.id = 'IRBaselineAgent'
self.length_penalty = float(opt['length_penalty'])
self.dictionary = DictionaryAgent(opt)
self.opt = opt
self.history = []
self.episodeDone = True
if opt.get('label_candidates_file'):
f = open(opt.get('label_candidates_file'))
self.label_candidates = f.read().split('\n') | [
"def",
"__init__",
"(",
"self",
",",
"opt",
",",
"shared",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"opt",
")",
"self",
".",
"id",
"=",
"'IRBaselineAgent'",
"self",
".",
"length_penalty",
"=",
"float",
"(",
"opt",
"[",
"'length_penalty'",
"]",
")",
"self",
".",
"dictionary",
"=",
"DictionaryAgent",
"(",
"opt",
")",
"self",
".",
"opt",
"=",
"opt",
"self",
".",
"history",
"=",
"[",
"]",
"self",
".",
"episodeDone",
"=",
"True",
"if",
"opt",
".",
"get",
"(",
"'label_candidates_file'",
")",
":",
"f",
"=",
"open",
"(",
"opt",
".",
"get",
"(",
"'label_candidates_file'",
")",
")",
"self",
".",
"label_candidates",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")"
] | [
259,
4
] | [
272,
56
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.reset | (self) |
Reset agent properties.
|
Reset agent properties.
| def reset(self):
"""
Reset agent properties.
"""
self.observation = None
self.history = []
self.episodeDone = True | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"observation",
"=",
"None",
"self",
".",
"history",
"=",
"[",
"]",
"self",
".",
"episodeDone",
"=",
"True"
] | [
274,
4
] | [
280,
31
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.observe | (self, obs) |
Store and remember incoming observation message dict.
|
Store and remember incoming observation message dict.
| def observe(self, obs):
"""
Store and remember incoming observation message dict.
"""
self.observation = obs
self.dictionary.observe(obs)
if self.episodeDone:
self.history = []
if 'text' in obs:
self.history.append(obs.get('text', ''))
self.episodeDone = obs.get('episode_done', False)
return obs | [
"def",
"observe",
"(",
"self",
",",
"obs",
")",
":",
"self",
".",
"observation",
"=",
"obs",
"self",
".",
"dictionary",
".",
"observe",
"(",
"obs",
")",
"if",
"self",
".",
"episodeDone",
":",
"self",
".",
"history",
"=",
"[",
"]",
"if",
"'text'",
"in",
"obs",
":",
"self",
".",
"history",
".",
"append",
"(",
"obs",
".",
"get",
"(",
"'text'",
",",
"''",
")",
")",
"self",
".",
"episodeDone",
"=",
"obs",
".",
"get",
"(",
"'episode_done'",
",",
"False",
")",
"return",
"obs"
] | [
282,
4
] | [
293,
18
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.act | (self) |
Generate a response to the previously seen observation(s).
|
Generate a response to the previously seen observation(s).
| def act(self):
"""
Generate a response to the previously seen observation(s).
"""
if self.opt.get('datatype', '').startswith('train'):
self.dictionary.act()
obs = self.observation
reply = {}
reply['id'] = self.getID()
# Rank candidates
cands = None
if obs.get('label_candidates', False) and len(obs['label_candidates']) > 0:
cands = obs['label_candidates']
if hasattr(self, 'label_candidates'):
# override label candidates with candidate file if set
cands = self.label_candidates
if cands:
hist_sz = self.opt.get('history_size', 1)
left_idx = max(0, len(self.history) - hist_sz)
text = ' '.join(self.history[left_idx : len(self.history)])
rep = self.build_query_representation(text)
reply['text_candidates'] = rank_candidates(
rep, cands, self.length_penalty, self.dictionary
)
reply['text'] = reply['text_candidates'][0]
return reply | [
"def",
"act",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
".",
"get",
"(",
"'datatype'",
",",
"''",
")",
".",
"startswith",
"(",
"'train'",
")",
":",
"self",
".",
"dictionary",
".",
"act",
"(",
")",
"obs",
"=",
"self",
".",
"observation",
"reply",
"=",
"{",
"}",
"reply",
"[",
"'id'",
"]",
"=",
"self",
".",
"getID",
"(",
")",
"# Rank candidates",
"cands",
"=",
"None",
"if",
"obs",
".",
"get",
"(",
"'label_candidates'",
",",
"False",
")",
"and",
"len",
"(",
"obs",
"[",
"'label_candidates'",
"]",
")",
">",
"0",
":",
"cands",
"=",
"obs",
"[",
"'label_candidates'",
"]",
"if",
"hasattr",
"(",
"self",
",",
"'label_candidates'",
")",
":",
"# override label candidates with candidate file if set",
"cands",
"=",
"self",
".",
"label_candidates",
"if",
"cands",
":",
"hist_sz",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'history_size'",
",",
"1",
")",
"left_idx",
"=",
"max",
"(",
"0",
",",
"len",
"(",
"self",
".",
"history",
")",
"-",
"hist_sz",
")",
"text",
"=",
"' '",
".",
"join",
"(",
"self",
".",
"history",
"[",
"left_idx",
":",
"len",
"(",
"self",
".",
"history",
")",
"]",
")",
"rep",
"=",
"self",
".",
"build_query_representation",
"(",
"text",
")",
"reply",
"[",
"'text_candidates'",
"]",
"=",
"rank_candidates",
"(",
"rep",
",",
"cands",
",",
"self",
".",
"length_penalty",
",",
"self",
".",
"dictionary",
")",
"reply",
"[",
"'text'",
"]",
"=",
"reply",
"[",
"'text_candidates'",
"]",
"[",
"0",
"]",
"return",
"reply"
] | [
295,
4
] | [
322,
20
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.save | (self, path=None) |
Save dictionary tokenizer if available.
|
Save dictionary tokenizer if available.
| def save(self, path=None):
"""
Save dictionary tokenizer if available.
"""
path = self.opt.get('model_file', None) if path is None else path
if path:
self.dictionary.save(path + '.dict')
data = {}
data['opt'] = self.opt
torch_utils.atomic_save(data, path)
with PathManager.open(path + '.opt', 'w') as handle:
json.dump(self.opt, handle) | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"opt",
".",
"get",
"(",
"'model_file'",
",",
"None",
")",
"if",
"path",
"is",
"None",
"else",
"path",
"if",
"path",
":",
"self",
".",
"dictionary",
".",
"save",
"(",
"path",
"+",
"'.dict'",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'opt'",
"]",
"=",
"self",
".",
"opt",
"torch_utils",
".",
"atomic_save",
"(",
"data",
",",
"path",
")",
"with",
"PathManager",
".",
"open",
"(",
"path",
"+",
"'.opt'",
",",
"'w'",
")",
"as",
"handle",
":",
"json",
".",
"dump",
"(",
"self",
".",
"opt",
",",
"handle",
")"
] | [
324,
4
] | [
335,
43
] | python | en | ['en', 'error', 'th'] | False |
IrBaselineAgent.build_query_representation | (self, query) |
Build representation of query, e.g. words or n-grams.
:param query: string to represent.
:returns: dictionary containing 'words' dictionary (token => frequency)
and 'norm' float (square root of the number of tokens)
|
Build representation of query, e.g. words or n-grams. | def build_query_representation(self, query):
"""
Build representation of query, e.g. words or n-grams.
:param query: string to represent.
:returns: dictionary containing 'words' dictionary (token => frequency)
and 'norm' float (square root of the number of tokens)
"""
rep = {}
rep['words'] = {}
words = [w for w in self.dictionary.tokenize(query.lower())]
rw = rep['words']
used = {}
for w in words:
assert len(self.dictionary.freq) > 0
rw[w] = 1.0 / (1.0 + math.log(1.0 + self.dictionary.freq[w]))
used[w] = True
rep['norm'] = math.sqrt(len(words))
return rep | [
"def",
"build_query_representation",
"(",
"self",
",",
"query",
")",
":",
"rep",
"=",
"{",
"}",
"rep",
"[",
"'words'",
"]",
"=",
"{",
"}",
"words",
"=",
"[",
"w",
"for",
"w",
"in",
"self",
".",
"dictionary",
".",
"tokenize",
"(",
"query",
".",
"lower",
"(",
")",
")",
"]",
"rw",
"=",
"rep",
"[",
"'words'",
"]",
"used",
"=",
"{",
"}",
"for",
"w",
"in",
"words",
":",
"assert",
"len",
"(",
"self",
".",
"dictionary",
".",
"freq",
")",
">",
"0",
"rw",
"[",
"w",
"]",
"=",
"1.0",
"/",
"(",
"1.0",
"+",
"math",
".",
"log",
"(",
"1.0",
"+",
"self",
".",
"dictionary",
".",
"freq",
"[",
"w",
"]",
")",
")",
"used",
"[",
"w",
"]",
"=",
"True",
"rep",
"[",
"'norm'",
"]",
"=",
"math",
".",
"sqrt",
"(",
"len",
"(",
"words",
")",
")",
"return",
"rep"
] | [
337,
4
] | [
356,
18
] | 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.