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 |
---|---|---|---|---|---|---|---|---|---|---|---|
test_turn_on_off_toggle_schema | (hass, hass_read_only_user) | Test the schemas for the turn on/off/toggle services. | Test the schemas for the turn on/off/toggle services. | async def test_turn_on_off_toggle_schema(hass, hass_read_only_user):
"""Test the schemas for the turn on/off/toggle services."""
await async_setup_component(hass, "homeassistant", {})
for service in SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE:
for invalid in None, "nothing", ENTITY_MATCH_ALL, ENTITY_MATCH_NONE:
with pytest.raises(vol.Invalid):
await hass.services.async_call(
ha.DOMAIN,
service,
{"entity_id": invalid},
context=ha.Context(user_id=hass_read_only_user.id),
blocking=True,
) | [
"async",
"def",
"test_turn_on_off_toggle_schema",
"(",
"hass",
",",
"hass_read_only_user",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"homeassistant\"",
",",
"{",
"}",
")",
"for",
"service",
"in",
"SERVICE_TURN_ON",
",",
"SERVICE_TURN_OFF",
",",
"SERVICE_TOGGLE",
":",
"for",
"invalid",
"in",
"None",
",",
"\"nothing\"",
",",
"ENTITY_MATCH_ALL",
",",
"ENTITY_MATCH_NONE",
":",
"with",
"pytest",
".",
"raises",
"(",
"vol",
".",
"Invalid",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"ha",
".",
"DOMAIN",
",",
"service",
",",
"{",
"\"entity_id\"",
":",
"invalid",
"}",
",",
"context",
"=",
"ha",
".",
"Context",
"(",
"user_id",
"=",
"hass_read_only_user",
".",
"id",
")",
",",
"blocking",
"=",
"True",
",",
")"
] | [
355,
0
] | [
368,
17
] | python | en | ['en', 'en', 'en'] | True |
test_not_allowing_recursion | (hass, caplog) | Test we do not allow recursion. | Test we do not allow recursion. | async def test_not_allowing_recursion(hass, caplog):
"""Test we do not allow recursion."""
await async_setup_component(hass, "homeassistant", {})
for service in SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE:
await hass.services.async_call(
ha.DOMAIN,
service,
{"entity_id": "homeassistant.light"},
blocking=True,
)
assert (
f"Called service homeassistant.{service} with invalid entity IDs homeassistant.light"
in caplog.text
), service | [
"async",
"def",
"test_not_allowing_recursion",
"(",
"hass",
",",
"caplog",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"homeassistant\"",
",",
"{",
"}",
")",
"for",
"service",
"in",
"SERVICE_TURN_ON",
",",
"SERVICE_TURN_OFF",
",",
"SERVICE_TOGGLE",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"ha",
".",
"DOMAIN",
",",
"service",
",",
"{",
"\"entity_id\"",
":",
"\"homeassistant.light\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"(",
"f\"Called service homeassistant.{service} with invalid entity IDs homeassistant.light\"",
"in",
"caplog",
".",
"text",
")",
",",
"service"
] | [
371,
0
] | [
385,
18
] | python | en | ['en', 'en', 'en'] | True |
TestComponentsCore.setUp | (self) | Set up things to be run when tests are started. | Set up things to be run when tests are started. | def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
assert asyncio.run_coroutine_threadsafe(
async_setup_component(self.hass, "homeassistant", {}), self.hass.loop
).result()
self.hass.states.set("light.Bowl", STATE_ON)
self.hass.states.set("light.Ceiling", STATE_OFF)
self.addCleanup(self.hass.stop) | [
"def",
"setUp",
"(",
"self",
")",
":",
"self",
".",
"hass",
"=",
"get_test_home_assistant",
"(",
")",
"assert",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"async_setup_component",
"(",
"self",
".",
"hass",
",",
"\"homeassistant\"",
",",
"{",
"}",
")",
",",
"self",
".",
"hass",
".",
"loop",
")",
".",
"result",
"(",
")",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"\"light.Bowl\"",
",",
"STATE_ON",
")",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"\"light.Ceiling\"",
",",
"STATE_OFF",
")",
"self",
".",
"addCleanup",
"(",
"self",
".",
"hass",
".",
"stop",
")"
] | [
113,
4
] | [
122,
39
] | python | en | ['en', 'en', 'en'] | True |
TestComponentsCore.test_is_on | (self) | Test is_on method. | Test is_on method. | def test_is_on(self):
"""Test is_on method."""
assert comps.is_on(self.hass, "light.Bowl")
assert not comps.is_on(self.hass, "light.Ceiling")
assert comps.is_on(self.hass)
assert not comps.is_on(self.hass, "non_existing.entity") | [
"def",
"test_is_on",
"(",
"self",
")",
":",
"assert",
"comps",
".",
"is_on",
"(",
"self",
".",
"hass",
",",
"\"light.Bowl\"",
")",
"assert",
"not",
"comps",
".",
"is_on",
"(",
"self",
".",
"hass",
",",
"\"light.Ceiling\"",
")",
"assert",
"comps",
".",
"is_on",
"(",
"self",
".",
"hass",
")",
"assert",
"not",
"comps",
".",
"is_on",
"(",
"self",
".",
"hass",
",",
"\"non_existing.entity\"",
")"
] | [
124,
4
] | [
129,
64
] | python | en | ['en', 'et', 'en'] | True |
TestComponentsCore.test_turn_on_without_entities | (self) | Test turn_on method without entities. | Test turn_on method without entities. | def test_turn_on_without_entities(self):
"""Test turn_on method without entities."""
calls = mock_service(self.hass, "light", SERVICE_TURN_ON)
turn_on(self.hass)
self.hass.block_till_done()
assert 0 == len(calls) | [
"def",
"test_turn_on_without_entities",
"(",
"self",
")",
":",
"calls",
"=",
"mock_service",
"(",
"self",
".",
"hass",
",",
"\"light\"",
",",
"SERVICE_TURN_ON",
")",
"turn_on",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"0",
"==",
"len",
"(",
"calls",
")"
] | [
131,
4
] | [
136,
30
] | python | en | ['en', 'en', 'en'] | True |
TestComponentsCore.test_turn_on | (self) | Test turn_on method. | Test turn_on method. | def test_turn_on(self):
"""Test turn_on method."""
calls = mock_service(self.hass, "light", SERVICE_TURN_ON)
turn_on(self.hass, "light.Ceiling")
self.hass.block_till_done()
assert 1 == len(calls) | [
"def",
"test_turn_on",
"(",
"self",
")",
":",
"calls",
"=",
"mock_service",
"(",
"self",
".",
"hass",
",",
"\"light\"",
",",
"SERVICE_TURN_ON",
")",
"turn_on",
"(",
"self",
".",
"hass",
",",
"\"light.Ceiling\"",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"1",
"==",
"len",
"(",
"calls",
")"
] | [
138,
4
] | [
143,
30
] | python | en | ['en', 'et', 'en'] | True |
TestComponentsCore.test_turn_off | (self) | Test turn_off method. | Test turn_off method. | def test_turn_off(self):
"""Test turn_off method."""
calls = mock_service(self.hass, "light", SERVICE_TURN_OFF)
turn_off(self.hass, "light.Bowl")
self.hass.block_till_done()
assert 1 == len(calls) | [
"def",
"test_turn_off",
"(",
"self",
")",
":",
"calls",
"=",
"mock_service",
"(",
"self",
".",
"hass",
",",
"\"light\"",
",",
"SERVICE_TURN_OFF",
")",
"turn_off",
"(",
"self",
".",
"hass",
",",
"\"light.Bowl\"",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"1",
"==",
"len",
"(",
"calls",
")"
] | [
145,
4
] | [
150,
30
] | python | en | ['en', 'et', 'en'] | True |
TestComponentsCore.test_toggle | (self) | Test toggle method. | Test toggle method. | def test_toggle(self):
"""Test toggle method."""
calls = mock_service(self.hass, "light", SERVICE_TOGGLE)
toggle(self.hass, "light.Bowl")
self.hass.block_till_done()
assert 1 == len(calls) | [
"def",
"test_toggle",
"(",
"self",
")",
":",
"calls",
"=",
"mock_service",
"(",
"self",
".",
"hass",
",",
"\"light\"",
",",
"SERVICE_TOGGLE",
")",
"toggle",
"(",
"self",
".",
"hass",
",",
"\"light.Bowl\"",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"1",
"==",
"len",
"(",
"calls",
")"
] | [
152,
4
] | [
157,
30
] | python | en | ['en', 'et', 'en'] | True |
TestComponentsCore.test_reload_core_conf | (self) | Test reload core conf service. | Test reload core conf service. | def test_reload_core_conf(self):
"""Test reload core conf service."""
ent = entity.Entity()
ent.entity_id = "test.entity"
ent.hass = self.hass
ent.schedule_update_ha_state()
self.hass.block_till_done()
state = self.hass.states.get("test.entity")
assert state is not None
assert state.state == "unknown"
assert state.attributes == {}
files = {
config.YAML_CONFIG_FILE: yaml.dump(
{
ha.DOMAIN: {
"latitude": 10,
"longitude": 20,
"customize": {"test.Entity": {"hello": "world"}},
}
}
)
}
with patch_yaml_files(files, True):
reload_core_config(self.hass)
self.hass.block_till_done()
assert self.hass.config.latitude == 10
assert self.hass.config.longitude == 20
ent.schedule_update_ha_state()
self.hass.block_till_done()
state = self.hass.states.get("test.entity")
assert state is not None
assert state.state == "unknown"
assert state.attributes.get("hello") == "world" | [
"def",
"test_reload_core_conf",
"(",
"self",
")",
":",
"ent",
"=",
"entity",
".",
"Entity",
"(",
")",
"ent",
".",
"entity_id",
"=",
"\"test.entity\"",
"ent",
".",
"hass",
"=",
"self",
".",
"hass",
"ent",
".",
"schedule_update_ha_state",
"(",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"state",
"=",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"\"test.entity\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"unknown\"",
"assert",
"state",
".",
"attributes",
"==",
"{",
"}",
"files",
"=",
"{",
"config",
".",
"YAML_CONFIG_FILE",
":",
"yaml",
".",
"dump",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"\"latitude\"",
":",
"10",
",",
"\"longitude\"",
":",
"20",
",",
"\"customize\"",
":",
"{",
"\"test.Entity\"",
":",
"{",
"\"hello\"",
":",
"\"world\"",
"}",
"}",
",",
"}",
"}",
")",
"}",
"with",
"patch_yaml_files",
"(",
"files",
",",
"True",
")",
":",
"reload_core_config",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"self",
".",
"hass",
".",
"config",
".",
"latitude",
"==",
"10",
"assert",
"self",
".",
"hass",
".",
"config",
".",
"longitude",
"==",
"20",
"ent",
".",
"schedule_update_ha_state",
"(",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"state",
"=",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"\"test.entity\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"unknown\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"\"hello\"",
")",
"==",
"\"world\""
] | [
160,
4
] | [
197,
55
] | python | en | ['en', 'it', 'en'] | True |
TestComponentsCore.test_reload_core_with_wrong_conf | (self, mock_process, mock_error) | Test reload core conf service. | Test reload core conf service. | def test_reload_core_with_wrong_conf(self, mock_process, mock_error):
"""Test reload core conf service."""
files = {config.YAML_CONFIG_FILE: yaml.dump(["invalid", "config"])}
with patch_yaml_files(files, True):
reload_core_config(self.hass)
self.hass.block_till_done()
assert mock_error.called
assert mock_process.called is False | [
"def",
"test_reload_core_with_wrong_conf",
"(",
"self",
",",
"mock_process",
",",
"mock_error",
")",
":",
"files",
"=",
"{",
"config",
".",
"YAML_CONFIG_FILE",
":",
"yaml",
".",
"dump",
"(",
"[",
"\"invalid\"",
",",
"\"config\"",
"]",
")",
"}",
"with",
"patch_yaml_files",
"(",
"files",
",",
"True",
")",
":",
"reload_core_config",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"mock_error",
".",
"called",
"assert",
"mock_process",
".",
"called",
"is",
"False"
] | [
202,
4
] | [
210,
43
] | python | en | ['en', 'it', 'en'] | True |
TestComponentsCore.test_stop_homeassistant | (self, mock_stop) | Test stop service. | Test stop service. | def test_stop_homeassistant(self, mock_stop):
"""Test stop service."""
stop(self.hass)
self.hass.block_till_done()
assert mock_stop.called | [
"def",
"test_stop_homeassistant",
"(",
"self",
",",
"mock_stop",
")",
":",
"stop",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"mock_stop",
".",
"called"
] | [
213,
4
] | [
217,
31
] | python | en | ['en', 'en', 'en'] | True |
TestComponentsCore.test_restart_homeassistant | (self, mock_check, mock_restart) | Test stop service. | Test stop service. | def test_restart_homeassistant(self, mock_check, mock_restart):
"""Test stop service."""
restart(self.hass)
self.hass.block_till_done()
assert mock_restart.called
assert mock_check.called | [
"def",
"test_restart_homeassistant",
"(",
"self",
",",
"mock_check",
",",
"mock_restart",
")",
":",
"restart",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"mock_restart",
".",
"called",
"assert",
"mock_check",
".",
"called"
] | [
221,
4
] | [
226,
32
] | python | en | ['en', 'en', 'en'] | True |
TestComponentsCore.test_restart_homeassistant_wrong_conf | (self, mock_check, mock_restart) | Test stop service. | Test stop service. | def test_restart_homeassistant_wrong_conf(self, mock_check, mock_restart):
"""Test stop service."""
restart(self.hass)
self.hass.block_till_done()
assert mock_check.called
assert not mock_restart.called | [
"def",
"test_restart_homeassistant_wrong_conf",
"(",
"self",
",",
"mock_check",
",",
"mock_restart",
")",
":",
"restart",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"mock_check",
".",
"called",
"assert",
"not",
"mock_restart",
".",
"called"
] | [
233,
4
] | [
238,
38
] | python | en | ['en', 'en', 'en'] | True |
TestComponentsCore.test_check_config | (self, mock_check, mock_stop) | Test stop service. | Test stop service. | def test_check_config(self, mock_check, mock_stop):
"""Test stop service."""
check_config(self.hass)
self.hass.block_till_done()
assert mock_check.called
assert not mock_stop.called | [
"def",
"test_check_config",
"(",
"self",
",",
"mock_check",
",",
"mock_stop",
")",
":",
"check_config",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"block_till_done",
"(",
")",
"assert",
"mock_check",
".",
"called",
"assert",
"not",
"mock_stop",
".",
"called"
] | [
242,
4
] | [
247,
35
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up Lupusec component. | Set up Lupusec component. | def setup(hass, config):
"""Set up Lupusec component."""
conf = config[DOMAIN]
username = conf[CONF_USERNAME]
password = conf[CONF_PASSWORD]
ip_address = conf[CONF_IP_ADDRESS]
name = conf.get(CONF_NAME)
try:
hass.data[DOMAIN] = LupusecSystem(username, password, ip_address, name)
except LupusecException as ex:
_LOGGER.error(ex)
hass.components.persistent_notification.create(
f"Error: {ex}<br />You will need to restart hass after fixing.",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
for platform in LUPUSEC_PLATFORMS:
discovery.load_platform(hass, platform, DOMAIN, {}, config)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"username",
"=",
"conf",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"conf",
"[",
"CONF_PASSWORD",
"]",
"ip_address",
"=",
"conf",
"[",
"CONF_IP_ADDRESS",
"]",
"name",
"=",
"conf",
".",
"get",
"(",
"CONF_NAME",
")",
"try",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"LupusecSystem",
"(",
"username",
",",
"password",
",",
"ip_address",
",",
"name",
")",
"except",
"LupusecException",
"as",
"ex",
":",
"_LOGGER",
".",
"error",
"(",
"ex",
")",
"hass",
".",
"components",
".",
"persistent_notification",
".",
"create",
"(",
"f\"Error: {ex}<br />You will need to restart hass after fixing.\"",
",",
"title",
"=",
"NOTIFICATION_TITLE",
",",
"notification_id",
"=",
"NOTIFICATION_ID",
",",
")",
"return",
"False",
"for",
"platform",
"in",
"LUPUSEC_PLATFORMS",
":",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"platform",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"return",
"True"
] | [
35,
0
] | [
58,
15
] | python | en | ['en', 'ca', 'en'] | True |
LupusecSystem.__init__ | (self, username, password, ip_address, name) | Initialize the system. | Initialize the system. | def __init__(self, username, password, ip_address, name):
"""Initialize the system."""
self.lupusec = lupupy.Lupusec(username, password, ip_address)
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"username",
",",
"password",
",",
"ip_address",
",",
"name",
")",
":",
"self",
".",
"lupusec",
"=",
"lupupy",
".",
"Lupusec",
"(",
"username",
",",
"password",
",",
"ip_address",
")",
"self",
".",
"name",
"=",
"name"
] | [
64,
4
] | [
67,
24
] | python | en | ['en', 'en', 'en'] | True |
LupusecDevice.__init__ | (self, data, device) | Initialize a sensor for Lupusec device. | Initialize a sensor for Lupusec device. | def __init__(self, data, device):
"""Initialize a sensor for Lupusec device."""
self._data = data
self._device = device | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"device",
")",
":",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_device",
"=",
"device"
] | [
73,
4
] | [
76,
29
] | python | en | ['en', 'en', 'en'] | True |
LupusecDevice.update | (self) | Update automation state. | Update automation state. | def update(self):
"""Update automation state."""
self._device.refresh() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_device",
".",
"refresh",
"(",
")"
] | [
78,
4
] | [
80,
30
] | python | en | ['de', 'en', 'en'] | True |
LupusecDevice.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._device.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"name"
] | [
83,
4
] | [
85,
32
] | python | en | ['en', 'mi', 'en'] | True |
_assert_tensors_equal | (a, b, atol=1e-12, prefix="") | If tensors not close, or a and b arent both tensors, raise a nice Assertion error. | If tensors not close, or a and b arent both tensors, raise a nice Assertion error. | def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
"""If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if tf.debugging.assert_near(a, b, atol=atol):
return True
raise
except Exception:
msg = "{} != {}".format(a, b)
if prefix:
msg = prefix + ": " + msg
raise AssertionError(msg) | [
"def",
"_assert_tensors_equal",
"(",
"a",
",",
"b",
",",
"atol",
"=",
"1e-12",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"a",
"is",
"None",
"and",
"b",
"is",
"None",
":",
"return",
"True",
"try",
":",
"if",
"tf",
".",
"debugging",
".",
"assert_near",
"(",
"a",
",",
"b",
",",
"atol",
"=",
"atol",
")",
":",
"return",
"True",
"raise",
"except",
"Exception",
":",
"msg",
"=",
"\"{} != {}\"",
".",
"format",
"(",
"a",
",",
"b",
")",
"if",
"prefix",
":",
"msg",
"=",
"prefix",
"+",
"\": \"",
"+",
"msg",
"raise",
"AssertionError",
"(",
"msg",
")"
] | [
282,
0
] | [
294,
33
] | python | en | ['en', 'en', 'en'] | True |
_validate_input | (data) | Validate the user input allows us to connect. | Validate the user input allows us to connect. | async def _validate_input(data):
"""Validate the user input allows us to connect."""
def _connected_callback():
connected_event.set()
connected_event = asyncio.Event()
file_path = data.get(CONF_FILE_PATH)
url = _make_url_from_data(data)
upb = upb_lib.UpbPim({"url": url, "UPStartExportFile": file_path})
if not upb.config_ok:
_LOGGER.error("Missing or invalid UPB file: %s", file_path)
raise InvalidUpbFile
upb.connect(_connected_callback)
try:
with async_timeout.timeout(VALIDATE_TIMEOUT):
await connected_event.wait()
except asyncio.TimeoutError:
pass
upb.disconnect()
if not connected_event.is_set():
_LOGGER.error(
"Timed out after %d seconds trying to connect with UPB PIM at %s",
VALIDATE_TIMEOUT,
url,
)
raise CannotConnect
# Return info that you want to store in the config entry.
return (upb.network_id, {"title": "UPB", CONF_HOST: url, CONF_FILE_PATH: file_path}) | [
"async",
"def",
"_validate_input",
"(",
"data",
")",
":",
"def",
"_connected_callback",
"(",
")",
":",
"connected_event",
".",
"set",
"(",
")",
"connected_event",
"=",
"asyncio",
".",
"Event",
"(",
")",
"file_path",
"=",
"data",
".",
"get",
"(",
"CONF_FILE_PATH",
")",
"url",
"=",
"_make_url_from_data",
"(",
"data",
")",
"upb",
"=",
"upb_lib",
".",
"UpbPim",
"(",
"{",
"\"url\"",
":",
"url",
",",
"\"UPStartExportFile\"",
":",
"file_path",
"}",
")",
"if",
"not",
"upb",
".",
"config_ok",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing or invalid UPB file: %s\"",
",",
"file_path",
")",
"raise",
"InvalidUpbFile",
"upb",
".",
"connect",
"(",
"_connected_callback",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"VALIDATE_TIMEOUT",
")",
":",
"await",
"connected_event",
".",
"wait",
"(",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"pass",
"upb",
".",
"disconnect",
"(",
")",
"if",
"not",
"connected_event",
".",
"is_set",
"(",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timed out after %d seconds trying to connect with UPB PIM at %s\"",
",",
"VALIDATE_TIMEOUT",
",",
"url",
",",
")",
"raise",
"CannotConnect",
"# Return info that you want to store in the config entry.",
"return",
"(",
"upb",
".",
"network_id",
",",
"{",
"\"title\"",
":",
"\"UPB\"",
",",
"CONF_HOST",
":",
"url",
",",
"CONF_FILE_PATH",
":",
"file_path",
"}",
")"
] | [
28,
0
] | [
62,
88
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.__init__ | (self) | Initialize the UPB config flow. | Initialize the UPB config flow. | def __init__(self):
"""Initialize the UPB config flow."""
self.importing = False | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"importing",
"=",
"False"
] | [
81,
4
] | [
83,
30
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_user | (self, user_input=None) | Handle the initial step. | Handle the initial step. | async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
if self._url_already_configured(_make_url_from_data(user_input)):
return self.async_abort(reason="already_configured")
network_id, info = await _validate_input(user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidUpbFile:
errors["base"] = "invalid_upb_file"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if "base" not in errors:
await self.async_set_unique_id(network_id)
self._abort_if_unique_id_configured()
if self.importing:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_create_entry(
title=info["title"],
data={
CONF_HOST: info[CONF_HOST],
CONF_FILE_PATH: user_input[CONF_FILE_PATH],
},
)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"try",
":",
"if",
"self",
".",
"_url_already_configured",
"(",
"_make_url_from_data",
"(",
"user_input",
")",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"network_id",
",",
"info",
"=",
"await",
"_validate_input",
"(",
"user_input",
")",
"except",
"CannotConnect",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"except",
"InvalidUpbFile",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_upb_file\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"exception",
"(",
"\"Unexpected exception\"",
")",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"if",
"\"base\"",
"not",
"in",
"errors",
":",
"await",
"self",
".",
"async_set_unique_id",
"(",
"network_id",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"if",
"self",
".",
"importing",
":",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"info",
"[",
"\"title\"",
"]",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"info",
"[",
"\"title\"",
"]",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"info",
"[",
"CONF_HOST",
"]",
",",
"CONF_FILE_PATH",
":",
"user_input",
"[",
"CONF_FILE_PATH",
"]",
",",
"}",
",",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"DATA_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
85,
4
] | [
118,
9
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_import | (self, user_input) | Handle import. | Handle import. | async def async_step_import(self, user_input):
"""Handle import."""
self.importing = True
return await self.async_step_user(user_input) | [
"async",
"def",
"async_step_import",
"(",
"self",
",",
"user_input",
")",
":",
"self",
".",
"importing",
"=",
"True",
"return",
"await",
"self",
".",
"async_step_user",
"(",
"user_input",
")"
] | [
120,
4
] | [
123,
53
] | python | en | ['en', 'ja', 'en'] | False |
ConfigFlow._url_already_configured | (self, url) | See if we already have a UPB PIM matching user input configured. | See if we already have a UPB PIM matching user input configured. | def _url_already_configured(self, url):
"""See if we already have a UPB PIM matching user input configured."""
existing_hosts = {
urlparse(entry.data[CONF_HOST]).hostname
for entry in self._async_current_entries()
}
return urlparse(url).hostname in existing_hosts | [
"def",
"_url_already_configured",
"(",
"self",
",",
"url",
")",
":",
"existing_hosts",
"=",
"{",
"urlparse",
"(",
"entry",
".",
"data",
"[",
"CONF_HOST",
"]",
")",
".",
"hostname",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
"}",
"return",
"urlparse",
"(",
"url",
")",
".",
"hostname",
"in",
"existing_hosts"
] | [
125,
4
] | [
131,
55
] | python | en | ['en', 'en', 'en'] | True |
setup_awair | (hass, fixtures) | Add Awair devices to hass, using specified fixtures for data. | Add Awair devices to hass, using specified fixtures for data. | async def setup_awair(hass, fixtures):
"""Add Awair devices to hass, using specified fixtures for data."""
entry = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG)
with patch("python_awair.AwairClient.query", side_effect=fixtures):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done() | [
"async",
"def",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"unique_id",
"=",
"UNIQUE_ID",
",",
"data",
"=",
"CONFIG",
")",
"with",
"patch",
"(",
"\"python_awair.AwairClient.query\"",
",",
"side_effect",
"=",
"fixtures",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
46,
0
] | [
53,
42
] | python | en | ['en', 'en', 'en'] | True |
assert_expected_properties | (
hass, registry, name, unique_id, state_value, attributes
) | Assert expected properties from a dict. | Assert expected properties from a dict. | def assert_expected_properties(
hass, registry, name, unique_id, state_value, attributes
):
"""Assert expected properties from a dict."""
entry = registry.async_get(name)
assert entry.unique_id == unique_id
state = hass.states.get(name)
assert state
assert state.state == state_value
for attr, value in attributes.items():
assert state.attributes.get(attr) == value | [
"def",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"name",
",",
"unique_id",
",",
"state_value",
",",
"attributes",
")",
":",
"entry",
"=",
"registry",
".",
"async_get",
"(",
"name",
")",
"assert",
"entry",
".",
"unique_id",
"==",
"unique_id",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"name",
")",
"assert",
"state",
"assert",
"state",
".",
"state",
"==",
"state_value",
"for",
"attr",
",",
"value",
"in",
"attributes",
".",
"items",
"(",
")",
":",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"attr",
")",
"==",
"value"
] | [
56,
0
] | [
67,
50
] | python | en | ['en', 'en', 'en'] | True |
test_awair_gen1_sensors | (hass) | Test expected sensors on a 1st gen Awair. | Test expected sensors on a 1st gen Awair. | async def test_awair_gen1_sensors(hass):
"""Test expected sensors on a 1st gen Awair."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GEN1_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"88",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_temperature",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_TEMP][ATTR_UNIQUE_ID]}",
"21.8",
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, "awair_index": 1.0},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_humidity",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_HUMID][ATTR_UNIQUE_ID]}",
"41.59",
{ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE, "awair_index": 0.0},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_carbon_dioxide",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_CO2][ATTR_UNIQUE_ID]}",
"654.0",
{
ATTR_ICON: "mdi:cloud",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_MILLION,
"awair_index": 0.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_volatile_organic_compounds",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_VOC][ATTR_UNIQUE_ID]}",
"366",
{
ATTR_ICON: "mdi:cloud",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_PARTS_PER_BILLION,
"awair_index": 1.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
# gen1 unique_id should be awair_12345-DUST, which matches old integration behavior
f"{AWAIR_UUID}_DUST",
"14.3",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 1.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm10",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_PM10][ATTR_UNIQUE_ID]}",
"14.3",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 1.0,
},
)
# We should not have a dust sensor; it's aliased as pm2.5
# and pm10 sensors.
assert hass.states.get("sensor.living_room_dust") is None
# We should not have sound or lux sensors.
assert hass.states.get("sensor.living_room_sound_level") is None
assert hass.states.get("sensor.living_room_illuminance") is None | [
"async",
"def",
"test_awair_gen1_sensors",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"GEN1_DATA_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"\"88\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_temperature\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_TEMP][ATTR_UNIQUE_ID]}\"",
",",
"\"21.8\"",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"TEMP_CELSIUS",
",",
"\"awair_index\"",
":",
"1.0",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_humidity\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_HUMID][ATTR_UNIQUE_ID]}\"",
",",
"\"41.59\"",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"PERCENTAGE",
",",
"\"awair_index\"",
":",
"0.0",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_carbon_dioxide\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_CO2][ATTR_UNIQUE_ID]}\"",
",",
"\"654.0\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:cloud\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"CONCENTRATION_PARTS_PER_MILLION",
",",
"\"awair_index\"",
":",
"0.0",
",",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_volatile_organic_compounds\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_VOC][ATTR_UNIQUE_ID]}\"",
",",
"\"366\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:cloud\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"CONCENTRATION_PARTS_PER_BILLION",
",",
"\"awair_index\"",
":",
"1.0",
",",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_pm2_5\"",
",",
"# gen1 unique_id should be awair_12345-DUST, which matches old integration behavior",
"f\"{AWAIR_UUID}_DUST\"",
",",
"\"14.3\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"CONCENTRATION_MICROGRAMS_PER_CUBIC_METER",
",",
"\"awair_index\"",
":",
"1.0",
",",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_pm10\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_PM10][ATTR_UNIQUE_ID]}\"",
",",
"\"14.3\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"CONCENTRATION_MICROGRAMS_PER_CUBIC_METER",
",",
"\"awair_index\"",
":",
"1.0",
",",
"}",
",",
")",
"# We should not have a dust sensor; it's aliased as pm2.5",
"# and pm10 sensors.",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_dust\"",
")",
"is",
"None",
"# We should not have sound or lux sensors.",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_sound_level\"",
")",
"is",
"None",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_illuminance\"",
")",
"is",
"None"
] | [
70,
0
] | [
163,
68
] | python | en | ['en', 'lb', 'en'] | True |
test_awair_gen2_sensors | (hass) | Test expected sensors on a 2nd gen Awair. | Test expected sensors on a 2nd gen Awair. | async def test_awair_gen2_sensors(hass):
"""Test expected sensors on a 2nd gen Awair."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GEN2_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"97",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_PM25][ATTR_UNIQUE_ID]}",
"2.0",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 0.0,
},
)
# The Awair 2nd gen reports specifically a pm2.5 sensor,
# and so we don't alias anything. Make sure we didn't do that.
assert hass.states.get("sensor.living_room_pm10") is None | [
"async",
"def",
"test_awair_gen2_sensors",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"GEN2_DATA_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"\"97\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_pm2_5\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_PM25][ATTR_UNIQUE_ID]}\"",
",",
"\"2.0\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"CONCENTRATION_MICROGRAMS_PER_CUBIC_METER",
",",
"\"awair_index\"",
":",
"0.0",
",",
"}",
",",
")",
"# The Awair 2nd gen reports specifically a pm2.5 sensor,",
"# and so we don't alias anything. Make sure we didn't do that.",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_pm10\"",
")",
"is",
"None"
] | [
166,
0
] | [
197,
61
] | python | en | ['en', 'lb', 'en'] | True |
test_awair_mint_sensors | (hass) | Test expected sensors on an Awair mint. | Test expected sensors on an Awair mint. | async def test_awair_mint_sensors(hass):
"""Test expected sensors on an Awair mint."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, MINT_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"98",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_pm2_5",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_PM25][ATTR_UNIQUE_ID]}",
"1.0",
{
ATTR_ICON: "mdi:blur",
ATTR_UNIT_OF_MEASUREMENT: CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
"awair_index": 0.0,
},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_illuminance",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}",
"441.7",
{ATTR_UNIT_OF_MEASUREMENT: LIGHT_LUX},
)
# The Mint does not have a CO2 sensor.
assert hass.states.get("sensor.living_room_carbon_dioxide") is None | [
"async",
"def",
"test_awair_mint_sensors",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"MINT_DATA_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"\"98\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_pm2_5\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_PM25][ATTR_UNIQUE_ID]}\"",
",",
"\"1.0\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"CONCENTRATION_MICROGRAMS_PER_CUBIC_METER",
",",
"\"awair_index\"",
":",
"0.0",
",",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_illuminance\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}\"",
",",
"\"441.7\"",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"LIGHT_LUX",
"}",
",",
")",
"# The Mint does not have a CO2 sensor.",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_carbon_dioxide\"",
")",
"is",
"None"
] | [
200,
0
] | [
239,
71
] | python | en | ['en', 'lb', 'en'] | True |
test_awair_glow_sensors | (hass) | Test expected sensors on an Awair glow. | Test expected sensors on an Awair glow. | async def test_awair_glow_sensors(hass):
"""Test expected sensors on an Awair glow."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GLOW_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"93",
{ATTR_ICON: "mdi:blur"},
)
# The glow does not have a particle sensor
assert hass.states.get("sensor.living_room_pm2_5") is None | [
"async",
"def",
"test_awair_glow_sensors",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"GLOW_DATA_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"\"93\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")",
"# The glow does not have a particle sensor",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_pm2_5\"",
")",
"is",
"None"
] | [
242,
0
] | [
259,
62
] | python | en | ['en', 'en', 'en'] | True |
test_awair_omni_sensors | (hass) | Test expected sensors on an Awair omni. | Test expected sensors on an Awair omni. | async def test_awair_omni_sensors(hass):
"""Test expected sensors on an Awair omni."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, OMNI_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"99",
{ATTR_ICON: "mdi:blur"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_sound_level",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SPL_A][ATTR_UNIQUE_ID]}",
"47.0",
{ATTR_ICON: "mdi:ear-hearing", ATTR_UNIT_OF_MEASUREMENT: "dBa"},
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_illuminance",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}",
"804.9",
{ATTR_UNIT_OF_MEASUREMENT: LIGHT_LUX},
) | [
"async",
"def",
"test_awair_omni_sensors",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"OMNI_DATA_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"\"99\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_sound_level\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SPL_A][ATTR_UNIQUE_ID]}\"",
",",
"\"47.0\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:ear-hearing\"",
",",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"\"dBa\"",
"}",
",",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_illuminance\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_LUX][ATTR_UNIQUE_ID]}\"",
",",
"\"804.9\"",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"LIGHT_LUX",
"}",
",",
")"
] | [
262,
0
] | [
294,
5
] | python | en | ['en', 'en', 'en'] | True |
test_awair_offline | (hass) | Test expected behavior when an Awair is offline. | Test expected behavior when an Awair is offline. | async def test_awair_offline(hass):
"""Test expected behavior when an Awair is offline."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, OFFLINE_FIXTURE]
await setup_awair(hass, fixtures)
# The expected behavior is that we won't have any sensors
# if the device is not online when we set it up. python_awair
# does not make any assumptions about what sensors a device
# might have - they are created dynamically.
# We check for the absence of the "awair score", which every
# device *should* have if it's online. If we don't see it,
# then we probably didn't set anything up. Which is correct,
# in this case.
assert hass.states.get("sensor.living_room_awair_score") is None | [
"async",
"def",
"test_awair_offline",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"OFFLINE_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"# The expected behavior is that we won't have any sensors",
"# if the device is not online when we set it up. python_awair",
"# does not make any assumptions about what sensors a device",
"# might have - they are created dynamically.",
"# We check for the absence of the \"awair score\", which every",
"# device *should* have if it's online. If we don't see it,",
"# then we probably didn't set anything up. Which is correct,",
"# in this case.",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.living_room_awair_score\"",
")",
"is",
"None"
] | [
297,
0
] | [
312,
68
] | python | en | ['en', 'lb', 'en'] | True |
test_awair_unavailable | (hass) | Test expected behavior when an Awair becomes offline later. | Test expected behavior when an Awair becomes offline later. | async def test_awair_unavailable(hass):
"""Test expected behavior when an Awair becomes offline later."""
fixtures = [USER_FIXTURE, DEVICES_FIXTURE, GEN1_DATA_FIXTURE]
await setup_awair(hass, fixtures)
registry = await hass.helpers.entity_registry.async_get_registry()
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
"88",
{ATTR_ICON: "mdi:blur"},
)
with patch("python_awair.AwairClient.query", side_effect=OFFLINE_FIXTURE):
await hass.helpers.entity_component.async_update_entity(
"sensor.living_room_awair_score"
)
assert_expected_properties(
hass,
registry,
"sensor.living_room_awair_score",
f"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}",
STATE_UNAVAILABLE,
{ATTR_ICON: "mdi:blur"},
) | [
"async",
"def",
"test_awair_unavailable",
"(",
"hass",
")",
":",
"fixtures",
"=",
"[",
"USER_FIXTURE",
",",
"DEVICES_FIXTURE",
",",
"GEN1_DATA_FIXTURE",
"]",
"await",
"setup_awair",
"(",
"hass",
",",
"fixtures",
")",
"registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"\"88\"",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")",
"with",
"patch",
"(",
"\"python_awair.AwairClient.query\"",
",",
"side_effect",
"=",
"OFFLINE_FIXTURE",
")",
":",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"\"sensor.living_room_awair_score\"",
")",
"assert_expected_properties",
"(",
"hass",
",",
"registry",
",",
"\"sensor.living_room_awair_score\"",
",",
"f\"{AWAIR_UUID}_{SENSOR_TYPES[API_SCORE][ATTR_UNIQUE_ID]}\"",
",",
"STATE_UNAVAILABLE",
",",
"{",
"ATTR_ICON",
":",
"\"mdi:blur\"",
"}",
",",
")"
] | [
315,
0
] | [
342,
9
] | python | en | ['en', 'lb', 'en'] | True |
validate_attributes | (list_attributes) | Validate face attributes. | Validate face attributes. | def validate_attributes(list_attributes):
"""Validate face attributes."""
for attr in list_attributes:
if attr not in SUPPORTED_ATTRIBUTES:
raise vol.Invalid(f"Invalid attribute {attr}")
return list_attributes | [
"def",
"validate_attributes",
"(",
"list_attributes",
")",
":",
"for",
"attr",
"in",
"list_attributes",
":",
"if",
"attr",
"not",
"in",
"SUPPORTED_ATTRIBUTES",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"f\"Invalid attribute {attr}\"",
")",
"return",
"list_attributes"
] | [
28,
0
] | [
33,
26
] | python | en | ['en', 'la', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Microsoft Face detection platform. | Set up the Microsoft Face detection platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Microsoft Face detection platform."""
api = hass.data[DATA_MICROSOFT_FACE]
attributes = config[CONF_ATTRIBUTES]
entities = []
for camera in config[CONF_SOURCE]:
entities.append(
MicrosoftFaceDetectEntity(
camera[CONF_ENTITY_ID], api, attributes, camera.get(CONF_NAME)
)
)
async_add_entities(entities) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"api",
"=",
"hass",
".",
"data",
"[",
"DATA_MICROSOFT_FACE",
"]",
"attributes",
"=",
"config",
"[",
"CONF_ATTRIBUTES",
"]",
"entities",
"=",
"[",
"]",
"for",
"camera",
"in",
"config",
"[",
"CONF_SOURCE",
"]",
":",
"entities",
".",
"append",
"(",
"MicrosoftFaceDetectEntity",
"(",
"camera",
"[",
"CONF_ENTITY_ID",
"]",
",",
"api",
",",
"attributes",
",",
"camera",
".",
"get",
"(",
"CONF_NAME",
")",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
45,
0
] | [
58,
32
] | python | en | ['en', 'da', 'en'] | True |
MicrosoftFaceDetectEntity.__init__ | (self, camera_entity, api, attributes, name=None) | Initialize Microsoft Face. | Initialize Microsoft Face. | def __init__(self, camera_entity, api, attributes, name=None):
"""Initialize Microsoft Face."""
super().__init__()
self._api = api
self._camera = camera_entity
self._attributes = attributes
if name:
self._name = name
else:
self._name = f"MicrosoftFace {split_entity_id(camera_entity)[1]}" | [
"def",
"__init__",
"(",
"self",
",",
"camera_entity",
",",
"api",
",",
"attributes",
",",
"name",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_api",
"=",
"api",
"self",
".",
"_camera",
"=",
"camera_entity",
"self",
".",
"_attributes",
"=",
"attributes",
"if",
"name",
":",
"self",
".",
"_name",
"=",
"name",
"else",
":",
"self",
".",
"_name",
"=",
"f\"MicrosoftFace {split_entity_id(camera_entity)[1]}\""
] | [
64,
4
] | [
75,
77
] | python | co | ['en', 'co', 'it'] | False |
MicrosoftFaceDetectEntity.camera_entity | (self) | Return camera entity id from process pictures. | Return camera entity id from process pictures. | def camera_entity(self):
"""Return camera entity id from process pictures."""
return self._camera | [
"def",
"camera_entity",
"(",
"self",
")",
":",
"return",
"self",
".",
"_camera"
] | [
78,
4
] | [
80,
27
] | python | en | ['en', 'en', 'en'] | True |
MicrosoftFaceDetectEntity.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._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
83,
4
] | [
85,
25
] | python | en | ['en', 'en', 'en'] | True |
MicrosoftFaceDetectEntity.async_process_image | (self, image) | Process image.
This method is a coroutine.
| Process image. | async def async_process_image(self, image):
"""Process image.
This method is a coroutine.
"""
face_data = None
try:
face_data = await self._api.call_api(
"post",
"detect",
image,
binary=True,
params={"returnFaceAttributes": ",".join(self._attributes)},
)
except HomeAssistantError as err:
_LOGGER.error("Can't process image on microsoft face: %s", err)
return
if not face_data:
face_data = []
faces = []
for face in face_data:
face_attr = {}
for attr in self._attributes:
if attr in face["faceAttributes"]:
face_attr[attr] = face["faceAttributes"][attr]
if face_attr:
faces.append(face_attr)
self.async_process_faces(faces, len(face_data)) | [
"async",
"def",
"async_process_image",
"(",
"self",
",",
"image",
")",
":",
"face_data",
"=",
"None",
"try",
":",
"face_data",
"=",
"await",
"self",
".",
"_api",
".",
"call_api",
"(",
"\"post\"",
",",
"\"detect\"",
",",
"image",
",",
"binary",
"=",
"True",
",",
"params",
"=",
"{",
"\"returnFaceAttributes\"",
":",
"\",\"",
".",
"join",
"(",
"self",
".",
"_attributes",
")",
"}",
",",
")",
"except",
"HomeAssistantError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Can't process image on microsoft face: %s\"",
",",
"err",
")",
"return",
"if",
"not",
"face_data",
":",
"face_data",
"=",
"[",
"]",
"faces",
"=",
"[",
"]",
"for",
"face",
"in",
"face_data",
":",
"face_attr",
"=",
"{",
"}",
"for",
"attr",
"in",
"self",
".",
"_attributes",
":",
"if",
"attr",
"in",
"face",
"[",
"\"faceAttributes\"",
"]",
":",
"face_attr",
"[",
"attr",
"]",
"=",
"face",
"[",
"\"faceAttributes\"",
"]",
"[",
"attr",
"]",
"if",
"face_attr",
":",
"faces",
".",
"append",
"(",
"face_attr",
")",
"self",
".",
"async_process_faces",
"(",
"faces",
",",
"len",
"(",
"face_data",
")",
")"
] | [
87,
4
] | [
119,
55
] | python | en | ['en', 'ny', 'en'] | False |
async_setup | (hass) | Set up the Customize config API. | Set up the Customize config API. | async def async_setup(hass):
"""Set up the Customize config API."""
async def hook(action, config_key):
"""post_write_hook for Config View that reloads groups."""
await hass.services.async_call(DOMAIN, SERVICE_RELOAD_CORE_CONFIG)
hass.http.register_view(
CustomizeConfigView(
"customize", "config", CONFIG_PATH, cv.entity_id, dict, post_write_hook=hook
)
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
")",
":",
"async",
"def",
"hook",
"(",
"action",
",",
"config_key",
")",
":",
"\"\"\"post_write_hook for Config View that reloads groups.\"\"\"",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_RELOAD_CORE_CONFIG",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"CustomizeConfigView",
"(",
"\"customize\"",
",",
"\"config\"",
",",
"CONFIG_PATH",
",",
"cv",
".",
"entity_id",
",",
"dict",
",",
"post_write_hook",
"=",
"hook",
")",
")",
"return",
"True"
] | [
11,
0
] | [
24,
15
] | python | en | ['en', 'su', 'en'] | True |
init_integration | (
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
skip_setup: bool = False,
) | Set up the Elgato Key Light integration in Home Assistant. | Set up the Elgato Key Light integration in Home Assistant. | async def init_integration(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
skip_setup: bool = False,
) -> MockConfigEntry:
"""Set up the Elgato Key Light integration in Home Assistant."""
aioclient_mock.get(
"http://1.2.3.4:9123/elgato/accessory-info",
text=load_fixture("elgato/info.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.put(
"http://1.2.3.4:9123/elgato/lights",
text=load_fixture("elgato/state.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
"http://1.2.3.4:9123/elgato/lights",
text=load_fixture("elgato/state.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
"http://5.6.7.8:9123/elgato/accessory-info",
text=load_fixture("elgato/info.json"),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="CN11A1A00001",
data={
CONF_HOST: "1.2.3.4",
CONF_PORT: 9123,
CONF_SERIAL_NUMBER: "CN11A1A00001",
},
)
entry.add_to_hass(hass)
if not skip_setup:
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry | [
"async",
"def",
"init_integration",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
",",
"skip_setup",
":",
"bool",
"=",
"False",
",",
")",
"->",
"MockConfigEntry",
":",
"aioclient_mock",
".",
"get",
"(",
"\"http://1.2.3.4:9123/elgato/accessory-info\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"elgato/info.json\"",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"CONTENT_TYPE_JSON",
"}",
",",
")",
"aioclient_mock",
".",
"put",
"(",
"\"http://1.2.3.4:9123/elgato/lights\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"elgato/state.json\"",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"CONTENT_TYPE_JSON",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://1.2.3.4:9123/elgato/lights\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"elgato/state.json\"",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"CONTENT_TYPE_JSON",
"}",
",",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://5.6.7.8:9123/elgato/accessory-info\"",
",",
"text",
"=",
"load_fixture",
"(",
"\"elgato/info.json\"",
")",
",",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"CONTENT_TYPE_JSON",
"}",
",",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"unique_id",
"=",
"\"CN11A1A00001\"",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_PORT",
":",
"9123",
",",
"CONF_SERIAL_NUMBER",
":",
"\"CN11A1A00001\"",
",",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"if",
"not",
"skip_setup",
":",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"return",
"entry"
] | [
10,
0
] | [
57,
16
] | python | en | ['en', 'en', 'en'] | True |
SummarizationDistiller.calc_ce_loss | (self, mask, s_logits, t_logits) | Copy pasted from distillbert (transformers/examples/distillation/) | Copy pasted from distillbert (transformers/examples/distillation/) | def calc_ce_loss(self, mask, s_logits, t_logits):
"""Copy pasted from distillbert (transformers/examples/distillation/)"""
# mask has False at padding_idx
sel_mask = mask[:, :, None].expand_as(s_logits)
vocab_size = s_logits.size(-1)
s_logits_slct = torch.masked_select(s_logits, sel_mask) # (bs * seq_length * voc_size) modulo the 1s in mask
t_logits_slct = torch.masked_select(t_logits, sel_mask) # (bs * seq_length * voc_size) modulo the 1s in mask
s_logits_slct = s_logits_slct.view(-1, vocab_size) # (bs * seq_length, voc_size) modulo the 1s in mask
t_logits_slct = t_logits_slct.view(-1, vocab_size) # (bs * seq_length, voc_size) modulo the 1s in mask
assert t_logits_slct.size() == s_logits_slct.size()
loss_ce = (
self.ce_loss_fct(
F.log_softmax(s_logits_slct / self.temperature, dim=-1),
F.softmax(t_logits_slct / self.temperature, dim=-1),
)
* (self.temperature) ** 2
)
return loss_ce | [
"def",
"calc_ce_loss",
"(",
"self",
",",
"mask",
",",
"s_logits",
",",
"t_logits",
")",
":",
"# mask has False at padding_idx",
"sel_mask",
"=",
"mask",
"[",
":",
",",
":",
",",
"None",
"]",
".",
"expand_as",
"(",
"s_logits",
")",
"vocab_size",
"=",
"s_logits",
".",
"size",
"(",
"-",
"1",
")",
"s_logits_slct",
"=",
"torch",
".",
"masked_select",
"(",
"s_logits",
",",
"sel_mask",
")",
"# (bs * seq_length * voc_size) modulo the 1s in mask",
"t_logits_slct",
"=",
"torch",
".",
"masked_select",
"(",
"t_logits",
",",
"sel_mask",
")",
"# (bs * seq_length * voc_size) modulo the 1s in mask",
"s_logits_slct",
"=",
"s_logits_slct",
".",
"view",
"(",
"-",
"1",
",",
"vocab_size",
")",
"# (bs * seq_length, voc_size) modulo the 1s in mask",
"t_logits_slct",
"=",
"t_logits_slct",
".",
"view",
"(",
"-",
"1",
",",
"vocab_size",
")",
"# (bs * seq_length, voc_size) modulo the 1s in mask",
"assert",
"t_logits_slct",
".",
"size",
"(",
")",
"==",
"s_logits_slct",
".",
"size",
"(",
")",
"loss_ce",
"=",
"(",
"self",
".",
"ce_loss_fct",
"(",
"F",
".",
"log_softmax",
"(",
"s_logits_slct",
"/",
"self",
".",
"temperature",
",",
"dim",
"=",
"-",
"1",
")",
",",
"F",
".",
"softmax",
"(",
"t_logits_slct",
"/",
"self",
".",
"temperature",
",",
"dim",
"=",
"-",
"1",
")",
",",
")",
"*",
"(",
"self",
".",
"temperature",
")",
"**",
"2",
")",
"return",
"loss_ce"
] | [
113,
4
] | [
130,
22
] | python | en | ['en', 'sv', 'en'] | True |
SummarizationDistiller._step | (self, batch: dict) | Compute the loss for a batch | Compute the loss for a batch | def _step(self, batch: dict) -> tuple:
"""Compute the loss for a batch"""
pad_token_id = self.tokenizer.pad_token_id
input_ids, src_mask, labels = batch["input_ids"], batch["attention_mask"], batch["labels"]
if isinstance(self.model, T5ForConditionalGeneration):
decoder_input_ids = self.model._shift_right(labels)
else:
decoder_input_ids = shift_tokens_right(labels, pad_token_id)
# noinspection PyCallingNonCallable
student_outputs = self(
input_ids,
attention_mask=src_mask,
decoder_input_ids=decoder_input_ids,
output_hidden_states=self.do_calc_hidden_loss,
output_attentions=False,
use_cache=False,
)
lm_logits = student_outputs["logits"]
# Same cross entropy vs. label smoothing logic as finetune.py
assert lm_logits.shape[-1] == self.model.config.vocab_size
if self.hparams.label_smoothing == 0:
# Same behavior as modeling_bart.py, besides ignoring pad_token_id
loss_fct = torch.nn.CrossEntropyLoss(ignore_index=pad_token_id)
student_lm_loss = loss_fct(lm_logits.view(-1, lm_logits.shape[-1]), labels.view(-1))
else:
lprobs = F.log_softmax(lm_logits, dim=-1)
student_lm_loss, _ = label_smoothed_nll_loss(
lprobs, labels, self.hparams.label_smoothing, ignore_index=pad_token_id
)
def zero_tensor():
return torch.tensor(0.0).type_as(student_lm_loss)
teacher_enc_outputs = student_outputs[
"encoder_last_hidden_state"
] # use this unless self.different_base_models
hid_loss_enc, hid_loss_dec = zero_tensor(), zero_tensor()
if self.different_encoder: # compute encoder hidden state loss
all_teacher_encoder_outputs = self.teacher.get_encoder()(
input_ids,
attention_mask=src_mask,
output_hidden_states=self.do_calc_hidden_loss,
)
if self.different_base_models:
teacher_enc_outputs = all_teacher_encoder_outputs["last_hidden_state"]
elif self.do_calc_hidden_loss:
hid_loss_enc = self.calc_hidden_loss(
src_mask,
student_outputs["encoder_hidden_states"],
all_teacher_encoder_outputs["hidden_states"],
self.e_matches,
normalize_hidden=self.hparams.normalize_hidden,
)
teacher_outputs = self.teacher(
input_ids,
attention_mask=src_mask,
encoder_outputs=(teacher_enc_outputs,),
decoder_input_ids=decoder_input_ids,
output_hidden_states=self.do_calc_hidden_loss,
use_cache=False, # since we are not passing labels, never let this default to True
)
dec_mask = decoder_input_ids.ne(pad_token_id)
loss_ce = self.calc_ce_loss(dec_mask, lm_logits, teacher_outputs["logits"])
if self.do_calc_hidden_loss: # Intermediate supervision of decoder hidden states
hid_loss_dec = self.calc_hidden_loss(
dec_mask,
student_outputs["decoder_hidden_states"],
teacher_outputs["decoder_hidden_states"],
self.d_matches,
normalize_hidden=self.hparams.normalize_hidden,
)
blended_loss = (
self.alpha_ce * loss_ce
+ self.alpha_mlm * student_lm_loss
+ self.hparams.alpha_hid * (hid_loss_enc + hid_loss_dec)
)
return blended_loss, loss_ce, student_lm_loss, hid_loss_enc, hid_loss_dec | [
"def",
"_step",
"(",
"self",
",",
"batch",
":",
"dict",
")",
"->",
"tuple",
":",
"pad_token_id",
"=",
"self",
".",
"tokenizer",
".",
"pad_token_id",
"input_ids",
",",
"src_mask",
",",
"labels",
"=",
"batch",
"[",
"\"input_ids\"",
"]",
",",
"batch",
"[",
"\"attention_mask\"",
"]",
",",
"batch",
"[",
"\"labels\"",
"]",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"T5ForConditionalGeneration",
")",
":",
"decoder_input_ids",
"=",
"self",
".",
"model",
".",
"_shift_right",
"(",
"labels",
")",
"else",
":",
"decoder_input_ids",
"=",
"shift_tokens_right",
"(",
"labels",
",",
"pad_token_id",
")",
"# noinspection PyCallingNonCallable",
"student_outputs",
"=",
"self",
"(",
"input_ids",
",",
"attention_mask",
"=",
"src_mask",
",",
"decoder_input_ids",
"=",
"decoder_input_ids",
",",
"output_hidden_states",
"=",
"self",
".",
"do_calc_hidden_loss",
",",
"output_attentions",
"=",
"False",
",",
"use_cache",
"=",
"False",
",",
")",
"lm_logits",
"=",
"student_outputs",
"[",
"\"logits\"",
"]",
"# Same cross entropy vs. label smoothing logic as finetune.py",
"assert",
"lm_logits",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"self",
".",
"model",
".",
"config",
".",
"vocab_size",
"if",
"self",
".",
"hparams",
".",
"label_smoothing",
"==",
"0",
":",
"# Same behavior as modeling_bart.py, besides ignoring pad_token_id",
"loss_fct",
"=",
"torch",
".",
"nn",
".",
"CrossEntropyLoss",
"(",
"ignore_index",
"=",
"pad_token_id",
")",
"student_lm_loss",
"=",
"loss_fct",
"(",
"lm_logits",
".",
"view",
"(",
"-",
"1",
",",
"lm_logits",
".",
"shape",
"[",
"-",
"1",
"]",
")",
",",
"labels",
".",
"view",
"(",
"-",
"1",
")",
")",
"else",
":",
"lprobs",
"=",
"F",
".",
"log_softmax",
"(",
"lm_logits",
",",
"dim",
"=",
"-",
"1",
")",
"student_lm_loss",
",",
"_",
"=",
"label_smoothed_nll_loss",
"(",
"lprobs",
",",
"labels",
",",
"self",
".",
"hparams",
".",
"label_smoothing",
",",
"ignore_index",
"=",
"pad_token_id",
")",
"def",
"zero_tensor",
"(",
")",
":",
"return",
"torch",
".",
"tensor",
"(",
"0.0",
")",
".",
"type_as",
"(",
"student_lm_loss",
")",
"teacher_enc_outputs",
"=",
"student_outputs",
"[",
"\"encoder_last_hidden_state\"",
"]",
"# use this unless self.different_base_models",
"hid_loss_enc",
",",
"hid_loss_dec",
"=",
"zero_tensor",
"(",
")",
",",
"zero_tensor",
"(",
")",
"if",
"self",
".",
"different_encoder",
":",
"# compute encoder hidden state loss",
"all_teacher_encoder_outputs",
"=",
"self",
".",
"teacher",
".",
"get_encoder",
"(",
")",
"(",
"input_ids",
",",
"attention_mask",
"=",
"src_mask",
",",
"output_hidden_states",
"=",
"self",
".",
"do_calc_hidden_loss",
",",
")",
"if",
"self",
".",
"different_base_models",
":",
"teacher_enc_outputs",
"=",
"all_teacher_encoder_outputs",
"[",
"\"last_hidden_state\"",
"]",
"elif",
"self",
".",
"do_calc_hidden_loss",
":",
"hid_loss_enc",
"=",
"self",
".",
"calc_hidden_loss",
"(",
"src_mask",
",",
"student_outputs",
"[",
"\"encoder_hidden_states\"",
"]",
",",
"all_teacher_encoder_outputs",
"[",
"\"hidden_states\"",
"]",
",",
"self",
".",
"e_matches",
",",
"normalize_hidden",
"=",
"self",
".",
"hparams",
".",
"normalize_hidden",
",",
")",
"teacher_outputs",
"=",
"self",
".",
"teacher",
"(",
"input_ids",
",",
"attention_mask",
"=",
"src_mask",
",",
"encoder_outputs",
"=",
"(",
"teacher_enc_outputs",
",",
")",
",",
"decoder_input_ids",
"=",
"decoder_input_ids",
",",
"output_hidden_states",
"=",
"self",
".",
"do_calc_hidden_loss",
",",
"use_cache",
"=",
"False",
",",
"# since we are not passing labels, never let this default to True",
")",
"dec_mask",
"=",
"decoder_input_ids",
".",
"ne",
"(",
"pad_token_id",
")",
"loss_ce",
"=",
"self",
".",
"calc_ce_loss",
"(",
"dec_mask",
",",
"lm_logits",
",",
"teacher_outputs",
"[",
"\"logits\"",
"]",
")",
"if",
"self",
".",
"do_calc_hidden_loss",
":",
"# Intermediate supervision of decoder hidden states",
"hid_loss_dec",
"=",
"self",
".",
"calc_hidden_loss",
"(",
"dec_mask",
",",
"student_outputs",
"[",
"\"decoder_hidden_states\"",
"]",
",",
"teacher_outputs",
"[",
"\"decoder_hidden_states\"",
"]",
",",
"self",
".",
"d_matches",
",",
"normalize_hidden",
"=",
"self",
".",
"hparams",
".",
"normalize_hidden",
",",
")",
"blended_loss",
"=",
"(",
"self",
".",
"alpha_ce",
"*",
"loss_ce",
"+",
"self",
".",
"alpha_mlm",
"*",
"student_lm_loss",
"+",
"self",
".",
"hparams",
".",
"alpha_hid",
"*",
"(",
"hid_loss_enc",
"+",
"hid_loss_dec",
")",
")",
"return",
"blended_loss",
",",
"loss_ce",
",",
"student_lm_loss",
",",
"hid_loss_enc",
",",
"hid_loss_dec"
] | [
138,
4
] | [
218,
81
] | python | en | ['en', 'en', 'en'] | True |
SummarizationDistiller.calc_hidden_loss | (attention_mask, hidden_states, hidden_states_T, matches, normalize_hidden) | MSE(student_hid, teacher_hid[matches]). Called "Intermediate supervision" in paper. Inspired by TinyBERT. | MSE(student_hid, teacher_hid[matches]). Called "Intermediate supervision" in paper. Inspired by TinyBERT. | def calc_hidden_loss(attention_mask, hidden_states, hidden_states_T, matches, normalize_hidden):
"""MSE(student_hid, teacher_hid[matches]). Called "Intermediate supervision" in paper. Inspired by TinyBERT."""
msg = "expected list or tuple for hidden_states, got tensor of shape: "
assert not isinstance(hidden_states, torch.Tensor), f"{msg}{hidden_states.shape}"
assert not isinstance(hidden_states_T, torch.Tensor), f"{msg}{hidden_states_T.shape}"
mask = attention_mask.to(hidden_states[0])
valid_count = mask.sum() * hidden_states[0].size(-1)
student_states = torch.stack([hidden_states[i] for i in range(len(matches))])
teacher_states = torch.stack([hidden_states_T[j] for j in matches])
assert student_states.shape == teacher_states.shape, f"{student_states.shape} != {teacher_states.shape}"
if normalize_hidden:
student_states = F.layer_norm(student_states, student_states.shape[1:])
teacher_states = F.layer_norm(teacher_states, teacher_states.shape[1:])
mse = F.mse_loss(student_states, teacher_states, reduction="none")
masked_mse = (mse * mask.unsqueeze(0).unsqueeze(-1)).sum() / valid_count
return masked_mse | [
"def",
"calc_hidden_loss",
"(",
"attention_mask",
",",
"hidden_states",
",",
"hidden_states_T",
",",
"matches",
",",
"normalize_hidden",
")",
":",
"msg",
"=",
"\"expected list or tuple for hidden_states, got tensor of shape: \"",
"assert",
"not",
"isinstance",
"(",
"hidden_states",
",",
"torch",
".",
"Tensor",
")",
",",
"f\"{msg}{hidden_states.shape}\"",
"assert",
"not",
"isinstance",
"(",
"hidden_states_T",
",",
"torch",
".",
"Tensor",
")",
",",
"f\"{msg}{hidden_states_T.shape}\"",
"mask",
"=",
"attention_mask",
".",
"to",
"(",
"hidden_states",
"[",
"0",
"]",
")",
"valid_count",
"=",
"mask",
".",
"sum",
"(",
")",
"*",
"hidden_states",
"[",
"0",
"]",
".",
"size",
"(",
"-",
"1",
")",
"student_states",
"=",
"torch",
".",
"stack",
"(",
"[",
"hidden_states",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"matches",
")",
")",
"]",
")",
"teacher_states",
"=",
"torch",
".",
"stack",
"(",
"[",
"hidden_states_T",
"[",
"j",
"]",
"for",
"j",
"in",
"matches",
"]",
")",
"assert",
"student_states",
".",
"shape",
"==",
"teacher_states",
".",
"shape",
",",
"f\"{student_states.shape} != {teacher_states.shape}\"",
"if",
"normalize_hidden",
":",
"student_states",
"=",
"F",
".",
"layer_norm",
"(",
"student_states",
",",
"student_states",
".",
"shape",
"[",
"1",
":",
"]",
")",
"teacher_states",
"=",
"F",
".",
"layer_norm",
"(",
"teacher_states",
",",
"teacher_states",
".",
"shape",
"[",
"1",
":",
"]",
")",
"mse",
"=",
"F",
".",
"mse_loss",
"(",
"student_states",
",",
"teacher_states",
",",
"reduction",
"=",
"\"none\"",
")",
"masked_mse",
"=",
"(",
"mse",
"*",
"mask",
".",
"unsqueeze",
"(",
"0",
")",
".",
"unsqueeze",
"(",
"-",
"1",
")",
")",
".",
"sum",
"(",
")",
"/",
"valid_count",
"return",
"masked_mse"
] | [
221,
4
] | [
236,
25
] | python | en | ['en', 'en', 'en'] | True |
test_abort_if_no_configuration | (hass) | Check flow aborts when no configuration is present. | Check flow aborts when no configuration is present. | async def test_abort_if_no_configuration(hass):
"""Check flow aborts when no configuration is present."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "missing_configuration"
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "missing_configuration" | [
"async",
"def",
"test_abort_if_no_configuration",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"missing_configuration\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"missing_configuration\""
] | [
13,
0
] | [
27,
54
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_abort_if_existing_entry | (hass) | Check zeroconf flow aborts when an entry already exist. | Check zeroconf flow aborts when an entry already exist. | async def test_zeroconf_abort_if_existing_entry(hass):
"""Check zeroconf flow aborts when an entry already exist."""
MockConfigEntry(domain=DOMAIN).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_zeroconf_abort_if_existing_entry",
"(",
"hass",
")",
":",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
30,
0
] | [
39,
51
] | python | en | ['en', 'gl', 'en'] | True |
test_full_flow | (hass, aiohttp_client, aioclient_mock, current_request) | Check a full flow. | Check a full flow. | async def test_full_flow(hass, aiohttp_client, aioclient_mock, current_request):
"""Check a full flow."""
assert await setup.async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {CONF_CLIENT_ID: "client", CONF_CLIENT_SECRET: "secret"},
"http": {"base_url": "https://example.com"},
},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# pylint: disable=protected-access
state = config_entry_oauth2_flow._encode_jwt(hass, {"flow_id": result["flow_id"]})
assert result["type"] == data_entry_flow.RESULT_TYPE_EXTERNAL_STEP
assert result["url"] == (
"https://accounts.spotify.com/authorize"
"?response_type=code&client_id=client"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}"
"&scope=user-modify-playback-state,user-read-playback-state,user-read-private,"
"playlist-read-private,playlist-read-collaborative,user-library-read,"
"user-top-read,user-read-playback-position,user-read-recently-played,user-follow-read"
)
client = await aiohttp_client(hass.http.app)
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post(
"https://accounts.spotify.com/api/token",
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock:
spotify_mock.return_value.current_user.return_value = {
"id": "fake_id",
"display_name": "frenck",
}
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["data"]["auth_implementation"] == DOMAIN
result["data"]["token"].pop("expires_at")
assert result["data"]["name"] == "frenck"
assert result["data"]["token"] == {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
} | [
"async",
"def",
"test_full_flow",
"(",
"hass",
",",
"aiohttp_client",
",",
"aioclient_mock",
",",
"current_request",
")",
":",
"assert",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"CONF_CLIENT_ID",
":",
"\"client\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"secret\"",
"}",
",",
"\"http\"",
":",
"{",
"\"base_url\"",
":",
"\"https://example.com\"",
"}",
",",
"}",
",",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"# pylint: disable=protected-access",
"state",
"=",
"config_entry_oauth2_flow",
".",
"_encode_jwt",
"(",
"hass",
",",
"{",
"\"flow_id\"",
":",
"result",
"[",
"\"flow_id\"",
"]",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_EXTERNAL_STEP",
"assert",
"result",
"[",
"\"url\"",
"]",
"==",
"(",
"\"https://accounts.spotify.com/authorize\"",
"\"?response_type=code&client_id=client\"",
"\"&redirect_uri=https://example.com/auth/external/callback\"",
"f\"&state={state}\"",
"\"&scope=user-modify-playback-state,user-read-playback-state,user-read-private,\"",
"\"playlist-read-private,playlist-read-collaborative,user-library-read,\"",
"\"user-top-read,user-read-playback-position,user-read-recently-played,user-follow-read\"",
")",
"client",
"=",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
"resp",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/auth/external/callback?code=abcd&state={state}\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"assert",
"resp",
".",
"headers",
"[",
"\"content-type\"",
"]",
"==",
"\"text/html; charset=utf-8\"",
"aioclient_mock",
".",
"post",
"(",
"\"https://accounts.spotify.com/api/token\"",
",",
"json",
"=",
"{",
"\"refresh_token\"",
":",
"\"mock-refresh-token\"",
",",
"\"access_token\"",
":",
"\"mock-access-token\"",
",",
"\"type\"",
":",
"\"Bearer\"",
",",
"\"expires_in\"",
":",
"60",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.components.spotify.config_flow.Spotify\"",
")",
"as",
"spotify_mock",
":",
"spotify_mock",
".",
"return_value",
".",
"current_user",
".",
"return_value",
"=",
"{",
"\"id\"",
":",
"\"fake_id\"",
",",
"\"display_name\"",
":",
"\"frenck\"",
",",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
")",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"auth_implementation\"",
"]",
"==",
"DOMAIN",
"result",
"[",
"\"data\"",
"]",
"[",
"\"token\"",
"]",
".",
"pop",
"(",
"\"expires_at\"",
")",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"name\"",
"]",
"==",
"\"frenck\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"token\"",
"]",
"==",
"{",
"\"refresh_token\"",
":",
"\"mock-refresh-token\"",
",",
"\"access_token\"",
":",
"\"mock-access-token\"",
",",
"\"type\"",
":",
"\"Bearer\"",
",",
"\"expires_in\"",
":",
"60",
",",
"}"
] | [
42,
0
] | [
101,
5
] | python | en | ['en', 'en', 'en'] | True |
test_abort_if_spotify_error | (
hass, aiohttp_client, aioclient_mock, current_request
) | Check Spotify errors causes flow to abort. | Check Spotify errors causes flow to abort. | async def test_abort_if_spotify_error(
hass, aiohttp_client, aioclient_mock, current_request
):
"""Check Spotify errors causes flow to abort."""
await setup.async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {CONF_CLIENT_ID: "client", CONF_CLIENT_SECRET: "secret"},
"http": {"base_url": "https://example.com"},
},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# pylint: disable=protected-access
state = config_entry_oauth2_flow._encode_jwt(hass, {"flow_id": result["flow_id"]})
client = await aiohttp_client(hass.http.app)
await client.get(f"/auth/external/callback?code=abcd&state={state}")
aioclient_mock.post(
"https://accounts.spotify.com/api/token",
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with patch(
"homeassistant.components.spotify.config_flow.Spotify.current_user",
side_effect=SpotifyException(400, -1, "message"),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "connection_error" | [
"async",
"def",
"test_abort_if_spotify_error",
"(",
"hass",
",",
"aiohttp_client",
",",
"aioclient_mock",
",",
"current_request",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"CONF_CLIENT_ID",
":",
"\"client\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"secret\"",
"}",
",",
"\"http\"",
":",
"{",
"\"base_url\"",
":",
"\"https://example.com\"",
"}",
",",
"}",
",",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"# pylint: disable=protected-access",
"state",
"=",
"config_entry_oauth2_flow",
".",
"_encode_jwt",
"(",
"hass",
",",
"{",
"\"flow_id\"",
":",
"result",
"[",
"\"flow_id\"",
"]",
"}",
")",
"client",
"=",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
"await",
"client",
".",
"get",
"(",
"f\"/auth/external/callback?code=abcd&state={state}\"",
")",
"aioclient_mock",
".",
"post",
"(",
"\"https://accounts.spotify.com/api/token\"",
",",
"json",
"=",
"{",
"\"refresh_token\"",
":",
"\"mock-refresh-token\"",
",",
"\"access_token\"",
":",
"\"mock-access-token\"",
",",
"\"type\"",
":",
"\"Bearer\"",
",",
"\"expires_in\"",
":",
"60",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.components.spotify.config_flow.Spotify.current_user\"",
",",
"side_effect",
"=",
"SpotifyException",
"(",
"400",
",",
"-",
"1",
",",
"\"message\"",
")",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"connection_error\""
] | [
104,
0
] | [
143,
49
] | python | en | ['en', 'en', 'en'] | True |
test_reauthentication | (hass, aiohttp_client, aioclient_mock, current_request) | Test Spotify reauthentication. | Test Spotify reauthentication. | async def test_reauthentication(hass, aiohttp_client, aioclient_mock, current_request):
"""Test Spotify reauthentication."""
await setup.async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {CONF_CLIENT_ID: "client", CONF_CLIENT_SECRET: "secret"},
"http": {"base_url": "https://example.com"},
},
)
old_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=123,
version=1,
data={"id": "frenck", "auth_implementation": DOMAIN},
)
old_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=old_entry.data
)
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
result = await hass.config_entries.flow.async_configure(flows[0]["flow_id"], {})
# pylint: disable=protected-access
state = config_entry_oauth2_flow._encode_jwt(hass, {"flow_id": result["flow_id"]})
client = await aiohttp_client(hass.http.app)
await client.get(f"/auth/external/callback?code=abcd&state={state}")
aioclient_mock.post(
"https://accounts.spotify.com/api/token",
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock:
spotify_mock.return_value.current_user.return_value = {"id": "frenck"}
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["data"]["auth_implementation"] == DOMAIN
result["data"]["token"].pop("expires_at")
assert result["data"]["token"] == {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
} | [
"async",
"def",
"test_reauthentication",
"(",
"hass",
",",
"aiohttp_client",
",",
"aioclient_mock",
",",
"current_request",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"CONF_CLIENT_ID",
":",
"\"client\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"secret\"",
"}",
",",
"\"http\"",
":",
"{",
"\"base_url\"",
":",
"\"https://example.com\"",
"}",
",",
"}",
",",
")",
"old_entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"unique_id",
"=",
"123",
",",
"version",
"=",
"1",
",",
"data",
"=",
"{",
"\"id\"",
":",
"\"frenck\"",
",",
"\"auth_implementation\"",
":",
"DOMAIN",
"}",
",",
")",
"old_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"reauth\"",
"}",
",",
"data",
"=",
"old_entry",
".",
"data",
")",
"flows",
"=",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_progress",
"(",
")",
"assert",
"len",
"(",
"flows",
")",
"==",
"1",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"flows",
"[",
"0",
"]",
"[",
"\"flow_id\"",
"]",
",",
"{",
"}",
")",
"# pylint: disable=protected-access",
"state",
"=",
"config_entry_oauth2_flow",
".",
"_encode_jwt",
"(",
"hass",
",",
"{",
"\"flow_id\"",
":",
"result",
"[",
"\"flow_id\"",
"]",
"}",
")",
"client",
"=",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
"await",
"client",
".",
"get",
"(",
"f\"/auth/external/callback?code=abcd&state={state}\"",
")",
"aioclient_mock",
".",
"post",
"(",
"\"https://accounts.spotify.com/api/token\"",
",",
"json",
"=",
"{",
"\"refresh_token\"",
":",
"\"mock-refresh-token\"",
",",
"\"access_token\"",
":",
"\"mock-access-token\"",
",",
"\"type\"",
":",
"\"Bearer\"",
",",
"\"expires_in\"",
":",
"60",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.components.spotify.config_flow.Spotify\"",
")",
"as",
"spotify_mock",
":",
"spotify_mock",
".",
"return_value",
".",
"current_user",
".",
"return_value",
"=",
"{",
"\"id\"",
":",
"\"frenck\"",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
")",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"auth_implementation\"",
"]",
"==",
"DOMAIN",
"result",
"[",
"\"data\"",
"]",
"[",
"\"token\"",
"]",
".",
"pop",
"(",
"\"expires_at\"",
")",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"token\"",
"]",
"==",
"{",
"\"refresh_token\"",
":",
"\"mock-refresh-token\"",
",",
"\"access_token\"",
":",
"\"mock-access-token\"",
",",
"\"type\"",
":",
"\"Bearer\"",
",",
"\"expires_in\"",
":",
"60",
",",
"}"
] | [
146,
0
] | [
200,
5
] | python | de | ['de', 'en', 'it'] | False |
test_reauth_account_mismatch | (
hass, aiohttp_client, aioclient_mock, current_request
) | Test Spotify reauthentication with different account. | Test Spotify reauthentication with different account. | async def test_reauth_account_mismatch(
hass, aiohttp_client, aioclient_mock, current_request
):
"""Test Spotify reauthentication with different account."""
await setup.async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {CONF_CLIENT_ID: "client", CONF_CLIENT_SECRET: "secret"},
"http": {"base_url": "https://example.com"},
},
)
old_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=123,
version=1,
data={"id": "frenck", "auth_implementation": DOMAIN},
)
old_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=old_entry.data
)
flows = hass.config_entries.flow.async_progress()
result = await hass.config_entries.flow.async_configure(flows[0]["flow_id"], {})
# pylint: disable=protected-access
state = config_entry_oauth2_flow._encode_jwt(hass, {"flow_id": result["flow_id"]})
client = await aiohttp_client(hass.http.app)
await client.get(f"/auth/external/callback?code=abcd&state={state}")
aioclient_mock.post(
"https://accounts.spotify.com/api/token",
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with patch("homeassistant.components.spotify.config_flow.Spotify") as spotify_mock:
spotify_mock.return_value.current_user.return_value = {"id": "fake_id"}
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "reauth_account_mismatch" | [
"async",
"def",
"test_reauth_account_mismatch",
"(",
"hass",
",",
"aiohttp_client",
",",
"aioclient_mock",
",",
"current_request",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"CONF_CLIENT_ID",
":",
"\"client\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"secret\"",
"}",
",",
"\"http\"",
":",
"{",
"\"base_url\"",
":",
"\"https://example.com\"",
"}",
",",
"}",
",",
")",
"old_entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"unique_id",
"=",
"123",
",",
"version",
"=",
"1",
",",
"data",
"=",
"{",
"\"id\"",
":",
"\"frenck\"",
",",
"\"auth_implementation\"",
":",
"DOMAIN",
"}",
",",
")",
"old_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"reauth\"",
"}",
",",
"data",
"=",
"old_entry",
".",
"data",
")",
"flows",
"=",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_progress",
"(",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"flows",
"[",
"0",
"]",
"[",
"\"flow_id\"",
"]",
",",
"{",
"}",
")",
"# pylint: disable=protected-access",
"state",
"=",
"config_entry_oauth2_flow",
".",
"_encode_jwt",
"(",
"hass",
",",
"{",
"\"flow_id\"",
":",
"result",
"[",
"\"flow_id\"",
"]",
"}",
")",
"client",
"=",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
"await",
"client",
".",
"get",
"(",
"f\"/auth/external/callback?code=abcd&state={state}\"",
")",
"aioclient_mock",
".",
"post",
"(",
"\"https://accounts.spotify.com/api/token\"",
",",
"json",
"=",
"{",
"\"refresh_token\"",
":",
"\"mock-refresh-token\"",
",",
"\"access_token\"",
":",
"\"mock-access-token\"",
",",
"\"type\"",
":",
"\"Bearer\"",
",",
"\"expires_in\"",
":",
"60",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.components.spotify.config_flow.Spotify\"",
")",
"as",
"spotify_mock",
":",
"spotify_mock",
".",
"return_value",
".",
"current_user",
".",
"return_value",
"=",
"{",
"\"id\"",
":",
"\"fake_id\"",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"reauth_account_mismatch\""
] | [
203,
0
] | [
251,
56
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, yaml_config) | Activate Azure EH component. | Activate Azure EH component. | async def async_setup(hass, yaml_config):
"""Activate Azure EH component."""
config = yaml_config[DOMAIN]
if config.get(CONF_EVENT_HUB_CON_STRING):
client_args = {"conn_str": config[CONF_EVENT_HUB_CON_STRING]}
conn_str_client = True
else:
client_args = {
"fully_qualified_namespace": f"{config[CONF_EVENT_HUB_NAMESPACE]}.servicebus.windows.net",
"credential": EventHubSharedKeyCredential(
policy=config[CONF_EVENT_HUB_SAS_POLICY],
key=config[CONF_EVENT_HUB_SAS_KEY],
),
"eventhub_name": config[CONF_EVENT_HUB_INSTANCE_NAME],
}
conn_str_client = False
instance = hass.data[DOMAIN] = AzureEventHub(
hass,
client_args,
conn_str_client,
config[CONF_FILTER],
config[CONF_SEND_INTERVAL],
config[CONF_MAX_DELAY],
)
hass.async_create_task(instance.async_start())
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"yaml_config",
")",
":",
"config",
"=",
"yaml_config",
"[",
"DOMAIN",
"]",
"if",
"config",
".",
"get",
"(",
"CONF_EVENT_HUB_CON_STRING",
")",
":",
"client_args",
"=",
"{",
"\"conn_str\"",
":",
"config",
"[",
"CONF_EVENT_HUB_CON_STRING",
"]",
"}",
"conn_str_client",
"=",
"True",
"else",
":",
"client_args",
"=",
"{",
"\"fully_qualified_namespace\"",
":",
"f\"{config[CONF_EVENT_HUB_NAMESPACE]}.servicebus.windows.net\"",
",",
"\"credential\"",
":",
"EventHubSharedKeyCredential",
"(",
"policy",
"=",
"config",
"[",
"CONF_EVENT_HUB_SAS_POLICY",
"]",
",",
"key",
"=",
"config",
"[",
"CONF_EVENT_HUB_SAS_KEY",
"]",
",",
")",
",",
"\"eventhub_name\"",
":",
"config",
"[",
"CONF_EVENT_HUB_INSTANCE_NAME",
"]",
",",
"}",
"conn_str_client",
"=",
"False",
"instance",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"AzureEventHub",
"(",
"hass",
",",
"client_args",
",",
"conn_str_client",
",",
"config",
"[",
"CONF_FILTER",
"]",
",",
"config",
"[",
"CONF_SEND_INTERVAL",
"]",
",",
"config",
"[",
"CONF_MAX_DELAY",
"]",
",",
")",
"hass",
".",
"async_create_task",
"(",
"instance",
".",
"async_start",
"(",
")",
")",
"return",
"True"
] | [
61,
0
] | [
88,
15
] | python | en | ['eu', 'en', 'en'] | True |
AzureEventHub.__init__ | (
self,
hass: HomeAssistant,
client_args: Dict[str, Any],
conn_str_client: bool,
entities_filter: vol.Schema,
send_interval: int,
max_delay: int,
) | Initialize the listener. | Initialize the listener. | def __init__(
self,
hass: HomeAssistant,
client_args: Dict[str, Any],
conn_str_client: bool,
entities_filter: vol.Schema,
send_interval: int,
max_delay: int,
):
"""Initialize the listener."""
self.hass = hass
self.queue = asyncio.PriorityQueue()
self._client_args = client_args
self._conn_str_client = conn_str_client
self._entities_filter = entities_filter
self._send_interval = send_interval
self._max_delay = max_delay + send_interval
self._listener_remover = None
self._next_send_remover = None
self.shutdown = False | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistant",
",",
"client_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"conn_str_client",
":",
"bool",
",",
"entities_filter",
":",
"vol",
".",
"Schema",
",",
"send_interval",
":",
"int",
",",
"max_delay",
":",
"int",
",",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"queue",
"=",
"asyncio",
".",
"PriorityQueue",
"(",
")",
"self",
".",
"_client_args",
"=",
"client_args",
"self",
".",
"_conn_str_client",
"=",
"conn_str_client",
"self",
".",
"_entities_filter",
"=",
"entities_filter",
"self",
".",
"_send_interval",
"=",
"send_interval",
"self",
".",
"_max_delay",
"=",
"max_delay",
"+",
"send_interval",
"self",
".",
"_listener_remover",
"=",
"None",
"self",
".",
"_next_send_remover",
"=",
"None",
"self",
".",
"shutdown",
"=",
"False"
] | [
94,
4
] | [
113,
29
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub.async_start | (self) | Start the recorder, suppress logging and register the callbacks and do the first send after five seconds, to capture the startup events. | Start the recorder, suppress logging and register the callbacks and do the first send after five seconds, to capture the startup events. | async def async_start(self):
"""Start the recorder, suppress logging and register the callbacks and do the first send after five seconds, to capture the startup events."""
# suppress the INFO and below logging on the underlying packages, they are very verbose, even at INFO
logging.getLogger("uamqp").setLevel(logging.WARNING)
logging.getLogger("azure.eventhub").setLevel(logging.WARNING)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.async_shutdown)
self._listener_remover = self.hass.bus.async_listen(
MATCH_ALL, self.async_listen
)
# schedule the first send after 10 seconds to capture startup events, after that each send will schedule the next after the interval.
self._next_send_remover = async_call_later(self.hass, 10, self.async_send) | [
"async",
"def",
"async_start",
"(",
"self",
")",
":",
"# suppress the INFO and below logging on the underlying packages, they are very verbose, even at INFO",
"logging",
".",
"getLogger",
"(",
"\"uamqp\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"logging",
".",
"getLogger",
"(",
"\"azure.eventhub\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"self",
".",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"self",
".",
"async_shutdown",
")",
"self",
".",
"_listener_remover",
"=",
"self",
".",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"MATCH_ALL",
",",
"self",
".",
"async_listen",
")",
"# schedule the first send after 10 seconds to capture startup events, after that each send will schedule the next after the interval.",
"self",
".",
"_next_send_remover",
"=",
"async_call_later",
"(",
"self",
".",
"hass",
",",
"10",
",",
"self",
".",
"async_send",
")"
] | [
115,
4
] | [
126,
82
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub.async_shutdown | (self, _: Event) | Shut down the AEH by queueing None and calling send. | Shut down the AEH by queueing None and calling send. | async def async_shutdown(self, _: Event):
"""Shut down the AEH by queueing None and calling send."""
if self._next_send_remover:
self._next_send_remover()
if self._listener_remover:
self._listener_remover()
await self.queue.put((3, (time.monotonic(), None)))
await self.async_send(None) | [
"async",
"def",
"async_shutdown",
"(",
"self",
",",
"_",
":",
"Event",
")",
":",
"if",
"self",
".",
"_next_send_remover",
":",
"self",
".",
"_next_send_remover",
"(",
")",
"if",
"self",
".",
"_listener_remover",
":",
"self",
".",
"_listener_remover",
"(",
")",
"await",
"self",
".",
"queue",
".",
"put",
"(",
"(",
"3",
",",
"(",
"time",
".",
"monotonic",
"(",
")",
",",
"None",
")",
")",
")",
"await",
"self",
".",
"async_send",
"(",
"None",
")"
] | [
128,
4
] | [
135,
35
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub.async_listen | (self, event: Event) | Listen for new messages on the bus and queue them for AEH. | Listen for new messages on the bus and queue them for AEH. | async def async_listen(self, event: Event):
"""Listen for new messages on the bus and queue them for AEH."""
await self.queue.put((2, (time.monotonic(), event))) | [
"async",
"def",
"async_listen",
"(",
"self",
",",
"event",
":",
"Event",
")",
":",
"await",
"self",
".",
"queue",
".",
"put",
"(",
"(",
"2",
",",
"(",
"time",
".",
"monotonic",
"(",
")",
",",
"event",
")",
")",
")"
] | [
137,
4
] | [
139,
60
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub.async_send | (self, _) | Write preprocessed events to eventhub, with retry. | Write preprocessed events to eventhub, with retry. | async def async_send(self, _):
"""Write preprocessed events to eventhub, with retry."""
client = self._get_client()
async with client:
while not self.queue.empty():
data_batch, dequeue_count = await self.fill_batch(client)
_LOGGER.debug(
"Sending %d event(s), out of %d events in the queue",
len(data_batch),
dequeue_count,
)
if data_batch:
try:
await client.send_batch(data_batch)
except EventHubError as exc:
_LOGGER.error("Error in sending events to Event Hub: %s", exc)
finally:
for _ in range(dequeue_count):
self.queue.task_done()
await client.close()
if not self.shutdown:
self._next_send_remover = async_call_later(
self.hass, self._send_interval, self.async_send
) | [
"async",
"def",
"async_send",
"(",
"self",
",",
"_",
")",
":",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"async",
"with",
"client",
":",
"while",
"not",
"self",
".",
"queue",
".",
"empty",
"(",
")",
":",
"data_batch",
",",
"dequeue_count",
"=",
"await",
"self",
".",
"fill_batch",
"(",
"client",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Sending %d event(s), out of %d events in the queue\"",
",",
"len",
"(",
"data_batch",
")",
",",
"dequeue_count",
",",
")",
"if",
"data_batch",
":",
"try",
":",
"await",
"client",
".",
"send_batch",
"(",
"data_batch",
")",
"except",
"EventHubError",
"as",
"exc",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error in sending events to Event Hub: %s\"",
",",
"exc",
")",
"finally",
":",
"for",
"_",
"in",
"range",
"(",
"dequeue_count",
")",
":",
"self",
".",
"queue",
".",
"task_done",
"(",
")",
"await",
"client",
".",
"close",
"(",
")",
"if",
"not",
"self",
".",
"shutdown",
":",
"self",
".",
"_next_send_remover",
"=",
"async_call_later",
"(",
"self",
".",
"hass",
",",
"self",
".",
"_send_interval",
",",
"self",
".",
"async_send",
")"
] | [
141,
4
] | [
165,
13
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub.fill_batch | (self, client) | Return a batch of events formatted for writing.
Uses get_nowait instead of await get, because the functions batches and doesn't wait for each single event, the send function is called.
Throws ValueError on add to batch when the EventDataBatch object reaches max_size. Put the item back in the queue and the next batch will include it.
| Return a batch of events formatted for writing. | async def fill_batch(self, client):
"""Return a batch of events formatted for writing.
Uses get_nowait instead of await get, because the functions batches and doesn't wait for each single event, the send function is called.
Throws ValueError on add to batch when the EventDataBatch object reaches max_size. Put the item back in the queue and the next batch will include it.
"""
event_batch = await client.create_batch()
dequeue_count = 0
dropped = 0
while not self.shutdown:
try:
_, (timestamp, event) = self.queue.get_nowait()
except asyncio.QueueEmpty:
break
dequeue_count += 1
if not event:
self.shutdown = True
break
event_data = self._event_to_filtered_event_data(event)
if not event_data:
continue
if time.monotonic() - timestamp <= self._max_delay:
try:
event_batch.add(event_data)
except ValueError:
self.queue.put_nowait((1, (timestamp, event)))
break
else:
dropped += 1
if dropped:
_LOGGER.warning(
"Dropped %d old events, consider increasing the max_delay", dropped
)
return event_batch, dequeue_count | [
"async",
"def",
"fill_batch",
"(",
"self",
",",
"client",
")",
":",
"event_batch",
"=",
"await",
"client",
".",
"create_batch",
"(",
")",
"dequeue_count",
"=",
"0",
"dropped",
"=",
"0",
"while",
"not",
"self",
".",
"shutdown",
":",
"try",
":",
"_",
",",
"(",
"timestamp",
",",
"event",
")",
"=",
"self",
".",
"queue",
".",
"get_nowait",
"(",
")",
"except",
"asyncio",
".",
"QueueEmpty",
":",
"break",
"dequeue_count",
"+=",
"1",
"if",
"not",
"event",
":",
"self",
".",
"shutdown",
"=",
"True",
"break",
"event_data",
"=",
"self",
".",
"_event_to_filtered_event_data",
"(",
"event",
")",
"if",
"not",
"event_data",
":",
"continue",
"if",
"time",
".",
"monotonic",
"(",
")",
"-",
"timestamp",
"<=",
"self",
".",
"_max_delay",
":",
"try",
":",
"event_batch",
".",
"add",
"(",
"event_data",
")",
"except",
"ValueError",
":",
"self",
".",
"queue",
".",
"put_nowait",
"(",
"(",
"1",
",",
"(",
"timestamp",
",",
"event",
")",
")",
")",
"break",
"else",
":",
"dropped",
"+=",
"1",
"if",
"dropped",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Dropped %d old events, consider increasing the max_delay\"",
",",
"dropped",
")",
"return",
"event_batch",
",",
"dequeue_count"
] | [
167,
4
] | [
203,
41
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub._event_to_filtered_event_data | (self, event: Event) | Filter event states and create EventData object. | Filter event states and create EventData object. | def _event_to_filtered_event_data(self, event: Event):
"""Filter event states and create EventData object."""
state = event.data.get("new_state")
if (
state is None
or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE)
or not self._entities_filter(state.entity_id)
):
return None
return EventData(json.dumps(obj=state, cls=JSONEncoder).encode("utf-8")) | [
"def",
"_event_to_filtered_event_data",
"(",
"self",
",",
"event",
":",
"Event",
")",
":",
"state",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"new_state\"",
")",
"if",
"(",
"state",
"is",
"None",
"or",
"state",
".",
"state",
"in",
"(",
"STATE_UNKNOWN",
",",
"\"\"",
",",
"STATE_UNAVAILABLE",
")",
"or",
"not",
"self",
".",
"_entities_filter",
"(",
"state",
".",
"entity_id",
")",
")",
":",
"return",
"None",
"return",
"EventData",
"(",
"json",
".",
"dumps",
"(",
"obj",
"=",
"state",
",",
"cls",
"=",
"JSONEncoder",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")"
] | [
205,
4
] | [
214,
80
] | python | en | ['en', 'en', 'en'] | True |
AzureEventHub._get_client | (self) | Get a Event Producer Client. | Get a Event Producer Client. | def _get_client(self):
"""Get a Event Producer Client."""
if self._conn_str_client:
return EventHubProducerClient.from_connection_string(
**self._client_args, **ADDITIONAL_ARGS
)
return EventHubProducerClient(**self._client_args, **ADDITIONAL_ARGS) | [
"def",
"_get_client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_conn_str_client",
":",
"return",
"EventHubProducerClient",
".",
"from_connection_string",
"(",
"*",
"*",
"self",
".",
"_client_args",
",",
"*",
"*",
"ADDITIONAL_ARGS",
")",
"return",
"EventHubProducerClient",
"(",
"*",
"*",
"self",
".",
"_client_args",
",",
"*",
"*",
"ADDITIONAL_ARGS",
")"
] | [
216,
4
] | [
222,
77
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: core.HomeAssistant, config: dict) | Set up the Rollease Acmeda Automate component. | Set up the Rollease Acmeda Automate component. | async def async_setup(hass: core.HomeAssistant, config: dict):
"""Set up the Rollease Acmeda Automate component."""
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"return",
"True"
] | [
13,
0
] | [
15,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry
) | Set up Rollease Acmeda Automate hub from a config entry. | Set up Rollease Acmeda Automate hub from a config entry. | async def async_setup_entry(
hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry
):
"""Set up Rollease Acmeda Automate hub from a config entry."""
hub = PulseHub(hass, config_entry)
if not await hub.async_setup():
return False
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][config_entry.entry_id] = hub
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, component)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"config_entry",
":",
"config_entries",
".",
"ConfigEntry",
")",
":",
"hub",
"=",
"PulseHub",
"(",
"hass",
",",
"config_entry",
")",
"if",
"not",
"await",
"hub",
".",
"async_setup",
"(",
")",
":",
"return",
"False",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"=",
"hub",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"config_entry",
",",
"component",
")",
")",
"return",
"True"
] | [
18,
0
] | [
35,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (
hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry
) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(
hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry
):
"""Unload a config entry."""
hub = hass.data[DOMAIN][config_entry.entry_id]
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(config_entry, component)
for component in PLATFORMS
]
)
)
if not await hub.async_reset():
return False
if unload_ok:
hass.data[DOMAIN].pop(config_entry.entry_id)
return unload_ok | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"config_entry",
":",
"config_entries",
".",
"ConfigEntry",
")",
":",
"hub",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"config_entry",
",",
"component",
")",
"for",
"component",
"in",
"PLATFORMS",
"]",
")",
")",
"if",
"not",
"await",
"hub",
".",
"async_reset",
"(",
")",
":",
"return",
"False",
"if",
"unload_ok",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"config_entry",
".",
"entry_id",
")",
"return",
"unload_ok"
] | [
38,
0
] | [
58,
20
] | python | en | ['en', 'es', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the Tesla binary_sensors by config_entry. | Set up the Tesla binary_sensors by config_entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Tesla binary_sensors by config_entry."""
coordinator = hass.data[TESLA_DOMAIN][config_entry.entry_id]["coordinator"]
entities = []
for device in hass.data[TESLA_DOMAIN][config_entry.entry_id]["devices"]["sensor"]:
if device.type == "temperature sensor":
entities.append(TeslaSensor(device, coordinator, "inside"))
entities.append(TeslaSensor(device, coordinator, "outside"))
else:
entities.append(TeslaSensor(device, coordinator))
async_add_entities(entities, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"coordinator",
"=",
"hass",
".",
"data",
"[",
"TESLA_DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"\"coordinator\"",
"]",
"entities",
"=",
"[",
"]",
"for",
"device",
"in",
"hass",
".",
"data",
"[",
"TESLA_DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"\"devices\"",
"]",
"[",
"\"sensor\"",
"]",
":",
"if",
"device",
".",
"type",
"==",
"\"temperature sensor\"",
":",
"entities",
".",
"append",
"(",
"TeslaSensor",
"(",
"device",
",",
"coordinator",
",",
"\"inside\"",
")",
")",
"entities",
".",
"append",
"(",
"TeslaSensor",
"(",
"device",
",",
"coordinator",
",",
"\"outside\"",
")",
")",
"else",
":",
"entities",
".",
"append",
"(",
"TeslaSensor",
"(",
"device",
",",
"coordinator",
")",
")",
"async_add_entities",
"(",
"entities",
",",
"True",
")"
] | [
16,
0
] | [
26,
38
] | python | en | ['en', 'en', 'en'] | True |
TeslaSensor.__init__ | (self, tesla_device, coordinator, sensor_type=None) | Initialize of the sensor. | Initialize of the sensor. | def __init__(self, tesla_device, coordinator, sensor_type=None):
"""Initialize of the sensor."""
super().__init__(tesla_device, coordinator)
self.type = sensor_type
if self.type:
self._name = f"{super().name} ({self.type})"
self._unique_id = f"{super().unique_id}_{self.type}" | [
"def",
"__init__",
"(",
"self",
",",
"tesla_device",
",",
"coordinator",
",",
"sensor_type",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"tesla_device",
",",
"coordinator",
")",
"self",
".",
"type",
"=",
"sensor_type",
"if",
"self",
".",
"type",
":",
"self",
".",
"_name",
"=",
"f\"{super().name} ({self.type})\"",
"self",
".",
"_unique_id",
"=",
"f\"{super().unique_id}_{self.type}\""
] | [
32,
4
] | [
38,
64
] | python | en | ['en', 'en', 'en'] | True |
TeslaSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self) -> Optional[float]:
"""Return the state of the sensor."""
if self.tesla_device.type == "temperature sensor":
if self.type == "outside":
return self.tesla_device.get_outside_temp()
return self.tesla_device.get_inside_temp()
if self.tesla_device.type in ["range sensor", "mileage sensor"]:
units = self.tesla_device.measurement
if units == "LENGTH_MILES":
return self.tesla_device.get_value()
return round(
convert(self.tesla_device.get_value(), LENGTH_MILES, LENGTH_KILOMETERS),
2,
)
if self.tesla_device.type == "charging rate sensor":
return self.tesla_device.charging_rate
return self.tesla_device.get_value() | [
"def",
"state",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"if",
"self",
".",
"tesla_device",
".",
"type",
"==",
"\"temperature sensor\"",
":",
"if",
"self",
".",
"type",
"==",
"\"outside\"",
":",
"return",
"self",
".",
"tesla_device",
".",
"get_outside_temp",
"(",
")",
"return",
"self",
".",
"tesla_device",
".",
"get_inside_temp",
"(",
")",
"if",
"self",
".",
"tesla_device",
".",
"type",
"in",
"[",
"\"range sensor\"",
",",
"\"mileage sensor\"",
"]",
":",
"units",
"=",
"self",
".",
"tesla_device",
".",
"measurement",
"if",
"units",
"==",
"\"LENGTH_MILES\"",
":",
"return",
"self",
".",
"tesla_device",
".",
"get_value",
"(",
")",
"return",
"round",
"(",
"convert",
"(",
"self",
".",
"tesla_device",
".",
"get_value",
"(",
")",
",",
"LENGTH_MILES",
",",
"LENGTH_KILOMETERS",
")",
",",
"2",
",",
")",
"if",
"self",
".",
"tesla_device",
".",
"type",
"==",
"\"charging rate sensor\"",
":",
"return",
"self",
".",
"tesla_device",
".",
"charging_rate",
"return",
"self",
".",
"tesla_device",
".",
"get_value",
"(",
")"
] | [
41,
4
] | [
57,
44
] | python | en | ['en', 'en', 'en'] | True |
TeslaSensor.unit_of_measurement | (self) | Return the unit_of_measurement of the device. | Return the unit_of_measurement of the device. | def unit_of_measurement(self) -> Optional[str]:
"""Return the unit_of_measurement of the device."""
units = self.tesla_device.measurement
if units == "F":
return TEMP_FAHRENHEIT
if units == "C":
return TEMP_CELSIUS
if units == "LENGTH_MILES":
return LENGTH_MILES
if units == "LENGTH_KILOMETERS":
return LENGTH_KILOMETERS
return units | [
"def",
"unit_of_measurement",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"units",
"=",
"self",
".",
"tesla_device",
".",
"measurement",
"if",
"units",
"==",
"\"F\"",
":",
"return",
"TEMP_FAHRENHEIT",
"if",
"units",
"==",
"\"C\"",
":",
"return",
"TEMP_CELSIUS",
"if",
"units",
"==",
"\"LENGTH_MILES\"",
":",
"return",
"LENGTH_MILES",
"if",
"units",
"==",
"\"LENGTH_KILOMETERS\"",
":",
"return",
"LENGTH_KILOMETERS",
"return",
"units"
] | [
60,
4
] | [
71,
20
] | python | en | ['en', 'en', 'en'] | True |
TeslaSensor.device_class | (self) | Return the device_class of the device. | Return the device_class of the device. | def device_class(self) -> Optional[str]:
"""Return the device_class of the device."""
return (
self.tesla_device.device_class
if self.tesla_device.device_class in DEVICE_CLASSES
else None
) | [
"def",
"device_class",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"(",
"self",
".",
"tesla_device",
".",
"device_class",
"if",
"self",
".",
"tesla_device",
".",
"device_class",
"in",
"DEVICE_CLASSES",
"else",
"None",
")"
] | [
74,
4
] | [
80,
9
] | python | en | ['en', 'en', 'en'] | True |
TeslaSensor.device_state_attributes | (self) | Return the state attributes of the device. | Return the state attributes of the device. | def device_state_attributes(self):
"""Return the state attributes of the device."""
attr = self._attributes.copy()
if self.tesla_device.type == "charging rate sensor":
attr.update(
{
"time_left": self.tesla_device.time_left,
"added_range": self.tesla_device.added_range,
"charge_energy_added": self.tesla_device.charge_energy_added,
"charge_current_request": self.tesla_device.charge_current_request,
"charger_actual_current": self.tesla_device.charger_actual_current,
"charger_voltage": self.tesla_device.charger_voltage,
}
)
return attr | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attr",
"=",
"self",
".",
"_attributes",
".",
"copy",
"(",
")",
"if",
"self",
".",
"tesla_device",
".",
"type",
"==",
"\"charging rate sensor\"",
":",
"attr",
".",
"update",
"(",
"{",
"\"time_left\"",
":",
"self",
".",
"tesla_device",
".",
"time_left",
",",
"\"added_range\"",
":",
"self",
".",
"tesla_device",
".",
"added_range",
",",
"\"charge_energy_added\"",
":",
"self",
".",
"tesla_device",
".",
"charge_energy_added",
",",
"\"charge_current_request\"",
":",
"self",
".",
"tesla_device",
".",
"charge_current_request",
",",
"\"charger_actual_current\"",
":",
"self",
".",
"tesla_device",
".",
"charger_actual_current",
",",
"\"charger_voltage\"",
":",
"self",
".",
"tesla_device",
".",
"charger_voltage",
",",
"}",
")",
"return",
"attr"
] | [
83,
4
] | [
97,
19
] | python | en | ['en', 'en', 'en'] | True |
OneWireHub.__init__ | (self, hass: HomeAssistantType) | Initialize. | Initialize. | def __init__(self, hass: HomeAssistantType):
"""Initialize."""
self.hass = hass
self.type: str = None
self.pi1proxy: Pi1Wire = None
self.owproxy: protocol._Proxy = None
self.devices = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistantType",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"type",
":",
"str",
"=",
"None",
"self",
".",
"pi1proxy",
":",
"Pi1Wire",
"=",
"None",
"self",
".",
"owproxy",
":",
"protocol",
".",
"_Proxy",
"=",
"None",
"self",
".",
"devices",
"=",
"None"
] | [
17,
4
] | [
23,
27
] | python | en | ['en', 'en', 'it'] | False |
OneWireHub.connect | (self, host: str, port: int) | Connect to the owserver host. | Connect to the owserver host. | async def connect(self, host: str, port: int) -> None:
"""Connect to the owserver host."""
try:
self.owproxy = await self.hass.async_add_executor_job(
protocol.proxy, host, port
)
except protocol.ConnError as exc:
raise CannotConnect from exc | [
"async",
"def",
"connect",
"(",
"self",
",",
"host",
":",
"str",
",",
"port",
":",
"int",
")",
"->",
"None",
":",
"try",
":",
"self",
".",
"owproxy",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"protocol",
".",
"proxy",
",",
"host",
",",
"port",
")",
"except",
"protocol",
".",
"ConnError",
"as",
"exc",
":",
"raise",
"CannotConnect",
"from",
"exc"
] | [
25,
4
] | [
32,
40
] | python | en | ['en', 'en', 'en'] | True |
OneWireHub.check_mount_dir | (self, mount_dir: str) | Test that the mount_dir is a valid path. | Test that the mount_dir is a valid path. | async def check_mount_dir(self, mount_dir: str) -> None:
"""Test that the mount_dir is a valid path."""
if not await self.hass.async_add_executor_job(os.path.isdir, mount_dir):
raise InvalidPath
self.pi1proxy = Pi1Wire(mount_dir) | [
"async",
"def",
"check_mount_dir",
"(",
"self",
",",
"mount_dir",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"os",
".",
"path",
".",
"isdir",
",",
"mount_dir",
")",
":",
"raise",
"InvalidPath",
"self",
".",
"pi1proxy",
"=",
"Pi1Wire",
"(",
"mount_dir",
")"
] | [
34,
4
] | [
38,
42
] | python | en | ['en', 'en', 'en'] | True |
OneWireHub.initialize | (self, config_entry: ConfigEntry) | Initialize a config entry. | Initialize a config entry. | async def initialize(self, config_entry: ConfigEntry) -> None:
"""Initialize a config entry."""
self.type = config_entry.data[CONF_TYPE]
if self.type == CONF_TYPE_SYSBUS:
await self.check_mount_dir(config_entry.data[CONF_MOUNT_DIR])
elif self.type == CONF_TYPE_OWSERVER:
host = config_entry.data[CONF_HOST]
port = config_entry.data[CONF_PORT]
await self.connect(host, port)
await self.discover_devices() | [
"async",
"def",
"initialize",
"(",
"self",
",",
"config_entry",
":",
"ConfigEntry",
")",
"->",
"None",
":",
"self",
".",
"type",
"=",
"config_entry",
".",
"data",
"[",
"CONF_TYPE",
"]",
"if",
"self",
".",
"type",
"==",
"CONF_TYPE_SYSBUS",
":",
"await",
"self",
".",
"check_mount_dir",
"(",
"config_entry",
".",
"data",
"[",
"CONF_MOUNT_DIR",
"]",
")",
"elif",
"self",
".",
"type",
"==",
"CONF_TYPE_OWSERVER",
":",
"host",
"=",
"config_entry",
".",
"data",
"[",
"CONF_HOST",
"]",
"port",
"=",
"config_entry",
".",
"data",
"[",
"CONF_PORT",
"]",
"await",
"self",
".",
"connect",
"(",
"host",
",",
"port",
")",
"await",
"self",
".",
"discover_devices",
"(",
")"
] | [
40,
4
] | [
49,
37
] | python | en | ['en', 'en', 'en'] | True |
OneWireHub.discover_devices | (self) | Discover all devices. | Discover all devices. | async def discover_devices(self):
"""Discover all devices."""
if self.devices is None:
if self.type == CONF_TYPE_SYSBUS:
self.devices = await self.hass.async_add_executor_job(
self.pi1proxy.find_all_sensors
)
if self.type == CONF_TYPE_OWSERVER:
self.devices = await self.hass.async_add_executor_job(
self._discover_devices_owserver
)
return self.devices | [
"async",
"def",
"discover_devices",
"(",
"self",
")",
":",
"if",
"self",
".",
"devices",
"is",
"None",
":",
"if",
"self",
".",
"type",
"==",
"CONF_TYPE_SYSBUS",
":",
"self",
".",
"devices",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"pi1proxy",
".",
"find_all_sensors",
")",
"if",
"self",
".",
"type",
"==",
"CONF_TYPE_OWSERVER",
":",
"self",
".",
"devices",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_discover_devices_owserver",
")",
"return",
"self",
".",
"devices"
] | [
51,
4
] | [
62,
27
] | python | en | ['sv', 'en', 'en'] | True |
OneWireHub._discover_devices_owserver | (self) | Discover all owserver devices. | Discover all owserver devices. | def _discover_devices_owserver(self):
"""Discover all owserver devices."""
devices = []
for device_path in self.owproxy.dir():
devices.append(
{
"path": device_path,
"family": self.owproxy.read(f"{device_path}family").decode(),
"type": self.owproxy.read(f"{device_path}type").decode(),
}
)
return devices | [
"def",
"_discover_devices_owserver",
"(",
"self",
")",
":",
"devices",
"=",
"[",
"]",
"for",
"device_path",
"in",
"self",
".",
"owproxy",
".",
"dir",
"(",
")",
":",
"devices",
".",
"append",
"(",
"{",
"\"path\"",
":",
"device_path",
",",
"\"family\"",
":",
"self",
".",
"owproxy",
".",
"read",
"(",
"f\"{device_path}family\"",
")",
".",
"decode",
"(",
")",
",",
"\"type\"",
":",
"self",
".",
"owproxy",
".",
"read",
"(",
"f\"{device_path}type\"",
")",
".",
"decode",
"(",
")",
",",
"}",
")",
"return",
"devices"
] | [
64,
4
] | [
75,
22
] | python | en | ['sv', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Homematic thermostat platform. | Set up the Homematic thermostat platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Homematic thermostat platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
new_device = HMThermostat(conf)
devices.append(new_device)
add_entities(devices, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"devices",
"=",
"[",
"]",
"for",
"conf",
"in",
"discovery_info",
"[",
"ATTR_DISCOVER_DEVICES",
"]",
":",
"new_device",
"=",
"HMThermostat",
"(",
"conf",
")",
"devices",
".",
"append",
"(",
"new_device",
")",
"add_entities",
"(",
"devices",
",",
"True",
")"
] | [
33,
0
] | [
43,
31
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat.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 SUPPORT_FLAGS | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_FLAGS"
] | [
50,
4
] | [
52,
28
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat.temperature_unit | (self) | Return the unit of measurement that is used. | Return the unit of measurement that is used. | def temperature_unit(self):
"""Return the unit of measurement that is used."""
return TEMP_CELSIUS | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_CELSIUS"
] | [
55,
4
] | [
57,
27
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat.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_*.
"""
if self.target_temperature <= self._hmdevice.OFF_VALUE + 0.5:
return HVAC_MODE_OFF
if "MANU_MODE" in self._hmdevice.ACTIONNODE:
if self._hm_control_mode == self._hmdevice.MANU_MODE:
return HVAC_MODE_HEAT
return HVAC_MODE_AUTO
# Simple devices
if self._data.get("BOOST_MODE"):
return HVAC_MODE_AUTO
return HVAC_MODE_HEAT | [
"def",
"hvac_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"target_temperature",
"<=",
"self",
".",
"_hmdevice",
".",
"OFF_VALUE",
"+",
"0.5",
":",
"return",
"HVAC_MODE_OFF",
"if",
"\"MANU_MODE\"",
"in",
"self",
".",
"_hmdevice",
".",
"ACTIONNODE",
":",
"if",
"self",
".",
"_hm_control_mode",
"==",
"self",
".",
"_hmdevice",
".",
"MANU_MODE",
":",
"return",
"HVAC_MODE_HEAT",
"return",
"HVAC_MODE_AUTO",
"# Simple devices",
"if",
"self",
".",
"_data",
".",
"get",
"(",
"\"BOOST_MODE\"",
")",
":",
"return",
"HVAC_MODE_AUTO",
"return",
"HVAC_MODE_HEAT"
] | [
60,
4
] | [
75,
29
] | python | bg | ['en', 'bg', 'bg'] | True |
HMThermostat.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.
"""
if "AUTO_MODE" in self._hmdevice.ACTIONNODE:
return [HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF]
return [HVAC_MODE_HEAT, HVAC_MODE_OFF] | [
"def",
"hvac_modes",
"(",
"self",
")",
":",
"if",
"\"AUTO_MODE\"",
"in",
"self",
".",
"_hmdevice",
".",
"ACTIONNODE",
":",
"return",
"[",
"HVAC_MODE_AUTO",
",",
"HVAC_MODE_HEAT",
",",
"HVAC_MODE_OFF",
"]",
"return",
"[",
"HVAC_MODE_HEAT",
",",
"HVAC_MODE_OFF",
"]"
] | [
78,
4
] | [
85,
46
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat.preset_mode | (self) | Return the current preset mode, e.g., home, away, temp. | Return the current preset mode, e.g., home, away, temp. | def preset_mode(self):
"""Return the current preset mode, e.g., home, away, temp."""
if self._data.get("BOOST_MODE", False):
return "boost"
if not self._hm_control_mode:
return None
mode = HM_ATTRIBUTE_SUPPORT[HM_CONTROL_MODE][1][self._hm_control_mode]
mode = mode.lower()
# Filter HVAC states
if mode not in (HVAC_MODE_AUTO, HVAC_MODE_HEAT):
return None
return mode | [
"def",
"preset_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data",
".",
"get",
"(",
"\"BOOST_MODE\"",
",",
"False",
")",
":",
"return",
"\"boost\"",
"if",
"not",
"self",
".",
"_hm_control_mode",
":",
"return",
"None",
"mode",
"=",
"HM_ATTRIBUTE_SUPPORT",
"[",
"HM_CONTROL_MODE",
"]",
"[",
"1",
"]",
"[",
"self",
".",
"_hm_control_mode",
"]",
"mode",
"=",
"mode",
".",
"lower",
"(",
")",
"# Filter HVAC states",
"if",
"mode",
"not",
"in",
"(",
"HVAC_MODE_AUTO",
",",
"HVAC_MODE_HEAT",
")",
":",
"return",
"None",
"return",
"mode"
] | [
88,
4
] | [
102,
19
] | python | en | ['en', 'pt', 'en'] | True |
HMThermostat.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."""
preset_modes = []
for mode in self._hmdevice.ACTIONNODE:
if mode in HM_PRESET_MAP:
preset_modes.append(HM_PRESET_MAP[mode])
return preset_modes | [
"def",
"preset_modes",
"(",
"self",
")",
":",
"preset_modes",
"=",
"[",
"]",
"for",
"mode",
"in",
"self",
".",
"_hmdevice",
".",
"ACTIONNODE",
":",
"if",
"mode",
"in",
"HM_PRESET_MAP",
":",
"preset_modes",
".",
"append",
"(",
"HM_PRESET_MAP",
"[",
"mode",
"]",
")",
"return",
"preset_modes"
] | [
105,
4
] | [
111,
27
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat.current_humidity | (self) | Return the current humidity. | Return the current humidity. | def current_humidity(self):
"""Return the current humidity."""
for node in HM_HUMI_MAP:
if node in self._data:
return self._data[node] | [
"def",
"current_humidity",
"(",
"self",
")",
":",
"for",
"node",
"in",
"HM_HUMI_MAP",
":",
"if",
"node",
"in",
"self",
".",
"_data",
":",
"return",
"self",
".",
"_data",
"[",
"node",
"]"
] | [
114,
4
] | [
118,
39
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat.current_temperature | (self) | Return the current temperature. | Return the current temperature. | def current_temperature(self):
"""Return the current temperature."""
for node in HM_TEMP_MAP:
if node in self._data:
return self._data[node] | [
"def",
"current_temperature",
"(",
"self",
")",
":",
"for",
"node",
"in",
"HM_TEMP_MAP",
":",
"if",
"node",
"in",
"self",
".",
"_data",
":",
"return",
"self",
".",
"_data",
"[",
"node",
"]"
] | [
121,
4
] | [
125,
39
] | python | en | ['en', 'la', 'en'] | True |
HMThermostat.target_temperature | (self) | Return the target temperature. | Return the target temperature. | def target_temperature(self):
"""Return the target temperature."""
return self._data.get(self._state) | [
"def",
"target_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_data",
".",
"get",
"(",
"self",
".",
"_state",
")"
] | [
128,
4
] | [
130,
42
] | python | en | ['en', 'la', 'en'] | True |
HMThermostat.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 None
self._hmdevice.writeNodeData(self._state, float(temperature)) | [
"def",
"set_temperature",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"temperature",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"if",
"temperature",
"is",
"None",
":",
"return",
"None",
"self",
".",
"_hmdevice",
".",
"writeNodeData",
"(",
"self",
".",
"_state",
",",
"float",
"(",
"temperature",
")",
")"
] | [
132,
4
] | [
138,
69
] | python | en | ['en', 'ca', 'en'] | True |
HMThermostat.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."""
if hvac_mode == HVAC_MODE_AUTO:
self._hmdevice.MODE = self._hmdevice.AUTO_MODE
elif hvac_mode == HVAC_MODE_HEAT:
self._hmdevice.MODE = self._hmdevice.MANU_MODE
elif hvac_mode == HVAC_MODE_OFF:
self._hmdevice.turnoff() | [
"def",
"set_hvac_mode",
"(",
"self",
",",
"hvac_mode",
")",
":",
"if",
"hvac_mode",
"==",
"HVAC_MODE_AUTO",
":",
"self",
".",
"_hmdevice",
".",
"MODE",
"=",
"self",
".",
"_hmdevice",
".",
"AUTO_MODE",
"elif",
"hvac_mode",
"==",
"HVAC_MODE_HEAT",
":",
"self",
".",
"_hmdevice",
".",
"MODE",
"=",
"self",
".",
"_hmdevice",
".",
"MANU_MODE",
"elif",
"hvac_mode",
"==",
"HVAC_MODE_OFF",
":",
"self",
".",
"_hmdevice",
".",
"turnoff",
"(",
")"
] | [
140,
4
] | [
147,
36
] | python | da | ['da', 'su', 'en'] | False |
HMThermostat.set_preset_mode | (self, preset_mode: str) | Set new preset mode. | Set new preset mode. | def set_preset_mode(self, preset_mode: str) -> None:
"""Set new preset mode."""
if preset_mode == PRESET_BOOST:
self._hmdevice.MODE = self._hmdevice.BOOST_MODE
elif preset_mode == PRESET_COMFORT:
self._hmdevice.MODE = self._hmdevice.COMFORT_MODE
elif preset_mode == PRESET_ECO:
self._hmdevice.MODE = self._hmdevice.LOWERING_MODE | [
"def",
"set_preset_mode",
"(",
"self",
",",
"preset_mode",
":",
"str",
")",
"->",
"None",
":",
"if",
"preset_mode",
"==",
"PRESET_BOOST",
":",
"self",
".",
"_hmdevice",
".",
"MODE",
"=",
"self",
".",
"_hmdevice",
".",
"BOOST_MODE",
"elif",
"preset_mode",
"==",
"PRESET_COMFORT",
":",
"self",
".",
"_hmdevice",
".",
"MODE",
"=",
"self",
".",
"_hmdevice",
".",
"COMFORT_MODE",
"elif",
"preset_mode",
"==",
"PRESET_ECO",
":",
"self",
".",
"_hmdevice",
".",
"MODE",
"=",
"self",
".",
"_hmdevice",
".",
"LOWERING_MODE"
] | [
149,
4
] | [
156,
62
] | python | en | ['en', 'sr', 'en'] | True |
HMThermostat.min_temp | (self) | Return the minimum temperature. | Return the minimum temperature. | def min_temp(self):
"""Return the minimum temperature."""
return 4.5 | [
"def",
"min_temp",
"(",
"self",
")",
":",
"return",
"4.5"
] | [
159,
4
] | [
161,
18
] | python | en | ['en', 'la', 'en'] | True |
HMThermostat.max_temp | (self) | Return the maximum temperature. | Return the maximum temperature. | def max_temp(self):
"""Return the maximum temperature."""
return 30.5 | [
"def",
"max_temp",
"(",
"self",
")",
":",
"return",
"30.5"
] | [
164,
4
] | [
166,
19
] | python | en | ['en', 'la', 'en'] | True |
HMThermostat.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."""
return 0.5 | [
"def",
"target_temperature_step",
"(",
"self",
")",
":",
"return",
"0.5"
] | [
169,
4
] | [
171,
18
] | python | en | ['en', 'en', 'en'] | True |
HMThermostat._hm_control_mode | (self) | Return Control mode. | Return Control mode. | def _hm_control_mode(self):
"""Return Control mode."""
if HMIP_CONTROL_MODE in self._data:
return self._data[HMIP_CONTROL_MODE]
# Homematic
return self._data.get("CONTROL_MODE") | [
"def",
"_hm_control_mode",
"(",
"self",
")",
":",
"if",
"HMIP_CONTROL_MODE",
"in",
"self",
".",
"_data",
":",
"return",
"self",
".",
"_data",
"[",
"HMIP_CONTROL_MODE",
"]",
"# Homematic",
"return",
"self",
".",
"_data",
".",
"get",
"(",
"\"CONTROL_MODE\"",
")"
] | [
174,
4
] | [
180,
45
] | python | en | ['en', 'co', 'en'] | True |
HMThermostat._init_data_struct | (self) | Generate a data dict (self._data) from the Homematic metadata. | Generate a data dict (self._data) from the Homematic metadata. | def _init_data_struct(self):
"""Generate a data dict (self._data) from the Homematic metadata."""
self._state = next(iter(self._hmdevice.WRITENODE.keys()))
self._data[self._state] = None
if (
HM_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE
or HMIP_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE
):
self._data[HM_CONTROL_MODE] = None
for node in self._hmdevice.SENSORNODE.keys():
self._data[node] = None | [
"def",
"_init_data_struct",
"(",
"self",
")",
":",
"self",
".",
"_state",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"_hmdevice",
".",
"WRITENODE",
".",
"keys",
"(",
")",
")",
")",
"self",
".",
"_data",
"[",
"self",
".",
"_state",
"]",
"=",
"None",
"if",
"(",
"HM_CONTROL_MODE",
"in",
"self",
".",
"_hmdevice",
".",
"ATTRIBUTENODE",
"or",
"HMIP_CONTROL_MODE",
"in",
"self",
".",
"_hmdevice",
".",
"ATTRIBUTENODE",
")",
":",
"self",
".",
"_data",
"[",
"HM_CONTROL_MODE",
"]",
"=",
"None",
"for",
"node",
"in",
"self",
".",
"_hmdevice",
".",
"SENSORNODE",
".",
"keys",
"(",
")",
":",
"self",
".",
"_data",
"[",
"node",
"]",
"=",
"None"
] | [
182,
4
] | [
194,
35
] | python | en | ['en', 'en', 'en'] | True |
mock_setup | () | Mock entry setup. | Mock entry setup. | def mock_setup():
"""Mock entry setup."""
with patch(
"homeassistant.components.islamic_prayer_times.async_setup_entry",
return_value=True,
):
yield | [
"def",
"mock_setup",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.islamic_prayer_times.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
":",
"yield"
] | [
12,
0
] | [
18,
13
] | python | en | ['en', 'da', 'en'] | True |
test_flow_works | (hass) | Test user config. | Test user config. | async def test_flow_works(hass):
"""Test user config."""
result = await hass.config_entries.flow.async_init(
islamic_prayer_times.DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "Islamic Prayer Times" | [
"async",
"def",
"test_flow_works",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"islamic_prayer_times",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"Islamic Prayer Times\""
] | [
21,
0
] | [
33,
52
] | python | en | ['en', 'da', 'en'] | True |
test_options | (hass) | Test updating options. | Test updating options. | async def test_options(hass):
"""Test updating options."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Islamic Prayer Times",
data={},
options={CONF_CALC_METHOD: "isna"},
)
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input={CONF_CALC_METHOD: "makkah"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_CALC_METHOD] == "makkah" | [
"async",
"def",
"test_options",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"title",
"=",
"\"Islamic Prayer Times\"",
",",
"data",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"CONF_CALC_METHOD",
":",
"\"isna\"",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"options",
".",
"async_init",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"init\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"options",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_CALC_METHOD",
":",
"\"makkah\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_CALC_METHOD",
"]",
"==",
"\"makkah\""
] | [
36,
0
] | [
56,
55
] | python | en | ['en', 'en', 'en'] | True |
test_import | (hass) | Test import step. | Test import step. | async def test_import(hass):
"""Test import step."""
result = await hass.config_entries.flow.async_init(
islamic_prayer_times.DOMAIN,
context={"source": "import"},
data={CONF_CALC_METHOD: "makkah"},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "Islamic Prayer Times"
assert result["data"][CONF_CALC_METHOD] == "makkah" | [
"async",
"def",
"test_import",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"islamic_prayer_times",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"import\"",
"}",
",",
"data",
"=",
"{",
"CONF_CALC_METHOD",
":",
"\"makkah\"",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"Islamic Prayer Times\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_CALC_METHOD",
"]",
"==",
"\"makkah\""
] | [
59,
0
] | [
69,
55
] | python | de | ['de', 'sd', 'en'] | False |
test_integration_already_configured | (hass) | Test integration is already configured. | Test integration is already configured. | async def test_integration_already_configured(hass):
"""Test integration is already configured."""
entry = MockConfigEntry(
domain=DOMAIN,
data={},
options={},
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
islamic_prayer_times.DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "single_instance_allowed" | [
"async",
"def",
"test_integration_already_configured",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"islamic_prayer_times",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"single_instance_allowed\""
] | [
72,
0
] | [
85,
56
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the Amcrest IP Camera component. | Set up the Amcrest IP Camera component. | def setup(hass, config):
"""Set up the Amcrest IP Camera component."""
hass.data.setdefault(DATA_AMCREST, {DEVICES: {}, CAMERAS: []})
for device in config[DOMAIN]:
name = device[CONF_NAME]
username = device[CONF_USERNAME]
password = device[CONF_PASSWORD]
api = AmcrestChecker(
hass, name, device[CONF_HOST], device[CONF_PORT], username, password
)
ffmpeg_arguments = device[CONF_FFMPEG_ARGUMENTS]
resolution = RESOLUTION_LIST[device[CONF_RESOLUTION]]
binary_sensors = device.get(CONF_BINARY_SENSORS)
sensors = device.get(CONF_SENSORS)
stream_source = device[CONF_STREAM_SOURCE]
control_light = device.get(CONF_CONTROL_LIGHT)
# currently aiohttp only works with basic authentication
# only valid for mjpeg streaming
if device[CONF_AUTHENTICATION] == HTTP_BASIC_AUTHENTICATION:
authentication = aiohttp.BasicAuth(username, password)
else:
authentication = None
hass.data[DATA_AMCREST][DEVICES][name] = AmcrestDevice(
api,
authentication,
ffmpeg_arguments,
stream_source,
resolution,
control_light,
)
discovery.load_platform(hass, CAMERA, DOMAIN, {CONF_NAME: name}, config)
if binary_sensors:
discovery.load_platform(
hass,
BINARY_SENSOR,
DOMAIN,
{CONF_NAME: name, CONF_BINARY_SENSORS: binary_sensors},
config,
)
event_codes = [
BINARY_SENSORS[sensor_type][SENSOR_EVENT_CODE]
for sensor_type in binary_sensors
if sensor_type not in BINARY_POLLED_SENSORS
]
if event_codes:
_start_event_monitor(hass, name, api, event_codes)
if sensors:
discovery.load_platform(
hass, SENSOR, DOMAIN, {CONF_NAME: name, CONF_SENSORS: sensors}, config
)
if not hass.data[DATA_AMCREST][DEVICES]:
return False
def have_permission(user, entity_id):
return not user or user.permissions.check_entity(entity_id, POLICY_CONTROL)
async def async_extract_from_service(call):
if call.context.user_id:
user = await hass.auth.async_get_user(call.context.user_id)
if user is None:
raise UnknownUser(context=call.context)
else:
user = None
if call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_ALL:
# Return all entity_ids user has permission to control.
return [
entity_id
for entity_id in hass.data[DATA_AMCREST][CAMERAS]
if have_permission(user, entity_id)
]
if call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_NONE:
return []
call_ids = await async_extract_entity_ids(hass, call)
entity_ids = []
for entity_id in hass.data[DATA_AMCREST][CAMERAS]:
if entity_id not in call_ids:
continue
if not have_permission(user, entity_id):
raise Unauthorized(
context=call.context, entity_id=entity_id, permission=POLICY_CONTROL
)
entity_ids.append(entity_id)
return entity_ids
async def async_service_handler(call):
args = []
for arg in CAMERA_SERVICES[call.service][2]:
args.append(call.data[arg])
for entity_id in await async_extract_from_service(call):
async_dispatcher_send(hass, service_signal(call.service, entity_id), *args)
for service, params in CAMERA_SERVICES.items():
hass.services.register(DOMAIN, service, async_service_handler, params[0])
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DATA_AMCREST",
",",
"{",
"DEVICES",
":",
"{",
"}",
",",
"CAMERAS",
":",
"[",
"]",
"}",
")",
"for",
"device",
"in",
"config",
"[",
"DOMAIN",
"]",
":",
"name",
"=",
"device",
"[",
"CONF_NAME",
"]",
"username",
"=",
"device",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"device",
"[",
"CONF_PASSWORD",
"]",
"api",
"=",
"AmcrestChecker",
"(",
"hass",
",",
"name",
",",
"device",
"[",
"CONF_HOST",
"]",
",",
"device",
"[",
"CONF_PORT",
"]",
",",
"username",
",",
"password",
")",
"ffmpeg_arguments",
"=",
"device",
"[",
"CONF_FFMPEG_ARGUMENTS",
"]",
"resolution",
"=",
"RESOLUTION_LIST",
"[",
"device",
"[",
"CONF_RESOLUTION",
"]",
"]",
"binary_sensors",
"=",
"device",
".",
"get",
"(",
"CONF_BINARY_SENSORS",
")",
"sensors",
"=",
"device",
".",
"get",
"(",
"CONF_SENSORS",
")",
"stream_source",
"=",
"device",
"[",
"CONF_STREAM_SOURCE",
"]",
"control_light",
"=",
"device",
".",
"get",
"(",
"CONF_CONTROL_LIGHT",
")",
"# currently aiohttp only works with basic authentication",
"# only valid for mjpeg streaming",
"if",
"device",
"[",
"CONF_AUTHENTICATION",
"]",
"==",
"HTTP_BASIC_AUTHENTICATION",
":",
"authentication",
"=",
"aiohttp",
".",
"BasicAuth",
"(",
"username",
",",
"password",
")",
"else",
":",
"authentication",
"=",
"None",
"hass",
".",
"data",
"[",
"DATA_AMCREST",
"]",
"[",
"DEVICES",
"]",
"[",
"name",
"]",
"=",
"AmcrestDevice",
"(",
"api",
",",
"authentication",
",",
"ffmpeg_arguments",
",",
"stream_source",
",",
"resolution",
",",
"control_light",
",",
")",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"CAMERA",
",",
"DOMAIN",
",",
"{",
"CONF_NAME",
":",
"name",
"}",
",",
"config",
")",
"if",
"binary_sensors",
":",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"BINARY_SENSOR",
",",
"DOMAIN",
",",
"{",
"CONF_NAME",
":",
"name",
",",
"CONF_BINARY_SENSORS",
":",
"binary_sensors",
"}",
",",
"config",
",",
")",
"event_codes",
"=",
"[",
"BINARY_SENSORS",
"[",
"sensor_type",
"]",
"[",
"SENSOR_EVENT_CODE",
"]",
"for",
"sensor_type",
"in",
"binary_sensors",
"if",
"sensor_type",
"not",
"in",
"BINARY_POLLED_SENSORS",
"]",
"if",
"event_codes",
":",
"_start_event_monitor",
"(",
"hass",
",",
"name",
",",
"api",
",",
"event_codes",
")",
"if",
"sensors",
":",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"SENSOR",
",",
"DOMAIN",
",",
"{",
"CONF_NAME",
":",
"name",
",",
"CONF_SENSORS",
":",
"sensors",
"}",
",",
"config",
")",
"if",
"not",
"hass",
".",
"data",
"[",
"DATA_AMCREST",
"]",
"[",
"DEVICES",
"]",
":",
"return",
"False",
"def",
"have_permission",
"(",
"user",
",",
"entity_id",
")",
":",
"return",
"not",
"user",
"or",
"user",
".",
"permissions",
".",
"check_entity",
"(",
"entity_id",
",",
"POLICY_CONTROL",
")",
"async",
"def",
"async_extract_from_service",
"(",
"call",
")",
":",
"if",
"call",
".",
"context",
".",
"user_id",
":",
"user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_get_user",
"(",
"call",
".",
"context",
".",
"user_id",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"UnknownUser",
"(",
"context",
"=",
"call",
".",
"context",
")",
"else",
":",
"user",
"=",
"None",
"if",
"call",
".",
"data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
"==",
"ENTITY_MATCH_ALL",
":",
"# Return all entity_ids user has permission to control.",
"return",
"[",
"entity_id",
"for",
"entity_id",
"in",
"hass",
".",
"data",
"[",
"DATA_AMCREST",
"]",
"[",
"CAMERAS",
"]",
"if",
"have_permission",
"(",
"user",
",",
"entity_id",
")",
"]",
"if",
"call",
".",
"data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
"==",
"ENTITY_MATCH_NONE",
":",
"return",
"[",
"]",
"call_ids",
"=",
"await",
"async_extract_entity_ids",
"(",
"hass",
",",
"call",
")",
"entity_ids",
"=",
"[",
"]",
"for",
"entity_id",
"in",
"hass",
".",
"data",
"[",
"DATA_AMCREST",
"]",
"[",
"CAMERAS",
"]",
":",
"if",
"entity_id",
"not",
"in",
"call_ids",
":",
"continue",
"if",
"not",
"have_permission",
"(",
"user",
",",
"entity_id",
")",
":",
"raise",
"Unauthorized",
"(",
"context",
"=",
"call",
".",
"context",
",",
"entity_id",
"=",
"entity_id",
",",
"permission",
"=",
"POLICY_CONTROL",
")",
"entity_ids",
".",
"append",
"(",
"entity_id",
")",
"return",
"entity_ids",
"async",
"def",
"async_service_handler",
"(",
"call",
")",
":",
"args",
"=",
"[",
"]",
"for",
"arg",
"in",
"CAMERA_SERVICES",
"[",
"call",
".",
"service",
"]",
"[",
"2",
"]",
":",
"args",
".",
"append",
"(",
"call",
".",
"data",
"[",
"arg",
"]",
")",
"for",
"entity_id",
"in",
"await",
"async_extract_from_service",
"(",
"call",
")",
":",
"async_dispatcher_send",
"(",
"hass",
",",
"service_signal",
"(",
"call",
".",
"service",
",",
"entity_id",
")",
",",
"*",
"args",
")",
"for",
"service",
",",
"params",
"in",
"CAMERA_SERVICES",
".",
"items",
"(",
")",
":",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"service",
",",
"async_service_handler",
",",
"params",
"[",
"0",
"]",
")",
"return",
"True"
] | [
224,
0
] | [
330,
15
] | python | en | ['en', 'da', 'en'] | True |
AmcrestChecker.__init__ | (self, hass, name, host, port, user, password) | Initialize. | Initialize. | def __init__(self, hass, name, host, port, user, password):
"""Initialize."""
self._hass = hass
self._wrap_name = name
self._wrap_errors = 0
self._wrap_lock = threading.Lock()
self._wrap_login_err = False
self._wrap_event_flag = threading.Event()
self._wrap_event_flag.set()
self._unsub_recheck = None
super().__init__(
host,
port,
user,
password,
retries_connection=COMM_RETRIES,
timeout_protocol=COMM_TIMEOUT,
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
",",
"host",
",",
"port",
",",
"user",
",",
"password",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_wrap_name",
"=",
"name",
"self",
".",
"_wrap_errors",
"=",
"0",
"self",
".",
"_wrap_lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"self",
".",
"_wrap_login_err",
"=",
"False",
"self",
".",
"_wrap_event_flag",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"_wrap_event_flag",
".",
"set",
"(",
")",
"self",
".",
"_unsub_recheck",
"=",
"None",
"super",
"(",
")",
".",
"__init__",
"(",
"host",
",",
"port",
",",
"user",
",",
"password",
",",
"retries_connection",
"=",
"COMM_RETRIES",
",",
"timeout_protocol",
"=",
"COMM_TIMEOUT",
",",
")"
] | [
118,
4
] | [
135,
9
] | python | en | ['en', 'en', 'it'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.