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 |
---|---|---|---|---|---|---|---|---|---|---|---|
encrypt_plaintext | (
message: str, add_data: bytes, key: bytes
) |
Encrypt the payload of a packed message.
Args:
message: Message to encrypt
add_data:
key: Key used for encryption
Returns:
A tuple of (ciphertext, nonce, tag)
|
Encrypt the payload of a packed message. | def encrypt_plaintext(
message: str, add_data: bytes, key: bytes
) -> (bytes, bytes, bytes):
"""
Encrypt the payload of a packed message.
Args:
message: Message to encrypt
add_data:
key: Key used for encryption
Returns:
A tuple of (ciphertext, nonce, tag)
"""
nonce = nacl.utils.random(nacl.bindings.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
message_bin = message.encode("ascii")
output = nacl.bindings.crypto_aead_chacha20poly1305_ietf_encrypt(
message_bin, add_data, nonce, key
)
mlen = len(message)
ciphertext = output[:mlen]
tag = output[mlen:]
return ciphertext, nonce, tag | [
"def",
"encrypt_plaintext",
"(",
"message",
":",
"str",
",",
"add_data",
":",
"bytes",
",",
"key",
":",
"bytes",
")",
"->",
"(",
"bytes",
",",
"bytes",
",",
"bytes",
")",
":",
"nonce",
"=",
"nacl",
".",
"utils",
".",
"random",
"(",
"nacl",
".",
"bindings",
".",
"crypto_aead_chacha20poly1305_ietf_NPUBBYTES",
")",
"message_bin",
"=",
"message",
".",
"encode",
"(",
"\"ascii\"",
")",
"output",
"=",
"nacl",
".",
"bindings",
".",
"crypto_aead_chacha20poly1305_ietf_encrypt",
"(",
"message_bin",
",",
"add_data",
",",
"nonce",
",",
"key",
")",
"mlen",
"=",
"len",
"(",
"message",
")",
"ciphertext",
"=",
"output",
"[",
":",
"mlen",
"]",
"tag",
"=",
"output",
"[",
"mlen",
":",
"]",
"return",
"ciphertext",
",",
"nonce",
",",
"tag"
] | [
376,
0
] | [
399,
33
] | python | en | ['en', 'error', 'th'] | False |
decrypt_plaintext | (
ciphertext: bytes, recips_bin: bytes, nonce: bytes, key: bytes
) |
Decrypt the payload of a packed message.
Args:
ciphertext:
recips_bin:
nonce:
key:
Returns:
The decrypted string
|
Decrypt the payload of a packed message. | def decrypt_plaintext(
ciphertext: bytes, recips_bin: bytes, nonce: bytes, key: bytes
) -> str:
"""
Decrypt the payload of a packed message.
Args:
ciphertext:
recips_bin:
nonce:
key:
Returns:
The decrypted string
"""
output = nacl.bindings.crypto_aead_chacha20poly1305_ietf_decrypt(
ciphertext, recips_bin, nonce, key
)
return output.decode("ascii") | [
"def",
"decrypt_plaintext",
"(",
"ciphertext",
":",
"bytes",
",",
"recips_bin",
":",
"bytes",
",",
"nonce",
":",
"bytes",
",",
"key",
":",
"bytes",
")",
"->",
"str",
":",
"output",
"=",
"nacl",
".",
"bindings",
".",
"crypto_aead_chacha20poly1305_ietf_decrypt",
"(",
"ciphertext",
",",
"recips_bin",
",",
"nonce",
",",
"key",
")",
"return",
"output",
".",
"decode",
"(",
"\"ascii\"",
")"
] | [
402,
0
] | [
421,
33
] | python | en | ['en', 'error', 'th'] | False |
encode_pack_message | (
message: str, to_verkeys: Sequence[bytes], from_secret: bytes = None
) |
Assemble a packed message for a set of recipients, optionally including the sender.
Args:
message: The message to pack
to_verkeys: The verkeys to pack the message for
from_secret: The sender secret
Returns:
The encoded message
|
Assemble a packed message for a set of recipients, optionally including the sender. | def encode_pack_message(
message: str, to_verkeys: Sequence[bytes], from_secret: bytes = None
) -> bytes:
"""
Assemble a packed message for a set of recipients, optionally including the sender.
Args:
message: The message to pack
to_verkeys: The verkeys to pack the message for
from_secret: The sender secret
Returns:
The encoded message
"""
recips_json, cek = prepare_pack_recipient_keys(to_verkeys, from_secret)
recips_b64 = bytes_to_b64(recips_json.encode("ascii"), urlsafe=True)
ciphertext, nonce, tag = encrypt_plaintext(message, recips_b64.encode("ascii"), cek)
data = OrderedDict(
[
("protected", recips_b64),
("iv", bytes_to_b64(nonce, urlsafe=True)),
("ciphertext", bytes_to_b64(ciphertext, urlsafe=True)),
("tag", bytes_to_b64(tag, urlsafe=True)),
]
)
return json.dumps(data).encode("ascii") | [
"def",
"encode_pack_message",
"(",
"message",
":",
"str",
",",
"to_verkeys",
":",
"Sequence",
"[",
"bytes",
"]",
",",
"from_secret",
":",
"bytes",
"=",
"None",
")",
"->",
"bytes",
":",
"recips_json",
",",
"cek",
"=",
"prepare_pack_recipient_keys",
"(",
"to_verkeys",
",",
"from_secret",
")",
"recips_b64",
"=",
"bytes_to_b64",
"(",
"recips_json",
".",
"encode",
"(",
"\"ascii\"",
")",
",",
"urlsafe",
"=",
"True",
")",
"ciphertext",
",",
"nonce",
",",
"tag",
"=",
"encrypt_plaintext",
"(",
"message",
",",
"recips_b64",
".",
"encode",
"(",
"\"ascii\"",
")",
",",
"cek",
")",
"data",
"=",
"OrderedDict",
"(",
"[",
"(",
"\"protected\"",
",",
"recips_b64",
")",
",",
"(",
"\"iv\"",
",",
"bytes_to_b64",
"(",
"nonce",
",",
"urlsafe",
"=",
"True",
")",
")",
",",
"(",
"\"ciphertext\"",
",",
"bytes_to_b64",
"(",
"ciphertext",
",",
"urlsafe",
"=",
"True",
")",
")",
",",
"(",
"\"tag\"",
",",
"bytes_to_b64",
"(",
"tag",
",",
"urlsafe",
"=",
"True",
")",
")",
",",
"]",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
")",
".",
"encode",
"(",
"\"ascii\"",
")"
] | [
424,
0
] | [
452,
43
] | python | en | ['en', 'error', 'th'] | False |
decode_pack_message | (
enc_message: bytes, find_key: Callable
) |
Decode a packed message.
Disassemble and unencrypt a packed message, returning the message content,
verification key of the sender (if available), and verification key of the
recipient.
Args:
enc_message: The encrypted message
find_key: Function to retrieve private key
Returns:
A tuple of (message, sender_vk, recip_vk)
Raises:
ValueError: If the packed message is invalid
ValueError: If the packed message reipients are invalid
ValueError: If the pack algorithm is unsupported
ValueError: If the sender's public key was not provided
|
Decode a packed message. | def decode_pack_message(
enc_message: bytes, find_key: Callable
) -> (str, Optional[str], str):
"""
Decode a packed message.
Disassemble and unencrypt a packed message, returning the message content,
verification key of the sender (if available), and verification key of the
recipient.
Args:
enc_message: The encrypted message
find_key: Function to retrieve private key
Returns:
A tuple of (message, sender_vk, recip_vk)
Raises:
ValueError: If the packed message is invalid
ValueError: If the packed message reipients are invalid
ValueError: If the pack algorithm is unsupported
ValueError: If the sender's public key was not provided
"""
try:
wrapper = PackMessageSchema().loads(enc_message)
except ValidationError:
raise ValueError("Invalid packed message")
protected_bin = wrapper["protected"].encode("ascii")
recips_json = b64_to_bytes(wrapper["protected"], urlsafe=True).decode("ascii")
try:
recips_outer = PackRecipientsSchema().loads(recips_json)
except ValidationError:
raise ValueError("Invalid packed message recipients")
alg = recips_outer["alg"]
is_authcrypt = alg == "Authcrypt"
if not is_authcrypt and alg != "Anoncrypt":
raise ValueError("Unsupported pack algorithm: {}".format(alg))
cek, sender_vk, recip_vk = locate_pack_recipient_key(
recips_outer["recipients"], find_key
)
if not sender_vk and is_authcrypt:
raise ValueError("Sender public key not provided for Authcrypt message")
ciphertext = b64_to_bytes(wrapper["ciphertext"], urlsafe=True)
nonce = b64_to_bytes(wrapper["iv"], urlsafe=True)
tag = b64_to_bytes(wrapper["tag"], urlsafe=True)
payload_bin = ciphertext + tag
message = decrypt_plaintext(payload_bin, protected_bin, nonce, cek)
return message, sender_vk, recip_vk | [
"def",
"decode_pack_message",
"(",
"enc_message",
":",
"bytes",
",",
"find_key",
":",
"Callable",
")",
"->",
"(",
"str",
",",
"Optional",
"[",
"str",
"]",
",",
"str",
")",
":",
"try",
":",
"wrapper",
"=",
"PackMessageSchema",
"(",
")",
".",
"loads",
"(",
"enc_message",
")",
"except",
"ValidationError",
":",
"raise",
"ValueError",
"(",
"\"Invalid packed message\"",
")",
"protected_bin",
"=",
"wrapper",
"[",
"\"protected\"",
"]",
".",
"encode",
"(",
"\"ascii\"",
")",
"recips_json",
"=",
"b64_to_bytes",
"(",
"wrapper",
"[",
"\"protected\"",
"]",
",",
"urlsafe",
"=",
"True",
")",
".",
"decode",
"(",
"\"ascii\"",
")",
"try",
":",
"recips_outer",
"=",
"PackRecipientsSchema",
"(",
")",
".",
"loads",
"(",
"recips_json",
")",
"except",
"ValidationError",
":",
"raise",
"ValueError",
"(",
"\"Invalid packed message recipients\"",
")",
"alg",
"=",
"recips_outer",
"[",
"\"alg\"",
"]",
"is_authcrypt",
"=",
"alg",
"==",
"\"Authcrypt\"",
"if",
"not",
"is_authcrypt",
"and",
"alg",
"!=",
"\"Anoncrypt\"",
":",
"raise",
"ValueError",
"(",
"\"Unsupported pack algorithm: {}\"",
".",
"format",
"(",
"alg",
")",
")",
"cek",
",",
"sender_vk",
",",
"recip_vk",
"=",
"locate_pack_recipient_key",
"(",
"recips_outer",
"[",
"\"recipients\"",
"]",
",",
"find_key",
")",
"if",
"not",
"sender_vk",
"and",
"is_authcrypt",
":",
"raise",
"ValueError",
"(",
"\"Sender public key not provided for Authcrypt message\"",
")",
"ciphertext",
"=",
"b64_to_bytes",
"(",
"wrapper",
"[",
"\"ciphertext\"",
"]",
",",
"urlsafe",
"=",
"True",
")",
"nonce",
"=",
"b64_to_bytes",
"(",
"wrapper",
"[",
"\"iv\"",
"]",
",",
"urlsafe",
"=",
"True",
")",
"tag",
"=",
"b64_to_bytes",
"(",
"wrapper",
"[",
"\"tag\"",
"]",
",",
"urlsafe",
"=",
"True",
")",
"payload_bin",
"=",
"ciphertext",
"+",
"tag",
"message",
"=",
"decrypt_plaintext",
"(",
"payload_bin",
",",
"protected_bin",
",",
"nonce",
",",
"cek",
")",
"return",
"message",
",",
"sender_vk",
",",
"recip_vk"
] | [
455,
0
] | [
508,
39
] | python | en | ['en', 'error', 'th'] | False |
validate_ohlc | (open, high, low, close, direction, **kwargs) |
ohlc and candlestick specific validations
Specifically, this checks that the high value is the greatest value and
the low value is the lowest value in each unit.
See FigureFactory.create_ohlc() or FigureFactory.create_candlestick()
for params
:raises: (PlotlyError) If the high value is not the greatest value in
each unit.
:raises: (PlotlyError) If the low value is not the lowest value in each
unit.
:raises: (PlotlyError) If direction is not 'increasing' or 'decreasing'
|
ohlc and candlestick specific validations | def validate_ohlc(open, high, low, close, direction, **kwargs):
"""
ohlc and candlestick specific validations
Specifically, this checks that the high value is the greatest value and
the low value is the lowest value in each unit.
See FigureFactory.create_ohlc() or FigureFactory.create_candlestick()
for params
:raises: (PlotlyError) If the high value is not the greatest value in
each unit.
:raises: (PlotlyError) If the low value is not the lowest value in each
unit.
:raises: (PlotlyError) If direction is not 'increasing' or 'decreasing'
"""
for lst in [open, low, close]:
for index in range(len(high)):
if high[index] < lst[index]:
raise exceptions.PlotlyError(
"Oops! Looks like some of "
"your high values are less "
"the corresponding open, "
"low, or close values. "
"Double check that your data "
"is entered in O-H-L-C order"
)
for lst in [open, high, close]:
for index in range(len(low)):
if low[index] > lst[index]:
raise exceptions.PlotlyError(
"Oops! Looks like some of "
"your low values are greater "
"than the corresponding high"
", open, or close values. "
"Double check that your data "
"is entered in O-H-L-C order"
)
direction_opts = ("increasing", "decreasing", "both")
if direction not in direction_opts:
raise exceptions.PlotlyError(
"direction must be defined as " "'increasing', 'decreasing', or " "'both'"
) | [
"def",
"validate_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"direction",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"lst",
"in",
"[",
"open",
",",
"low",
",",
"close",
"]",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"high",
")",
")",
":",
"if",
"high",
"[",
"index",
"]",
"<",
"lst",
"[",
"index",
"]",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Oops! Looks like some of \"",
"\"your high values are less \"",
"\"the corresponding open, \"",
"\"low, or close values. \"",
"\"Double check that your data \"",
"\"is entered in O-H-L-C order\"",
")",
"for",
"lst",
"in",
"[",
"open",
",",
"high",
",",
"close",
"]",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"low",
")",
")",
":",
"if",
"low",
"[",
"index",
"]",
">",
"lst",
"[",
"index",
"]",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Oops! Looks like some of \"",
"\"your low values are greater \"",
"\"than the corresponding high\"",
"\", open, or close values. \"",
"\"Double check that your data \"",
"\"is entered in O-H-L-C order\"",
")",
"direction_opts",
"=",
"(",
"\"increasing\"",
",",
"\"decreasing\"",
",",
"\"both\"",
")",
"if",
"direction",
"not",
"in",
"direction_opts",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"direction must be defined as \"",
"\"'increasing', 'decreasing', or \"",
"\"'both'\"",
")"
] | [
12,
0
] | [
56,
9
] | python | en | ['en', 'error', 'th'] | False |
make_increasing_ohlc | (open, high, low, close, dates, **kwargs) |
Makes increasing ohlc sticks
_make_increasing_ohlc() and _make_decreasing_ohlc separate the
increasing trace from the decreasing trace so kwargs (such as
color) can be passed separately to increasing or decreasing traces
when direction is set to 'increasing' or 'decreasing' in
FigureFactory.create_candlestick()
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing values
:param (list) dates: list of datetime objects. Default: None
:param kwargs: kwargs to be passed to increasing trace via
plotly.graph_objs.Scatter.
:rtype (trace) ohlc_incr_data: Scatter trace of all increasing ohlc
sticks.
|
Makes increasing ohlc sticks | def make_increasing_ohlc(open, high, low, close, dates, **kwargs):
"""
Makes increasing ohlc sticks
_make_increasing_ohlc() and _make_decreasing_ohlc separate the
increasing trace from the decreasing trace so kwargs (such as
color) can be passed separately to increasing or decreasing traces
when direction is set to 'increasing' or 'decreasing' in
FigureFactory.create_candlestick()
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing values
:param (list) dates: list of datetime objects. Default: None
:param kwargs: kwargs to be passed to increasing trace via
plotly.graph_objs.Scatter.
:rtype (trace) ohlc_incr_data: Scatter trace of all increasing ohlc
sticks.
"""
(flat_increase_x, flat_increase_y, text_increase) = _OHLC(
open, high, low, close, dates
).get_increase()
if "name" in kwargs:
showlegend = True
else:
kwargs.setdefault("name", "Increasing")
showlegend = False
kwargs.setdefault("line", dict(color=_DEFAULT_INCREASING_COLOR, width=1))
kwargs.setdefault("text", text_increase)
ohlc_incr = dict(
type="scatter",
x=flat_increase_x,
y=flat_increase_y,
mode="lines",
showlegend=showlegend,
**kwargs
)
return ohlc_incr | [
"def",
"make_increasing_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"flat_increase_x",
",",
"flat_increase_y",
",",
"text_increase",
")",
"=",
"_OHLC",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
")",
".",
"get_increase",
"(",
")",
"if",
"\"name\"",
"in",
"kwargs",
":",
"showlegend",
"=",
"True",
"else",
":",
"kwargs",
".",
"setdefault",
"(",
"\"name\"",
",",
"\"Increasing\"",
")",
"showlegend",
"=",
"False",
"kwargs",
".",
"setdefault",
"(",
"\"line\"",
",",
"dict",
"(",
"color",
"=",
"_DEFAULT_INCREASING_COLOR",
",",
"width",
"=",
"1",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"\"text\"",
",",
"text_increase",
")",
"ohlc_incr",
"=",
"dict",
"(",
"type",
"=",
"\"scatter\"",
",",
"x",
"=",
"flat_increase_x",
",",
"y",
"=",
"flat_increase_y",
",",
"mode",
"=",
"\"lines\"",
",",
"showlegend",
"=",
"showlegend",
",",
"*",
"*",
"kwargs",
")",
"return",
"ohlc_incr"
] | [
59,
0
] | [
101,
20
] | python | en | ['en', 'error', 'th'] | False |
make_decreasing_ohlc | (open, high, low, close, dates, **kwargs) |
Makes decreasing ohlc sticks
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing values
:param (list) dates: list of datetime objects. Default: None
:param kwargs: kwargs to be passed to increasing trace via
plotly.graph_objs.Scatter.
:rtype (trace) ohlc_decr_data: Scatter trace of all decreasing ohlc
sticks.
|
Makes decreasing ohlc sticks | def make_decreasing_ohlc(open, high, low, close, dates, **kwargs):
"""
Makes decreasing ohlc sticks
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing values
:param (list) dates: list of datetime objects. Default: None
:param kwargs: kwargs to be passed to increasing trace via
plotly.graph_objs.Scatter.
:rtype (trace) ohlc_decr_data: Scatter trace of all decreasing ohlc
sticks.
"""
(flat_decrease_x, flat_decrease_y, text_decrease) = _OHLC(
open, high, low, close, dates
).get_decrease()
kwargs.setdefault("line", dict(color=_DEFAULT_DECREASING_COLOR, width=1))
kwargs.setdefault("text", text_decrease)
kwargs.setdefault("showlegend", False)
kwargs.setdefault("name", "Decreasing")
ohlc_decr = dict(
type="scatter", x=flat_decrease_x, y=flat_decrease_y, mode="lines", **kwargs
)
return ohlc_decr | [
"def",
"make_decreasing_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"flat_decrease_x",
",",
"flat_decrease_y",
",",
"text_decrease",
")",
"=",
"_OHLC",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
")",
".",
"get_decrease",
"(",
")",
"kwargs",
".",
"setdefault",
"(",
"\"line\"",
",",
"dict",
"(",
"color",
"=",
"_DEFAULT_DECREASING_COLOR",
",",
"width",
"=",
"1",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"\"text\"",
",",
"text_decrease",
")",
"kwargs",
".",
"setdefault",
"(",
"\"showlegend\"",
",",
"False",
")",
"kwargs",
".",
"setdefault",
"(",
"\"name\"",
",",
"\"Decreasing\"",
")",
"ohlc_decr",
"=",
"dict",
"(",
"type",
"=",
"\"scatter\"",
",",
"x",
"=",
"flat_decrease_x",
",",
"y",
"=",
"flat_decrease_y",
",",
"mode",
"=",
"\"lines\"",
",",
"*",
"*",
"kwargs",
")",
"return",
"ohlc_decr"
] | [
104,
0
] | [
131,
20
] | python | en | ['en', 'error', 'th'] | False |
create_ohlc | (open, high, low, close, dates=None, direction="both", **kwargs) |
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Ohlc`
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing
:param (list) dates: list of datetime objects. Default: None
:param (string) direction: direction can be 'increasing', 'decreasing',
or 'both'. When the direction is 'increasing', the returned figure
consists of all units where the close value is greater than the
corresponding open value, and when the direction is 'decreasing',
the returned figure consists of all units where the close value is
less than or equal to the corresponding open value. When the
direction is 'both', both increasing and decreasing units are
returned. Default: 'both'
:param kwargs: kwargs passed through plotly.graph_objs.Scatter.
These kwargs describe other attributes about the ohlc Scatter trace
such as the color or the legend name. For more information on valid
kwargs call help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of an ohlc chart figure.
Example 1: Simple OHLC chart from a Pandas DataFrame
>>> from plotly.figure_factory import create_ohlc
>>> from datetime import datetime
>>> import pandas as pd
>>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
>>> fig = create_ohlc(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], dates=df.index)
>>> fig.show()
|
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Ohlc` | def create_ohlc(open, high, low, close, dates=None, direction="both", **kwargs):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Ohlc`
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing
:param (list) dates: list of datetime objects. Default: None
:param (string) direction: direction can be 'increasing', 'decreasing',
or 'both'. When the direction is 'increasing', the returned figure
consists of all units where the close value is greater than the
corresponding open value, and when the direction is 'decreasing',
the returned figure consists of all units where the close value is
less than or equal to the corresponding open value. When the
direction is 'both', both increasing and decreasing units are
returned. Default: 'both'
:param kwargs: kwargs passed through plotly.graph_objs.Scatter.
These kwargs describe other attributes about the ohlc Scatter trace
such as the color or the legend name. For more information on valid
kwargs call help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of an ohlc chart figure.
Example 1: Simple OHLC chart from a Pandas DataFrame
>>> from plotly.figure_factory import create_ohlc
>>> from datetime import datetime
>>> import pandas as pd
>>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
>>> fig = create_ohlc(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], dates=df.index)
>>> fig.show()
"""
if dates is not None:
utils.validate_equal_length(open, high, low, close, dates)
else:
utils.validate_equal_length(open, high, low, close)
validate_ohlc(open, high, low, close, direction, **kwargs)
if direction == "increasing":
ohlc_incr = make_increasing_ohlc(open, high, low, close, dates, **kwargs)
data = [ohlc_incr]
elif direction == "decreasing":
ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates, **kwargs)
data = [ohlc_decr]
else:
ohlc_incr = make_increasing_ohlc(open, high, low, close, dates, **kwargs)
ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates, **kwargs)
data = [ohlc_incr, ohlc_decr]
layout = graph_objs.Layout(xaxis=dict(zeroline=False), hovermode="closest")
return graph_objs.Figure(data=data, layout=layout) | [
"def",
"create_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
"=",
"None",
",",
"direction",
"=",
"\"both\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dates",
"is",
"not",
"None",
":",
"utils",
".",
"validate_equal_length",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
")",
"else",
":",
"utils",
".",
"validate_equal_length",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
")",
"validate_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"direction",
",",
"*",
"*",
"kwargs",
")",
"if",
"direction",
"==",
"\"increasing\"",
":",
"ohlc_incr",
"=",
"make_increasing_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"[",
"ohlc_incr",
"]",
"elif",
"direction",
"==",
"\"decreasing\"",
":",
"ohlc_decr",
"=",
"make_decreasing_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"[",
"ohlc_decr",
"]",
"else",
":",
"ohlc_incr",
"=",
"make_increasing_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
",",
"*",
"*",
"kwargs",
")",
"ohlc_decr",
"=",
"make_decreasing_ohlc",
"(",
"open",
",",
"high",
",",
"low",
",",
"close",
",",
"dates",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"[",
"ohlc_incr",
",",
"ohlc_decr",
"]",
"layout",
"=",
"graph_objs",
".",
"Layout",
"(",
"xaxis",
"=",
"dict",
"(",
"zeroline",
"=",
"False",
")",
",",
"hovermode",
"=",
"\"closest\"",
")",
"return",
"graph_objs",
".",
"Figure",
"(",
"data",
"=",
"data",
",",
"layout",
"=",
"layout",
")"
] | [
134,
0
] | [
188,
54
] | python | en | ['en', 'error', 'th'] | False |
_OHLC.get_all_xy | (self) |
Zip data to create OHLC shape
OHLC shape: low to high vertical bar with
horizontal branches for open and close values.
If dates were added, the smallest date difference is calculated and
multiplied by .2 to get the length of the open and close branches.
If no date data was provided, the x-axis is a list of integers and the
length of the open and close branches is .2.
|
Zip data to create OHLC shape | def get_all_xy(self):
"""
Zip data to create OHLC shape
OHLC shape: low to high vertical bar with
horizontal branches for open and close values.
If dates were added, the smallest date difference is calculated and
multiplied by .2 to get the length of the open and close branches.
If no date data was provided, the x-axis is a list of integers and the
length of the open and close branches is .2.
"""
self.all_y = list(
zip(
self.open,
self.open,
self.high,
self.low,
self.close,
self.close,
self.empty,
)
)
if self.dates is not None:
date_dif = []
for i in range(len(self.dates) - 1):
date_dif.append(self.dates[i + 1] - self.dates[i])
date_dif_min = (min(date_dif)) / 5
self.all_x = [
[x - date_dif_min, x, x, x, x, x + date_dif_min, None]
for x in self.dates
]
else:
self.all_x = [
[x - 0.2, x, x, x, x, x + 0.2, None] for x in range(len(self.open))
] | [
"def",
"get_all_xy",
"(",
"self",
")",
":",
"self",
".",
"all_y",
"=",
"list",
"(",
"zip",
"(",
"self",
".",
"open",
",",
"self",
".",
"open",
",",
"self",
".",
"high",
",",
"self",
".",
"low",
",",
"self",
".",
"close",
",",
"self",
".",
"close",
",",
"self",
".",
"empty",
",",
")",
")",
"if",
"self",
".",
"dates",
"is",
"not",
"None",
":",
"date_dif",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"dates",
")",
"-",
"1",
")",
":",
"date_dif",
".",
"append",
"(",
"self",
".",
"dates",
"[",
"i",
"+",
"1",
"]",
"-",
"self",
".",
"dates",
"[",
"i",
"]",
")",
"date_dif_min",
"=",
"(",
"min",
"(",
"date_dif",
")",
")",
"/",
"5",
"self",
".",
"all_x",
"=",
"[",
"[",
"x",
"-",
"date_dif_min",
",",
"x",
",",
"x",
",",
"x",
",",
"x",
",",
"x",
"+",
"date_dif_min",
",",
"None",
"]",
"for",
"x",
"in",
"self",
".",
"dates",
"]",
"else",
":",
"self",
".",
"all_x",
"=",
"[",
"[",
"x",
"-",
"0.2",
",",
"x",
",",
"x",
",",
"x",
",",
"x",
",",
"x",
"+",
"0.2",
",",
"None",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"open",
")",
")",
"]"
] | [
213,
4
] | [
247,
13
] | python | en | ['en', 'error', 'th'] | False |
_OHLC.separate_increase_decrease | (self) |
Separate data into two groups: increase and decrease
(1) Increase, where close > open and
(2) Decrease, where close <= open
|
Separate data into two groups: increase and decrease | def separate_increase_decrease(self):
"""
Separate data into two groups: increase and decrease
(1) Increase, where close > open and
(2) Decrease, where close <= open
"""
for index in range(len(self.open)):
if self.close[index] is None:
pass
elif self.close[index] > self.open[index]:
self.increase_x.append(self.all_x[index])
self.increase_y.append(self.all_y[index])
else:
self.decrease_x.append(self.all_x[index])
self.decrease_y.append(self.all_y[index]) | [
"def",
"separate_increase_decrease",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"open",
")",
")",
":",
"if",
"self",
".",
"close",
"[",
"index",
"]",
"is",
"None",
":",
"pass",
"elif",
"self",
".",
"close",
"[",
"index",
"]",
">",
"self",
".",
"open",
"[",
"index",
"]",
":",
"self",
".",
"increase_x",
".",
"append",
"(",
"self",
".",
"all_x",
"[",
"index",
"]",
")",
"self",
".",
"increase_y",
".",
"append",
"(",
"self",
".",
"all_y",
"[",
"index",
"]",
")",
"else",
":",
"self",
".",
"decrease_x",
".",
"append",
"(",
"self",
".",
"all_x",
"[",
"index",
"]",
")",
"self",
".",
"decrease_y",
".",
"append",
"(",
"self",
".",
"all_y",
"[",
"index",
"]",
")"
] | [
249,
4
] | [
264,
57
] | python | en | ['en', 'error', 'th'] | False |
_OHLC.get_increase | (self) |
Flatten increase data and get increase text
:rtype (list, list, list): flat_increase_x: x-values for the increasing
trace, flat_increase_y: y=values for the increasing trace and
text_increase: hovertext for the increasing trace
|
Flatten increase data and get increase text | def get_increase(self):
"""
Flatten increase data and get increase text
:rtype (list, list, list): flat_increase_x: x-values for the increasing
trace, flat_increase_y: y=values for the increasing trace and
text_increase: hovertext for the increasing trace
"""
flat_increase_x = utils.flatten(self.increase_x)
flat_increase_y = utils.flatten(self.increase_y)
text_increase = ("Open", "Open", "High", "Low", "Close", "Close", "") * (
len(self.increase_x)
)
return flat_increase_x, flat_increase_y, text_increase | [
"def",
"get_increase",
"(",
"self",
")",
":",
"flat_increase_x",
"=",
"utils",
".",
"flatten",
"(",
"self",
".",
"increase_x",
")",
"flat_increase_y",
"=",
"utils",
".",
"flatten",
"(",
"self",
".",
"increase_y",
")",
"text_increase",
"=",
"(",
"\"Open\"",
",",
"\"Open\"",
",",
"\"High\"",
",",
"\"Low\"",
",",
"\"Close\"",
",",
"\"Close\"",
",",
"\"\"",
")",
"*",
"(",
"len",
"(",
"self",
".",
"increase_x",
")",
")",
"return",
"flat_increase_x",
",",
"flat_increase_y",
",",
"text_increase"
] | [
266,
4
] | [
280,
62
] | python | en | ['en', 'error', 'th'] | False |
_OHLC.get_decrease | (self) |
Flatten decrease data and get decrease text
:rtype (list, list, list): flat_decrease_x: x-values for the decreasing
trace, flat_decrease_y: y=values for the decreasing trace and
text_decrease: hovertext for the decreasing trace
|
Flatten decrease data and get decrease text | def get_decrease(self):
"""
Flatten decrease data and get decrease text
:rtype (list, list, list): flat_decrease_x: x-values for the decreasing
trace, flat_decrease_y: y=values for the decreasing trace and
text_decrease: hovertext for the decreasing trace
"""
flat_decrease_x = utils.flatten(self.decrease_x)
flat_decrease_y = utils.flatten(self.decrease_y)
text_decrease = ("Open", "Open", "High", "Low", "Close", "Close", "") * (
len(self.decrease_x)
)
return flat_decrease_x, flat_decrease_y, text_decrease | [
"def",
"get_decrease",
"(",
"self",
")",
":",
"flat_decrease_x",
"=",
"utils",
".",
"flatten",
"(",
"self",
".",
"decrease_x",
")",
"flat_decrease_y",
"=",
"utils",
".",
"flatten",
"(",
"self",
".",
"decrease_y",
")",
"text_decrease",
"=",
"(",
"\"Open\"",
",",
"\"Open\"",
",",
"\"High\"",
",",
"\"Low\"",
",",
"\"Close\"",
",",
"\"Close\"",
",",
"\"\"",
")",
"*",
"(",
"len",
"(",
"self",
".",
"decrease_x",
")",
")",
"return",
"flat_decrease_x",
",",
"flat_decrease_y",
",",
"text_decrease"
] | [
282,
4
] | [
296,
62
] | 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.treemap.marker
.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
|
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.treemap.marker
.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat" | def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.treemap.marker
.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super(Tickformatstop, self).__init__("tickformatstops")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.treemap.marker.colorbar.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.treemap.marker.colorbar.Tickformatstop`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("dtickrange", None)
_v = dtickrange if dtickrange is not None else _v
if _v is not None:
self["dtickrange"] = _v
_v = arg.pop("enabled", None)
_v = enabled if enabled is not None else _v
if _v is not None:
self["enabled"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("value", None)
_v = value if value is not None else _v
if _v is not None:
self["value"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"dtickrange",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"name",
"=",
"None",
",",
"templateitemname",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Tickformatstop",
",",
"self",
")",
".",
"__init__",
"(",
"\"tickformatstops\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.treemap.marker.colorbar.Tickformatstop \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.treemap.marker.colorbar.Tickformatstop`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"dtickrange\"",
",",
"None",
")",
"_v",
"=",
"dtickrange",
"if",
"dtickrange",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"dtickrange\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"enabled\"",
",",
"None",
")",
"_v",
"=",
"enabled",
"if",
"enabled",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"enabled\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"name\"",
",",
"None",
")",
"_v",
"=",
"name",
"if",
"name",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"name\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"templateitemname\"",
",",
"None",
")",
"_v",
"=",
"templateitemname",
"if",
"templateitemname",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"templateitemname\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"value\"",
",",
"None",
")",
"_v",
"=",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"value\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
172,
4
] | [
282,
34
] | python | en | ['en', 'error', 'th'] | False |
_shared_login | (request) |
Handle the shared login between website and webclient.
|
Handle the shared login between website and webclient. | def _shared_login(request):
"""
Handle the shared login between website and webclient.
"""
csession = request.session
account = request.user
website_uid = csession.get("website_authenticated_uid", None)
webclient_uid = csession.get("webclient_authenticated_uid", None)
if not csession.session_key:
# this is necessary to build the sessid key
csession.save()
if account.is_authenticated():
# Logged into website
if not website_uid:
# fresh website login (just from login page)
csession["website_authenticated_uid"] = account.id
if webclient_uid is None:
# auto-login web client
csession["webclient_authenticated_uid"] = account.id
elif webclient_uid:
# Not logged into website, but logged into webclient
if not website_uid:
csession["website_authenticated_uid"] = account.id
account = AccountDB.objects.get(id=webclient_uid)
try:
# calls our custom authenticate, in web/utils/backend.py
authenticate(autologin=account)
login(request, account)
except AttributeError:
logger.log_trace() | [
"def",
"_shared_login",
"(",
"request",
")",
":",
"csession",
"=",
"request",
".",
"session",
"account",
"=",
"request",
".",
"user",
"website_uid",
"=",
"csession",
".",
"get",
"(",
"\"website_authenticated_uid\"",
",",
"None",
")",
"webclient_uid",
"=",
"csession",
".",
"get",
"(",
"\"webclient_authenticated_uid\"",
",",
"None",
")",
"if",
"not",
"csession",
".",
"session_key",
":",
"# this is necessary to build the sessid key",
"csession",
".",
"save",
"(",
")",
"if",
"account",
".",
"is_authenticated",
"(",
")",
":",
"# Logged into website",
"if",
"not",
"website_uid",
":",
"# fresh website login (just from login page)",
"csession",
"[",
"\"website_authenticated_uid\"",
"]",
"=",
"account",
".",
"id",
"if",
"webclient_uid",
"is",
"None",
":",
"# auto-login web client",
"csession",
"[",
"\"webclient_authenticated_uid\"",
"]",
"=",
"account",
".",
"id",
"elif",
"webclient_uid",
":",
"# Not logged into website, but logged into webclient",
"if",
"not",
"website_uid",
":",
"csession",
"[",
"\"website_authenticated_uid\"",
"]",
"=",
"account",
".",
"id",
"account",
"=",
"AccountDB",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"webclient_uid",
")",
"try",
":",
"# calls our custom authenticate, in web/utils/backend.py",
"authenticate",
"(",
"autologin",
"=",
"account",
")",
"login",
"(",
"request",
",",
"account",
")",
"except",
"AttributeError",
":",
"logger",
".",
"log_trace",
"(",
")"
] | [
23,
0
] | [
56,
34
] | python | en | ['en', 'error', 'th'] | False |
page_index | (request) |
Main root page.
|
Main root page.
| def page_index(request):
"""
Main root page.
"""
# handle webclient-website shared login
_shared_login(request)
# get game db stats
pagevars = _gamestats()
return render(request, 'index.html', pagevars) | [
"def",
"page_index",
"(",
"request",
")",
":",
"# handle webclient-website shared login",
"_shared_login",
"(",
"request",
")",
"# get game db stats",
"pagevars",
"=",
"_gamestats",
"(",
")",
"return",
"render",
"(",
"request",
",",
"'index.html'",
",",
"pagevars",
")"
] | [
94,
0
] | [
105,
50
] | python | en | ['en', 'error', 'th'] | False |
to_be_implemented | (request) |
A notice letting the user know that this particular feature hasn't been
implemented yet.
|
A notice letting the user know that this particular feature hasn't been
implemented yet.
| def to_be_implemented(request):
"""
A notice letting the user know that this particular feature hasn't been
implemented yet.
"""
pagevars = {
"page_title": "To Be Implemented...",
}
return render(request, 'tbi.html', pagevars) | [
"def",
"to_be_implemented",
"(",
"request",
")",
":",
"pagevars",
"=",
"{",
"\"page_title\"",
":",
"\"To Be Implemented...\"",
",",
"}",
"return",
"render",
"(",
"request",
",",
"'tbi.html'",
",",
"pagevars",
")"
] | [
108,
0
] | [
118,
48
] | python | en | ['en', 'error', 'th'] | False |
evennia_admin | (request) |
Helpful Evennia-specific admin page.
|
Helpful Evennia-specific admin page.
| def evennia_admin(request):
"""
Helpful Evennia-specific admin page.
"""
return render(
request, 'evennia_admin.html', {
'accountdb': AccountDB}) | [
"def",
"evennia_admin",
"(",
"request",
")",
":",
"return",
"render",
"(",
"request",
",",
"'evennia_admin.html'",
",",
"{",
"'accountdb'",
":",
"AccountDB",
"}",
")"
] | [
122,
0
] | [
128,
36
] | python | en | ['en', 'error', 'th'] | False |
admin_wrapper | (request) |
Wrapper that allows us to properly use the base Django admin site, if needed.
|
Wrapper that allows us to properly use the base Django admin site, if needed.
| def admin_wrapper(request):
"""
Wrapper that allows us to properly use the base Django admin site, if needed.
"""
return staff_member_required(site.index)(request) | [
"def",
"admin_wrapper",
"(",
"request",
")",
":",
"return",
"staff_member_required",
"(",
"site",
".",
"index",
")",
"(",
"request",
")"
] | [
131,
0
] | [
135,
53
] | python | en | ['en', 'error', 'th'] | False |
DepthPoints.flip | (self, bev_direction='horizontal') | Flip the boxes in BEV along given BEV direction. | Flip the boxes in BEV along given BEV direction. | def flip(self, bev_direction='horizontal'):
"""Flip the boxes in BEV along given BEV direction."""
if bev_direction == 'horizontal':
self.tensor[:, 0] = -self.tensor[:, 0]
elif bev_direction == 'vertical':
self.tensor[:, 1] = -self.tensor[:, 1] | [
"def",
"flip",
"(",
"self",
",",
"bev_direction",
"=",
"'horizontal'",
")",
":",
"if",
"bev_direction",
"==",
"'horizontal'",
":",
"self",
".",
"tensor",
"[",
":",
",",
"0",
"]",
"=",
"-",
"self",
".",
"tensor",
"[",
":",
",",
"0",
"]",
"elif",
"bev_direction",
"==",
"'vertical'",
":",
"self",
".",
"tensor",
"[",
":",
",",
"1",
"]",
"=",
"-",
"self",
".",
"tensor",
"[",
":",
",",
"1",
"]"
] | [
27,
4
] | [
32,
50
] | python | en | ['en', 'da', 'en'] | True |
DepthPoints.in_range_bev | (self, point_range) | Check whether the points are in the given range.
Args:
point_range (list | torch.Tensor): The range of point
in order of (x_min, y_min, x_max, y_max).
Returns:
torch.Tensor: Indicating whether each point is inside \
the reference range.
| Check whether the points are in the given range. | def in_range_bev(self, point_range):
"""Check whether the points are in the given range.
Args:
point_range (list | torch.Tensor): The range of point
in order of (x_min, y_min, x_max, y_max).
Returns:
torch.Tensor: Indicating whether each point is inside \
the reference range.
"""
in_range_flags = ((self.tensor[:, 0] > point_range[0])
& (self.tensor[:, 1] > point_range[1])
& (self.tensor[:, 0] < point_range[2])
& (self.tensor[:, 1] < point_range[3]))
return in_range_flags | [
"def",
"in_range_bev",
"(",
"self",
",",
"point_range",
")",
":",
"in_range_flags",
"=",
"(",
"(",
"self",
".",
"tensor",
"[",
":",
",",
"0",
"]",
">",
"point_range",
"[",
"0",
"]",
")",
"&",
"(",
"self",
".",
"tensor",
"[",
":",
",",
"1",
"]",
">",
"point_range",
"[",
"1",
"]",
")",
"&",
"(",
"self",
".",
"tensor",
"[",
":",
",",
"0",
"]",
"<",
"point_range",
"[",
"2",
"]",
")",
"&",
"(",
"self",
".",
"tensor",
"[",
":",
",",
"1",
"]",
"<",
"point_range",
"[",
"3",
"]",
")",
")",
"return",
"in_range_flags"
] | [
34,
4
] | [
49,
29
] | python | en | ['en', 'en', 'en'] | True |
DepthPoints.convert_to | (self, dst, rt_mat=None) | Convert self to ``dst`` mode.
Args:
dst (:obj:`CoordMode`): The target Point mode.
rt_mat (np.ndarray | torch.Tensor): The rotation and translation
matrix between different coordinates. Defaults to None.
The conversion from `src` coordinates to `dst` coordinates
usually comes along the change of sensors, e.g., from camera
to LiDAR. This requires a transformation matrix.
Returns:
:obj:`BasePoints`: The converted point of the same type \
in the `dst` mode.
| Convert self to ``dst`` mode. | def convert_to(self, dst, rt_mat=None):
"""Convert self to ``dst`` mode.
Args:
dst (:obj:`CoordMode`): The target Point mode.
rt_mat (np.ndarray | torch.Tensor): The rotation and translation
matrix between different coordinates. Defaults to None.
The conversion from `src` coordinates to `dst` coordinates
usually comes along the change of sensors, e.g., from camera
to LiDAR. This requires a transformation matrix.
Returns:
:obj:`BasePoints`: The converted point of the same type \
in the `dst` mode.
"""
from mmdet3d.core.bbox import Coord3DMode
return Coord3DMode.convert_point(
point=self, src=Coord3DMode.DEPTH, dst=dst, rt_mat=rt_mat) | [
"def",
"convert_to",
"(",
"self",
",",
"dst",
",",
"rt_mat",
"=",
"None",
")",
":",
"from",
"mmdet3d",
".",
"core",
".",
"bbox",
"import",
"Coord3DMode",
"return",
"Coord3DMode",
".",
"convert_point",
"(",
"point",
"=",
"self",
",",
"src",
"=",
"Coord3DMode",
".",
"DEPTH",
",",
"dst",
"=",
"dst",
",",
"rt_mat",
"=",
"rt_mat",
")"
] | [
51,
4
] | [
68,
70
] | python | en | ['en', 'en', 'en'] | True |
Rangefont.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
63,
28
] | python | en | ['en', 'error', 'th'] | False |
Rangefont.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
72,
4
] | [
94,
29
] | python | en | ['en', 'error', 'th'] | False |
Rangefont.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf] | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
103,
4
] | [
112,
27
] | python | en | ['en', 'error', 'th'] | False |
Rangefont.__init__ | (self, arg=None, color=None, family=None, size=None, **kwargs) |
Construct a new Rangefont object
Sets the font for the `dimension` range values.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.parcoords.Rangefont`
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
-------
Rangefont
|
Construct a new Rangefont object
Sets the font for the `dimension` range values. | def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Rangefont object
Sets the font for the `dimension` range values.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.parcoords.Rangefont`
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
-------
Rangefont
"""
super(Rangefont, self).__init__("rangefont")
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.parcoords.Rangefont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.parcoords.Rangefont`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"family",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Rangefont",
",",
"self",
")",
".",
"__init__",
"(",
"\"rangefont\"",
")",
"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.parcoords.Rangefont \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.parcoords.Rangefont`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
143,
4
] | [
226,
34
] | python | en | ['en', 'error', 'th'] | False |
calc_stats | (data) |
Calculate statistics for use in violin plot.
|
Calculate statistics for use in violin plot.
| def calc_stats(data):
"""
Calculate statistics for use in violin plot.
"""
x = np.asarray(data, np.float)
vals_min = np.min(x)
vals_max = np.max(x)
q2 = np.percentile(x, 50, interpolation="linear")
q1 = np.percentile(x, 25, interpolation="lower")
q3 = np.percentile(x, 75, interpolation="higher")
iqr = q3 - q1
whisker_dist = 1.5 * iqr
# in order to prevent drawing whiskers outside the interval
# of data one defines the whisker positions as:
d1 = np.min(x[x >= (q1 - whisker_dist)])
d2 = np.max(x[x <= (q3 + whisker_dist)])
return {
"min": vals_min,
"max": vals_max,
"q1": q1,
"q2": q2,
"q3": q3,
"d1": d1,
"d2": d2,
} | [
"def",
"calc_stats",
"(",
"data",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"data",
",",
"np",
".",
"float",
")",
"vals_min",
"=",
"np",
".",
"min",
"(",
"x",
")",
"vals_max",
"=",
"np",
".",
"max",
"(",
"x",
")",
"q2",
"=",
"np",
".",
"percentile",
"(",
"x",
",",
"50",
",",
"interpolation",
"=",
"\"linear\"",
")",
"q1",
"=",
"np",
".",
"percentile",
"(",
"x",
",",
"25",
",",
"interpolation",
"=",
"\"lower\"",
")",
"q3",
"=",
"np",
".",
"percentile",
"(",
"x",
",",
"75",
",",
"interpolation",
"=",
"\"higher\"",
")",
"iqr",
"=",
"q3",
"-",
"q1",
"whisker_dist",
"=",
"1.5",
"*",
"iqr",
"# in order to prevent drawing whiskers outside the interval",
"# of data one defines the whisker positions as:",
"d1",
"=",
"np",
".",
"min",
"(",
"x",
"[",
"x",
">=",
"(",
"q1",
"-",
"whisker_dist",
")",
"]",
")",
"d2",
"=",
"np",
".",
"max",
"(",
"x",
"[",
"x",
"<=",
"(",
"q3",
"+",
"whisker_dist",
")",
"]",
")",
"return",
"{",
"\"min\"",
":",
"vals_min",
",",
"\"max\"",
":",
"vals_max",
",",
"\"q1\"",
":",
"q1",
",",
"\"q2\"",
":",
"q2",
",",
"\"q3\"",
":",
"q3",
",",
"\"d1\"",
":",
"d1",
",",
"\"d2\"",
":",
"d2",
",",
"}"
] | [
14,
0
] | [
39,
5
] | python | en | ['en', 'error', 'th'] | False |
make_half_violin | (x, y, fillcolor="#1f77b4", linecolor="rgb(0, 0, 0)") |
Produces a sideways probability distribution fig violin plot.
|
Produces a sideways probability distribution fig violin plot.
| def make_half_violin(x, y, fillcolor="#1f77b4", linecolor="rgb(0, 0, 0)"):
"""
Produces a sideways probability distribution fig violin plot.
"""
text = [
"(pdf(y), y)=(" + "{:0.2f}".format(x[i]) + ", " + "{:0.2f}".format(y[i]) + ")"
for i in range(len(x))
]
return graph_objs.Scatter(
x=x,
y=y,
mode="lines",
name="",
text=text,
fill="tonextx",
fillcolor=fillcolor,
line=graph_objs.scatter.Line(width=0.5, color=linecolor, shape="spline"),
hoverinfo="text",
opacity=0.5,
) | [
"def",
"make_half_violin",
"(",
"x",
",",
"y",
",",
"fillcolor",
"=",
"\"#1f77b4\"",
",",
"linecolor",
"=",
"\"rgb(0, 0, 0)\"",
")",
":",
"text",
"=",
"[",
"\"(pdf(y), y)=(\"",
"+",
"\"{:0.2f}\"",
".",
"format",
"(",
"x",
"[",
"i",
"]",
")",
"+",
"\", \"",
"+",
"\"{:0.2f}\"",
".",
"format",
"(",
"y",
"[",
"i",
"]",
")",
"+",
"\")\"",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"x",
")",
")",
"]",
"return",
"graph_objs",
".",
"Scatter",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"mode",
"=",
"\"lines\"",
",",
"name",
"=",
"\"\"",
",",
"text",
"=",
"text",
",",
"fill",
"=",
"\"tonextx\"",
",",
"fillcolor",
"=",
"fillcolor",
",",
"line",
"=",
"graph_objs",
".",
"scatter",
".",
"Line",
"(",
"width",
"=",
"0.5",
",",
"color",
"=",
"linecolor",
",",
"shape",
"=",
"\"spline\"",
")",
",",
"hoverinfo",
"=",
"\"text\"",
",",
"opacity",
"=",
"0.5",
",",
")"
] | [
42,
0
] | [
62,
5
] | python | en | ['en', 'error', 'th'] | False |
make_violin_rugplot | (vals, pdf_max, distance, color="#1f77b4") |
Returns a rugplot fig for a violin plot.
|
Returns a rugplot fig for a violin plot.
| def make_violin_rugplot(vals, pdf_max, distance, color="#1f77b4"):
"""
Returns a rugplot fig for a violin plot.
"""
return graph_objs.Scatter(
y=vals,
x=[-pdf_max - distance] * len(vals),
marker=graph_objs.scatter.Marker(color=color, symbol="line-ew-open"),
mode="markers",
name="",
showlegend=False,
hoverinfo="y",
) | [
"def",
"make_violin_rugplot",
"(",
"vals",
",",
"pdf_max",
",",
"distance",
",",
"color",
"=",
"\"#1f77b4\"",
")",
":",
"return",
"graph_objs",
".",
"Scatter",
"(",
"y",
"=",
"vals",
",",
"x",
"=",
"[",
"-",
"pdf_max",
"-",
"distance",
"]",
"*",
"len",
"(",
"vals",
")",
",",
"marker",
"=",
"graph_objs",
".",
"scatter",
".",
"Marker",
"(",
"color",
"=",
"color",
",",
"symbol",
"=",
"\"line-ew-open\"",
")",
",",
"mode",
"=",
"\"markers\"",
",",
"name",
"=",
"\"\"",
",",
"showlegend",
"=",
"False",
",",
"hoverinfo",
"=",
"\"y\"",
",",
")"
] | [
65,
0
] | [
77,
5
] | python | en | ['en', 'error', 'th'] | False |
make_non_outlier_interval | (d1, d2) |
Returns the scatterplot fig of most of a violin plot.
|
Returns the scatterplot fig of most of a violin plot.
| def make_non_outlier_interval(d1, d2):
"""
Returns the scatterplot fig of most of a violin plot.
"""
return graph_objs.Scatter(
x=[0, 0],
y=[d1, d2],
name="",
mode="lines",
line=graph_objs.scatter.Line(width=1.5, color="rgb(0,0,0)"),
) | [
"def",
"make_non_outlier_interval",
"(",
"d1",
",",
"d2",
")",
":",
"return",
"graph_objs",
".",
"Scatter",
"(",
"x",
"=",
"[",
"0",
",",
"0",
"]",
",",
"y",
"=",
"[",
"d1",
",",
"d2",
"]",
",",
"name",
"=",
"\"\"",
",",
"mode",
"=",
"\"lines\"",
",",
"line",
"=",
"graph_objs",
".",
"scatter",
".",
"Line",
"(",
"width",
"=",
"1.5",
",",
"color",
"=",
"\"rgb(0,0,0)\"",
")",
",",
")"
] | [
80,
0
] | [
90,
5
] | python | en | ['en', 'error', 'th'] | False |
make_quartiles | (q1, q3) |
Makes the upper and lower quartiles for a violin plot.
|
Makes the upper and lower quartiles for a violin plot.
| def make_quartiles(q1, q3):
"""
Makes the upper and lower quartiles for a violin plot.
"""
return graph_objs.Scatter(
x=[0, 0],
y=[q1, q3],
text=[
"lower-quartile: " + "{:0.2f}".format(q1),
"upper-quartile: " + "{:0.2f}".format(q3),
],
mode="lines",
line=graph_objs.scatter.Line(width=4, color="rgb(0,0,0)"),
hoverinfo="text",
) | [
"def",
"make_quartiles",
"(",
"q1",
",",
"q3",
")",
":",
"return",
"graph_objs",
".",
"Scatter",
"(",
"x",
"=",
"[",
"0",
",",
"0",
"]",
",",
"y",
"=",
"[",
"q1",
",",
"q3",
"]",
",",
"text",
"=",
"[",
"\"lower-quartile: \"",
"+",
"\"{:0.2f}\"",
".",
"format",
"(",
"q1",
")",
",",
"\"upper-quartile: \"",
"+",
"\"{:0.2f}\"",
".",
"format",
"(",
"q3",
")",
",",
"]",
",",
"mode",
"=",
"\"lines\"",
",",
"line",
"=",
"graph_objs",
".",
"scatter",
".",
"Line",
"(",
"width",
"=",
"4",
",",
"color",
"=",
"\"rgb(0,0,0)\"",
")",
",",
"hoverinfo",
"=",
"\"text\"",
",",
")"
] | [
93,
0
] | [
107,
5
] | python | en | ['en', 'error', 'th'] | False |
make_median | (q2) |
Formats the 'median' hovertext for a violin plot.
|
Formats the 'median' hovertext for a violin plot.
| def make_median(q2):
"""
Formats the 'median' hovertext for a violin plot.
"""
return graph_objs.Scatter(
x=[0],
y=[q2],
text=["median: " + "{:0.2f}".format(q2)],
mode="markers",
marker=dict(symbol="square", color="rgb(255,255,255)"),
hoverinfo="text",
) | [
"def",
"make_median",
"(",
"q2",
")",
":",
"return",
"graph_objs",
".",
"Scatter",
"(",
"x",
"=",
"[",
"0",
"]",
",",
"y",
"=",
"[",
"q2",
"]",
",",
"text",
"=",
"[",
"\"median: \"",
"+",
"\"{:0.2f}\"",
".",
"format",
"(",
"q2",
")",
"]",
",",
"mode",
"=",
"\"markers\"",
",",
"marker",
"=",
"dict",
"(",
"symbol",
"=",
"\"square\"",
",",
"color",
"=",
"\"rgb(255,255,255)\"",
")",
",",
"hoverinfo",
"=",
"\"text\"",
",",
")"
] | [
110,
0
] | [
121,
5
] | python | en | ['en', 'error', 'th'] | False |
make_XAxis | (xaxis_title, xaxis_range) |
Makes the x-axis for a violin plot.
|
Makes the x-axis for a violin plot.
| def make_XAxis(xaxis_title, xaxis_range):
"""
Makes the x-axis for a violin plot.
"""
xaxis = graph_objs.layout.XAxis(
title=xaxis_title,
range=xaxis_range,
showgrid=False,
zeroline=False,
showline=False,
mirror=False,
ticks="",
showticklabels=False,
)
return xaxis | [
"def",
"make_XAxis",
"(",
"xaxis_title",
",",
"xaxis_range",
")",
":",
"xaxis",
"=",
"graph_objs",
".",
"layout",
".",
"XAxis",
"(",
"title",
"=",
"xaxis_title",
",",
"range",
"=",
"xaxis_range",
",",
"showgrid",
"=",
"False",
",",
"zeroline",
"=",
"False",
",",
"showline",
"=",
"False",
",",
"mirror",
"=",
"False",
",",
"ticks",
"=",
"\"\"",
",",
"showticklabels",
"=",
"False",
",",
")",
"return",
"xaxis"
] | [
124,
0
] | [
138,
16
] | python | en | ['en', 'error', 'th'] | False |
make_YAxis | (yaxis_title) |
Makes the y-axis for a violin plot.
|
Makes the y-axis for a violin plot.
| def make_YAxis(yaxis_title):
"""
Makes the y-axis for a violin plot.
"""
yaxis = graph_objs.layout.YAxis(
title=yaxis_title,
showticklabels=True,
autorange=True,
ticklen=4,
showline=True,
zeroline=False,
showgrid=False,
mirror=False,
)
return yaxis | [
"def",
"make_YAxis",
"(",
"yaxis_title",
")",
":",
"yaxis",
"=",
"graph_objs",
".",
"layout",
".",
"YAxis",
"(",
"title",
"=",
"yaxis_title",
",",
"showticklabels",
"=",
"True",
",",
"autorange",
"=",
"True",
",",
"ticklen",
"=",
"4",
",",
"showline",
"=",
"True",
",",
"zeroline",
"=",
"False",
",",
"showgrid",
"=",
"False",
",",
"mirror",
"=",
"False",
",",
")",
"return",
"yaxis"
] | [
141,
0
] | [
155,
16
] | python | en | ['en', 'error', 'th'] | False |
violinplot | (vals, fillcolor="#1f77b4", rugplot=True) |
Refer to FigureFactory.create_violin() for docstring.
|
Refer to FigureFactory.create_violin() for docstring.
| def violinplot(vals, fillcolor="#1f77b4", rugplot=True):
"""
Refer to FigureFactory.create_violin() for docstring.
"""
vals = np.asarray(vals, np.float)
# summary statistics
vals_min = calc_stats(vals)["min"]
vals_max = calc_stats(vals)["max"]
q1 = calc_stats(vals)["q1"]
q2 = calc_stats(vals)["q2"]
q3 = calc_stats(vals)["q3"]
d1 = calc_stats(vals)["d1"]
d2 = calc_stats(vals)["d2"]
# kernel density estimation of pdf
pdf = scipy_stats.gaussian_kde(vals)
# grid over the data interval
xx = np.linspace(vals_min, vals_max, 100)
# evaluate the pdf at the grid xx
yy = pdf(xx)
max_pdf = np.max(yy)
# distance from the violin plot to rugplot
distance = (2.0 * max_pdf) / 10 if rugplot else 0
# range for x values in the plot
plot_xrange = [-max_pdf - distance - 0.1, max_pdf + 0.1]
plot_data = [
make_half_violin(-yy, xx, fillcolor=fillcolor),
make_half_violin(yy, xx, fillcolor=fillcolor),
make_non_outlier_interval(d1, d2),
make_quartiles(q1, q3),
make_median(q2),
]
if rugplot:
plot_data.append(
make_violin_rugplot(vals, max_pdf, distance=distance, color=fillcolor)
)
return plot_data, plot_xrange | [
"def",
"violinplot",
"(",
"vals",
",",
"fillcolor",
"=",
"\"#1f77b4\"",
",",
"rugplot",
"=",
"True",
")",
":",
"vals",
"=",
"np",
".",
"asarray",
"(",
"vals",
",",
"np",
".",
"float",
")",
"# summary statistics",
"vals_min",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"min\"",
"]",
"vals_max",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"max\"",
"]",
"q1",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"q1\"",
"]",
"q2",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"q2\"",
"]",
"q3",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"q3\"",
"]",
"d1",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"d1\"",
"]",
"d2",
"=",
"calc_stats",
"(",
"vals",
")",
"[",
"\"d2\"",
"]",
"# kernel density estimation of pdf",
"pdf",
"=",
"scipy_stats",
".",
"gaussian_kde",
"(",
"vals",
")",
"# grid over the data interval",
"xx",
"=",
"np",
".",
"linspace",
"(",
"vals_min",
",",
"vals_max",
",",
"100",
")",
"# evaluate the pdf at the grid xx",
"yy",
"=",
"pdf",
"(",
"xx",
")",
"max_pdf",
"=",
"np",
".",
"max",
"(",
"yy",
")",
"# distance from the violin plot to rugplot",
"distance",
"=",
"(",
"2.0",
"*",
"max_pdf",
")",
"/",
"10",
"if",
"rugplot",
"else",
"0",
"# range for x values in the plot",
"plot_xrange",
"=",
"[",
"-",
"max_pdf",
"-",
"distance",
"-",
"0.1",
",",
"max_pdf",
"+",
"0.1",
"]",
"plot_data",
"=",
"[",
"make_half_violin",
"(",
"-",
"yy",
",",
"xx",
",",
"fillcolor",
"=",
"fillcolor",
")",
",",
"make_half_violin",
"(",
"yy",
",",
"xx",
",",
"fillcolor",
"=",
"fillcolor",
")",
",",
"make_non_outlier_interval",
"(",
"d1",
",",
"d2",
")",
",",
"make_quartiles",
"(",
"q1",
",",
"q3",
")",
",",
"make_median",
"(",
"q2",
")",
",",
"]",
"if",
"rugplot",
":",
"plot_data",
".",
"append",
"(",
"make_violin_rugplot",
"(",
"vals",
",",
"max_pdf",
",",
"distance",
"=",
"distance",
",",
"color",
"=",
"fillcolor",
")",
")",
"return",
"plot_data",
",",
"plot_xrange"
] | [
158,
0
] | [
194,
33
] | python | en | ['en', 'error', 'th'] | False |
violin_no_colorscale | (
data,
data_header,
group_header,
colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
) |
Refer to FigureFactory.create_violin() for docstring.
Returns fig for violin plot without colorscale.
|
Refer to FigureFactory.create_violin() for docstring. | def violin_no_colorscale(
data,
data_header,
group_header,
colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
):
"""
Refer to FigureFactory.create_violin() for docstring.
Returns fig for violin plot without colorscale.
"""
# collect all group names
group_name = []
for name in data[group_header]:
if name not in group_name:
group_name.append(name)
if sort:
group_name.sort()
gb = data.groupby([group_header])
L = len(group_name)
fig = make_subplots(
rows=1, cols=L, shared_yaxes=True, horizontal_spacing=0.025, print_grid=False
)
color_index = 0
for k, gr in enumerate(group_name):
vals = np.asarray(gb.get_group(gr)[data_header], np.float)
if color_index >= len(colors):
color_index = 0
plot_data, plot_xrange = violinplot(
vals, fillcolor=colors[color_index], rugplot=rugplot
)
layout = graph_objs.Layout()
for item in plot_data:
fig.append_trace(item, 1, k + 1)
color_index += 1
# add violin plot labels
fig["layout"].update(
{"xaxis{}".format(k + 1): make_XAxis(group_name[k], plot_xrange)}
)
# set the sharey axis style
fig["layout"].update({"yaxis{}".format(1): make_YAxis("")})
fig["layout"].update(
title=title,
showlegend=False,
hovermode="closest",
autosize=False,
height=height,
width=width,
)
return fig | [
"def",
"violin_no_colorscale",
"(",
"data",
",",
"data_header",
",",
"group_header",
",",
"colors",
",",
"use_colorscale",
",",
"group_stats",
",",
"rugplot",
",",
"sort",
",",
"height",
",",
"width",
",",
"title",
",",
")",
":",
"# collect all group names",
"group_name",
"=",
"[",
"]",
"for",
"name",
"in",
"data",
"[",
"group_header",
"]",
":",
"if",
"name",
"not",
"in",
"group_name",
":",
"group_name",
".",
"append",
"(",
"name",
")",
"if",
"sort",
":",
"group_name",
".",
"sort",
"(",
")",
"gb",
"=",
"data",
".",
"groupby",
"(",
"[",
"group_header",
"]",
")",
"L",
"=",
"len",
"(",
"group_name",
")",
"fig",
"=",
"make_subplots",
"(",
"rows",
"=",
"1",
",",
"cols",
"=",
"L",
",",
"shared_yaxes",
"=",
"True",
",",
"horizontal_spacing",
"=",
"0.025",
",",
"print_grid",
"=",
"False",
")",
"color_index",
"=",
"0",
"for",
"k",
",",
"gr",
"in",
"enumerate",
"(",
"group_name",
")",
":",
"vals",
"=",
"np",
".",
"asarray",
"(",
"gb",
".",
"get_group",
"(",
"gr",
")",
"[",
"data_header",
"]",
",",
"np",
".",
"float",
")",
"if",
"color_index",
">=",
"len",
"(",
"colors",
")",
":",
"color_index",
"=",
"0",
"plot_data",
",",
"plot_xrange",
"=",
"violinplot",
"(",
"vals",
",",
"fillcolor",
"=",
"colors",
"[",
"color_index",
"]",
",",
"rugplot",
"=",
"rugplot",
")",
"layout",
"=",
"graph_objs",
".",
"Layout",
"(",
")",
"for",
"item",
"in",
"plot_data",
":",
"fig",
".",
"append_trace",
"(",
"item",
",",
"1",
",",
"k",
"+",
"1",
")",
"color_index",
"+=",
"1",
"# add violin plot labels",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"{",
"\"xaxis{}\"",
".",
"format",
"(",
"k",
"+",
"1",
")",
":",
"make_XAxis",
"(",
"group_name",
"[",
"k",
"]",
",",
"plot_xrange",
")",
"}",
")",
"# set the sharey axis style",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"{",
"\"yaxis{}\"",
".",
"format",
"(",
"1",
")",
":",
"make_YAxis",
"(",
"\"\"",
")",
"}",
")",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"title",
"=",
"title",
",",
"showlegend",
"=",
"False",
",",
"hovermode",
"=",
"\"closest\"",
",",
"autosize",
"=",
"False",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
",",
")",
"return",
"fig"
] | [
197,
0
] | [
261,
14
] | python | en | ['en', 'error', 'th'] | False |
violin_colorscale | (
data,
data_header,
group_header,
colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
) |
Refer to FigureFactory.create_violin() for docstring.
Returns fig for violin plot with colorscale.
|
Refer to FigureFactory.create_violin() for docstring. | def violin_colorscale(
data,
data_header,
group_header,
colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
):
"""
Refer to FigureFactory.create_violin() for docstring.
Returns fig for violin plot with colorscale.
"""
# collect all group names
group_name = []
for name in data[group_header]:
if name not in group_name:
group_name.append(name)
if sort:
group_name.sort()
# make sure all group names are keys in group_stats
for group in group_name:
if group not in group_stats:
raise exceptions.PlotlyError(
"All values/groups in the index "
"column must be represented "
"as a key in group_stats."
)
gb = data.groupby([group_header])
L = len(group_name)
fig = make_subplots(
rows=1, cols=L, shared_yaxes=True, horizontal_spacing=0.025, print_grid=False
)
# prepare low and high color for colorscale
lowcolor = clrs.color_parser(colors[0], clrs.unlabel_rgb)
highcolor = clrs.color_parser(colors[1], clrs.unlabel_rgb)
# find min and max values in group_stats
group_stats_values = []
for key in group_stats:
group_stats_values.append(group_stats[key])
max_value = max(group_stats_values)
min_value = min(group_stats_values)
for k, gr in enumerate(group_name):
vals = np.asarray(gb.get_group(gr)[data_header], np.float)
# find intermediate color from colorscale
intermed = (group_stats[gr] - min_value) / (max_value - min_value)
intermed_color = clrs.find_intermediate_color(lowcolor, highcolor, intermed)
plot_data, plot_xrange = violinplot(
vals, fillcolor="rgb{}".format(intermed_color), rugplot=rugplot
)
layout = graph_objs.Layout()
for item in plot_data:
fig.append_trace(item, 1, k + 1)
fig["layout"].update(
{"xaxis{}".format(k + 1): make_XAxis(group_name[k], plot_xrange)}
)
# add colorbar to plot
trace_dummy = graph_objs.Scatter(
x=[0],
y=[0],
mode="markers",
marker=dict(
size=2,
cmin=min_value,
cmax=max_value,
colorscale=[[0, colors[0]], [1, colors[1]]],
showscale=True,
),
showlegend=False,
)
fig.append_trace(trace_dummy, 1, L)
# set the sharey axis style
fig["layout"].update({"yaxis{}".format(1): make_YAxis("")})
fig["layout"].update(
title=title,
showlegend=False,
hovermode="closest",
autosize=False,
height=height,
width=width,
)
return fig | [
"def",
"violin_colorscale",
"(",
"data",
",",
"data_header",
",",
"group_header",
",",
"colors",
",",
"use_colorscale",
",",
"group_stats",
",",
"rugplot",
",",
"sort",
",",
"height",
",",
"width",
",",
"title",
",",
")",
":",
"# collect all group names",
"group_name",
"=",
"[",
"]",
"for",
"name",
"in",
"data",
"[",
"group_header",
"]",
":",
"if",
"name",
"not",
"in",
"group_name",
":",
"group_name",
".",
"append",
"(",
"name",
")",
"if",
"sort",
":",
"group_name",
".",
"sort",
"(",
")",
"# make sure all group names are keys in group_stats",
"for",
"group",
"in",
"group_name",
":",
"if",
"group",
"not",
"in",
"group_stats",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"All values/groups in the index \"",
"\"column must be represented \"",
"\"as a key in group_stats.\"",
")",
"gb",
"=",
"data",
".",
"groupby",
"(",
"[",
"group_header",
"]",
")",
"L",
"=",
"len",
"(",
"group_name",
")",
"fig",
"=",
"make_subplots",
"(",
"rows",
"=",
"1",
",",
"cols",
"=",
"L",
",",
"shared_yaxes",
"=",
"True",
",",
"horizontal_spacing",
"=",
"0.025",
",",
"print_grid",
"=",
"False",
")",
"# prepare low and high color for colorscale",
"lowcolor",
"=",
"clrs",
".",
"color_parser",
"(",
"colors",
"[",
"0",
"]",
",",
"clrs",
".",
"unlabel_rgb",
")",
"highcolor",
"=",
"clrs",
".",
"color_parser",
"(",
"colors",
"[",
"1",
"]",
",",
"clrs",
".",
"unlabel_rgb",
")",
"# find min and max values in group_stats",
"group_stats_values",
"=",
"[",
"]",
"for",
"key",
"in",
"group_stats",
":",
"group_stats_values",
".",
"append",
"(",
"group_stats",
"[",
"key",
"]",
")",
"max_value",
"=",
"max",
"(",
"group_stats_values",
")",
"min_value",
"=",
"min",
"(",
"group_stats_values",
")",
"for",
"k",
",",
"gr",
"in",
"enumerate",
"(",
"group_name",
")",
":",
"vals",
"=",
"np",
".",
"asarray",
"(",
"gb",
".",
"get_group",
"(",
"gr",
")",
"[",
"data_header",
"]",
",",
"np",
".",
"float",
")",
"# find intermediate color from colorscale",
"intermed",
"=",
"(",
"group_stats",
"[",
"gr",
"]",
"-",
"min_value",
")",
"/",
"(",
"max_value",
"-",
"min_value",
")",
"intermed_color",
"=",
"clrs",
".",
"find_intermediate_color",
"(",
"lowcolor",
",",
"highcolor",
",",
"intermed",
")",
"plot_data",
",",
"plot_xrange",
"=",
"violinplot",
"(",
"vals",
",",
"fillcolor",
"=",
"\"rgb{}\"",
".",
"format",
"(",
"intermed_color",
")",
",",
"rugplot",
"=",
"rugplot",
")",
"layout",
"=",
"graph_objs",
".",
"Layout",
"(",
")",
"for",
"item",
"in",
"plot_data",
":",
"fig",
".",
"append_trace",
"(",
"item",
",",
"1",
",",
"k",
"+",
"1",
")",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"{",
"\"xaxis{}\"",
".",
"format",
"(",
"k",
"+",
"1",
")",
":",
"make_XAxis",
"(",
"group_name",
"[",
"k",
"]",
",",
"plot_xrange",
")",
"}",
")",
"# add colorbar to plot",
"trace_dummy",
"=",
"graph_objs",
".",
"Scatter",
"(",
"x",
"=",
"[",
"0",
"]",
",",
"y",
"=",
"[",
"0",
"]",
",",
"mode",
"=",
"\"markers\"",
",",
"marker",
"=",
"dict",
"(",
"size",
"=",
"2",
",",
"cmin",
"=",
"min_value",
",",
"cmax",
"=",
"max_value",
",",
"colorscale",
"=",
"[",
"[",
"0",
",",
"colors",
"[",
"0",
"]",
"]",
",",
"[",
"1",
",",
"colors",
"[",
"1",
"]",
"]",
"]",
",",
"showscale",
"=",
"True",
",",
")",
",",
"showlegend",
"=",
"False",
",",
")",
"fig",
".",
"append_trace",
"(",
"trace_dummy",
",",
"1",
",",
"L",
")",
"# set the sharey axis style",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"{",
"\"yaxis{}\"",
".",
"format",
"(",
"1",
")",
":",
"make_YAxis",
"(",
"\"\"",
")",
"}",
")",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"title",
"=",
"title",
",",
"showlegend",
"=",
"False",
",",
"hovermode",
"=",
"\"closest\"",
",",
"autosize",
"=",
"False",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
",",
")",
"return",
"fig"
] | [
264,
0
] | [
364,
14
] | python | en | ['en', 'error', 'th'] | False |
violin_dict | (
data,
data_header,
group_header,
colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
) |
Refer to FigureFactory.create_violin() for docstring.
Returns fig for violin plot without colorscale.
|
Refer to FigureFactory.create_violin() for docstring. | def violin_dict(
data,
data_header,
group_header,
colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
):
"""
Refer to FigureFactory.create_violin() for docstring.
Returns fig for violin plot without colorscale.
"""
# collect all group names
group_name = []
for name in data[group_header]:
if name not in group_name:
group_name.append(name)
if sort:
group_name.sort()
# check if all group names appear in colors dict
for group in group_name:
if group not in colors:
raise exceptions.PlotlyError(
"If colors is a dictionary, all "
"the group names must appear as "
"keys in colors."
)
gb = data.groupby([group_header])
L = len(group_name)
fig = make_subplots(
rows=1, cols=L, shared_yaxes=True, horizontal_spacing=0.025, print_grid=False
)
for k, gr in enumerate(group_name):
vals = np.asarray(gb.get_group(gr)[data_header], np.float)
plot_data, plot_xrange = violinplot(vals, fillcolor=colors[gr], rugplot=rugplot)
layout = graph_objs.Layout()
for item in plot_data:
fig.append_trace(item, 1, k + 1)
# add violin plot labels
fig["layout"].update(
{"xaxis{}".format(k + 1): make_XAxis(group_name[k], plot_xrange)}
)
# set the sharey axis style
fig["layout"].update({"yaxis{}".format(1): make_YAxis("")})
fig["layout"].update(
title=title,
showlegend=False,
hovermode="closest",
autosize=False,
height=height,
width=width,
)
return fig | [
"def",
"violin_dict",
"(",
"data",
",",
"data_header",
",",
"group_header",
",",
"colors",
",",
"use_colorscale",
",",
"group_stats",
",",
"rugplot",
",",
"sort",
",",
"height",
",",
"width",
",",
"title",
",",
")",
":",
"# collect all group names",
"group_name",
"=",
"[",
"]",
"for",
"name",
"in",
"data",
"[",
"group_header",
"]",
":",
"if",
"name",
"not",
"in",
"group_name",
":",
"group_name",
".",
"append",
"(",
"name",
")",
"if",
"sort",
":",
"group_name",
".",
"sort",
"(",
")",
"# check if all group names appear in colors dict",
"for",
"group",
"in",
"group_name",
":",
"if",
"group",
"not",
"in",
"colors",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"If colors is a dictionary, all \"",
"\"the group names must appear as \"",
"\"keys in colors.\"",
")",
"gb",
"=",
"data",
".",
"groupby",
"(",
"[",
"group_header",
"]",
")",
"L",
"=",
"len",
"(",
"group_name",
")",
"fig",
"=",
"make_subplots",
"(",
"rows",
"=",
"1",
",",
"cols",
"=",
"L",
",",
"shared_yaxes",
"=",
"True",
",",
"horizontal_spacing",
"=",
"0.025",
",",
"print_grid",
"=",
"False",
")",
"for",
"k",
",",
"gr",
"in",
"enumerate",
"(",
"group_name",
")",
":",
"vals",
"=",
"np",
".",
"asarray",
"(",
"gb",
".",
"get_group",
"(",
"gr",
")",
"[",
"data_header",
"]",
",",
"np",
".",
"float",
")",
"plot_data",
",",
"plot_xrange",
"=",
"violinplot",
"(",
"vals",
",",
"fillcolor",
"=",
"colors",
"[",
"gr",
"]",
",",
"rugplot",
"=",
"rugplot",
")",
"layout",
"=",
"graph_objs",
".",
"Layout",
"(",
")",
"for",
"item",
"in",
"plot_data",
":",
"fig",
".",
"append_trace",
"(",
"item",
",",
"1",
",",
"k",
"+",
"1",
")",
"# add violin plot labels",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"{",
"\"xaxis{}\"",
".",
"format",
"(",
"k",
"+",
"1",
")",
":",
"make_XAxis",
"(",
"group_name",
"[",
"k",
"]",
",",
"plot_xrange",
")",
"}",
")",
"# set the sharey axis style",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"{",
"\"yaxis{}\"",
".",
"format",
"(",
"1",
")",
":",
"make_YAxis",
"(",
"\"\"",
")",
"}",
")",
"fig",
"[",
"\"layout\"",
"]",
".",
"update",
"(",
"title",
"=",
"title",
",",
"showlegend",
"=",
"False",
",",
"hovermode",
"=",
"\"closest\"",
",",
"autosize",
"=",
"False",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
",",
")",
"return",
"fig"
] | [
367,
0
] | [
436,
14
] | python | en | ['en', 'error', 'th'] | False |
create_violin | (
data,
data_header=None,
group_header=None,
colors=None,
use_colorscale=False,
group_stats=None,
rugplot=True,
sort=False,
height=450,
width=600,
title="Violin and Rug Plot",
) |
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Violin`.
:param (list|array) data: accepts either a list of numerical values,
a list of dictionaries all with identical keys and at least one
column of numeric values, or a pandas dataframe with at least one
column of numbers.
:param (str) data_header: the header of the data column to be used
from an inputted pandas dataframe. Not applicable if 'data' is
a list of numeric values.
:param (str) group_header: applicable if grouping data by a variable.
'group_header' must be set to the name of the grouping variable.
:param (str|tuple|list|dict) colors: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colors is a list, it must contain valid color types as its
members.
:param (bool) use_colorscale: only applicable if grouping by another
variable. Will implement a colorscale based on the first 2 colors
of param colors. This means colors must be a list with at least 2
colors in it (Plotly colorscales are accepted since they map to a
list of two rgb colors). Default = False
:param (dict) group_stats: a dictioanry where each key is a unique
value from the group_header column in data. Each value must be a
number and will be used to color the violin plots if a colorscale
is being used.
:param (bool) rugplot: determines if a rugplot is draw on violin plot.
Default = True
:param (bool) sort: determines if violins are sorted
alphabetically (True) or by input order (False). Default = False
:param (float) height: the height of the violin plot.
:param (float) width: the width of the violin plot.
:param (str) title: the title of the violin plot.
Example 1: Single Violin Plot
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> from scipy import stats
>>> # create list of random values
>>> data_list = np.random.randn(100)
>>> # create violin fig
>>> fig = create_violin(data_list, colors='#604d9e')
>>> # plot
>>> fig.show()
Example 2: Multiple Violin Plots with Qualitative Coloring
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... sort=True, height=600, width=1000)
>>> # plot
>>> fig.show()
Example 3: Violin Plots with Colorscale
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # define header params
>>> data_header = 'Score'
>>> group_header = 'Group'
>>> # make groupby object with pandas
>>> group_stats = {}
>>> groupby_data = df.groupby([group_header])
>>> for group in "ABCDE":
... data_from_group = groupby_data.get_group(group)[data_header]
... # take a stat of the grouped data
... stat = np.median(data_from_group)
... # add to dictionary
... group_stats[group] = stat
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... height=600, width=1000, use_colorscale=True,
... group_stats=group_stats)
>>> # plot
>>> fig.show()
|
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Violin`. | def create_violin(
data,
data_header=None,
group_header=None,
colors=None,
use_colorscale=False,
group_stats=None,
rugplot=True,
sort=False,
height=450,
width=600,
title="Violin and Rug Plot",
):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Violin`.
:param (list|array) data: accepts either a list of numerical values,
a list of dictionaries all with identical keys and at least one
column of numeric values, or a pandas dataframe with at least one
column of numbers.
:param (str) data_header: the header of the data column to be used
from an inputted pandas dataframe. Not applicable if 'data' is
a list of numeric values.
:param (str) group_header: applicable if grouping data by a variable.
'group_header' must be set to the name of the grouping variable.
:param (str|tuple|list|dict) colors: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colors is a list, it must contain valid color types as its
members.
:param (bool) use_colorscale: only applicable if grouping by another
variable. Will implement a colorscale based on the first 2 colors
of param colors. This means colors must be a list with at least 2
colors in it (Plotly colorscales are accepted since they map to a
list of two rgb colors). Default = False
:param (dict) group_stats: a dictioanry where each key is a unique
value from the group_header column in data. Each value must be a
number and will be used to color the violin plots if a colorscale
is being used.
:param (bool) rugplot: determines if a rugplot is draw on violin plot.
Default = True
:param (bool) sort: determines if violins are sorted
alphabetically (True) or by input order (False). Default = False
:param (float) height: the height of the violin plot.
:param (float) width: the width of the violin plot.
:param (str) title: the title of the violin plot.
Example 1: Single Violin Plot
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> from scipy import stats
>>> # create list of random values
>>> data_list = np.random.randn(100)
>>> # create violin fig
>>> fig = create_violin(data_list, colors='#604d9e')
>>> # plot
>>> fig.show()
Example 2: Multiple Violin Plots with Qualitative Coloring
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... sort=True, height=600, width=1000)
>>> # plot
>>> fig.show()
Example 3: Violin Plots with Colorscale
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # define header params
>>> data_header = 'Score'
>>> group_header = 'Group'
>>> # make groupby object with pandas
>>> group_stats = {}
>>> groupby_data = df.groupby([group_header])
>>> for group in "ABCDE":
... data_from_group = groupby_data.get_group(group)[data_header]
... # take a stat of the grouped data
... stat = np.median(data_from_group)
... # add to dictionary
... group_stats[group] = stat
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... height=600, width=1000, use_colorscale=True,
... group_stats=group_stats)
>>> # plot
>>> fig.show()
"""
# Validate colors
if isinstance(colors, dict):
valid_colors = clrs.validate_colors_dict(colors, "rgb")
else:
valid_colors = clrs.validate_colors(colors, "rgb")
# validate data and choose plot type
if group_header is None:
if isinstance(data, list):
if len(data) <= 0:
raise exceptions.PlotlyError(
"If data is a list, it must be "
"nonempty and contain either "
"numbers or dictionaries."
)
if not all(isinstance(element, Number) for element in data):
raise exceptions.PlotlyError(
"If data is a list, it must " "contain only numbers."
)
if pd and isinstance(data, pd.core.frame.DataFrame):
if data_header is None:
raise exceptions.PlotlyError(
"data_header must be the "
"column name with the "
"desired numeric data for "
"the violin plot."
)
data = data[data_header].values.tolist()
# call the plotting functions
plot_data, plot_xrange = violinplot(
data, fillcolor=valid_colors[0], rugplot=rugplot
)
layout = graph_objs.Layout(
title=title,
autosize=False,
font=graph_objs.layout.Font(size=11),
height=height,
showlegend=False,
width=width,
xaxis=make_XAxis("", plot_xrange),
yaxis=make_YAxis(""),
hovermode="closest",
)
layout["yaxis"].update(dict(showline=False, showticklabels=False, ticks=""))
fig = graph_objs.Figure(data=plot_data, layout=layout)
return fig
else:
if not isinstance(data, pd.core.frame.DataFrame):
raise exceptions.PlotlyError(
"Error. You must use a pandas "
"DataFrame if you are using a "
"group header."
)
if data_header is None:
raise exceptions.PlotlyError(
"data_header must be the column "
"name with the desired numeric "
"data for the violin plot."
)
if use_colorscale is False:
if isinstance(valid_colors, dict):
# validate colors dict choice below
fig = violin_dict(
data,
data_header,
group_header,
valid_colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
)
return fig
else:
fig = violin_no_colorscale(
data,
data_header,
group_header,
valid_colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
)
return fig
else:
if isinstance(valid_colors, dict):
raise exceptions.PlotlyError(
"The colors param cannot be "
"a dictionary if you are "
"using a colorscale."
)
if len(valid_colors) < 2:
raise exceptions.PlotlyError(
"colors must be a list with "
"at least 2 colors. A "
"Plotly scale is allowed."
)
if not isinstance(group_stats, dict):
raise exceptions.PlotlyError(
"Your group_stats param " "must be a dictionary."
)
fig = violin_colorscale(
data,
data_header,
group_header,
valid_colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
)
return fig | [
"def",
"create_violin",
"(",
"data",
",",
"data_header",
"=",
"None",
",",
"group_header",
"=",
"None",
",",
"colors",
"=",
"None",
",",
"use_colorscale",
"=",
"False",
",",
"group_stats",
"=",
"None",
",",
"rugplot",
"=",
"True",
",",
"sort",
"=",
"False",
",",
"height",
"=",
"450",
",",
"width",
"=",
"600",
",",
"title",
"=",
"\"Violin and Rug Plot\"",
",",
")",
":",
"# Validate colors",
"if",
"isinstance",
"(",
"colors",
",",
"dict",
")",
":",
"valid_colors",
"=",
"clrs",
".",
"validate_colors_dict",
"(",
"colors",
",",
"\"rgb\"",
")",
"else",
":",
"valid_colors",
"=",
"clrs",
".",
"validate_colors",
"(",
"colors",
",",
"\"rgb\"",
")",
"# validate data and choose plot type",
"if",
"group_header",
"is",
"None",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"if",
"len",
"(",
"data",
")",
"<=",
"0",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"If data is a list, it must be \"",
"\"nonempty and contain either \"",
"\"numbers or dictionaries.\"",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"element",
",",
"Number",
")",
"for",
"element",
"in",
"data",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"If data is a list, it must \"",
"\"contain only numbers.\"",
")",
"if",
"pd",
"and",
"isinstance",
"(",
"data",
",",
"pd",
".",
"core",
".",
"frame",
".",
"DataFrame",
")",
":",
"if",
"data_header",
"is",
"None",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"data_header must be the \"",
"\"column name with the \"",
"\"desired numeric data for \"",
"\"the violin plot.\"",
")",
"data",
"=",
"data",
"[",
"data_header",
"]",
".",
"values",
".",
"tolist",
"(",
")",
"# call the plotting functions",
"plot_data",
",",
"plot_xrange",
"=",
"violinplot",
"(",
"data",
",",
"fillcolor",
"=",
"valid_colors",
"[",
"0",
"]",
",",
"rugplot",
"=",
"rugplot",
")",
"layout",
"=",
"graph_objs",
".",
"Layout",
"(",
"title",
"=",
"title",
",",
"autosize",
"=",
"False",
",",
"font",
"=",
"graph_objs",
".",
"layout",
".",
"Font",
"(",
"size",
"=",
"11",
")",
",",
"height",
"=",
"height",
",",
"showlegend",
"=",
"False",
",",
"width",
"=",
"width",
",",
"xaxis",
"=",
"make_XAxis",
"(",
"\"\"",
",",
"plot_xrange",
")",
",",
"yaxis",
"=",
"make_YAxis",
"(",
"\"\"",
")",
",",
"hovermode",
"=",
"\"closest\"",
",",
")",
"layout",
"[",
"\"yaxis\"",
"]",
".",
"update",
"(",
"dict",
"(",
"showline",
"=",
"False",
",",
"showticklabels",
"=",
"False",
",",
"ticks",
"=",
"\"\"",
")",
")",
"fig",
"=",
"graph_objs",
".",
"Figure",
"(",
"data",
"=",
"plot_data",
",",
"layout",
"=",
"layout",
")",
"return",
"fig",
"else",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"pd",
".",
"core",
".",
"frame",
".",
"DataFrame",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Error. You must use a pandas \"",
"\"DataFrame if you are using a \"",
"\"group header.\"",
")",
"if",
"data_header",
"is",
"None",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"data_header must be the column \"",
"\"name with the desired numeric \"",
"\"data for the violin plot.\"",
")",
"if",
"use_colorscale",
"is",
"False",
":",
"if",
"isinstance",
"(",
"valid_colors",
",",
"dict",
")",
":",
"# validate colors dict choice below",
"fig",
"=",
"violin_dict",
"(",
"data",
",",
"data_header",
",",
"group_header",
",",
"valid_colors",
",",
"use_colorscale",
",",
"group_stats",
",",
"rugplot",
",",
"sort",
",",
"height",
",",
"width",
",",
"title",
",",
")",
"return",
"fig",
"else",
":",
"fig",
"=",
"violin_no_colorscale",
"(",
"data",
",",
"data_header",
",",
"group_header",
",",
"valid_colors",
",",
"use_colorscale",
",",
"group_stats",
",",
"rugplot",
",",
"sort",
",",
"height",
",",
"width",
",",
"title",
",",
")",
"return",
"fig",
"else",
":",
"if",
"isinstance",
"(",
"valid_colors",
",",
"dict",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"The colors param cannot be \"",
"\"a dictionary if you are \"",
"\"using a colorscale.\"",
")",
"if",
"len",
"(",
"valid_colors",
")",
"<",
"2",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"colors must be a list with \"",
"\"at least 2 colors. A \"",
"\"Plotly scale is allowed.\"",
")",
"if",
"not",
"isinstance",
"(",
"group_stats",
",",
"dict",
")",
":",
"raise",
"exceptions",
".",
"PlotlyError",
"(",
"\"Your group_stats param \"",
"\"must be a dictionary.\"",
")",
"fig",
"=",
"violin_colorscale",
"(",
"data",
",",
"data_header",
",",
"group_header",
",",
"valid_colors",
",",
"use_colorscale",
",",
"group_stats",
",",
"rugplot",
",",
"sort",
",",
"height",
",",
"width",
",",
"title",
",",
")",
"return",
"fig"
] | [
439,
0
] | [
711,
22
] | python | en | ['en', 'error', 'th'] | False |
Font.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
64,
28
] | python | en | ['en', 'error', 'th'] | False |
Font.colorsrc | (self) |
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"] | [
"def",
"colorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorsrc\"",
"]"
] | [
73,
4
] | [
84,
31
] | python | en | ['en', 'error', 'th'] | False |
Font.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
93,
4
] | [
116,
29
] | python | en | ['en', 'error', 'th'] | False |
Font.familysrc | (self) |
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"] | [
"def",
"familysrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"familysrc\"",
"]"
] | [
125,
4
] | [
136,
32
] | python | en | ['en', 'error', 'th'] | False |
Font.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
145,
4
] | [
155,
27
] | python | en | ['en', 'error', 'th'] | False |
Font.sizesrc | (self) |
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"] | [
"def",
"sizesrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizesrc\"",
"]"
] | [
164,
4
] | [
175,
30
] | python | en | ['en', 'error', 'th'] | False |
Font.__init__ | (
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
size=None,
sizesrc=None,
**kwargs
) |
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sankey.link.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
Returns
-------
Font
|
Construct a new Font object
Sets the font used in hover labels. | def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
size=None,
sizesrc=None,
**kwargs
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sankey.link.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.sankey.link.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sankey.link.hoverlabel.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("familysrc", None)
_v = familysrc if familysrc is not None else _v
if _v is not None:
self["familysrc"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"colorsrc",
"=",
"None",
",",
"family",
"=",
"None",
",",
"familysrc",
"=",
"None",
",",
"size",
"=",
"None",
",",
"sizesrc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Font",
",",
"self",
")",
".",
"__init__",
"(",
"\"font\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.sankey.link.hoverlabel.Font \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.sankey.link.hoverlabel.Font`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"colorsrc\"",
",",
"None",
")",
"_v",
"=",
"colorsrc",
"if",
"colorsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"colorsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"familysrc\"",
",",
"None",
")",
"_v",
"=",
"familysrc",
"if",
"familysrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"familysrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizesrc\"",
",",
"None",
")",
"_v",
"=",
"sizesrc",
"if",
"sizesrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizesrc\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
215,
4
] | [
329,
34
] | python | en | ['en', 'error', 'th'] | False |
CredentialOfferHandler.handle | (self, context: RequestContext, responder: BaseResponder) |
Message handler logic for credential offers.
Args:
context: request context
responder: responder callback
|
Message handler logic for credential offers. | async def handle(self, context: RequestContext, responder: BaseResponder):
"""
Message handler logic for credential offers.
Args:
context: request context
responder: responder callback
"""
self._logger.debug("CredentialOfferHandler called with context %s", context)
assert isinstance(context.message, CredentialOffer)
self._logger.info(
"Received credential offer message: %s",
context.message.serialize(as_string=True),
)
if not context.connection_ready:
raise HandlerException("No connection established for credential offer")
credential_manager = CredentialManager(context)
credential_exchange_record = await credential_manager.receive_offer()
# If auto respond is turned on, automatically reply with credential request
if context.settings.get("debug.auto_respond_credential_offer"):
(_, credential_request_message) = await credential_manager.create_request(
credential_exchange_record=credential_exchange_record,
holder_did=context.connection_record.my_did,
)
await responder.send_reply(credential_request_message) | [
"async",
"def",
"handle",
"(",
"self",
",",
"context",
":",
"RequestContext",
",",
"responder",
":",
"BaseResponder",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"CredentialOfferHandler called with context %s\"",
",",
"context",
")",
"assert",
"isinstance",
"(",
"context",
".",
"message",
",",
"CredentialOffer",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Received credential offer message: %s\"",
",",
"context",
".",
"message",
".",
"serialize",
"(",
"as_string",
"=",
"True",
")",
",",
")",
"if",
"not",
"context",
".",
"connection_ready",
":",
"raise",
"HandlerException",
"(",
"\"No connection established for credential offer\"",
")",
"credential_manager",
"=",
"CredentialManager",
"(",
"context",
")",
"credential_exchange_record",
"=",
"await",
"credential_manager",
".",
"receive_offer",
"(",
")",
"# If auto respond is turned on, automatically reply with credential request",
"if",
"context",
".",
"settings",
".",
"get",
"(",
"\"debug.auto_respond_credential_offer\"",
")",
":",
"(",
"_",
",",
"credential_request_message",
")",
"=",
"await",
"credential_manager",
".",
"create_request",
"(",
"credential_exchange_record",
"=",
"credential_exchange_record",
",",
"holder_did",
"=",
"context",
".",
"connection_record",
".",
"my_did",
",",
")",
"await",
"responder",
".",
"send_reply",
"(",
"credential_request_message",
")"
] | [
16,
4
] | [
45,
66
] | python | en | ['en', 'error', 'th'] | False |
init_weight | (module) | Recursively apply weight initialization | Recursively apply weight initialization | def init_weight(module):
"""Recursively apply weight initialization"""
if isinstance(module, nn.Linear):
init_linear_wt(module)
elif isinstance(module, (nn.LSTMCell, nn.LSTM, nn.GRUCell, nn.GRU)):
init_rnn_wt(module)
elif isinstance(module, nn.Embedding):
init_wt_normal(module.weight) | [
"def",
"init_weight",
"(",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"nn",
".",
"Linear",
")",
":",
"init_linear_wt",
"(",
"module",
")",
"elif",
"isinstance",
"(",
"module",
",",
"(",
"nn",
".",
"LSTMCell",
",",
"nn",
".",
"LSTM",
",",
"nn",
".",
"GRUCell",
",",
"nn",
".",
"GRU",
")",
")",
":",
"init_rnn_wt",
"(",
"module",
")",
"elif",
"isinstance",
"(",
"module",
",",
"nn",
".",
"Embedding",
")",
":",
"init_wt_normal",
"(",
"module",
".",
"weight",
")"
] | [
55,
0
] | [
62,
37
] | python | en | ['en', 'en', 'en'] | True |
Font.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
64,
28
] | python | en | ['en', 'error', 'th'] | False |
Font.colorsrc | (self) |
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for color .
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"] | [
"def",
"colorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorsrc\"",
"]"
] | [
73,
4
] | [
84,
31
] | python | en | ['en', 'error', 'th'] | False |
Font.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
93,
4
] | [
116,
29
] | python | en | ['en', 'error', 'th'] | False |
Font.familysrc | (self) |
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for family .
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"] | [
"def",
"familysrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"familysrc\"",
"]"
] | [
125,
4
] | [
136,
32
] | python | en | ['en', 'error', 'th'] | False |
Font.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
145,
4
] | [
155,
27
] | python | en | ['en', 'error', 'th'] | False |
Font.sizesrc | (self) |
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
|
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object | def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for size .
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"] | [
"def",
"sizesrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"sizesrc\"",
"]"
] | [
164,
4
] | [
175,
30
] | python | en | ['en', 'error', 'th'] | False |
Font.__init__ | (
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
size=None,
sizesrc=None,
**kwargs
) |
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
Returns
-------
Font
|
Construct a new Font object
Sets the font used in hover labels. | def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
size=None,
sizesrc=None,
**kwargs
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter3d.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
color .
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
family .
size
sizesrc
Sets the source reference on Chart Studio Cloud for
size .
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.scatter3d.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter3d.hoverlabel.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("familysrc", None)
_v = familysrc if familysrc is not None else _v
if _v is not None:
self["familysrc"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"colorsrc",
"=",
"None",
",",
"family",
"=",
"None",
",",
"familysrc",
"=",
"None",
",",
"size",
"=",
"None",
",",
"sizesrc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Font",
",",
"self",
")",
".",
"__init__",
"(",
"\"font\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.scatter3d.hoverlabel.Font \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatter3d.hoverlabel.Font`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"colorsrc\"",
",",
"None",
")",
"_v",
"=",
"colorsrc",
"if",
"colorsrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"colorsrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"familysrc\"",
",",
"None",
")",
"_v",
"=",
"familysrc",
"if",
"familysrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"familysrc\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"sizesrc\"",
",",
"None",
")",
"_v",
"=",
"sizesrc",
"if",
"sizesrc",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"sizesrc\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
215,
4
] | [
329,
34
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.color | (self) |
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
|
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen | def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color:
aliceblue, antiquewhite, aqua, aquamarine, azure,
beige, bisque, black, blanchedalmond, blue,
blueviolet, brown, burlywood, cadetblue,
chartreuse, chocolate, coral, cornflowerblue,
cornsilk, crimson, cyan, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgrey, darkgreen,
darkkhaki, darkmagenta, darkolivegreen, darkorange,
darkorchid, darkred, darksalmon, darkseagreen,
darkslateblue, darkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hotpink, indianred, indigo,
ivory, khaki, lavender, lavenderblush, lawngreen,
lemonchiffon, lightblue, lightcoral, lightcyan,
lightgoldenrodyellow, lightgray, lightgrey,
lightgreen, lightpink, lightsalmon, lightseagreen,
lightskyblue, lightslategray, lightslategrey,
lightsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mistyrose, moccasin, navajowhite, navy,
oldlace, olive, olivedrab, orange, orangered,
orchid, palegoldenrod, palegreen, paleturquoise,
palevioletred, papayawhip, peachpuff, peru, pink,
plum, powderblue, purple, red, rosybrown,
royalblue, rebeccapurple, saddlebrown, salmon,
sandybrown, seagreen, seashell, sienna, silver,
skyblue, slateblue, slategray, slategrey, snow,
springgreen, steelblue, tan, teal, thistle, tomato,
turquoise, violet, wheat, white, whitesmoke,
yellow, yellowgreen
Returns
-------
str
"""
return self["color"] | [
"def",
"color",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"color\"",
"]"
] | [
15,
4
] | [
63,
28
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.family | (self) |
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
|
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string | def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser will only be able to apply a font if
it is available on the system which it operates. Provide
multiple font families, separated by commas, to indicate the
preference in which to apply fonts if they aren't available on
the system. The Chart Studio Cloud (at https://chart-
studio.plotly.com or on-premise) generates images on a server,
where only a select number of fonts are installed and
supported. These include "Arial", "Balto", "Courier New",
"Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"] | [
"def",
"family",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"family\"",
"]"
] | [
72,
4
] | [
94,
29
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.size | (self) |
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
|
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf] | def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"] | [
"def",
"size",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"size\"",
"]"
] | [
103,
4
] | [
112,
27
] | python | en | ['en', 'error', 'th'] | False |
Tickfont.__init__ | (self, arg=None, color=None, family=None, size=None, **kwargs) |
Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.histogram2d.co
lorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Tickfont
|
Construct a new Tickfont object
Sets the color bar's tick label font | def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.histogram2d.co
lorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Tickfont
"""
super(Tickfont, self).__init__("tickfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.histogram2d.colorbar.Tickfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.histogram2d.colorbar.Tickfont`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"family",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Tickfont",
",",
"self",
")",
".",
"__init__",
"(",
"\"tickfont\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.histogram2d.colorbar.Tickfont \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.histogram2d.colorbar.Tickfont`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_v",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"color\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"family\"",
",",
"None",
")",
"_v",
"=",
"family",
"if",
"family",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"family\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"size\"",
",",
"None",
")",
"_v",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"size\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
143,
4
] | [
226,
34
] | python | en | ['en', 'error', 'th'] | False |
hash | (token, num_buckets) |
Unsigned 32 bit murmurhash for feature hashing.
|
Unsigned 32 bit murmurhash for feature hashing.
| def hash(token, num_buckets):
"""
Unsigned 32 bit murmurhash for feature hashing.
"""
return murmurhash3_32(token, positive=True) % num_buckets | [
"def",
"hash",
"(",
"token",
",",
"num_buckets",
")",
":",
"return",
"murmurhash3_32",
"(",
"token",
",",
"positive",
"=",
"True",
")",
"%",
"num_buckets"
] | [
46,
0
] | [
50,
61
] | python | en | ['en', 'error', 'th'] | False |
normalize | (text) |
Resolve different type of unicode encodings.
|
Resolve different type of unicode encodings.
| def normalize(text):
"""
Resolve different type of unicode encodings.
"""
if type(text) != str:
return text
return unicodedata.normalize('NFD', text) | [
"def",
"normalize",
"(",
"text",
")",
":",
"if",
"type",
"(",
"text",
")",
"!=",
"str",
":",
"return",
"text",
"return",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"text",
")"
] | [
224,
0
] | [
230,
45
] | python | en | ['en', 'error', 'th'] | False |
filter_word | (text) |
Take out english stopwords, punctuation, and compound endings.
|
Take out english stopwords, punctuation, and compound endings.
| def filter_word(text):
"""
Take out english stopwords, punctuation, and compound endings.
"""
text = normalize(text)
if regex.match(r'^\p{P}+$', text):
return True
if text.lower() in STOPWORDS:
return True
return False | [
"def",
"filter_word",
"(",
"text",
")",
":",
"text",
"=",
"normalize",
"(",
"text",
")",
"if",
"regex",
".",
"match",
"(",
"r'^\\p{P}+$'",
",",
"text",
")",
":",
"return",
"True",
"if",
"text",
".",
"lower",
"(",
")",
"in",
"STOPWORDS",
":",
"return",
"True",
"return",
"False"
] | [
233,
0
] | [
242,
16
] | python | en | ['en', 'error', 'th'] | False |
filter_ngram | (gram, mode='any') |
Decide whether to keep or discard an n-gram.
:param gram:
list of tokens (length N)
|
Decide whether to keep or discard an n-gram. | def filter_ngram(gram, mode='any'):
"""
Decide whether to keep or discard an n-gram.
:param gram:
list of tokens (length N)
"""
return any(filter_word(w) for w in gram) | [
"def",
"filter_ngram",
"(",
"gram",
",",
"mode",
"=",
"'any'",
")",
":",
"return",
"any",
"(",
"filter_word",
"(",
"w",
")",
"for",
"w",
"in",
"gram",
")"
] | [
245,
0
] | [
252,
44
] | python | en | ['en', 'error', 'th'] | False |
cosine_similarity | (vec1, vec2) |
Cosine similarity between two scipy sparse row matricies.
|
Cosine similarity between two scipy sparse row matricies.
| def cosine_similarity(vec1, vec2) -> float:
"""
Cosine similarity between two scipy sparse row matricies.
"""
numerator = np.dot(vec1, vec2.transpose())[0, 0]
denominator = np.linalg.norm(vec1.data) * np.linalg.norm(vec2.data)
return numerator / max(denominator, 1e-8) | [
"def",
"cosine_similarity",
"(",
"vec1",
",",
"vec2",
")",
"->",
"float",
":",
"numerator",
"=",
"np",
".",
"dot",
"(",
"vec1",
",",
"vec2",
".",
"transpose",
"(",
")",
")",
"[",
"0",
",",
"0",
"]",
"denominator",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"vec1",
".",
"data",
")",
"*",
"np",
".",
"linalg",
".",
"norm",
"(",
"vec2",
".",
"data",
")",
"return",
"numerator",
"/",
"max",
"(",
"denominator",
",",
"1e-8",
")"
] | [
255,
0
] | [
261,
45
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.__init__ | (self, hard_reset, warmup_updates, warmup_rate) |
Initialize warmup scheduler. Specific main schedulers should be initialized in
the subclasses. Do not invoke this method diretly.
:param optimizer optimizer:
Optimizer being used for training. May be wrapped in
fp16_optimizer_wrapper depending on whether fp16 is used.
:param state_dict states:
Possible state_dict provided by model checkpoint, for restoring
LR state.
:param bool hard_reset:
If true, the LR scheduler should ignore the state dictionary.
:param int warmup_updates:
Number of training step updates warmup scheduler should take.
:param float warmup_rate:
Starting multiplier for warmup scheduler.
|
Initialize warmup scheduler. Specific main schedulers should be initialized in
the subclasses. Do not invoke this method diretly. | def __init__(self, hard_reset, warmup_updates, warmup_rate):
"""
Initialize warmup scheduler. Specific main schedulers should be initialized in
the subclasses. Do not invoke this method diretly.
:param optimizer optimizer:
Optimizer being used for training. May be wrapped in
fp16_optimizer_wrapper depending on whether fp16 is used.
:param state_dict states:
Possible state_dict provided by model checkpoint, for restoring
LR state.
:param bool hard_reset:
If true, the LR scheduler should ignore the state dictionary.
:param int warmup_updates:
Number of training step updates warmup scheduler should take.
:param float warmup_rate:
Starting multiplier for warmup scheduler.
"""
self._number_training_updates = 0
self.warmup_updates = max(0, warmup_updates)
self.warmup_rate = warmup_rate
self.hard_reset = hard_reset | [
"def",
"__init__",
"(",
"self",
",",
"hard_reset",
",",
"warmup_updates",
",",
"warmup_rate",
")",
":",
"self",
".",
"_number_training_updates",
"=",
"0",
"self",
".",
"warmup_updates",
"=",
"max",
"(",
"0",
",",
"warmup_updates",
")",
"self",
".",
"warmup_rate",
"=",
"warmup_rate",
"self",
".",
"hard_reset",
"=",
"hard_reset"
] | [
34,
4
] | [
55,
36
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler._is_lr_warming_up | (self) |
Check if we're warming up the learning rate.
|
Check if we're warming up the learning rate.
| def _is_lr_warming_up(self):
"""
Check if we're warming up the learning rate.
"""
return (
hasattr(self, 'warmup_scheduler')
and self.warmup_scheduler is not None
and self._number_training_updates <= self.warmup_updates
) | [
"def",
"_is_lr_warming_up",
"(",
"self",
")",
":",
"return",
"(",
"hasattr",
"(",
"self",
",",
"'warmup_scheduler'",
")",
"and",
"self",
".",
"warmup_scheduler",
"is",
"not",
"None",
"and",
"self",
".",
"_number_training_updates",
"<=",
"self",
".",
"warmup_updates",
")"
] | [
80,
4
] | [
88,
9
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler._warmup_lr | (self, step) |
Return lr multiplier (on initial lr) for warmup scheduler.
|
Return lr multiplier (on initial lr) for warmup scheduler.
| def _warmup_lr(self, step):
"""
Return lr multiplier (on initial lr) for warmup scheduler.
"""
start = self.warmup_rate
end = 1.0
progress = min(1.0, step / self.warmup_updates)
lr_mult = start + (end - start) * progress
return lr_mult | [
"def",
"_warmup_lr",
"(",
"self",
",",
"step",
")",
":",
"start",
"=",
"self",
".",
"warmup_rate",
"end",
"=",
"1.0",
"progress",
"=",
"min",
"(",
"1.0",
",",
"step",
"/",
"self",
".",
"warmup_updates",
")",
"lr_mult",
"=",
"start",
"+",
"(",
"end",
"-",
"start",
")",
"*",
"progress",
"return",
"lr_mult"
] | [
90,
4
] | [
98,
22
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.load_state | (self, states) |
Load state of scheduler from states.
|
Load state of scheduler from states.
| def load_state(self, states):
"""
Load state of scheduler from states.
"""
if states.get('warmup_scheduler') and getattr(self, 'warmup_scheduler', None):
self.warmup_scheduler.load_state_dict(states['warmup_scheduler'])
if self.scheduler and 'lr_scheduler' in states:
self.scheduler.load_state_dict(states['lr_scheduler'])
self._number_training_updates = states.get('number_training_updates', 0)
try:
self.scheduler.get_last_lr()
except AttributeError:
# on older pytorches
self.step(self._number_training_updates) | [
"def",
"load_state",
"(",
"self",
",",
"states",
")",
":",
"if",
"states",
".",
"get",
"(",
"'warmup_scheduler'",
")",
"and",
"getattr",
"(",
"self",
",",
"'warmup_scheduler'",
",",
"None",
")",
":",
"self",
".",
"warmup_scheduler",
".",
"load_state_dict",
"(",
"states",
"[",
"'warmup_scheduler'",
"]",
")",
"if",
"self",
".",
"scheduler",
"and",
"'lr_scheduler'",
"in",
"states",
":",
"self",
".",
"scheduler",
".",
"load_state_dict",
"(",
"states",
"[",
"'lr_scheduler'",
"]",
")",
"self",
".",
"_number_training_updates",
"=",
"states",
".",
"get",
"(",
"'number_training_updates'",
",",
"0",
")",
"try",
":",
"self",
".",
"scheduler",
".",
"get_last_lr",
"(",
")",
"except",
"AttributeError",
":",
"# on older pytorches",
"self",
".",
"step",
"(",
"self",
".",
"_number_training_updates",
")"
] | [
100,
4
] | [
114,
52
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.get_state_dict | (self) |
Return scheduler state dictionary.
|
Return scheduler state dictionary.
| def get_state_dict(self):
"""
Return scheduler state dictionary.
"""
return self.scheduler.state_dict() | [
"def",
"get_state_dict",
"(",
"self",
")",
":",
"return",
"self",
".",
"scheduler",
".",
"state_dict",
"(",
")"
] | [
119,
4
] | [
123,
42
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.get_warmup_state_dict | (self) |
Return warmup scheduler state dictionary.
|
Return warmup scheduler state dictionary.
| def get_warmup_state_dict(self):
"""
Return warmup scheduler state dictionary.
"""
if self.warmup_scheduler is None:
return None
return self.warmup_scheduler.state_dict() | [
"def",
"get_warmup_state_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"warmup_scheduler",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"warmup_scheduler",
".",
"state_dict",
"(",
")"
] | [
125,
4
] | [
131,
49
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.lr_scheduler_factory | (cls, opt, optimizer, states, hard_reset=False) |
Create the learning rate scheduler, and assign it to self.scheduler. This
scheduler will be updated upon a call to receive_metrics. May also create
self.warmup_scheduler, if appropriate.
:param opt opt:
Arguments received by torch_agent
:param optimizer optimizer:
Optimizer being used for training. May be wrapped in
fp16_optimizer_wrapper depending on whether fp16 is used.
:param state_dict states:
Possible state_dict provided by model checkpoint, for restoring
LR state.
:param bool hard_reset:
If true, the LR scheduler should ignore the state dictionary.
:return: ParlAILRScheduler object
|
Create the learning rate scheduler, and assign it to self.scheduler. This
scheduler will be updated upon a call to receive_metrics. May also create
self.warmup_scheduler, if appropriate. | def lr_scheduler_factory(cls, opt, optimizer, states, hard_reset=False):
"""
Create the learning rate scheduler, and assign it to self.scheduler. This
scheduler will be updated upon a call to receive_metrics. May also create
self.warmup_scheduler, if appropriate.
:param opt opt:
Arguments received by torch_agent
:param optimizer optimizer:
Optimizer being used for training. May be wrapped in
fp16_optimizer_wrapper depending on whether fp16 is used.
:param state_dict states:
Possible state_dict provided by model checkpoint, for restoring
LR state.
:param bool hard_reset:
If true, the LR scheduler should ignore the state dictionary.
:return: ParlAILRScheduler object
"""
patience = opt.get('lr_scheduler_patience', 3)
decay = opt.get('lr_scheduler_decay', 0.5)
warmup_updates = opt.get('warmup_updates', -1)
warmup_rate = opt.get('warmup_rate', 1e-4)
max_lr_steps = opt.get('max_lr_steps', -1)
invsqrt_lr_decay_gamma = opt.get('invsqrt_lr_decay_gamma', -1)
if opt.get('lr_scheduler') == 'none':
return None
elif decay == 1.0:
warn_once(
"Your LR decay is set to 1.0. Assuming you meant you wanted "
"to disable learning rate scheduling. Adjust --lr-scheduler-decay "
"if this is not correct."
)
return None
elif opt.get('lr_scheduler') == 'reduceonplateau':
scheduler = ReduceOnPlateauLRScheduler(
optimizer, hard_reset, patience, decay, warmup_updates, warmup_rate
)
elif opt.get('lr_scheduler') == 'fixed':
scheduler = FixedLRScheduler(
optimizer, hard_reset, patience, decay, warmup_updates, warmup_rate
)
elif opt.get('lr_scheduler') == 'invsqrt':
scheduler = InvSqrtLRScheduler(
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
invsqrt_lr_decay_gamma,
max_lr_steps,
)
elif opt.get('lr_scheduler') == 'cosine':
scheduler = CosineLRScheduler(
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
max_lr_steps,
)
elif opt.get('lr_scheduler') == 'linear':
scheduler = LinearLRScheduler(
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
max_lr_steps,
)
else:
raise ValueError(
"Don't know what to do with --lr-scheduler '{}'".format(
opt.get('lr_scheduler')
)
)
# time to load LR state from the checkpoint, if possible.
if (
# there is already an old LR scheduler saved on disk
states
# and there was a scheduler in the dump
and 'lr_scheduler_type' in states
# and the old LR scheduler is different
and states.get('lr_scheduler_type') != opt['lr_scheduler']
# and we're not already using a fresh scheduler
and not hard_reset
):
# the LR scheduler changed, start things fresh
warn_once(
f"LR scheduler ({opt['lr_scheduler']}) is different from saved "
f"({states.get('lr_scheduler_type')}). Starting fresh!"
)
hard_reset = True
if not hard_reset:
# do the actual loading (if possible)
scheduler.load_state(states)
# setup warmup scheduler after loading saved scheduler
scheduler._init_warmup_scheduler(optimizer, states)
return scheduler | [
"def",
"lr_scheduler_factory",
"(",
"cls",
",",
"opt",
",",
"optimizer",
",",
"states",
",",
"hard_reset",
"=",
"False",
")",
":",
"patience",
"=",
"opt",
".",
"get",
"(",
"'lr_scheduler_patience'",
",",
"3",
")",
"decay",
"=",
"opt",
".",
"get",
"(",
"'lr_scheduler_decay'",
",",
"0.5",
")",
"warmup_updates",
"=",
"opt",
".",
"get",
"(",
"'warmup_updates'",
",",
"-",
"1",
")",
"warmup_rate",
"=",
"opt",
".",
"get",
"(",
"'warmup_rate'",
",",
"1e-4",
")",
"max_lr_steps",
"=",
"opt",
".",
"get",
"(",
"'max_lr_steps'",
",",
"-",
"1",
")",
"invsqrt_lr_decay_gamma",
"=",
"opt",
".",
"get",
"(",
"'invsqrt_lr_decay_gamma'",
",",
"-",
"1",
")",
"if",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
"==",
"'none'",
":",
"return",
"None",
"elif",
"decay",
"==",
"1.0",
":",
"warn_once",
"(",
"\"Your LR decay is set to 1.0. Assuming you meant you wanted \"",
"\"to disable learning rate scheduling. Adjust --lr-scheduler-decay \"",
"\"if this is not correct.\"",
")",
"return",
"None",
"elif",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
"==",
"'reduceonplateau'",
":",
"scheduler",
"=",
"ReduceOnPlateauLRScheduler",
"(",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
")",
"elif",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
"==",
"'fixed'",
":",
"scheduler",
"=",
"FixedLRScheduler",
"(",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
")",
"elif",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
"==",
"'invsqrt'",
":",
"scheduler",
"=",
"InvSqrtLRScheduler",
"(",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
",",
"invsqrt_lr_decay_gamma",
",",
"max_lr_steps",
",",
")",
"elif",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
"==",
"'cosine'",
":",
"scheduler",
"=",
"CosineLRScheduler",
"(",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
",",
"max_lr_steps",
",",
")",
"elif",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
"==",
"'linear'",
":",
"scheduler",
"=",
"LinearLRScheduler",
"(",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
",",
"max_lr_steps",
",",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Don't know what to do with --lr-scheduler '{}'\"",
".",
"format",
"(",
"opt",
".",
"get",
"(",
"'lr_scheduler'",
")",
")",
")",
"# time to load LR state from the checkpoint, if possible.",
"if",
"(",
"# there is already an old LR scheduler saved on disk",
"states",
"# and there was a scheduler in the dump",
"and",
"'lr_scheduler_type'",
"in",
"states",
"# and the old LR scheduler is different",
"and",
"states",
".",
"get",
"(",
"'lr_scheduler_type'",
")",
"!=",
"opt",
"[",
"'lr_scheduler'",
"]",
"# and we're not already using a fresh scheduler",
"and",
"not",
"hard_reset",
")",
":",
"# the LR scheduler changed, start things fresh",
"warn_once",
"(",
"f\"LR scheduler ({opt['lr_scheduler']}) is different from saved \"",
"f\"({states.get('lr_scheduler_type')}). Starting fresh!\"",
")",
"hard_reset",
"=",
"True",
"if",
"not",
"hard_reset",
":",
"# do the actual loading (if possible)",
"scheduler",
".",
"load_state",
"(",
"states",
")",
"# setup warmup scheduler after loading saved scheduler",
"scheduler",
".",
"_init_warmup_scheduler",
"(",
"optimizer",
",",
"states",
")",
"return",
"scheduler"
] | [
201,
4
] | [
307,
24
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.step | (self, num_steps) |
Use the number of train steps to adjust the warmup scheduler or the main
scheduler, depending on where in training we are.
Override this method to override the behavior for training schedulers.
|
Use the number of train steps to adjust the warmup scheduler or the main
scheduler, depending on where in training we are. | def step(self, num_steps):
"""
Use the number of train steps to adjust the warmup scheduler or the main
scheduler, depending on where in training we are.
Override this method to override the behavior for training schedulers.
"""
self._number_training_updates = num_steps
if self._is_lr_warming_up():
self.warmup_scheduler.step()
else:
scheduler_steps = num_steps - self.warmup_updates
self.train_step(scheduler_steps) | [
"def",
"step",
"(",
"self",
",",
"num_steps",
")",
":",
"self",
".",
"_number_training_updates",
"=",
"num_steps",
"if",
"self",
".",
"_is_lr_warming_up",
"(",
")",
":",
"self",
".",
"warmup_scheduler",
".",
"step",
"(",
")",
"else",
":",
"scheduler_steps",
"=",
"num_steps",
"-",
"self",
".",
"warmup_updates",
"self",
".",
"train_step",
"(",
"scheduler_steps",
")"
] | [
309,
4
] | [
321,
44
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.train_step | (self, scheduler_steps) |
Use the number of train steps to decide when to adjust LR schedule.
Override this method to override the behavior for training schedulers.
|
Use the number of train steps to decide when to adjust LR schedule. | def train_step(self, scheduler_steps):
"""
Use the number of train steps to decide when to adjust LR schedule.
Override this method to override the behavior for training schedulers.
"""
pass | [
"def",
"train_step",
"(",
"self",
",",
"scheduler_steps",
")",
":",
"pass"
] | [
324,
4
] | [
330,
12
] | python | en | ['en', 'error', 'th'] | False |
ParlAILRScheduler.valid_step | (self, metrics_dict) |
Use the metrics to decide when to adjust LR schedule.
This uses the loss as the validation metric if present, if not this
function does nothing. Note that the model must be reporting loss for
this to work.
Override this method to override the behavior for validation schedulers.
|
Use the metrics to decide when to adjust LR schedule. | def valid_step(self, metrics_dict):
"""
Use the metrics to decide when to adjust LR schedule.
This uses the loss as the validation metric if present, if not this
function does nothing. Note that the model must be reporting loss for
this to work.
Override this method to override the behavior for validation schedulers.
"""
pass | [
"def",
"valid_step",
"(",
"self",
",",
"metrics_dict",
")",
":",
"pass"
] | [
333,
4
] | [
343,
12
] | python | en | ['en', 'error', 'th'] | False |
InvSqrtLRScheduler.__init__ | (
self,
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
invsqrt_lr_decay_gamma,
max_lr_steps,
) |
invsqrt_lr_decay_gamma determines the cycle length of the inverse square root
scheduler.
When steps taken == invsqrt_lr_decay_gamma, the lr multiplier is 1
|
invsqrt_lr_decay_gamma determines the cycle length of the inverse square root
scheduler. | def __init__(
self,
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
invsqrt_lr_decay_gamma,
max_lr_steps,
):
"""
invsqrt_lr_decay_gamma determines the cycle length of the inverse square root
scheduler.
When steps taken == invsqrt_lr_decay_gamma, the lr multiplier is 1
"""
super().__init__(hard_reset, warmup_updates, warmup_rate)
self.max_lr_steps = max_lr_steps
self.invsqrt_lr_decay_gamma = invsqrt_lr_decay_gamma
if invsqrt_lr_decay_gamma <= 0:
warn_once(
'--lr-scheduler invsqrt requires a value for '
'--invsqrt-lr-decay-gamma. Defaulting to set gamma to '
'--warmup-updates value for backwards compatibility.'
)
self.invsqrt_lr_decay_gamma = self.warmup_updates
self.decay_factor = np.sqrt(max(1, self.invsqrt_lr_decay_gamma))
self.scheduler = optim.lr_scheduler.LambdaLR(optimizer, self._invsqrt_lr) | [
"def",
"__init__",
"(",
"self",
",",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
",",
"invsqrt_lr_decay_gamma",
",",
"max_lr_steps",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"hard_reset",
",",
"warmup_updates",
",",
"warmup_rate",
")",
"self",
".",
"max_lr_steps",
"=",
"max_lr_steps",
"self",
".",
"invsqrt_lr_decay_gamma",
"=",
"invsqrt_lr_decay_gamma",
"if",
"invsqrt_lr_decay_gamma",
"<=",
"0",
":",
"warn_once",
"(",
"'--lr-scheduler invsqrt requires a value for '",
"'--invsqrt-lr-decay-gamma. Defaulting to set gamma to '",
"'--warmup-updates value for backwards compatibility.'",
")",
"self",
".",
"invsqrt_lr_decay_gamma",
"=",
"self",
".",
"warmup_updates",
"self",
".",
"decay_factor",
"=",
"np",
".",
"sqrt",
"(",
"max",
"(",
"1",
",",
"self",
".",
"invsqrt_lr_decay_gamma",
")",
")",
"self",
".",
"scheduler",
"=",
"optim",
".",
"lr_scheduler",
".",
"LambdaLR",
"(",
"optimizer",
",",
"self",
".",
"_invsqrt_lr",
")"
] | [
401,
4
] | [
430,
81
] | python | en | ['en', 'error', 'th'] | False |
CosineLRScheduler.__init__ | (
self,
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
max_lr_steps,
) |
max_lr_steps determines the cycle length of the cosine annealing.
It indicates the number of steps from 1.0 multiplier to 0.0, which corresponds
to going from cos(0) to cos(pi)
|
max_lr_steps determines the cycle length of the cosine annealing. | def __init__(
self,
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
max_lr_steps,
):
"""
max_lr_steps determines the cycle length of the cosine annealing.
It indicates the number of steps from 1.0 multiplier to 0.0, which corresponds
to going from cos(0) to cos(pi)
"""
super().__init__(hard_reset, warmup_updates, warmup_rate)
if max_lr_steps <= 0:
raise ValueError('--lr-scheduler cosine requires setting --max-lr-steps')
self.max_lr_steps = max_lr_steps
self.scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, max_lr_steps) | [
"def",
"__init__",
"(",
"self",
",",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
",",
"max_lr_steps",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"hard_reset",
",",
"warmup_updates",
",",
"warmup_rate",
")",
"if",
"max_lr_steps",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'--lr-scheduler cosine requires setting --max-lr-steps'",
")",
"self",
".",
"max_lr_steps",
"=",
"max_lr_steps",
"self",
".",
"scheduler",
"=",
"optim",
".",
"lr_scheduler",
".",
"CosineAnnealingLR",
"(",
"optimizer",
",",
"max_lr_steps",
")"
] | [
450,
4
] | [
470,
86
] | python | en | ['en', 'error', 'th'] | False |
LinearLRScheduler.__init__ | (
self,
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
max_lr_steps,
) |
max_lr_steps determines the cycle length of the linear annealing.
It indicates the number of steps from 1.0 multiplier to 0.0
|
max_lr_steps determines the cycle length of the linear annealing. | def __init__(
self,
optimizer,
hard_reset,
patience,
decay,
warmup_updates,
warmup_rate,
max_lr_steps,
):
"""
max_lr_steps determines the cycle length of the linear annealing.
It indicates the number of steps from 1.0 multiplier to 0.0
"""
super().__init__(hard_reset, warmup_updates, warmup_rate)
if max_lr_steps <= 0:
raise ValueError('--lr-scheduler linear requires setting --max-lr-steps')
self.max_lr_steps = max_lr_steps
self.scheduler = optim.lr_scheduler.LambdaLR(optimizer, self._linear_lr) | [
"def",
"__init__",
"(",
"self",
",",
"optimizer",
",",
"hard_reset",
",",
"patience",
",",
"decay",
",",
"warmup_updates",
",",
"warmup_rate",
",",
"max_lr_steps",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"hard_reset",
",",
"warmup_updates",
",",
"warmup_rate",
")",
"if",
"max_lr_steps",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'--lr-scheduler linear requires setting --max-lr-steps'",
")",
"self",
".",
"max_lr_steps",
"=",
"max_lr_steps",
"self",
".",
"scheduler",
"=",
"optim",
".",
"lr_scheduler",
".",
"LambdaLR",
"(",
"optimizer",
",",
"self",
".",
"_linear_lr",
")"
] | [
486,
4
] | [
505,
80
] | python | en | ['en', 'error', 'th'] | False |
X.fill | (self) |
Sets the fill ratio of the `caps`. The default fill value of
the `caps` is 1 meaning that they are entirely shaded. On the
other hand Applying a `fill` ratio less than one would allow
the creation of openings parallel to the edges.
The 'fill' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
|
Sets the fill ratio of the `caps`. The default fill value of
the `caps` is 1 meaning that they are entirely shaded. On the
other hand Applying a `fill` ratio less than one would allow
the creation of openings parallel to the edges.
The 'fill' property is a number and may be specified as:
- An int or float in the interval [0, 1] | def fill(self):
"""
Sets the fill ratio of the `caps`. The default fill value of
the `caps` is 1 meaning that they are entirely shaded. On the
other hand Applying a `fill` ratio less than one would allow
the creation of openings parallel to the edges.
The 'fill' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["fill"] | [
"def",
"fill",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"fill\"",
"]"
] | [
15,
4
] | [
29,
27
] | python | en | ['en', 'error', 'th'] | False |
X.show | (self) |
Sets the fill ratio of the `slices`. The default fill value of
the x `slices` is 1 meaning that they are entirely shaded. On
the other hand Applying a `fill` ratio less than one would
allow the creation of openings parallel to the edges.
The 'show' property must be specified as a bool
(either True, or False)
Returns
-------
bool
|
Sets the fill ratio of the `slices`. The default fill value of
the x `slices` is 1 meaning that they are entirely shaded. On
the other hand Applying a `fill` ratio less than one would
allow the creation of openings parallel to the edges.
The 'show' property must be specified as a bool
(either True, or False) | def show(self):
"""
Sets the fill ratio of the `slices`. The default fill value of
the x `slices` is 1 meaning that they are entirely shaded. On
the other hand Applying a `fill` ratio less than one would
allow the creation of openings parallel to the edges.
The 'show' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["show"] | [
"def",
"show",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"show\"",
"]"
] | [
38,
4
] | [
52,
27
] | python | en | ['en', 'error', 'th'] | False |
X.__init__ | (self, arg=None, fill=None, show=None, **kwargs) |
Construct a new X object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.isosurface.caps.X`
fill
Sets the fill ratio of the `caps`. The default fill
value of the `caps` is 1 meaning that they are entirely
shaded. On the other hand Applying a `fill` ratio less
than one would allow the creation of openings parallel
to the edges.
show
Sets the fill ratio of the `slices`. The default fill
value of the x `slices` is 1 meaning that they are
entirely shaded. On the other hand Applying a `fill`
ratio less than one would allow the creation of
openings parallel to the edges.
Returns
-------
X
|
Construct a new X object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.isosurface.caps.X`
fill
Sets the fill ratio of the `caps`. The default fill
value of the `caps` is 1 meaning that they are entirely
shaded. On the other hand Applying a `fill` ratio less
than one would allow the creation of openings parallel
to the edges.
show
Sets the fill ratio of the `slices`. The default fill
value of the x `slices` is 1 meaning that they are
entirely shaded. On the other hand Applying a `fill`
ratio less than one would allow the creation of
openings parallel to the edges. | def __init__(self, arg=None, fill=None, show=None, **kwargs):
"""
Construct a new X object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.isosurface.caps.X`
fill
Sets the fill ratio of the `caps`. The default fill
value of the `caps` is 1 meaning that they are entirely
shaded. On the other hand Applying a `fill` ratio less
than one would allow the creation of openings parallel
to the edges.
show
Sets the fill ratio of the `slices`. The default fill
value of the x `slices` is 1 meaning that they are
entirely shaded. On the other hand Applying a `fill`
ratio less than one would allow the creation of
openings parallel to the edges.
Returns
-------
X
"""
super(X, self).__init__("x")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.isosurface.caps.X
constructor must be a dict or
an instance of :class:`plotly.graph_objs.isosurface.caps.X`"""
)
# 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("fill", None)
_v = fill if fill is not None else _v
if _v is not None:
self["fill"] = _v
_v = arg.pop("show", None)
_v = show if show is not None else _v
if _v is not None:
self["show"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"fill",
"=",
"None",
",",
"show",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"X",
",",
"self",
")",
".",
"__init__",
"(",
"\"x\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.isosurface.caps.X \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.isosurface.caps.X`\"\"\"",
")",
"# 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",
"(",
"\"fill\"",
",",
"None",
")",
"_v",
"=",
"fill",
"if",
"fill",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"fill\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"show\"",
",",
"None",
")",
"_v",
"=",
"show",
"if",
"show",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"show\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] | [
77,
4
] | [
148,
34
] | python | en | ['en', 'error', 'th'] | False |
_to_ansi | (obj) |
convert to ANSIString.
Args:
obj (str): Convert incoming text to
be ANSI aware ANSIStrings.
|
convert to ANSIString. | def _to_ansi(obj):
"""
convert to ANSIString.
Args:
obj (str): Convert incoming text to
be ANSI aware ANSIStrings.
"""
if hasattr(obj, "__iter__"):
return [_to_ansi(o) for o in obj]
else:
return ANSIString(to_unicode(obj)) | [
"def",
"_to_ansi",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"__iter__\"",
")",
":",
"return",
"[",
"_to_ansi",
"(",
"o",
")",
"for",
"o",
"in",
"obj",
"]",
"else",
":",
"return",
"ANSIString",
"(",
"to_unicode",
"(",
"obj",
")",
")"
] | [
129,
0
] | [
140,
42
] | python | en | ['en', 'error', 'th'] | False |
wrap | (text, width=_DEFAULT_WIDTH, **kwargs) |
Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
Args:
text (str): Text to wrap.
width (int, optional): Width to wrap `text` to.
Kwargs:
See TextWrapper class for available keyword args to customize
wrapping behaviour.
|
Wrap a single paragraph of text, returning a list of wrapped lines. | def wrap(text, width=_DEFAULT_WIDTH, **kwargs):
"""
Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
Args:
text (str): Text to wrap.
width (int, optional): Width to wrap `text` to.
Kwargs:
See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
w = ANSITextWrapper(width=width, **kwargs)
return w.wrap(text) | [
"def",
"wrap",
"(",
"text",
",",
"width",
"=",
"_DEFAULT_WIDTH",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"ANSITextWrapper",
"(",
"width",
"=",
"width",
",",
"*",
"*",
"kwargs",
")",
"return",
"w",
".",
"wrap",
"(",
"text",
")"
] | [
272,
0
] | [
291,
23
] | python | en | ['en', 'error', 'th'] | False |
fill | (text, width=_DEFAULT_WIDTH, **kwargs) | Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space.
Args:
text (str): Text to fill.
width (int, optional): Width of fill area.
Kwargs:
See TextWrapper class for available keyword args to customize
filling behaviour.
| Fill a single paragraph of text, returning a new string. | def fill(text, width=_DEFAULT_WIDTH, **kwargs):
"""Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space.
Args:
text (str): Text to fill.
width (int, optional): Width of fill area.
Kwargs:
See TextWrapper class for available keyword args to customize
filling behaviour.
"""
w = ANSITextWrapper(width=width, **kwargs)
return w.fill(text) | [
"def",
"fill",
"(",
"text",
",",
"width",
"=",
"_DEFAULT_WIDTH",
",",
"*",
"*",
"kwargs",
")",
":",
"w",
"=",
"ANSITextWrapper",
"(",
"width",
"=",
"width",
",",
"*",
"*",
"kwargs",
")",
"return",
"w",
".",
"fill",
"(",
"text",
")"
] | [
294,
0
] | [
312,
23
] | python | en | ['en', 'en', 'en'] | True |
ANSITextWrapper._munge_whitespace | (self, text) | _munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
becomes " foo bar baz".
| _munge_whitespace(text : string) -> string | def _munge_whitespace(self, text):
"""_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\tbar\n\nbaz"
becomes " foo bar baz".
"""
return text | [
"def",
"_munge_whitespace",
"(",
"self",
",",
"text",
")",
":",
"return",
"text"
] | [
155,
4
] | [
162,
19
] | python | de | ['de', 'jv', 'ur'] | False |
ANSITextWrapper._split | (self, text) | _split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the following chunks:
'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', 'option!'
if break_on_hyphens is True, or in:
'Look,', ' ', 'goof-ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', option!'
otherwise.
| _split(text : string) -> [string] | def _split(self, text):
"""_split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the following chunks:
'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', 'option!'
if break_on_hyphens is True, or in:
'Look,', ' ', 'goof-ball', ' ', '--', ' ',
'use', ' ', 'the', ' ', '-b', ' ', option!'
otherwise.
"""
# only use unicode wrapper
if self.break_on_hyphens:
pat = self.wordsep_re_uni
else:
pat = self.wordsep_simple_re_uni
chunks = pat.split(_to_ansi(text))
return [chunk for chunk in chunks if chunk] | [
"def",
"_split",
"(",
"self",
",",
"text",
")",
":",
"# only use unicode wrapper",
"if",
"self",
".",
"break_on_hyphens",
":",
"pat",
"=",
"self",
".",
"wordsep_re_uni",
"else",
":",
"pat",
"=",
"self",
".",
"wordsep_simple_re_uni",
"chunks",
"=",
"pat",
".",
"split",
"(",
"_to_ansi",
"(",
"text",
")",
")",
"return",
"[",
"chunk",
"for",
"chunk",
"in",
"chunks",
"if",
"chunk",
"]"
] | [
174,
4
] | [
195,
51
] | python | en | ['en', 'kk', 'en'] | True |
ANSITextWrapper._wrap_chunks | (self, chunks) | _wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and the whitespace between them: each chunk is
indivisible (modulo 'break_long_words'), but a line break can
come between any two chunks. Chunks should not have internal
whitespace; ie. a chunk is either all whitespace or a "word".
Whitespace chunks will be removed from the beginning and end of
lines, but apart from that whitespace is preserved.
| _wrap_chunks(chunks : [string]) -> [string] | def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and the whitespace between them: each chunk is
indivisible (modulo 'break_long_words'), but a line break can
come between any two chunks. Chunks should not have internal
whitespace; ie. a chunk is either all whitespace or a "word".
Whitespace chunks will be removed from the beginning and end of
lines, but apart from that whitespace is preserved.
"""
lines = []
if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width)
# Arrange in reverse order so items can be efficiently popped
# from a stack of chucks.
chunks.reverse()
while chunks:
# Start the list of chunks that will make up the current line.
# cur_len is just the length of all the chunks in cur_line.
cur_line = []
cur_len = 0
# Figure out which static string will prefix this line.
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
# Maximum width for this line.
width = self.width - m_len(indent)
# First chunk on line is whitespace -- drop it, unless this
# is the very beginning of the text (ie. no lines started yet).
if self.drop_whitespace and chunks[-1].strip() == '' and lines:
del chunks[-1]
while chunks:
l = m_len(chunks[-1])
# Can at least squeeze this chunk onto the current line.
if cur_len + l <= width:
cur_line.append(chunks.pop())
cur_len += l
# Nope, this line is full.
else:
break
# The current line is full, and the next chunk is too big to
# fit on *any* line (not just this one).
if chunks and m_len(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width)
# If the last chunk on this line is all whitespace, drop it.
if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
del cur_line[-1]
# Convert current line back to a string and store it in list
# of all lines (return value).
if cur_line:
l = ""
for w in cur_line: # ANSI fix
l += w #
lines.append(indent + l)
return lines | [
"def",
"_wrap_chunks",
"(",
"self",
",",
"chunks",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"self",
".",
"width",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"invalid width %r (must be > 0)\"",
"%",
"self",
".",
"width",
")",
"# Arrange in reverse order so items can be efficiently popped",
"# from a stack of chucks.",
"chunks",
".",
"reverse",
"(",
")",
"while",
"chunks",
":",
"# Start the list of chunks that will make up the current line.",
"# cur_len is just the length of all the chunks in cur_line.",
"cur_line",
"=",
"[",
"]",
"cur_len",
"=",
"0",
"# Figure out which static string will prefix this line.",
"if",
"lines",
":",
"indent",
"=",
"self",
".",
"subsequent_indent",
"else",
":",
"indent",
"=",
"self",
".",
"initial_indent",
"# Maximum width for this line.",
"width",
"=",
"self",
".",
"width",
"-",
"m_len",
"(",
"indent",
")",
"# First chunk on line is whitespace -- drop it, unless this",
"# is the very beginning of the text (ie. no lines started yet).",
"if",
"self",
".",
"drop_whitespace",
"and",
"chunks",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"==",
"''",
"and",
"lines",
":",
"del",
"chunks",
"[",
"-",
"1",
"]",
"while",
"chunks",
":",
"l",
"=",
"m_len",
"(",
"chunks",
"[",
"-",
"1",
"]",
")",
"# Can at least squeeze this chunk onto the current line.",
"if",
"cur_len",
"+",
"l",
"<=",
"width",
":",
"cur_line",
".",
"append",
"(",
"chunks",
".",
"pop",
"(",
")",
")",
"cur_len",
"+=",
"l",
"# Nope, this line is full.",
"else",
":",
"break",
"# The current line is full, and the next chunk is too big to",
"# fit on *any* line (not just this one).",
"if",
"chunks",
"and",
"m_len",
"(",
"chunks",
"[",
"-",
"1",
"]",
")",
">",
"width",
":",
"self",
".",
"_handle_long_word",
"(",
"chunks",
",",
"cur_line",
",",
"cur_len",
",",
"width",
")",
"# If the last chunk on this line is all whitespace, drop it.",
"if",
"self",
".",
"drop_whitespace",
"and",
"cur_line",
"and",
"cur_line",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"==",
"''",
":",
"del",
"cur_line",
"[",
"-",
"1",
"]",
"# Convert current line back to a string and store it in list",
"# of all lines (return value).",
"if",
"cur_line",
":",
"l",
"=",
"\"\"",
"for",
"w",
"in",
"cur_line",
":",
"# ANSI fix",
"l",
"+=",
"w",
"#",
"lines",
".",
"append",
"(",
"indent",
"+",
"l",
")",
"return",
"lines"
] | [
197,
4
] | [
267,
20
] | python | en | ['en', 'hi-Latn', 'sw'] | False |
EvCell.__init__ | (self, data, **kwargs) |
Args:
data (str): The un-padded data of the entry.
Kwargs:
width (int): Desired width of cell. It will pad
to this size.
height (int): Desired height of cell. it will pad
to this size.
pad_width (int): General padding width. This can be overruled
by individual settings below.
pad_left (int): Number of extra pad characters on the left.
pad_right (int): Number of extra pad characters on the right.
pad_top (int): Number of extra pad lines top (will pad with `vpad_char`).
pad_bottom (int): Number of extra pad lines bottom (will pad with `vpad_char`).
pad_char (str)- pad character to use for padding. This is overruled
by individual settings below (default `" "`).
hpad_char (str): Pad character to use both for extra horizontal
padding (default `" "`).
vpad_char (str): Pad character to use for extra vertical padding
and for vertical fill (default `" "`).
fill_char (str): Character used to filling (expanding cells to
desired size). This can be overruled by individual settings below.
hfill_char (str): Character used for horizontal fill (default `" "`).
vfill_char (str): Character used for vertical fill (default `" "`).
align (str): Should be one of "l", "r" or "c" for left-, right- or center
horizontal alignment respectively. Default is left-aligned.
valign (str): Should be one of "t", "b" or "c" for top-, bottom and center
vertical alignment respectively. Default is centered.
border_width (int): General border width. This is overruled
by individual settings below.
border_left (int): Left border width.
border_right (int): Right border width.
border_top (int): Top border width.
border_bottom (int): Bottom border width.
border_char (str): This will use a single border char for all borders.
overruled by individual settings below.
border_left_char (str): Char used for left border.
border_right_char (str): Char used for right border.
border_top_char (str): Char used for top border.
border_bottom_char (str): Char user for bottom border.
corner_char (str): Character used when two borders cross. (default is "").
This is overruled by individual settings below.
corner_top_left_char (str): Char used for "nw" corner.
corner_top_right_char (str): Char used for "ne" corner.
corner_bottom_left_char (str): Char used for "sw" corner.
corner_bottom_right_char (str): Char used for "se" corner.
crop_string (str): String to use when cropping sideways, default is `'[...]'`.
crop (bool): Crop contentof cell rather than expand vertically, default=`False`.
enforce_size (bool): If true, the width/height of the cell is
strictly enforced and extra text will be cropped rather than the
cell growing vertically.
Raises:
Exception: for impossible cell size requirements where the
border width or height cannot fit, or the content is too
small.
|
Args:
data (str): The un-padded data of the entry. | def __init__(self, data, **kwargs):
"""
Args:
data (str): The un-padded data of the entry.
Kwargs:
width (int): Desired width of cell. It will pad
to this size.
height (int): Desired height of cell. it will pad
to this size.
pad_width (int): General padding width. This can be overruled
by individual settings below.
pad_left (int): Number of extra pad characters on the left.
pad_right (int): Number of extra pad characters on the right.
pad_top (int): Number of extra pad lines top (will pad with `vpad_char`).
pad_bottom (int): Number of extra pad lines bottom (will pad with `vpad_char`).
pad_char (str)- pad character to use for padding. This is overruled
by individual settings below (default `" "`).
hpad_char (str): Pad character to use both for extra horizontal
padding (default `" "`).
vpad_char (str): Pad character to use for extra vertical padding
and for vertical fill (default `" "`).
fill_char (str): Character used to filling (expanding cells to
desired size). This can be overruled by individual settings below.
hfill_char (str): Character used for horizontal fill (default `" "`).
vfill_char (str): Character used for vertical fill (default `" "`).
align (str): Should be one of "l", "r" or "c" for left-, right- or center
horizontal alignment respectively. Default is left-aligned.
valign (str): Should be one of "t", "b" or "c" for top-, bottom and center
vertical alignment respectively. Default is centered.
border_width (int): General border width. This is overruled
by individual settings below.
border_left (int): Left border width.
border_right (int): Right border width.
border_top (int): Top border width.
border_bottom (int): Bottom border width.
border_char (str): This will use a single border char for all borders.
overruled by individual settings below.
border_left_char (str): Char used for left border.
border_right_char (str): Char used for right border.
border_top_char (str): Char used for top border.
border_bottom_char (str): Char user for bottom border.
corner_char (str): Character used when two borders cross. (default is "").
This is overruled by individual settings below.
corner_top_left_char (str): Char used for "nw" corner.
corner_top_right_char (str): Char used for "ne" corner.
corner_bottom_left_char (str): Char used for "sw" corner.
corner_bottom_right_char (str): Char used for "se" corner.
crop_string (str): String to use when cropping sideways, default is `'[...]'`.
crop (bool): Crop contentof cell rather than expand vertically, default=`False`.
enforce_size (bool): If true, the width/height of the cell is
strictly enforced and extra text will be cropped rather than the
cell growing vertically.
Raises:
Exception: for impossible cell size requirements where the
border width or height cannot fit, or the content is too
small.
"""
self.formatted = None
padwidth = kwargs.get("pad_width", None)
padwidth = int(padwidth) if padwidth is not None else None
self.pad_left = int(kwargs.get("pad_left", padwidth if padwidth is not None else 1))
self.pad_right = int(kwargs.get("pad_right", padwidth if padwidth is not None else 1))
self.pad_top = int(kwargs.get("pad_top", padwidth if padwidth is not None else 0))
self.pad_bottom = int(kwargs.get("pad_bottom", padwidth if padwidth is not None else 0))
self.enforce_size = kwargs.get("enforce_size", False)
# avoid multi-char pad_chars messing up counting
pad_char = kwargs.get("pad_char", " ")
pad_char = pad_char[0] if pad_char else " "
hpad_char = kwargs.get("hpad_char", pad_char)
self.hpad_char = hpad_char[0] if hpad_char else pad_char
vpad_char = kwargs.get("vpad_char", pad_char)
self.vpad_char = vpad_char[0] if vpad_char else pad_char
fill_char = kwargs.get("fill_char", " ")
fill_char = fill_char[0] if fill_char else " "
hfill_char = kwargs.get("hfill_char", fill_char)
self.hfill_char = hfill_char[0] if hfill_char else " "
vfill_char = kwargs.get("vfill_char", fill_char)
self.vfill_char = vfill_char[0] if vfill_char else " "
self.crop_string = kwargs.get("crop_string", "[...]")
# borders and corners
borderwidth = kwargs.get("border_width", 0)
self.border_left = kwargs.get("border_left", borderwidth)
self.border_right = kwargs.get("border_right", borderwidth)
self.border_top = kwargs.get("border_top", borderwidth)
self.border_bottom = kwargs.get("border_bottom", borderwidth)
borderchar = kwargs.get("border_char", None)
self.border_left_char = kwargs.get("border_left_char", borderchar if borderchar else "|")
self.border_right_char = kwargs.get("border_right_char", borderchar if borderchar else "|")
self.border_top_char = kwargs.get("border_topchar", borderchar if borderchar else "-")
self.border_bottom_char = kwargs.get("border_bottom_char", borderchar if borderchar else "-")
corner_char = kwargs.get("corner_char", "+")
self.corner_top_left_char = kwargs.get("corner_top_left_char", corner_char)
self.corner_top_right_char = kwargs.get("corner_top_right_char", corner_char)
self.corner_bottom_left_char = kwargs.get("corner_bottom_left_char", corner_char)
self.corner_bottom_right_char = kwargs.get("corner_bottom_right_char", corner_char)
# alignments
self.align = kwargs.get("align", "l")
self.valign = kwargs.get("valign", "c")
# self.data = self._split_lines(unicode(data))
self.data = self._split_lines(_to_ansi(data))
self.raw_width = max(m_len(line) for line in self.data)
self.raw_height = len(self.data)
# this is extra trimming required for cels in the middle of a table only
self.trim_horizontal = 0
self.trim_vertical = 0
# width/height is given without left/right or top/bottom padding
if "width" in kwargs:
width = kwargs.pop("width")
self.width = width - self.pad_left - self.pad_right - self.border_left - self.border_right
if self.width <= 0 < self.raw_width:
raise Exception("Cell width too small - no space for data.")
else:
self.width = self.raw_width
if "height" in kwargs:
height = kwargs.pop("height")
self.height = height - self.pad_top - self.pad_bottom - self.border_top - self.border_bottom
if self.height <= 0 < self.raw_height:
raise Exception("Cell height too small - no space for data.")
else:
self.height = self.raw_height | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"formatted",
"=",
"None",
"padwidth",
"=",
"kwargs",
".",
"get",
"(",
"\"pad_width\"",
",",
"None",
")",
"padwidth",
"=",
"int",
"(",
"padwidth",
")",
"if",
"padwidth",
"is",
"not",
"None",
"else",
"None",
"self",
".",
"pad_left",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"\"pad_left\"",
",",
"padwidth",
"if",
"padwidth",
"is",
"not",
"None",
"else",
"1",
")",
")",
"self",
".",
"pad_right",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"\"pad_right\"",
",",
"padwidth",
"if",
"padwidth",
"is",
"not",
"None",
"else",
"1",
")",
")",
"self",
".",
"pad_top",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"\"pad_top\"",
",",
"padwidth",
"if",
"padwidth",
"is",
"not",
"None",
"else",
"0",
")",
")",
"self",
".",
"pad_bottom",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"\"pad_bottom\"",
",",
"padwidth",
"if",
"padwidth",
"is",
"not",
"None",
"else",
"0",
")",
")",
"self",
".",
"enforce_size",
"=",
"kwargs",
".",
"get",
"(",
"\"enforce_size\"",
",",
"False",
")",
"# avoid multi-char pad_chars messing up counting",
"pad_char",
"=",
"kwargs",
".",
"get",
"(",
"\"pad_char\"",
",",
"\" \"",
")",
"pad_char",
"=",
"pad_char",
"[",
"0",
"]",
"if",
"pad_char",
"else",
"\" \"",
"hpad_char",
"=",
"kwargs",
".",
"get",
"(",
"\"hpad_char\"",
",",
"pad_char",
")",
"self",
".",
"hpad_char",
"=",
"hpad_char",
"[",
"0",
"]",
"if",
"hpad_char",
"else",
"pad_char",
"vpad_char",
"=",
"kwargs",
".",
"get",
"(",
"\"vpad_char\"",
",",
"pad_char",
")",
"self",
".",
"vpad_char",
"=",
"vpad_char",
"[",
"0",
"]",
"if",
"vpad_char",
"else",
"pad_char",
"fill_char",
"=",
"kwargs",
".",
"get",
"(",
"\"fill_char\"",
",",
"\" \"",
")",
"fill_char",
"=",
"fill_char",
"[",
"0",
"]",
"if",
"fill_char",
"else",
"\" \"",
"hfill_char",
"=",
"kwargs",
".",
"get",
"(",
"\"hfill_char\"",
",",
"fill_char",
")",
"self",
".",
"hfill_char",
"=",
"hfill_char",
"[",
"0",
"]",
"if",
"hfill_char",
"else",
"\" \"",
"vfill_char",
"=",
"kwargs",
".",
"get",
"(",
"\"vfill_char\"",
",",
"fill_char",
")",
"self",
".",
"vfill_char",
"=",
"vfill_char",
"[",
"0",
"]",
"if",
"vfill_char",
"else",
"\" \"",
"self",
".",
"crop_string",
"=",
"kwargs",
".",
"get",
"(",
"\"crop_string\"",
",",
"\"[...]\"",
")",
"# borders and corners",
"borderwidth",
"=",
"kwargs",
".",
"get",
"(",
"\"border_width\"",
",",
"0",
")",
"self",
".",
"border_left",
"=",
"kwargs",
".",
"get",
"(",
"\"border_left\"",
",",
"borderwidth",
")",
"self",
".",
"border_right",
"=",
"kwargs",
".",
"get",
"(",
"\"border_right\"",
",",
"borderwidth",
")",
"self",
".",
"border_top",
"=",
"kwargs",
".",
"get",
"(",
"\"border_top\"",
",",
"borderwidth",
")",
"self",
".",
"border_bottom",
"=",
"kwargs",
".",
"get",
"(",
"\"border_bottom\"",
",",
"borderwidth",
")",
"borderchar",
"=",
"kwargs",
".",
"get",
"(",
"\"border_char\"",
",",
"None",
")",
"self",
".",
"border_left_char",
"=",
"kwargs",
".",
"get",
"(",
"\"border_left_char\"",
",",
"borderchar",
"if",
"borderchar",
"else",
"\"|\"",
")",
"self",
".",
"border_right_char",
"=",
"kwargs",
".",
"get",
"(",
"\"border_right_char\"",
",",
"borderchar",
"if",
"borderchar",
"else",
"\"|\"",
")",
"self",
".",
"border_top_char",
"=",
"kwargs",
".",
"get",
"(",
"\"border_topchar\"",
",",
"borderchar",
"if",
"borderchar",
"else",
"\"-\"",
")",
"self",
".",
"border_bottom_char",
"=",
"kwargs",
".",
"get",
"(",
"\"border_bottom_char\"",
",",
"borderchar",
"if",
"borderchar",
"else",
"\"-\"",
")",
"corner_char",
"=",
"kwargs",
".",
"get",
"(",
"\"corner_char\"",
",",
"\"+\"",
")",
"self",
".",
"corner_top_left_char",
"=",
"kwargs",
".",
"get",
"(",
"\"corner_top_left_char\"",
",",
"corner_char",
")",
"self",
".",
"corner_top_right_char",
"=",
"kwargs",
".",
"get",
"(",
"\"corner_top_right_char\"",
",",
"corner_char",
")",
"self",
".",
"corner_bottom_left_char",
"=",
"kwargs",
".",
"get",
"(",
"\"corner_bottom_left_char\"",
",",
"corner_char",
")",
"self",
".",
"corner_bottom_right_char",
"=",
"kwargs",
".",
"get",
"(",
"\"corner_bottom_right_char\"",
",",
"corner_char",
")",
"# alignments",
"self",
".",
"align",
"=",
"kwargs",
".",
"get",
"(",
"\"align\"",
",",
"\"l\"",
")",
"self",
".",
"valign",
"=",
"kwargs",
".",
"get",
"(",
"\"valign\"",
",",
"\"c\"",
")",
"# self.data = self._split_lines(unicode(data))",
"self",
".",
"data",
"=",
"self",
".",
"_split_lines",
"(",
"_to_ansi",
"(",
"data",
")",
")",
"self",
".",
"raw_width",
"=",
"max",
"(",
"m_len",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"data",
")",
"self",
".",
"raw_height",
"=",
"len",
"(",
"self",
".",
"data",
")",
"# this is extra trimming required for cels in the middle of a table only",
"self",
".",
"trim_horizontal",
"=",
"0",
"self",
".",
"trim_vertical",
"=",
"0",
"# width/height is given without left/right or top/bottom padding",
"if",
"\"width\"",
"in",
"kwargs",
":",
"width",
"=",
"kwargs",
".",
"pop",
"(",
"\"width\"",
")",
"self",
".",
"width",
"=",
"width",
"-",
"self",
".",
"pad_left",
"-",
"self",
".",
"pad_right",
"-",
"self",
".",
"border_left",
"-",
"self",
".",
"border_right",
"if",
"self",
".",
"width",
"<=",
"0",
"<",
"self",
".",
"raw_width",
":",
"raise",
"Exception",
"(",
"\"Cell width too small - no space for data.\"",
")",
"else",
":",
"self",
".",
"width",
"=",
"self",
".",
"raw_width",
"if",
"\"height\"",
"in",
"kwargs",
":",
"height",
"=",
"kwargs",
".",
"pop",
"(",
"\"height\"",
")",
"self",
".",
"height",
"=",
"height",
"-",
"self",
".",
"pad_top",
"-",
"self",
".",
"pad_bottom",
"-",
"self",
".",
"border_top",
"-",
"self",
".",
"border_bottom",
"if",
"self",
".",
"height",
"<=",
"0",
"<",
"self",
".",
"raw_height",
":",
"raise",
"Exception",
"(",
"\"Cell height too small - no space for data.\"",
")",
"else",
":",
"self",
".",
"height",
"=",
"self",
".",
"raw_height"
] | [
325,
4
] | [
459,
41
] | python | en | ['en', 'error', 'th'] | False |
EvCell._crop | (self, text, width) |
Apply cropping of text.
Args:
text (str): The text to crop.
width (int): The width to crop `text` to.
|
Apply cropping of text. | def _crop(self, text, width):
"""
Apply cropping of text.
Args:
text (str): The text to crop.
width (int): The width to crop `text` to.
"""
if m_len(text) > width:
crop_string = self.crop_string
return text[:width - m_len(crop_string)] + crop_string
return text | [
"def",
"_crop",
"(",
"self",
",",
"text",
",",
"width",
")",
":",
"if",
"m_len",
"(",
"text",
")",
">",
"width",
":",
"crop_string",
"=",
"self",
".",
"crop_string",
"return",
"text",
"[",
":",
"width",
"-",
"m_len",
"(",
"crop_string",
")",
"]",
"+",
"crop_string",
"return",
"text"
] | [
464,
4
] | [
476,
19
] | python | en | ['en', 'error', 'th'] | False |
EvCell._reformat | (self) |
Apply all EvCells' formatting operations.
|
Apply all EvCells' formatting operations. | def _reformat(self):
"""
Apply all EvCells' formatting operations.
"""
data = self._border(self._pad(self._valign(self._align(self._fit_width(self.data)))))
return data | [
"def",
"_reformat",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_border",
"(",
"self",
".",
"_pad",
"(",
"self",
".",
"_valign",
"(",
"self",
".",
"_align",
"(",
"self",
".",
"_fit_width",
"(",
"self",
".",
"data",
")",
")",
")",
")",
")",
"return",
"data"
] | [
478,
4
] | [
484,
19
] | python | en | ['en', 'error', 'th'] | False |
EvCell._split_lines | (self, text) |
Simply split by linebreaks
Args:
text (str): text to split.
Returns:
split (list): split text.
|
Simply split by linebreaks | def _split_lines(self, text):
"""
Simply split by linebreaks
Args:
text (str): text to split.
Returns:
split (list): split text.
"""
return text.split("\n") | [
"def",
"_split_lines",
"(",
"self",
",",
"text",
")",
":",
"return",
"text",
".",
"split",
"(",
"\"\\n\"",
")"
] | [
486,
4
] | [
496,
31
] | python | en | ['en', 'error', 'th'] | False |
EvCell._fit_width | (self, data) |
Split too-long lines to fit the desired width of the Cell.
Args:
data (str): Text to adjust to the cell's width.
Returns:
adjusted data (str): The adjusted text.
Notes:
This also updates `raw_width`.
|
Split too-long lines to fit the desired width of the Cell. | def _fit_width(self, data):
"""
Split too-long lines to fit the desired width of the Cell.
Args:
data (str): Text to adjust to the cell's width.
Returns:
adjusted data (str): The adjusted text.
Notes:
This also updates `raw_width`.
"""
width = self.width
adjusted_data = []
for line in data:
if 0 < width < m_len(line):
# replace_whitespace=False, expand_tabs=False is a
# fix for ANSIString not supporting expand_tabs/translate
adjusted_data.extend([ANSIString(part + ANSIString("|n"))
for part in wrap(line, width=width, drop_whitespace=False)])
else:
adjusted_data.append(line)
if self.enforce_size:
# don't allow too high cells
excess = len(adjusted_data) - self.height
if excess > 0:
# too many lines. Crop and mark last line with crop_string
crop_string = self.crop_string
adjusted_data = adjusted_data[:-excess]
crop_string_length = len(crop_string)
if len(adjusted_data[-1]) > crop_string_length:
adjusted_data[-1] = adjusted_data[-1][:-crop_string_length] + crop_string
else:
adjusted_data[-1] += crop_string
elif excess < 0:
# too few lines. Fill to height.
adjusted_data.extend(["" for _ in range(excess)])
return adjusted_data | [
"def",
"_fit_width",
"(",
"self",
",",
"data",
")",
":",
"width",
"=",
"self",
".",
"width",
"adjusted_data",
"=",
"[",
"]",
"for",
"line",
"in",
"data",
":",
"if",
"0",
"<",
"width",
"<",
"m_len",
"(",
"line",
")",
":",
"# replace_whitespace=False, expand_tabs=False is a",
"# fix for ANSIString not supporting expand_tabs/translate",
"adjusted_data",
".",
"extend",
"(",
"[",
"ANSIString",
"(",
"part",
"+",
"ANSIString",
"(",
"\"|n\"",
")",
")",
"for",
"part",
"in",
"wrap",
"(",
"line",
",",
"width",
"=",
"width",
",",
"drop_whitespace",
"=",
"False",
")",
"]",
")",
"else",
":",
"adjusted_data",
".",
"append",
"(",
"line",
")",
"if",
"self",
".",
"enforce_size",
":",
"# don't allow too high cells",
"excess",
"=",
"len",
"(",
"adjusted_data",
")",
"-",
"self",
".",
"height",
"if",
"excess",
">",
"0",
":",
"# too many lines. Crop and mark last line with crop_string",
"crop_string",
"=",
"self",
".",
"crop_string",
"adjusted_data",
"=",
"adjusted_data",
"[",
":",
"-",
"excess",
"]",
"crop_string_length",
"=",
"len",
"(",
"crop_string",
")",
"if",
"len",
"(",
"adjusted_data",
"[",
"-",
"1",
"]",
")",
">",
"crop_string_length",
":",
"adjusted_data",
"[",
"-",
"1",
"]",
"=",
"adjusted_data",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"crop_string_length",
"]",
"+",
"crop_string",
"else",
":",
"adjusted_data",
"[",
"-",
"1",
"]",
"+=",
"crop_string",
"elif",
"excess",
"<",
"0",
":",
"# too few lines. Fill to height.",
"adjusted_data",
".",
"extend",
"(",
"[",
"\"\"",
"for",
"_",
"in",
"range",
"(",
"excess",
")",
"]",
")",
"return",
"adjusted_data"
] | [
498,
4
] | [
539,
28
] | python | en | ['en', 'error', 'th'] | False |
EvCell._center | (self, text, width, pad_char) |
Horizontally center text on line of certain width, using padding.
Args:
text (str): The text to center.
width (int): How wide the area is (in characters) where `text`
should be centered.
pad_char (str): Which padding character to use.
Returns:
text (str): Centered text.
|
Horizontally center text on line of certain width, using padding. | def _center(self, text, width, pad_char):
"""
Horizontally center text on line of certain width, using padding.
Args:
text (str): The text to center.
width (int): How wide the area is (in characters) where `text`
should be centered.
pad_char (str): Which padding character to use.
Returns:
text (str): Centered text.
"""
excess = width - m_len(text)
if excess <= 0:
return text
if excess % 2:
# uneven padding
narrowside = (excess // 2) * pad_char
widerside = narrowside + pad_char
if width % 2:
return narrowside + text + widerside
else:
return widerside + text + narrowside
else:
# even padding - same on both sides
side = (excess // 2) * pad_char
return side + text + side | [
"def",
"_center",
"(",
"self",
",",
"text",
",",
"width",
",",
"pad_char",
")",
":",
"excess",
"=",
"width",
"-",
"m_len",
"(",
"text",
")",
"if",
"excess",
"<=",
"0",
":",
"return",
"text",
"if",
"excess",
"%",
"2",
":",
"# uneven padding",
"narrowside",
"=",
"(",
"excess",
"//",
"2",
")",
"*",
"pad_char",
"widerside",
"=",
"narrowside",
"+",
"pad_char",
"if",
"width",
"%",
"2",
":",
"return",
"narrowside",
"+",
"text",
"+",
"widerside",
"else",
":",
"return",
"widerside",
"+",
"text",
"+",
"narrowside",
"else",
":",
"# even padding - same on both sides",
"side",
"=",
"(",
"excess",
"//",
"2",
")",
"*",
"pad_char",
"return",
"side",
"+",
"text",
"+",
"side"
] | [
541,
4
] | [
569,
37
] | python | en | ['en', 'error', 'th'] | False |
EvCell._align | (self, data) |
Align list of rows of cell. Whitespace characters will be stripped
if there is only one whitespace character - otherwise, it's assumed
the caller may be trying some manual formatting in the text.
Args:
data (str): Text to align.
Returns:
text (str): Aligned result.
|
Align list of rows of cell. Whitespace characters will be stripped
if there is only one whitespace character - otherwise, it's assumed
the caller may be trying some manual formatting in the text. | def _align(self, data):
"""
Align list of rows of cell. Whitespace characters will be stripped
if there is only one whitespace character - otherwise, it's assumed
the caller may be trying some manual formatting in the text.
Args:
data (str): Text to align.
Returns:
text (str): Aligned result.
"""
align = self.align
hfill_char = self.hfill_char
width = self.width
if align == "l":
lines = [(line.lstrip(" ") + " " if line.startswith(" ") and not line.startswith(" ")
else line) + hfill_char * (width - m_len(line)) for line in data]
return lines
elif align == "r":
return [hfill_char * (width - m_len(line)) + (" " + line.rstrip(" ")
if line.endswith(" ") and not line.endswith(" ")
else line) for line in data]
else: # center, 'c'
return [self._center(line, self.width, self.hfill_char) for line in data] | [
"def",
"_align",
"(",
"self",
",",
"data",
")",
":",
"align",
"=",
"self",
".",
"align",
"hfill_char",
"=",
"self",
".",
"hfill_char",
"width",
"=",
"self",
".",
"width",
"if",
"align",
"==",
"\"l\"",
":",
"lines",
"=",
"[",
"(",
"line",
".",
"lstrip",
"(",
"\" \"",
")",
"+",
"\" \"",
"if",
"line",
".",
"startswith",
"(",
"\" \"",
")",
"and",
"not",
"line",
".",
"startswith",
"(",
"\" \"",
")",
"else",
"line",
")",
"+",
"hfill_char",
"*",
"(",
"width",
"-",
"m_len",
"(",
"line",
")",
")",
"for",
"line",
"in",
"data",
"]",
"return",
"lines",
"elif",
"align",
"==",
"\"r\"",
":",
"return",
"[",
"hfill_char",
"*",
"(",
"width",
"-",
"m_len",
"(",
"line",
")",
")",
"+",
"(",
"\" \"",
"+",
"line",
".",
"rstrip",
"(",
"\" \"",
")",
"if",
"line",
".",
"endswith",
"(",
"\" \"",
")",
"and",
"not",
"line",
".",
"endswith",
"(",
"\" \"",
")",
"else",
"line",
")",
"for",
"line",
"in",
"data",
"]",
"else",
":",
"# center, 'c'",
"return",
"[",
"self",
".",
"_center",
"(",
"line",
",",
"self",
".",
"width",
",",
"self",
".",
"hfill_char",
")",
"for",
"line",
"in",
"data",
"]"
] | [
571,
4
] | [
596,
85
] | python | en | ['en', 'error', 'th'] | False |
EvCell._valign | (self, data) |
Align cell vertically
Args:
data (str): Text to align.
Returns:
text (str): Vertically aligned text.
|
Align cell vertically | def _valign(self, data):
"""
Align cell vertically
Args:
data (str): Text to align.
Returns:
text (str): Vertically aligned text.
"""
valign = self.valign
height = self.height
cheight = len(data)
excess = height - cheight
padline = self.vfill_char * self.width
if excess <= 0:
return data
# only care if we need to add new lines
if valign == 't':
return data + [padline for _ in range(excess)]
elif valign == 'b':
return [padline for _ in range(excess)] + data
else: # center
narrowside = [padline for _ in range(excess // 2)]
widerside = narrowside + [padline]
if excess % 2:
# uneven padding
if height % 2:
return widerside + data + narrowside
else:
return narrowside + data + widerside
else:
# even padding, same on both sides
return narrowside + data + narrowside | [
"def",
"_valign",
"(",
"self",
",",
"data",
")",
":",
"valign",
"=",
"self",
".",
"valign",
"height",
"=",
"self",
".",
"height",
"cheight",
"=",
"len",
"(",
"data",
")",
"excess",
"=",
"height",
"-",
"cheight",
"padline",
"=",
"self",
".",
"vfill_char",
"*",
"self",
".",
"width",
"if",
"excess",
"<=",
"0",
":",
"return",
"data",
"# only care if we need to add new lines",
"if",
"valign",
"==",
"'t'",
":",
"return",
"data",
"+",
"[",
"padline",
"for",
"_",
"in",
"range",
"(",
"excess",
")",
"]",
"elif",
"valign",
"==",
"'b'",
":",
"return",
"[",
"padline",
"for",
"_",
"in",
"range",
"(",
"excess",
")",
"]",
"+",
"data",
"else",
":",
"# center",
"narrowside",
"=",
"[",
"padline",
"for",
"_",
"in",
"range",
"(",
"excess",
"//",
"2",
")",
"]",
"widerside",
"=",
"narrowside",
"+",
"[",
"padline",
"]",
"if",
"excess",
"%",
"2",
":",
"# uneven padding",
"if",
"height",
"%",
"2",
":",
"return",
"widerside",
"+",
"data",
"+",
"narrowside",
"else",
":",
"return",
"narrowside",
"+",
"data",
"+",
"widerside",
"else",
":",
"# even padding, same on both sides",
"return",
"narrowside",
"+",
"data",
"+",
"narrowside"
] | [
598,
4
] | [
633,
53
] | python | en | ['en', 'error', 'th'] | False |
EvCell._pad | (self, data) |
Pad data with extra characters on all sides.
Args:
data (str): Text to pad.
Returns:
text (str): Padded text.
|
Pad data with extra characters on all sides. | def _pad(self, data):
"""
Pad data with extra characters on all sides.
Args:
data (str): Text to pad.
Returns:
text (str): Padded text.
"""
left = self.hpad_char * self.pad_left
right = self.hpad_char * self.pad_right
vfill = (self.width + self.pad_left + self.pad_right) * self.vpad_char
top = [vfill for _ in range(self.pad_top)]
bottom = [vfill for _ in range(self.pad_bottom)]
return top + [left + line + right for line in data] + bottom | [
"def",
"_pad",
"(",
"self",
",",
"data",
")",
":",
"left",
"=",
"self",
".",
"hpad_char",
"*",
"self",
".",
"pad_left",
"right",
"=",
"self",
".",
"hpad_char",
"*",
"self",
".",
"pad_right",
"vfill",
"=",
"(",
"self",
".",
"width",
"+",
"self",
".",
"pad_left",
"+",
"self",
".",
"pad_right",
")",
"*",
"self",
".",
"vpad_char",
"top",
"=",
"[",
"vfill",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"pad_top",
")",
"]",
"bottom",
"=",
"[",
"vfill",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"pad_bottom",
")",
"]",
"return",
"top",
"+",
"[",
"left",
"+",
"line",
"+",
"right",
"for",
"line",
"in",
"data",
"]",
"+",
"bottom"
] | [
635,
4
] | [
651,
68
] | python | en | ['en', 'error', 'th'] | False |
EvCell._border | (self, data) |
Add borders to the cell.
Args:
data (str): Text to surround with borders.
Return:
text (str): Text with borders.
|
Add borders to the cell. | def _border(self, data):
"""
Add borders to the cell.
Args:
data (str): Text to surround with borders.
Return:
text (str): Text with borders.
"""
left = self.border_left_char * self.border_left + ANSIString('|n')
right = ANSIString('|n') + self.border_right_char * self.border_right
cwidth = self.width + self.pad_left + self.pad_right + max(0, self.border_left - 1) + max(0, self.border_right - 1)
vfill = self.corner_top_left_char if left else ""
vfill += cwidth * self.border_top_char
vfill += self.corner_top_right_char if right else ""
top = [vfill for _ in range(self.border_top)]
vfill = self.corner_bottom_left_char if left else ""
vfill += cwidth * self.border_bottom_char
vfill += self.corner_bottom_right_char if right else ""
bottom = [vfill for _ in range(self.border_bottom)]
return top + [left + line + right for line in data] + bottom | [
"def",
"_border",
"(",
"self",
",",
"data",
")",
":",
"left",
"=",
"self",
".",
"border_left_char",
"*",
"self",
".",
"border_left",
"+",
"ANSIString",
"(",
"'|n'",
")",
"right",
"=",
"ANSIString",
"(",
"'|n'",
")",
"+",
"self",
".",
"border_right_char",
"*",
"self",
".",
"border_right",
"cwidth",
"=",
"self",
".",
"width",
"+",
"self",
".",
"pad_left",
"+",
"self",
".",
"pad_right",
"+",
"max",
"(",
"0",
",",
"self",
".",
"border_left",
"-",
"1",
")",
"+",
"max",
"(",
"0",
",",
"self",
".",
"border_right",
"-",
"1",
")",
"vfill",
"=",
"self",
".",
"corner_top_left_char",
"if",
"left",
"else",
"\"\"",
"vfill",
"+=",
"cwidth",
"*",
"self",
".",
"border_top_char",
"vfill",
"+=",
"self",
".",
"corner_top_right_char",
"if",
"right",
"else",
"\"\"",
"top",
"=",
"[",
"vfill",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"border_top",
")",
"]",
"vfill",
"=",
"self",
".",
"corner_bottom_left_char",
"if",
"left",
"else",
"\"\"",
"vfill",
"+=",
"cwidth",
"*",
"self",
".",
"border_bottom_char",
"vfill",
"+=",
"self",
".",
"corner_bottom_right_char",
"if",
"right",
"else",
"\"\"",
"bottom",
"=",
"[",
"vfill",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"border_bottom",
")",
"]",
"return",
"top",
"+",
"[",
"left",
"+",
"line",
"+",
"right",
"for",
"line",
"in",
"data",
"]",
"+",
"bottom"
] | [
653,
4
] | [
680,
68
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.