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 |
---|---|---|---|---|---|---|---|---|---|---|---|
SwitchBot.assumed_state | (self) | Return true if unable to access real state of entity. | Return true if unable to access real state of entity. | def assumed_state(self) -> bool:
"""Return true if unable to access real state of entity."""
return True | [
"def",
"assumed_state",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | [
68,
4
] | [
70,
19
] | python | en | ['en', 'en', 'en'] | True |
SwitchBot.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self) -> bool:
"""Return true if device is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_state"
] | [
73,
4
] | [
75,
26
] | python | en | ['en', 'fy', 'en'] | True |
SwitchBot.unique_id | (self) | Return a unique, Home Assistant friendly identifier for this entity. | Return a unique, Home Assistant friendly identifier for this entity. | def unique_id(self) -> str:
"""Return a unique, Home Assistant friendly identifier for this entity."""
return self._mac.replace(":", "") | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_mac",
".",
"replace",
"(",
"\":\"",
",",
"\"\"",
")"
] | [
78,
4
] | [
80,
41
] | python | en | ['en', 'en', 'en'] | True |
SwitchBot.name | (self) | Return the name of the switch. | Return the name of the switch. | def name(self) -> str:
"""Return the name of the switch."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
83,
4
] | [
85,
25
] | python | en | ['en', 'en', 'en'] | True |
SwitchBot.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self) -> Dict[str, Any]:
"""Return the state attributes."""
return {"last_run_success": self._last_run_success} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"\"last_run_success\"",
":",
"self",
".",
"_last_run_success",
"}"
] | [
88,
4
] | [
90,
59
] | python | en | ['en', 'en', 'en'] | True |
test_sensor_state | (hass) | Test sensor state data. | Test sensor state data. | async def test_sensor_state(hass):
"""Test sensor state data."""
await init_integration(hass)
test_glucose_sensor = hass.states.get("sensor.blood_sugar")
assert test_glucose_sensor.state == str(
GLUCOSE_READINGS[0].sgv # pylint: disable=maybe-no-member
) | [
"async",
"def",
"test_sensor_state",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"test_glucose_sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.blood_sugar\"",
")",
"assert",
"test_glucose_sensor",
".",
"state",
"==",
"str",
"(",
"GLUCOSE_READINGS",
"[",
"0",
"]",
".",
"sgv",
"# pylint: disable=maybe-no-member",
")"
] | [
18,
0
] | [
25,
5
] | python | en | ['fr', 'no', 'en'] | False |
test_sensor_error | (hass) | Test sensor state data. | Test sensor state data. | async def test_sensor_error(hass):
"""Test sensor state data."""
await init_integration_unavailable(hass)
test_glucose_sensor = hass.states.get("sensor.blood_sugar")
assert test_glucose_sensor.state == STATE_UNAVAILABLE | [
"async",
"def",
"test_sensor_error",
"(",
"hass",
")",
":",
"await",
"init_integration_unavailable",
"(",
"hass",
")",
"test_glucose_sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.blood_sugar\"",
")",
"assert",
"test_glucose_sensor",
".",
"state",
"==",
"STATE_UNAVAILABLE"
] | [
28,
0
] | [
33,
57
] | python | en | ['fr', 'no', 'en'] | False |
test_sensor_empty_response | (hass) | Test sensor state data. | Test sensor state data. | async def test_sensor_empty_response(hass):
"""Test sensor state data."""
await init_integration_empty_response(hass)
test_glucose_sensor = hass.states.get("sensor.blood_sugar")
assert test_glucose_sensor.state == STATE_UNAVAILABLE | [
"async",
"def",
"test_sensor_empty_response",
"(",
"hass",
")",
":",
"await",
"init_integration_empty_response",
"(",
"hass",
")",
"test_glucose_sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.blood_sugar\"",
")",
"assert",
"test_glucose_sensor",
".",
"state",
"==",
"STATE_UNAVAILABLE"
] | [
36,
0
] | [
41,
57
] | python | en | ['fr', 'no', 'en'] | False |
test_sensor_attributes | (hass) | Test sensor attributes. | Test sensor attributes. | async def test_sensor_attributes(hass):
"""Test sensor attributes."""
await init_integration(hass)
test_glucose_sensor = hass.states.get("sensor.blood_sugar")
reading = GLUCOSE_READINGS[0]
assert reading is not None
attr = test_glucose_sensor.attributes
assert attr[ATTR_DATE] == reading.date # pylint: disable=maybe-no-member
assert attr[ATTR_DELTA] == reading.delta # pylint: disable=maybe-no-member
assert attr[ATTR_DEVICE] == reading.device # pylint: disable=maybe-no-member
assert attr[ATTR_DIRECTION] == reading.direction # pylint: disable=maybe-no-member
assert attr[ATTR_ICON] == "mdi:arrow-bottom-right" | [
"async",
"def",
"test_sensor_attributes",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"test_glucose_sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.blood_sugar\"",
")",
"reading",
"=",
"GLUCOSE_READINGS",
"[",
"0",
"]",
"assert",
"reading",
"is",
"not",
"None",
"attr",
"=",
"test_glucose_sensor",
".",
"attributes",
"assert",
"attr",
"[",
"ATTR_DATE",
"]",
"==",
"reading",
".",
"date",
"# pylint: disable=maybe-no-member",
"assert",
"attr",
"[",
"ATTR_DELTA",
"]",
"==",
"reading",
".",
"delta",
"# pylint: disable=maybe-no-member",
"assert",
"attr",
"[",
"ATTR_DEVICE",
"]",
"==",
"reading",
".",
"device",
"# pylint: disable=maybe-no-member",
"assert",
"attr",
"[",
"ATTR_DIRECTION",
"]",
"==",
"reading",
".",
"direction",
"# pylint: disable=maybe-no-member",
"assert",
"attr",
"[",
"ATTR_ICON",
"]",
"==",
"\"mdi:arrow-bottom-right\""
] | [
44,
0
] | [
57,
54
] | python | en | ['sv', 'mt', 'en'] | False |
mock_responses | (mock) | Mock responses for Efergy. | Mock responses for Efergy. | def mock_responses(mock):
"""Mock responses for Efergy."""
base_url = "https://engage.efergy.com/mobile_proxy/"
mock.get(
f"{base_url}getInstant?token={token}",
text=load_fixture("efergy_instant.json"),
)
mock.get(
f"{base_url}getEnergy?token={token}&offset=300&period=day",
text=load_fixture("efergy_energy.json"),
)
mock.get(
f"{base_url}getBudget?token={token}",
text=load_fixture("efergy_budget.json"),
)
mock.get(
f"{base_url}getCost?token={token}&offset=300&period=day",
text=load_fixture("efergy_cost.json"),
)
mock.get(
f"{base_url}getCurrentValuesSummary?token={token}",
text=load_fixture("efergy_current_values_single.json"),
)
mock.get(
f"{base_url}getCurrentValuesSummary?token={multi_sensor_token}",
text=load_fixture("efergy_current_values_multi.json"),
) | [
"def",
"mock_responses",
"(",
"mock",
")",
":",
"base_url",
"=",
"\"https://engage.efergy.com/mobile_proxy/\"",
"mock",
".",
"get",
"(",
"f\"{base_url}getInstant?token={token}\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"efergy_instant.json\"",
")",
",",
")",
"mock",
".",
"get",
"(",
"f\"{base_url}getEnergy?token={token}&offset=300&period=day\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"efergy_energy.json\"",
")",
",",
")",
"mock",
".",
"get",
"(",
"f\"{base_url}getBudget?token={token}\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"efergy_budget.json\"",
")",
",",
")",
"mock",
".",
"get",
"(",
"f\"{base_url}getCost?token={token}&offset=300&period=day\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"efergy_cost.json\"",
")",
",",
")",
"mock",
".",
"get",
"(",
"f\"{base_url}getCurrentValuesSummary?token={token}\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"efergy_current_values_single.json\"",
")",
",",
")",
"mock",
".",
"get",
"(",
"f\"{base_url}getCurrentValuesSummary?token={multi_sensor_token}\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"efergy_current_values_multi.json\"",
")",
",",
")"
] | [
30,
0
] | [
56,
5
] | python | en | ['en', 'no', 'en'] | True |
test_single_sensor_readings | (hass, requests_mock) | Test for successfully setting up the Efergy platform. | Test for successfully setting up the Efergy platform. | async def test_single_sensor_readings(hass, requests_mock):
"""Test for successfully setting up the Efergy platform."""
mock_responses(requests_mock)
assert await async_setup_component(hass, "sensor", {"sensor": ONE_SENSOR_CONFIG})
await hass.async_block_till_done()
assert "38.21" == hass.states.get("sensor.energy_consumed").state
assert "1580" == hass.states.get("sensor.energy_usage").state
assert "ok" == hass.states.get("sensor.energy_budget").state
assert "5.27" == hass.states.get("sensor.energy_cost").state
assert "1628" == hass.states.get("sensor.efergy_728386").state | [
"async",
"def",
"test_single_sensor_readings",
"(",
"hass",
",",
"requests_mock",
")",
":",
"mock_responses",
"(",
"requests_mock",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"sensor\"",
",",
"{",
"\"sensor\"",
":",
"ONE_SENSOR_CONFIG",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"38.21\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_consumed\"",
")",
".",
"state",
"assert",
"\"1580\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_usage\"",
")",
".",
"state",
"assert",
"\"ok\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_budget\"",
")",
".",
"state",
"assert",
"\"5.27\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_cost\"",
")",
".",
"state",
"assert",
"\"1628\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.efergy_728386\"",
")",
".",
"state"
] | [
59,
0
] | [
69,
66
] | python | en | ['en', 'en', 'en'] | True |
test_multi_sensor_readings | (hass, requests_mock) | Test for multiple sensors in one household. | Test for multiple sensors in one household. | async def test_multi_sensor_readings(hass, requests_mock):
"""Test for multiple sensors in one household."""
mock_responses(requests_mock)
assert await async_setup_component(hass, "sensor", {"sensor": MULTI_SENSOR_CONFIG})
await hass.async_block_till_done()
assert "218" == hass.states.get("sensor.efergy_728386").state
assert "1808" == hass.states.get("sensor.efergy_0").state
assert "312" == hass.states.get("sensor.efergy_728387").state | [
"async",
"def",
"test_multi_sensor_readings",
"(",
"hass",
",",
"requests_mock",
")",
":",
"mock_responses",
"(",
"requests_mock",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"sensor\"",
",",
"{",
"\"sensor\"",
":",
"MULTI_SENSOR_CONFIG",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"218\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.efergy_728386\"",
")",
".",
"state",
"assert",
"\"1808\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.efergy_0\"",
")",
".",
"state",
"assert",
"\"312\"",
"==",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.efergy_728387\"",
")",
".",
"state"
] | [
72,
0
] | [
80,
65
] | python | en | ['en', 'no', 'en'] | True |
is_media_source_id | (media_content_id: str) | Test if identifier is a media source. | Test if identifier is a media source. | def is_media_source_id(media_content_id: str):
"""Test if identifier is a media source."""
return URI_SCHEME_REGEX.match(media_content_id) is not None | [
"def",
"is_media_source_id",
"(",
"media_content_id",
":",
"str",
")",
":",
"return",
"URI_SCHEME_REGEX",
".",
"match",
"(",
"media_content_id",
")",
"is",
"not",
"None"
] | [
21,
0
] | [
23,
63
] | python | en | ['en', 'fy', 'en'] | True |
generate_media_source_id | (domain: str, identifier: str) | Generate a media source ID. | Generate a media source ID. | def generate_media_source_id(domain: str, identifier: str) -> str:
"""Generate a media source ID."""
uri = f"{URI_SCHEME}{domain or ''}"
if identifier:
uri += f"/{identifier}"
return uri | [
"def",
"generate_media_source_id",
"(",
"domain",
":",
"str",
",",
"identifier",
":",
"str",
")",
"->",
"str",
":",
"uri",
"=",
"f\"{URI_SCHEME}{domain or ''}\"",
"if",
"identifier",
":",
"uri",
"+=",
"f\"/{identifier}\"",
"return",
"uri"
] | [
26,
0
] | [
31,
14
] | python | en | ['en', 'co', 'en'] | True |
async_setup | (hass: HomeAssistant, config: dict) | Set up the media_source component. | Set up the media_source component. | async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the media_source component."""
hass.data[DOMAIN] = {}
hass.components.websocket_api.async_register_command(websocket_browse_media)
hass.components.websocket_api.async_register_command(websocket_resolve_media)
hass.components.frontend.async_register_built_in_panel(
"media-browser", "media_browser", "hass:play-box-multiple"
)
local_source.async_setup(hass)
await async_process_integration_platforms(
hass, DOMAIN, _process_media_source_platform
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"hass",
".",
"components",
".",
"websocket_api",
".",
"async_register_command",
"(",
"websocket_browse_media",
")",
"hass",
".",
"components",
".",
"websocket_api",
".",
"async_register_command",
"(",
"websocket_resolve_media",
")",
"hass",
".",
"components",
".",
"frontend",
".",
"async_register_built_in_panel",
"(",
"\"media-browser\"",
",",
"\"media_browser\"",
",",
"\"hass:play-box-multiple\"",
")",
"local_source",
".",
"async_setup",
"(",
"hass",
")",
"await",
"async_process_integration_platforms",
"(",
"hass",
",",
"DOMAIN",
",",
"_process_media_source_platform",
")",
"return",
"True"
] | [
34,
0
] | [
46,
15
] | python | en | ['en', 'en', 'en'] | True |
_process_media_source_platform | (hass, domain, platform) | Process a media source platform. | Process a media source platform. | async def _process_media_source_platform(hass, domain, platform):
"""Process a media source platform."""
hass.data[DOMAIN][domain] = await platform.async_get_media_source(hass) | [
"async",
"def",
"_process_media_source_platform",
"(",
"hass",
",",
"domain",
",",
"platform",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"domain",
"]",
"=",
"await",
"platform",
".",
"async_get_media_source",
"(",
"hass",
")"
] | [
49,
0
] | [
51,
75
] | python | en | ['en', 'lv', 'en'] | True |
_get_media_item | (
hass: HomeAssistant, media_content_id: Optional[str]
) | Return media item. | Return media item. | def _get_media_item(
hass: HomeAssistant, media_content_id: Optional[str]
) -> models.MediaSourceItem:
"""Return media item."""
if media_content_id:
return models.MediaSourceItem.from_uri(hass, media_content_id)
# We default to our own domain if its only one registered
domain = None if len(hass.data[DOMAIN]) > 1 else DOMAIN
return models.MediaSourceItem(hass, domain, "") | [
"def",
"_get_media_item",
"(",
"hass",
":",
"HomeAssistant",
",",
"media_content_id",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"models",
".",
"MediaSourceItem",
":",
"if",
"media_content_id",
":",
"return",
"models",
".",
"MediaSourceItem",
".",
"from_uri",
"(",
"hass",
",",
"media_content_id",
")",
"# We default to our own domain if its only one registered",
"domain",
"=",
"None",
"if",
"len",
"(",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
")",
">",
"1",
"else",
"DOMAIN",
"return",
"models",
".",
"MediaSourceItem",
"(",
"hass",
",",
"domain",
",",
"\"\"",
")"
] | [
55,
0
] | [
64,
51
] | python | en | ['en', 'et', 'en'] | True |
async_browse_media | (
hass: HomeAssistant, media_content_id: str
) | Return media player browse media results. | Return media player browse media results. | async def async_browse_media(
hass: HomeAssistant, media_content_id: str
) -> models.BrowseMediaSource:
"""Return media player browse media results."""
return await _get_media_item(hass, media_content_id).async_browse() | [
"async",
"def",
"async_browse_media",
"(",
"hass",
":",
"HomeAssistant",
",",
"media_content_id",
":",
"str",
")",
"->",
"models",
".",
"BrowseMediaSource",
":",
"return",
"await",
"_get_media_item",
"(",
"hass",
",",
"media_content_id",
")",
".",
"async_browse",
"(",
")"
] | [
68,
0
] | [
72,
71
] | python | en | ['en', 'en', 'en'] | True |
async_resolve_media | (
hass: HomeAssistant, media_content_id: str
) | Get info to play media. | Get info to play media. | async def async_resolve_media(
hass: HomeAssistant, media_content_id: str
) -> models.PlayMedia:
"""Get info to play media."""
return await _get_media_item(hass, media_content_id).async_resolve() | [
"async",
"def",
"async_resolve_media",
"(",
"hass",
":",
"HomeAssistant",
",",
"media_content_id",
":",
"str",
")",
"->",
"models",
".",
"PlayMedia",
":",
"return",
"await",
"_get_media_item",
"(",
"hass",
",",
"media_content_id",
")",
".",
"async_resolve",
"(",
")"
] | [
76,
0
] | [
80,
72
] | python | en | ['en', 'en', 'en'] | True |
websocket_browse_media | (hass, connection, msg) | Browse available media. | Browse available media. | async def websocket_browse_media(hass, connection, msg):
"""Browse available media."""
try:
media = await async_browse_media(hass, msg.get("media_content_id"))
connection.send_result(
msg["id"],
media.as_dict(),
)
except BrowseError as err:
connection.send_error(msg["id"], "browse_media_failed", str(err)) | [
"async",
"def",
"websocket_browse_media",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"try",
":",
"media",
"=",
"await",
"async_browse_media",
"(",
"hass",
",",
"msg",
".",
"get",
"(",
"\"media_content_id\"",
")",
")",
"connection",
".",
"send_result",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"media",
".",
"as_dict",
"(",
")",
",",
")",
"except",
"BrowseError",
"as",
"err",
":",
"connection",
".",
"send_error",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"\"browse_media_failed\"",
",",
"str",
"(",
"err",
")",
")"
] | [
90,
0
] | [
99,
73
] | python | en | ['fr', 'en', 'en'] | True |
websocket_resolve_media | (hass, connection, msg) | Resolve media. | Resolve media. | async def websocket_resolve_media(hass, connection, msg):
"""Resolve media."""
try:
media = await async_resolve_media(hass, msg["media_content_id"])
url = media.url
except Unresolvable as err:
connection.send_error(msg["id"], "resolve_media_failed", str(err))
else:
if url[0] == "/":
url = async_sign_path(
hass,
connection.refresh_token_id,
url,
timedelta(seconds=msg["expires"]),
)
connection.send_result(msg["id"], {"url": url, "mime_type": media.mime_type}) | [
"async",
"def",
"websocket_resolve_media",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"try",
":",
"media",
"=",
"await",
"async_resolve_media",
"(",
"hass",
",",
"msg",
"[",
"\"media_content_id\"",
"]",
")",
"url",
"=",
"media",
".",
"url",
"except",
"Unresolvable",
"as",
"err",
":",
"connection",
".",
"send_error",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"\"resolve_media_failed\"",
",",
"str",
"(",
"err",
")",
")",
"else",
":",
"if",
"url",
"[",
"0",
"]",
"==",
"\"/\"",
":",
"url",
"=",
"async_sign_path",
"(",
"hass",
",",
"connection",
".",
"refresh_token_id",
",",
"url",
",",
"timedelta",
"(",
"seconds",
"=",
"msg",
"[",
"\"expires\"",
"]",
")",
",",
")",
"connection",
".",
"send_result",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"{",
"\"url\"",
":",
"url",
",",
"\"mime_type\"",
":",
"media",
".",
"mime_type",
"}",
")"
] | [
110,
0
] | [
126,
85
] | python | en | ['et', 'sv', 'en'] | False |
async_setup | (hass, config) | Initialize the DuckDNS component. | Initialize the DuckDNS component. | async def async_setup(hass, config):
"""Initialize the DuckDNS component."""
domain = config[DOMAIN][CONF_DOMAIN]
token = config[DOMAIN][CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass)
async def update_domain_interval(_now):
"""Update the DuckDNS entry."""
return await _update_duckdns(session, domain, token)
intervals = (
INTERVAL,
timedelta(minutes=1),
timedelta(minutes=5),
timedelta(minutes=15),
timedelta(minutes=30),
)
async_track_time_interval_backoff(hass, update_domain_interval, intervals)
async def update_domain_service(call):
"""Update the DuckDNS entry."""
await _update_duckdns(session, domain, token, txt=call.data[ATTR_TXT])
hass.services.async_register(
DOMAIN, SERVICE_SET_TXT, update_domain_service, schema=SERVICE_TXT_SCHEMA
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"domain",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_DOMAIN",
"]",
"token",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_ACCESS_TOKEN",
"]",
"session",
"=",
"async_get_clientsession",
"(",
"hass",
")",
"async",
"def",
"update_domain_interval",
"(",
"_now",
")",
":",
"\"\"\"Update the DuckDNS entry.\"\"\"",
"return",
"await",
"_update_duckdns",
"(",
"session",
",",
"domain",
",",
"token",
")",
"intervals",
"=",
"(",
"INTERVAL",
",",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
",",
"timedelta",
"(",
"minutes",
"=",
"5",
")",
",",
"timedelta",
"(",
"minutes",
"=",
"15",
")",
",",
"timedelta",
"(",
"minutes",
"=",
"30",
")",
",",
")",
"async_track_time_interval_backoff",
"(",
"hass",
",",
"update_domain_interval",
",",
"intervals",
")",
"async",
"def",
"update_domain_service",
"(",
"call",
")",
":",
"\"\"\"Update the DuckDNS entry.\"\"\"",
"await",
"_update_duckdns",
"(",
"session",
",",
"domain",
",",
"token",
",",
"txt",
"=",
"call",
".",
"data",
"[",
"ATTR_TXT",
"]",
")",
"hass",
".",
"services",
".",
"async_register",
"(",
"DOMAIN",
",",
"SERVICE_SET_TXT",
",",
"update_domain_service",
",",
"schema",
"=",
"SERVICE_TXT_SCHEMA",
")",
"return",
"True"
] | [
42,
0
] | [
69,
15
] | python | en | ['en', 'en', 'en'] | True |
_update_duckdns | (session, domain, token, *, txt=_SENTINEL, clear=False) | Update DuckDNS. | Update DuckDNS. | async def _update_duckdns(session, domain, token, *, txt=_SENTINEL, clear=False):
"""Update DuckDNS."""
params = {"domains": domain, "token": token}
if txt is not _SENTINEL:
if txt is None:
# Pass in empty txt value to indicate it's clearing txt record
params["txt"] = ""
clear = True
else:
params["txt"] = txt
if clear:
params["clear"] = "true"
resp = await session.get(UPDATE_URL, params=params)
body = await resp.text()
if body != "OK":
_LOGGER.warning("Updating DuckDNS domain failed: %s", domain)
return False
return True | [
"async",
"def",
"_update_duckdns",
"(",
"session",
",",
"domain",
",",
"token",
",",
"*",
",",
"txt",
"=",
"_SENTINEL",
",",
"clear",
"=",
"False",
")",
":",
"params",
"=",
"{",
"\"domains\"",
":",
"domain",
",",
"\"token\"",
":",
"token",
"}",
"if",
"txt",
"is",
"not",
"_SENTINEL",
":",
"if",
"txt",
"is",
"None",
":",
"# Pass in empty txt value to indicate it's clearing txt record",
"params",
"[",
"\"txt\"",
"]",
"=",
"\"\"",
"clear",
"=",
"True",
"else",
":",
"params",
"[",
"\"txt\"",
"]",
"=",
"txt",
"if",
"clear",
":",
"params",
"[",
"\"clear\"",
"]",
"=",
"\"true\"",
"resp",
"=",
"await",
"session",
".",
"get",
"(",
"UPDATE_URL",
",",
"params",
"=",
"params",
")",
"body",
"=",
"await",
"resp",
".",
"text",
"(",
")",
"if",
"body",
"!=",
"\"OK\"",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Updating DuckDNS domain failed: %s\"",
",",
"domain",
")",
"return",
"False",
"return",
"True"
] | [
75,
0
] | [
97,
15
] | python | en | ['en', 'de', 'en'] | False |
async_track_time_interval_backoff | (hass, action, intervals) | Add a listener that fires repetitively at every timedelta interval. | Add a listener that fires repetitively at every timedelta interval. | def async_track_time_interval_backoff(hass, action, intervals) -> CALLBACK_TYPE:
"""Add a listener that fires repetitively at every timedelta interval."""
if not iscoroutinefunction:
_LOGGER.error("action needs to be a coroutine and return True/False")
return
if not isinstance(intervals, (list, tuple)):
intervals = (intervals,)
remove = None
failed = 0
async def interval_listener(now):
"""Handle elapsed intervals with backoff."""
nonlocal failed, remove
try:
failed += 1
if await action(now):
failed = 0
finally:
delay = intervals[failed] if failed < len(intervals) else intervals[-1]
remove = async_call_later(hass, delay.total_seconds(), interval_listener)
hass.async_run_job(interval_listener, dt_util.utcnow())
def remove_listener():
"""Remove interval listener."""
if remove:
remove() # pylint: disable=not-callable
return remove_listener | [
"def",
"async_track_time_interval_backoff",
"(",
"hass",
",",
"action",
",",
"intervals",
")",
"->",
"CALLBACK_TYPE",
":",
"if",
"not",
"iscoroutinefunction",
":",
"_LOGGER",
".",
"error",
"(",
"\"action needs to be a coroutine and return True/False\"",
")",
"return",
"if",
"not",
"isinstance",
"(",
"intervals",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"intervals",
"=",
"(",
"intervals",
",",
")",
"remove",
"=",
"None",
"failed",
"=",
"0",
"async",
"def",
"interval_listener",
"(",
"now",
")",
":",
"\"\"\"Handle elapsed intervals with backoff.\"\"\"",
"nonlocal",
"failed",
",",
"remove",
"try",
":",
"failed",
"+=",
"1",
"if",
"await",
"action",
"(",
"now",
")",
":",
"failed",
"=",
"0",
"finally",
":",
"delay",
"=",
"intervals",
"[",
"failed",
"]",
"if",
"failed",
"<",
"len",
"(",
"intervals",
")",
"else",
"intervals",
"[",
"-",
"1",
"]",
"remove",
"=",
"async_call_later",
"(",
"hass",
",",
"delay",
".",
"total_seconds",
"(",
")",
",",
"interval_listener",
")",
"hass",
".",
"async_run_job",
"(",
"interval_listener",
",",
"dt_util",
".",
"utcnow",
"(",
")",
")",
"def",
"remove_listener",
"(",
")",
":",
"\"\"\"Remove interval listener.\"\"\"",
"if",
"remove",
":",
"remove",
"(",
")",
"# pylint: disable=not-callable",
"return",
"remove_listener"
] | [
102,
0
] | [
131,
26
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass, config_entry, async_add_entities, discovery_info=None
) | Set up the Agent DVR Alarm Control Panels. | Set up the Agent DVR Alarm Control Panels. | async def async_setup_entry(
hass, config_entry, async_add_entities, discovery_info=None
):
"""Set up the Agent DVR Alarm Control Panels."""
async_add_entities(
[AgentBaseStation(hass.data[AGENT_DOMAIN][config_entry.entry_id][CONNECTION])]
) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"async_add_entities",
"(",
"[",
"AgentBaseStation",
"(",
"hass",
".",
"data",
"[",
"AGENT_DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"CONNECTION",
"]",
")",
"]",
")"
] | [
25,
0
] | [
31,
5
] | python | en | ['en', 'fr', 'en'] | True |
AgentBaseStation.__init__ | (self, client) | Initialize the alarm control panel. | Initialize the alarm control panel. | def __init__(self, client):
"""Initialize the alarm control panel."""
self._state = None
self._client = client
self._unique_id = f"{client.unique}_CP"
name = CONST_ALARM_CONTROL_PANEL_NAME
self._name = name = f"{client.name} {name}" | [
"def",
"__init__",
"(",
"self",
",",
"client",
")",
":",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_unique_id",
"=",
"f\"{client.unique}_CP\"",
"name",
"=",
"CONST_ALARM_CONTROL_PANEL_NAME",
"self",
".",
"_name",
"=",
"name",
"=",
"f\"{client.name} {name}\""
] | [
37,
4
] | [
43,
51
] | python | en | ['en', 'en', 'en'] | True |
AgentBaseStation.icon | (self) | Return icon. | Return icon. | def icon(self):
"""Return icon."""
return ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
46,
4
] | [
48,
19
] | python | en | ['en', 'la', 'en'] | False |
AgentBaseStation.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
51,
4
] | [
53,
26
] | python | en | ['en', 'en', 'en'] | True |
AgentBaseStation.supported_features | (self) | Return the list of supported features. | Return the list of supported features. | def supported_features(self) -> int:
"""Return the list of supported features."""
return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY | SUPPORT_ALARM_ARM_NIGHT | [
"def",
"supported_features",
"(",
"self",
")",
"->",
"int",
":",
"return",
"SUPPORT_ALARM_ARM_HOME",
"|",
"SUPPORT_ALARM_ARM_AWAY",
"|",
"SUPPORT_ALARM_ARM_NIGHT"
] | [
56,
4
] | [
58,
88
] | python | en | ['en', 'en', 'en'] | True |
AgentBaseStation.device_info | (self) | Return the device info for adding the entity to the agent object. | Return the device info for adding the entity to the agent object. | def device_info(self):
"""Return the device info for adding the entity to the agent object."""
return {
"identifiers": {(AGENT_DOMAIN, self._client.unique)},
"manufacturer": "Agent",
"model": CONST_ALARM_CONTROL_PANEL_NAME,
"sw_version": self._client.version,
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"AGENT_DOMAIN",
",",
"self",
".",
"_client",
".",
"unique",
")",
"}",
",",
"\"manufacturer\"",
":",
"\"Agent\"",
",",
"\"model\"",
":",
"CONST_ALARM_CONTROL_PANEL_NAME",
",",
"\"sw_version\"",
":",
"self",
".",
"_client",
".",
"version",
",",
"}"
] | [
61,
4
] | [
68,
9
] | python | en | ['en', 'en', 'en'] | True |
AgentBaseStation.async_update | (self) | Update the state of the device. | Update the state of the device. | async def async_update(self):
"""Update the state of the device."""
await self._client.update()
armed = self._client.is_armed
if armed is None:
self._state = None
return
if armed:
prof = (await self._client.get_active_profile()).lower()
self._state = STATE_ALARM_ARMED_AWAY
if prof == CONF_HOME_MODE_NAME:
self._state = STATE_ALARM_ARMED_HOME
elif prof == CONF_NIGHT_MODE_NAME:
self._state = STATE_ALARM_ARMED_NIGHT
else:
self._state = STATE_ALARM_DISARMED | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"await",
"self",
".",
"_client",
".",
"update",
"(",
")",
"armed",
"=",
"self",
".",
"_client",
".",
"is_armed",
"if",
"armed",
"is",
"None",
":",
"self",
".",
"_state",
"=",
"None",
"return",
"if",
"armed",
":",
"prof",
"=",
"(",
"await",
"self",
".",
"_client",
".",
"get_active_profile",
"(",
")",
")",
".",
"lower",
"(",
")",
"self",
".",
"_state",
"=",
"STATE_ALARM_ARMED_AWAY",
"if",
"prof",
"==",
"CONF_HOME_MODE_NAME",
":",
"self",
".",
"_state",
"=",
"STATE_ALARM_ARMED_HOME",
"elif",
"prof",
"==",
"CONF_NIGHT_MODE_NAME",
":",
"self",
".",
"_state",
"=",
"STATE_ALARM_ARMED_NIGHT",
"else",
":",
"self",
".",
"_state",
"=",
"STATE_ALARM_DISARMED"
] | [
70,
4
] | [
85,
46
] | python | en | ['en', 'en', 'en'] | True |
AgentBaseStation.async_alarm_disarm | (self, code=None) | Send disarm command. | Send disarm command. | async def async_alarm_disarm(self, code=None):
"""Send disarm command."""
await self._client.disarm()
self._state = STATE_ALARM_DISARMED | [
"async",
"def",
"async_alarm_disarm",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"await",
"self",
".",
"_client",
".",
"disarm",
"(",
")",
"self",
".",
"_state",
"=",
"STATE_ALARM_DISARMED"
] | [
87,
4
] | [
90,
42
] | python | en | ['en', 'pt', 'en'] | True |
AgentBaseStation.async_alarm_arm_away | (self, code=None) | Send arm away command. Uses custom mode. | Send arm away command. Uses custom mode. | async def async_alarm_arm_away(self, code=None):
"""Send arm away command. Uses custom mode."""
await self._client.arm()
await self._client.set_active_profile(CONF_AWAY_MODE_NAME)
self._state = STATE_ALARM_ARMED_AWAY | [
"async",
"def",
"async_alarm_arm_away",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"await",
"self",
".",
"_client",
".",
"arm",
"(",
")",
"await",
"self",
".",
"_client",
".",
"set_active_profile",
"(",
"CONF_AWAY_MODE_NAME",
")",
"self",
".",
"_state",
"=",
"STATE_ALARM_ARMED_AWAY"
] | [
92,
4
] | [
96,
44
] | python | en | ['en', 'pt', 'en'] | True |
AgentBaseStation.async_alarm_arm_home | (self, code=None) | Send arm home command. Uses custom mode. | Send arm home command. Uses custom mode. | async def async_alarm_arm_home(self, code=None):
"""Send arm home command. Uses custom mode."""
await self._client.arm()
await self._client.set_active_profile(CONF_HOME_MODE_NAME)
self._state = STATE_ALARM_ARMED_HOME | [
"async",
"def",
"async_alarm_arm_home",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"await",
"self",
".",
"_client",
".",
"arm",
"(",
")",
"await",
"self",
".",
"_client",
".",
"set_active_profile",
"(",
"CONF_HOME_MODE_NAME",
")",
"self",
".",
"_state",
"=",
"STATE_ALARM_ARMED_HOME"
] | [
98,
4
] | [
102,
44
] | python | en | ['en', 'pt', 'en'] | True |
AgentBaseStation.async_alarm_arm_night | (self, code=None) | Send arm night command. Uses custom mode. | Send arm night command. Uses custom mode. | async def async_alarm_arm_night(self, code=None):
"""Send arm night command. Uses custom mode."""
await self._client.arm()
await self._client.set_active_profile(CONF_NIGHT_MODE_NAME)
self._state = STATE_ALARM_ARMED_NIGHT | [
"async",
"def",
"async_alarm_arm_night",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"await",
"self",
".",
"_client",
".",
"arm",
"(",
")",
"await",
"self",
".",
"_client",
".",
"set_active_profile",
"(",
"CONF_NIGHT_MODE_NAME",
")",
"self",
".",
"_state",
"=",
"STATE_ALARM_ARMED_NIGHT"
] | [
104,
4
] | [
108,
45
] | python | en | ['en', 'pt', 'en'] | True |
AgentBaseStation.name | (self) | Return the name of the base station. | Return the name of the base station. | def name(self):
"""Return the name of the base station."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
111,
4
] | [
113,
25
] | python | en | ['en', 'en', 'en'] | True |
AgentBaseStation.available | (self) | Device available. | Device available. | def available(self) -> bool:
"""Device available."""
return self._client.is_available | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_client",
".",
"is_available"
] | [
116,
4
] | [
118,
40
] | python | en | ['fr', 'en', 'en'] | False |
AgentBaseStation.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self) -> str:
"""Return a unique ID."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_unique_id"
] | [
121,
4
] | [
123,
30
] | python | ca | ['fr', 'ca', 'en'] | False |
async_setup_entry | (
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
) | Set up the Tado climate platform. | Set up the Tado climate platform. | async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Set up the Tado climate platform."""
tado = hass.data[DOMAIN][entry.entry_id][DATA]
entities = await hass.async_add_executor_job(_generate_entities, tado)
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
SERVICE_CLIMATE_TIMER,
CLIMATE_TIMER_SCHEMA,
"set_timer",
)
if entities:
async_add_entities(entities, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
")",
":",
"tado",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"DATA",
"]",
"entities",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"_generate_entities",
",",
"tado",
")",
"platform",
"=",
"entity_platform",
".",
"current_platform",
".",
"get",
"(",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_CLIMATE_TIMER",
",",
"CLIMATE_TIMER_SCHEMA",
",",
"\"set_timer\"",
",",
")",
"if",
"entities",
":",
"async_add_entities",
"(",
"entities",
",",
"True",
")"
] | [
66,
0
] | [
83,
42
] | python | en | ['en', 'pt', 'en'] | True |
_generate_entities | (tado) | Create all climate entities. | Create all climate entities. | def _generate_entities(tado):
"""Create all climate entities."""
entities = []
for zone in tado.zones:
if zone["type"] in [TYPE_HEATING, TYPE_AIR_CONDITIONING]:
entity = create_climate_entity(
tado, zone["name"], zone["id"], zone["devices"][0]
)
if entity:
entities.append(entity)
return entities | [
"def",
"_generate_entities",
"(",
"tado",
")",
":",
"entities",
"=",
"[",
"]",
"for",
"zone",
"in",
"tado",
".",
"zones",
":",
"if",
"zone",
"[",
"\"type\"",
"]",
"in",
"[",
"TYPE_HEATING",
",",
"TYPE_AIR_CONDITIONING",
"]",
":",
"entity",
"=",
"create_climate_entity",
"(",
"tado",
",",
"zone",
"[",
"\"name\"",
"]",
",",
"zone",
"[",
"\"id\"",
"]",
",",
"zone",
"[",
"\"devices\"",
"]",
"[",
"0",
"]",
")",
"if",
"entity",
":",
"entities",
".",
"append",
"(",
"entity",
")",
"return",
"entities"
] | [
86,
0
] | [
96,
19
] | python | en | ['en', 'en', 'en'] | True |
create_climate_entity | (tado, name: str, zone_id: int, zone: dict) | Create a Tado climate entity. | Create a Tado climate entity. | def create_climate_entity(tado, name: str, zone_id: int, zone: dict):
"""Create a Tado climate entity."""
capabilities = tado.get_capabilities(zone_id)
_LOGGER.debug("Capabilities for zone %s: %s", zone_id, capabilities)
zone_type = capabilities["type"]
support_flags = SUPPORT_PRESET_MODE | SUPPORT_TARGET_TEMPERATURE
supported_hvac_modes = [
TADO_TO_HA_HVAC_MODE_MAP[CONST_MODE_OFF],
TADO_TO_HA_HVAC_MODE_MAP[CONST_MODE_SMART_SCHEDULE],
]
supported_fan_modes = None
heat_temperatures = None
cool_temperatures = None
if zone_type == TYPE_AIR_CONDITIONING:
# Heat is preferred as it generally has a lower minimum temperature
for mode in ORDERED_KNOWN_TADO_MODES:
if mode not in capabilities:
continue
supported_hvac_modes.append(TADO_TO_HA_HVAC_MODE_MAP[mode])
if capabilities[mode].get("swings"):
support_flags |= SUPPORT_SWING_MODE
if not capabilities[mode].get("fanSpeeds"):
continue
support_flags |= SUPPORT_FAN_MODE
if supported_fan_modes:
continue
supported_fan_modes = [
TADO_TO_HA_FAN_MODE_MAP[speed]
for speed in capabilities[mode]["fanSpeeds"]
]
cool_temperatures = capabilities[CONST_MODE_COOL]["temperatures"]
else:
supported_hvac_modes.append(HVAC_MODE_HEAT)
if CONST_MODE_HEAT in capabilities:
heat_temperatures = capabilities[CONST_MODE_HEAT]["temperatures"]
if heat_temperatures is None and "temperatures" in capabilities:
heat_temperatures = capabilities["temperatures"]
if cool_temperatures is None and heat_temperatures is None:
_LOGGER.debug("Not adding zone %s since it has no temperatures", name)
return None
heat_min_temp = None
heat_max_temp = None
heat_step = None
cool_min_temp = None
cool_max_temp = None
cool_step = None
if heat_temperatures is not None:
heat_min_temp = float(heat_temperatures["celsius"]["min"])
heat_max_temp = float(heat_temperatures["celsius"]["max"])
heat_step = heat_temperatures["celsius"].get("step", PRECISION_TENTHS)
if cool_temperatures is not None:
cool_min_temp = float(cool_temperatures["celsius"]["min"])
cool_max_temp = float(cool_temperatures["celsius"]["max"])
cool_step = cool_temperatures["celsius"].get("step", PRECISION_TENTHS)
entity = TadoClimate(
tado,
name,
zone_id,
zone_type,
heat_min_temp,
heat_max_temp,
heat_step,
cool_min_temp,
cool_max_temp,
cool_step,
supported_hvac_modes,
supported_fan_modes,
support_flags,
zone,
)
return entity | [
"def",
"create_climate_entity",
"(",
"tado",
",",
"name",
":",
"str",
",",
"zone_id",
":",
"int",
",",
"zone",
":",
"dict",
")",
":",
"capabilities",
"=",
"tado",
".",
"get_capabilities",
"(",
"zone_id",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Capabilities for zone %s: %s\"",
",",
"zone_id",
",",
"capabilities",
")",
"zone_type",
"=",
"capabilities",
"[",
"\"type\"",
"]",
"support_flags",
"=",
"SUPPORT_PRESET_MODE",
"|",
"SUPPORT_TARGET_TEMPERATURE",
"supported_hvac_modes",
"=",
"[",
"TADO_TO_HA_HVAC_MODE_MAP",
"[",
"CONST_MODE_OFF",
"]",
",",
"TADO_TO_HA_HVAC_MODE_MAP",
"[",
"CONST_MODE_SMART_SCHEDULE",
"]",
",",
"]",
"supported_fan_modes",
"=",
"None",
"heat_temperatures",
"=",
"None",
"cool_temperatures",
"=",
"None",
"if",
"zone_type",
"==",
"TYPE_AIR_CONDITIONING",
":",
"# Heat is preferred as it generally has a lower minimum temperature",
"for",
"mode",
"in",
"ORDERED_KNOWN_TADO_MODES",
":",
"if",
"mode",
"not",
"in",
"capabilities",
":",
"continue",
"supported_hvac_modes",
".",
"append",
"(",
"TADO_TO_HA_HVAC_MODE_MAP",
"[",
"mode",
"]",
")",
"if",
"capabilities",
"[",
"mode",
"]",
".",
"get",
"(",
"\"swings\"",
")",
":",
"support_flags",
"|=",
"SUPPORT_SWING_MODE",
"if",
"not",
"capabilities",
"[",
"mode",
"]",
".",
"get",
"(",
"\"fanSpeeds\"",
")",
":",
"continue",
"support_flags",
"|=",
"SUPPORT_FAN_MODE",
"if",
"supported_fan_modes",
":",
"continue",
"supported_fan_modes",
"=",
"[",
"TADO_TO_HA_FAN_MODE_MAP",
"[",
"speed",
"]",
"for",
"speed",
"in",
"capabilities",
"[",
"mode",
"]",
"[",
"\"fanSpeeds\"",
"]",
"]",
"cool_temperatures",
"=",
"capabilities",
"[",
"CONST_MODE_COOL",
"]",
"[",
"\"temperatures\"",
"]",
"else",
":",
"supported_hvac_modes",
".",
"append",
"(",
"HVAC_MODE_HEAT",
")",
"if",
"CONST_MODE_HEAT",
"in",
"capabilities",
":",
"heat_temperatures",
"=",
"capabilities",
"[",
"CONST_MODE_HEAT",
"]",
"[",
"\"temperatures\"",
"]",
"if",
"heat_temperatures",
"is",
"None",
"and",
"\"temperatures\"",
"in",
"capabilities",
":",
"heat_temperatures",
"=",
"capabilities",
"[",
"\"temperatures\"",
"]",
"if",
"cool_temperatures",
"is",
"None",
"and",
"heat_temperatures",
"is",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Not adding zone %s since it has no temperatures\"",
",",
"name",
")",
"return",
"None",
"heat_min_temp",
"=",
"None",
"heat_max_temp",
"=",
"None",
"heat_step",
"=",
"None",
"cool_min_temp",
"=",
"None",
"cool_max_temp",
"=",
"None",
"cool_step",
"=",
"None",
"if",
"heat_temperatures",
"is",
"not",
"None",
":",
"heat_min_temp",
"=",
"float",
"(",
"heat_temperatures",
"[",
"\"celsius\"",
"]",
"[",
"\"min\"",
"]",
")",
"heat_max_temp",
"=",
"float",
"(",
"heat_temperatures",
"[",
"\"celsius\"",
"]",
"[",
"\"max\"",
"]",
")",
"heat_step",
"=",
"heat_temperatures",
"[",
"\"celsius\"",
"]",
".",
"get",
"(",
"\"step\"",
",",
"PRECISION_TENTHS",
")",
"if",
"cool_temperatures",
"is",
"not",
"None",
":",
"cool_min_temp",
"=",
"float",
"(",
"cool_temperatures",
"[",
"\"celsius\"",
"]",
"[",
"\"min\"",
"]",
")",
"cool_max_temp",
"=",
"float",
"(",
"cool_temperatures",
"[",
"\"celsius\"",
"]",
"[",
"\"max\"",
"]",
")",
"cool_step",
"=",
"cool_temperatures",
"[",
"\"celsius\"",
"]",
".",
"get",
"(",
"\"step\"",
",",
"PRECISION_TENTHS",
")",
"entity",
"=",
"TadoClimate",
"(",
"tado",
",",
"name",
",",
"zone_id",
",",
"zone_type",
",",
"heat_min_temp",
",",
"heat_max_temp",
",",
"heat_step",
",",
"cool_min_temp",
",",
"cool_max_temp",
",",
"cool_step",
",",
"supported_hvac_modes",
",",
"supported_fan_modes",
",",
"support_flags",
",",
"zone",
",",
")",
"return",
"entity"
] | [
99,
0
] | [
184,
17
] | python | en | ['es', 'sm', 'en'] | False |
TadoClimate.__init__ | (
self,
tado,
zone_name,
zone_id,
zone_type,
heat_min_temp,
heat_max_temp,
heat_step,
cool_min_temp,
cool_max_temp,
cool_step,
supported_hvac_modes,
supported_fan_modes,
support_flags,
device_info,
) | Initialize of Tado climate entity. | Initialize of Tado climate entity. | def __init__(
self,
tado,
zone_name,
zone_id,
zone_type,
heat_min_temp,
heat_max_temp,
heat_step,
cool_min_temp,
cool_max_temp,
cool_step,
supported_hvac_modes,
supported_fan_modes,
support_flags,
device_info,
):
"""Initialize of Tado climate entity."""
self._tado = tado
super().__init__(zone_name, device_info, tado.device_id, zone_id)
self.zone_id = zone_id
self.zone_type = zone_type
self._unique_id = f"{zone_type} {zone_id} {tado.device_id}"
self._ac_device = zone_type == TYPE_AIR_CONDITIONING
self._supported_hvac_modes = supported_hvac_modes
self._supported_fan_modes = supported_fan_modes
self._support_flags = support_flags
self._available = False
self._cur_temp = None
self._cur_humidity = None
self._heat_min_temp = heat_min_temp
self._heat_max_temp = heat_max_temp
self._heat_step = heat_step
self._cool_min_temp = cool_min_temp
self._cool_max_temp = cool_max_temp
self._cool_step = cool_step
self._target_temp = None
self._current_tado_fan_speed = CONST_FAN_OFF
self._current_tado_hvac_mode = CONST_MODE_OFF
self._current_tado_hvac_action = CURRENT_HVAC_OFF
self._current_tado_swing_mode = TADO_SWING_OFF
self._tado_zone_data = None
self._async_update_zone_data() | [
"def",
"__init__",
"(",
"self",
",",
"tado",
",",
"zone_name",
",",
"zone_id",
",",
"zone_type",
",",
"heat_min_temp",
",",
"heat_max_temp",
",",
"heat_step",
",",
"cool_min_temp",
",",
"cool_max_temp",
",",
"cool_step",
",",
"supported_hvac_modes",
",",
"supported_fan_modes",
",",
"support_flags",
",",
"device_info",
",",
")",
":",
"self",
".",
"_tado",
"=",
"tado",
"super",
"(",
")",
".",
"__init__",
"(",
"zone_name",
",",
"device_info",
",",
"tado",
".",
"device_id",
",",
"zone_id",
")",
"self",
".",
"zone_id",
"=",
"zone_id",
"self",
".",
"zone_type",
"=",
"zone_type",
"self",
".",
"_unique_id",
"=",
"f\"{zone_type} {zone_id} {tado.device_id}\"",
"self",
".",
"_ac_device",
"=",
"zone_type",
"==",
"TYPE_AIR_CONDITIONING",
"self",
".",
"_supported_hvac_modes",
"=",
"supported_hvac_modes",
"self",
".",
"_supported_fan_modes",
"=",
"supported_fan_modes",
"self",
".",
"_support_flags",
"=",
"support_flags",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"_cur_temp",
"=",
"None",
"self",
".",
"_cur_humidity",
"=",
"None",
"self",
".",
"_heat_min_temp",
"=",
"heat_min_temp",
"self",
".",
"_heat_max_temp",
"=",
"heat_max_temp",
"self",
".",
"_heat_step",
"=",
"heat_step",
"self",
".",
"_cool_min_temp",
"=",
"cool_min_temp",
"self",
".",
"_cool_max_temp",
"=",
"cool_max_temp",
"self",
".",
"_cool_step",
"=",
"cool_step",
"self",
".",
"_target_temp",
"=",
"None",
"self",
".",
"_current_tado_fan_speed",
"=",
"CONST_FAN_OFF",
"self",
".",
"_current_tado_hvac_mode",
"=",
"CONST_MODE_OFF",
"self",
".",
"_current_tado_hvac_action",
"=",
"CURRENT_HVAC_OFF",
"self",
".",
"_current_tado_swing_mode",
"=",
"TADO_SWING_OFF",
"self",
".",
"_tado_zone_data",
"=",
"None",
"self",
".",
"_async_update_zone_data",
"(",
")"
] | [
190,
4
] | [
242,
38
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.async_added_to_hass | (self) | Register for sensor updates. | Register for sensor updates. | async def async_added_to_hass(self):
"""Register for sensor updates."""
self.async_on_remove(
async_dispatcher_connect(
self.hass,
SIGNAL_TADO_UPDATE_RECEIVED.format(
self._tado.device_id, "zone", self.zone_id
),
self._async_update_callback,
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"SIGNAL_TADO_UPDATE_RECEIVED",
".",
"format",
"(",
"self",
".",
"_tado",
".",
"device_id",
",",
"\"zone\"",
",",
"self",
".",
"zone_id",
")",
",",
"self",
".",
"_async_update_callback",
",",
")",
")"
] | [
244,
4
] | [
255,
9
] | python | da | ['da', 'no', 'en'] | False |
TadoClimate.supported_features | (self) | Return the list of supported features. | Return the list of supported features. | def supported_features(self):
"""Return the list of supported features."""
return self._support_flags | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"self",
".",
"_support_flags"
] | [
258,
4
] | [
260,
34
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.name | (self) | Return the name of the entity. | Return the name of the entity. | def name(self):
"""Return the name of the entity."""
return self.zone_name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"zone_name"
] | [
263,
4
] | [
265,
29
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.unique_id | (self) | Return the unique id. | Return the unique id. | def unique_id(self):
"""Return the unique id."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
268,
4
] | [
270,
30
] | python | en | ['en', 'la', 'en'] | True |
TadoClimate.current_humidity | (self) | Return the current humidity. | Return the current humidity. | def current_humidity(self):
"""Return the current humidity."""
return self._tado_zone_data.current_humidity | [
"def",
"current_humidity",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tado_zone_data",
".",
"current_humidity"
] | [
273,
4
] | [
275,
52
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.current_temperature | (self) | Return the sensor temperature. | Return the sensor temperature. | def current_temperature(self):
"""Return the sensor temperature."""
return self._tado_zone_data.current_temp | [
"def",
"current_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tado_zone_data",
".",
"current_temp"
] | [
278,
4
] | [
280,
48
] | python | en | ['en', 'la', 'en'] | True |
TadoClimate.hvac_mode | (self) | Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
| Return hvac operation ie. heat, cool mode. | def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
return TADO_TO_HA_HVAC_MODE_MAP.get(self._current_tado_hvac_mode, HVAC_MODE_OFF) | [
"def",
"hvac_mode",
"(",
"self",
")",
":",
"return",
"TADO_TO_HA_HVAC_MODE_MAP",
".",
"get",
"(",
"self",
".",
"_current_tado_hvac_mode",
",",
"HVAC_MODE_OFF",
")"
] | [
283,
4
] | [
288,
88
] | python | bg | ['en', 'bg', 'bg'] | True |
TadoClimate.hvac_modes | (self) | Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
| Return the list of available hvac operation modes. | def hvac_modes(self):
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
return self._supported_hvac_modes | [
"def",
"hvac_modes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_supported_hvac_modes"
] | [
291,
4
] | [
296,
41
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.hvac_action | (self) | Return the current running hvac operation if supported.
Need to be one of CURRENT_HVAC_*.
| Return the current running hvac operation if supported. | def hvac_action(self):
"""Return the current running hvac operation if supported.
Need to be one of CURRENT_HVAC_*.
"""
return TADO_HVAC_ACTION_TO_HA_HVAC_ACTION.get(
self._tado_zone_data.current_hvac_action, CURRENT_HVAC_OFF
) | [
"def",
"hvac_action",
"(",
"self",
")",
":",
"return",
"TADO_HVAC_ACTION_TO_HA_HVAC_ACTION",
".",
"get",
"(",
"self",
".",
"_tado_zone_data",
".",
"current_hvac_action",
",",
"CURRENT_HVAC_OFF",
")"
] | [
299,
4
] | [
306,
9
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.fan_mode | (self) | Return the fan setting. | Return the fan setting. | def fan_mode(self):
"""Return the fan setting."""
if self._ac_device:
return TADO_TO_HA_FAN_MODE_MAP.get(self._current_tado_fan_speed, FAN_AUTO)
return None | [
"def",
"fan_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ac_device",
":",
"return",
"TADO_TO_HA_FAN_MODE_MAP",
".",
"get",
"(",
"self",
".",
"_current_tado_fan_speed",
",",
"FAN_AUTO",
")",
"return",
"None"
] | [
309,
4
] | [
313,
19
] | python | en | ['en', 'fy', 'en'] | True |
TadoClimate.fan_modes | (self) | List of available fan modes. | List of available fan modes. | def fan_modes(self):
"""List of available fan modes."""
return self._supported_fan_modes | [
"def",
"fan_modes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_supported_fan_modes"
] | [
316,
4
] | [
318,
40
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.set_fan_mode | (self, fan_mode: str) | Turn fan on/off. | Turn fan on/off. | def set_fan_mode(self, fan_mode: str):
"""Turn fan on/off."""
self._control_hvac(fan_mode=HA_TO_TADO_FAN_MODE_MAP[fan_mode]) | [
"def",
"set_fan_mode",
"(",
"self",
",",
"fan_mode",
":",
"str",
")",
":",
"self",
".",
"_control_hvac",
"(",
"fan_mode",
"=",
"HA_TO_TADO_FAN_MODE_MAP",
"[",
"fan_mode",
"]",
")"
] | [
320,
4
] | [
322,
70
] | python | en | ['en', 'fy', 'en'] | True |
TadoClimate.preset_mode | (self) | Return the current preset mode (home, away). | Return the current preset mode (home, away). | def preset_mode(self):
"""Return the current preset mode (home, away)."""
if self._tado_zone_data.is_away:
return PRESET_AWAY
return PRESET_HOME | [
"def",
"preset_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tado_zone_data",
".",
"is_away",
":",
"return",
"PRESET_AWAY",
"return",
"PRESET_HOME"
] | [
325,
4
] | [
329,
26
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.preset_modes | (self) | Return a list of available preset modes. | Return a list of available preset modes. | def preset_modes(self):
"""Return a list of available preset modes."""
return SUPPORT_PRESET | [
"def",
"preset_modes",
"(",
"self",
")",
":",
"return",
"SUPPORT_PRESET"
] | [
332,
4
] | [
334,
29
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.set_preset_mode | (self, preset_mode) | Set new preset mode. | Set new preset mode. | def set_preset_mode(self, preset_mode):
"""Set new preset mode."""
self._tado.set_presence(preset_mode) | [
"def",
"set_preset_mode",
"(",
"self",
",",
"preset_mode",
")",
":",
"self",
".",
"_tado",
".",
"set_presence",
"(",
"preset_mode",
")"
] | [
336,
4
] | [
338,
44
] | python | en | ['en', 'sr', 'en'] | True |
TadoClimate.temperature_unit | (self) | Return the unit of measurement used by the platform. | Return the unit of measurement used by the platform. | def temperature_unit(self):
"""Return the unit of measurement used by the platform."""
return TEMP_CELSIUS | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_CELSIUS"
] | [
341,
4
] | [
343,
27
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.target_temperature_step | (self) | Return the supported step of target temperature. | Return the supported step of target temperature. | def target_temperature_step(self):
"""Return the supported step of target temperature."""
if self._tado_zone_data.current_hvac_mode == CONST_MODE_COOL:
return self._cool_step or self._heat_step
return self._heat_step or self._cool_step | [
"def",
"target_temperature_step",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tado_zone_data",
".",
"current_hvac_mode",
"==",
"CONST_MODE_COOL",
":",
"return",
"self",
".",
"_cool_step",
"or",
"self",
".",
"_heat_step",
"return",
"self",
".",
"_heat_step",
"or",
"self",
".",
"_cool_step"
] | [
346,
4
] | [
350,
49
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.target_temperature | (self) | Return the temperature we try to reach. | Return the temperature we try to reach. | def target_temperature(self):
"""Return the temperature we try to reach."""
# If the target temperature will be None
# if the device is performing an action
# that does not affect the temperature or
# the device is switching states
return self._tado_zone_data.target_temp or self._tado_zone_data.current_temp | [
"def",
"target_temperature",
"(",
"self",
")",
":",
"# If the target temperature will be None",
"# if the device is performing an action",
"# that does not affect the temperature or",
"# the device is switching states",
"return",
"self",
".",
"_tado_zone_data",
".",
"target_temp",
"or",
"self",
".",
"_tado_zone_data",
".",
"current_temp"
] | [
353,
4
] | [
359,
84
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.set_timer | (self, time_period, temperature=None) | Set the timer on the entity, and temperature if supported. | Set the timer on the entity, and temperature if supported. | def set_timer(self, time_period, temperature=None):
"""Set the timer on the entity, and temperature if supported."""
self._control_hvac(
hvac_mode=CONST_MODE_HEAT, target_temp=temperature, duration=time_period
) | [
"def",
"set_timer",
"(",
"self",
",",
"time_period",
",",
"temperature",
"=",
"None",
")",
":",
"self",
".",
"_control_hvac",
"(",
"hvac_mode",
"=",
"CONST_MODE_HEAT",
",",
"target_temp",
"=",
"temperature",
",",
"duration",
"=",
"time_period",
")"
] | [
361,
4
] | [
366,
9
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.set_temperature | (self, **kwargs) | Set new target temperature. | Set new target temperature. | def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
if self._current_tado_hvac_mode not in (
CONST_MODE_OFF,
CONST_MODE_AUTO,
CONST_MODE_SMART_SCHEDULE,
):
self._control_hvac(target_temp=temperature)
return
new_hvac_mode = CONST_MODE_COOL if self._ac_device else CONST_MODE_HEAT
self._control_hvac(target_temp=temperature, hvac_mode=new_hvac_mode) | [
"def",
"set_temperature",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"temperature",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"if",
"temperature",
"is",
"None",
":",
"return",
"if",
"self",
".",
"_current_tado_hvac_mode",
"not",
"in",
"(",
"CONST_MODE_OFF",
",",
"CONST_MODE_AUTO",
",",
"CONST_MODE_SMART_SCHEDULE",
",",
")",
":",
"self",
".",
"_control_hvac",
"(",
"target_temp",
"=",
"temperature",
")",
"return",
"new_hvac_mode",
"=",
"CONST_MODE_COOL",
"if",
"self",
".",
"_ac_device",
"else",
"CONST_MODE_HEAT",
"self",
".",
"_control_hvac",
"(",
"target_temp",
"=",
"temperature",
",",
"hvac_mode",
"=",
"new_hvac_mode",
")"
] | [
368,
4
] | [
383,
76
] | python | en | ['en', 'ca', 'en'] | True |
TadoClimate.set_hvac_mode | (self, hvac_mode) | Set new target hvac mode. | Set new target hvac mode. | def set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
self._control_hvac(hvac_mode=HA_TO_TADO_HVAC_MODE_MAP[hvac_mode]) | [
"def",
"set_hvac_mode",
"(",
"self",
",",
"hvac_mode",
")",
":",
"self",
".",
"_control_hvac",
"(",
"hvac_mode",
"=",
"HA_TO_TADO_HVAC_MODE_MAP",
"[",
"hvac_mode",
"]",
")"
] | [
385,
4
] | [
388,
73
] | python | da | ['da', 'su', 'en'] | False |
TadoClimate.available | (self) | Return if the device is available. | Return if the device is available. | def available(self):
"""Return if the device is available."""
return self._tado_zone_data.available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tado_zone_data",
".",
"available"
] | [
391,
4
] | [
393,
45
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.min_temp | (self) | Return the minimum temperature. | Return the minimum temperature. | def min_temp(self):
"""Return the minimum temperature."""
if (
self._current_tado_hvac_mode == CONST_MODE_COOL
and self._cool_min_temp is not None
):
return self._cool_min_temp
if self._heat_min_temp is not None:
return self._heat_min_temp
return self._cool_min_temp | [
"def",
"min_temp",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_current_tado_hvac_mode",
"==",
"CONST_MODE_COOL",
"and",
"self",
".",
"_cool_min_temp",
"is",
"not",
"None",
")",
":",
"return",
"self",
".",
"_cool_min_temp",
"if",
"self",
".",
"_heat_min_temp",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_heat_min_temp",
"return",
"self",
".",
"_cool_min_temp"
] | [
396,
4
] | [
406,
34
] | python | en | ['en', 'la', 'en'] | True |
TadoClimate.max_temp | (self) | Return the maximum temperature. | Return the maximum temperature. | def max_temp(self):
"""Return the maximum temperature."""
if (
self._current_tado_hvac_mode == CONST_MODE_HEAT
and self._heat_max_temp is not None
):
return self._heat_max_temp
if self._heat_max_temp is not None:
return self._heat_max_temp
return self._heat_max_temp | [
"def",
"max_temp",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_current_tado_hvac_mode",
"==",
"CONST_MODE_HEAT",
"and",
"self",
".",
"_heat_max_temp",
"is",
"not",
"None",
")",
":",
"return",
"self",
".",
"_heat_max_temp",
"if",
"self",
".",
"_heat_max_temp",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_heat_max_temp",
"return",
"self",
".",
"_heat_max_temp"
] | [
409,
4
] | [
419,
34
] | python | en | ['en', 'la', 'en'] | True |
TadoClimate.swing_mode | (self) | Active swing mode for the device. | Active swing mode for the device. | def swing_mode(self):
"""Active swing mode for the device."""
return self._current_tado_swing_mode | [
"def",
"swing_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_current_tado_swing_mode"
] | [
422,
4
] | [
424,
44
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.swing_modes | (self) | Swing modes for the device. | Swing modes for the device. | def swing_modes(self):
"""Swing modes for the device."""
if self._support_flags & SUPPORT_SWING_MODE:
return [TADO_SWING_ON, TADO_SWING_OFF]
return None | [
"def",
"swing_modes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_support_flags",
"&",
"SUPPORT_SWING_MODE",
":",
"return",
"[",
"TADO_SWING_ON",
",",
"TADO_SWING_OFF",
"]",
"return",
"None"
] | [
427,
4
] | [
431,
19
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate.set_swing_mode | (self, swing_mode) | Set swing modes for the device. | Set swing modes for the device. | def set_swing_mode(self, swing_mode):
"""Set swing modes for the device."""
self._control_hvac(swing_mode=swing_mode) | [
"def",
"set_swing_mode",
"(",
"self",
",",
"swing_mode",
")",
":",
"self",
".",
"_control_hvac",
"(",
"swing_mode",
"=",
"swing_mode",
")"
] | [
433,
4
] | [
435,
49
] | python | en | ['en', 'en', 'en'] | True |
TadoClimate._async_update_zone_data | (self) | Load tado data into zone. | Load tado data into zone. | def _async_update_zone_data(self):
"""Load tado data into zone."""
self._tado_zone_data = self._tado.data["zone"][self.zone_id]
self._current_tado_fan_speed = self._tado_zone_data.current_fan_speed
self._current_tado_hvac_mode = self._tado_zone_data.current_hvac_mode
self._current_tado_hvac_action = self._tado_zone_data.current_hvac_action
self._current_tado_swing_mode = self._tado_zone_data.current_swing_mode | [
"def",
"_async_update_zone_data",
"(",
"self",
")",
":",
"self",
".",
"_tado_zone_data",
"=",
"self",
".",
"_tado",
".",
"data",
"[",
"\"zone\"",
"]",
"[",
"self",
".",
"zone_id",
"]",
"self",
".",
"_current_tado_fan_speed",
"=",
"self",
".",
"_tado_zone_data",
".",
"current_fan_speed",
"self",
".",
"_current_tado_hvac_mode",
"=",
"self",
".",
"_tado_zone_data",
".",
"current_hvac_mode",
"self",
".",
"_current_tado_hvac_action",
"=",
"self",
".",
"_tado_zone_data",
".",
"current_hvac_action",
"self",
".",
"_current_tado_swing_mode",
"=",
"self",
".",
"_tado_zone_data",
".",
"current_swing_mode"
] | [
438,
4
] | [
444,
79
] | python | pt | ['pt', 'it', 'pt'] | True |
TadoClimate._async_update_callback | (self) | Load tado data and update state. | Load tado data and update state. | def _async_update_callback(self):
"""Load tado data and update state."""
self._async_update_zone_data()
self.async_write_ha_state() | [
"def",
"_async_update_callback",
"(",
"self",
")",
":",
"self",
".",
"_async_update_zone_data",
"(",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
447,
4
] | [
450,
35
] | python | en | ['pt', 'en', 'en'] | True |
TadoClimate._control_hvac | (
self,
hvac_mode=None,
target_temp=None,
fan_mode=None,
swing_mode=None,
duration=None,
) | Send new target temperature to Tado. | Send new target temperature to Tado. | def _control_hvac(
self,
hvac_mode=None,
target_temp=None,
fan_mode=None,
swing_mode=None,
duration=None,
):
"""Send new target temperature to Tado."""
if hvac_mode:
self._current_tado_hvac_mode = hvac_mode
if target_temp:
self._target_temp = target_temp
if fan_mode:
self._current_tado_fan_speed = fan_mode
if swing_mode:
self._current_tado_swing_mode = swing_mode
self._normalize_target_temp_for_hvac_mode()
# tado does not permit setting the fan speed to
# off, you must turn off the device
if (
self._current_tado_fan_speed == CONST_FAN_OFF
and self._current_tado_hvac_mode != CONST_MODE_OFF
):
self._current_tado_fan_speed = CONST_FAN_AUTO
if self._current_tado_hvac_mode == CONST_MODE_OFF:
_LOGGER.debug(
"Switching to OFF for zone %s (%d)", self.zone_name, self.zone_id
)
self._tado.set_zone_off(self.zone_id, CONST_OVERLAY_MANUAL, self.zone_type)
return
if self._current_tado_hvac_mode == CONST_MODE_SMART_SCHEDULE:
_LOGGER.debug(
"Switching to SMART_SCHEDULE for zone %s (%d)",
self.zone_name,
self.zone_id,
)
self._tado.reset_zone_overlay(self.zone_id)
return
_LOGGER.debug(
"Switching to %s for zone %s (%d) with temperature %s °C and duration %s",
self._current_tado_hvac_mode,
self.zone_name,
self.zone_id,
self._target_temp,
duration,
)
overlay_mode = CONST_OVERLAY_MANUAL
if duration:
overlay_mode = CONST_OVERLAY_TIMER
elif self._tado.fallback:
# Fallback to Smart Schedule at next Schedule switch if we have fallback enabled
overlay_mode = CONST_OVERLAY_TADO_MODE
temperature_to_send = self._target_temp
if self._current_tado_hvac_mode in TADO_MODES_WITH_NO_TEMP_SETTING:
# A temperature cannot be passed with these modes
temperature_to_send = None
fan_speed = None
if self._support_flags & SUPPORT_FAN_MODE:
fan_speed = self._current_tado_fan_speed
swing = None
if self._support_flags & SUPPORT_SWING_MODE:
swing = self._current_tado_swing_mode
self._tado.set_zone_overlay(
zone_id=self.zone_id,
overlay_mode=overlay_mode, # What to do when the period ends
temperature=temperature_to_send,
duration=duration,
device_type=self.zone_type,
mode=self._current_tado_hvac_mode,
fan_speed=fan_speed, # api defaults to not sending fanSpeed if None specified
swing=swing, # api defaults to not sending swing if None specified
) | [
"def",
"_control_hvac",
"(",
"self",
",",
"hvac_mode",
"=",
"None",
",",
"target_temp",
"=",
"None",
",",
"fan_mode",
"=",
"None",
",",
"swing_mode",
"=",
"None",
",",
"duration",
"=",
"None",
",",
")",
":",
"if",
"hvac_mode",
":",
"self",
".",
"_current_tado_hvac_mode",
"=",
"hvac_mode",
"if",
"target_temp",
":",
"self",
".",
"_target_temp",
"=",
"target_temp",
"if",
"fan_mode",
":",
"self",
".",
"_current_tado_fan_speed",
"=",
"fan_mode",
"if",
"swing_mode",
":",
"self",
".",
"_current_tado_swing_mode",
"=",
"swing_mode",
"self",
".",
"_normalize_target_temp_for_hvac_mode",
"(",
")",
"# tado does not permit setting the fan speed to",
"# off, you must turn off the device",
"if",
"(",
"self",
".",
"_current_tado_fan_speed",
"==",
"CONST_FAN_OFF",
"and",
"self",
".",
"_current_tado_hvac_mode",
"!=",
"CONST_MODE_OFF",
")",
":",
"self",
".",
"_current_tado_fan_speed",
"=",
"CONST_FAN_AUTO",
"if",
"self",
".",
"_current_tado_hvac_mode",
"==",
"CONST_MODE_OFF",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Switching to OFF for zone %s (%d)\"",
",",
"self",
".",
"zone_name",
",",
"self",
".",
"zone_id",
")",
"self",
".",
"_tado",
".",
"set_zone_off",
"(",
"self",
".",
"zone_id",
",",
"CONST_OVERLAY_MANUAL",
",",
"self",
".",
"zone_type",
")",
"return",
"if",
"self",
".",
"_current_tado_hvac_mode",
"==",
"CONST_MODE_SMART_SCHEDULE",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Switching to SMART_SCHEDULE for zone %s (%d)\"",
",",
"self",
".",
"zone_name",
",",
"self",
".",
"zone_id",
",",
")",
"self",
".",
"_tado",
".",
"reset_zone_overlay",
"(",
"self",
".",
"zone_id",
")",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Switching to %s for zone %s (%d) with temperature %s °C and duration %s\",",
"",
"self",
".",
"_current_tado_hvac_mode",
",",
"self",
".",
"zone_name",
",",
"self",
".",
"zone_id",
",",
"self",
".",
"_target_temp",
",",
"duration",
",",
")",
"overlay_mode",
"=",
"CONST_OVERLAY_MANUAL",
"if",
"duration",
":",
"overlay_mode",
"=",
"CONST_OVERLAY_TIMER",
"elif",
"self",
".",
"_tado",
".",
"fallback",
":",
"# Fallback to Smart Schedule at next Schedule switch if we have fallback enabled",
"overlay_mode",
"=",
"CONST_OVERLAY_TADO_MODE",
"temperature_to_send",
"=",
"self",
".",
"_target_temp",
"if",
"self",
".",
"_current_tado_hvac_mode",
"in",
"TADO_MODES_WITH_NO_TEMP_SETTING",
":",
"# A temperature cannot be passed with these modes",
"temperature_to_send",
"=",
"None",
"fan_speed",
"=",
"None",
"if",
"self",
".",
"_support_flags",
"&",
"SUPPORT_FAN_MODE",
":",
"fan_speed",
"=",
"self",
".",
"_current_tado_fan_speed",
"swing",
"=",
"None",
"if",
"self",
".",
"_support_flags",
"&",
"SUPPORT_SWING_MODE",
":",
"swing",
"=",
"self",
".",
"_current_tado_swing_mode",
"self",
".",
"_tado",
".",
"set_zone_overlay",
"(",
"zone_id",
"=",
"self",
".",
"zone_id",
",",
"overlay_mode",
"=",
"overlay_mode",
",",
"# What to do when the period ends",
"temperature",
"=",
"temperature_to_send",
",",
"duration",
"=",
"duration",
",",
"device_type",
"=",
"self",
".",
"zone_type",
",",
"mode",
"=",
"self",
".",
"_current_tado_hvac_mode",
",",
"fan_speed",
"=",
"fan_speed",
",",
"# api defaults to not sending fanSpeed if None specified",
"swing",
"=",
"swing",
",",
"# api defaults to not sending swing if None specified",
")"
] | [
468,
4
] | [
553,
9
] | python | en | ['en', 'es', 'en'] | True |
test_show_user_form | (hass: HomeAssistant) | Test that the user set up form is served. | Test that the user set up form is served. | async def test_show_user_form(hass: HomeAssistant) -> None:
"""Test that the user set up form is served."""
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": SOURCE_USER},
)
assert result["step_id"] == "user"
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM | [
"async",
"def",
"test_show_user_form",
"(",
"hass",
":",
"HomeAssistant",
")",
"->",
"None",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"config_flow",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
")",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM"
] | [
14,
0
] | [
22,
61
] | python | en | ['en', 'en', 'en'] | True |
test_user_device_exists_abort | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test we abort flow if Agent device already configured. | Test we abort flow if Agent device already configured. | async def test_user_device_exists_abort(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort flow if Agent device already configured."""
await init_integration(hass, aioclient_mock)
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": SOURCE_USER},
data={CONF_HOST: "example.local", CONF_PORT: 8090},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT | [
"async",
"def",
"test_user_device_exists_abort",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"config_flow",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"example.local\"",
",",
"CONF_PORT",
":",
"8090",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT"
] | [
25,
0
] | [
37,
62
] | python | en | ['fr', 'en', 'en'] | True |
test_connection_error | (hass: HomeAssistant, aioclient_mock) | Test we show user form on Agent connection error. | Test we show user form on Agent connection error. | async def test_connection_error(hass: HomeAssistant, aioclient_mock) -> None:
"""Test we show user form on Agent connection error."""
aioclient_mock.get("http://example.local:8090/command.cgi?cmd=getStatus", text="")
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": SOURCE_USER},
data={CONF_HOST: "example.local", CONF_PORT: 8090},
)
assert result["errors"] == {"base": "cannot_connect"}
assert result["step_id"] == "user"
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM | [
"async",
"def",
"test_connection_error",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
")",
"->",
"None",
":",
"aioclient_mock",
".",
"get",
"(",
"\"http://example.local:8090/command.cgi?cmd=getStatus\"",
",",
"text",
"=",
"\"\"",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"config_flow",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"example.local\"",
",",
"CONF_PORT",
":",
"8090",
"}",
",",
")",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM"
] | [
40,
0
] | [
53,
61
] | python | en | ['en', 'en', 'en'] | True |
test_full_user_flow_implementation | (
hass: HomeAssistant, aioclient_mock
) | Test the full manual user flow from start to finish. | Test the full manual user flow from start to finish. | async def test_full_user_flow_implementation(
hass: HomeAssistant, aioclient_mock
) -> None:
"""Test the full manual user flow from start to finish."""
aioclient_mock.get(
"http://example.local:8090/command.cgi?cmd=getStatus",
text=load_fixture("agent_dvr/status.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
"http://example.local:8090/command.cgi?cmd=getObjects",
text=load_fixture("agent_dvr/objects.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": SOURCE_USER},
)
assert result["step_id"] == "user"
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: "example.local", CONF_PORT: 8090}
)
assert result["data"][CONF_HOST] == "example.local"
assert result["data"][CONF_PORT] == 8090
assert result["data"][SERVER_URL] == "http://example.local:8090/"
assert result["title"] == "DESKTOP"
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
entries = hass.config_entries.async_entries(config_flow.DOMAIN)
assert entries[0].unique_id == "c0715bba-c2d0-48ef-9e3e-bc81c9ea4447" | [
"async",
"def",
"test_full_user_flow_implementation",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
")",
"->",
"None",
":",
"aioclient_mock",
".",
"get",
"(",
"\"http://example.local:8090/command.cgi?cmd=getStatus\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"agent_dvr/status.json\"",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"CONTENT_TYPE_JSON",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://example.local:8090/command.cgi?cmd=getObjects\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"agent_dvr/objects.json\"",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"CONTENT_TYPE_JSON",
"}",
",",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"config_flow",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
")",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"example.local\"",
",",
"CONF_PORT",
":",
"8090",
"}",
")",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"\"example.local\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PORT",
"]",
"==",
"8090",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"SERVER_URL",
"]",
"==",
"\"http://example.local:8090/\"",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"DESKTOP\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"entries",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"config_flow",
".",
"DOMAIN",
")",
"assert",
"entries",
"[",
"0",
"]",
".",
"unique_id",
"==",
"\"c0715bba-c2d0-48ef-9e3e-bc81c9ea4447\""
] | [
56,
0
] | [
91,
73
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistantType, config: Dict) | Set up the Sonarr component. | Set up the Sonarr component. | async def async_setup(hass: HomeAssistantType, config: Dict) -> bool:
"""Set up the Sonarr component."""
hass.data.setdefault(DOMAIN, {})
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistantType",
",",
"config",
":",
"Dict",
")",
"->",
"bool",
":",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"return",
"True"
] | [
42,
0
] | [
45,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass: HomeAssistantType, entry: ConfigEntry) | Set up Sonarr from a config entry. | Set up Sonarr from a config entry. | async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
"""Set up Sonarr from a config entry."""
if not entry.options:
options = {
CONF_UPCOMING_DAYS: entry.data.get(
CONF_UPCOMING_DAYS, DEFAULT_UPCOMING_DAYS
),
CONF_WANTED_MAX_ITEMS: entry.data.get(
CONF_WANTED_MAX_ITEMS, DEFAULT_WANTED_MAX_ITEMS
),
}
hass.config_entries.async_update_entry(entry, options=options)
sonarr = Sonarr(
host=entry.data[CONF_HOST],
port=entry.data[CONF_PORT],
api_key=entry.data[CONF_API_KEY],
base_path=entry.data[CONF_BASE_PATH],
session=async_get_clientsession(hass),
tls=entry.data[CONF_SSL],
verify_ssl=entry.data[CONF_VERIFY_SSL],
)
try:
await sonarr.update()
except SonarrAccessRestricted:
_async_start_reauth(hass, entry)
return False
except SonarrError as err:
raise ConfigEntryNotReady from err
undo_listener = entry.add_update_listener(_async_update_listener)
hass.data[DOMAIN][entry.entry_id] = {
DATA_SONARR: sonarr,
DATA_UNDO_UPDATE_LISTENER: undo_listener,
}
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"bool",
":",
"if",
"not",
"entry",
".",
"options",
":",
"options",
"=",
"{",
"CONF_UPCOMING_DAYS",
":",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_UPCOMING_DAYS",
",",
"DEFAULT_UPCOMING_DAYS",
")",
",",
"CONF_WANTED_MAX_ITEMS",
":",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_WANTED_MAX_ITEMS",
",",
"DEFAULT_WANTED_MAX_ITEMS",
")",
",",
"}",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"entry",
",",
"options",
"=",
"options",
")",
"sonarr",
"=",
"Sonarr",
"(",
"host",
"=",
"entry",
".",
"data",
"[",
"CONF_HOST",
"]",
",",
"port",
"=",
"entry",
".",
"data",
"[",
"CONF_PORT",
"]",
",",
"api_key",
"=",
"entry",
".",
"data",
"[",
"CONF_API_KEY",
"]",
",",
"base_path",
"=",
"entry",
".",
"data",
"[",
"CONF_BASE_PATH",
"]",
",",
"session",
"=",
"async_get_clientsession",
"(",
"hass",
")",
",",
"tls",
"=",
"entry",
".",
"data",
"[",
"CONF_SSL",
"]",
",",
"verify_ssl",
"=",
"entry",
".",
"data",
"[",
"CONF_VERIFY_SSL",
"]",
",",
")",
"try",
":",
"await",
"sonarr",
".",
"update",
"(",
")",
"except",
"SonarrAccessRestricted",
":",
"_async_start_reauth",
"(",
"hass",
",",
"entry",
")",
"return",
"False",
"except",
"SonarrError",
"as",
"err",
":",
"raise",
"ConfigEntryNotReady",
"from",
"err",
"undo_listener",
"=",
"entry",
".",
"add_update_listener",
"(",
"_async_update_listener",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"=",
"{",
"DATA_SONARR",
":",
"sonarr",
",",
"DATA_UNDO_UPDATE_LISTENER",
":",
"undo_listener",
",",
"}",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"component",
")",
")",
"return",
"True"
] | [
48,
0
] | [
91,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass: HomeAssistantType, entry: ConfigEntry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
hass.data[DOMAIN][entry.entry_id][DATA_UNDO_UPDATE_LISTENER]()
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"bool",
":",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"entry",
",",
"component",
")",
"for",
"component",
"in",
"PLATFORMS",
"]",
")",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"DATA_UNDO_UPDATE_LISTENER",
"]",
"(",
")",
"if",
"unload_ok",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"entry",
".",
"entry_id",
")",
"return",
"unload_ok"
] | [
94,
0
] | [
110,
20
] | python | en | ['en', 'es', 'en'] | True |
_async_update_listener | (hass: HomeAssistantType, entry: ConfigEntry) | Handle options update. | Handle options update. | async def _async_update_listener(hass: HomeAssistantType, entry: ConfigEntry) -> None:
"""Handle options update."""
await hass.config_entries.async_reload(entry.entry_id) | [
"async",
"def",
"_async_update_listener",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"None",
":",
"await",
"hass",
".",
"config_entries",
".",
"async_reload",
"(",
"entry",
".",
"entry_id",
")"
] | [
124,
0
] | [
126,
58
] | python | en | ['en', 'nl', 'en'] | True |
SonarrEntity.__init__ | (
self,
*,
sonarr: Sonarr,
entry_id: str,
device_id: str,
name: str,
icon: str,
enabled_default: bool = True,
) | Initialize the Sonar entity. | Initialize the Sonar entity. | def __init__(
self,
*,
sonarr: Sonarr,
entry_id: str,
device_id: str,
name: str,
icon: str,
enabled_default: bool = True,
) -> None:
"""Initialize the Sonar entity."""
self._entry_id = entry_id
self._device_id = device_id
self._enabled_default = enabled_default
self._icon = icon
self._name = name
self.sonarr = sonarr | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"sonarr",
":",
"Sonarr",
",",
"entry_id",
":",
"str",
",",
"device_id",
":",
"str",
",",
"name",
":",
"str",
",",
"icon",
":",
"str",
",",
"enabled_default",
":",
"bool",
"=",
"True",
",",
")",
"->",
"None",
":",
"self",
".",
"_entry_id",
"=",
"entry_id",
"self",
".",
"_device_id",
"=",
"device_id",
"self",
".",
"_enabled_default",
"=",
"enabled_default",
"self",
".",
"_icon",
"=",
"icon",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"sonarr",
"=",
"sonarr"
] | [
132,
4
] | [
148,
28
] | python | en | ['en', 'en', 'en'] | True |
SonarrEntity.name | (self) | Return the name of the entity. | Return the name of the entity. | def name(self) -> str:
"""Return the name of the entity."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
151,
4
] | [
153,
25
] | python | en | ['en', 'en', 'en'] | True |
SonarrEntity.icon | (self) | Return the mdi icon of the entity. | Return the mdi icon of the entity. | def icon(self) -> str:
"""Return the mdi icon of the entity."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_icon"
] | [
156,
4
] | [
158,
25
] | python | en | ['en', 'en', 'en'] | True |
SonarrEntity.entity_registry_enabled_default | (self) | Return if the entity should be enabled when first added to the entity registry. | Return if the entity should be enabled when first added to the entity registry. | def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self._enabled_default | [
"def",
"entity_registry_enabled_default",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_enabled_default"
] | [
161,
4
] | [
163,
36
] | python | en | ['en', 'en', 'en'] | True |
SonarrEntity.device_info | (self) | Return device information about the application. | Return device information about the application. | def device_info(self) -> Dict[str, Any]:
"""Return device information about the application."""
if self._device_id is None:
return None
return {
ATTR_IDENTIFIERS: {(DOMAIN, self._device_id)},
ATTR_NAME: "Activity Sensor",
ATTR_MANUFACTURER: "Sonarr",
ATTR_SOFTWARE_VERSION: self.sonarr.app.info.version,
"entry_type": "service",
} | [
"def",
"device_info",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"self",
".",
"_device_id",
"is",
"None",
":",
"return",
"None",
"return",
"{",
"ATTR_IDENTIFIERS",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"_device_id",
")",
"}",
",",
"ATTR_NAME",
":",
"\"Activity Sensor\"",
",",
"ATTR_MANUFACTURER",
":",
"\"Sonarr\"",
",",
"ATTR_SOFTWARE_VERSION",
":",
"self",
".",
"sonarr",
".",
"app",
".",
"info",
".",
"version",
",",
"\"entry_type\"",
":",
"\"service\"",
",",
"}"
] | [
166,
4
] | [
177,
9
] | python | en | ['en', 'en', 'en'] | True |
mock_daikin | () | Mock pydaikin. | Mock pydaikin. | def mock_daikin():
"""Mock pydaikin."""
async def mock_daikin_factory(*args, **kwargs):
"""Mock the init function in pydaikin."""
return Appliance
with patch("homeassistant.components.daikin.config_flow.Appliance") as Appliance:
type(Appliance).mac = PropertyMock(return_value="AABBCCDDEEFF")
Appliance.factory.side_effect = mock_daikin_factory
yield Appliance | [
"def",
"mock_daikin",
"(",
")",
":",
"async",
"def",
"mock_daikin_factory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Mock the init function in pydaikin.\"\"\"",
"return",
"Appliance",
"with",
"patch",
"(",
"\"homeassistant.components.daikin.config_flow.Appliance\"",
")",
"as",
"Appliance",
":",
"type",
"(",
"Appliance",
")",
".",
"mac",
"=",
"PropertyMock",
"(",
"return_value",
"=",
"\"AABBCCDDEEFF\"",
")",
"Appliance",
".",
"factory",
".",
"side_effect",
"=",
"mock_daikin_factory",
"yield",
"Appliance"
] | [
30,
0
] | [
40,
23
] | python | en | ['lt', 'tr', 'en'] | False |
mock_daikin_discovery | () | Mock pydaikin Discovery. | Mock pydaikin Discovery. | def mock_daikin_discovery():
"""Mock pydaikin Discovery."""
with patch("homeassistant.components.daikin.config_flow.Discovery") as Discovery:
Discovery().poll.return_value = {
"127.0.01": {"mac": "AABBCCDDEEFF", "id": "test"}
}.values()
yield Discovery | [
"def",
"mock_daikin_discovery",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.daikin.config_flow.Discovery\"",
")",
"as",
"Discovery",
":",
"Discovery",
"(",
")",
".",
"poll",
".",
"return_value",
"=",
"{",
"\"127.0.01\"",
":",
"{",
"\"mac\"",
":",
"\"AABBCCDDEEFF\"",
",",
"\"id\"",
":",
"\"test\"",
"}",
"}",
".",
"values",
"(",
")",
"yield",
"Discovery"
] | [
44,
0
] | [
50,
23
] | python | en | ['en', 'fy', 'en'] | True |
test_user | (hass, mock_daikin) | Test user config. | Test user config. | async def test_user(hass, mock_daikin):
"""Test user config."""
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_USER},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_USER},
data={CONF_HOST: HOST},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][KEY_MAC] == MAC | [
"async",
"def",
"test_user",
"(",
"hass",
",",
"mock_daikin",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"HOST",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"KEY_MAC",
"]",
"==",
"MAC"
] | [
53,
0
] | [
71,
41
] | python | en | ['en', 'da', 'en'] | True |
test_abort_if_already_setup | (hass, mock_daikin) | Test we abort if Daikin is already setup. | Test we abort if Daikin is already setup. | async def test_abort_if_already_setup(hass, mock_daikin):
"""Test we abort if Daikin is already setup."""
MockConfigEntry(domain="daikin", unique_id=MAC).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_USER},
data={CONF_HOST: HOST, KEY_MAC: MAC},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_abort_if_already_setup",
"(",
"hass",
",",
"mock_daikin",
")",
":",
"MockConfigEntry",
"(",
"domain",
"=",
"\"daikin\"",
",",
"unique_id",
"=",
"MAC",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"HOST",
",",
"KEY_MAC",
":",
"MAC",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
74,
0
] | [
84,
51
] | python | en | ['en', 'de', 'en'] | True |
test_import | (hass, mock_daikin) | Test import step. | Test import step. | async def test_import(hass, mock_daikin):
"""Test import step."""
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_IMPORT},
data={},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_IMPORT},
data={CONF_HOST: HOST},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"][CONF_HOST] == HOST
assert result["data"][KEY_MAC] == MAC | [
"async",
"def",
"test_import",
"(",
"hass",
",",
"mock_daikin",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"{",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"HOST",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"KEY_MAC",
"]",
"==",
"MAC"
] | [
87,
0
] | [
105,
41
] | python | de | ['de', 'sd', 'en'] | False |
test_device_abort | (hass, mock_daikin, s_effect, reason) | Test device abort. | Test device abort. | async def test_device_abort(hass, mock_daikin, s_effect, reason):
"""Test device abort."""
mock_daikin.factory.side_effect = s_effect
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_USER},
data={CONF_HOST: HOST, KEY_MAC: MAC},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"base": reason}
assert result["step_id"] == "user" | [
"async",
"def",
"test_device_abort",
"(",
"hass",
",",
"mock_daikin",
",",
"s_effect",
",",
"reason",
")",
":",
"mock_daikin",
".",
"factory",
".",
"side_effect",
"=",
"s_effect",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"HOST",
",",
"KEY_MAC",
":",
"MAC",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"reason",
"}",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\""
] | [
117,
0
] | [
128,
38
] | python | de | ['fr', 'de', 'en'] | False |
test_discovery_zeroconf | (
hass, mock_daikin, mock_daikin_discovery, source, data, unique_id
) | Test discovery/zeroconf step. | Test discovery/zeroconf step. | async def test_discovery_zeroconf(
hass, mock_daikin, mock_daikin_discovery, source, data, unique_id
):
"""Test discovery/zeroconf step."""
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": source},
data=data,
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
MockConfigEntry(domain="daikin", unique_id=unique_id).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": SOURCE_USER, "unique_id": unique_id},
data={CONF_HOST: HOST},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
result = await hass.config_entries.flow.async_init(
"daikin",
context={"source": source},
data=data,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_in_progress" | [
"async",
"def",
"test_discovery_zeroconf",
"(",
"hass",
",",
"mock_daikin",
",",
"mock_daikin_discovery",
",",
"source",
",",
"data",
",",
"unique_id",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"source",
"}",
",",
"data",
"=",
"data",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"MockConfigEntry",
"(",
"domain",
"=",
"\"daikin\"",
",",
"unique_id",
"=",
"unique_id",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
",",
"\"unique_id\"",
":",
"unique_id",
"}",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"HOST",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"daikin\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"source",
"}",
",",
"data",
"=",
"data",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_in_progress\""
] | [
138,
0
] | [
167,
52
] | python | de | ['de', 'pl', 'en'] | False |
get_service | (hass, config, discovery_info=None) | Get the RESTful notification service. | Get the RESTful notification service. | def get_service(hass, config, discovery_info=None):
"""Get the RESTful notification service."""
setup_reload_service(hass, DOMAIN, PLATFORMS)
resource = config.get(CONF_RESOURCE)
method = config.get(CONF_METHOD)
headers = config.get(CONF_HEADERS)
params = config.get(CONF_PARAMS)
message_param_name = config.get(CONF_MESSAGE_PARAMETER_NAME)
title_param_name = config.get(CONF_TITLE_PARAMETER_NAME)
target_param_name = config.get(CONF_TARGET_PARAMETER_NAME)
data = config.get(CONF_DATA)
data_template = config.get(CONF_DATA_TEMPLATE)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
verify_ssl = config.get(CONF_VERIFY_SSL)
if username and password:
if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
auth = requests.auth.HTTPDigestAuth(username, password)
else:
auth = requests.auth.HTTPBasicAuth(username, password)
else:
auth = None
return RestNotificationService(
hass,
resource,
method,
headers,
params,
message_param_name,
title_param_name,
target_param_name,
data,
data_template,
auth,
verify_ssl,
) | [
"def",
"get_service",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"setup_reload_service",
"(",
"hass",
",",
"DOMAIN",
",",
"PLATFORMS",
")",
"resource",
"=",
"config",
".",
"get",
"(",
"CONF_RESOURCE",
")",
"method",
"=",
"config",
".",
"get",
"(",
"CONF_METHOD",
")",
"headers",
"=",
"config",
".",
"get",
"(",
"CONF_HEADERS",
")",
"params",
"=",
"config",
".",
"get",
"(",
"CONF_PARAMS",
")",
"message_param_name",
"=",
"config",
".",
"get",
"(",
"CONF_MESSAGE_PARAMETER_NAME",
")",
"title_param_name",
"=",
"config",
".",
"get",
"(",
"CONF_TITLE_PARAMETER_NAME",
")",
"target_param_name",
"=",
"config",
".",
"get",
"(",
"CONF_TARGET_PARAMETER_NAME",
")",
"data",
"=",
"config",
".",
"get",
"(",
"CONF_DATA",
")",
"data_template",
"=",
"config",
".",
"get",
"(",
"CONF_DATA_TEMPLATE",
")",
"username",
"=",
"config",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"verify_ssl",
"=",
"config",
".",
"get",
"(",
"CONF_VERIFY_SSL",
")",
"if",
"username",
"and",
"password",
":",
"if",
"config",
".",
"get",
"(",
"CONF_AUTHENTICATION",
")",
"==",
"HTTP_DIGEST_AUTHENTICATION",
":",
"auth",
"=",
"requests",
".",
"auth",
".",
"HTTPDigestAuth",
"(",
"username",
",",
"password",
")",
"else",
":",
"auth",
"=",
"requests",
".",
"auth",
".",
"HTTPBasicAuth",
"(",
"username",
",",
"password",
")",
"else",
":",
"auth",
"=",
"None",
"return",
"RestNotificationService",
"(",
"hass",
",",
"resource",
",",
"method",
",",
"headers",
",",
"params",
",",
"message_param_name",
",",
"title_param_name",
",",
"target_param_name",
",",
"data",
",",
"data_template",
",",
"auth",
",",
"verify_ssl",
",",
")"
] | [
72,
0
] | [
110,
5
] | python | en | ['en', 'en', 'en'] | True |
RestNotificationService.__init__ | (
self,
hass,
resource,
method,
headers,
params,
message_param_name,
title_param_name,
target_param_name,
data,
data_template,
auth,
verify_ssl,
) | Initialize the service. | Initialize the service. | def __init__(
self,
hass,
resource,
method,
headers,
params,
message_param_name,
title_param_name,
target_param_name,
data,
data_template,
auth,
verify_ssl,
):
"""Initialize the service."""
self._resource = resource
self._hass = hass
self._method = method.upper()
self._headers = headers
self._params = params
self._message_param_name = message_param_name
self._title_param_name = title_param_name
self._target_param_name = target_param_name
self._data = data
self._data_template = data_template
self._auth = auth
self._verify_ssl = verify_ssl | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"resource",
",",
"method",
",",
"headers",
",",
"params",
",",
"message_param_name",
",",
"title_param_name",
",",
"target_param_name",
",",
"data",
",",
"data_template",
",",
"auth",
",",
"verify_ssl",
",",
")",
":",
"self",
".",
"_resource",
"=",
"resource",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_method",
"=",
"method",
".",
"upper",
"(",
")",
"self",
".",
"_headers",
"=",
"headers",
"self",
".",
"_params",
"=",
"params",
"self",
".",
"_message_param_name",
"=",
"message_param_name",
"self",
".",
"_title_param_name",
"=",
"title_param_name",
"self",
".",
"_target_param_name",
"=",
"target_param_name",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_data_template",
"=",
"data_template",
"self",
".",
"_auth",
"=",
"auth",
"self",
".",
"_verify_ssl",
"=",
"verify_ssl"
] | [
116,
4
] | [
143,
37
] | python | en | ['en', 'en', 'en'] | True |
RestNotificationService.send_message | (self, message="", **kwargs) | Send a message to a user. | Send a message to a user. | def send_message(self, message="", **kwargs):
"""Send a message to a user."""
data = {self._message_param_name: message}
if self._title_param_name is not None:
data[self._title_param_name] = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
if self._target_param_name is not None and ATTR_TARGET in kwargs:
# Target is a list as of 0.29 and we don't want to break existing
# integrations, so just return the first target in the list.
data[self._target_param_name] = kwargs[ATTR_TARGET][0]
if self._data:
data.update(self._data)
elif self._data_template:
kwargs[ATTR_MESSAGE] = message
def _data_template_creator(value):
"""Recursive template creator helper function."""
if isinstance(value, list):
return [_data_template_creator(item) for item in value]
if isinstance(value, dict):
return {
key: _data_template_creator(item) for key, item in value.items()
}
value.hass = self._hass
return value.async_render(kwargs, parse_result=False)
data.update(_data_template_creator(self._data_template))
if self._method == "POST":
response = requests.post(
self._resource,
headers=self._headers,
params=self._params,
data=data,
timeout=10,
auth=self._auth,
verify=self._verify_ssl,
)
elif self._method == "POST_JSON":
response = requests.post(
self._resource,
headers=self._headers,
params=self._params,
json=data,
timeout=10,
auth=self._auth,
verify=self._verify_ssl,
)
else: # default GET
response = requests.get(
self._resource,
headers=self._headers,
params=self._params.update(data),
timeout=10,
auth=self._auth,
verify=self._verify_ssl,
)
if (
response.status_code >= HTTP_INTERNAL_SERVER_ERROR
and response.status_code < 600
):
_LOGGER.exception(
"Server error. Response %d: %s:", response.status_code, response.reason
)
elif (
response.status_code >= HTTP_BAD_REQUEST
and response.status_code < HTTP_INTERNAL_SERVER_ERROR
):
_LOGGER.exception(
"Client error. Response %d: %s:", response.status_code, response.reason
)
elif response.status_code >= HTTP_OK and response.status_code < 300:
_LOGGER.debug(
"Success. Response %d: %s:", response.status_code, response.reason
)
else:
_LOGGER.debug("Response %d: %s:", response.status_code, response.reason) | [
"def",
"send_message",
"(",
"self",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"self",
".",
"_message_param_name",
":",
"message",
"}",
"if",
"self",
".",
"_title_param_name",
"is",
"not",
"None",
":",
"data",
"[",
"self",
".",
"_title_param_name",
"]",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TITLE",
",",
"ATTR_TITLE_DEFAULT",
")",
"if",
"self",
".",
"_target_param_name",
"is",
"not",
"None",
"and",
"ATTR_TARGET",
"in",
"kwargs",
":",
"# Target is a list as of 0.29 and we don't want to break existing",
"# integrations, so just return the first target in the list.",
"data",
"[",
"self",
".",
"_target_param_name",
"]",
"=",
"kwargs",
"[",
"ATTR_TARGET",
"]",
"[",
"0",
"]",
"if",
"self",
".",
"_data",
":",
"data",
".",
"update",
"(",
"self",
".",
"_data",
")",
"elif",
"self",
".",
"_data_template",
":",
"kwargs",
"[",
"ATTR_MESSAGE",
"]",
"=",
"message",
"def",
"_data_template_creator",
"(",
"value",
")",
":",
"\"\"\"Recursive template creator helper function.\"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"_data_template_creator",
"(",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"{",
"key",
":",
"_data_template_creator",
"(",
"item",
")",
"for",
"key",
",",
"item",
"in",
"value",
".",
"items",
"(",
")",
"}",
"value",
".",
"hass",
"=",
"self",
".",
"_hass",
"return",
"value",
".",
"async_render",
"(",
"kwargs",
",",
"parse_result",
"=",
"False",
")",
"data",
".",
"update",
"(",
"_data_template_creator",
"(",
"self",
".",
"_data_template",
")",
")",
"if",
"self",
".",
"_method",
"==",
"\"POST\"",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_resource",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"params",
"=",
"self",
".",
"_params",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"10",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"verify",
"=",
"self",
".",
"_verify_ssl",
",",
")",
"elif",
"self",
".",
"_method",
"==",
"\"POST_JSON\"",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_resource",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"params",
"=",
"self",
".",
"_params",
",",
"json",
"=",
"data",
",",
"timeout",
"=",
"10",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"verify",
"=",
"self",
".",
"_verify_ssl",
",",
")",
"else",
":",
"# default GET",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_resource",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"params",
"=",
"self",
".",
"_params",
".",
"update",
"(",
"data",
")",
",",
"timeout",
"=",
"10",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"verify",
"=",
"self",
".",
"_verify_ssl",
",",
")",
"if",
"(",
"response",
".",
"status_code",
">=",
"HTTP_INTERNAL_SERVER_ERROR",
"and",
"response",
".",
"status_code",
"<",
"600",
")",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Server error. Response %d: %s:\"",
",",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")",
"elif",
"(",
"response",
".",
"status_code",
">=",
"HTTP_BAD_REQUEST",
"and",
"response",
".",
"status_code",
"<",
"HTTP_INTERNAL_SERVER_ERROR",
")",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Client error. Response %d: %s:\"",
",",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")",
"elif",
"response",
".",
"status_code",
">=",
"HTTP_OK",
"and",
"response",
".",
"status_code",
"<",
"300",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Success. Response %d: %s:\"",
",",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Response %d: %s:\"",
",",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")"
] | [
145,
4
] | [
224,
84
] | python | en | ['en', 'en', 'en'] | True |
block_digonal_matrix | (*blocks) |
Construct block diagonal matrix
:param blocks: blocks of block diagonal matrix
:param device
:param dtype
:return: block diagonal matrix
|
Construct block diagonal matrix
:param blocks: blocks of block diagonal matrix
:param device
:param dtype
:return: block diagonal matrix
| def block_digonal_matrix(*blocks):
"""
Construct block diagonal matrix
:param blocks: blocks of block diagonal matrix
:param device
:param dtype
:return: block diagonal matrix
"""
assert len(blocks) > 0
rows = [block.shape[0] for block in blocks]
cols = [block.shape[1] for block in blocks]
out = torch.zeros((sum(rows), sum(cols)),
device=blocks[0].device,
dtype=blocks[0].dtype)
cur_row = 0
cur_col = 0
for block, row, col in zip(blocks, rows, cols):
out[cur_row:(cur_row + row), cur_col:(cur_col + col)] = block
cur_row += row
cur_col += col
return out | [
"def",
"block_digonal_matrix",
"(",
"*",
"blocks",
")",
":",
"assert",
"len",
"(",
"blocks",
")",
">",
"0",
"rows",
"=",
"[",
"block",
".",
"shape",
"[",
"0",
"]",
"for",
"block",
"in",
"blocks",
"]",
"cols",
"=",
"[",
"block",
".",
"shape",
"[",
"1",
"]",
"for",
"block",
"in",
"blocks",
"]",
"out",
"=",
"torch",
".",
"zeros",
"(",
"(",
"sum",
"(",
"rows",
")",
",",
"sum",
"(",
"cols",
")",
")",
",",
"device",
"=",
"blocks",
"[",
"0",
"]",
".",
"device",
",",
"dtype",
"=",
"blocks",
"[",
"0",
"]",
".",
"dtype",
")",
"cur_row",
"=",
"0",
"cur_col",
"=",
"0",
"for",
"block",
",",
"row",
",",
"col",
"in",
"zip",
"(",
"blocks",
",",
"rows",
",",
"cols",
")",
":",
"out",
"[",
"cur_row",
":",
"(",
"cur_row",
"+",
"row",
")",
",",
"cur_col",
":",
"(",
"cur_col",
"+",
"col",
")",
"]",
"=",
"block",
"cur_row",
"+=",
"row",
"cur_col",
"+=",
"col",
"return",
"out"
] | [
7,
0
] | [
28,
14
] | python | en | ['en', 'error', 'th'] | False |
summary_parameters | (model, logger=None) |
Summary Parameters of Model
:param model: torch.nn.module_name
:param logger: logger
:return: None
|
Summary Parameters of Model
:param model: torch.nn.module_name
:param logger: logger
:return: None
| def summary_parameters(model, logger=None):
"""
Summary Parameters of Model
:param model: torch.nn.module_name
:param logger: logger
:return: None
"""
print_and_log('>> Trainable Parameters:', logger)
trainable_paramters = [(str(n), str(v.dtype), str(tuple(v.shape)), str(v.numel()))
for n, v in model.named_parameters() if v.requires_grad]
max_lens = [max([len(item) + 4 for item in col]) for col in zip(*trainable_paramters)]
raw_format = '|' + '|'.join(['{{:{}s}}'.format(max_len) for max_len in max_lens]) + '|'
raw_split = '-' * (sum(max_lens) + len(max_lens) + 1)
print_and_log(raw_split, logger)
print_and_log(raw_format.format('Name', 'Dtype', 'Shape', '#Params'), logger)
print_and_log(raw_split, logger)
for name, dtype, shape, number in trainable_paramters:
print_and_log(raw_format.format(name, dtype, shape, number), logger)
print_and_log(raw_split, logger)
num_trainable_params = sum([v.numel() for v in model.parameters() if v.requires_grad])
total_params = sum([v.numel() for v in model.parameters()])
non_trainable_params = total_params - num_trainable_params
print_and_log('>> {:25s}\t{:.2f}\tM'.format('# TrainableParams:', num_trainable_params / (1.0 * 10 ** 6)), logger)
print_and_log('>> {:25s}\t{:.2f}\tM'.format('# NonTrainableParams:', non_trainable_params / (1.0 * 10 ** 6)), logger)
print_and_log('>> {:25s}\t{:.2f}\tM'.format('# TotalParams:', total_params / (1.0 * 10 ** 6)), logger) | [
"def",
"summary_parameters",
"(",
"model",
",",
"logger",
"=",
"None",
")",
":",
"print_and_log",
"(",
"'>> Trainable Parameters:'",
",",
"logger",
")",
"trainable_paramters",
"=",
"[",
"(",
"str",
"(",
"n",
")",
",",
"str",
"(",
"v",
".",
"dtype",
")",
",",
"str",
"(",
"tuple",
"(",
"v",
".",
"shape",
")",
")",
",",
"str",
"(",
"v",
".",
"numel",
"(",
")",
")",
")",
"for",
"n",
",",
"v",
"in",
"model",
".",
"named_parameters",
"(",
")",
"if",
"v",
".",
"requires_grad",
"]",
"max_lens",
"=",
"[",
"max",
"(",
"[",
"len",
"(",
"item",
")",
"+",
"4",
"for",
"item",
"in",
"col",
"]",
")",
"for",
"col",
"in",
"zip",
"(",
"*",
"trainable_paramters",
")",
"]",
"raw_format",
"=",
"'|'",
"+",
"'|'",
".",
"join",
"(",
"[",
"'{{:{}s}}'",
".",
"format",
"(",
"max_len",
")",
"for",
"max_len",
"in",
"max_lens",
"]",
")",
"+",
"'|'",
"raw_split",
"=",
"'-'",
"*",
"(",
"sum",
"(",
"max_lens",
")",
"+",
"len",
"(",
"max_lens",
")",
"+",
"1",
")",
"print_and_log",
"(",
"raw_split",
",",
"logger",
")",
"print_and_log",
"(",
"raw_format",
".",
"format",
"(",
"'Name'",
",",
"'Dtype'",
",",
"'Shape'",
",",
"'#Params'",
")",
",",
"logger",
")",
"print_and_log",
"(",
"raw_split",
",",
"logger",
")",
"for",
"name",
",",
"dtype",
",",
"shape",
",",
"number",
"in",
"trainable_paramters",
":",
"print_and_log",
"(",
"raw_format",
".",
"format",
"(",
"name",
",",
"dtype",
",",
"shape",
",",
"number",
")",
",",
"logger",
")",
"print_and_log",
"(",
"raw_split",
",",
"logger",
")",
"num_trainable_params",
"=",
"sum",
"(",
"[",
"v",
".",
"numel",
"(",
")",
"for",
"v",
"in",
"model",
".",
"parameters",
"(",
")",
"if",
"v",
".",
"requires_grad",
"]",
")",
"total_params",
"=",
"sum",
"(",
"[",
"v",
".",
"numel",
"(",
")",
"for",
"v",
"in",
"model",
".",
"parameters",
"(",
")",
"]",
")",
"non_trainable_params",
"=",
"total_params",
"-",
"num_trainable_params",
"print_and_log",
"(",
"'>> {:25s}\\t{:.2f}\\tM'",
".",
"format",
"(",
"'# TrainableParams:'",
",",
"num_trainable_params",
"/",
"(",
"1.0",
"*",
"10",
"**",
"6",
")",
")",
",",
"logger",
")",
"print_and_log",
"(",
"'>> {:25s}\\t{:.2f}\\tM'",
".",
"format",
"(",
"'# NonTrainableParams:'",
",",
"non_trainable_params",
"/",
"(",
"1.0",
"*",
"10",
"**",
"6",
")",
")",
",",
"logger",
")",
"print_and_log",
"(",
"'>> {:25s}\\t{:.2f}\\tM'",
".",
"format",
"(",
"'# TotalParams:'",
",",
"total_params",
"/",
"(",
"1.0",
"*",
"10",
"**",
"6",
")",
")",
",",
"logger",
")"
] | [
39,
0
] | [
66,
106
] | python | en | ['en', 'error', 'th'] | False |
clip_grad | (named_parameters, max_norm, logger=logging, std_verbose=False, log_verbose=False) | Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
:param named_parameters: dict, named parameters of pytorch module
:param max_norm: float or int, max norm of the gradients
:param logger: logger to write verbose info
:param std_verbose: verbose info in stdout
:param log_verbose: verbose info in log
:return Total norm of the parameters (viewed as a dict: param name -> param grad norm).
| Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
:param named_parameters: dict, named parameters of pytorch module
:param max_norm: float or int, max norm of the gradients
:param logger: logger to write verbose info
:param std_verbose: verbose info in stdout
:param log_verbose: verbose info in log | def clip_grad(named_parameters, max_norm, logger=logging, std_verbose=False, log_verbose=False):
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
:param named_parameters: dict, named parameters of pytorch module
:param max_norm: float or int, max norm of the gradients
:param logger: logger to write verbose info
:param std_verbose: verbose info in stdout
:param log_verbose: verbose info in log
:return Total norm of the parameters (viewed as a dict: param name -> param grad norm).
"""
max_norm = float(max_norm)
parameters = [(n, p) for n, p in named_parameters if p.grad is not None]
total_norm = 0
param_to_norm = {}
param_to_shape = {}
for n, p in parameters:
param_norm = p.grad.data.norm(2)
total_norm += param_norm ** 2
param_to_norm[n] = param_norm
param_to_shape[n] = tuple(p.size())
if np.isnan(param_norm.item()):
raise ValueError("the param {} was null.".format(n))
total_norm = total_norm ** (1. / 2)
clip_coef = max_norm / (total_norm + 1e-6)
if clip_coef.item() < 1:
logger.info('---Clip grad! Total norm: {:.3f}, clip coef: {:.3f}.'.format(total_norm, clip_coef))
for n, p in parameters:
p.grad.data.mul_(clip_coef)
if std_verbose:
print('---Total norm {:.3f} clip coef {:.3f}-----------------'.format(total_norm, clip_coef))
for name, norm in sorted(param_to_norm.items(), key=lambda x: -x[1]):
print("{:<60s}: {:.3f}, ({}: {})".format(name, norm, np.prod(param_to_shape[name]), param_to_shape[name]))
print('-------------------------------', flush=True)
if log_verbose:
logger.info('---Total norm {:.3f} clip coef {:.3f}-----------------'.format(total_norm, clip_coef))
for name, norm in sorted(param_to_norm.items(), key=lambda x: -x[1]):
logger.info("{:<60s}: {:.3f}, ({}: {})".format(name, norm, np.prod(param_to_shape[name]), param_to_shape[name]))
logger.info('-------------------------------')
return {name: norm.item() for name, norm in param_to_norm.items()} | [
"def",
"clip_grad",
"(",
"named_parameters",
",",
"max_norm",
",",
"logger",
"=",
"logging",
",",
"std_verbose",
"=",
"False",
",",
"log_verbose",
"=",
"False",
")",
":",
"max_norm",
"=",
"float",
"(",
"max_norm",
")",
"parameters",
"=",
"[",
"(",
"n",
",",
"p",
")",
"for",
"n",
",",
"p",
"in",
"named_parameters",
"if",
"p",
".",
"grad",
"is",
"not",
"None",
"]",
"total_norm",
"=",
"0",
"param_to_norm",
"=",
"{",
"}",
"param_to_shape",
"=",
"{",
"}",
"for",
"n",
",",
"p",
"in",
"parameters",
":",
"param_norm",
"=",
"p",
".",
"grad",
".",
"data",
".",
"norm",
"(",
"2",
")",
"total_norm",
"+=",
"param_norm",
"**",
"2",
"param_to_norm",
"[",
"n",
"]",
"=",
"param_norm",
"param_to_shape",
"[",
"n",
"]",
"=",
"tuple",
"(",
"p",
".",
"size",
"(",
")",
")",
"if",
"np",
".",
"isnan",
"(",
"param_norm",
".",
"item",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"the param {} was null.\"",
".",
"format",
"(",
"n",
")",
")",
"total_norm",
"=",
"total_norm",
"**",
"(",
"1.",
"/",
"2",
")",
"clip_coef",
"=",
"max_norm",
"/",
"(",
"total_norm",
"+",
"1e-6",
")",
"if",
"clip_coef",
".",
"item",
"(",
")",
"<",
"1",
":",
"logger",
".",
"info",
"(",
"'---Clip grad! Total norm: {:.3f}, clip coef: {:.3f}.'",
".",
"format",
"(",
"total_norm",
",",
"clip_coef",
")",
")",
"for",
"n",
",",
"p",
"in",
"parameters",
":",
"p",
".",
"grad",
".",
"data",
".",
"mul_",
"(",
"clip_coef",
")",
"if",
"std_verbose",
":",
"print",
"(",
"'---Total norm {:.3f} clip coef {:.3f}-----------------'",
".",
"format",
"(",
"total_norm",
",",
"clip_coef",
")",
")",
"for",
"name",
",",
"norm",
"in",
"sorted",
"(",
"param_to_norm",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"-",
"x",
"[",
"1",
"]",
")",
":",
"print",
"(",
"\"{:<60s}: {:.3f}, ({}: {})\"",
".",
"format",
"(",
"name",
",",
"norm",
",",
"np",
".",
"prod",
"(",
"param_to_shape",
"[",
"name",
"]",
")",
",",
"param_to_shape",
"[",
"name",
"]",
")",
")",
"print",
"(",
"'-------------------------------'",
",",
"flush",
"=",
"True",
")",
"if",
"log_verbose",
":",
"logger",
".",
"info",
"(",
"'---Total norm {:.3f} clip coef {:.3f}-----------------'",
".",
"format",
"(",
"total_norm",
",",
"clip_coef",
")",
")",
"for",
"name",
",",
"norm",
"in",
"sorted",
"(",
"param_to_norm",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"-",
"x",
"[",
"1",
"]",
")",
":",
"logger",
".",
"info",
"(",
"\"{:<60s}: {:.3f}, ({}: {})\"",
".",
"format",
"(",
"name",
",",
"norm",
",",
"np",
".",
"prod",
"(",
"param_to_shape",
"[",
"name",
"]",
")",
",",
"param_to_shape",
"[",
"name",
"]",
")",
")",
"logger",
".",
"info",
"(",
"'-------------------------------'",
")",
"return",
"{",
"name",
":",
"norm",
".",
"item",
"(",
")",
"for",
"name",
",",
"norm",
"in",
"param_to_norm",
".",
"items",
"(",
")",
"}"
] | [
71,
0
] | [
114,
70
] | python | en | ['en', 'en', 'en'] | True |
soft_cross_entropy | (input, target, reduction='mean') |
Cross entropy loss with input logits and soft target
:param input: Tensor, size: (N, C)
:param target: Tensor, size: (N, C)
:param reduction: 'none' or 'mean' or 'sum', default: 'mean'
:return: loss
|
Cross entropy loss with input logits and soft target
:param input: Tensor, size: (N, C)
:param target: Tensor, size: (N, C)
:param reduction: 'none' or 'mean' or 'sum', default: 'mean'
:return: loss
| def soft_cross_entropy(input, target, reduction='mean'):
"""
Cross entropy loss with input logits and soft target
:param input: Tensor, size: (N, C)
:param target: Tensor, size: (N, C)
:param reduction: 'none' or 'mean' or 'sum', default: 'mean'
:return: loss
"""
eps = 1.0e-1
# debug = False
valid = (target.sum(1) - 1).abs() < eps
# if debug:
# print('valid', valid.sum().item())
# print('all', valid.numel())
# print('non valid')
# print(target[valid == 0])
if valid.sum().item() == 0:
return input.new_zeros(())
if reduction == 'mean':
return (- F.log_softmax(input[valid], 1) * target[valid]).sum(1).mean(0)
elif reduction == 'sum':
return (- F.log_softmax(input[valid], 1) * target[valid]).sum()
elif reduction == 'none':
l = input.new_zeros((input.shape[0], ))
l[valid] = (- F.log_softmax(input[valid], 1) * target[valid]).sum(1)
return l
else:
raise ValueError('Not support reduction type: {}.'.format(reduction)) | [
"def",
"soft_cross_entropy",
"(",
"input",
",",
"target",
",",
"reduction",
"=",
"'mean'",
")",
":",
"eps",
"=",
"1.0e-1",
"# debug = False",
"valid",
"=",
"(",
"target",
".",
"sum",
"(",
"1",
")",
"-",
"1",
")",
".",
"abs",
"(",
")",
"<",
"eps",
"# if debug:",
"# print('valid', valid.sum().item())",
"# print('all', valid.numel())",
"# print('non valid')",
"# print(target[valid == 0])",
"if",
"valid",
".",
"sum",
"(",
")",
".",
"item",
"(",
")",
"==",
"0",
":",
"return",
"input",
".",
"new_zeros",
"(",
"(",
")",
")",
"if",
"reduction",
"==",
"'mean'",
":",
"return",
"(",
"-",
"F",
".",
"log_softmax",
"(",
"input",
"[",
"valid",
"]",
",",
"1",
")",
"*",
"target",
"[",
"valid",
"]",
")",
".",
"sum",
"(",
"1",
")",
".",
"mean",
"(",
"0",
")",
"elif",
"reduction",
"==",
"'sum'",
":",
"return",
"(",
"-",
"F",
".",
"log_softmax",
"(",
"input",
"[",
"valid",
"]",
",",
"1",
")",
"*",
"target",
"[",
"valid",
"]",
")",
".",
"sum",
"(",
")",
"elif",
"reduction",
"==",
"'none'",
":",
"l",
"=",
"input",
".",
"new_zeros",
"(",
"(",
"input",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"l",
"[",
"valid",
"]",
"=",
"(",
"-",
"F",
".",
"log_softmax",
"(",
"input",
"[",
"valid",
"]",
",",
"1",
")",
"*",
"target",
"[",
"valid",
"]",
")",
".",
"sum",
"(",
"1",
")",
"return",
"l",
"else",
":",
"raise",
"ValueError",
"(",
"'Not support reduction type: {}.'",
".",
"format",
"(",
"reduction",
")",
")"
] | [
123,
0
] | [
150,
77
] | python | en | ['en', 'error', 'th'] | False |
_make_causal_mask | (input_ids_shape: tf.TensorShape, past_key_values_length: int = 0) |
Make causal mask used for bi-directional self-attention.
|
Make causal mask used for bi-directional self-attention.
| def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
mask_cond = tf.range(shape_list(mask)[-1])
mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
if past_key_values_length > 0:
mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1)) | [
"def",
"_make_causal_mask",
"(",
"input_ids_shape",
":",
"tf",
".",
"TensorShape",
",",
"past_key_values_length",
":",
"int",
"=",
"0",
")",
":",
"bsz",
",",
"tgt_len",
"=",
"input_ids_shape",
"mask",
"=",
"tf",
".",
"ones",
"(",
"(",
"tgt_len",
",",
"tgt_len",
")",
")",
"*",
"LARGE_NEGATIVE",
"mask_cond",
"=",
"tf",
".",
"range",
"(",
"shape_list",
"(",
"mask",
")",
"[",
"-",
"1",
"]",
")",
"mask",
"=",
"tf",
".",
"where",
"(",
"mask_cond",
"<",
"tf",
".",
"reshape",
"(",
"mask_cond",
"+",
"1",
",",
"(",
"shape_list",
"(",
"mask",
")",
"[",
"-",
"1",
"]",
",",
"1",
")",
")",
",",
"0.0",
",",
"mask",
")",
"if",
"past_key_values_length",
">",
"0",
":",
"mask",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"zeros",
"(",
"(",
"tgt_len",
",",
"past_key_values_length",
")",
")",
",",
"mask",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"return",
"tf",
".",
"tile",
"(",
"mask",
"[",
"None",
",",
"None",
",",
":",
",",
":",
"]",
",",
"(",
"bsz",
",",
"1",
",",
"1",
",",
"1",
")",
")"
] | [
77,
0
] | [
90,
58
] | 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.