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
ColorBar.tickprefix
(self)
Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string
def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"]
[ "def", "tickprefix", "(", "self", ")", ":", "return", "self", "[", "\"tickprefix\"", "]" ]
[ 878, 4 ]
[ 890, 33 ]
python
en
['en', 'error', 'th']
False
ColorBar.ticks
(self)
Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any
Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', '']
def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"]
[ "def", "ticks", "(", "self", ")", ":", "return", "self", "[", "\"ticks\"", "]" ]
[ 899, 4 ]
[ 913, 28 ]
python
en
['en', 'error', 'th']
False
ColorBar.ticksuffix
(self)
Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string
def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"]
[ "def", "ticksuffix", "(", "self", ")", ":", "return", "self", "[", "\"ticksuffix\"", "]" ]
[ 922, 4 ]
[ 934, 33 ]
python
en
['en', 'error', 'th']
False
ColorBar.ticktext
(self)
Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray
Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series
def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"]
[ "def", "ticktext", "(", "self", ")", ":", "return", "self", "[", "\"ticktext\"", "]" ]
[ 943, 4 ]
[ 956, 31 ]
python
en
['en', 'error', 'th']
False
ColorBar.ticktextsrc
(self)
Sets the source reference on Chart Studio Cloud for ticktext . The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for ticktext . The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object
def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for ticktext . The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"]
[ "def", "ticktextsrc", "(", "self", ")", ":", "return", "self", "[", "\"ticktextsrc\"", "]" ]
[ 965, 4 ]
[ 976, 34 ]
python
en
['en', 'error', 'th']
False
ColorBar.tickvals
(self)
Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray
Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series
def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"]
[ "def", "tickvals", "(", "self", ")", ":", "return", "self", "[", "\"tickvals\"", "]" ]
[ 985, 4 ]
[ 997, 31 ]
python
en
['en', 'error', 'th']
False
ColorBar.tickvalssrc
(self)
Sets the source reference on Chart Studio Cloud for tickvals . The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for tickvals . The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object
def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for tickvals . The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"]
[ "def", "tickvalssrc", "(", "self", ")", ":", "return", "self", "[", "\"tickvalssrc\"", "]" ]
[ 1006, 4 ]
[ 1017, 34 ]
python
en
['en', 'error', 'th']
False
ColorBar.tickwidth
(self)
Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf]
def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"]
[ "def", "tickwidth", "(", "self", ")", ":", "return", "self", "[", "\"tickwidth\"", "]" ]
[ 1026, 4 ]
[ 1037, 32 ]
python
en
['en', 'error', 'th']
False
ColorBar.title
(self)
The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.densitymapbox.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Supported dict properties: font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- plotly.graph_objs.densitymapbox.colorbar.Title
The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.densitymapbox.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Supported dict properties: font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated.
def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.densitymapbox.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Supported dict properties: font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- plotly.graph_objs.densitymapbox.colorbar.Title """ return self["title"]
[ "def", "title", "(", "self", ")", ":", "return", "self", "[", "\"title\"", "]" ]
[ 1046, 4 ]
[ 1076, 28 ]
python
en
['en', 'error', 'th']
False
ColorBar.titlefont
(self)
Deprecated: Please use densitymapbox.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.densitymapbox.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: 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 -------
Deprecated: Please use densitymapbox.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.densitymapbox.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: 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
def titlefont(self): """ Deprecated: Please use densitymapbox.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.densitymapbox.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: 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 ------- """ return self["titlefont"]
[ "def", "titlefont", "(", "self", ")", ":", "return", "self", "[", "\"titlefont\"", "]" ]
[ 1085, 4 ]
[ 1125, 32 ]
python
en
['en', 'error', 'th']
False
ColorBar.titleside
(self)
Deprecated: Please use densitymapbox.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns -------
Deprecated: Please use densitymapbox.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom']
def titleside(self): """ Deprecated: Please use densitymapbox.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- """ return self["titleside"]
[ "def", "titleside", "(", "self", ")", ":", "return", "self", "[", "\"titleside\"", "]" ]
[ 1134, 4 ]
[ 1149, 32 ]
python
en
['en', 'error', 'th']
False
ColorBar.x
(self)
Sets the x position of the color bar (in plot fraction). The 'x' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float
Sets the x position of the color bar (in plot fraction). The 'x' property is a number and may be specified as: - An int or float in the interval [-2, 3]
def x(self): """ Sets the x position of the color bar (in plot fraction). The 'x' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float """ return self["x"]
[ "def", "x", "(", "self", ")", ":", "return", "self", "[", "\"x\"", "]" ]
[ 1158, 4 ]
[ 1169, 24 ]
python
en
['en', 'error', 'th']
False
ColorBar.xanchor
(self)
Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any
Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right']
def xanchor(self): """ Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"]
[ "def", "xanchor", "(", "self", ")", ":", "return", "self", "[", "\"xanchor\"", "]" ]
[ 1178, 4 ]
[ 1192, 30 ]
python
en
['en', 'error', 'th']
False
ColorBar.xpad
(self)
Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf]
def xpad(self): """ Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["xpad"]
[ "def", "xpad", "(", "self", ")", ":", "return", "self", "[", "\"xpad\"", "]" ]
[ 1201, 4 ]
[ 1212, 27 ]
python
en
['en', 'error', 'th']
False
ColorBar.y
(self)
Sets the y position of the color bar (in plot fraction). The 'y' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float
Sets the y position of the color bar (in plot fraction). The 'y' property is a number and may be specified as: - An int or float in the interval [-2, 3]
def y(self): """ Sets the y position of the color bar (in plot fraction). The 'y' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float """ return self["y"]
[ "def", "y", "(", "self", ")", ":", "return", "self", "[", "\"y\"", "]" ]
[ 1221, 4 ]
[ 1232, 24 ]
python
en
['en', 'error', 'th']
False
ColorBar.yanchor
(self)
Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any
Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom']
def yanchor(self): """ Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"]
[ "def", "yanchor", "(", "self", ")", ":", "return", "self", "[", "\"yanchor\"", "]" ]
[ 1241, 4 ]
[ 1255, 30 ]
python
en
['en', 'error', 'th']
False
ColorBar.ypad
(self)
Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf]
def ypad(self): """ Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ypad"]
[ "def", "ypad", "(", "self", ")", ":", "return", "self", "[", "\"ypad\"", "]" ]
[ 1264, 4 ]
[ 1275, 27 ]
python
en
['en', 'error', 'th']
False
ColorBar.__init__
( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, len=None, lenmode=None, nticks=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, titlefont=None, titleside=None, x=None, xanchor=None, xpad=None, y=None, yanchor=None, ypad=None, **kwargs )
Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.densitymapbox.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format And for dates see: https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format We add one item to d3's date formatter: "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.densitymapbox.c olorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.densit ymapbox.colorbar.tickformatstopdefaults), sets the default property values to use for elements of densitymapbox.colorbar.tickformatstops ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for ticktext . tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for tickvals . tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.densitymapbox.colorbar.Tit le` instance or dict with compatible properties titlefont Deprecated: Please use densitymapbox.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleside Deprecated: Please use densitymapbox.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. x Sets the x position of the color bar (in plot fraction). xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. xpad Sets the amount of padding (in px) along the x direction. y Sets the y position of the color bar (in plot fraction). yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. ypad Sets the amount of padding (in px) along the y direction. Returns ------- ColorBar
Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.densitymapbox.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format And for dates see: https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format We add one item to d3's date formatter: "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.densitymapbox.c olorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.densit ymapbox.colorbar.tickformatstopdefaults), sets the default property values to use for elements of densitymapbox.colorbar.tickformatstops ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for ticktext . tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for tickvals . tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.densitymapbox.colorbar.Tit le` instance or dict with compatible properties titlefont Deprecated: Please use densitymapbox.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleside Deprecated: Please use densitymapbox.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. x Sets the x position of the color bar (in plot fraction). xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. xpad Sets the amount of padding (in px) along the x direction. y Sets the y position of the color bar (in plot fraction). yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. ypad Sets the amount of padding (in px) along the y direction.
def __init__( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, len=None, lenmode=None, nticks=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, titlefont=None, titleside=None, x=None, xanchor=None, xpad=None, y=None, yanchor=None, ypad=None, **kwargs ): """ Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.densitymapbox.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format And for dates see: https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format We add one item to d3's date formatter: "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.densitymapbox.c olorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.densit ymapbox.colorbar.tickformatstopdefaults), sets the default property values to use for elements of densitymapbox.colorbar.tickformatstops ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for ticktext . tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for tickvals . tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.densitymapbox.colorbar.Tit le` instance or dict with compatible properties titlefont Deprecated: Please use densitymapbox.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleside Deprecated: Please use densitymapbox.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. x Sets the x position of the color bar (in plot fraction). xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. xpad Sets the amount of padding (in px) along the x direction. y Sets the y position of the color bar (in plot fraction). yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. ypad Sets the amount of padding (in px) along the y direction. Returns ------- ColorBar """ super(ColorBar, self).__init__("colorbar") 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.ColorBar constructor must be a dict or an instance of :class:`plotly.graph_objs.densitymapbox.ColorBar`""" ) # 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("bgcolor", None) _v = bgcolor if bgcolor is not None else _v if _v is not None: self["bgcolor"] = _v _v = arg.pop("bordercolor", None) _v = bordercolor if bordercolor is not None else _v if _v is not None: self["bordercolor"] = _v _v = arg.pop("borderwidth", None) _v = borderwidth if borderwidth is not None else _v if _v is not None: self["borderwidth"] = _v _v = arg.pop("dtick", None) _v = dtick if dtick is not None else _v if _v is not None: self["dtick"] = _v _v = arg.pop("exponentformat", None) _v = exponentformat if exponentformat is not None else _v if _v is not None: self["exponentformat"] = _v _v = arg.pop("len", None) _v = len if len is not None else _v if _v is not None: self["len"] = _v _v = arg.pop("lenmode", None) _v = lenmode if lenmode is not None else _v if _v is not None: self["lenmode"] = _v _v = arg.pop("nticks", None) _v = nticks if nticks is not None else _v if _v is not None: self["nticks"] = _v _v = arg.pop("outlinecolor", None) _v = outlinecolor if outlinecolor is not None else _v if _v is not None: self["outlinecolor"] = _v _v = arg.pop("outlinewidth", None) _v = outlinewidth if outlinewidth is not None else _v if _v is not None: self["outlinewidth"] = _v _v = arg.pop("separatethousands", None) _v = separatethousands if separatethousands is not None else _v if _v is not None: self["separatethousands"] = _v _v = arg.pop("showexponent", None) _v = showexponent if showexponent is not None else _v if _v is not None: self["showexponent"] = _v _v = arg.pop("showticklabels", None) _v = showticklabels if showticklabels is not None else _v if _v is not None: self["showticklabels"] = _v _v = arg.pop("showtickprefix", None) _v = showtickprefix if showtickprefix is not None else _v if _v is not None: self["showtickprefix"] = _v _v = arg.pop("showticksuffix", None) _v = showticksuffix if showticksuffix is not None else _v if _v is not None: self["showticksuffix"] = _v _v = arg.pop("thickness", None) _v = thickness if thickness is not None else _v if _v is not None: self["thickness"] = _v _v = arg.pop("thicknessmode", None) _v = thicknessmode if thicknessmode is not None else _v if _v is not None: self["thicknessmode"] = _v _v = arg.pop("tick0", None) _v = tick0 if tick0 is not None else _v if _v is not None: self["tick0"] = _v _v = arg.pop("tickangle", None) _v = tickangle if tickangle is not None else _v if _v is not None: self["tickangle"] = _v _v = arg.pop("tickcolor", None) _v = tickcolor if tickcolor is not None else _v if _v is not None: self["tickcolor"] = _v _v = arg.pop("tickfont", None) _v = tickfont if tickfont is not None else _v if _v is not None: self["tickfont"] = _v _v = arg.pop("tickformat", None) _v = tickformat if tickformat is not None else _v if _v is not None: self["tickformat"] = _v _v = arg.pop("tickformatstops", None) _v = tickformatstops if tickformatstops is not None else _v if _v is not None: self["tickformatstops"] = _v _v = arg.pop("tickformatstopdefaults", None) _v = tickformatstopdefaults if tickformatstopdefaults is not None else _v if _v is not None: self["tickformatstopdefaults"] = _v _v = arg.pop("ticklen", None) _v = ticklen if ticklen is not None else _v if _v is not None: self["ticklen"] = _v _v = arg.pop("tickmode", None) _v = tickmode if tickmode is not None else _v if _v is not None: self["tickmode"] = _v _v = arg.pop("tickprefix", None) _v = tickprefix if tickprefix is not None else _v if _v is not None: self["tickprefix"] = _v _v = arg.pop("ticks", None) _v = ticks if ticks is not None else _v if _v is not None: self["ticks"] = _v _v = arg.pop("ticksuffix", None) _v = ticksuffix if ticksuffix is not None else _v if _v is not None: self["ticksuffix"] = _v _v = arg.pop("ticktext", None) _v = ticktext if ticktext is not None else _v if _v is not None: self["ticktext"] = _v _v = arg.pop("ticktextsrc", None) _v = ticktextsrc if ticktextsrc is not None else _v if _v is not None: self["ticktextsrc"] = _v _v = arg.pop("tickvals", None) _v = tickvals if tickvals is not None else _v if _v is not None: self["tickvals"] = _v _v = arg.pop("tickvalssrc", None) _v = tickvalssrc if tickvalssrc is not None else _v if _v is not None: self["tickvalssrc"] = _v _v = arg.pop("tickwidth", None) _v = tickwidth if tickwidth is not None else _v if _v is not None: self["tickwidth"] = _v _v = arg.pop("title", None) _v = title if title is not None else _v if _v is not None: self["title"] = _v _v = arg.pop("titlefont", None) _v = titlefont if titlefont is not None else _v if _v is not None: self["titlefont"] = _v _v = arg.pop("titleside", None) _v = titleside if titleside is not None else _v if _v is not None: self["titleside"] = _v _v = arg.pop("x", None) _v = x if x is not None else _v if _v is not None: self["x"] = _v _v = arg.pop("xanchor", None) _v = xanchor if xanchor is not None else _v if _v is not None: self["xanchor"] = _v _v = arg.pop("xpad", None) _v = xpad if xpad is not None else _v if _v is not None: self["xpad"] = _v _v = arg.pop("y", None) _v = y if y is not None else _v if _v is not None: self["y"] = _v _v = arg.pop("yanchor", None) _v = yanchor if yanchor is not None else _v if _v is not None: self["yanchor"] = _v _v = arg.pop("ypad", None) _v = ypad if ypad is not None else _v if _v is not None: self["ypad"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "bgcolor", "=", "None", ",", "bordercolor", "=", "None", ",", "borderwidth", "=", "None", ",", "dtick", "=", "None", ",", "exponentformat", "=", "None", ",", "len", "=", "None", ",", "lenmode", "=", "None", ",", "nticks", "=", "None", ",", "outlinecolor", "=", "None", ",", "outlinewidth", "=", "None", ",", "separatethousands", "=", "None", ",", "showexponent", "=", "None", ",", "showticklabels", "=", "None", ",", "showtickprefix", "=", "None", ",", "showticksuffix", "=", "None", ",", "thickness", "=", "None", ",", "thicknessmode", "=", "None", ",", "tick0", "=", "None", ",", "tickangle", "=", "None", ",", "tickcolor", "=", "None", ",", "tickfont", "=", "None", ",", "tickformat", "=", "None", ",", "tickformatstops", "=", "None", ",", "tickformatstopdefaults", "=", "None", ",", "ticklen", "=", "None", ",", "tickmode", "=", "None", ",", "tickprefix", "=", "None", ",", "ticks", "=", "None", ",", "ticksuffix", "=", "None", ",", "ticktext", "=", "None", ",", "ticktextsrc", "=", "None", ",", "tickvals", "=", "None", ",", "tickvalssrc", "=", "None", ",", "tickwidth", "=", "None", ",", "title", "=", "None", ",", "titlefont", "=", "None", ",", "titleside", "=", "None", ",", "x", "=", "None", ",", "xanchor", "=", "None", ",", "xpad", "=", "None", ",", "y", "=", "None", ",", "yanchor", "=", "None", ",", "ypad", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "ColorBar", ",", "self", ")", ".", "__init__", "(", "\"colorbar\"", ")", "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.ColorBar \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.densitymapbox.ColorBar`\"\"\"", ")", "# 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", "(", "\"bgcolor\"", ",", "None", ")", "_v", "=", "bgcolor", "if", "bgcolor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"bgcolor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"bordercolor\"", ",", "None", ")", "_v", "=", "bordercolor", "if", "bordercolor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"bordercolor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"borderwidth\"", ",", "None", ")", "_v", "=", "borderwidth", "if", "borderwidth", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"borderwidth\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"dtick\"", ",", "None", ")", "_v", "=", "dtick", "if", "dtick", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"dtick\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"exponentformat\"", ",", "None", ")", "_v", "=", "exponentformat", "if", "exponentformat", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"exponentformat\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"len\"", ",", "None", ")", "_v", "=", "len", "if", "len", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"len\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"lenmode\"", ",", "None", ")", "_v", "=", "lenmode", "if", "lenmode", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"lenmode\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"nticks\"", ",", "None", ")", "_v", "=", "nticks", "if", "nticks", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"nticks\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"outlinecolor\"", ",", "None", ")", "_v", "=", "outlinecolor", "if", "outlinecolor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"outlinecolor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"outlinewidth\"", ",", "None", ")", "_v", "=", "outlinewidth", "if", "outlinewidth", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"outlinewidth\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"separatethousands\"", ",", "None", ")", "_v", "=", "separatethousands", "if", "separatethousands", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"separatethousands\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"showexponent\"", ",", "None", ")", "_v", "=", "showexponent", "if", "showexponent", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"showexponent\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"showticklabels\"", ",", "None", ")", "_v", "=", "showticklabels", "if", "showticklabels", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"showticklabels\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"showtickprefix\"", ",", "None", ")", "_v", "=", "showtickprefix", "if", "showtickprefix", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"showtickprefix\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"showticksuffix\"", ",", "None", ")", "_v", "=", "showticksuffix", "if", "showticksuffix", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"showticksuffix\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"thickness\"", ",", "None", ")", "_v", "=", "thickness", "if", "thickness", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"thickness\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"thicknessmode\"", ",", "None", ")", "_v", "=", "thicknessmode", "if", "thicknessmode", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"thicknessmode\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tick0\"", ",", "None", ")", "_v", "=", "tick0", "if", "tick0", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tick0\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickangle\"", ",", "None", ")", "_v", "=", "tickangle", "if", "tickangle", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickangle\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickcolor\"", ",", "None", ")", "_v", "=", "tickcolor", "if", "tickcolor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickcolor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickfont\"", ",", "None", ")", "_v", "=", "tickfont", "if", "tickfont", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickfont\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickformat\"", ",", "None", ")", "_v", "=", "tickformat", "if", "tickformat", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickformat\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickformatstops\"", ",", "None", ")", "_v", "=", "tickformatstops", "if", "tickformatstops", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickformatstops\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickformatstopdefaults\"", ",", "None", ")", "_v", "=", "tickformatstopdefaults", "if", "tickformatstopdefaults", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickformatstopdefaults\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ticklen\"", ",", "None", ")", "_v", "=", "ticklen", "if", "ticklen", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticklen\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickmode\"", ",", "None", ")", "_v", "=", "tickmode", "if", "tickmode", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickmode\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickprefix\"", ",", "None", ")", "_v", "=", "tickprefix", "if", "tickprefix", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickprefix\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ticks\"", ",", "None", ")", "_v", "=", "ticks", "if", "ticks", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticks\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ticksuffix\"", ",", "None", ")", "_v", "=", "ticksuffix", "if", "ticksuffix", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticksuffix\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ticktext\"", ",", "None", ")", "_v", "=", "ticktext", "if", "ticktext", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticktext\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ticktextsrc\"", ",", "None", ")", "_v", "=", "ticktextsrc", "if", "ticktextsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticktextsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickvals\"", ",", "None", ")", "_v", "=", "tickvals", "if", "tickvals", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickvals\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickvalssrc\"", ",", "None", ")", "_v", "=", "tickvalssrc", "if", "tickvalssrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickvalssrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"tickwidth\"", ",", "None", ")", "_v", "=", "tickwidth", "if", "tickwidth", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"tickwidth\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"title\"", ",", "None", ")", "_v", "=", "title", "if", "title", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"title\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"titlefont\"", ",", "None", ")", "_v", "=", "titlefont", "if", "titlefont", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"titlefont\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"titleside\"", ",", "None", ")", "_v", "=", "titleside", "if", "titleside", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"titleside\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"x\"", ",", "None", ")", "_v", "=", "x", "if", "x", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"x\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"xanchor\"", ",", "None", ")", "_v", "=", "xanchor", "if", "xanchor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"xanchor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"xpad\"", ",", "None", ")", "_v", "=", "xpad", "if", "xpad", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"xpad\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"y\"", ",", "None", ")", "_v", "=", "y", "if", "y", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"y\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"yanchor\"", ",", "None", ")", "_v", "=", "yanchor", "if", "yanchor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"yanchor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ypad\"", ",", "None", ")", "_v", "=", "ypad", "if", "ypad", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ypad\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 1482, 4 ]
[ 1941, 34 ]
python
en
['en', 'error', 'th']
False
get_kitti_image_info
(path, training=True, label_info=True, velodyne=False, calib=False, image_ids=7481, extend_matrix=True, num_worker=8, relative_path=True, with_imageshape=True)
KITTI annotation format version 2: { [optional]points: [N, 3+] point cloud [optional, for kitti]image: { image_idx: ... image_path: ... image_shape: ... } point_cloud: { num_features: 4 velodyne_path: ... } [optional, for kitti]calib: { R0_rect: ... Tr_velo_to_cam: ... P2: ... } annos: { location: [num_gt, 3] array dimensions: [num_gt, 3] array rotation_y: [num_gt] angle array name: [num_gt] ground truth name array [optional]difficulty: kitti difficulty [optional]group_ids: used for multi-part object } }
KITTI annotation format version 2: { [optional]points: [N, 3+] point cloud [optional, for kitti]image: { image_idx: ... image_path: ... image_shape: ... } point_cloud: { num_features: 4 velodyne_path: ... } [optional, for kitti]calib: { R0_rect: ... Tr_velo_to_cam: ... P2: ... } annos: { location: [num_gt, 3] array dimensions: [num_gt, 3] array rotation_y: [num_gt] angle array name: [num_gt] ground truth name array [optional]difficulty: kitti difficulty [optional]group_ids: used for multi-part object } }
def get_kitti_image_info(path, training=True, label_info=True, velodyne=False, calib=False, image_ids=7481, extend_matrix=True, num_worker=8, relative_path=True, with_imageshape=True): """ KITTI annotation format version 2: { [optional]points: [N, 3+] point cloud [optional, for kitti]image: { image_idx: ... image_path: ... image_shape: ... } point_cloud: { num_features: 4 velodyne_path: ... } [optional, for kitti]calib: { R0_rect: ... Tr_velo_to_cam: ... P2: ... } annos: { location: [num_gt, 3] array dimensions: [num_gt, 3] array rotation_y: [num_gt] angle array name: [num_gt] ground truth name array [optional]difficulty: kitti difficulty [optional]group_ids: used for multi-part object } } """ root_path = Path(path) if not isinstance(image_ids, list): image_ids = list(range(image_ids)) def map_func(idx): info = {} pc_info = {'num_features': 4} calib_info = {} image_info = {'image_idx': idx} annotations = None if velodyne: pc_info['velodyne_path'] = get_velodyne_path( idx, path, training, relative_path) image_info['image_path'] = get_image_path(idx, path, training, relative_path) if with_imageshape: img_path = image_info['image_path'] if relative_path: img_path = str(root_path / img_path) image_info['image_shape'] = np.array( io.imread(img_path).shape[:2], dtype=np.int32) if label_info: label_path = get_label_path(idx, path, training, relative_path) if relative_path: label_path = str(root_path / label_path) annotations = get_label_anno(label_path) info['image'] = image_info info['point_cloud'] = pc_info if calib: calib_path = get_calib_path( idx, path, training, relative_path=False) with open(calib_path, 'r') as f: lines = f.readlines() P0 = np.array([float(info) for info in lines[0].split(' ')[1:13] ]).reshape([3, 4]) P1 = np.array([float(info) for info in lines[1].split(' ')[1:13] ]).reshape([3, 4]) P2 = np.array([float(info) for info in lines[2].split(' ')[1:13] ]).reshape([3, 4]) P3 = np.array([float(info) for info in lines[3].split(' ')[1:13] ]).reshape([3, 4]) if extend_matrix: P0 = _extend_matrix(P0) P1 = _extend_matrix(P1) P2 = _extend_matrix(P2) P3 = _extend_matrix(P3) R0_rect = np.array([ float(info) for info in lines[4].split(' ')[1:10] ]).reshape([3, 3]) if extend_matrix: rect_4x4 = np.zeros([4, 4], dtype=R0_rect.dtype) rect_4x4[3, 3] = 1. rect_4x4[:3, :3] = R0_rect else: rect_4x4 = R0_rect Tr_velo_to_cam = np.array([ float(info) for info in lines[5].split(' ')[1:13] ]).reshape([3, 4]) Tr_imu_to_velo = np.array([ float(info) for info in lines[6].split(' ')[1:13] ]).reshape([3, 4]) if extend_matrix: Tr_velo_to_cam = _extend_matrix(Tr_velo_to_cam) Tr_imu_to_velo = _extend_matrix(Tr_imu_to_velo) calib_info['P0'] = P0 calib_info['P1'] = P1 calib_info['P2'] = P2 calib_info['P3'] = P3 calib_info['R0_rect'] = rect_4x4 calib_info['Tr_velo_to_cam'] = Tr_velo_to_cam calib_info['Tr_imu_to_velo'] = Tr_imu_to_velo info['calib'] = calib_info if annotations is not None: info['annos'] = annotations add_difficulty_to_annos(info) return info with futures.ThreadPoolExecutor(num_worker) as executor: image_infos = executor.map(map_func, image_ids) return list(image_infos)
[ "def", "get_kitti_image_info", "(", "path", ",", "training", "=", "True", ",", "label_info", "=", "True", ",", "velodyne", "=", "False", ",", "calib", "=", "False", ",", "image_ids", "=", "7481", ",", "extend_matrix", "=", "True", ",", "num_worker", "=", "8", ",", "relative_path", "=", "True", ",", "with_imageshape", "=", "True", ")", ":", "root_path", "=", "Path", "(", "path", ")", "if", "not", "isinstance", "(", "image_ids", ",", "list", ")", ":", "image_ids", "=", "list", "(", "range", "(", "image_ids", ")", ")", "def", "map_func", "(", "idx", ")", ":", "info", "=", "{", "}", "pc_info", "=", "{", "'num_features'", ":", "4", "}", "calib_info", "=", "{", "}", "image_info", "=", "{", "'image_idx'", ":", "idx", "}", "annotations", "=", "None", "if", "velodyne", ":", "pc_info", "[", "'velodyne_path'", "]", "=", "get_velodyne_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", ")", "image_info", "[", "'image_path'", "]", "=", "get_image_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", ")", "if", "with_imageshape", ":", "img_path", "=", "image_info", "[", "'image_path'", "]", "if", "relative_path", ":", "img_path", "=", "str", "(", "root_path", "/", "img_path", ")", "image_info", "[", "'image_shape'", "]", "=", "np", ".", "array", "(", "io", ".", "imread", "(", "img_path", ")", ".", "shape", "[", ":", "2", "]", ",", "dtype", "=", "np", ".", "int32", ")", "if", "label_info", ":", "label_path", "=", "get_label_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", ")", "if", "relative_path", ":", "label_path", "=", "str", "(", "root_path", "/", "label_path", ")", "annotations", "=", "get_label_anno", "(", "label_path", ")", "info", "[", "'image'", "]", "=", "image_info", "info", "[", "'point_cloud'", "]", "=", "pc_info", "if", "calib", ":", "calib_path", "=", "get_calib_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", "=", "False", ")", "with", "open", "(", "calib_path", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "P0", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "0", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P1", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "1", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P2", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "2", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P3", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "3", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "if", "extend_matrix", ":", "P0", "=", "_extend_matrix", "(", "P0", ")", "P1", "=", "_extend_matrix", "(", "P1", ")", "P2", "=", "_extend_matrix", "(", "P2", ")", "P3", "=", "_extend_matrix", "(", "P3", ")", "R0_rect", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "4", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "10", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "3", "]", ")", "if", "extend_matrix", ":", "rect_4x4", "=", "np", ".", "zeros", "(", "[", "4", ",", "4", "]", ",", "dtype", "=", "R0_rect", ".", "dtype", ")", "rect_4x4", "[", "3", ",", "3", "]", "=", "1.", "rect_4x4", "[", ":", "3", ",", ":", "3", "]", "=", "R0_rect", "else", ":", "rect_4x4", "=", "R0_rect", "Tr_velo_to_cam", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "5", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "Tr_imu_to_velo", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "6", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "if", "extend_matrix", ":", "Tr_velo_to_cam", "=", "_extend_matrix", "(", "Tr_velo_to_cam", ")", "Tr_imu_to_velo", "=", "_extend_matrix", "(", "Tr_imu_to_velo", ")", "calib_info", "[", "'P0'", "]", "=", "P0", "calib_info", "[", "'P1'", "]", "=", "P1", "calib_info", "[", "'P2'", "]", "=", "P2", "calib_info", "[", "'P3'", "]", "=", "P3", "calib_info", "[", "'R0_rect'", "]", "=", "rect_4x4", "calib_info", "[", "'Tr_velo_to_cam'", "]", "=", "Tr_velo_to_cam", "calib_info", "[", "'Tr_imu_to_velo'", "]", "=", "Tr_imu_to_velo", "info", "[", "'calib'", "]", "=", "calib_info", "if", "annotations", "is", "not", "None", ":", "info", "[", "'annos'", "]", "=", "annotations", "add_difficulty_to_annos", "(", "info", ")", "return", "info", "with", "futures", ".", "ThreadPoolExecutor", "(", "num_worker", ")", "as", "executor", ":", "image_infos", "=", "executor", ".", "map", "(", "map_func", ",", "image_ids", ")", "return", "list", "(", "image_infos", ")" ]
[ 139, 0 ]
[ 260, 28 ]
python
en
['en', 'error', 'th']
False
get_waymo_image_info
(path, training=True, label_info=True, velodyne=False, calib=False, pose=False, image_ids=7481, extend_matrix=True, num_worker=8, relative_path=True, with_imageshape=True, max_sweeps=5)
Waymo annotation format version like KITTI: { [optional]points: [N, 3+] point cloud [optional, for kitti]image: { image_idx: ... image_path: ... image_shape: ... } point_cloud: { num_features: 6 velodyne_path: ... } [optional, for kitti]calib: { R0_rect: ... Tr_velo_to_cam0: ... P0: ... } annos: { location: [num_gt, 3] array dimensions: [num_gt, 3] array rotation_y: [num_gt] angle array name: [num_gt] ground truth name array [optional]difficulty: kitti difficulty [optional]group_ids: used for multi-part object } }
Waymo annotation format version like KITTI: { [optional]points: [N, 3+] point cloud [optional, for kitti]image: { image_idx: ... image_path: ... image_shape: ... } point_cloud: { num_features: 6 velodyne_path: ... } [optional, for kitti]calib: { R0_rect: ... Tr_velo_to_cam0: ... P0: ... } annos: { location: [num_gt, 3] array dimensions: [num_gt, 3] array rotation_y: [num_gt] angle array name: [num_gt] ground truth name array [optional]difficulty: kitti difficulty [optional]group_ids: used for multi-part object } }
def get_waymo_image_info(path, training=True, label_info=True, velodyne=False, calib=False, pose=False, image_ids=7481, extend_matrix=True, num_worker=8, relative_path=True, with_imageshape=True, max_sweeps=5): """ Waymo annotation format version like KITTI: { [optional]points: [N, 3+] point cloud [optional, for kitti]image: { image_idx: ... image_path: ... image_shape: ... } point_cloud: { num_features: 6 velodyne_path: ... } [optional, for kitti]calib: { R0_rect: ... Tr_velo_to_cam0: ... P0: ... } annos: { location: [num_gt, 3] array dimensions: [num_gt, 3] array rotation_y: [num_gt] angle array name: [num_gt] ground truth name array [optional]difficulty: kitti difficulty [optional]group_ids: used for multi-part object } } """ root_path = Path(path) if not isinstance(image_ids, list): image_ids = list(range(image_ids)) def map_func(idx): info = {} pc_info = {'num_features': 6} calib_info = {} image_info = {'image_idx': idx} annotations = None if velodyne: pc_info['velodyne_path'] = get_velodyne_path( idx, path, training, relative_path, use_prefix_id=True) points = np.fromfile( Path(path) / pc_info['velodyne_path'], dtype=np.float32) points = np.copy(points).reshape(-1, pc_info['num_features']) info['timestamp'] = np.int64(points[0, -1]) # values of the last dim are all the timestamp image_info['image_path'] = get_image_path( idx, path, training, relative_path, info_type='image_0', use_prefix_id=True) if with_imageshape: img_path = image_info['image_path'] if relative_path: img_path = str(root_path / img_path) image_info['image_shape'] = np.array( io.imread(img_path).shape[:2], dtype=np.int32) if label_info: label_path = get_label_path( idx, path, training, relative_path, info_type='label_all', use_prefix_id=True) if relative_path: label_path = str(root_path / label_path) annotations = get_label_anno(label_path) info['image'] = image_info info['point_cloud'] = pc_info if calib: calib_path = get_calib_path( idx, path, training, relative_path=False, use_prefix_id=True) with open(calib_path, 'r') as f: lines = f.readlines() P0 = np.array([float(info) for info in lines[0].split(' ')[1:13] ]).reshape([3, 4]) P1 = np.array([float(info) for info in lines[1].split(' ')[1:13] ]).reshape([3, 4]) P2 = np.array([float(info) for info in lines[2].split(' ')[1:13] ]).reshape([3, 4]) P3 = np.array([float(info) for info in lines[3].split(' ')[1:13] ]).reshape([3, 4]) P4 = np.array([float(info) for info in lines[4].split(' ')[1:13] ]).reshape([3, 4]) if extend_matrix: P0 = _extend_matrix(P0) P1 = _extend_matrix(P1) P2 = _extend_matrix(P2) P3 = _extend_matrix(P3) P4 = _extend_matrix(P4) R0_rect = np.array([ float(info) for info in lines[5].split(' ')[1:10] ]).reshape([3, 3]) if extend_matrix: rect_4x4 = np.zeros([4, 4], dtype=R0_rect.dtype) rect_4x4[3, 3] = 1. rect_4x4[:3, :3] = R0_rect else: rect_4x4 = R0_rect Tr_velo_to_cam = np.array([ float(info) for info in lines[6].split(' ')[1:13] ]).reshape([3, 4]) if extend_matrix: Tr_velo_to_cam = _extend_matrix(Tr_velo_to_cam) calib_info['P0'] = P0 calib_info['P1'] = P1 calib_info['P2'] = P2 calib_info['P3'] = P3 calib_info['P4'] = P4 calib_info['R0_rect'] = rect_4x4 calib_info['Tr_velo_to_cam'] = Tr_velo_to_cam info['calib'] = calib_info if pose: pose_path = get_pose_path( idx, path, training, relative_path=False, use_prefix_id=True) info['pose'] = np.loadtxt(pose_path) if annotations is not None: info['annos'] = annotations info['annos']['camera_id'] = info['annos'].pop('score') add_difficulty_to_annos(info) sweeps = [] prev_idx = idx while len(sweeps) < max_sweeps: prev_info = {} prev_idx -= 1 prev_info['velodyne_path'] = get_velodyne_path( prev_idx, path, training, relative_path, exist_check=False, use_prefix_id=True) if_prev_exists = osp.exists( Path(path) / prev_info['velodyne_path']) if if_prev_exists: prev_points = np.fromfile( Path(path) / prev_info['velodyne_path'], dtype=np.float32) prev_points = np.copy(prev_points).reshape( -1, pc_info['num_features']) prev_info['timestamp'] = np.int64(prev_points[0, -1]) prev_pose_path = get_pose_path( prev_idx, path, training, relative_path=False, use_prefix_id=True) prev_info['pose'] = np.loadtxt(prev_pose_path) sweeps.append(prev_info) else: break info['sweeps'] = sweeps return info with futures.ThreadPoolExecutor(num_worker) as executor: image_infos = executor.map(map_func, image_ids) return list(image_infos)
[ "def", "get_waymo_image_info", "(", "path", ",", "training", "=", "True", ",", "label_info", "=", "True", ",", "velodyne", "=", "False", ",", "calib", "=", "False", ",", "pose", "=", "False", ",", "image_ids", "=", "7481", ",", "extend_matrix", "=", "True", ",", "num_worker", "=", "8", ",", "relative_path", "=", "True", ",", "with_imageshape", "=", "True", ",", "max_sweeps", "=", "5", ")", ":", "root_path", "=", "Path", "(", "path", ")", "if", "not", "isinstance", "(", "image_ids", ",", "list", ")", ":", "image_ids", "=", "list", "(", "range", "(", "image_ids", ")", ")", "def", "map_func", "(", "idx", ")", ":", "info", "=", "{", "}", "pc_info", "=", "{", "'num_features'", ":", "6", "}", "calib_info", "=", "{", "}", "image_info", "=", "{", "'image_idx'", ":", "idx", "}", "annotations", "=", "None", "if", "velodyne", ":", "pc_info", "[", "'velodyne_path'", "]", "=", "get_velodyne_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", ",", "use_prefix_id", "=", "True", ")", "points", "=", "np", ".", "fromfile", "(", "Path", "(", "path", ")", "/", "pc_info", "[", "'velodyne_path'", "]", ",", "dtype", "=", "np", ".", "float32", ")", "points", "=", "np", ".", "copy", "(", "points", ")", ".", "reshape", "(", "-", "1", ",", "pc_info", "[", "'num_features'", "]", ")", "info", "[", "'timestamp'", "]", "=", "np", ".", "int64", "(", "points", "[", "0", ",", "-", "1", "]", ")", "# values of the last dim are all the timestamp", "image_info", "[", "'image_path'", "]", "=", "get_image_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", ",", "info_type", "=", "'image_0'", ",", "use_prefix_id", "=", "True", ")", "if", "with_imageshape", ":", "img_path", "=", "image_info", "[", "'image_path'", "]", "if", "relative_path", ":", "img_path", "=", "str", "(", "root_path", "/", "img_path", ")", "image_info", "[", "'image_shape'", "]", "=", "np", ".", "array", "(", "io", ".", "imread", "(", "img_path", ")", ".", "shape", "[", ":", "2", "]", ",", "dtype", "=", "np", ".", "int32", ")", "if", "label_info", ":", "label_path", "=", "get_label_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", ",", "info_type", "=", "'label_all'", ",", "use_prefix_id", "=", "True", ")", "if", "relative_path", ":", "label_path", "=", "str", "(", "root_path", "/", "label_path", ")", "annotations", "=", "get_label_anno", "(", "label_path", ")", "info", "[", "'image'", "]", "=", "image_info", "info", "[", "'point_cloud'", "]", "=", "pc_info", "if", "calib", ":", "calib_path", "=", "get_calib_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", "=", "False", ",", "use_prefix_id", "=", "True", ")", "with", "open", "(", "calib_path", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "P0", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "0", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P1", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "1", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P2", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "2", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P3", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "3", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "P4", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "4", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "if", "extend_matrix", ":", "P0", "=", "_extend_matrix", "(", "P0", ")", "P1", "=", "_extend_matrix", "(", "P1", ")", "P2", "=", "_extend_matrix", "(", "P2", ")", "P3", "=", "_extend_matrix", "(", "P3", ")", "P4", "=", "_extend_matrix", "(", "P4", ")", "R0_rect", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "5", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "10", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "3", "]", ")", "if", "extend_matrix", ":", "rect_4x4", "=", "np", ".", "zeros", "(", "[", "4", ",", "4", "]", ",", "dtype", "=", "R0_rect", ".", "dtype", ")", "rect_4x4", "[", "3", ",", "3", "]", "=", "1.", "rect_4x4", "[", ":", "3", ",", ":", "3", "]", "=", "R0_rect", "else", ":", "rect_4x4", "=", "R0_rect", "Tr_velo_to_cam", "=", "np", ".", "array", "(", "[", "float", "(", "info", ")", "for", "info", "in", "lines", "[", "6", "]", ".", "split", "(", "' '", ")", "[", "1", ":", "13", "]", "]", ")", ".", "reshape", "(", "[", "3", ",", "4", "]", ")", "if", "extend_matrix", ":", "Tr_velo_to_cam", "=", "_extend_matrix", "(", "Tr_velo_to_cam", ")", "calib_info", "[", "'P0'", "]", "=", "P0", "calib_info", "[", "'P1'", "]", "=", "P1", "calib_info", "[", "'P2'", "]", "=", "P2", "calib_info", "[", "'P3'", "]", "=", "P3", "calib_info", "[", "'P4'", "]", "=", "P4", "calib_info", "[", "'R0_rect'", "]", "=", "rect_4x4", "calib_info", "[", "'Tr_velo_to_cam'", "]", "=", "Tr_velo_to_cam", "info", "[", "'calib'", "]", "=", "calib_info", "if", "pose", ":", "pose_path", "=", "get_pose_path", "(", "idx", ",", "path", ",", "training", ",", "relative_path", "=", "False", ",", "use_prefix_id", "=", "True", ")", "info", "[", "'pose'", "]", "=", "np", ".", "loadtxt", "(", "pose_path", ")", "if", "annotations", "is", "not", "None", ":", "info", "[", "'annos'", "]", "=", "annotations", "info", "[", "'annos'", "]", "[", "'camera_id'", "]", "=", "info", "[", "'annos'", "]", ".", "pop", "(", "'score'", ")", "add_difficulty_to_annos", "(", "info", ")", "sweeps", "=", "[", "]", "prev_idx", "=", "idx", "while", "len", "(", "sweeps", ")", "<", "max_sweeps", ":", "prev_info", "=", "{", "}", "prev_idx", "-=", "1", "prev_info", "[", "'velodyne_path'", "]", "=", "get_velodyne_path", "(", "prev_idx", ",", "path", ",", "training", ",", "relative_path", ",", "exist_check", "=", "False", ",", "use_prefix_id", "=", "True", ")", "if_prev_exists", "=", "osp", ".", "exists", "(", "Path", "(", "path", ")", "/", "prev_info", "[", "'velodyne_path'", "]", ")", "if", "if_prev_exists", ":", "prev_points", "=", "np", ".", "fromfile", "(", "Path", "(", "path", ")", "/", "prev_info", "[", "'velodyne_path'", "]", ",", "dtype", "=", "np", ".", "float32", ")", "prev_points", "=", "np", ".", "copy", "(", "prev_points", ")", ".", "reshape", "(", "-", "1", ",", "pc_info", "[", "'num_features'", "]", ")", "prev_info", "[", "'timestamp'", "]", "=", "np", ".", "int64", "(", "prev_points", "[", "0", ",", "-", "1", "]", ")", "prev_pose_path", "=", "get_pose_path", "(", "prev_idx", ",", "path", ",", "training", ",", "relative_path", "=", "False", ",", "use_prefix_id", "=", "True", ")", "prev_info", "[", "'pose'", "]", "=", "np", ".", "loadtxt", "(", "prev_pose_path", ")", "sweeps", ".", "append", "(", "prev_info", ")", "else", ":", "break", "info", "[", "'sweeps'", "]", "=", "sweeps", "return", "info", "with", "futures", ".", "ThreadPoolExecutor", "(", "num_worker", ")", "as", "executor", ":", "image_infos", "=", "executor", ".", "map", "(", "map_func", ",", "image_ids", ")", "return", "list", "(", "image_infos", ")" ]
[ 263, 0 ]
[ 439, 28 ]
python
en
['en', 'error', 'th']
False
RouteUpdate.__init__
(self, *, recipient_key: str = None, action: str = None, **kwargs)
Initialize a RouteUpdate instance. Args: recipient_key: The recipient verkey of the route action: The action to perform
Initialize a RouteUpdate instance.
def __init__(self, *, recipient_key: str = None, action: str = None, **kwargs): """ Initialize a RouteUpdate instance. Args: recipient_key: The recipient verkey of the route action: The action to perform """ super(RouteUpdate, self).__init__(**kwargs) self.recipient_key = recipient_key self.action = action
[ "def", "__init__", "(", "self", ",", "*", ",", "recipient_key", ":", "str", "=", "None", ",", "action", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "RouteUpdate", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "self", ".", "recipient_key", "=", "recipient_key", "self", ".", "action", "=", "action" ]
[ 18, 4 ]
[ 29, 28 ]
python
en
['en', 'error', 'th']
False
list_node
(option_generator, select=None, pagesize=10)
Decorator for making an EvMenu node into a multi-page list node. Will add new options, prepending those options added in the node. Args: option_generator (callable or list): A list of strings indicating the options, or a callable that is called as option_generator(caller) to produce such a list. select (callable or str, optional): Node to redirect a selection to. Its `**kwargs` will contain the `available_choices` list and `selection` will hold one of the elements in that list. If a callable, it will be called as select(caller, menuchoice) where menuchoice is the chosen option as a string. Should return the target node to goto after this selection (or None to repeat the list-node). Note that if this is not given, the decorated node must itself provide a way to continue from the node! pagesize (int): How many options to show per page. Example: @list_node(['foo', 'bar'], select) def node_index(caller): text = "describing the list" return text, [] Notes: All normal `goto` or `exec` callables returned from the decorated nodes will, if they accept **kwargs, get a new kwarg 'available_choices' injected. These are the ordered list of named options (descs) visible on the current node page.
Decorator for making an EvMenu node into a multi-page list node. Will add new options, prepending those options added in the node.
def list_node(option_generator, select=None, pagesize=10): """ Decorator for making an EvMenu node into a multi-page list node. Will add new options, prepending those options added in the node. Args: option_generator (callable or list): A list of strings indicating the options, or a callable that is called as option_generator(caller) to produce such a list. select (callable or str, optional): Node to redirect a selection to. Its `**kwargs` will contain the `available_choices` list and `selection` will hold one of the elements in that list. If a callable, it will be called as select(caller, menuchoice) where menuchoice is the chosen option as a string. Should return the target node to goto after this selection (or None to repeat the list-node). Note that if this is not given, the decorated node must itself provide a way to continue from the node! pagesize (int): How many options to show per page. Example: @list_node(['foo', 'bar'], select) def node_index(caller): text = "describing the list" return text, [] Notes: All normal `goto` or `exec` callables returned from the decorated nodes will, if they accept **kwargs, get a new kwarg 'available_choices' injected. These are the ordered list of named options (descs) visible on the current node page. """ def decorator(func): def _select_parser(caller, raw_string, **kwargs): """ Parse the select action """ available_choices = kwargs.get("available_choices", []) try: index = int(raw_string.strip()) - 1 selection = available_choices[index] except Exception: caller.msg("|rInvalid choice.|n") else: if callable(select): try: if bool(getargspec(select).keywords): return select(caller, selection, available_choices=available_choices) else: return select(caller, selection) except Exception: logger.log_trace() elif select: # we assume a string was given, we inject the result into the kwargs # to pass on to the next node kwargs['selection'] = selection return str(select) # this means the previous node will be re-run with these same kwargs return None def _list_node(caller, raw_string, **kwargs): option_list = option_generator(caller) \ if callable(option_generator) else option_generator npages = 0 page_index = 0 page = [] options = [] if option_list: nall_options = len(option_list) pages = [option_list[ind:ind + pagesize] for ind in range(0, nall_options, pagesize)] npages = len(pages) page_index = max(0, min(npages - 1, kwargs.get("optionpage_index", 0))) page = pages[page_index] text = "" extra_text = None # dynamic, multi-page option list. Each selection leads to the `select` # callback being called with a result from the available choices options.extend([{"desc": opt, "goto": (_select_parser, {"available_choices": page})} for opt in page]) if npages > 1: # if the goto callable returns None, the same node is rerun, and # kwargs not used by the callable are passed on to the node. This # allows us to call ourselves over and over, using different kwargs. options.append({"key": ("|Wcurrent|n", "c"), "desc": "|W({}/{})|n".format(page_index + 1, npages), "goto": (lambda caller: None, {"optionpage_index": page_index})}) if page_index > 0: options.append({"key": ("|wp|Wrevious page|n", "p"), "goto": (lambda caller: None, {"optionpage_index": page_index - 1})}) if page_index < npages - 1: options.append({"key": ("|wn|Wext page|n", "n"), "goto": (lambda caller: None, {"optionpage_index": page_index + 1})}) # add data from the decorated node decorated_options = [] supports_kwargs = bool(getargspec(func).keywords) try: if supports_kwargs: text, decorated_options = func(caller, raw_string, **kwargs) else: text, decorated_options = func(caller, raw_string) except TypeError: try: if supports_kwargs: text, decorated_options = func(caller, **kwargs) else: text, decorated_options = func(caller) except Exception: raise except Exception: logger.log_trace() else: if isinstance(decorated_options, dict): decorated_options = [decorated_options] else: decorated_options = make_iter(decorated_options) extra_options = [] if isinstance(decorated_options, dict): decorated_options = [decorated_options] for eopt in decorated_options: cback = ("goto" in eopt and "goto") or ("exec" in eopt and "exec") or None if cback: signature = eopt[cback] if callable(signature): # callable with no kwargs defined eopt[cback] = (signature, {"available_choices": page}) elif is_iter(signature): if len(signature) > 1 and isinstance(signature[1], dict): signature[1]["available_choices"] = page eopt[cback] = signature elif signature: # a callable alone in a tuple (i.e. no previous kwargs) eopt[cback] = (signature[0], {"available_choices": page}) else: # malformed input. logger.log_err("EvMenu @list_node decorator found " "malformed option to decorate: {}".format(eopt)) extra_options.append(eopt) options.extend(extra_options) text = text + "\n\n" + extra_text if extra_text else text return text, options return _list_node return decorator
[ "def", "list_node", "(", "option_generator", ",", "select", "=", "None", ",", "pagesize", "=", "10", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "_select_parser", "(", "caller", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Parse the select action\n \"\"\"", "available_choices", "=", "kwargs", ".", "get", "(", "\"available_choices\"", ",", "[", "]", ")", "try", ":", "index", "=", "int", "(", "raw_string", ".", "strip", "(", ")", ")", "-", "1", "selection", "=", "available_choices", "[", "index", "]", "except", "Exception", ":", "caller", ".", "msg", "(", "\"|rInvalid choice.|n\"", ")", "else", ":", "if", "callable", "(", "select", ")", ":", "try", ":", "if", "bool", "(", "getargspec", "(", "select", ")", ".", "keywords", ")", ":", "return", "select", "(", "caller", ",", "selection", ",", "available_choices", "=", "available_choices", ")", "else", ":", "return", "select", "(", "caller", ",", "selection", ")", "except", "Exception", ":", "logger", ".", "log_trace", "(", ")", "elif", "select", ":", "# we assume a string was given, we inject the result into the kwargs", "# to pass on to the next node", "kwargs", "[", "'selection'", "]", "=", "selection", "return", "str", "(", "select", ")", "# this means the previous node will be re-run with these same kwargs", "return", "None", "def", "_list_node", "(", "caller", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "option_list", "=", "option_generator", "(", "caller", ")", "if", "callable", "(", "option_generator", ")", "else", "option_generator", "npages", "=", "0", "page_index", "=", "0", "page", "=", "[", "]", "options", "=", "[", "]", "if", "option_list", ":", "nall_options", "=", "len", "(", "option_list", ")", "pages", "=", "[", "option_list", "[", "ind", ":", "ind", "+", "pagesize", "]", "for", "ind", "in", "range", "(", "0", ",", "nall_options", ",", "pagesize", ")", "]", "npages", "=", "len", "(", "pages", ")", "page_index", "=", "max", "(", "0", ",", "min", "(", "npages", "-", "1", ",", "kwargs", ".", "get", "(", "\"optionpage_index\"", ",", "0", ")", ")", ")", "page", "=", "pages", "[", "page_index", "]", "text", "=", "\"\"", "extra_text", "=", "None", "# dynamic, multi-page option list. Each selection leads to the `select`", "# callback being called with a result from the available choices", "options", ".", "extend", "(", "[", "{", "\"desc\"", ":", "opt", ",", "\"goto\"", ":", "(", "_select_parser", ",", "{", "\"available_choices\"", ":", "page", "}", ")", "}", "for", "opt", "in", "page", "]", ")", "if", "npages", ">", "1", ":", "# if the goto callable returns None, the same node is rerun, and", "# kwargs not used by the callable are passed on to the node. This", "# allows us to call ourselves over and over, using different kwargs.", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|Wcurrent|n\"", ",", "\"c\"", ")", ",", "\"desc\"", ":", "\"|W({}/{})|n\"", ".", "format", "(", "page_index", "+", "1", ",", "npages", ")", ",", "\"goto\"", ":", "(", "lambda", "caller", ":", "None", ",", "{", "\"optionpage_index\"", ":", "page_index", "}", ")", "}", ")", "if", "page_index", ">", "0", ":", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wp|Wrevious page|n\"", ",", "\"p\"", ")", ",", "\"goto\"", ":", "(", "lambda", "caller", ":", "None", ",", "{", "\"optionpage_index\"", ":", "page_index", "-", "1", "}", ")", "}", ")", "if", "page_index", "<", "npages", "-", "1", ":", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wn|Wext page|n\"", ",", "\"n\"", ")", ",", "\"goto\"", ":", "(", "lambda", "caller", ":", "None", ",", "{", "\"optionpage_index\"", ":", "page_index", "+", "1", "}", ")", "}", ")", "# add data from the decorated node", "decorated_options", "=", "[", "]", "supports_kwargs", "=", "bool", "(", "getargspec", "(", "func", ")", ".", "keywords", ")", "try", ":", "if", "supports_kwargs", ":", "text", ",", "decorated_options", "=", "func", "(", "caller", ",", "raw_string", ",", "*", "*", "kwargs", ")", "else", ":", "text", ",", "decorated_options", "=", "func", "(", "caller", ",", "raw_string", ")", "except", "TypeError", ":", "try", ":", "if", "supports_kwargs", ":", "text", ",", "decorated_options", "=", "func", "(", "caller", ",", "*", "*", "kwargs", ")", "else", ":", "text", ",", "decorated_options", "=", "func", "(", "caller", ")", "except", "Exception", ":", "raise", "except", "Exception", ":", "logger", ".", "log_trace", "(", ")", "else", ":", "if", "isinstance", "(", "decorated_options", ",", "dict", ")", ":", "decorated_options", "=", "[", "decorated_options", "]", "else", ":", "decorated_options", "=", "make_iter", "(", "decorated_options", ")", "extra_options", "=", "[", "]", "if", "isinstance", "(", "decorated_options", ",", "dict", ")", ":", "decorated_options", "=", "[", "decorated_options", "]", "for", "eopt", "in", "decorated_options", ":", "cback", "=", "(", "\"goto\"", "in", "eopt", "and", "\"goto\"", ")", "or", "(", "\"exec\"", "in", "eopt", "and", "\"exec\"", ")", "or", "None", "if", "cback", ":", "signature", "=", "eopt", "[", "cback", "]", "if", "callable", "(", "signature", ")", ":", "# callable with no kwargs defined", "eopt", "[", "cback", "]", "=", "(", "signature", ",", "{", "\"available_choices\"", ":", "page", "}", ")", "elif", "is_iter", "(", "signature", ")", ":", "if", "len", "(", "signature", ")", ">", "1", "and", "isinstance", "(", "signature", "[", "1", "]", ",", "dict", ")", ":", "signature", "[", "1", "]", "[", "\"available_choices\"", "]", "=", "page", "eopt", "[", "cback", "]", "=", "signature", "elif", "signature", ":", "# a callable alone in a tuple (i.e. no previous kwargs)", "eopt", "[", "cback", "]", "=", "(", "signature", "[", "0", "]", ",", "{", "\"available_choices\"", ":", "page", "}", ")", "else", ":", "# malformed input.", "logger", ".", "log_err", "(", "\"EvMenu @list_node decorator found \"", "\"malformed option to decorate: {}\"", ".", "format", "(", "eopt", ")", ")", "extra_options", ".", "append", "(", "eopt", ")", "options", ".", "extend", "(", "extra_options", ")", "text", "=", "text", "+", "\"\\n\\n\"", "+", "extra_text", "if", "extra_text", "else", "text", "return", "text", ",", "options", "return", "_list_node", "return", "decorator" ]
[ 1068, 0 ]
[ 1226, 20 ]
python
en
['en', 'error', 'th']
False
get_input
(caller, prompt, callback, session=None, *args, **kwargs)
This is a helper function for easily request input from the caller. Args: caller (Account or Object): The entity being asked the question. This should usually be an object controlled by a user. prompt (str): This text will be shown to the user, in order to let them know their input is needed. callback (callable): A function that will be called when the user enters a reply. It must take three arguments: the `caller`, the `prompt` text and the `result` of the input given by the user. If the callback doesn't return anything or return False, the input prompt will be cleaned up and exited. If returning True, the prompt will remain and continue to accept input. session (Session, optional): This allows to specify the session to send the prompt to. It's usually only needed if `caller` is an Account in multisession modes greater than 2. The session is then updated by the command and is available (for example in callbacks) through `caller.ndb.getinput._session`. *args, **kwargs (optional): Extra arguments will be passed to the fall back function as a list 'args' and all keyword arguments as a dictionary 'kwargs'. To utilise *args and **kwargs, a value for the session argument must be provided (None by default) and the callback function must take *args and **kwargs as arguments. Raises: RuntimeError: If the given callback is not callable. Notes: The result value sent to the callback is raw and not processed in any way. This means that you will get the ending line return character from most types of client inputs. So make sure to strip that before doing a comparison. When the prompt is running, a temporary object `caller.ndb._getinput` is stored; this will be removed when the prompt finishes. If you need the specific Session of the caller (which may not be easy to get if caller is an account in higher multisession modes), then it is available in the callback through `caller.ndb._getinput._session`. Chaining get_input functions will result in the caller stacking ever more instances of InputCmdSets. Whilst they will all be cleared on concluding the get_input chain, EvMenu should be considered for anything beyond a single question.
This is a helper function for easily request input from the caller.
def get_input(caller, prompt, callback, session=None, *args, **kwargs): """ This is a helper function for easily request input from the caller. Args: caller (Account or Object): The entity being asked the question. This should usually be an object controlled by a user. prompt (str): This text will be shown to the user, in order to let them know their input is needed. callback (callable): A function that will be called when the user enters a reply. It must take three arguments: the `caller`, the `prompt` text and the `result` of the input given by the user. If the callback doesn't return anything or return False, the input prompt will be cleaned up and exited. If returning True, the prompt will remain and continue to accept input. session (Session, optional): This allows to specify the session to send the prompt to. It's usually only needed if `caller` is an Account in multisession modes greater than 2. The session is then updated by the command and is available (for example in callbacks) through `caller.ndb.getinput._session`. *args, **kwargs (optional): Extra arguments will be passed to the fall back function as a list 'args' and all keyword arguments as a dictionary 'kwargs'. To utilise *args and **kwargs, a value for the session argument must be provided (None by default) and the callback function must take *args and **kwargs as arguments. Raises: RuntimeError: If the given callback is not callable. Notes: The result value sent to the callback is raw and not processed in any way. This means that you will get the ending line return character from most types of client inputs. So make sure to strip that before doing a comparison. When the prompt is running, a temporary object `caller.ndb._getinput` is stored; this will be removed when the prompt finishes. If you need the specific Session of the caller (which may not be easy to get if caller is an account in higher multisession modes), then it is available in the callback through `caller.ndb._getinput._session`. Chaining get_input functions will result in the caller stacking ever more instances of InputCmdSets. Whilst they will all be cleared on concluding the get_input chain, EvMenu should be considered for anything beyond a single question. """ if not callable(callback): raise RuntimeError("get_input: input callback is not callable.") caller.ndb._getinput = _Prompt() caller.ndb._getinput._callback = callback caller.ndb._getinput._prompt = prompt caller.ndb._getinput._session = session caller.ndb._getinput._args = args caller.ndb._getinput._kwargs = kwargs caller.cmdset.add(InputCmdSet) caller.msg(prompt, session=session)
[ "def", "get_input", "(", "caller", ",", "prompt", ",", "callback", ",", "session", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "callable", "(", "callback", ")", ":", "raise", "RuntimeError", "(", "\"get_input: input callback is not callable.\"", ")", "caller", ".", "ndb", ".", "_getinput", "=", "_Prompt", "(", ")", "caller", ".", "ndb", ".", "_getinput", ".", "_callback", "=", "callback", "caller", ".", "ndb", ".", "_getinput", ".", "_prompt", "=", "prompt", "caller", ".", "ndb", ".", "_getinput", ".", "_session", "=", "session", "caller", ".", "ndb", ".", "_getinput", ".", "_args", "=", "args", "caller", ".", "ndb", ".", "_getinput", ".", "_kwargs", "=", "kwargs", "caller", ".", "cmdset", ".", "add", "(", "InputCmdSet", ")", "caller", ".", "msg", "(", "prompt", ",", "session", "=", "session", ")" ]
[ 1292, 0 ]
[ 1359, 39 ]
python
en
['en', 'error', 'th']
False
CmdEvMenuNode.func
(self)
Implement all menu commands.
Implement all menu commands.
def func(self): """ Implement all menu commands. """ def _restore(caller): # check if there is a saved menu available. # this will re-start a completely new evmenu call. saved_options = caller.attributes.get("_menutree_saved") if saved_options: startnode_tuple = caller.attributes.get("_menutree_saved_startnode") try: startnode, startnode_input = startnode_tuple except ValueError: # old form of startnode store startnode, startnode_input = startnode_tuple, "" if startnode: saved_options[2]["startnode"] = startnode saved_options[2]["startnode_input"] = startnode_input MenuClass = saved_options[0] # this will create a completely new menu call MenuClass(caller, *saved_options[1], **saved_options[2]) return True return None caller = self.caller # we store Session on the menu since this can be hard to # get in multisession environemtns if caller is an Account. menu = caller.ndb._menutree if not menu: if _restore(caller): return orig_caller = caller caller = caller.account if hasattr(caller, "account") else None menu = caller.ndb._menutree if caller else None if not menu: if caller and _restore(caller): return caller = self.session menu = caller.ndb._menutree if not menu: # can't restore from a session err = "Menu object not found as %s.ndb._menutree!" % orig_caller orig_caller.msg(err) # don't give the session as a kwarg here, direct to original raise EvMenuError(err) # we must do this after the caller with the menu has been correctly identified since it # can be either Account, Object or Session (in the latter case this info will be superfluous). caller.ndb._menutree._session = self.session # we have a menu, use it. menu.parse_input(self.raw_string)
[ "def", "func", "(", "self", ")", ":", "def", "_restore", "(", "caller", ")", ":", "# check if there is a saved menu available.", "# this will re-start a completely new evmenu call.", "saved_options", "=", "caller", ".", "attributes", ".", "get", "(", "\"_menutree_saved\"", ")", "if", "saved_options", ":", "startnode_tuple", "=", "caller", ".", "attributes", ".", "get", "(", "\"_menutree_saved_startnode\"", ")", "try", ":", "startnode", ",", "startnode_input", "=", "startnode_tuple", "except", "ValueError", ":", "# old form of startnode store", "startnode", ",", "startnode_input", "=", "startnode_tuple", ",", "\"\"", "if", "startnode", ":", "saved_options", "[", "2", "]", "[", "\"startnode\"", "]", "=", "startnode", "saved_options", "[", "2", "]", "[", "\"startnode_input\"", "]", "=", "startnode_input", "MenuClass", "=", "saved_options", "[", "0", "]", "# this will create a completely new menu call", "MenuClass", "(", "caller", ",", "*", "saved_options", "[", "1", "]", ",", "*", "*", "saved_options", "[", "2", "]", ")", "return", "True", "return", "None", "caller", "=", "self", ".", "caller", "# we store Session on the menu since this can be hard to", "# get in multisession environemtns if caller is an Account.", "menu", "=", "caller", ".", "ndb", ".", "_menutree", "if", "not", "menu", ":", "if", "_restore", "(", "caller", ")", ":", "return", "orig_caller", "=", "caller", "caller", "=", "caller", ".", "account", "if", "hasattr", "(", "caller", ",", "\"account\"", ")", "else", "None", "menu", "=", "caller", ".", "ndb", ".", "_menutree", "if", "caller", "else", "None", "if", "not", "menu", ":", "if", "caller", "and", "_restore", "(", "caller", ")", ":", "return", "caller", "=", "self", ".", "session", "menu", "=", "caller", ".", "ndb", ".", "_menutree", "if", "not", "menu", ":", "# can't restore from a session", "err", "=", "\"Menu object not found as %s.ndb._menutree!\"", "%", "orig_caller", "orig_caller", ".", "msg", "(", "err", ")", "# don't give the session as a kwarg here, direct to original", "raise", "EvMenuError", "(", "err", ")", "# we must do this after the caller with the menu has been correctly identified since it", "# can be either Account, Object or Session (in the latter case this info will be superfluous).", "caller", ".", "ndb", ".", "_menutree", ".", "_session", "=", "self", ".", "session", "# we have a menu, use it.", "menu", ".", "parse_input", "(", "self", ".", "raw_string", ")" ]
[ 237, 4 ]
[ 284, 41 ]
python
en
['en', 'error', 'th']
False
EvMenuCmdSet.at_cmdset_creation
(self)
Called when creating the set.
Called when creating the set.
def at_cmdset_creation(self): """ Called when creating the set. """ self.add(CmdEvMenuNode())
[ "def", "at_cmdset_creation", "(", "self", ")", ":", "self", ".", "add", "(", "CmdEvMenuNode", "(", ")", ")" ]
[ 299, 4 ]
[ 303, 33 ]
python
en
['en', 'error', 'th']
False
EvMenu.__init__
(self, caller, menudata, startnode="start", cmdset_mergetype="Replace", cmdset_priority=1, auto_quit=True, auto_look=True, auto_help=True, cmd_on_exit="look", persistent=False, startnode_input="", session=None, debug=False, **kwargs)
Initialize the menu tree and start the caller onto the first node. Args: caller (Object, Account or Session): The user of the menu. menudata (str, module or dict): The full or relative path to the module holding the menu tree data. All global functions in this module whose name doesn't start with '_ ' will be parsed as menu nodes. Also the module itself is accepted as input. Finally, a dictionary menu tree can be given directly. This must then be a mapping `{"nodekey":callable,...}` where `callable` must be called as and return the data expected of a menu node. This allows for dynamic menu creation. startnode (str, optional): The starting node name in the menufile. cmdset_mergetype (str, optional): 'Replace' (default) means the menu commands will be exclusive - no other normal commands will be usable while the user is in the menu. 'Union' means the menu commands will be integrated with the existing commands (it will merge with `merge_priority`), if so, make sure that the menu's command names don't collide with existing commands in an unexpected way. Also the CMD_NOMATCH and CMD_NOINPUT will be overloaded by the menu cmdset. Other cmdser mergetypes has little purpose for the menu. cmdset_priority (int, optional): The merge priority for the menu command set. The default (1) is usually enough for most types of menus. auto_quit (bool, optional): Allow user to use "q", "quit" or "exit" to leave the menu at any point. Recommended during development! auto_look (bool, optional): Automatically make "looK" or "l" to re-show the last node. Turning this off means you have to handle re-showing nodes yourself, but may be useful if you need to use "l" for some other purpose. auto_help (bool, optional): Automatically make "help" or "h" show the current help entry for the node. If turned off, eventual help must be handled manually, but it may be useful if you need 'h' for some other purpose, for example. cmd_on_exit (callable, str or None, optional): When exiting the menu (either by reaching a node with no options or by using the in-built quit command (activated with `allow_quit`), this callback function or command string will be executed. The callback function takes two parameters, the caller then the EvMenu object. This is called after cleanup is complete. Set to None to not call any command. persistent (bool, optional): Make the Menu persistent (i.e. it will survive a reload. This will make the Menu cmdset persistent. Use with caution - if your menu is buggy you may end up in a state you can't get out of! Also note that persistent mode requires that all formatters, menu nodes and callables are possible to *pickle*. When the server is reloaded, the latest node shown will be completely re-run with the same input arguments - so be careful if you are counting up some persistent counter or similar - the counter may be run twice if reload happens on the node that does that. Note that if `debug` is True, this setting is ignored and assumed to be False. startnode_input (str or (str, dict), optional): Send an input text to `startnode` as if a user input text from a fictional previous node. If including the dict, this will be passed as **kwargs to that node. When the server reloads, the latest visited node will be re-run as `node(caller, raw_string, **kwargs)`. session (Session, optional): This is useful when calling EvMenu from an account in multisession mode > 2. Note that this session only really relevant for the very first display of the first node - after that, EvMenu itself will keep the session updated from the command input. So a persistent menu will *not* be using this same session anymore after a reload. debug (bool, optional): If set, the 'menudebug' command will be made available by default in all nodes of the menu. This will print out the current state of the menu. Deactivate for production use! When the debug flag is active, the `persistent` flag is deactivated. Kwargs: any (any): All kwargs will become initialization variables on `caller.ndb._menutree`, to be available at run. Raises: EvMenuError: If the start/end node is not found in menu tree. Notes: While running, the menu is stored on the caller as `caller.ndb._menutree`. Also the current Session (from the Command, so this is still valid in multisession environments) is available through `caller.ndb._menutree._session`. The `_menutree` property is a good one for storing intermediary data on between nodes since it will be automatically deleted when the menu closes. In persistent mode, all nodes, formatters and callbacks in the menu must be possible to be *pickled*, this excludes e.g. callables that are class methods or functions defined dynamically or as part of another function. In non-persistent mode no such restrictions exist.
Initialize the menu tree and start the caller onto the first node.
def __init__(self, caller, menudata, startnode="start", cmdset_mergetype="Replace", cmdset_priority=1, auto_quit=True, auto_look=True, auto_help=True, cmd_on_exit="look", persistent=False, startnode_input="", session=None, debug=False, **kwargs): """ Initialize the menu tree and start the caller onto the first node. Args: caller (Object, Account or Session): The user of the menu. menudata (str, module or dict): The full or relative path to the module holding the menu tree data. All global functions in this module whose name doesn't start with '_ ' will be parsed as menu nodes. Also the module itself is accepted as input. Finally, a dictionary menu tree can be given directly. This must then be a mapping `{"nodekey":callable,...}` where `callable` must be called as and return the data expected of a menu node. This allows for dynamic menu creation. startnode (str, optional): The starting node name in the menufile. cmdset_mergetype (str, optional): 'Replace' (default) means the menu commands will be exclusive - no other normal commands will be usable while the user is in the menu. 'Union' means the menu commands will be integrated with the existing commands (it will merge with `merge_priority`), if so, make sure that the menu's command names don't collide with existing commands in an unexpected way. Also the CMD_NOMATCH and CMD_NOINPUT will be overloaded by the menu cmdset. Other cmdser mergetypes has little purpose for the menu. cmdset_priority (int, optional): The merge priority for the menu command set. The default (1) is usually enough for most types of menus. auto_quit (bool, optional): Allow user to use "q", "quit" or "exit" to leave the menu at any point. Recommended during development! auto_look (bool, optional): Automatically make "looK" or "l" to re-show the last node. Turning this off means you have to handle re-showing nodes yourself, but may be useful if you need to use "l" for some other purpose. auto_help (bool, optional): Automatically make "help" or "h" show the current help entry for the node. If turned off, eventual help must be handled manually, but it may be useful if you need 'h' for some other purpose, for example. cmd_on_exit (callable, str or None, optional): When exiting the menu (either by reaching a node with no options or by using the in-built quit command (activated with `allow_quit`), this callback function or command string will be executed. The callback function takes two parameters, the caller then the EvMenu object. This is called after cleanup is complete. Set to None to not call any command. persistent (bool, optional): Make the Menu persistent (i.e. it will survive a reload. This will make the Menu cmdset persistent. Use with caution - if your menu is buggy you may end up in a state you can't get out of! Also note that persistent mode requires that all formatters, menu nodes and callables are possible to *pickle*. When the server is reloaded, the latest node shown will be completely re-run with the same input arguments - so be careful if you are counting up some persistent counter or similar - the counter may be run twice if reload happens on the node that does that. Note that if `debug` is True, this setting is ignored and assumed to be False. startnode_input (str or (str, dict), optional): Send an input text to `startnode` as if a user input text from a fictional previous node. If including the dict, this will be passed as **kwargs to that node. When the server reloads, the latest visited node will be re-run as `node(caller, raw_string, **kwargs)`. session (Session, optional): This is useful when calling EvMenu from an account in multisession mode > 2. Note that this session only really relevant for the very first display of the first node - after that, EvMenu itself will keep the session updated from the command input. So a persistent menu will *not* be using this same session anymore after a reload. debug (bool, optional): If set, the 'menudebug' command will be made available by default in all nodes of the menu. This will print out the current state of the menu. Deactivate for production use! When the debug flag is active, the `persistent` flag is deactivated. Kwargs: any (any): All kwargs will become initialization variables on `caller.ndb._menutree`, to be available at run. Raises: EvMenuError: If the start/end node is not found in menu tree. Notes: While running, the menu is stored on the caller as `caller.ndb._menutree`. Also the current Session (from the Command, so this is still valid in multisession environments) is available through `caller.ndb._menutree._session`. The `_menutree` property is a good one for storing intermediary data on between nodes since it will be automatically deleted when the menu closes. In persistent mode, all nodes, formatters and callbacks in the menu must be possible to be *pickled*, this excludes e.g. callables that are class methods or functions defined dynamically or as part of another function. In non-persistent mode no such restrictions exist. """ self._startnode = startnode self._menutree = self._parse_menudata(menudata) self._persistent = persistent if not debug else False self._quitting = False if startnode not in self._menutree: raise EvMenuError("Start node '%s' not in menu tree!" % startnode) # public variables made available to the command self.caller = caller # track EvMenu kwargs self.auto_quit = auto_quit self.auto_look = auto_look self.auto_help = auto_help self.debug_mode = debug self._session = session if isinstance(cmd_on_exit, str): # At this point menu._session will have been replaced by the # menu command to the actual session calling. self.cmd_on_exit = lambda caller, menu: caller.execute_cmd(cmd_on_exit, session=menu._session) elif callable(cmd_on_exit): self.cmd_on_exit = cmd_on_exit else: self.cmd_on_exit = None # current menu state self.default = None self.nodetext = None self.helptext = None self.options = None self.nodename = None self.node_kwargs = {} # used for testing self.test_options = {} self.test_nodetext = "" # assign kwargs as initialization vars on ourselves. if set(("_startnode", "_menutree", "_session", "_persistent", "cmd_on_exit", "default", "nodetext", "helptext", "options", "cmdset_mergetype", "auto_quit")).intersection(set(kwargs.keys())): raise RuntimeError("One or more of the EvMenu `**kwargs` is reserved by EvMenu for internal use.") for key, val in kwargs.iteritems(): setattr(self, key, val) # if self.caller.ndb._menutree: # an evmenu already exists - we try to close it cleanly. Note that this will # not fire the previous menu's end node. try: self.caller.ndb._menutree.close_menu() except Exception: pass # store ourself on the object self.caller.ndb._menutree = self if persistent: # save the menu to the database calldict = {"startnode": startnode, "cmdset_mergetype": cmdset_mergetype, "cmdset_priority": cmdset_priority, "auto_quit": auto_quit, "auto_look": auto_look, "auto_help": auto_help, "cmd_on_exit": cmd_on_exit, "persistent": persistent} calldict.update(kwargs) try: caller.attributes.add("_menutree_saved", (self.__class__, (menudata, ), calldict)) caller.attributes.add("_menutree_saved_startnode", (startnode, startnode_input)) except Exception as err: caller.msg(_ERROR_PERSISTENT_SAVING.format(error=err), session=self._session) logger.log_trace(_TRACE_PERSISTENT_SAVING) persistent = False # set up the menu command on the caller menu_cmdset = EvMenuCmdSet() menu_cmdset.mergetype = str(cmdset_mergetype).lower().capitalize() or "Replace" menu_cmdset.priority = int(cmdset_priority) self.caller.cmdset.add(menu_cmdset, permanent=persistent) startnode_kwargs = {} if isinstance(startnode_input, (tuple, list)) and len(startnode_input) > 1: startnode_input, startnode_kwargs = startnode_input[:2] if not isinstance(startnode_kwargs, dict): raise EvMenuError("startnode_input must be either a str or a tuple (str, dict).") # start the menu self.goto(self._startnode, startnode_input, **startnode_kwargs)
[ "def", "__init__", "(", "self", ",", "caller", ",", "menudata", ",", "startnode", "=", "\"start\"", ",", "cmdset_mergetype", "=", "\"Replace\"", ",", "cmdset_priority", "=", "1", ",", "auto_quit", "=", "True", ",", "auto_look", "=", "True", ",", "auto_help", "=", "True", ",", "cmd_on_exit", "=", "\"look\"", ",", "persistent", "=", "False", ",", "startnode_input", "=", "\"\"", ",", "session", "=", "None", ",", "debug", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_startnode", "=", "startnode", "self", ".", "_menutree", "=", "self", ".", "_parse_menudata", "(", "menudata", ")", "self", ".", "_persistent", "=", "persistent", "if", "not", "debug", "else", "False", "self", ".", "_quitting", "=", "False", "if", "startnode", "not", "in", "self", ".", "_menutree", ":", "raise", "EvMenuError", "(", "\"Start node '%s' not in menu tree!\"", "%", "startnode", ")", "# public variables made available to the command", "self", ".", "caller", "=", "caller", "# track EvMenu kwargs", "self", ".", "auto_quit", "=", "auto_quit", "self", ".", "auto_look", "=", "auto_look", "self", ".", "auto_help", "=", "auto_help", "self", ".", "debug_mode", "=", "debug", "self", ".", "_session", "=", "session", "if", "isinstance", "(", "cmd_on_exit", ",", "str", ")", ":", "# At this point menu._session will have been replaced by the", "# menu command to the actual session calling.", "self", ".", "cmd_on_exit", "=", "lambda", "caller", ",", "menu", ":", "caller", ".", "execute_cmd", "(", "cmd_on_exit", ",", "session", "=", "menu", ".", "_session", ")", "elif", "callable", "(", "cmd_on_exit", ")", ":", "self", ".", "cmd_on_exit", "=", "cmd_on_exit", "else", ":", "self", ".", "cmd_on_exit", "=", "None", "# current menu state", "self", ".", "default", "=", "None", "self", ".", "nodetext", "=", "None", "self", ".", "helptext", "=", "None", "self", ".", "options", "=", "None", "self", ".", "nodename", "=", "None", "self", ".", "node_kwargs", "=", "{", "}", "# used for testing", "self", ".", "test_options", "=", "{", "}", "self", ".", "test_nodetext", "=", "\"\"", "# assign kwargs as initialization vars on ourselves.", "if", "set", "(", "(", "\"_startnode\"", ",", "\"_menutree\"", ",", "\"_session\"", ",", "\"_persistent\"", ",", "\"cmd_on_exit\"", ",", "\"default\"", ",", "\"nodetext\"", ",", "\"helptext\"", ",", "\"options\"", ",", "\"cmdset_mergetype\"", ",", "\"auto_quit\"", ")", ")", ".", "intersection", "(", "set", "(", "kwargs", ".", "keys", "(", ")", ")", ")", ":", "raise", "RuntimeError", "(", "\"One or more of the EvMenu `**kwargs` is reserved by EvMenu for internal use.\"", ")", "for", "key", ",", "val", "in", "kwargs", ".", "iteritems", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "val", ")", "#", "if", "self", ".", "caller", ".", "ndb", ".", "_menutree", ":", "# an evmenu already exists - we try to close it cleanly. Note that this will", "# not fire the previous menu's end node.", "try", ":", "self", ".", "caller", ".", "ndb", ".", "_menutree", ".", "close_menu", "(", ")", "except", "Exception", ":", "pass", "# store ourself on the object", "self", ".", "caller", ".", "ndb", ".", "_menutree", "=", "self", "if", "persistent", ":", "# save the menu to the database", "calldict", "=", "{", "\"startnode\"", ":", "startnode", ",", "\"cmdset_mergetype\"", ":", "cmdset_mergetype", ",", "\"cmdset_priority\"", ":", "cmdset_priority", ",", "\"auto_quit\"", ":", "auto_quit", ",", "\"auto_look\"", ":", "auto_look", ",", "\"auto_help\"", ":", "auto_help", ",", "\"cmd_on_exit\"", ":", "cmd_on_exit", ",", "\"persistent\"", ":", "persistent", "}", "calldict", ".", "update", "(", "kwargs", ")", "try", ":", "caller", ".", "attributes", ".", "add", "(", "\"_menutree_saved\"", ",", "(", "self", ".", "__class__", ",", "(", "menudata", ",", ")", ",", "calldict", ")", ")", "caller", ".", "attributes", ".", "add", "(", "\"_menutree_saved_startnode\"", ",", "(", "startnode", ",", "startnode_input", ")", ")", "except", "Exception", "as", "err", ":", "caller", ".", "msg", "(", "_ERROR_PERSISTENT_SAVING", ".", "format", "(", "error", "=", "err", ")", ",", "session", "=", "self", ".", "_session", ")", "logger", ".", "log_trace", "(", "_TRACE_PERSISTENT_SAVING", ")", "persistent", "=", "False", "# set up the menu command on the caller", "menu_cmdset", "=", "EvMenuCmdSet", "(", ")", "menu_cmdset", ".", "mergetype", "=", "str", "(", "cmdset_mergetype", ")", ".", "lower", "(", ")", ".", "capitalize", "(", ")", "or", "\"Replace\"", "menu_cmdset", ".", "priority", "=", "int", "(", "cmdset_priority", ")", "self", ".", "caller", ".", "cmdset", ".", "add", "(", "menu_cmdset", ",", "permanent", "=", "persistent", ")", "startnode_kwargs", "=", "{", "}", "if", "isinstance", "(", "startnode_input", ",", "(", "tuple", ",", "list", ")", ")", "and", "len", "(", "startnode_input", ")", ">", "1", ":", "startnode_input", ",", "startnode_kwargs", "=", "startnode_input", "[", ":", "2", "]", "if", "not", "isinstance", "(", "startnode_kwargs", ",", "dict", ")", ":", "raise", "EvMenuError", "(", "\"startnode_input must be either a str or a tuple (str, dict).\"", ")", "# start the menu", "self", ".", "goto", "(", "self", ".", "_startnode", ",", "startnode_input", ",", "*", "*", "startnode_kwargs", ")" ]
[ 320, 4 ]
[ 503, 71 ]
python
en
['en', 'error', 'th']
False
EvMenu._parse_menudata
(self, menudata)
Parse a menufile for node functions and store in dictionary map. Alternatively, accept a pre-made mapping dictionary of node functions. Args: menudata (str, module or dict): The python.path to the menufile, or the python module itself. If a dict, this should be a mapping nodename:callable, where the callable must match the criteria for a menu node. Returns: menutree (dict): A {nodekey: func}
Parse a menufile for node functions and store in dictionary map. Alternatively, accept a pre-made mapping dictionary of node functions.
def _parse_menudata(self, menudata): """ Parse a menufile for node functions and store in dictionary map. Alternatively, accept a pre-made mapping dictionary of node functions. Args: menudata (str, module or dict): The python.path to the menufile, or the python module itself. If a dict, this should be a mapping nodename:callable, where the callable must match the criteria for a menu node. Returns: menutree (dict): A {nodekey: func} """ if isinstance(menudata, dict): # This is assumed to be a pre-loaded menu tree. return menudata else: # a python path of a module module = mod_import(menudata) return dict((key, func) for key, func in module.__dict__.items() if isfunction(func) and not key.startswith("_"))
[ "def", "_parse_menudata", "(", "self", ",", "menudata", ")", ":", "if", "isinstance", "(", "menudata", ",", "dict", ")", ":", "# This is assumed to be a pre-loaded menu tree.", "return", "menudata", "else", ":", "# a python path of a module", "module", "=", "mod_import", "(", "menudata", ")", "return", "dict", "(", "(", "key", ",", "func", ")", "for", "key", ",", "func", "in", "module", ".", "__dict__", ".", "items", "(", ")", "if", "isfunction", "(", "func", ")", "and", "not", "key", ".", "startswith", "(", "\"_\"", ")", ")" ]
[ 505, 4 ]
[ 528, 72 ]
python
en
['en', 'error', 'th']
False
EvMenu._format_node
(self, nodetext, optionlist)
Format the node text + option section Args: nodetext (str): The node text optionlist (list): List of (key, desc) pairs. Returns: string (str): The options section, including all needed spaces. Notes: This will adjust the columns of the options, first to use a maxiumum of 4 rows (expanding in columns), then gradually growing to make use of the screen space.
Format the node text + option section
def _format_node(self, nodetext, optionlist): """ Format the node text + option section Args: nodetext (str): The node text optionlist (list): List of (key, desc) pairs. Returns: string (str): The options section, including all needed spaces. Notes: This will adjust the columns of the options, first to use a maxiumum of 4 rows (expanding in columns), then gradually growing to make use of the screen space. """ # handle the node text nodetext = self.nodetext_formatter(nodetext) # handle the options optionstext = self.options_formatter(optionlist) # format the entire node return self.node_formatter(nodetext, optionstext)
[ "def", "_format_node", "(", "self", ",", "nodetext", ",", "optionlist", ")", ":", "# handle the node text", "nodetext", "=", "self", ".", "nodetext_formatter", "(", "nodetext", ")", "# handle the options", "optionstext", "=", "self", ".", "options_formatter", "(", "optionlist", ")", "# format the entire node", "return", "self", ".", "node_formatter", "(", "nodetext", ",", "optionstext", ")" ]
[ 530, 4 ]
[ 556, 57 ]
python
en
['en', 'error', 'th']
False
EvMenu._safe_call
(self, callback, raw_string, **kwargs)
Call a node-like callable, with a variable number of raw_string, *args, **kwargs, all of which should work also if not present (only `caller` is always required). Return its result.
Call a node-like callable, with a variable number of raw_string, *args, **kwargs, all of which should work also if not present (only `caller` is always required). Return its result.
def _safe_call(self, callback, raw_string, **kwargs): """ Call a node-like callable, with a variable number of raw_string, *args, **kwargs, all of which should work also if not present (only `caller` is always required). Return its result. """ try: try: nargs = len(getargspec(callback).args) except TypeError: raise EvMenuError("Callable {} doesn't accept any arguments!".format(callback)) supports_kwargs = bool(getargspec(callback).keywords) if nargs <= 0: raise EvMenuError("Callable {} doesn't accept any arguments!".format(callback)) if supports_kwargs: if nargs > 1: ret = callback(self.caller, raw_string, **kwargs) # callback accepting raw_string, **kwargs else: # callback accepting **kwargs ret = callback(self.caller, **kwargs) elif nargs > 1: # callback accepting raw_string ret = callback(self.caller, raw_string) else: # normal callback, only the caller as arg ret = callback(self.caller) except EvMenuError: errmsg = _ERR_GENERAL.format(nodename=callback) self.caller.msg(errmsg, self._session) logger.log_trace() raise return ret
[ "def", "_safe_call", "(", "self", ",", "callback", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "try", ":", "try", ":", "nargs", "=", "len", "(", "getargspec", "(", "callback", ")", ".", "args", ")", "except", "TypeError", ":", "raise", "EvMenuError", "(", "\"Callable {} doesn't accept any arguments!\"", ".", "format", "(", "callback", ")", ")", "supports_kwargs", "=", "bool", "(", "getargspec", "(", "callback", ")", ".", "keywords", ")", "if", "nargs", "<=", "0", ":", "raise", "EvMenuError", "(", "\"Callable {} doesn't accept any arguments!\"", ".", "format", "(", "callback", ")", ")", "if", "supports_kwargs", ":", "if", "nargs", ">", "1", ":", "ret", "=", "callback", "(", "self", ".", "caller", ",", "raw_string", ",", "*", "*", "kwargs", ")", "# callback accepting raw_string, **kwargs", "else", ":", "# callback accepting **kwargs", "ret", "=", "callback", "(", "self", ".", "caller", ",", "*", "*", "kwargs", ")", "elif", "nargs", ">", "1", ":", "# callback accepting raw_string", "ret", "=", "callback", "(", "self", ".", "caller", ",", "raw_string", ")", "else", ":", "# normal callback, only the caller as arg", "ret", "=", "callback", "(", "self", ".", "caller", ")", "except", "EvMenuError", ":", "errmsg", "=", "_ERR_GENERAL", ".", "format", "(", "nodename", "=", "callback", ")", "self", ".", "caller", ".", "msg", "(", "errmsg", ",", "self", ".", "_session", ")", "logger", ".", "log_trace", "(", ")", "raise", "return", "ret" ]
[ 558, 4 ]
[ 592, 18 ]
python
en
['en', 'error', 'th']
False
EvMenu._execute_node
(self, nodename, raw_string, **kwargs)
Execute a node. Args: nodename (str): Name of node. raw_string (str): The raw default string entered on the previous node (only used if the node accepts it as an argument) kwargs (any, optional): Optional kwargs for the node. Returns: nodetext, options (tuple): The node text (a string or a tuple and the options tuple, if any.
Execute a node.
def _execute_node(self, nodename, raw_string, **kwargs): """ Execute a node. Args: nodename (str): Name of node. raw_string (str): The raw default string entered on the previous node (only used if the node accepts it as an argument) kwargs (any, optional): Optional kwargs for the node. Returns: nodetext, options (tuple): The node text (a string or a tuple and the options tuple, if any. """ try: node = self._menutree[nodename] except KeyError: self.caller.msg(_ERR_NOT_IMPLEMENTED.format(nodename=nodename), session=self._session) raise EvMenuError try: ret = self._safe_call(node, raw_string, **kwargs) if isinstance(ret, (tuple, list)) and len(ret) > 1: nodetext, options = ret[:2] else: nodetext, options = ret, None except KeyError: self.caller.msg(_ERR_NOT_IMPLEMENTED.format(nodename=nodename), session=self._session) logger.log_trace() raise EvMenuError except Exception: self.caller.msg(_ERR_GENERAL.format(nodename=nodename), session=self._session) logger.log_trace() raise # store options to make them easier to test self.test_options = options self.test_nodetext = nodetext return nodetext, options
[ "def", "_execute_node", "(", "self", ",", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "try", ":", "node", "=", "self", ".", "_menutree", "[", "nodename", "]", "except", "KeyError", ":", "self", ".", "caller", ".", "msg", "(", "_ERR_NOT_IMPLEMENTED", ".", "format", "(", "nodename", "=", "nodename", ")", ",", "session", "=", "self", ".", "_session", ")", "raise", "EvMenuError", "try", ":", "ret", "=", "self", ".", "_safe_call", "(", "node", ",", "raw_string", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "ret", ",", "(", "tuple", ",", "list", ")", ")", "and", "len", "(", "ret", ")", ">", "1", ":", "nodetext", ",", "options", "=", "ret", "[", ":", "2", "]", "else", ":", "nodetext", ",", "options", "=", "ret", ",", "None", "except", "KeyError", ":", "self", ".", "caller", ".", "msg", "(", "_ERR_NOT_IMPLEMENTED", ".", "format", "(", "nodename", "=", "nodename", ")", ",", "session", "=", "self", ".", "_session", ")", "logger", ".", "log_trace", "(", ")", "raise", "EvMenuError", "except", "Exception", ":", "self", ".", "caller", ".", "msg", "(", "_ERR_GENERAL", ".", "format", "(", "nodename", "=", "nodename", ")", ",", "session", "=", "self", ".", "_session", ")", "logger", ".", "log_trace", "(", ")", "raise", "# store options to make them easier to test", "self", ".", "test_options", "=", "options", "self", ".", "test_nodetext", "=", "nodetext", "return", "nodetext", ",", "options" ]
[ 594, 4 ]
[ 634, 32 ]
python
en
['en', 'error', 'th']
False
EvMenu.run_exec
(self, nodename, raw_string, **kwargs)
Run a function or node as a callback (with the 'exec' option key). Args: nodename (callable or str): A callable to run as `callable(caller, raw_string)`, or the Name of an existing node to run as a callable. This may or may not return a string. raw_string (str): The raw default string entered on the previous node (only used if the node accepts it as an argument) kwargs (any): These are optional kwargs passed into goto Returns: new_goto (str or None): A replacement goto location string or None (no replacement). Notes: Relying on exec callbacks to set the goto location is very powerful but will easily lead to spaghetti structure and hard-to-trace paths through the menu logic. So be careful with relying on this.
Run a function or node as a callback (with the 'exec' option key).
def run_exec(self, nodename, raw_string, **kwargs): """ Run a function or node as a callback (with the 'exec' option key). Args: nodename (callable or str): A callable to run as `callable(caller, raw_string)`, or the Name of an existing node to run as a callable. This may or may not return a string. raw_string (str): The raw default string entered on the previous node (only used if the node accepts it as an argument) kwargs (any): These are optional kwargs passed into goto Returns: new_goto (str or None): A replacement goto location string or None (no replacement). Notes: Relying on exec callbacks to set the goto location is very powerful but will easily lead to spaghetti structure and hard-to-trace paths through the menu logic. So be careful with relying on this. """ try: if callable(nodename): # this is a direct callable - execute it directly ret = self._safe_call(nodename, raw_string, **kwargs) if isinstance(ret, (tuple, list)): if not len(ret) > 1 or not isinstance(ret[1], dict): raise EvMenuError("exec callable must return either None, str or (str, dict)") ret, kwargs = ret[:2] else: # nodename is a string; lookup as node and run as node in-place (don't goto it) # execute the node ret = self._execute_node(nodename, raw_string, **kwargs) if isinstance(ret, (tuple, list)): if not len(ret) > 1 and ret[1] and not isinstance(ret[1], dict): raise EvMenuError("exec node must return either None, str or (str, dict)") ret, kwargs = ret[:2] except EvMenuError as err: errmsg = "Error in exec '%s' (input: '%s'): %s" % (nodename, raw_string.rstrip(), err) self.caller.msg("|r%s|n" % errmsg) logger.log_trace(errmsg) return if isinstance(ret, basestring): # only return a value if a string (a goto target), ignore all other returns if not ret: # an empty string - rerun the same node return self.nodename return ret, kwargs return None
[ "def", "run_exec", "(", "self", ",", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "callable", "(", "nodename", ")", ":", "# this is a direct callable - execute it directly", "ret", "=", "self", ".", "_safe_call", "(", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "ret", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "not", "len", "(", "ret", ")", ">", "1", "or", "not", "isinstance", "(", "ret", "[", "1", "]", ",", "dict", ")", ":", "raise", "EvMenuError", "(", "\"exec callable must return either None, str or (str, dict)\"", ")", "ret", ",", "kwargs", "=", "ret", "[", ":", "2", "]", "else", ":", "# nodename is a string; lookup as node and run as node in-place (don't goto it)", "# execute the node", "ret", "=", "self", ".", "_execute_node", "(", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "ret", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "not", "len", "(", "ret", ")", ">", "1", "and", "ret", "[", "1", "]", "and", "not", "isinstance", "(", "ret", "[", "1", "]", ",", "dict", ")", ":", "raise", "EvMenuError", "(", "\"exec node must return either None, str or (str, dict)\"", ")", "ret", ",", "kwargs", "=", "ret", "[", ":", "2", "]", "except", "EvMenuError", "as", "err", ":", "errmsg", "=", "\"Error in exec '%s' (input: '%s'): %s\"", "%", "(", "nodename", ",", "raw_string", ".", "rstrip", "(", ")", ",", "err", ")", "self", ".", "caller", ".", "msg", "(", "\"|r%s|n\"", "%", "errmsg", ")", "logger", ".", "log_trace", "(", "errmsg", ")", "return", "if", "isinstance", "(", "ret", ",", "basestring", ")", ":", "# only return a value if a string (a goto target), ignore all other returns", "if", "not", "ret", ":", "# an empty string - rerun the same node", "return", "self", ".", "nodename", "return", "ret", ",", "kwargs", "return", "None" ]
[ 636, 4 ]
[ 688, 19 ]
python
en
['en', 'error', 'th']
False
EvMenu.extract_goto_exec
(self, nodename, option_dict)
Helper: Get callables and their eventual kwargs. Args: nodename (str): The current node name (used for error reporting). option_dict (dict): The seleted option's dict. Returns: goto (str, callable or None): The goto directive in the option. goto_kwargs (dict): Kwargs for `goto` if the former is callable, otherwise empty. execute (callable or None): Executable given by the `exec` directive. exec_kwargs (dict): Kwargs for `execute` if it's callable, otherwise empty.
Helper: Get callables and their eventual kwargs.
def extract_goto_exec(self, nodename, option_dict): """ Helper: Get callables and their eventual kwargs. Args: nodename (str): The current node name (used for error reporting). option_dict (dict): The seleted option's dict. Returns: goto (str, callable or None): The goto directive in the option. goto_kwargs (dict): Kwargs for `goto` if the former is callable, otherwise empty. execute (callable or None): Executable given by the `exec` directive. exec_kwargs (dict): Kwargs for `execute` if it's callable, otherwise empty. """ goto_kwargs, exec_kwargs = {}, {} goto, execute = option_dict.get("goto", None), option_dict.get("exec", None) if goto and isinstance(goto, (tuple, list)): if len(goto) > 1: goto, goto_kwargs = goto[:2] # ignore any extra arguments if not hasattr(goto_kwargs, "__getitem__"): # not a dict-like structure raise EvMenuError("EvMenu node {}: goto kwargs is not a dict: {}".format( nodename, goto_kwargs)) else: goto = goto[0] if execute and isinstance(execute, (tuple, list)): if len(execute) > 1: execute, exec_kwargs = execute[:2] # ignore any extra arguments if not hasattr(exec_kwargs, "__getitem__"): # not a dict-like structure raise EvMenuError("EvMenu node {}: exec kwargs is not a dict: {}".format( nodename, goto_kwargs)) else: execute = execute[0] return goto, goto_kwargs, execute, exec_kwargs
[ "def", "extract_goto_exec", "(", "self", ",", "nodename", ",", "option_dict", ")", ":", "goto_kwargs", ",", "exec_kwargs", "=", "{", "}", ",", "{", "}", "goto", ",", "execute", "=", "option_dict", ".", "get", "(", "\"goto\"", ",", "None", ")", ",", "option_dict", ".", "get", "(", "\"exec\"", ",", "None", ")", "if", "goto", "and", "isinstance", "(", "goto", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "goto", ")", ">", "1", ":", "goto", ",", "goto_kwargs", "=", "goto", "[", ":", "2", "]", "# ignore any extra arguments", "if", "not", "hasattr", "(", "goto_kwargs", ",", "\"__getitem__\"", ")", ":", "# not a dict-like structure", "raise", "EvMenuError", "(", "\"EvMenu node {}: goto kwargs is not a dict: {}\"", ".", "format", "(", "nodename", ",", "goto_kwargs", ")", ")", "else", ":", "goto", "=", "goto", "[", "0", "]", "if", "execute", "and", "isinstance", "(", "execute", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "execute", ")", ">", "1", ":", "execute", ",", "exec_kwargs", "=", "execute", "[", ":", "2", "]", "# ignore any extra arguments", "if", "not", "hasattr", "(", "exec_kwargs", ",", "\"__getitem__\"", ")", ":", "# not a dict-like structure", "raise", "EvMenuError", "(", "\"EvMenu node {}: exec kwargs is not a dict: {}\"", ".", "format", "(", "nodename", ",", "goto_kwargs", ")", ")", "else", ":", "execute", "=", "execute", "[", "0", "]", "return", "goto", ",", "goto_kwargs", ",", "execute", ",", "exec_kwargs" ]
[ 690, 4 ]
[ 725, 54 ]
python
en
['en', 'error', 'th']
False
EvMenu.goto
(self, nodename, raw_string, **kwargs)
Run a node by name, optionally dynamically generating that name first. Args: nodename (str or callable): Name of node or a callable to be called as `function(caller, raw_string, **kwargs)` or `function(caller, **kwargs)` to return the actual goto string or a ("nodename", kwargs) tuple. raw_string (str): The raw default string entered on the previous node (only used if the node accepts it as an argument) Kwargs: any: Extra arguments to goto callables.
Run a node by name, optionally dynamically generating that name first.
def goto(self, nodename, raw_string, **kwargs): """ Run a node by name, optionally dynamically generating that name first. Args: nodename (str or callable): Name of node or a callable to be called as `function(caller, raw_string, **kwargs)` or `function(caller, **kwargs)` to return the actual goto string or a ("nodename", kwargs) tuple. raw_string (str): The raw default string entered on the previous node (only used if the node accepts it as an argument) Kwargs: any: Extra arguments to goto callables. """ if callable(nodename): # run the "goto" callable, if possible inp_nodename = nodename nodename = self._safe_call(nodename, raw_string, **kwargs) if isinstance(nodename, (tuple, list)): if not len(nodename) > 1 or not isinstance(nodename[1], dict): raise EvMenuError( "{}: goto callable must return str or (str, dict)".format(inp_nodename)) nodename, kwargs = nodename[:2] if not nodename: # no nodename return. Re-run current node nodename = self.nodename try: # execute the found node, make use of the returns. nodetext, options = self._execute_node(nodename, raw_string, **kwargs) except EvMenuError: return if self._persistent: self.caller.attributes.add("_menutree_saved_startnode", (nodename, (raw_string, kwargs))) # validation of the node return values helptext = "" if hasattr(nodetext, "__iter__"): if len(nodetext) > 1: nodetext, helptext = nodetext[:2] else: nodetext = nodetext[0] nodetext = "" if nodetext is None else str(nodetext) options = [options] if isinstance(options, dict) else options # this will be displayed in the given order display_options = [] # this is used for lookup self.options = {} self.default = None if options: for inum, dic in enumerate(options): # fix up the option dicts keys = make_iter(dic.get("key")) desc = dic.get("desc", dic.get("text", None)) if "_default" in keys: keys = [key for key in keys if key != "_default"] goto, goto_kwargs, execute, exec_kwargs = self.extract_goto_exec(nodename, dic) self.default = (goto, goto_kwargs, execute, exec_kwargs) else: # use the key (only) if set, otherwise use the running number keys = list(make_iter(dic.get("key", str(inum + 1).strip()))) goto, goto_kwargs, execute, exec_kwargs = self.extract_goto_exec(nodename, dic) if keys: display_options.append((keys[0], desc)) for key in keys: if goto or execute: self.options[strip_ansi(key).strip().lower()] = \ (goto, goto_kwargs, execute, exec_kwargs) self.nodetext = self._format_node(nodetext, display_options) self.node_kwargs = kwargs self.nodename = nodename # handle the helptext if helptext: self.helptext = self.helptext_formatter(helptext) elif options: self.helptext = _HELP_FULL if self.auto_quit else _HELP_NO_QUIT else: self.helptext = _HELP_NO_OPTIONS if self.auto_quit else _HELP_NO_OPTIONS_NO_QUIT self.display_nodetext() if not options: self.close_menu()
[ "def", "goto", "(", "self", ",", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "nodename", ")", ":", "# run the \"goto\" callable, if possible", "inp_nodename", "=", "nodename", "nodename", "=", "self", ".", "_safe_call", "(", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "nodename", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "not", "len", "(", "nodename", ")", ">", "1", "or", "not", "isinstance", "(", "nodename", "[", "1", "]", ",", "dict", ")", ":", "raise", "EvMenuError", "(", "\"{}: goto callable must return str or (str, dict)\"", ".", "format", "(", "inp_nodename", ")", ")", "nodename", ",", "kwargs", "=", "nodename", "[", ":", "2", "]", "if", "not", "nodename", ":", "# no nodename return. Re-run current node", "nodename", "=", "self", ".", "nodename", "try", ":", "# execute the found node, make use of the returns.", "nodetext", ",", "options", "=", "self", ".", "_execute_node", "(", "nodename", ",", "raw_string", ",", "*", "*", "kwargs", ")", "except", "EvMenuError", ":", "return", "if", "self", ".", "_persistent", ":", "self", ".", "caller", ".", "attributes", ".", "add", "(", "\"_menutree_saved_startnode\"", ",", "(", "nodename", ",", "(", "raw_string", ",", "kwargs", ")", ")", ")", "# validation of the node return values", "helptext", "=", "\"\"", "if", "hasattr", "(", "nodetext", ",", "\"__iter__\"", ")", ":", "if", "len", "(", "nodetext", ")", ">", "1", ":", "nodetext", ",", "helptext", "=", "nodetext", "[", ":", "2", "]", "else", ":", "nodetext", "=", "nodetext", "[", "0", "]", "nodetext", "=", "\"\"", "if", "nodetext", "is", "None", "else", "str", "(", "nodetext", ")", "options", "=", "[", "options", "]", "if", "isinstance", "(", "options", ",", "dict", ")", "else", "options", "# this will be displayed in the given order", "display_options", "=", "[", "]", "# this is used for lookup", "self", ".", "options", "=", "{", "}", "self", ".", "default", "=", "None", "if", "options", ":", "for", "inum", ",", "dic", "in", "enumerate", "(", "options", ")", ":", "# fix up the option dicts", "keys", "=", "make_iter", "(", "dic", ".", "get", "(", "\"key\"", ")", ")", "desc", "=", "dic", ".", "get", "(", "\"desc\"", ",", "dic", ".", "get", "(", "\"text\"", ",", "None", ")", ")", "if", "\"_default\"", "in", "keys", ":", "keys", "=", "[", "key", "for", "key", "in", "keys", "if", "key", "!=", "\"_default\"", "]", "goto", ",", "goto_kwargs", ",", "execute", ",", "exec_kwargs", "=", "self", ".", "extract_goto_exec", "(", "nodename", ",", "dic", ")", "self", ".", "default", "=", "(", "goto", ",", "goto_kwargs", ",", "execute", ",", "exec_kwargs", ")", "else", ":", "# use the key (only) if set, otherwise use the running number", "keys", "=", "list", "(", "make_iter", "(", "dic", ".", "get", "(", "\"key\"", ",", "str", "(", "inum", "+", "1", ")", ".", "strip", "(", ")", ")", ")", ")", "goto", ",", "goto_kwargs", ",", "execute", ",", "exec_kwargs", "=", "self", ".", "extract_goto_exec", "(", "nodename", ",", "dic", ")", "if", "keys", ":", "display_options", ".", "append", "(", "(", "keys", "[", "0", "]", ",", "desc", ")", ")", "for", "key", "in", "keys", ":", "if", "goto", "or", "execute", ":", "self", ".", "options", "[", "strip_ansi", "(", "key", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "]", "=", "(", "goto", ",", "goto_kwargs", ",", "execute", ",", "exec_kwargs", ")", "self", ".", "nodetext", "=", "self", ".", "_format_node", "(", "nodetext", ",", "display_options", ")", "self", ".", "node_kwargs", "=", "kwargs", "self", ".", "nodename", "=", "nodename", "# handle the helptext", "if", "helptext", ":", "self", ".", "helptext", "=", "self", ".", "helptext_formatter", "(", "helptext", ")", "elif", "options", ":", "self", ".", "helptext", "=", "_HELP_FULL", "if", "self", ".", "auto_quit", "else", "_HELP_NO_QUIT", "else", ":", "self", ".", "helptext", "=", "_HELP_NO_OPTIONS", "if", "self", ".", "auto_quit", "else", "_HELP_NO_OPTIONS_NO_QUIT", "self", ".", "display_nodetext", "(", ")", "if", "not", "options", ":", "self", ".", "close_menu", "(", ")" ]
[ 727, 4 ]
[ 815, 29 ]
python
en
['en', 'error', 'th']
False
EvMenu.run_exec_then_goto
(self, runexec, goto, raw_string, runexec_kwargs=None, goto_kwargs=None)
Call 'exec' callback and goto (which may also be a callable) in sequence. Args: runexec (callable or str): Callback to run before goto. If the callback returns a string, this is used to replace the `goto` string/callable before being passed into the goto handler. goto (str): The target node to go to next (may be replaced by `runexec`).. raw_string (str): The original user input. runexec_kwargs (dict, optional): Optional kwargs for runexec. goto_kwargs (dict, optional): Optional kwargs for goto.
Call 'exec' callback and goto (which may also be a callable) in sequence.
def run_exec_then_goto(self, runexec, goto, raw_string, runexec_kwargs=None, goto_kwargs=None): """ Call 'exec' callback and goto (which may also be a callable) in sequence. Args: runexec (callable or str): Callback to run before goto. If the callback returns a string, this is used to replace the `goto` string/callable before being passed into the goto handler. goto (str): The target node to go to next (may be replaced by `runexec`).. raw_string (str): The original user input. runexec_kwargs (dict, optional): Optional kwargs for runexec. goto_kwargs (dict, optional): Optional kwargs for goto. """ if runexec: # replace goto only if callback returns goto, goto_kwargs = ( self.run_exec(runexec, raw_string, **(runexec_kwargs if runexec_kwargs else {})) or (goto, goto_kwargs)) if goto: self.goto(goto, raw_string, **(goto_kwargs if goto_kwargs else {}))
[ "def", "run_exec_then_goto", "(", "self", ",", "runexec", ",", "goto", ",", "raw_string", ",", "runexec_kwargs", "=", "None", ",", "goto_kwargs", "=", "None", ")", ":", "if", "runexec", ":", "# replace goto only if callback returns", "goto", ",", "goto_kwargs", "=", "(", "self", ".", "run_exec", "(", "runexec", ",", "raw_string", ",", "*", "*", "(", "runexec_kwargs", "if", "runexec_kwargs", "else", "{", "}", ")", ")", "or", "(", "goto", ",", "goto_kwargs", ")", ")", "if", "goto", ":", "self", ".", "goto", "(", "goto", ",", "raw_string", ",", "*", "*", "(", "goto_kwargs", "if", "goto_kwargs", "else", "{", "}", ")", ")" ]
[ 817, 4 ]
[ 839, 79 ]
python
en
['en', 'error', 'th']
False
EvMenu.close_menu
(self)
Shutdown menu; occurs when reaching the end node or using the quit command.
Shutdown menu; occurs when reaching the end node or using the quit command.
def close_menu(self): """ Shutdown menu; occurs when reaching the end node or using the quit command. """ if not self._quitting: # avoid multiple calls from different sources self._quitting = True self.caller.cmdset.remove(EvMenuCmdSet) del self.caller.ndb._menutree if self._persistent: self.caller.attributes.remove("_menutree_saved") self.caller.attributes.remove("_menutree_saved_startnode") if self.cmd_on_exit is not None: self.cmd_on_exit(self.caller, self)
[ "def", "close_menu", "(", "self", ")", ":", "if", "not", "self", ".", "_quitting", ":", "# avoid multiple calls from different sources", "self", ".", "_quitting", "=", "True", "self", ".", "caller", ".", "cmdset", ".", "remove", "(", "EvMenuCmdSet", ")", "del", "self", ".", "caller", ".", "ndb", ".", "_menutree", "if", "self", ".", "_persistent", ":", "self", ".", "caller", ".", "attributes", ".", "remove", "(", "\"_menutree_saved\"", ")", "self", ".", "caller", ".", "attributes", ".", "remove", "(", "\"_menutree_saved_startnode\"", ")", "if", "self", ".", "cmd_on_exit", "is", "not", "None", ":", "self", ".", "cmd_on_exit", "(", "self", ".", "caller", ",", "self", ")" ]
[ 841, 4 ]
[ 854, 51 ]
python
en
['en', 'error', 'th']
False
EvMenu.print_debug_info
(self, arg)
Messages the caller with the current menu state, for debug purposes. Args: arg (str): Arg to debug instruction, either nothing, 'full' or the name of a property to inspect.
Messages the caller with the current menu state, for debug purposes.
def print_debug_info(self, arg): """ Messages the caller with the current menu state, for debug purposes. Args: arg (str): Arg to debug instruction, either nothing, 'full' or the name of a property to inspect. """ all_props = inspect.getmembers(self) all_methods = [name for name, _ in inspect.getmembers(self, predicate=inspect.ismethod)] all_builtins = [name for name, _ in inspect.getmembers(self, predicate=inspect.isbuiltin)] props = {prop: value for prop, value in all_props if prop not in all_methods and prop not in all_builtins and not prop.endswith("__")} local = {key: var for key, var in locals().items() if key not in all_props and not key.endswith("__")} if arg: if arg in props: debugtxt = " |y* {}:|n\n{}".format(arg, props[arg]) elif arg in local: debugtxt = " |y* {}:|n\n{}".format(arg, local[arg]) elif arg == 'full': debugtxt = ("|yMENU DEBUG full ... |n\n" + "\n".join( "|y *|n {}: {}".format(key, val) for key, val in sorted(props.items())) + "\n |yLOCAL VARS:|n\n" + "\n".join( "|y *|n {}: {}".format(key, val) for key, val in sorted(local.items())) + "\n |y... END MENU DEBUG|n") else: debugtxt = "|yUsage: menudebug full|<name of property>|n" else: debugtxt = ("|yMENU DEBUG properties ... |n\n" + "\n".join( "|y *|n {}: {}".format( key, crop(to_str(val, force_string=True), width=50)) for key, val in sorted(props.items())) + "\n |yLOCAL VARS:|n\n" + "\n".join( "|y *|n {}: {}".format( key, crop(to_str(val, force_string=True), width=50)) for key, val in sorted(local.items())) + "\n |y... END MENU DEBUG|n") self.caller.msg(debugtxt)
[ "def", "print_debug_info", "(", "self", ",", "arg", ")", ":", "all_props", "=", "inspect", ".", "getmembers", "(", "self", ")", "all_methods", "=", "[", "name", "for", "name", ",", "_", "in", "inspect", ".", "getmembers", "(", "self", ",", "predicate", "=", "inspect", ".", "ismethod", ")", "]", "all_builtins", "=", "[", "name", "for", "name", ",", "_", "in", "inspect", ".", "getmembers", "(", "self", ",", "predicate", "=", "inspect", ".", "isbuiltin", ")", "]", "props", "=", "{", "prop", ":", "value", "for", "prop", ",", "value", "in", "all_props", "if", "prop", "not", "in", "all_methods", "and", "prop", "not", "in", "all_builtins", "and", "not", "prop", ".", "endswith", "(", "\"__\"", ")", "}", "local", "=", "{", "key", ":", "var", "for", "key", ",", "var", "in", "locals", "(", ")", ".", "items", "(", ")", "if", "key", "not", "in", "all_props", "and", "not", "key", ".", "endswith", "(", "\"__\"", ")", "}", "if", "arg", ":", "if", "arg", "in", "props", ":", "debugtxt", "=", "\" |y* {}:|n\\n{}\"", ".", "format", "(", "arg", ",", "props", "[", "arg", "]", ")", "elif", "arg", "in", "local", ":", "debugtxt", "=", "\" |y* {}:|n\\n{}\"", ".", "format", "(", "arg", ",", "local", "[", "arg", "]", ")", "elif", "arg", "==", "'full'", ":", "debugtxt", "=", "(", "\"|yMENU DEBUG full ... |n\\n\"", "+", "\"\\n\"", ".", "join", "(", "\"|y *|n {}: {}\"", ".", "format", "(", "key", ",", "val", ")", "for", "key", ",", "val", "in", "sorted", "(", "props", ".", "items", "(", ")", ")", ")", "+", "\"\\n |yLOCAL VARS:|n\\n\"", "+", "\"\\n\"", ".", "join", "(", "\"|y *|n {}: {}\"", ".", "format", "(", "key", ",", "val", ")", "for", "key", ",", "val", "in", "sorted", "(", "local", ".", "items", "(", ")", ")", ")", "+", "\"\\n |y... END MENU DEBUG|n\"", ")", "else", ":", "debugtxt", "=", "\"|yUsage: menudebug full|<name of property>|n\"", "else", ":", "debugtxt", "=", "(", "\"|yMENU DEBUG properties ... |n\\n\"", "+", "\"\\n\"", ".", "join", "(", "\"|y *|n {}: {}\"", ".", "format", "(", "key", ",", "crop", "(", "to_str", "(", "val", ",", "force_string", "=", "True", ")", ",", "width", "=", "50", ")", ")", "for", "key", ",", "val", "in", "sorted", "(", "props", ".", "items", "(", ")", ")", ")", "+", "\"\\n |yLOCAL VARS:|n\\n\"", "+", "\"\\n\"", ".", "join", "(", "\"|y *|n {}: {}\"", ".", "format", "(", "key", ",", "crop", "(", "to_str", "(", "val", ",", "force_string", "=", "True", ")", ",", "width", "=", "50", ")", ")", "for", "key", ",", "val", "in", "sorted", "(", "local", ".", "items", "(", ")", ")", ")", "+", "\"\\n |y... END MENU DEBUG|n\"", ")", "self", ".", "caller", ".", "msg", "(", "debugtxt", ")" ]
[ 856, 4 ]
[ 899, 33 ]
python
en
['en', 'error', 'th']
False
EvMenu.parse_input
(self, raw_string)
Parses the incoming string from the menu user. Args: raw_string (str): The incoming, unmodified string from the user. Notes: This method is expected to parse input and use the result to relay execution to the relevant methods of the menu. It should also report errors directly to the user.
Parses the incoming string from the menu user.
def parse_input(self, raw_string): """ Parses the incoming string from the menu user. Args: raw_string (str): The incoming, unmodified string from the user. Notes: This method is expected to parse input and use the result to relay execution to the relevant methods of the menu. It should also report errors directly to the user. """ cmd = strip_ansi(raw_string.strip().lower()) if cmd in self.options: # this will take precedence over the default commands # below goto, goto_kwargs, execfunc, exec_kwargs = self.options[cmd] self.run_exec_then_goto(execfunc, goto, raw_string, exec_kwargs, goto_kwargs) elif self.auto_look and cmd in ("look", "l"): self.display_nodetext() elif self.auto_help and cmd in ("help", "h"): self.display_helptext() elif self.auto_quit and cmd in ("quit", "q", "exit"): self.close_menu() elif self.debug_mode and cmd.startswith("menudebug"): self.print_debug_info(cmd[9:].strip()) elif self.default: goto, goto_kwargs, execfunc, exec_kwargs = self.default self.run_exec_then_goto(execfunc, goto, raw_string, exec_kwargs, goto_kwargs) else: self.caller.msg(_HELP_NO_OPTION_MATCH, session=self._session)
[ "def", "parse_input", "(", "self", ",", "raw_string", ")", ":", "cmd", "=", "strip_ansi", "(", "raw_string", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", "if", "cmd", "in", "self", ".", "options", ":", "# this will take precedence over the default commands", "# below", "goto", ",", "goto_kwargs", ",", "execfunc", ",", "exec_kwargs", "=", "self", ".", "options", "[", "cmd", "]", "self", ".", "run_exec_then_goto", "(", "execfunc", ",", "goto", ",", "raw_string", ",", "exec_kwargs", ",", "goto_kwargs", ")", "elif", "self", ".", "auto_look", "and", "cmd", "in", "(", "\"look\"", ",", "\"l\"", ")", ":", "self", ".", "display_nodetext", "(", ")", "elif", "self", ".", "auto_help", "and", "cmd", "in", "(", "\"help\"", ",", "\"h\"", ")", ":", "self", ".", "display_helptext", "(", ")", "elif", "self", ".", "auto_quit", "and", "cmd", "in", "(", "\"quit\"", ",", "\"q\"", ",", "\"exit\"", ")", ":", "self", ".", "close_menu", "(", ")", "elif", "self", ".", "debug_mode", "and", "cmd", ".", "startswith", "(", "\"menudebug\"", ")", ":", "self", ".", "print_debug_info", "(", "cmd", "[", "9", ":", "]", ".", "strip", "(", ")", ")", "elif", "self", ".", "default", ":", "goto", ",", "goto_kwargs", ",", "execfunc", ",", "exec_kwargs", "=", "self", ".", "default", "self", ".", "run_exec_then_goto", "(", "execfunc", ",", "goto", ",", "raw_string", ",", "exec_kwargs", ",", "goto_kwargs", ")", "else", ":", "self", ".", "caller", ".", "msg", "(", "_HELP_NO_OPTION_MATCH", ",", "session", "=", "self", ".", "_session", ")" ]
[ 901, 4 ]
[ 933, 73 ]
python
en
['en', 'error', 'th']
False
EvMenu.nodetext_formatter
(self, nodetext)
Format the node text itself. Args: nodetext (str): The full node text (the text describing the node). Returns: nodetext (str): The formatted node text.
Format the node text itself.
def nodetext_formatter(self, nodetext): """ Format the node text itself. Args: nodetext (str): The full node text (the text describing the node). Returns: nodetext (str): The formatted node text. """ return dedent(nodetext.strip('\n'), baseline_index=0).rstrip()
[ "def", "nodetext_formatter", "(", "self", ",", "nodetext", ")", ":", "return", "dedent", "(", "nodetext", ".", "strip", "(", "'\\n'", ")", ",", "baseline_index", "=", "0", ")", ".", "rstrip", "(", ")" ]
[ 943, 4 ]
[ 954, 70 ]
python
en
['en', 'error', 'th']
False
EvMenu.helptext_formatter
(self, helptext)
Format the node's help text Args: helptext (str): The unformatted help text for the node. Returns: helptext (str): The formatted help text.
Format the node's help text
def helptext_formatter(self, helptext): """ Format the node's help text Args: helptext (str): The unformatted help text for the node. Returns: helptext (str): The formatted help text. """ return dedent(helptext.strip('\n'), baseline_index=0).rstrip()
[ "def", "helptext_formatter", "(", "self", ",", "helptext", ")", ":", "return", "dedent", "(", "helptext", ".", "strip", "(", "'\\n'", ")", ",", "baseline_index", "=", "0", ")", ".", "rstrip", "(", ")" ]
[ 956, 4 ]
[ 967, 70 ]
python
en
['en', 'error', 'th']
False
EvMenu.options_formatter
(self, optionlist)
Formats the option block. Args: optionlist (list): List of (key, description) tuples for every option related to this node. caller (Object, Account or None, optional): The caller of the node. Returns: options (str): The formatted option display.
Formats the option block.
def options_formatter(self, optionlist): """ Formats the option block. Args: optionlist (list): List of (key, description) tuples for every option related to this node. caller (Object, Account or None, optional): The caller of the node. Returns: options (str): The formatted option display. """ if not optionlist: return "" # column separation distance colsep = 4 nlist = len(optionlist) # get the widest option line in the table. table_width_max = -1 table = [] for key, desc in optionlist: if not (key or desc): continue desc_string = ": %s" % desc if desc else "" table_width_max = max(table_width_max, max(m_len(p) for p in key.split("\n")) + max(m_len(p) for p in desc_string.split("\n")) + colsep) raw_key = strip_ansi(key) if raw_key != key: # already decorations in key definition table.append(" |lc%s|lt%s|le%s" % (raw_key, key, desc_string)) else: # add a default white color to key table.append(" |lc%s|lt|w%s|n|le%s" % (raw_key, raw_key, desc_string)) ncols = (_MAX_TEXT_WIDTH // table_width_max) + 1 # number of ncols # get the amount of rows needed (start with 4 rows) nrows = 4 while nrows * ncols < nlist: nrows += 1 ncols = nlist // nrows # number of full columns nlastcol = nlist % nrows # number of elements in last column # get the final column count ncols = ncols + 1 if nlastcol > 0 else ncols if ncols > 1: # only extend if longer than one column table.extend([" " for i in range(nrows - nlastcol)]) # build the actual table grid table = [table[icol * nrows: (icol * nrows) + nrows] for icol in range(0, ncols)] # adjust the width of each column for icol in range(len(table)): col_width = max(max(m_len(p) for p in part.split("\n")) for part in table[icol]) + colsep table[icol] = [pad(part, width=col_width + colsep, align="l") for part in table[icol]] # format the table into columns return unicode(EvTable(table=table, border="none"))
[ "def", "options_formatter", "(", "self", ",", "optionlist", ")", ":", "if", "not", "optionlist", ":", "return", "\"\"", "# column separation distance", "colsep", "=", "4", "nlist", "=", "len", "(", "optionlist", ")", "# get the widest option line in the table.", "table_width_max", "=", "-", "1", "table", "=", "[", "]", "for", "key", ",", "desc", "in", "optionlist", ":", "if", "not", "(", "key", "or", "desc", ")", ":", "continue", "desc_string", "=", "\": %s\"", "%", "desc", "if", "desc", "else", "\"\"", "table_width_max", "=", "max", "(", "table_width_max", ",", "max", "(", "m_len", "(", "p", ")", "for", "p", "in", "key", ".", "split", "(", "\"\\n\"", ")", ")", "+", "max", "(", "m_len", "(", "p", ")", "for", "p", "in", "desc_string", ".", "split", "(", "\"\\n\"", ")", ")", "+", "colsep", ")", "raw_key", "=", "strip_ansi", "(", "key", ")", "if", "raw_key", "!=", "key", ":", "# already decorations in key definition", "table", ".", "append", "(", "\" |lc%s|lt%s|le%s\"", "%", "(", "raw_key", ",", "key", ",", "desc_string", ")", ")", "else", ":", "# add a default white color to key", "table", ".", "append", "(", "\" |lc%s|lt|w%s|n|le%s\"", "%", "(", "raw_key", ",", "raw_key", ",", "desc_string", ")", ")", "ncols", "=", "(", "_MAX_TEXT_WIDTH", "//", "table_width_max", ")", "+", "1", "# number of ncols", "# get the amount of rows needed (start with 4 rows)", "nrows", "=", "4", "while", "nrows", "*", "ncols", "<", "nlist", ":", "nrows", "+=", "1", "ncols", "=", "nlist", "//", "nrows", "# number of full columns", "nlastcol", "=", "nlist", "%", "nrows", "# number of elements in last column", "# get the final column count", "ncols", "=", "ncols", "+", "1", "if", "nlastcol", ">", "0", "else", "ncols", "if", "ncols", ">", "1", ":", "# only extend if longer than one column", "table", ".", "extend", "(", "[", "\" \"", "for", "i", "in", "range", "(", "nrows", "-", "nlastcol", ")", "]", ")", "# build the actual table grid", "table", "=", "[", "table", "[", "icol", "*", "nrows", ":", "(", "icol", "*", "nrows", ")", "+", "nrows", "]", "for", "icol", "in", "range", "(", "0", ",", "ncols", ")", "]", "# adjust the width of each column", "for", "icol", "in", "range", "(", "len", "(", "table", ")", ")", ":", "col_width", "=", "max", "(", "max", "(", "m_len", "(", "p", ")", "for", "p", "in", "part", ".", "split", "(", "\"\\n\"", ")", ")", "for", "part", "in", "table", "[", "icol", "]", ")", "+", "colsep", "table", "[", "icol", "]", "=", "[", "pad", "(", "part", ",", "width", "=", "col_width", "+", "colsep", ",", "align", "=", "\"l\"", ")", "for", "part", "in", "table", "[", "icol", "]", "]", "# format the table into columns", "return", "unicode", "(", "EvTable", "(", "table", "=", "table", ",", "border", "=", "\"none\"", ")", ")" ]
[ 969, 4 ]
[ 1032, 59 ]
python
en
['en', 'error', 'th']
False
EvMenu.node_formatter
(self, nodetext, optionstext)
Formats the entirety of the node. Args: nodetext (str): The node text as returned by `self.nodetext_formatter`. optionstext (str): The options display as returned by `self.options_formatter`. caller (Object, Account or None, optional): The caller of the node. Returns: node (str): The formatted node to display.
Formats the entirety of the node.
def node_formatter(self, nodetext, optionstext): """ Formats the entirety of the node. Args: nodetext (str): The node text as returned by `self.nodetext_formatter`. optionstext (str): The options display as returned by `self.options_formatter`. caller (Object, Account or None, optional): The caller of the node. Returns: node (str): The formatted node to display. """ if self._session: screen_width = self._session.protocol_flags.get( "SCREENWIDTH", {0: _MAX_TEXT_WIDTH})[0] else: screen_width = _MAX_TEXT_WIDTH nodetext_width_max = max(m_len(line) for line in nodetext.split("\n")) options_width_max = max(m_len(line) for line in optionstext.split("\n")) total_width = min(screen_width, max(options_width_max, nodetext_width_max)) separator1 = "_" * total_width + "\n\n" if nodetext_width_max else "" separator2 = "\n" + "_" * total_width + "\n\n" if total_width else "" return separator1 + "|n" + nodetext + "|n" + separator2 + "|n" + optionstext
[ "def", "node_formatter", "(", "self", ",", "nodetext", ",", "optionstext", ")", ":", "if", "self", ".", "_session", ":", "screen_width", "=", "self", ".", "_session", ".", "protocol_flags", ".", "get", "(", "\"SCREENWIDTH\"", ",", "{", "0", ":", "_MAX_TEXT_WIDTH", "}", ")", "[", "0", "]", "else", ":", "screen_width", "=", "_MAX_TEXT_WIDTH", "nodetext_width_max", "=", "max", "(", "m_len", "(", "line", ")", "for", "line", "in", "nodetext", ".", "split", "(", "\"\\n\"", ")", ")", "options_width_max", "=", "max", "(", "m_len", "(", "line", ")", "for", "line", "in", "optionstext", ".", "split", "(", "\"\\n\"", ")", ")", "total_width", "=", "min", "(", "screen_width", ",", "max", "(", "options_width_max", ",", "nodetext_width_max", ")", ")", "separator1", "=", "\"_\"", "*", "total_width", "+", "\"\\n\\n\"", "if", "nodetext_width_max", "else", "\"\"", "separator2", "=", "\"\\n\"", "+", "\"_\"", "*", "total_width", "+", "\"\\n\\n\"", "if", "total_width", "else", "\"\"", "return", "separator1", "+", "\"|n\"", "+", "nodetext", "+", "\"|n\"", "+", "separator2", "+", "\"|n\"", "+", "optionstext" ]
[ 1034, 4 ]
[ 1058, 84 ]
python
en
['en', 'error', 'th']
False
CmdGetInput.func
(self)
This is called when user enters anything.
This is called when user enters anything.
def func(self): """This is called when user enters anything.""" caller = self.caller try: getinput = caller.ndb._getinput if not getinput and hasattr(caller, "account"): getinput = caller.account.ndb._getinput caller = caller.account callback = getinput._callback caller.ndb._getinput._session = self.session prompt = caller.ndb._getinput._prompt args = caller.ndb._getinput._args kwargs = caller.ndb._getinput._kwargs result = self.raw_string.strip() # we strip the ending line break caused by sending ok = not callback(caller, prompt, result, *args, **kwargs) if ok: # only clear the state if the callback does not return # anything del caller.ndb._getinput caller.cmdset.remove(InputCmdSet) except Exception: # make sure to clean up cmdset if something goes wrong caller.msg("|rError in get_input. Choice not confirmed (report to admin)|n") logger.log_trace("Error in get_input") caller.cmdset.remove(InputCmdSet)
[ "def", "func", "(", "self", ")", ":", "caller", "=", "self", ".", "caller", "try", ":", "getinput", "=", "caller", ".", "ndb", ".", "_getinput", "if", "not", "getinput", "and", "hasattr", "(", "caller", ",", "\"account\"", ")", ":", "getinput", "=", "caller", ".", "account", ".", "ndb", ".", "_getinput", "caller", "=", "caller", ".", "account", "callback", "=", "getinput", ".", "_callback", "caller", ".", "ndb", ".", "_getinput", ".", "_session", "=", "self", ".", "session", "prompt", "=", "caller", ".", "ndb", ".", "_getinput", ".", "_prompt", "args", "=", "caller", ".", "ndb", ".", "_getinput", ".", "_args", "kwargs", "=", "caller", ".", "ndb", ".", "_getinput", ".", "_kwargs", "result", "=", "self", ".", "raw_string", ".", "strip", "(", ")", "# we strip the ending line break caused by sending", "ok", "=", "not", "callback", "(", "caller", ",", "prompt", ",", "result", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "ok", ":", "# only clear the state if the callback does not return", "# anything", "del", "caller", ".", "ndb", ".", "_getinput", "caller", ".", "cmdset", ".", "remove", "(", "InputCmdSet", ")", "except", "Exception", ":", "# make sure to clean up cmdset if something goes wrong", "caller", ".", "msg", "(", "\"|rError in get_input. Choice not confirmed (report to admin)|n\"", ")", "logger", ".", "log_trace", "(", "\"Error in get_input\"", ")", "caller", ".", "cmdset", ".", "remove", "(", "InputCmdSet", ")" ]
[ 1242, 4 ]
[ 1268, 45 ]
python
en
['en', 'en', 'en']
True
InputCmdSet.at_cmdset_creation
(self)
called once at creation
called once at creation
def at_cmdset_creation(self): """called once at creation""" self.add(CmdGetInput())
[ "def", "at_cmdset_creation", "(", "self", ")", ":", "self", ".", "add", "(", "CmdGetInput", "(", ")", ")" ]
[ 1282, 4 ]
[ 1284, 31 ]
python
en
['en', 'en', 'en']
True
setup
(bot)
Mandatory function to add the Cog to the bot.
Mandatory function to add the Cog to the bot.
def setup(bot): """ Mandatory function to add the Cog to the bot. """ bot.add_cog(SaveSuggestionCog(bot))
[ "def", "setup", "(", "bot", ")", ":", "bot", ".", "add_cog", "(", "SaveSuggestionCog", "(", "bot", ")", ")" ]
[ 595, 0 ]
[ 599, 39 ]
python
en
['en', 'error', 'th']
False
InstanceProvider.__init__
(self, instance)
Initialize the instance provider.
Initialize the instance provider.
def __init__(self, instance): """Initialize the instance provider.""" if not instance: raise ValueError("Class instance binding must be non-empty") self._instance = instance
[ "def", "__init__", "(", "self", ",", "instance", ")", ":", "if", "not", "instance", ":", "raise", "ValueError", "(", "\"Class instance binding must be non-empty\"", ")", "self", ".", "_instance", "=", "instance" ]
[ 12, 4 ]
[ 16, 33 ]
python
en
['en', 'en', 'en']
True
InstanceProvider.provide
(self, config: BaseSettings, injector: BaseInjector)
Provide the object instance given a config and injector.
Provide the object instance given a config and injector.
async def provide(self, config: BaseSettings, injector: BaseInjector): """Provide the object instance given a config and injector.""" return self._instance
[ "async", "def", "provide", "(", "self", ",", "config", ":", "BaseSettings", ",", "injector", ":", "BaseInjector", ")", ":", "return", "self", ".", "_instance" ]
[ 18, 4 ]
[ 20, 29 ]
python
en
['en', 'en', 'en']
True
ClassProvider.__init__
( self, instance_cls: Union[str, type], *ctor_args, async_init: str = None, **ctor_kwargs )
Initialize the class provider.
Initialize the class provider.
def __init__( self, instance_cls: Union[str, type], *ctor_args, async_init: str = None, **ctor_kwargs ): """Initialize the class provider.""" self._async_init = async_init self._ctor_args = ctor_args self._ctor_kwargs = ctor_kwargs self._instance_cls = instance_cls
[ "def", "__init__", "(", "self", ",", "instance_cls", ":", "Union", "[", "str", ",", "type", "]", ",", "*", "ctor_args", ",", "async_init", ":", "str", "=", "None", ",", "*", "*", "ctor_kwargs", ")", ":", "self", ".", "_async_init", "=", "async_init", "self", ".", "_ctor_args", "=", "ctor_args", "self", ".", "_ctor_kwargs", "=", "ctor_kwargs", "self", ".", "_instance_cls", "=", "instance_cls" ]
[ 33, 4 ]
[ 44, 41 ]
python
en
['en', 'en', 'en']
True
ClassProvider.provide
(self, config: BaseSettings, injector: BaseInjector)
Provide the object instance given a config and injector.
Provide the object instance given a config and injector.
async def provide(self, config: BaseSettings, injector: BaseInjector): """Provide the object instance given a config and injector.""" instance_cls = self._instance_cls if isinstance(instance_cls, str): instance_cls = ClassLoader.load_class(instance_cls) self._instance_cls = instance_cls args = [] for arg in self._ctor_args: if isinstance(arg, self.Inject): arg = await injector.inject(arg.base_class) args.append(arg) kwargs = {} for arg_name, arg in self._ctor_kwargs.items(): if isinstance(arg, self.Inject): arg = await injector.inject(arg.base_class) kwargs[arg_name] = arg instance = instance_cls(*args, **kwargs) if self._async_init: await getattr(instance, self._async_init)() return instance
[ "async", "def", "provide", "(", "self", ",", "config", ":", "BaseSettings", ",", "injector", ":", "BaseInjector", ")", ":", "instance_cls", "=", "self", ".", "_instance_cls", "if", "isinstance", "(", "instance_cls", ",", "str", ")", ":", "instance_cls", "=", "ClassLoader", ".", "load_class", "(", "instance_cls", ")", "self", ".", "_instance_cls", "=", "instance_cls", "args", "=", "[", "]", "for", "arg", "in", "self", ".", "_ctor_args", ":", "if", "isinstance", "(", "arg", ",", "self", ".", "Inject", ")", ":", "arg", "=", "await", "injector", ".", "inject", "(", "arg", ".", "base_class", ")", "args", ".", "append", "(", "arg", ")", "kwargs", "=", "{", "}", "for", "arg_name", ",", "arg", "in", "self", ".", "_ctor_kwargs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "arg", ",", "self", ".", "Inject", ")", ":", "arg", "=", "await", "injector", ".", "inject", "(", "arg", ".", "base_class", ")", "kwargs", "[", "arg_name", "]", "=", "arg", "instance", "=", "instance_cls", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", "_async_init", ":", "await", "getattr", "(", "instance", ",", "self", ".", "_async_init", ")", "(", ")", "return", "instance" ]
[ 46, 4 ]
[ 65, 23 ]
python
en
['en', 'en', 'en']
True
CachedProvider.__init__
(self, provider: BaseProvider)
Initialize the cached provider instance.
Initialize the cached provider instance.
def __init__(self, provider: BaseProvider): """Initialize the cached provider instance.""" if not provider: raise ValueError("Cache provider input must not be empty.") self._instance = None self._provider = provider
[ "def", "__init__", "(", "self", ",", "provider", ":", "BaseProvider", ")", ":", "if", "not", "provider", ":", "raise", "ValueError", "(", "\"Cache provider input must not be empty.\"", ")", "self", ".", "_instance", "=", "None", "self", ".", "_provider", "=", "provider" ]
[ 71, 4 ]
[ 76, 33 ]
python
en
['en', 'en', 'en']
True
CachedProvider.provide
(self, config: BaseSettings, injector: BaseInjector)
Provide the object instance given a config and injector.
Provide the object instance given a config and injector.
async def provide(self, config: BaseSettings, injector: BaseInjector): """Provide the object instance given a config and injector.""" if not self._instance: self._instance = await self._provider.provide(config, injector) return self._instance
[ "async", "def", "provide", "(", "self", ",", "config", ":", "BaseSettings", ",", "injector", ":", "BaseInjector", ")", ":", "if", "not", "self", ".", "_instance", ":", "self", ".", "_instance", "=", "await", "self", ".", "_provider", ".", "provide", "(", "config", ",", "injector", ")", "return", "self", ".", "_instance" ]
[ 78, 4 ]
[ 82, 29 ]
python
en
['en', 'en', 'en']
True
StatsProvider.__init__
( self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool = True )
Initialize the statistics provider instance.
Initialize the statistics provider instance.
def __init__( self, provider: BaseProvider, methods: Sequence[str], *, ignore_missing: bool = True ): """Initialize the statistics provider instance.""" if not provider: raise ValueError("Stats provider input must not be empty.") self._provider = provider self._methods = methods self._ignore_missing = ignore_missing
[ "def", "__init__", "(", "self", ",", "provider", ":", "BaseProvider", ",", "methods", ":", "Sequence", "[", "str", "]", ",", "*", ",", "ignore_missing", ":", "bool", "=", "True", ")", ":", "if", "not", "provider", ":", "raise", "ValueError", "(", "\"Stats provider input must not be empty.\"", ")", "self", ".", "_provider", "=", "provider", "self", ".", "_methods", "=", "methods", "self", ".", "_ignore_missing", "=", "ignore_missing" ]
[ 88, 4 ]
[ 100, 45 ]
python
en
['en', 'en', 'en']
True
StatsProvider.provide
(self, config: BaseSettings, injector: BaseInjector)
Provide the object instance given a config and injector.
Provide the object instance given a config and injector.
async def provide(self, config: BaseSettings, injector: BaseInjector): """Provide the object instance given a config and injector.""" instance = await self._provider.provide(config, injector) collector: Collector = await injector.inject(Collector, required=False) if collector: collector.wrap(instance, self._methods, ignore_missing=self._ignore_missing) return instance
[ "async", "def", "provide", "(", "self", ",", "config", ":", "BaseSettings", ",", "injector", ":", "BaseInjector", ")", ":", "instance", "=", "await", "self", ".", "_provider", ".", "provide", "(", "config", ",", "injector", ")", "collector", ":", "Collector", "=", "await", "injector", ".", "inject", "(", "Collector", ",", "required", "=", "False", ")", "if", "collector", ":", "collector", ".", "wrap", "(", "instance", ",", "self", ".", "_methods", ",", "ignore_missing", "=", "self", ".", "_ignore_missing", ")", "return", "instance" ]
[ 102, 4 ]
[ 108, 23 ]
python
en
['en', 'en', 'en']
True
test_state_regenerated_from_ledger
(looper, nodeSet, tconf, tdir, sdk_pool_handle, sdk_wallet_trustee, allPluginsPath)
Node loses its state database but recreates it from ledger after start. Checking ATTRIB txns too since they store some data off ledger too
Node loses its state database but recreates it from ledger after start. Checking ATTRIB txns too since they store some data off ledger too
def test_state_regenerated_from_ledger(looper, nodeSet, tconf, tdir, sdk_pool_handle, sdk_wallet_trustee, allPluginsPath): """ Node loses its state database but recreates it from ledger after start. Checking ATTRIB txns too since they store some data off ledger too """ endorsers = [] for i in range(5): endorsers.append(sdk_add_new_nym(looper, sdk_pool_handle, sdk_wallet_trustee, 'TA' + str(i), ENDORSER_STRING)) sdk_add_raw_attribute(looper, sdk_pool_handle, endorsers[-1], randomString(6), randomString(10)) for wh in endorsers: for i in range(3): sdk_add_new_nym(looper, sdk_pool_handle, wh, 'NP1' + str(i)) ensure_all_nodes_have_same_data(looper, nodeSet) node_to_stop = nodeSet[-1] node_state = node_to_stop.states[DOMAIN_LEDGER_ID] assert not node_state.isEmpty state_db_path = node_state._kv.db_path node_to_stop.cleanupOnStopping = False node_to_stop.stop() looper.removeProdable(node_to_stop) ensure_node_disconnected(looper, node_to_stop, nodeSet[:-1]) shutil.rmtree(state_db_path) config_helper = NodeConfigHelper(node_to_stop.name, tconf, chroot=tdir) restarted_node = TestNode( node_to_stop.name, config_helper=config_helper, config=tconf, pluginPaths=allPluginsPath, ha=node_to_stop.nodestack.ha, cliha=node_to_stop.clientstack.ha) looper.add(restarted_node) nodeSet[-1] = restarted_node looper.run(checkNodesConnected(nodeSet)) # Need some time as `last_ordered_3PC` is compared too and that is # communicated through catchup waitNodeDataEquality(looper, restarted_node, *nodeSet[:-1]) # Pool is still functional for wh in endorsers: sdk_add_new_nym(looper, sdk_pool_handle, wh, 'NP--' + randomString(5)) ensure_all_nodes_have_same_data(looper, nodeSet)
[ "def", "test_state_regenerated_from_ledger", "(", "looper", ",", "nodeSet", ",", "tconf", ",", "tdir", ",", "sdk_pool_handle", ",", "sdk_wallet_trustee", ",", "allPluginsPath", ")", ":", "endorsers", "=", "[", "]", "for", "i", "in", "range", "(", "5", ")", ":", "endorsers", ".", "append", "(", "sdk_add_new_nym", "(", "looper", ",", "sdk_pool_handle", ",", "sdk_wallet_trustee", ",", "'TA'", "+", "str", "(", "i", ")", ",", "ENDORSER_STRING", ")", ")", "sdk_add_raw_attribute", "(", "looper", ",", "sdk_pool_handle", ",", "endorsers", "[", "-", "1", "]", ",", "randomString", "(", "6", ")", ",", "randomString", "(", "10", ")", ")", "for", "wh", "in", "endorsers", ":", "for", "i", "in", "range", "(", "3", ")", ":", "sdk_add_new_nym", "(", "looper", ",", "sdk_pool_handle", ",", "wh", ",", "'NP1'", "+", "str", "(", "i", ")", ")", "ensure_all_nodes_have_same_data", "(", "looper", ",", "nodeSet", ")", "node_to_stop", "=", "nodeSet", "[", "-", "1", "]", "node_state", "=", "node_to_stop", ".", "states", "[", "DOMAIN_LEDGER_ID", "]", "assert", "not", "node_state", ".", "isEmpty", "state_db_path", "=", "node_state", ".", "_kv", ".", "db_path", "node_to_stop", ".", "cleanupOnStopping", "=", "False", "node_to_stop", ".", "stop", "(", ")", "looper", ".", "removeProdable", "(", "node_to_stop", ")", "ensure_node_disconnected", "(", "looper", ",", "node_to_stop", ",", "nodeSet", "[", ":", "-", "1", "]", ")", "shutil", ".", "rmtree", "(", "state_db_path", ")", "config_helper", "=", "NodeConfigHelper", "(", "node_to_stop", ".", "name", ",", "tconf", ",", "chroot", "=", "tdir", ")", "restarted_node", "=", "TestNode", "(", "node_to_stop", ".", "name", ",", "config_helper", "=", "config_helper", ",", "config", "=", "tconf", ",", "pluginPaths", "=", "allPluginsPath", ",", "ha", "=", "node_to_stop", ".", "nodestack", ".", "ha", ",", "cliha", "=", "node_to_stop", ".", "clientstack", ".", "ha", ")", "looper", ".", "add", "(", "restarted_node", ")", "nodeSet", "[", "-", "1", "]", "=", "restarted_node", "looper", ".", "run", "(", "checkNodesConnected", "(", "nodeSet", ")", ")", "# Need some time as `last_ordered_3PC` is compared too and that is", "# communicated through catchup", "waitNodeDataEquality", "(", "looper", ",", "restarted_node", ",", "*", "nodeSet", "[", ":", "-", "1", "]", ")", "# Pool is still functional", "for", "wh", "in", "endorsers", ":", "sdk_add_new_nym", "(", "looper", ",", "sdk_pool_handle", ",", "wh", ",", "'NP--'", "+", "randomString", "(", "5", ")", ")", "ensure_all_nodes_have_same_data", "(", "looper", ",", "nodeSet", ")" ]
[ 15, 0 ]
[ 74, 52 ]
python
en
['en', 'error', 'th']
False
pm_only
()
A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is derived from :exc:`.CheckFailure`.
A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is derived from :exc:`.CheckFailure`.
def pm_only(): """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is derived from :exc:`.CheckFailure`. """ def predicate(ctx): return ctx.guild is not None return commands.check(predicate)
[ "def", "pm_only", "(", ")", ":", "def", "predicate", "(", "ctx", ")", ":", "return", "ctx", ".", "guild", "is", "not", "None", "return", "commands", ".", "check", "(", "predicate", ")" ]
[ 35, 0 ]
[ 46, 36 ]
python
en
['en', 'en', 'en']
True
create_nuscenes_infos
(root_path, info_prefix, version='v1.0-trainval', max_sweeps=10)
Create info file of nuscene dataset. Given the raw data, generate its related info file in pkl format. Args: root_path (str): Path of the data root. info_prefix (str): Prefix of the info file to be generated. version (str): Version of the data. Default: 'v1.0-trainval' max_sweeps (int): Max number of sweeps. Default: 10
Create info file of nuscene dataset.
def create_nuscenes_infos(root_path, info_prefix, version='v1.0-trainval', max_sweeps=10): """Create info file of nuscene dataset. Given the raw data, generate its related info file in pkl format. Args: root_path (str): Path of the data root. info_prefix (str): Prefix of the info file to be generated. version (str): Version of the data. Default: 'v1.0-trainval' max_sweeps (int): Max number of sweeps. Default: 10 """ from nuscenes.nuscenes import NuScenes nusc = NuScenes(version=version, dataroot=root_path, verbose=True) from nuscenes.utils import splits available_vers = ['v1.0-trainval', 'v1.0-test', 'v1.0-mini'] assert version in available_vers if version == 'v1.0-trainval': train_scenes = splits.train val_scenes = splits.val elif version == 'v1.0-test': train_scenes = splits.test val_scenes = [] elif version == 'v1.0-mini': train_scenes = splits.mini_train val_scenes = splits.mini_val else: raise ValueError('unknown') # filter existing scenes. available_scenes = get_available_scenes(nusc) available_scene_names = [s['name'] for s in available_scenes] train_scenes = list( filter(lambda x: x in available_scene_names, train_scenes)) val_scenes = list(filter(lambda x: x in available_scene_names, val_scenes)) train_scenes = set([ available_scenes[available_scene_names.index(s)]['token'] for s in train_scenes ]) val_scenes = set([ available_scenes[available_scene_names.index(s)]['token'] for s in val_scenes ]) test = 'test' in version if test: print('test scene: {}'.format(len(train_scenes))) else: print('train scene: {}, val scene: {}'.format( len(train_scenes), len(val_scenes))) train_nusc_infos, val_nusc_infos = _fill_trainval_infos( nusc, train_scenes, val_scenes, test, max_sweeps=max_sweeps) metadata = dict(version=version) if test: print('test sample: {}'.format(len(train_nusc_infos))) data = dict(infos=train_nusc_infos, metadata=metadata) info_path = osp.join(root_path, '{}_infos_test.pkl'.format(info_prefix)) mmcv.dump(data, info_path) else: print('train sample: {}, val sample: {}'.format( len(train_nusc_infos), len(val_nusc_infos))) data = dict(infos=train_nusc_infos, metadata=metadata) info_path = osp.join(root_path, '{}_infos_train.pkl'.format(info_prefix)) mmcv.dump(data, info_path) data['infos'] = val_nusc_infos info_val_path = osp.join(root_path, '{}_infos_val.pkl'.format(info_prefix)) mmcv.dump(data, info_val_path)
[ "def", "create_nuscenes_infos", "(", "root_path", ",", "info_prefix", ",", "version", "=", "'v1.0-trainval'", ",", "max_sweeps", "=", "10", ")", ":", "from", "nuscenes", ".", "nuscenes", "import", "NuScenes", "nusc", "=", "NuScenes", "(", "version", "=", "version", ",", "dataroot", "=", "root_path", ",", "verbose", "=", "True", ")", "from", "nuscenes", ".", "utils", "import", "splits", "available_vers", "=", "[", "'v1.0-trainval'", ",", "'v1.0-test'", ",", "'v1.0-mini'", "]", "assert", "version", "in", "available_vers", "if", "version", "==", "'v1.0-trainval'", ":", "train_scenes", "=", "splits", ".", "train", "val_scenes", "=", "splits", ".", "val", "elif", "version", "==", "'v1.0-test'", ":", "train_scenes", "=", "splits", ".", "test", "val_scenes", "=", "[", "]", "elif", "version", "==", "'v1.0-mini'", ":", "train_scenes", "=", "splits", ".", "mini_train", "val_scenes", "=", "splits", ".", "mini_val", "else", ":", "raise", "ValueError", "(", "'unknown'", ")", "# filter existing scenes.", "available_scenes", "=", "get_available_scenes", "(", "nusc", ")", "available_scene_names", "=", "[", "s", "[", "'name'", "]", "for", "s", "in", "available_scenes", "]", "train_scenes", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "in", "available_scene_names", ",", "train_scenes", ")", ")", "val_scenes", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "in", "available_scene_names", ",", "val_scenes", ")", ")", "train_scenes", "=", "set", "(", "[", "available_scenes", "[", "available_scene_names", ".", "index", "(", "s", ")", "]", "[", "'token'", "]", "for", "s", "in", "train_scenes", "]", ")", "val_scenes", "=", "set", "(", "[", "available_scenes", "[", "available_scene_names", ".", "index", "(", "s", ")", "]", "[", "'token'", "]", "for", "s", "in", "val_scenes", "]", ")", "test", "=", "'test'", "in", "version", "if", "test", ":", "print", "(", "'test scene: {}'", ".", "format", "(", "len", "(", "train_scenes", ")", ")", ")", "else", ":", "print", "(", "'train scene: {}, val scene: {}'", ".", "format", "(", "len", "(", "train_scenes", ")", ",", "len", "(", "val_scenes", ")", ")", ")", "train_nusc_infos", ",", "val_nusc_infos", "=", "_fill_trainval_infos", "(", "nusc", ",", "train_scenes", ",", "val_scenes", ",", "test", ",", "max_sweeps", "=", "max_sweeps", ")", "metadata", "=", "dict", "(", "version", "=", "version", ")", "if", "test", ":", "print", "(", "'test sample: {}'", ".", "format", "(", "len", "(", "train_nusc_infos", ")", ")", ")", "data", "=", "dict", "(", "infos", "=", "train_nusc_infos", ",", "metadata", "=", "metadata", ")", "info_path", "=", "osp", ".", "join", "(", "root_path", ",", "'{}_infos_test.pkl'", ".", "format", "(", "info_prefix", ")", ")", "mmcv", ".", "dump", "(", "data", ",", "info_path", ")", "else", ":", "print", "(", "'train sample: {}, val sample: {}'", ".", "format", "(", "len", "(", "train_nusc_infos", ")", ",", "len", "(", "val_nusc_infos", ")", ")", ")", "data", "=", "dict", "(", "infos", "=", "train_nusc_infos", ",", "metadata", "=", "metadata", ")", "info_path", "=", "osp", ".", "join", "(", "root_path", ",", "'{}_infos_train.pkl'", ".", "format", "(", "info_prefix", ")", ")", "mmcv", ".", "dump", "(", "data", ",", "info_path", ")", "data", "[", "'infos'", "]", "=", "val_nusc_infos", "info_val_path", "=", "osp", ".", "join", "(", "root_path", ",", "'{}_infos_val.pkl'", ".", "format", "(", "info_prefix", ")", ")", "mmcv", ".", "dump", "(", "data", ",", "info_val_path", ")" ]
[ 18, 0 ]
[ 92, 38 ]
python
en
['en', 'et', 'en']
True
get_available_scenes
(nusc)
Get available scenes from the input nuscenes class. Given the raw data, get the information of available scenes for further info generation. Args: nusc (class): Dataset class in the nuScenes dataset. Returns: available_scenes (list[dict]): List of basic information for the available scenes.
Get available scenes from the input nuscenes class.
def get_available_scenes(nusc): """Get available scenes from the input nuscenes class. Given the raw data, get the information of available scenes for further info generation. Args: nusc (class): Dataset class in the nuScenes dataset. Returns: available_scenes (list[dict]): List of basic information for the available scenes. """ available_scenes = [] print('total scene num: {}'.format(len(nusc.scene))) for scene in nusc.scene: scene_token = scene['token'] scene_rec = nusc.get('scene', scene_token) sample_rec = nusc.get('sample', scene_rec['first_sample_token']) sd_rec = nusc.get('sample_data', sample_rec['data']['LIDAR_TOP']) has_more_frames = True scene_not_exist = False while has_more_frames: lidar_path, boxes, _ = nusc.get_sample_data(sd_rec['token']) lidar_path = str(lidar_path) if os.getcwd() in lidar_path: # path from lyftdataset is absolute path lidar_path = lidar_path.split(f'{os.getcwd()}/')[-1] # relative path if not mmcv.is_filepath(lidar_path): scene_not_exist = True break else: break if scene_not_exist: continue available_scenes.append(scene) print('exist scene num: {}'.format(len(available_scenes))) return available_scenes
[ "def", "get_available_scenes", "(", "nusc", ")", ":", "available_scenes", "=", "[", "]", "print", "(", "'total scene num: {}'", ".", "format", "(", "len", "(", "nusc", ".", "scene", ")", ")", ")", "for", "scene", "in", "nusc", ".", "scene", ":", "scene_token", "=", "scene", "[", "'token'", "]", "scene_rec", "=", "nusc", ".", "get", "(", "'scene'", ",", "scene_token", ")", "sample_rec", "=", "nusc", ".", "get", "(", "'sample'", ",", "scene_rec", "[", "'first_sample_token'", "]", ")", "sd_rec", "=", "nusc", ".", "get", "(", "'sample_data'", ",", "sample_rec", "[", "'data'", "]", "[", "'LIDAR_TOP'", "]", ")", "has_more_frames", "=", "True", "scene_not_exist", "=", "False", "while", "has_more_frames", ":", "lidar_path", ",", "boxes", ",", "_", "=", "nusc", ".", "get_sample_data", "(", "sd_rec", "[", "'token'", "]", ")", "lidar_path", "=", "str", "(", "lidar_path", ")", "if", "os", ".", "getcwd", "(", ")", "in", "lidar_path", ":", "# path from lyftdataset is absolute path", "lidar_path", "=", "lidar_path", ".", "split", "(", "f'{os.getcwd()}/'", ")", "[", "-", "1", "]", "# relative path", "if", "not", "mmcv", ".", "is_filepath", "(", "lidar_path", ")", ":", "scene_not_exist", "=", "True", "break", "else", ":", "break", "if", "scene_not_exist", ":", "continue", "available_scenes", ".", "append", "(", "scene", ")", "print", "(", "'exist scene num: {}'", ".", "format", "(", "len", "(", "available_scenes", ")", ")", ")", "return", "available_scenes" ]
[ 95, 0 ]
[ 133, 27 ]
python
en
['en', 'en', 'en']
True
_fill_trainval_infos
(nusc, train_scenes, val_scenes, test=False, max_sweeps=10)
Generate the train/val infos from the raw data. Args: nusc (:obj:`NuScenes`): Dataset class in the nuScenes dataset. train_scenes (list[str]): Basic information of training scenes. val_scenes (list[str]): Basic information of validation scenes. test (bool): Whether use the test mode. In the test mode, no annotations can be accessed. Default: False. max_sweeps (int): Max number of sweeps. Default: 10. Returns: tuple[list[dict]]: Information of training set and validation set that will be saved to the info file.
Generate the train/val infos from the raw data.
def _fill_trainval_infos(nusc, train_scenes, val_scenes, test=False, max_sweeps=10): """Generate the train/val infos from the raw data. Args: nusc (:obj:`NuScenes`): Dataset class in the nuScenes dataset. train_scenes (list[str]): Basic information of training scenes. val_scenes (list[str]): Basic information of validation scenes. test (bool): Whether use the test mode. In the test mode, no annotations can be accessed. Default: False. max_sweeps (int): Max number of sweeps. Default: 10. Returns: tuple[list[dict]]: Information of training set and validation set that will be saved to the info file. """ train_nusc_infos = [] val_nusc_infos = [] for sample in mmcv.track_iter_progress(nusc.sample): lidar_token = sample['data']['LIDAR_TOP'] sd_rec = nusc.get('sample_data', sample['data']['LIDAR_TOP']) cs_record = nusc.get('calibrated_sensor', sd_rec['calibrated_sensor_token']) pose_record = nusc.get('ego_pose', sd_rec['ego_pose_token']) lidar_path, boxes, _ = nusc.get_sample_data(lidar_token) mmcv.check_file_exist(lidar_path) info = { 'lidar_path': lidar_path, 'token': sample['token'], 'sweeps': [], 'cams': dict(), 'lidar2ego_translation': cs_record['translation'], 'lidar2ego_rotation': cs_record['rotation'], 'ego2global_translation': pose_record['translation'], 'ego2global_rotation': pose_record['rotation'], 'timestamp': sample['timestamp'], } l2e_r = info['lidar2ego_rotation'] l2e_t = info['lidar2ego_translation'] e2g_r = info['ego2global_rotation'] e2g_t = info['ego2global_translation'] l2e_r_mat = Quaternion(l2e_r).rotation_matrix e2g_r_mat = Quaternion(e2g_r).rotation_matrix # obtain 6 image's information per frame camera_types = [ 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_FRONT_LEFT', 'CAM_BACK', 'CAM_BACK_LEFT', 'CAM_BACK_RIGHT', ] for cam in camera_types: cam_token = sample['data'][cam] cam_path, _, cam_intrinsic = nusc.get_sample_data(cam_token) cam_info = obtain_sensor2top(nusc, cam_token, l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, cam) cam_info.update(cam_intrinsic=cam_intrinsic) info['cams'].update({cam: cam_info}) # obtain sweeps for a single key-frame sd_rec = nusc.get('sample_data', sample['data']['LIDAR_TOP']) sweeps = [] while len(sweeps) < max_sweeps: if not sd_rec['prev'] == '': sweep = obtain_sensor2top(nusc, sd_rec['prev'], l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, 'lidar') sweeps.append(sweep) sd_rec = nusc.get('sample_data', sd_rec['prev']) else: break info['sweeps'] = sweeps # obtain annotation if not test: annotations = [ nusc.get('sample_annotation', token) for token in sample['anns'] ] locs = np.array([b.center for b in boxes]).reshape(-1, 3) dims = np.array([b.wlh for b in boxes]).reshape(-1, 3) rots = np.array([b.orientation.yaw_pitch_roll[0] for b in boxes]).reshape(-1, 1) velocity = np.array( [nusc.box_velocity(token)[:2] for token in sample['anns']]) valid_flag = np.array( [(anno['num_lidar_pts'] + anno['num_radar_pts']) > 0 for anno in annotations], dtype=bool).reshape(-1) # convert velo from global to lidar for i in range(len(boxes)): velo = np.array([*velocity[i], 0.0]) velo = velo @ np.linalg.inv(e2g_r_mat).T @ np.linalg.inv( l2e_r_mat).T velocity[i] = velo[:2] names = [b.name for b in boxes] for i in range(len(names)): if names[i] in NuScenesDataset.NameMapping: names[i] = NuScenesDataset.NameMapping[names[i]] names = np.array(names) # we need to convert rot to SECOND format. gt_boxes = np.concatenate([locs, dims, -rots - np.pi / 2], axis=1) assert len(gt_boxes) == len( annotations), f'{len(gt_boxes)}, {len(annotations)}' info['gt_boxes'] = gt_boxes info['gt_names'] = names info['gt_velocity'] = velocity.reshape(-1, 2) info['num_lidar_pts'] = np.array( [a['num_lidar_pts'] for a in annotations]) info['num_radar_pts'] = np.array( [a['num_radar_pts'] for a in annotations]) info['valid_flag'] = valid_flag if sample['scene_token'] in train_scenes: train_nusc_infos.append(info) else: val_nusc_infos.append(info) return train_nusc_infos, val_nusc_infos
[ "def", "_fill_trainval_infos", "(", "nusc", ",", "train_scenes", ",", "val_scenes", ",", "test", "=", "False", ",", "max_sweeps", "=", "10", ")", ":", "train_nusc_infos", "=", "[", "]", "val_nusc_infos", "=", "[", "]", "for", "sample", "in", "mmcv", ".", "track_iter_progress", "(", "nusc", ".", "sample", ")", ":", "lidar_token", "=", "sample", "[", "'data'", "]", "[", "'LIDAR_TOP'", "]", "sd_rec", "=", "nusc", ".", "get", "(", "'sample_data'", ",", "sample", "[", "'data'", "]", "[", "'LIDAR_TOP'", "]", ")", "cs_record", "=", "nusc", ".", "get", "(", "'calibrated_sensor'", ",", "sd_rec", "[", "'calibrated_sensor_token'", "]", ")", "pose_record", "=", "nusc", ".", "get", "(", "'ego_pose'", ",", "sd_rec", "[", "'ego_pose_token'", "]", ")", "lidar_path", ",", "boxes", ",", "_", "=", "nusc", ".", "get_sample_data", "(", "lidar_token", ")", "mmcv", ".", "check_file_exist", "(", "lidar_path", ")", "info", "=", "{", "'lidar_path'", ":", "lidar_path", ",", "'token'", ":", "sample", "[", "'token'", "]", ",", "'sweeps'", ":", "[", "]", ",", "'cams'", ":", "dict", "(", ")", ",", "'lidar2ego_translation'", ":", "cs_record", "[", "'translation'", "]", ",", "'lidar2ego_rotation'", ":", "cs_record", "[", "'rotation'", "]", ",", "'ego2global_translation'", ":", "pose_record", "[", "'translation'", "]", ",", "'ego2global_rotation'", ":", "pose_record", "[", "'rotation'", "]", ",", "'timestamp'", ":", "sample", "[", "'timestamp'", "]", ",", "}", "l2e_r", "=", "info", "[", "'lidar2ego_rotation'", "]", "l2e_t", "=", "info", "[", "'lidar2ego_translation'", "]", "e2g_r", "=", "info", "[", "'ego2global_rotation'", "]", "e2g_t", "=", "info", "[", "'ego2global_translation'", "]", "l2e_r_mat", "=", "Quaternion", "(", "l2e_r", ")", ".", "rotation_matrix", "e2g_r_mat", "=", "Quaternion", "(", "e2g_r", ")", ".", "rotation_matrix", "# obtain 6 image's information per frame", "camera_types", "=", "[", "'CAM_FRONT'", ",", "'CAM_FRONT_RIGHT'", ",", "'CAM_FRONT_LEFT'", ",", "'CAM_BACK'", ",", "'CAM_BACK_LEFT'", ",", "'CAM_BACK_RIGHT'", ",", "]", "for", "cam", "in", "camera_types", ":", "cam_token", "=", "sample", "[", "'data'", "]", "[", "cam", "]", "cam_path", ",", "_", ",", "cam_intrinsic", "=", "nusc", ".", "get_sample_data", "(", "cam_token", ")", "cam_info", "=", "obtain_sensor2top", "(", "nusc", ",", "cam_token", ",", "l2e_t", ",", "l2e_r_mat", ",", "e2g_t", ",", "e2g_r_mat", ",", "cam", ")", "cam_info", ".", "update", "(", "cam_intrinsic", "=", "cam_intrinsic", ")", "info", "[", "'cams'", "]", ".", "update", "(", "{", "cam", ":", "cam_info", "}", ")", "# obtain sweeps for a single key-frame", "sd_rec", "=", "nusc", ".", "get", "(", "'sample_data'", ",", "sample", "[", "'data'", "]", "[", "'LIDAR_TOP'", "]", ")", "sweeps", "=", "[", "]", "while", "len", "(", "sweeps", ")", "<", "max_sweeps", ":", "if", "not", "sd_rec", "[", "'prev'", "]", "==", "''", ":", "sweep", "=", "obtain_sensor2top", "(", "nusc", ",", "sd_rec", "[", "'prev'", "]", ",", "l2e_t", ",", "l2e_r_mat", ",", "e2g_t", ",", "e2g_r_mat", ",", "'lidar'", ")", "sweeps", ".", "append", "(", "sweep", ")", "sd_rec", "=", "nusc", ".", "get", "(", "'sample_data'", ",", "sd_rec", "[", "'prev'", "]", ")", "else", ":", "break", "info", "[", "'sweeps'", "]", "=", "sweeps", "# obtain annotation", "if", "not", "test", ":", "annotations", "=", "[", "nusc", ".", "get", "(", "'sample_annotation'", ",", "token", ")", "for", "token", "in", "sample", "[", "'anns'", "]", "]", "locs", "=", "np", ".", "array", "(", "[", "b", ".", "center", "for", "b", "in", "boxes", "]", ")", ".", "reshape", "(", "-", "1", ",", "3", ")", "dims", "=", "np", ".", "array", "(", "[", "b", ".", "wlh", "for", "b", "in", "boxes", "]", ")", ".", "reshape", "(", "-", "1", ",", "3", ")", "rots", "=", "np", ".", "array", "(", "[", "b", ".", "orientation", ".", "yaw_pitch_roll", "[", "0", "]", "for", "b", "in", "boxes", "]", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", "velocity", "=", "np", ".", "array", "(", "[", "nusc", ".", "box_velocity", "(", "token", ")", "[", ":", "2", "]", "for", "token", "in", "sample", "[", "'anns'", "]", "]", ")", "valid_flag", "=", "np", ".", "array", "(", "[", "(", "anno", "[", "'num_lidar_pts'", "]", "+", "anno", "[", "'num_radar_pts'", "]", ")", ">", "0", "for", "anno", "in", "annotations", "]", ",", "dtype", "=", "bool", ")", ".", "reshape", "(", "-", "1", ")", "# convert velo from global to lidar", "for", "i", "in", "range", "(", "len", "(", "boxes", ")", ")", ":", "velo", "=", "np", ".", "array", "(", "[", "*", "velocity", "[", "i", "]", ",", "0.0", "]", ")", "velo", "=", "velo", "@", "np", ".", "linalg", ".", "inv", "(", "e2g_r_mat", ")", ".", "T", "@", "np", ".", "linalg", ".", "inv", "(", "l2e_r_mat", ")", ".", "T", "velocity", "[", "i", "]", "=", "velo", "[", ":", "2", "]", "names", "=", "[", "b", ".", "name", "for", "b", "in", "boxes", "]", "for", "i", "in", "range", "(", "len", "(", "names", ")", ")", ":", "if", "names", "[", "i", "]", "in", "NuScenesDataset", ".", "NameMapping", ":", "names", "[", "i", "]", "=", "NuScenesDataset", ".", "NameMapping", "[", "names", "[", "i", "]", "]", "names", "=", "np", ".", "array", "(", "names", ")", "# we need to convert rot to SECOND format.", "gt_boxes", "=", "np", ".", "concatenate", "(", "[", "locs", ",", "dims", ",", "-", "rots", "-", "np", ".", "pi", "/", "2", "]", ",", "axis", "=", "1", ")", "assert", "len", "(", "gt_boxes", ")", "==", "len", "(", "annotations", ")", ",", "f'{len(gt_boxes)}, {len(annotations)}'", "info", "[", "'gt_boxes'", "]", "=", "gt_boxes", "info", "[", "'gt_names'", "]", "=", "names", "info", "[", "'gt_velocity'", "]", "=", "velocity", ".", "reshape", "(", "-", "1", ",", "2", ")", "info", "[", "'num_lidar_pts'", "]", "=", "np", ".", "array", "(", "[", "a", "[", "'num_lidar_pts'", "]", "for", "a", "in", "annotations", "]", ")", "info", "[", "'num_radar_pts'", "]", "=", "np", ".", "array", "(", "[", "a", "[", "'num_radar_pts'", "]", "for", "a", "in", "annotations", "]", ")", "info", "[", "'valid_flag'", "]", "=", "valid_flag", "if", "sample", "[", "'scene_token'", "]", "in", "train_scenes", ":", "train_nusc_infos", ".", "append", "(", "info", ")", "else", ":", "val_nusc_infos", ".", "append", "(", "info", ")", "return", "train_nusc_infos", ",", "val_nusc_infos" ]
[ 136, 0 ]
[ 262, 43 ]
python
en
['en', 'en', 'en']
True
obtain_sensor2top
(nusc, sensor_token, l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, sensor_type='lidar')
Obtain the info with RT matric from general sensor to Top LiDAR. Args: nusc (class): Dataset class in the nuScenes dataset. sensor_token (str): Sample data token corresponding to the specific sensor type. l2e_t (np.ndarray): Translation from lidar to ego in shape (1, 3). l2e_r_mat (np.ndarray): Rotation matrix from lidar to ego in shape (3, 3). e2g_t (np.ndarray): Translation from ego to global in shape (1, 3). e2g_r_mat (np.ndarray): Rotation matrix from ego to global in shape (3, 3). sensor_type (str): Sensor to calibrate. Default: 'lidar'. Returns: sweep (dict): Sweep information after transformation.
Obtain the info with RT matric from general sensor to Top LiDAR.
def obtain_sensor2top(nusc, sensor_token, l2e_t, l2e_r_mat, e2g_t, e2g_r_mat, sensor_type='lidar'): """Obtain the info with RT matric from general sensor to Top LiDAR. Args: nusc (class): Dataset class in the nuScenes dataset. sensor_token (str): Sample data token corresponding to the specific sensor type. l2e_t (np.ndarray): Translation from lidar to ego in shape (1, 3). l2e_r_mat (np.ndarray): Rotation matrix from lidar to ego in shape (3, 3). e2g_t (np.ndarray): Translation from ego to global in shape (1, 3). e2g_r_mat (np.ndarray): Rotation matrix from ego to global in shape (3, 3). sensor_type (str): Sensor to calibrate. Default: 'lidar'. Returns: sweep (dict): Sweep information after transformation. """ sd_rec = nusc.get('sample_data', sensor_token) cs_record = nusc.get('calibrated_sensor', sd_rec['calibrated_sensor_token']) pose_record = nusc.get('ego_pose', sd_rec['ego_pose_token']) data_path = str(nusc.get_sample_data_path(sd_rec['token'])) if os.getcwd() in data_path: # path from lyftdataset is absolute path data_path = data_path.split(f'{os.getcwd()}/')[-1] # relative path sweep = { 'data_path': data_path, 'type': sensor_type, 'sample_data_token': sd_rec['token'], 'sensor2ego_translation': cs_record['translation'], 'sensor2ego_rotation': cs_record['rotation'], 'ego2global_translation': pose_record['translation'], 'ego2global_rotation': pose_record['rotation'], 'timestamp': sd_rec['timestamp'] } l2e_r_s = sweep['sensor2ego_rotation'] l2e_t_s = sweep['sensor2ego_translation'] e2g_r_s = sweep['ego2global_rotation'] e2g_t_s = sweep['ego2global_translation'] # obtain the RT from sensor to Top LiDAR # sweep->ego->global->ego'->lidar l2e_r_s_mat = Quaternion(l2e_r_s).rotation_matrix e2g_r_s_mat = Quaternion(e2g_r_s).rotation_matrix R = (l2e_r_s_mat.T @ e2g_r_s_mat.T) @ ( np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T) T = (l2e_t_s @ e2g_r_s_mat.T + e2g_t_s) @ ( np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T) T -= e2g_t @ (np.linalg.inv(e2g_r_mat).T @ np.linalg.inv(l2e_r_mat).T ) + l2e_t @ np.linalg.inv(l2e_r_mat).T sweep['sensor2lidar_rotation'] = R.T # points @ R.T + T sweep['sensor2lidar_translation'] = T return sweep
[ "def", "obtain_sensor2top", "(", "nusc", ",", "sensor_token", ",", "l2e_t", ",", "l2e_r_mat", ",", "e2g_t", ",", "e2g_r_mat", ",", "sensor_type", "=", "'lidar'", ")", ":", "sd_rec", "=", "nusc", ".", "get", "(", "'sample_data'", ",", "sensor_token", ")", "cs_record", "=", "nusc", ".", "get", "(", "'calibrated_sensor'", ",", "sd_rec", "[", "'calibrated_sensor_token'", "]", ")", "pose_record", "=", "nusc", ".", "get", "(", "'ego_pose'", ",", "sd_rec", "[", "'ego_pose_token'", "]", ")", "data_path", "=", "str", "(", "nusc", ".", "get_sample_data_path", "(", "sd_rec", "[", "'token'", "]", ")", ")", "if", "os", ".", "getcwd", "(", ")", "in", "data_path", ":", "# path from lyftdataset is absolute path", "data_path", "=", "data_path", ".", "split", "(", "f'{os.getcwd()}/'", ")", "[", "-", "1", "]", "# relative path", "sweep", "=", "{", "'data_path'", ":", "data_path", ",", "'type'", ":", "sensor_type", ",", "'sample_data_token'", ":", "sd_rec", "[", "'token'", "]", ",", "'sensor2ego_translation'", ":", "cs_record", "[", "'translation'", "]", ",", "'sensor2ego_rotation'", ":", "cs_record", "[", "'rotation'", "]", ",", "'ego2global_translation'", ":", "pose_record", "[", "'translation'", "]", ",", "'ego2global_rotation'", ":", "pose_record", "[", "'rotation'", "]", ",", "'timestamp'", ":", "sd_rec", "[", "'timestamp'", "]", "}", "l2e_r_s", "=", "sweep", "[", "'sensor2ego_rotation'", "]", "l2e_t_s", "=", "sweep", "[", "'sensor2ego_translation'", "]", "e2g_r_s", "=", "sweep", "[", "'ego2global_rotation'", "]", "e2g_t_s", "=", "sweep", "[", "'ego2global_translation'", "]", "# obtain the RT from sensor to Top LiDAR", "# sweep->ego->global->ego'->lidar", "l2e_r_s_mat", "=", "Quaternion", "(", "l2e_r_s", ")", ".", "rotation_matrix", "e2g_r_s_mat", "=", "Quaternion", "(", "e2g_r_s", ")", ".", "rotation_matrix", "R", "=", "(", "l2e_r_s_mat", ".", "T", "@", "e2g_r_s_mat", ".", "T", ")", "@", "(", "np", ".", "linalg", ".", "inv", "(", "e2g_r_mat", ")", ".", "T", "@", "np", ".", "linalg", ".", "inv", "(", "l2e_r_mat", ")", ".", "T", ")", "T", "=", "(", "l2e_t_s", "@", "e2g_r_s_mat", ".", "T", "+", "e2g_t_s", ")", "@", "(", "np", ".", "linalg", ".", "inv", "(", "e2g_r_mat", ")", ".", "T", "@", "np", ".", "linalg", ".", "inv", "(", "l2e_r_mat", ")", ".", "T", ")", "T", "-=", "e2g_t", "@", "(", "np", ".", "linalg", ".", "inv", "(", "e2g_r_mat", ")", ".", "T", "@", "np", ".", "linalg", ".", "inv", "(", "l2e_r_mat", ")", ".", "T", ")", "+", "l2e_t", "@", "np", ".", "linalg", ".", "inv", "(", "l2e_r_mat", ")", ".", "T", "sweep", "[", "'sensor2lidar_rotation'", "]", "=", "R", ".", "T", "# points @ R.T + T", "sweep", "[", "'sensor2lidar_translation'", "]", "=", "T", "return", "sweep" ]
[ 265, 0 ]
[ 323, 16 ]
python
en
['en', 'en', 'en']
True
export_2d_annotation
(root_path, info_path, version)
Export 2d annotation from the info file and raw data. Args: root_path (str): Root path of the raw data. info_path (str): Path of the info file. version (str): Dataset version.
Export 2d annotation from the info file and raw data.
def export_2d_annotation(root_path, info_path, version): """Export 2d annotation from the info file and raw data. Args: root_path (str): Root path of the raw data. info_path (str): Path of the info file. version (str): Dataset version. """ # get bbox annotations for camera camera_types = [ 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_FRONT_LEFT', 'CAM_BACK', 'CAM_BACK_LEFT', 'CAM_BACK_RIGHT', ] nusc_infos = mmcv.load(info_path)['infos'] nusc = NuScenes(version=version, dataroot=root_path, verbose=True) # info_2d_list = [] cat2Ids = [ dict(id=nus_categories.index(cat_name), name=cat_name) for cat_name in nus_categories ] coco_ann_id = 0 coco_2d_dict = dict(annotations=[], images=[], categories=cat2Ids) for info in mmcv.track_iter_progress(nusc_infos): for cam in camera_types: cam_info = info['cams'][cam] coco_infos = get_2d_boxes( nusc, cam_info['sample_data_token'], visibilities=['', '1', '2', '3', '4']) (height, width, _) = mmcv.imread(cam_info['data_path']).shape coco_2d_dict['images'].append( dict( file_name=cam_info['data_path'], id=cam_info['sample_data_token'], width=width, height=height)) for coco_info in coco_infos: if coco_info is None: continue # add an empty key for coco format coco_info['segmentation'] = [] coco_info['id'] = coco_ann_id coco_2d_dict['annotations'].append(coco_info) coco_ann_id += 1 mmcv.dump(coco_2d_dict, f'{info_path[:-4]}.coco.json')
[ "def", "export_2d_annotation", "(", "root_path", ",", "info_path", ",", "version", ")", ":", "# get bbox annotations for camera", "camera_types", "=", "[", "'CAM_FRONT'", ",", "'CAM_FRONT_RIGHT'", ",", "'CAM_FRONT_LEFT'", ",", "'CAM_BACK'", ",", "'CAM_BACK_LEFT'", ",", "'CAM_BACK_RIGHT'", ",", "]", "nusc_infos", "=", "mmcv", ".", "load", "(", "info_path", ")", "[", "'infos'", "]", "nusc", "=", "NuScenes", "(", "version", "=", "version", ",", "dataroot", "=", "root_path", ",", "verbose", "=", "True", ")", "# info_2d_list = []", "cat2Ids", "=", "[", "dict", "(", "id", "=", "nus_categories", ".", "index", "(", "cat_name", ")", ",", "name", "=", "cat_name", ")", "for", "cat_name", "in", "nus_categories", "]", "coco_ann_id", "=", "0", "coco_2d_dict", "=", "dict", "(", "annotations", "=", "[", "]", ",", "images", "=", "[", "]", ",", "categories", "=", "cat2Ids", ")", "for", "info", "in", "mmcv", ".", "track_iter_progress", "(", "nusc_infos", ")", ":", "for", "cam", "in", "camera_types", ":", "cam_info", "=", "info", "[", "'cams'", "]", "[", "cam", "]", "coco_infos", "=", "get_2d_boxes", "(", "nusc", ",", "cam_info", "[", "'sample_data_token'", "]", ",", "visibilities", "=", "[", "''", ",", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", "]", ")", "(", "height", ",", "width", ",", "_", ")", "=", "mmcv", ".", "imread", "(", "cam_info", "[", "'data_path'", "]", ")", ".", "shape", "coco_2d_dict", "[", "'images'", "]", ".", "append", "(", "dict", "(", "file_name", "=", "cam_info", "[", "'data_path'", "]", ",", "id", "=", "cam_info", "[", "'sample_data_token'", "]", ",", "width", "=", "width", ",", "height", "=", "height", ")", ")", "for", "coco_info", "in", "coco_infos", ":", "if", "coco_info", "is", "None", ":", "continue", "# add an empty key for coco format", "coco_info", "[", "'segmentation'", "]", "=", "[", "]", "coco_info", "[", "'id'", "]", "=", "coco_ann_id", "coco_2d_dict", "[", "'annotations'", "]", ".", "append", "(", "coco_info", ")", "coco_ann_id", "+=", "1", "mmcv", ".", "dump", "(", "coco_2d_dict", ",", "f'{info_path[:-4]}.coco.json'", ")" ]
[ 326, 0 ]
[ 374, 58 ]
python
en
['en', 'en', 'en']
True
get_2d_boxes
(nusc, sample_data_token: str, visibilities: List[str])
Get the 2D annotation records for a given `sample_data_token`. Args: sample_data_token: Sample data token belonging to a camera keyframe. visibilities: Visibility filter. Return: list[dict]: List of 2D annotation record that belongs to the input `sample_data_token`.
Get the 2D annotation records for a given `sample_data_token`.
def get_2d_boxes(nusc, sample_data_token: str, visibilities: List[str]) -> List[OrderedDict]: """Get the 2D annotation records for a given `sample_data_token`. Args: sample_data_token: Sample data token belonging to a camera keyframe. visibilities: Visibility filter. Return: list[dict]: List of 2D annotation record that belongs to the input `sample_data_token`. """ # Get the sample data and the sample corresponding to that sample data. sd_rec = nusc.get('sample_data', sample_data_token) assert sd_rec[ 'sensor_modality'] == 'camera', 'Error: get_2d_boxes only works' \ ' for camera sample_data!' if not sd_rec['is_key_frame']: raise ValueError( 'The 2D re-projections are available only for keyframes.') s_rec = nusc.get('sample', sd_rec['sample_token']) # Get the calibrated sensor and ego pose # record to get the transformation matrices. cs_rec = nusc.get('calibrated_sensor', sd_rec['calibrated_sensor_token']) pose_rec = nusc.get('ego_pose', sd_rec['ego_pose_token']) camera_intrinsic = np.array(cs_rec['camera_intrinsic']) # Get all the annotation with the specified visibilties. ann_recs = [ nusc.get('sample_annotation', token) for token in s_rec['anns'] ] ann_recs = [ ann_rec for ann_rec in ann_recs if (ann_rec['visibility_token'] in visibilities) ] repro_recs = [] for ann_rec in ann_recs: # Augment sample_annotation with token information. ann_rec['sample_annotation_token'] = ann_rec['token'] ann_rec['sample_data_token'] = sample_data_token # Get the box in global coordinates. box = nusc.get_box(ann_rec['token']) # Move them to the ego-pose frame. box.translate(-np.array(pose_rec['translation'])) box.rotate(Quaternion(pose_rec['rotation']).inverse) # Move them to the calibrated sensor frame. box.translate(-np.array(cs_rec['translation'])) box.rotate(Quaternion(cs_rec['rotation']).inverse) # Filter out the corners that are not in front of the calibrated # sensor. corners_3d = box.corners() in_front = np.argwhere(corners_3d[2, :] > 0).flatten() corners_3d = corners_3d[:, in_front] # Project 3d box to 2d. corner_coords = view_points(corners_3d, camera_intrinsic, True).T[:, :2].tolist() # Keep only corners that fall within the image. final_coords = post_process_coords(corner_coords) # Skip if the convex hull of the re-projected corners # does not intersect the image canvas. if final_coords is None: continue else: min_x, min_y, max_x, max_y = final_coords # Generate dictionary record to be included in the .json file. repro_rec = generate_record(ann_rec, min_x, min_y, max_x, max_y, sample_data_token, sd_rec['filename']) repro_recs.append(repro_rec) return repro_recs
[ "def", "get_2d_boxes", "(", "nusc", ",", "sample_data_token", ":", "str", ",", "visibilities", ":", "List", "[", "str", "]", ")", "->", "List", "[", "OrderedDict", "]", ":", "# Get the sample data and the sample corresponding to that sample data.", "sd_rec", "=", "nusc", ".", "get", "(", "'sample_data'", ",", "sample_data_token", ")", "assert", "sd_rec", "[", "'sensor_modality'", "]", "==", "'camera'", ",", "'Error: get_2d_boxes only works'", "' for camera sample_data!'", "if", "not", "sd_rec", "[", "'is_key_frame'", "]", ":", "raise", "ValueError", "(", "'The 2D re-projections are available only for keyframes.'", ")", "s_rec", "=", "nusc", ".", "get", "(", "'sample'", ",", "sd_rec", "[", "'sample_token'", "]", ")", "# Get the calibrated sensor and ego pose", "# record to get the transformation matrices.", "cs_rec", "=", "nusc", ".", "get", "(", "'calibrated_sensor'", ",", "sd_rec", "[", "'calibrated_sensor_token'", "]", ")", "pose_rec", "=", "nusc", ".", "get", "(", "'ego_pose'", ",", "sd_rec", "[", "'ego_pose_token'", "]", ")", "camera_intrinsic", "=", "np", ".", "array", "(", "cs_rec", "[", "'camera_intrinsic'", "]", ")", "# Get all the annotation with the specified visibilties.", "ann_recs", "=", "[", "nusc", ".", "get", "(", "'sample_annotation'", ",", "token", ")", "for", "token", "in", "s_rec", "[", "'anns'", "]", "]", "ann_recs", "=", "[", "ann_rec", "for", "ann_rec", "in", "ann_recs", "if", "(", "ann_rec", "[", "'visibility_token'", "]", "in", "visibilities", ")", "]", "repro_recs", "=", "[", "]", "for", "ann_rec", "in", "ann_recs", ":", "# Augment sample_annotation with token information.", "ann_rec", "[", "'sample_annotation_token'", "]", "=", "ann_rec", "[", "'token'", "]", "ann_rec", "[", "'sample_data_token'", "]", "=", "sample_data_token", "# Get the box in global coordinates.", "box", "=", "nusc", ".", "get_box", "(", "ann_rec", "[", "'token'", "]", ")", "# Move them to the ego-pose frame.", "box", ".", "translate", "(", "-", "np", ".", "array", "(", "pose_rec", "[", "'translation'", "]", ")", ")", "box", ".", "rotate", "(", "Quaternion", "(", "pose_rec", "[", "'rotation'", "]", ")", ".", "inverse", ")", "# Move them to the calibrated sensor frame.", "box", ".", "translate", "(", "-", "np", ".", "array", "(", "cs_rec", "[", "'translation'", "]", ")", ")", "box", ".", "rotate", "(", "Quaternion", "(", "cs_rec", "[", "'rotation'", "]", ")", ".", "inverse", ")", "# Filter out the corners that are not in front of the calibrated", "# sensor.", "corners_3d", "=", "box", ".", "corners", "(", ")", "in_front", "=", "np", ".", "argwhere", "(", "corners_3d", "[", "2", ",", ":", "]", ">", "0", ")", ".", "flatten", "(", ")", "corners_3d", "=", "corners_3d", "[", ":", ",", "in_front", "]", "# Project 3d box to 2d.", "corner_coords", "=", "view_points", "(", "corners_3d", ",", "camera_intrinsic", ",", "True", ")", ".", "T", "[", ":", ",", ":", "2", "]", ".", "tolist", "(", ")", "# Keep only corners that fall within the image.", "final_coords", "=", "post_process_coords", "(", "corner_coords", ")", "# Skip if the convex hull of the re-projected corners", "# does not intersect the image canvas.", "if", "final_coords", "is", "None", ":", "continue", "else", ":", "min_x", ",", "min_y", ",", "max_x", ",", "max_y", "=", "final_coords", "# Generate dictionary record to be included in the .json file.", "repro_rec", "=", "generate_record", "(", "ann_rec", ",", "min_x", ",", "min_y", ",", "max_x", ",", "max_y", ",", "sample_data_token", ",", "sd_rec", "[", "'filename'", "]", ")", "repro_recs", ".", "append", "(", "repro_rec", ")", "return", "repro_recs" ]
[ 377, 0 ]
[ 460, 21 ]
python
en
['en', 'en', 'en']
True
post_process_coords
( corner_coords: List, imsize: Tuple[int, int] = (1600, 900) )
Get the intersection of the convex hull of the reprojected bbox corners and the image canvas, return None if no intersection. Args: corner_coords (list[int]): Corner coordinates of reprojected bounding box. imsize (tuple[int]): Size of the image canvas. Return: tuple [float]: Intersection of the convex hull of the 2D box corners and the image canvas.
Get the intersection of the convex hull of the reprojected bbox corners and the image canvas, return None if no intersection.
def post_process_coords( corner_coords: List, imsize: Tuple[int, int] = (1600, 900) ) -> Union[Tuple[float, float, float, float], None]: """Get the intersection of the convex hull of the reprojected bbox corners and the image canvas, return None if no intersection. Args: corner_coords (list[int]): Corner coordinates of reprojected bounding box. imsize (tuple[int]): Size of the image canvas. Return: tuple [float]: Intersection of the convex hull of the 2D box corners and the image canvas. """ polygon_from_2d_box = MultiPoint(corner_coords).convex_hull img_canvas = box(0, 0, imsize[0], imsize[1]) if polygon_from_2d_box.intersects(img_canvas): img_intersection = polygon_from_2d_box.intersection(img_canvas) intersection_coords = np.array( [coord for coord in img_intersection.exterior.coords]) min_x = min(intersection_coords[:, 0]) min_y = min(intersection_coords[:, 1]) max_x = max(intersection_coords[:, 0]) max_y = max(intersection_coords[:, 1]) return min_x, min_y, max_x, max_y else: return None
[ "def", "post_process_coords", "(", "corner_coords", ":", "List", ",", "imsize", ":", "Tuple", "[", "int", ",", "int", "]", "=", "(", "1600", ",", "900", ")", ")", "->", "Union", "[", "Tuple", "[", "float", ",", "float", ",", "float", ",", "float", "]", ",", "None", "]", ":", "polygon_from_2d_box", "=", "MultiPoint", "(", "corner_coords", ")", ".", "convex_hull", "img_canvas", "=", "box", "(", "0", ",", "0", ",", "imsize", "[", "0", "]", ",", "imsize", "[", "1", "]", ")", "if", "polygon_from_2d_box", ".", "intersects", "(", "img_canvas", ")", ":", "img_intersection", "=", "polygon_from_2d_box", ".", "intersection", "(", "img_canvas", ")", "intersection_coords", "=", "np", ".", "array", "(", "[", "coord", "for", "coord", "in", "img_intersection", ".", "exterior", ".", "coords", "]", ")", "min_x", "=", "min", "(", "intersection_coords", "[", ":", ",", "0", "]", ")", "min_y", "=", "min", "(", "intersection_coords", "[", ":", ",", "1", "]", ")", "max_x", "=", "max", "(", "intersection_coords", "[", ":", ",", "0", "]", ")", "max_y", "=", "max", "(", "intersection_coords", "[", ":", ",", "1", "]", ")", "return", "min_x", ",", "min_y", ",", "max_x", ",", "max_y", "else", ":", "return", "None" ]
[ 463, 0 ]
[ 493, 19 ]
python
en
['en', 'en', 'en']
True
generate_record
(ann_rec: dict, x1: float, y1: float, x2: float, y2: float, sample_data_token: str, filename: str)
Generate one 2D annotation record given various informations on top of the 2D bounding box coordinates. Args: ann_rec (dict): Original 3d annotation record. x1 (float): Minimum value of the x coordinate. y1 (float): Minimum value of the y coordinate. x2 (float): Maximum value of the x coordinate. y2 (float): Maximum value of the y coordinate. sample_data_token (str): Sample data token. filename (str):The corresponding image file where the annotation is present. Returns: dict: A sample 2D annotation record. - file_name (str): flie name - image_id (str): sample data token - area (float): 2d box area - category_name (str): category name - category_id (int): category id - bbox (list[float]): left x, top y, dx, dy of 2d box - iscrowd (int): whether the area is crowd
Generate one 2D annotation record given various informations on top of the 2D bounding box coordinates.
def generate_record(ann_rec: dict, x1: float, y1: float, x2: float, y2: float, sample_data_token: str, filename: str) -> OrderedDict: """Generate one 2D annotation record given various informations on top of the 2D bounding box coordinates. Args: ann_rec (dict): Original 3d annotation record. x1 (float): Minimum value of the x coordinate. y1 (float): Minimum value of the y coordinate. x2 (float): Maximum value of the x coordinate. y2 (float): Maximum value of the y coordinate. sample_data_token (str): Sample data token. filename (str):The corresponding image file where the annotation is present. Returns: dict: A sample 2D annotation record. - file_name (str): flie name - image_id (str): sample data token - area (float): 2d box area - category_name (str): category name - category_id (int): category id - bbox (list[float]): left x, top y, dx, dy of 2d box - iscrowd (int): whether the area is crowd """ repro_rec = OrderedDict() repro_rec['sample_data_token'] = sample_data_token coco_rec = dict() relevant_keys = [ 'attribute_tokens', 'category_name', 'instance_token', 'next', 'num_lidar_pts', 'num_radar_pts', 'prev', 'sample_annotation_token', 'sample_data_token', 'visibility_token', ] for key, value in ann_rec.items(): if key in relevant_keys: repro_rec[key] = value repro_rec['bbox_corners'] = [x1, y1, x2, y2] repro_rec['filename'] = filename coco_rec['file_name'] = filename coco_rec['image_id'] = sample_data_token coco_rec['area'] = (y2 - y1) * (x2 - x1) if repro_rec['category_name'] not in NuScenesDataset.NameMapping: return None cat_name = NuScenesDataset.NameMapping[repro_rec['category_name']] coco_rec['category_name'] = cat_name coco_rec['category_id'] = nus_categories.index(cat_name) coco_rec['bbox'] = [x1, y1, x2 - x1, y2 - y1] coco_rec['iscrowd'] = 0 return coco_rec
[ "def", "generate_record", "(", "ann_rec", ":", "dict", ",", "x1", ":", "float", ",", "y1", ":", "float", ",", "x2", ":", "float", ",", "y2", ":", "float", ",", "sample_data_token", ":", "str", ",", "filename", ":", "str", ")", "->", "OrderedDict", ":", "repro_rec", "=", "OrderedDict", "(", ")", "repro_rec", "[", "'sample_data_token'", "]", "=", "sample_data_token", "coco_rec", "=", "dict", "(", ")", "relevant_keys", "=", "[", "'attribute_tokens'", ",", "'category_name'", ",", "'instance_token'", ",", "'next'", ",", "'num_lidar_pts'", ",", "'num_radar_pts'", ",", "'prev'", ",", "'sample_annotation_token'", ",", "'sample_data_token'", ",", "'visibility_token'", ",", "]", "for", "key", ",", "value", "in", "ann_rec", ".", "items", "(", ")", ":", "if", "key", "in", "relevant_keys", ":", "repro_rec", "[", "key", "]", "=", "value", "repro_rec", "[", "'bbox_corners'", "]", "=", "[", "x1", ",", "y1", ",", "x2", ",", "y2", "]", "repro_rec", "[", "'filename'", "]", "=", "filename", "coco_rec", "[", "'file_name'", "]", "=", "filename", "coco_rec", "[", "'image_id'", "]", "=", "sample_data_token", "coco_rec", "[", "'area'", "]", "=", "(", "y2", "-", "y1", ")", "*", "(", "x2", "-", "x1", ")", "if", "repro_rec", "[", "'category_name'", "]", "not", "in", "NuScenesDataset", ".", "NameMapping", ":", "return", "None", "cat_name", "=", "NuScenesDataset", ".", "NameMapping", "[", "repro_rec", "[", "'category_name'", "]", "]", "coco_rec", "[", "'category_name'", "]", "=", "cat_name", "coco_rec", "[", "'category_id'", "]", "=", "nus_categories", ".", "index", "(", "cat_name", ")", "coco_rec", "[", "'bbox'", "]", "=", "[", "x1", ",", "y1", ",", "x2", "-", "x1", ",", "y2", "-", "y1", "]", "coco_rec", "[", "'iscrowd'", "]", "=", "0", "return", "coco_rec" ]
[ 496, 0 ]
[ 557, 19 ]
python
en
['en', 'en', 'en']
True
_Voxelization.forward
(ctx, points, voxel_size, coors_range, max_points=35, max_voxels=20000)
convert kitti points(N, >=3) to voxels. Args: points: [N, ndim] float tensor. points[:, :3] contain xyz points and points[:, 3:] contain other information like reflectivity voxel_size: [3] list/tuple or array, float. xyz, indicate voxel size coors_range: [6] list/tuple or array, float. indicate voxel range. format: xyzxyz, minmax max_points: int. indicate maximum points contained in a voxel. if max_points=-1, it means using dynamic_voxelize max_voxels: int. indicate maximum voxels this function create. for second, 20000 is a good choice. Users should shuffle points before call this function because max_voxels may drop points. Returns: voxels: [M, max_points, ndim] float tensor. only contain points and returned when max_points != -1. coordinates: [M, 3] int32 tensor, always returned. num_points_per_voxel: [M] int32 tensor. Only returned when max_points != -1.
convert kitti points(N, >=3) to voxels.
def forward(ctx, points, voxel_size, coors_range, max_points=35, max_voxels=20000): """convert kitti points(N, >=3) to voxels. Args: points: [N, ndim] float tensor. points[:, :3] contain xyz points and points[:, 3:] contain other information like reflectivity voxel_size: [3] list/tuple or array, float. xyz, indicate voxel size coors_range: [6] list/tuple or array, float. indicate voxel range. format: xyzxyz, minmax max_points: int. indicate maximum points contained in a voxel. if max_points=-1, it means using dynamic_voxelize max_voxels: int. indicate maximum voxels this function create. for second, 20000 is a good choice. Users should shuffle points before call this function because max_voxels may drop points. Returns: voxels: [M, max_points, ndim] float tensor. only contain points and returned when max_points != -1. coordinates: [M, 3] int32 tensor, always returned. num_points_per_voxel: [M] int32 tensor. Only returned when max_points != -1. """ if max_points == -1 or max_voxels == -1: coors = points.new_zeros(size=(points.size(0), 3), dtype=torch.int) dynamic_voxelize(points, coors, voxel_size, coors_range, 3) return coors else: voxels = points.new_zeros( size=(max_voxels, max_points, points.size(1))) coors = points.new_zeros(size=(max_voxels, 3), dtype=torch.int) num_points_per_voxel = points.new_zeros( size=(max_voxels, ), dtype=torch.int) voxel_num = hard_voxelize(points, voxels, coors, num_points_per_voxel, voxel_size, coors_range, max_points, max_voxels, 3) # select the valid voxels voxels_out = voxels[:voxel_num] coors_out = coors[:voxel_num] num_points_per_voxel_out = num_points_per_voxel[:voxel_num] return voxels_out, coors_out, num_points_per_voxel_out
[ "def", "forward", "(", "ctx", ",", "points", ",", "voxel_size", ",", "coors_range", ",", "max_points", "=", "35", ",", "max_voxels", "=", "20000", ")", ":", "if", "max_points", "==", "-", "1", "or", "max_voxels", "==", "-", "1", ":", "coors", "=", "points", ".", "new_zeros", "(", "size", "=", "(", "points", ".", "size", "(", "0", ")", ",", "3", ")", ",", "dtype", "=", "torch", ".", "int", ")", "dynamic_voxelize", "(", "points", ",", "coors", ",", "voxel_size", ",", "coors_range", ",", "3", ")", "return", "coors", "else", ":", "voxels", "=", "points", ".", "new_zeros", "(", "size", "=", "(", "max_voxels", ",", "max_points", ",", "points", ".", "size", "(", "1", ")", ")", ")", "coors", "=", "points", ".", "new_zeros", "(", "size", "=", "(", "max_voxels", ",", "3", ")", ",", "dtype", "=", "torch", ".", "int", ")", "num_points_per_voxel", "=", "points", ".", "new_zeros", "(", "size", "=", "(", "max_voxels", ",", ")", ",", "dtype", "=", "torch", ".", "int", ")", "voxel_num", "=", "hard_voxelize", "(", "points", ",", "voxels", ",", "coors", ",", "num_points_per_voxel", ",", "voxel_size", ",", "coors_range", ",", "max_points", ",", "max_voxels", ",", "3", ")", "# select the valid voxels", "voxels_out", "=", "voxels", "[", ":", "voxel_num", "]", "coors_out", "=", "coors", "[", ":", "voxel_num", "]", "num_points_per_voxel_out", "=", "num_points_per_voxel", "[", ":", "voxel_num", "]", "return", "voxels_out", ",", "coors_out", ",", "num_points_per_voxel_out" ]
[ 12, 4 ]
[ 57, 66 ]
python
en
['it', 'en', 'hi']
False
Voxelization.__init__
(self, voxel_size, point_cloud_range, max_num_points, max_voxels=20000)
Args: voxel_size (list): list [x, y, z] size of three dimension point_cloud_range (list): [x_min, y_min, z_min, x_max, y_max, z_max] max_num_points (int): max number of points per voxel max_voxels (tuple or int): max number of voxels in (training, testing) time
Args: voxel_size (list): list [x, y, z] size of three dimension point_cloud_range (list): [x_min, y_min, z_min, x_max, y_max, z_max] max_num_points (int): max number of points per voxel max_voxels (tuple or int): max number of voxels in (training, testing) time
def __init__(self, voxel_size, point_cloud_range, max_num_points, max_voxels=20000): super(Voxelization, self).__init__() """ Args: voxel_size (list): list [x, y, z] size of three dimension point_cloud_range (list): [x_min, y_min, z_min, x_max, y_max, z_max] max_num_points (int): max number of points per voxel max_voxels (tuple or int): max number of voxels in (training, testing) time """ self.voxel_size = voxel_size self.point_cloud_range = point_cloud_range self.max_num_points = max_num_points if isinstance(max_voxels, tuple): self.max_voxels = max_voxels else: self.max_voxels = _pair(max_voxels) point_cloud_range = torch.tensor( point_cloud_range, dtype=torch.float32) # [0, -40, -3, 70.4, 40, 1] voxel_size = torch.tensor(voxel_size, dtype=torch.float32) grid_size = (point_cloud_range[3:] - point_cloud_range[:3]) / voxel_size grid_size = torch.round(grid_size).long() input_feat_shape = grid_size[:2] self.grid_size = grid_size # the origin shape is as [x-len, y-len, z-len] # [w, h, d] -> [d, h, w] self.pcd_shape = [*input_feat_shape, 1][::-1]
[ "def", "__init__", "(", "self", ",", "voxel_size", ",", "point_cloud_range", ",", "max_num_points", ",", "max_voxels", "=", "20000", ")", ":", "super", "(", "Voxelization", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "voxel_size", "=", "voxel_size", "self", ".", "point_cloud_range", "=", "point_cloud_range", "self", ".", "max_num_points", "=", "max_num_points", "if", "isinstance", "(", "max_voxels", ",", "tuple", ")", ":", "self", ".", "max_voxels", "=", "max_voxels", "else", ":", "self", ".", "max_voxels", "=", "_pair", "(", "max_voxels", ")", "point_cloud_range", "=", "torch", ".", "tensor", "(", "point_cloud_range", ",", "dtype", "=", "torch", ".", "float32", ")", "# [0, -40, -3, 70.4, 40, 1]", "voxel_size", "=", "torch", ".", "tensor", "(", "voxel_size", ",", "dtype", "=", "torch", ".", "float32", ")", "grid_size", "=", "(", "point_cloud_range", "[", "3", ":", "]", "-", "point_cloud_range", "[", ":", "3", "]", ")", "/", "voxel_size", "grid_size", "=", "torch", ".", "round", "(", "grid_size", ")", ".", "long", "(", ")", "input_feat_shape", "=", "grid_size", "[", ":", "2", "]", "self", ".", "grid_size", "=", "grid_size", "# the origin shape is as [x-len, y-len, z-len]", "# [w, h, d] -> [d, h, w]", "self", ".", "pcd_shape", "=", "[", "*", "input_feat_shape", ",", "1", "]", "[", ":", ":", "-", "1", "]" ]
[ 65, 4 ]
[ 99, 53 ]
python
en
['en', 'error', 'th']
False
Voxelization.forward
(self, input)
Args: input: NC points
Args: input: NC points
def forward(self, input): """ Args: input: NC points """ if self.training: max_voxels = self.max_voxels[0] else: max_voxels = self.max_voxels[1] return voxelization(input, self.voxel_size, self.point_cloud_range, self.max_num_points, max_voxels)
[ "def", "forward", "(", "self", ",", "input", ")", ":", "if", "self", ".", "training", ":", "max_voxels", "=", "self", ".", "max_voxels", "[", "0", "]", "else", ":", "max_voxels", "=", "self", ".", "max_voxels", "[", "1", "]", "return", "voxelization", "(", "input", ",", "self", ".", "voxel_size", ",", "self", ".", "point_cloud_range", ",", "self", ".", "max_num_points", ",", "max_voxels", ")" ]
[ 101, 4 ]
[ 112, 60 ]
python
en
['en', 'error', 'th']
False
TestZooAndTasks.test_zoolist_fields
(self)
Ensure zoo entries conform to style standards.
Ensure zoo entries conform to style standards.
def test_zoolist_fields(self): """ Ensure zoo entries conform to style standards. """ for animal in model_list: self._assertZooString('title', animal) name = animal['title'] # every task must at least contain these for key in ['id', 'task', 'description', 'example', 'result']: self._assertZooString(key, animal, name) # if there's a second example there should be a second result if 'example2' in animal: self._assertZooString('result2', animal, name) # every entry needs a project page or a website self.assertTrue( ("project" in animal) or ("external_website" in animal), f"Zoo entry ({name}) should contain either project or external_website", )
[ "def", "test_zoolist_fields", "(", "self", ")", ":", "for", "animal", "in", "model_list", ":", "self", ".", "_assertZooString", "(", "'title'", ",", "animal", ")", "name", "=", "animal", "[", "'title'", "]", "# every task must at least contain these", "for", "key", "in", "[", "'id'", ",", "'task'", ",", "'description'", ",", "'example'", ",", "'result'", "]", ":", "self", ".", "_assertZooString", "(", "key", ",", "animal", ",", "name", ")", "# if there's a second example there should be a second result", "if", "'example2'", "in", "animal", ":", "self", ".", "_assertZooString", "(", "'result2'", ",", "animal", ",", "name", ")", "# every entry needs a project page or a website", "self", ".", "assertTrue", "(", "(", "\"project\"", "in", "animal", ")", "or", "(", "\"external_website\"", "in", "animal", ")", ",", "f\"Zoo entry ({name}) should contain either project or external_website\"", ",", ")" ]
[ 34, 4 ]
[ 54, 13 ]
python
en
['en', 'error', 'th']
False
TestZooAndTasks.test_zoolist_types
(self)
Ensure no type errors in the model zoo.
Ensure no type errors in the model zoo.
def test_zoolist_types(self): """ Ensure no type errors in the model zoo. """ self._check_types(model_list, 'Zoo')
[ "def", "test_zoolist_types", "(", "self", ")", ":", "self", ".", "_check_types", "(", "model_list", ",", "'Zoo'", ")" ]
[ 56, 4 ]
[ 60, 44 ]
python
en
['en', 'error', 'th']
False
TestZooAndTasks.test_tasklist_types
(self)
Ensure no type errors in the task list.
Ensure no type errors in the task list.
def test_tasklist_types(self): """ Ensure no type errors in the task list. """ self._check_types(task_list, 'Task')
[ "def", "test_tasklist_types", "(", "self", ")", ":", "self", ".", "_check_types", "(", "task_list", ",", "'Task'", ")" ]
[ 62, 4 ]
[ 66, 44 ]
python
en
['en', 'error', 'th']
False
TestZooAndTasks.test_tasklist
(self)
Check the task list for issues.
Check the task list for issues.
def test_tasklist(self): """ Check the task list for issues. """ self._check_directory( "task_list", task_list, "parlai/tasks", "task", ignore=['fromfile', 'interactive', 'jsonfile', 'wrapper'], )
[ "def", "test_tasklist", "(", "self", ")", ":", "self", ".", "_check_directory", "(", "\"task_list\"", ",", "task_list", ",", "\"parlai/tasks\"", ",", "\"task\"", ",", "ignore", "=", "[", "'fromfile'", ",", "'interactive'", ",", "'jsonfile'", ",", "'wrapper'", "]", ",", ")" ]
[ 69, 4 ]
[ 79, 9 ]
python
en
['en', 'error', 'th']
False
TestZooAndTasks.test_zoolist
(self)
Check the zoo list for issues.
Check the zoo list for issues.
def test_zoolist(self): """ Check the zoo list for issues. """ self._check_directory( "model_list", model_list, "parlai/zoo", "id", ignore=ZOO_EXCEPTIONS )
[ "def", "test_zoolist", "(", "self", ")", ":", "self", ".", "_check_directory", "(", "\"model_list\"", ",", "model_list", ",", "\"parlai/zoo\"", ",", "\"id\"", ",", "ignore", "=", "ZOO_EXCEPTIONS", ")" ]
[ 82, 4 ]
[ 88, 9 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_noevalmode
(self)
Ensure you get an error trying to use eval_model with -dt train.
Ensure you get an error trying to use eval_model with -dt train.
def test_noevalmode(self): """ Ensure you get an error trying to use eval_model with -dt train. """ with self.assertRaises(ValueError): testing_utils.eval_model( {'task': 'integration_tests', 'model': 'repeat_label'}, valid_datatype='train', )
[ "def", "test_noevalmode", "(", "self", ")", ":", "with", "self", ".", "assertRaises", "(", "ValueError", ")", ":", "testing_utils", ".", "eval_model", "(", "{", "'task'", ":", "'integration_tests'", ",", "'model'", ":", "'repeat_label'", "}", ",", "valid_datatype", "=", "'train'", ",", ")" ]
[ 16, 4 ]
[ 24, 13 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_evalmode
(self)
Eval_model with -dt train:evalmode should be okay.
Eval_model with -dt train:evalmode should be okay.
def test_evalmode(self): """ Eval_model with -dt train:evalmode should be okay. """ testing_utils.eval_model( {'task': 'integration_tests', 'model': 'repeat_label'}, valid_datatype='train:evalmode', )
[ "def", "test_evalmode", "(", "self", ")", ":", "testing_utils", ".", "eval_model", "(", "{", "'task'", ":", "'integration_tests'", ",", "'model'", ":", "'repeat_label'", "}", ",", "valid_datatype", "=", "'train:evalmode'", ",", ")" ]
[ 26, 4 ]
[ 33, 9 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_output
(self)
Test output of running eval_model.
Test output of running eval_model.
def test_output(self): """ Test output of running eval_model. """ opt = dict( task='integration_tests', model='repeat_label', datatype='valid', num_examples=5, display_examples=False, ) valid, test = testing_utils.eval_model(opt) self.assertEqual(valid['accuracy'], 1) self.assertEqual(test['accuracy'], 1) self.assertNotIn('rouge_L', valid) self.assertNotIn('rouge_L', test)
[ "def", "test_output", "(", "self", ")", ":", "opt", "=", "dict", "(", "task", "=", "'integration_tests'", ",", "model", "=", "'repeat_label'", ",", "datatype", "=", "'valid'", ",", "num_examples", "=", "5", ",", "display_examples", "=", "False", ",", ")", "valid", ",", "test", "=", "testing_utils", ".", "eval_model", "(", "opt", ")", "self", ".", "assertEqual", "(", "valid", "[", "'accuracy'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'accuracy'", "]", ",", "1", ")", "self", ".", "assertNotIn", "(", "'rouge_L'", ",", "valid", ")", "self", ".", "assertNotIn", "(", "'rouge_L'", ",", "test", ")" ]
[ 35, 4 ]
[ 52, 41 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_metrics_all
(self)
Test output of running eval_model.
Test output of running eval_model.
def test_metrics_all(self): """ Test output of running eval_model. """ opt = dict( task='integration_tests', model='repeat_label', datatype='valid', num_examples=5, display_examples=False, metrics='all', ) valid, test = testing_utils.eval_model(opt) self.assertEqual(valid['accuracy'], 1) self.assertEqual(valid['rouge_L'], 1) self.assertEqual(valid['rouge_1'], 1) self.assertEqual(valid['rouge_2'], 1) self.assertEqual(test['accuracy'], 1) self.assertEqual(test['rouge_L'], 1) self.assertEqual(test['rouge_1'], 1) self.assertEqual(test['rouge_2'], 1)
[ "def", "test_metrics_all", "(", "self", ")", ":", "opt", "=", "dict", "(", "task", "=", "'integration_tests'", ",", "model", "=", "'repeat_label'", ",", "datatype", "=", "'valid'", ",", "num_examples", "=", "5", ",", "display_examples", "=", "False", ",", "metrics", "=", "'all'", ",", ")", "valid", ",", "test", "=", "testing_utils", ".", "eval_model", "(", "opt", ")", "self", ".", "assertEqual", "(", "valid", "[", "'accuracy'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "valid", "[", "'rouge_L'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "valid", "[", "'rouge_1'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "valid", "[", "'rouge_2'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'accuracy'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'rouge_L'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'rouge_1'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'rouge_2'", "]", ",", "1", ")" ]
[ 56, 4 ]
[ 78, 44 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_metrics_select
(self)
Test output of running eval_model.
Test output of running eval_model.
def test_metrics_select(self): """ Test output of running eval_model. """ opt = dict( task='integration_tests', model='repeat_label', datatype='valid', num_examples=5, display_examples=False, metrics='accuracy,rouge', ) valid, test = testing_utils.eval_model(opt) self.assertEqual(valid['accuracy'], 1) self.assertEqual(valid['rouge_L'], 1) self.assertEqual(valid['rouge_1'], 1) self.assertEqual(valid['rouge_2'], 1) self.assertEqual(test['accuracy'], 1) self.assertEqual(test['rouge_L'], 1) self.assertEqual(test['rouge_1'], 1) self.assertEqual(test['rouge_2'], 1) self.assertNotIn('bleu-4', valid) self.assertNotIn('bleu-4', test)
[ "def", "test_metrics_select", "(", "self", ")", ":", "opt", "=", "dict", "(", "task", "=", "'integration_tests'", ",", "model", "=", "'repeat_label'", ",", "datatype", "=", "'valid'", ",", "num_examples", "=", "5", ",", "display_examples", "=", "False", ",", "metrics", "=", "'accuracy,rouge'", ",", ")", "valid", ",", "test", "=", "testing_utils", ".", "eval_model", "(", "opt", ")", "self", ".", "assertEqual", "(", "valid", "[", "'accuracy'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "valid", "[", "'rouge_L'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "valid", "[", "'rouge_1'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "valid", "[", "'rouge_2'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'accuracy'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'rouge_L'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'rouge_1'", "]", ",", "1", ")", "self", ".", "assertEqual", "(", "test", "[", "'rouge_2'", "]", ",", "1", ")", "self", ".", "assertNotIn", "(", "'bleu-4'", ",", "valid", ")", "self", ".", "assertNotIn", "(", "'bleu-4'", ",", "test", ")" ]
[ 82, 4 ]
[ 107, 40 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_train_evalmode
(self)
Test that evaluating a model with train:evalmode completes an epoch.
Test that evaluating a model with train:evalmode completes an epoch.
def test_train_evalmode(self): """ Test that evaluating a model with train:evalmode completes an epoch. """ base_dict = {'model': 'repeat_label', 'datatype': 'train:evalmode'} teachers = ['integration_tests:fixed_dialog_candidate', 'integration_tests'] batchsize = [1, 64] for bs in batchsize: for teacher in teachers: d = base_dict.copy() d['task'] = teacher d['batchsize'] = bs with testing_utils.timeout(time=20): valid, test = testing_utils.eval_model( d, valid_datatype=d['datatype'] ) self.assertEqual( int(valid['exs']), 500, f'train:evalmode failed with bs {bs} and teacher {teacher}', )
[ "def", "test_train_evalmode", "(", "self", ")", ":", "base_dict", "=", "{", "'model'", ":", "'repeat_label'", ",", "'datatype'", ":", "'train:evalmode'", "}", "teachers", "=", "[", "'integration_tests:fixed_dialog_candidate'", ",", "'integration_tests'", "]", "batchsize", "=", "[", "1", ",", "64", "]", "for", "bs", "in", "batchsize", ":", "for", "teacher", "in", "teachers", ":", "d", "=", "base_dict", ".", "copy", "(", ")", "d", "[", "'task'", "]", "=", "teacher", "d", "[", "'batchsize'", "]", "=", "bs", "with", "testing_utils", ".", "timeout", "(", "time", "=", "20", ")", ":", "valid", ",", "test", "=", "testing_utils", ".", "eval_model", "(", "d", ",", "valid_datatype", "=", "d", "[", "'datatype'", "]", ")", "self", ".", "assertEqual", "(", "int", "(", "valid", "[", "'exs'", "]", ")", ",", "500", ",", "f'train:evalmode failed with bs {bs} and teacher {teacher}'", ",", ")" ]
[ 183, 4 ]
[ 204, 17 ]
python
en
['en', 'error', 'th']
False
TestEvalModel.test_save_report
(self)
Test that we can save report from eval model.
Test that we can save report from eval model.
def test_save_report(self): """ Test that we can save report from eval model. """ with testing_utils.tempdir() as tmpdir: save_report = os.path.join(tmpdir, 'report') opt = dict( task='integration_tests', model='repeat_label', datatype='valid', num_examples=5, display_examples=False, world_logs=save_report, report_filename=save_report, ) valid, test = testing_utils.eval_model(opt)
[ "def", "test_save_report", "(", "self", ")", ":", "with", "testing_utils", ".", "tempdir", "(", ")", "as", "tmpdir", ":", "save_report", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'report'", ")", "opt", "=", "dict", "(", "task", "=", "'integration_tests'", ",", "model", "=", "'repeat_label'", ",", "datatype", "=", "'valid'", ",", "num_examples", "=", "5", ",", "display_examples", "=", "False", ",", "world_logs", "=", "save_report", ",", "report_filename", "=", "save_report", ",", ")", "valid", ",", "test", "=", "testing_utils", ".", "eval_model", "(", "opt", ")" ]
[ 206, 4 ]
[ 221, 55 ]
python
en
['en', 'error', 'th']
False
Threshold.line
(self)
The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.indicator.gauge.threshold.Line` - A dict of string/value properties that will be passed to the Line constructor Supported dict properties: color Sets the color of the threshold line. width Sets the width (in px) of the threshold line. Returns ------- plotly.graph_objs.indicator.gauge.threshold.Line
The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.indicator.gauge.threshold.Line` - A dict of string/value properties that will be passed to the Line constructor Supported dict properties: color Sets the color of the threshold line. width Sets the width (in px) of the threshold line.
def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.indicator.gauge.threshold.Line` - A dict of string/value properties that will be passed to the Line constructor Supported dict properties: color Sets the color of the threshold line. width Sets the width (in px) of the threshold line. Returns ------- plotly.graph_objs.indicator.gauge.threshold.Line """ return self["line"]
[ "def", "line", "(", "self", ")", ":", "return", "self", "[", "\"line\"", "]" ]
[ 15, 4 ]
[ 34, 27 ]
python
en
['en', 'error', 'th']
False
Threshold.thickness
(self)
Sets the thickness of the threshold line as a fraction of the thickness of the gauge. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float
Sets the thickness of the threshold line as a fraction of the thickness of the gauge. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, 1]
def thickness(self): """ Sets the thickness of the threshold line as a fraction of the thickness of the gauge. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["thickness"]
[ "def", "thickness", "(", "self", ")", ":", "return", "self", "[", "\"thickness\"", "]" ]
[ 43, 4 ]
[ 55, 32 ]
python
en
['en', 'error', 'th']
False
Threshold.value
(self)
Sets a treshold value drawn as a line. The 'value' property is a number and may be specified as: - An int or float Returns ------- int|float
Sets a treshold value drawn as a line. The 'value' property is a number and may be specified as: - An int or float
def value(self): """ Sets a treshold value drawn as a line. The 'value' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["value"]
[ "def", "value", "(", "self", ")", ":", "return", "self", "[", "\"value\"", "]" ]
[ 64, 4 ]
[ 75, 28 ]
python
en
['en', 'error', 'th']
False
Threshold.__init__
(self, arg=None, line=None, thickness=None, value=None, **kwargs)
Construct a new Threshold object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.gauge.Threshold` line :class:`plotly.graph_objects.indicator.gauge.threshold. Line` instance or dict with compatible properties thickness Sets the thickness of the threshold line as a fraction of the thickness of the gauge. value Sets a treshold value drawn as a line. Returns ------- Threshold
Construct a new Threshold object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.gauge.Threshold` line :class:`plotly.graph_objects.indicator.gauge.threshold. Line` instance or dict with compatible properties thickness Sets the thickness of the threshold line as a fraction of the thickness of the gauge. value Sets a treshold value drawn as a line.
def __init__(self, arg=None, line=None, thickness=None, value=None, **kwargs): """ Construct a new Threshold object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.gauge.Threshold` line :class:`plotly.graph_objects.indicator.gauge.threshold. Line` instance or dict with compatible properties thickness Sets the thickness of the threshold line as a fraction of the thickness of the gauge. value Sets a treshold value drawn as a line. Returns ------- Threshold """ super(Threshold, self).__init__("threshold") 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.gauge.Threshold constructor must be a dict or an instance of :class:`plotly.graph_objs.indicator.gauge.Threshold`""" ) # 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("line", None) _v = line if line is not None else _v if _v is not None: self["line"] = _v _v = arg.pop("thickness", None) _v = thickness if thickness is not None else _v if _v is not None: self["thickness"] = _v _v = arg.pop("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", ",", "line", "=", "None", ",", "thickness", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Threshold", ",", "self", ")", ".", "__init__", "(", "\"threshold\"", ")", "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.gauge.Threshold \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.indicator.gauge.Threshold`\"\"\"", ")", "# 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", "(", "\"line\"", ",", "None", ")", "_v", "=", "line", "if", "line", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"line\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"thickness\"", ",", "None", ")", "_v", "=", "thickness", "if", "thickness", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"thickness\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"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" ]
[ 96, 4 ]
[ 167, 34 ]
python
en
['en', 'error', 'th']
False
Dimension.categoryarray
(self)
Sets the order in which categories in this dimension appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. The 'categoryarray' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray
Sets the order in which categories in this dimension appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. The 'categoryarray' property is an array that may be specified as a tuple, list, numpy array, or pandas Series
def categoryarray(self): """ Sets the order in which categories in this dimension appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. The 'categoryarray' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["categoryarray"]
[ "def", "categoryarray", "(", "self", ")", ":", "return", "self", "[", "\"categoryarray\"", "]" ]
[ 26, 4 ]
[ 39, 36 ]
python
en
['en', 'error', 'th']
False
Dimension.categoryarraysrc
(self)
Sets the source reference on Chart Studio Cloud for categoryarray . The 'categoryarraysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for categoryarray . The 'categoryarraysrc' property must be specified as a string or as a plotly.grid_objs.Column object
def categoryarraysrc(self): """ Sets the source reference on Chart Studio Cloud for categoryarray . The 'categoryarraysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["categoryarraysrc"]
[ "def", "categoryarraysrc", "(", "self", ")", ":", "return", "self", "[", "\"categoryarraysrc\"", "]" ]
[ 48, 4 ]
[ 60, 39 ]
python
en
['en', 'error', 'th']
False
Dimension.categoryorder
(self)
Specifies the ordering logic for the categories in the dimension. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. The 'categoryorder' property is an enumeration that may be specified as: - One of the following enumeration values: ['trace', 'category ascending', 'category descending', 'array'] Returns ------- Any
Specifies the ordering logic for the categories in the dimension. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. The 'categoryorder' property is an enumeration that may be specified as: - One of the following enumeration values: ['trace', 'category ascending', 'category descending', 'array']
def categoryorder(self): """ Specifies the ordering logic for the categories in the dimension. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. The 'categoryorder' property is an enumeration that may be specified as: - One of the following enumeration values: ['trace', 'category ascending', 'category descending', 'array'] Returns ------- Any """ return self["categoryorder"]
[ "def", "categoryorder", "(", "self", ")", ":", "return", "self", "[", "\"categoryorder\"", "]" ]
[ 69, 4 ]
[ 92, 36 ]
python
en
['en', 'error', 'th']
False
Dimension.displayindex
(self)
The display index of dimension, from left to right, zero indexed, defaults to dimension index. The 'displayindex' property is a integer and may be specified as: - An int (or float that will be cast to an int) Returns ------- int
The display index of dimension, from left to right, zero indexed, defaults to dimension index. The 'displayindex' property is a integer and may be specified as: - An int (or float that will be cast to an int)
def displayindex(self): """ The display index of dimension, from left to right, zero indexed, defaults to dimension index. The 'displayindex' property is a integer and may be specified as: - An int (or float that will be cast to an int) Returns ------- int """ return self["displayindex"]
[ "def", "displayindex", "(", "self", ")", ":", "return", "self", "[", "\"displayindex\"", "]" ]
[ 101, 4 ]
[ 113, 35 ]
python
en
['en', 'error', 'th']
False
Dimension.label
(self)
The shown name of the dimension. The 'label' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
The shown name of the dimension. 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): """ The shown name of the dimension. 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\"", "]" ]
[ 122, 4 ]
[ 134, 28 ]
python
en
['en', 'error', 'th']
False
Dimension.ticktext
(self)
Sets alternative tick labels for the categories in this dimension. Only has an effect if `categoryorder` is set to "array". Should be an array the same length as `categoryarray` Used with `categoryorder`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray
Sets alternative tick labels for the categories in this dimension. Only has an effect if `categoryorder` is set to "array". Should be an array the same length as `categoryarray` Used with `categoryorder`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series
def ticktext(self): """ Sets alternative tick labels for the categories in this dimension. Only has an effect if `categoryorder` is set to "array". Should be an array the same length as `categoryarray` Used with `categoryorder`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"]
[ "def", "ticktext", "(", "self", ")", ":", "return", "self", "[", "\"ticktext\"", "]" ]
[ 143, 4 ]
[ 157, 31 ]
python
en
['en', 'error', 'th']
False
Dimension.ticktextsrc
(self)
Sets the source reference on Chart Studio Cloud for ticktext . The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for ticktext . The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object
def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for ticktext . The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"]
[ "def", "ticktextsrc", "(", "self", ")", ":", "return", "self", "[", "\"ticktextsrc\"", "]" ]
[ 166, 4 ]
[ 177, 34 ]
python
en
['en', 'error', 'th']
False
Dimension.values
(self)
Dimension values. `values[n]` represents the category value of the `n`th point in the dataset, therefore the `values` vector for all dimensions must be the same (longer vectors will be truncated). The 'values' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray
Dimension values. `values[n]` represents the category value of the `n`th point in the dataset, therefore the `values` vector for all dimensions must be the same (longer vectors will be truncated). The 'values' property is an array that may be specified as a tuple, list, numpy array, or pandas Series
def values(self): """ Dimension values. `values[n]` represents the category value of the `n`th point in the dataset, therefore the `values` vector for all dimensions must be the same (longer vectors will be truncated). The 'values' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["values"]
[ "def", "values", "(", "self", ")", ":", "return", "self", "[", "\"values\"", "]" ]
[ 186, 4 ]
[ 200, 29 ]
python
en
['en', 'error', 'th']
False
Dimension.valuessrc
(self)
Sets the source reference on Chart Studio Cloud for values . The 'valuessrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for values . The 'valuessrc' property must be specified as a string or as a plotly.grid_objs.Column object
def valuessrc(self): """ Sets the source reference on Chart Studio Cloud for values . The 'valuessrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["valuessrc"]
[ "def", "valuessrc", "(", "self", ")", ":", "return", "self", "[", "\"valuessrc\"", "]" ]
[ 209, 4 ]
[ 220, 32 ]
python
en
['en', 'error', 'th']
False
Dimension.visible
(self)
Shows the dimension when set to `true` (the default). Hides the dimension for `false`. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool
Shows the dimension when set to `true` (the default). Hides the dimension for `false`. The 'visible' property must be specified as a bool (either True, or False)
def visible(self): """ Shows the dimension when set to `true` (the default). Hides the dimension for `false`. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"]
[ "def", "visible", "(", "self", ")", ":", "return", "self", "[", "\"visible\"", "]" ]
[ 229, 4 ]
[ 241, 30 ]
python
en
['en', 'error', 'th']
False
Dimension.__init__
( self, arg=None, categoryarray=None, categoryarraysrc=None, categoryorder=None, displayindex=None, label=None, ticktext=None, ticktextsrc=None, values=None, valuessrc=None, visible=None, **kwargs )
Construct a new Dimension object The dimensions (variables) of the parallel categories diagram. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcats.Dimension` categoryarray Sets the order in which categories in this dimension appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. categoryarraysrc Sets the source reference on Chart Studio Cloud for categoryarray . categoryorder Specifies the ordering logic for the categories in the dimension. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. displayindex The display index of dimension, from left to right, zero indexed, defaults to dimension index. label The shown name of the dimension. ticktext Sets alternative tick labels for the categories in this dimension. Only has an effect if `categoryorder` is set to "array". Should be an array the same length as `categoryarray` Used with `categoryorder`. ticktextsrc Sets the source reference on Chart Studio Cloud for ticktext . values Dimension values. `values[n]` represents the category value of the `n`th point in the dataset, therefore the `values` vector for all dimensions must be the same (longer vectors will be truncated). valuessrc Sets the source reference on Chart Studio Cloud for values . visible Shows the dimension when set to `true` (the default). Hides the dimension for `false`. Returns ------- Dimension
Construct a new Dimension object The dimensions (variables) of the parallel categories diagram.
def __init__( self, arg=None, categoryarray=None, categoryarraysrc=None, categoryorder=None, displayindex=None, label=None, ticktext=None, ticktextsrc=None, values=None, valuessrc=None, visible=None, **kwargs ): """ Construct a new Dimension object The dimensions (variables) of the parallel categories diagram. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcats.Dimension` categoryarray Sets the order in which categories in this dimension appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. categoryarraysrc Sets the source reference on Chart Studio Cloud for categoryarray . categoryorder Specifies the ordering logic for the categories in the dimension. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. displayindex The display index of dimension, from left to right, zero indexed, defaults to dimension index. label The shown name of the dimension. ticktext Sets alternative tick labels for the categories in this dimension. Only has an effect if `categoryorder` is set to "array". Should be an array the same length as `categoryarray` Used with `categoryorder`. ticktextsrc Sets the source reference on Chart Studio Cloud for ticktext . values Dimension values. `values[n]` represents the category value of the `n`th point in the dataset, therefore the `values` vector for all dimensions must be the same (longer vectors will be truncated). valuessrc Sets the source reference on Chart Studio Cloud for values . visible Shows the dimension when set to `true` (the default). Hides the dimension for `false`. Returns ------- Dimension """ super(Dimension, self).__init__("dimensions") 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.parcats.Dimension constructor must be a dict or an instance of :class:`plotly.graph_objs.parcats.Dimension`""" ) # 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("categoryarray", None) _v = categoryarray if categoryarray is not None else _v if _v is not None: self["categoryarray"] = _v _v = arg.pop("categoryarraysrc", None) _v = categoryarraysrc if categoryarraysrc is not None else _v if _v is not None: self["categoryarraysrc"] = _v _v = arg.pop("categoryorder", None) _v = categoryorder if categoryorder is not None else _v if _v is not None: self["categoryorder"] = _v _v = arg.pop("displayindex", None) _v = displayindex if displayindex is not None else _v if _v is not None: self["displayindex"] = _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("ticktext", None) _v = ticktext if ticktext is not None else _v if _v is not None: self["ticktext"] = _v _v = arg.pop("ticktextsrc", None) _v = ticktextsrc if ticktextsrc is not None else _v if _v is not None: self["ticktextsrc"] = _v _v = arg.pop("values", None) _v = values if values is not None else _v if _v is not None: self["values"] = _v _v = arg.pop("valuessrc", None) _v = valuessrc if valuessrc is not None else _v if _v is not None: self["valuessrc"] = _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", ",", "categoryarray", "=", "None", ",", "categoryarraysrc", "=", "None", ",", "categoryorder", "=", "None", ",", "displayindex", "=", "None", ",", "label", "=", "None", ",", "ticktext", "=", "None", ",", "ticktextsrc", "=", "None", ",", "values", "=", "None", ",", "valuessrc", "=", "None", ",", "visible", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Dimension", ",", "self", ")", ".", "__init__", "(", "\"dimensions\"", ")", "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.parcats.Dimension \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.parcats.Dimension`\"\"\"", ")", "# 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", "(", "\"categoryarray\"", ",", "None", ")", "_v", "=", "categoryarray", "if", "categoryarray", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"categoryarray\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"categoryarraysrc\"", ",", "None", ")", "_v", "=", "categoryarraysrc", "if", "categoryarraysrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"categoryarraysrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"categoryorder\"", ",", "None", ")", "_v", "=", "categoryorder", "if", "categoryorder", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"categoryorder\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"displayindex\"", ",", "None", ")", "_v", "=", "displayindex", "if", "displayindex", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"displayindex\"", "]", "=", "_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", "(", "\"ticktext\"", ",", "None", ")", "_v", "=", "ticktext", "if", "ticktext", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticktext\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ticktextsrc\"", ",", "None", ")", "_v", "=", "ticktextsrc", "if", "ticktextsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ticktextsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"values\"", ",", "None", ")", "_v", "=", "values", "if", "values", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"values\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"valuessrc\"", ",", "None", ")", "_v", "=", "valuessrc", "if", "valuessrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"valuessrc\"", "]", "=", "_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" ]
[ 298, 4 ]
[ 449, 34 ]
python
en
['en', 'error', 'th']
False
Tickformatstop.dtickrange
(self)
range [*min*, *max*], where "min", "max" - dtick values which describe some zoom level, it is possible to omit "min" or "max" value by passing "null" The 'dtickrange' property is an info array that may be specified as: * a list or tuple of 2 elements where: (0) The 'dtickrange[0]' property accepts values of any type (1) The 'dtickrange[1]' property accepts values of any type Returns ------- list
range [*min*, *max*], where "min", "max" - dtick values which describe some zoom level, it is possible to omit "min" or "max" value by passing "null" The 'dtickrange' property is an info array that may be specified as: * a list or tuple of 2 elements where: (0) The 'dtickrange[0]' property accepts values of any type (1) The 'dtickrange[1]' property accepts values of any type
def dtickrange(self): """ range [*min*, *max*], where "min", "max" - dtick values which describe some zoom level, it is possible to omit "min" or "max" value by passing "null" The 'dtickrange' property is an info array that may be specified as: * a list or tuple of 2 elements where: (0) The 'dtickrange[0]' property accepts values of any type (1) The 'dtickrange[1]' property accepts values of any type Returns ------- list """ return self["dtickrange"]
[ "def", "dtickrange", "(", "self", ")", ":", "return", "self", "[", "\"dtickrange\"", "]" ]
[ 15, 4 ]
[ 31, 33 ]
python
en
['en', 'error', 'th']
False
Tickformatstop.enabled
(self)
Determines whether or not this stop is used. If `false`, this stop is ignored even within its `dtickrange`. The 'enabled' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not this stop is used. If `false`, this stop is ignored even within its `dtickrange`. The 'enabled' property must be specified as a bool (either True, or False)
def enabled(self): """ Determines whether or not this stop is used. If `false`, this stop is ignored even within its `dtickrange`. The 'enabled' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["enabled"]
[ "def", "enabled", "(", "self", ")", ":", "return", "self", "[", "\"enabled\"", "]" ]
[ 40, 4 ]
[ 52, 30 ]
python
en
['en', 'error', 'th']
False
Tickformatstop.name
(self)
When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string
def name(self): """ When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["name"]
[ "def", "name", "(", "self", ")", ":", "return", "self", "[", "\"name\"", "]" ]
[ 61, 4 ]
[ 79, 27 ]
python
en
['en', 'error', 'th']
False
Tickformatstop.templateitemname
(self)
Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. The 'templateitemname' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. The 'templateitemname' property is a string and must be specified as: - A string - A number that will be converted to a string
def templateitemname(self): """ Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. The 'templateitemname' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["templateitemname"]
[ "def", "templateitemname", "(", "self", ")", ":", "return", "self", "[", "\"templateitemname\"", "]" ]
[ 88, 4 ]
[ 107, 39 ]
python
en
['en', 'error', 'th']
False
Tickformatstop.value
(self)
string - dtickformat for described zoom level, the same as "tickformat" The 'value' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
string - dtickformat for described zoom level, the same as "tickformat" The 'value' property is a string and must be specified as: - A string - A number that will be converted to a string
def value(self): """ string - dtickformat for described zoom level, the same as "tickformat" The 'value' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["value"]
[ "def", "value", "(", "self", ")", ":", "return", "self", "[", "\"value\"", "]" ]
[ 116, 4 ]
[ 129, 28 ]
python
en
['en', 'error', 'th']
False
Tickformatstop.__init__
( self, arg=None, dtickrange=None, enabled=None, name=None, templateitemname=None, value=None, **kwargs )
Construct a new Tickformatstop object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.choropleth.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.choropleth.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.choropleth.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.choropleth.colorbar.Tickformatstop constructor must be a dict or an instance of :class:`plotly.graph_objs.choropleth.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.choropleth.colorbar.Tickformatstop \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.choropleth.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
Updatemenu.active
(self)
Determines which button (by index starting from 0) is considered active. The 'active' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [-1, 9223372036854775807] Returns ------- int
Determines which button (by index starting from 0) is considered active. The 'active' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [-1, 9223372036854775807]
def active(self): """ Determines which button (by index starting from 0) is considered active. The 'active' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [-1, 9223372036854775807] Returns ------- int """ return self["active"]
[ "def", "active", "(", "self", ")", ":", "return", "self", "[", "\"active\"", "]" ]
[ 34, 4 ]
[ 47, 29 ]
python
en
['en', 'error', 'th']
False
Updatemenu.bgcolor
(self)
Sets the background color of the update menu buttons. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the background color of the update menu buttons. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
def bgcolor(self): """ Sets the background color of the update menu buttons. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bgcolor"]
[ "def", "bgcolor", "(", "self", ")", ":", "return", "self", "[", "\"bgcolor\"", "]" ]
[ 56, 4 ]
[ 106, 30 ]
python
en
['en', 'error', 'th']
False