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_all_devices_unavailable_when_hap_not_connected | (
hass, default_mock_hap_factory
) | Test make all devices unavaulable when hap is not connected. | Test make all devices unavaulable when hap is not connected. | async def test_all_devices_unavailable_when_hap_not_connected(
hass, default_mock_hap_factory
):
"""Test make all devices unavaulable when hap is not connected."""
entity_id = "light.treppe_ch"
entity_name = "Treppe CH"
device_model = "HmIP-BSL"
mock_hap = await default_mock_hap_factory.async_get_mock_hap(
test_devices=["Treppe"]
)
ha_state, hmip_device = get_and_check_entity_basics(
hass, mock_hap, entity_id, entity_name, device_model
)
assert ha_state.state == STATE_ON
assert hmip_device
assert mock_hap.home.connected
await async_manipulate_test_data(hass, mock_hap.home, "connected", False)
ha_state = hass.states.get(entity_id)
assert ha_state.state == STATE_UNAVAILABLE | [
"async",
"def",
"test_all_devices_unavailable_when_hap_not_connected",
"(",
"hass",
",",
"default_mock_hap_factory",
")",
":",
"entity_id",
"=",
"\"light.treppe_ch\"",
"entity_name",
"=",
"\"Treppe CH\"",
"device_model",
"=",
"\"HmIP-BSL\"",
"mock_hap",
"=",
"await",
"default_mock_hap_factory",
".",
"async_get_mock_hap",
"(",
"test_devices",
"=",
"[",
"\"Treppe\"",
"]",
")",
"ha_state",
",",
"hmip_device",
"=",
"get_and_check_entity_basics",
"(",
"hass",
",",
"mock_hap",
",",
"entity_id",
",",
"entity_name",
",",
"device_model",
")",
"assert",
"ha_state",
".",
"state",
"==",
"STATE_ON",
"assert",
"hmip_device",
"assert",
"mock_hap",
".",
"home",
".",
"connected",
"await",
"async_manipulate_test_data",
"(",
"hass",
",",
"mock_hap",
".",
"home",
",",
"\"connected\"",
",",
"False",
")",
"ha_state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"ha_state",
".",
"state",
"==",
"STATE_UNAVAILABLE"
] | [
136,
0
] | [
159,
46
] | python | en | ['en', 'en', 'en'] | True |
test_hap_reconnected | (hass, default_mock_hap_factory) | Test reconnect hap. | Test reconnect hap. | async def test_hap_reconnected(hass, default_mock_hap_factory):
"""Test reconnect hap."""
entity_id = "light.treppe_ch"
entity_name = "Treppe CH"
device_model = "HmIP-BSL"
mock_hap = await default_mock_hap_factory.async_get_mock_hap(
test_devices=["Treppe"]
)
ha_state, hmip_device = get_and_check_entity_basics(
hass, mock_hap, entity_id, entity_name, device_model
)
assert ha_state.state == STATE_ON
assert hmip_device
assert mock_hap.home.connected
await async_manipulate_test_data(hass, mock_hap.home, "connected", False)
ha_state = hass.states.get(entity_id)
assert ha_state.state == STATE_UNAVAILABLE
mock_hap._accesspoint_connected = False # pylint: disable=protected-access
await async_manipulate_test_data(hass, mock_hap.home, "connected", True)
await hass.async_block_till_done()
ha_state = hass.states.get(entity_id)
assert ha_state.state == STATE_ON | [
"async",
"def",
"test_hap_reconnected",
"(",
"hass",
",",
"default_mock_hap_factory",
")",
":",
"entity_id",
"=",
"\"light.treppe_ch\"",
"entity_name",
"=",
"\"Treppe CH\"",
"device_model",
"=",
"\"HmIP-BSL\"",
"mock_hap",
"=",
"await",
"default_mock_hap_factory",
".",
"async_get_mock_hap",
"(",
"test_devices",
"=",
"[",
"\"Treppe\"",
"]",
")",
"ha_state",
",",
"hmip_device",
"=",
"get_and_check_entity_basics",
"(",
"hass",
",",
"mock_hap",
",",
"entity_id",
",",
"entity_name",
",",
"device_model",
")",
"assert",
"ha_state",
".",
"state",
"==",
"STATE_ON",
"assert",
"hmip_device",
"assert",
"mock_hap",
".",
"home",
".",
"connected",
"await",
"async_manipulate_test_data",
"(",
"hass",
",",
"mock_hap",
".",
"home",
",",
"\"connected\"",
",",
"False",
")",
"ha_state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"ha_state",
".",
"state",
"==",
"STATE_UNAVAILABLE",
"mock_hap",
".",
"_accesspoint_connected",
"=",
"False",
"# pylint: disable=protected-access",
"await",
"async_manipulate_test_data",
"(",
"hass",
",",
"mock_hap",
".",
"home",
",",
"\"connected\"",
",",
"True",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"ha_state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"ha_state",
".",
"state",
"==",
"STATE_ON"
] | [
162,
0
] | [
189,
37
] | python | en | ['en', 'fr', 'en'] | True |
test_hap_with_name | (hass, mock_connection, hmip_config_entry) | Test hap with name. | Test hap with name. | async def test_hap_with_name(hass, mock_connection, hmip_config_entry):
"""Test hap with name."""
home_name = "TestName"
entity_id = f"light.{home_name.lower()}_treppe_ch"
entity_name = f"{home_name} Treppe CH"
device_model = "HmIP-BSL"
hmip_config_entry.data = {**hmip_config_entry.data, "name": home_name}
mock_hap = await HomeFactory(
hass, mock_connection, hmip_config_entry
).async_get_mock_hap(test_devices=["Treppe"])
assert mock_hap
ha_state, hmip_device = get_and_check_entity_basics(
hass, mock_hap, entity_id, entity_name, device_model
)
assert hmip_device
assert ha_state.state == STATE_ON
assert ha_state.attributes["friendly_name"] == entity_name | [
"async",
"def",
"test_hap_with_name",
"(",
"hass",
",",
"mock_connection",
",",
"hmip_config_entry",
")",
":",
"home_name",
"=",
"\"TestName\"",
"entity_id",
"=",
"f\"light.{home_name.lower()}_treppe_ch\"",
"entity_name",
"=",
"f\"{home_name} Treppe CH\"",
"device_model",
"=",
"\"HmIP-BSL\"",
"hmip_config_entry",
".",
"data",
"=",
"{",
"*",
"*",
"hmip_config_entry",
".",
"data",
",",
"\"name\"",
":",
"home_name",
"}",
"mock_hap",
"=",
"await",
"HomeFactory",
"(",
"hass",
",",
"mock_connection",
",",
"hmip_config_entry",
")",
".",
"async_get_mock_hap",
"(",
"test_devices",
"=",
"[",
"\"Treppe\"",
"]",
")",
"assert",
"mock_hap",
"ha_state",
",",
"hmip_device",
"=",
"get_and_check_entity_basics",
"(",
"hass",
",",
"mock_hap",
",",
"entity_id",
",",
"entity_name",
",",
"device_model",
")",
"assert",
"hmip_device",
"assert",
"ha_state",
".",
"state",
"==",
"STATE_ON",
"assert",
"ha_state",
".",
"attributes",
"[",
"\"friendly_name\"",
"]",
"==",
"entity_name"
] | [
192,
0
] | [
211,
62
] | python | en | ['en', 'en', 'en'] | True |
test_hmip_reset_energy_counter_services | (hass, default_mock_hap_factory) | Test reset_energy_counter service. | Test reset_energy_counter service. | async def test_hmip_reset_energy_counter_services(hass, default_mock_hap_factory):
"""Test reset_energy_counter service."""
entity_id = "switch.pc"
entity_name = "Pc"
device_model = "HMIP-PSM"
mock_hap = await default_mock_hap_factory.async_get_mock_hap(
test_devices=[entity_name]
)
ha_state, hmip_device = get_and_check_entity_basics(
hass, mock_hap, entity_id, entity_name, device_model
)
assert ha_state
await hass.services.async_call(
"homematicip_cloud",
"reset_energy_counter",
{"entity_id": "switch.pc"},
blocking=True,
)
assert hmip_device.mock_calls[-1][0] == "reset_energy_counter"
assert len(hmip_device._connection.mock_calls) == 2 # pylint: disable=W0212
await hass.services.async_call(
"homematicip_cloud", "reset_energy_counter", {"entity_id": "all"}, blocking=True
)
assert hmip_device.mock_calls[-1][0] == "reset_energy_counter"
assert len(hmip_device._connection.mock_calls) == 4 | [
"async",
"def",
"test_hmip_reset_energy_counter_services",
"(",
"hass",
",",
"default_mock_hap_factory",
")",
":",
"entity_id",
"=",
"\"switch.pc\"",
"entity_name",
"=",
"\"Pc\"",
"device_model",
"=",
"\"HMIP-PSM\"",
"mock_hap",
"=",
"await",
"default_mock_hap_factory",
".",
"async_get_mock_hap",
"(",
"test_devices",
"=",
"[",
"entity_name",
"]",
")",
"ha_state",
",",
"hmip_device",
"=",
"get_and_check_entity_basics",
"(",
"hass",
",",
"mock_hap",
",",
"entity_id",
",",
"entity_name",
",",
"device_model",
")",
"assert",
"ha_state",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"homematicip_cloud\"",
",",
"\"reset_energy_counter\"",
",",
"{",
"\"entity_id\"",
":",
"\"switch.pc\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"hmip_device",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
"\"reset_energy_counter\"",
"assert",
"len",
"(",
"hmip_device",
".",
"_connection",
".",
"mock_calls",
")",
"==",
"2",
"# pylint: disable=W0212",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"homematicip_cloud\"",
",",
"\"reset_energy_counter\"",
",",
"{",
"\"entity_id\"",
":",
"\"all\"",
"}",
",",
"blocking",
"=",
"True",
")",
"assert",
"hmip_device",
".",
"mock_calls",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
"\"reset_energy_counter\"",
"assert",
"len",
"(",
"hmip_device",
".",
"_connection",
".",
"mock_calls",
")",
"==",
"4"
] | [
214,
0
] | [
241,
55
] | python | en | ['de', 'en', 'en'] | True |
test_hmip_multi_area_device | (hass, default_mock_hap_factory) | Test multi area device. Check if devices are created and referenced. | Test multi area device. Check if devices are created and referenced. | async def test_hmip_multi_area_device(hass, default_mock_hap_factory):
"""Test multi area device. Check if devices are created and referenced."""
entity_id = "binary_sensor.wired_eingangsmodul_32_fach_channel5"
entity_name = "Wired Eingangsmodul – 32-fach Channel5"
device_model = "HmIPW-DRI32"
mock_hap = await default_mock_hap_factory.async_get_mock_hap(
test_devices=["Wired Eingangsmodul – 32-fach"]
)
ha_state, hmip_device = get_and_check_entity_basics(
hass, mock_hap, entity_id, entity_name, device_model
)
assert ha_state
# get the entity
entity_registry = await er.async_get_registry(hass)
entity = entity_registry.async_get(ha_state.entity_id)
assert entity
# get the device
device_registry = await dr.async_get_registry(hass)
device = device_registry.async_get(entity.device_id)
assert device.name == "Wired Eingangsmodul – 32-fach"
# get the hap
hap_device = device_registry.async_get(device.via_device_id)
assert hap_device.name == "Home" | [
"async",
"def",
"test_hmip_multi_area_device",
"(",
"hass",
",",
"default_mock_hap_factory",
")",
":",
"entity_id",
"=",
"\"binary_sensor.wired_eingangsmodul_32_fach_channel5\"",
"entity_name",
"=",
"\"Wired Eingangsmodul – 32-fach Channel5\"",
"device_model",
"=",
"\"HmIPW-DRI32\"",
"mock_hap",
"=",
"await",
"default_mock_hap_factory",
".",
"async_get_mock_hap",
"(",
"test_devices",
"=",
"[",
"\"Wired Eingangsmodul – 32-fach\"]",
"",
")",
"ha_state",
",",
"hmip_device",
"=",
"get_and_check_entity_basics",
"(",
"hass",
",",
"mock_hap",
",",
"entity_id",
",",
"entity_name",
",",
"device_model",
")",
"assert",
"ha_state",
"# get the entity",
"entity_registry",
"=",
"await",
"er",
".",
"async_get_registry",
"(",
"hass",
")",
"entity",
"=",
"entity_registry",
".",
"async_get",
"(",
"ha_state",
".",
"entity_id",
")",
"assert",
"entity",
"# get the device",
"device_registry",
"=",
"await",
"dr",
".",
"async_get_registry",
"(",
"hass",
")",
"device",
"=",
"device_registry",
".",
"async_get",
"(",
"entity",
".",
"device_id",
")",
"assert",
"device",
".",
"name",
"==",
"\"Wired Eingangsmodul – 32-fach\"",
"# get the hap",
"hap_device",
"=",
"device_registry",
".",
"async_get",
"(",
"device",
".",
"via_device_id",
")",
"assert",
"hap_device",
".",
"name",
"==",
"\"Home\""
] | [
244,
0
] | [
270,
36
] | python | en | ['en', 'en', 'en'] | True |
Proxy._join | (self) | Join the communication network for the experiment given by experiment_name with ID given by name.
Specifically, it gets sockets' address for receiving (pulling) messages from its driver and uploads
the receiving address to the Redis server. It then attempts to collect remote peers' receiving address
by querying the Redis server. Finally, ask its driver to connect remote peers using those receiving address.
| Join the communication network for the experiment given by experiment_name with ID given by name. | def _join(self):
"""Join the communication network for the experiment given by experiment_name with ID given by name.
Specifically, it gets sockets' address for receiving (pulling) messages from its driver and uploads
the receiving address to the Redis server. It then attempts to collect remote peers' receiving address
by querying the Redis server. Finally, ask its driver to connect remote peers using those receiving address.
"""
self._register_redis()
self._get_peers_list()
self._build_connection()
# TODO: Handle slow joiner for PUB/SUB.
time.sleep(DELAY_FOR_SLOW_JOINER)
# Build component-container-mapping for dynamic component in k8s/grass cluster.
if "JOB_ID" in os.environ and "CONTAINER_NAME" in os.environ:
container_name = os.getenv("CONTAINER_NAME")
job_id = os.getenv("JOB_ID")
rejoin_config = {
"rejoin:enable": int(self._enable_rejoin),
"rejoin:max_restart_times": self._max_rejoin_times,
"is_remove_failed_container": int(self._is_remove_failed_container)
}
self._redis_connection.hmset(f"job:{job_id}:runtime_details", rejoin_config)
if self._enable_rejoin:
self._redis_connection.hset(
f"job:{job_id}:rejoin_component_name_to_container_name", self._name, container_name
) | [
"def",
"_join",
"(",
"self",
")",
":",
"self",
".",
"_register_redis",
"(",
")",
"self",
".",
"_get_peers_list",
"(",
")",
"self",
".",
"_build_connection",
"(",
")",
"# TODO: Handle slow joiner for PUB/SUB.",
"time",
".",
"sleep",
"(",
"DELAY_FOR_SLOW_JOINER",
")",
"# Build component-container-mapping for dynamic component in k8s/grass cluster.",
"if",
"\"JOB_ID\"",
"in",
"os",
".",
"environ",
"and",
"\"CONTAINER_NAME\"",
"in",
"os",
".",
"environ",
":",
"container_name",
"=",
"os",
".",
"getenv",
"(",
"\"CONTAINER_NAME\"",
")",
"job_id",
"=",
"os",
".",
"getenv",
"(",
"\"JOB_ID\"",
")",
"rejoin_config",
"=",
"{",
"\"rejoin:enable\"",
":",
"int",
"(",
"self",
".",
"_enable_rejoin",
")",
",",
"\"rejoin:max_restart_times\"",
":",
"self",
".",
"_max_rejoin_times",
",",
"\"is_remove_failed_container\"",
":",
"int",
"(",
"self",
".",
"_is_remove_failed_container",
")",
"}",
"self",
".",
"_redis_connection",
".",
"hmset",
"(",
"f\"job:{job_id}:runtime_details\"",
",",
"rejoin_config",
")",
"if",
"self",
".",
"_enable_rejoin",
":",
"self",
".",
"_redis_connection",
".",
"hset",
"(",
"f\"job:{job_id}:rejoin_component_name_to_container_name\"",
",",
"self",
".",
"_name",
",",
"container_name",
")"
] | [
168,
4
] | [
196,
17
] | python | en | ['en', 'en', 'en'] | True |
Proxy._register_redis | (self) | Self-registration on Redis and driver initialization.
Redis store structure:
Hash Table: name: group name + peer's type,
table (Dict[]): The key of table is the peer's name,
the value of table is the peer's socket address.
| Self-registration on Redis and driver initialization. | def _register_redis(self):
"""Self-registration on Redis and driver initialization.
Redis store structure:
Hash Table: name: group name + peer's type,
table (Dict[]): The key of table is the peer's name,
the value of table is the peer's socket address.
"""
self._redis_connection.hset(self._redis_hash_name, self._name, json.dumps(self._driver.address))
# Handle interrupt signal for clearing Redis record.
try:
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
except Exception as e:
self._logger.error(
"Signal detector disable. This may cause dirty data to be left in the Redis! "
"To avoid this, please use multiprocess or make sure it can exit successfully."
f"Due to {str(e)}."
) | [
"def",
"_register_redis",
"(",
"self",
")",
":",
"self",
".",
"_redis_connection",
".",
"hset",
"(",
"self",
".",
"_redis_hash_name",
",",
"self",
".",
"_name",
",",
"json",
".",
"dumps",
"(",
"self",
".",
"_driver",
".",
"address",
")",
")",
"# Handle interrupt signal for clearing Redis record.",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"_signal_handler",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"self",
".",
"_signal_handler",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"\"Signal detector disable. This may cause dirty data to be left in the Redis! \"",
"\"To avoid this, please use multiprocess or make sure it can exit successfully.\"",
"f\"Due to {str(e)}.\"",
")"
] | [
202,
4
] | [
221,
13
] | python | en | ['en', 'en', 'en'] | True |
Proxy._get_peers_list | (self) | To collect all peers' name in the same group (group name) from Redis. | To collect all peers' name in the same group (group name) from Redis. | def _get_peers_list(self):
"""To collect all peers' name in the same group (group name) from Redis."""
if not self._peers_info_dict:
raise PeersMissError(f"Cannot get {self._name}\'s peers.")
for peer_type in self._peers_info_dict.keys():
peer_hash_name, peer_number = self._peers_info_dict[peer_type]
retry_number = 0
expected_peers_name = []
while retry_number < self._max_retries:
if self._redis_connection.hlen(peer_hash_name) >= peer_number:
expected_peers_name = self._redis_connection.hkeys(peer_hash_name)
expected_peers_name = [peer.decode() for peer in expected_peers_name]
if len(expected_peers_name) > peer_number:
expected_peers_name = expected_peers_name[:peer_number]
self._logger.info(f"{self._name} successfully get all {peer_type}\'s name.")
break
else:
self._logger.warn(
f"{self._name} failed to get {peer_type}\'s name. Retrying in "
f"{self._retry_interval_base_value * (2 ** retry_number)} seconds."
)
time.sleep(self._retry_interval_base_value * (2 ** retry_number))
retry_number += 1
if not expected_peers_name:
raise InformationUncompletedError(
f"{self._name} failure to get enough number of {peer_type} from redis."
)
self._onboard_peer_dict[peer_type] = {peer_name: None for peer_name in expected_peers_name}
self._onboard_peers_start_time = time.time() | [
"def",
"_get_peers_list",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_peers_info_dict",
":",
"raise",
"PeersMissError",
"(",
"f\"Cannot get {self._name}\\'s peers.\"",
")",
"for",
"peer_type",
"in",
"self",
".",
"_peers_info_dict",
".",
"keys",
"(",
")",
":",
"peer_hash_name",
",",
"peer_number",
"=",
"self",
".",
"_peers_info_dict",
"[",
"peer_type",
"]",
"retry_number",
"=",
"0",
"expected_peers_name",
"=",
"[",
"]",
"while",
"retry_number",
"<",
"self",
".",
"_max_retries",
":",
"if",
"self",
".",
"_redis_connection",
".",
"hlen",
"(",
"peer_hash_name",
")",
">=",
"peer_number",
":",
"expected_peers_name",
"=",
"self",
".",
"_redis_connection",
".",
"hkeys",
"(",
"peer_hash_name",
")",
"expected_peers_name",
"=",
"[",
"peer",
".",
"decode",
"(",
")",
"for",
"peer",
"in",
"expected_peers_name",
"]",
"if",
"len",
"(",
"expected_peers_name",
")",
">",
"peer_number",
":",
"expected_peers_name",
"=",
"expected_peers_name",
"[",
":",
"peer_number",
"]",
"self",
".",
"_logger",
".",
"info",
"(",
"f\"{self._name} successfully get all {peer_type}\\'s name.\"",
")",
"break",
"else",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"f\"{self._name} failed to get {peer_type}\\'s name. Retrying in \"",
"f\"{self._retry_interval_base_value * (2 ** retry_number)} seconds.\"",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_retry_interval_base_value",
"*",
"(",
"2",
"**",
"retry_number",
")",
")",
"retry_number",
"+=",
"1",
"if",
"not",
"expected_peers_name",
":",
"raise",
"InformationUncompletedError",
"(",
"f\"{self._name} failure to get enough number of {peer_type} from redis.\"",
")",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"=",
"{",
"peer_name",
":",
"None",
"for",
"peer_name",
"in",
"expected_peers_name",
"}",
"self",
".",
"_onboard_peers_start_time",
"=",
"time",
".",
"time",
"(",
")"
] | [
223,
4
] | [
255,
52
] | python | en | ['en', 'en', 'en'] | True |
Proxy._build_connection | (self) | Grabbing all peers' address from Redis, and connect all peers in driver. | Grabbing all peers' address from Redis, and connect all peers in driver. | def _build_connection(self):
"""Grabbing all peers' address from Redis, and connect all peers in driver."""
for peer_type in self._peers_info_dict.keys():
name_list = list(self._onboard_peer_dict[peer_type].keys())
try:
peers_socket_value = self._redis_connection.hmget(
self._peers_info_dict[peer_type].hash_table_name,
name_list
)
for idx, peer_name in enumerate(name_list):
self._onboard_peer_dict[peer_type][peer_name] = json.loads(peers_socket_value[idx])
self._logger.info(f"{self._name} successfully get {peer_name}\'s socket address")
except Exception as e:
raise InformationUncompletedError(f"{self._name} failed to get {name_list}\'s address. Due to {str(e)}")
self._driver.connect(self._onboard_peer_dict[peer_type]) | [
"def",
"_build_connection",
"(",
"self",
")",
":",
"for",
"peer_type",
"in",
"self",
".",
"_peers_info_dict",
".",
"keys",
"(",
")",
":",
"name_list",
"=",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
".",
"keys",
"(",
")",
")",
"try",
":",
"peers_socket_value",
"=",
"self",
".",
"_redis_connection",
".",
"hmget",
"(",
"self",
".",
"_peers_info_dict",
"[",
"peer_type",
"]",
".",
"hash_table_name",
",",
"name_list",
")",
"for",
"idx",
",",
"peer_name",
"in",
"enumerate",
"(",
"name_list",
")",
":",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
"=",
"json",
".",
"loads",
"(",
"peers_socket_value",
"[",
"idx",
"]",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"f\"{self._name} successfully get {peer_name}\\'s socket address\"",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"InformationUncompletedError",
"(",
"f\"{self._name} failed to get {name_list}\\'s address. Due to {str(e)}\"",
")",
"self",
".",
"_driver",
".",
"connect",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
")"
] | [
257,
4
] | [
272,
68
] | python | en | ['en', 'en', 'en'] | True |
Proxy.group_name | (self) | str: Identifier for the group of all communication components. | str: Identifier for the group of all communication components. | def group_name(self) -> str:
"""str: Identifier for the group of all communication components."""
return self._group_name | [
"def",
"group_name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_group_name"
] | [
275,
4
] | [
277,
31
] | python | en | ['en', 'en', 'en'] | True |
Proxy.name | (self) | str: Unique identifier in the current group. | str: Unique identifier in the current group. | def name(self) -> str:
"""str: Unique identifier in the current group."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
280,
4
] | [
282,
25
] | python | en | ['en', 'en', 'en'] | True |
Proxy.component_type | (self) | str: Component's type in the current group. | str: Component's type in the current group. | def component_type(self) -> str:
"""str: Component's type in the current group."""
return self._component_type | [
"def",
"component_type",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_component_type"
] | [
285,
4
] | [
287,
35
] | python | en | ['en', 'en', 'en'] | True |
Proxy.peers_name | (self) | Dict: The ``Dict`` of all connected peers' names, stored by peer type. | Dict: The ``Dict`` of all connected peers' names, stored by peer type. | def peers_name(self) -> Dict:
"""Dict: The ``Dict`` of all connected peers' names, stored by peer type."""
return {
peer_type: list(self._onboard_peer_dict[peer_type].keys()) for peer_type in self._peers_info_dict.keys()
} | [
"def",
"peers_name",
"(",
"self",
")",
"->",
"Dict",
":",
"return",
"{",
"peer_type",
":",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
".",
"keys",
"(",
")",
")",
"for",
"peer_type",
"in",
"self",
".",
"_peers_info_dict",
".",
"keys",
"(",
")",
"}"
] | [
290,
4
] | [
294,
9
] | python | en | ['en', 'en', 'en'] | True |
Proxy.receive | (self, is_continuous: bool = True, timeout: int = None) | Receive messages from communication driver.
Args:
is_continuous (bool): Continuously receive message or not. Defaults to True.
| Receive messages from communication driver. | def receive(self, is_continuous: bool = True, timeout: int = None):
"""Receive messages from communication driver.
Args:
is_continuous (bool): Continuously receive message or not. Defaults to True.
"""
return self._driver.receive(is_continuous, timeout=timeout) | [
"def",
"receive",
"(",
"self",
",",
"is_continuous",
":",
"bool",
"=",
"True",
",",
"timeout",
":",
"int",
"=",
"None",
")",
":",
"return",
"self",
".",
"_driver",
".",
"receive",
"(",
"is_continuous",
",",
"timeout",
"=",
"timeout",
")"
] | [
296,
4
] | [
302,
67
] | python | en | ['en', 'en', 'en'] | True |
Proxy.receive_by_id | (self, targets: List[str], timeout: int = None) | Receive target messages from communication driver.
Args:
targets List[str]: List of ``session_id``.
E.g. ['0_learner0_actor0', '1_learner1_actor1', ...].
Returns:
List[Message]: List of received messages.
| Receive target messages from communication driver. | def receive_by_id(self, targets: List[str], timeout: int = None) -> List[Message]:
"""Receive target messages from communication driver.
Args:
targets List[str]: List of ``session_id``.
E.g. ['0_learner0_actor0', '1_learner1_actor1', ...].
Returns:
List[Message]: List of received messages.
"""
if not isinstance(targets, list) and not isinstance(targets, str):
# The input may be None, if enable peer rejoin.
self._logger.warn(f"Unrecognized target {targets}.")
return
# Pre-process targets.
if isinstance(targets, str):
targets = [targets]
pending_targets, received_messages = targets[:], []
# Check message cache for saved messages.
for session_id in targets:
if session_id in self._message_cache:
pending_targets.remove(session_id)
received_messages.append(self._message_cache[session_id].pop(0))
if not self._message_cache[session_id]:
del self._message_cache[session_id]
if not pending_targets:
return received_messages
# Wait for incoming messages.
for msg in self._driver.receive(is_continuous=True, timeout=timeout):
if not msg:
return received_messages
if msg.session_id in pending_targets:
pending_targets.remove(msg.session_id)
received_messages.append(msg)
else:
self._message_cache[msg.session_id].append(msg)
if not pending_targets:
break
return received_messages | [
"def",
"receive_by_id",
"(",
"self",
",",
"targets",
":",
"List",
"[",
"str",
"]",
",",
"timeout",
":",
"int",
"=",
"None",
")",
"->",
"List",
"[",
"Message",
"]",
":",
"if",
"not",
"isinstance",
"(",
"targets",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"targets",
",",
"str",
")",
":",
"# The input may be None, if enable peer rejoin.",
"self",
".",
"_logger",
".",
"warn",
"(",
"f\"Unrecognized target {targets}.\"",
")",
"return",
"# Pre-process targets.",
"if",
"isinstance",
"(",
"targets",
",",
"str",
")",
":",
"targets",
"=",
"[",
"targets",
"]",
"pending_targets",
",",
"received_messages",
"=",
"targets",
"[",
":",
"]",
",",
"[",
"]",
"# Check message cache for saved messages.",
"for",
"session_id",
"in",
"targets",
":",
"if",
"session_id",
"in",
"self",
".",
"_message_cache",
":",
"pending_targets",
".",
"remove",
"(",
"session_id",
")",
"received_messages",
".",
"append",
"(",
"self",
".",
"_message_cache",
"[",
"session_id",
"]",
".",
"pop",
"(",
"0",
")",
")",
"if",
"not",
"self",
".",
"_message_cache",
"[",
"session_id",
"]",
":",
"del",
"self",
".",
"_message_cache",
"[",
"session_id",
"]",
"if",
"not",
"pending_targets",
":",
"return",
"received_messages",
"# Wait for incoming messages.",
"for",
"msg",
"in",
"self",
".",
"_driver",
".",
"receive",
"(",
"is_continuous",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
":",
"if",
"not",
"msg",
":",
"return",
"received_messages",
"if",
"msg",
".",
"session_id",
"in",
"pending_targets",
":",
"pending_targets",
".",
"remove",
"(",
"msg",
".",
"session_id",
")",
"received_messages",
".",
"append",
"(",
"msg",
")",
"else",
":",
"self",
".",
"_message_cache",
"[",
"msg",
".",
"session_id",
"]",
".",
"append",
"(",
"msg",
")",
"if",
"not",
"pending_targets",
":",
"break",
"return",
"received_messages"
] | [
304,
4
] | [
349,
32
] | python | en | ['en', 'en', 'en'] | True |
Proxy._scatter | (
self,
tag: Union[str, Enum],
session_type: SessionType,
destination_payload_list: list
) | Scatters a list of data to peers, and return list of session id. | Scatters a list of data to peers, and return list of session id. | def _scatter(
self,
tag: Union[str, Enum],
session_type: SessionType,
destination_payload_list: list
) -> List[str]:
"""Scatters a list of data to peers, and return list of session id."""
session_id_list = []
for destination, payload in destination_payload_list:
message = SessionMessage(
tag=tag,
source=self._name,
destination=destination,
payload=payload,
session_type=session_type
)
send_result = self.isend(message)
if isinstance(send_result, list):
session_id_list += send_result
return session_id_list | [
"def",
"_scatter",
"(",
"self",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
",",
"session_type",
":",
"SessionType",
",",
"destination_payload_list",
":",
"list",
")",
"->",
"List",
"[",
"str",
"]",
":",
"session_id_list",
"=",
"[",
"]",
"for",
"destination",
",",
"payload",
"in",
"destination_payload_list",
":",
"message",
"=",
"SessionMessage",
"(",
"tag",
"=",
"tag",
",",
"source",
"=",
"self",
".",
"_name",
",",
"destination",
"=",
"destination",
",",
"payload",
"=",
"payload",
",",
"session_type",
"=",
"session_type",
")",
"send_result",
"=",
"self",
".",
"isend",
"(",
"message",
")",
"if",
"isinstance",
"(",
"send_result",
",",
"list",
")",
":",
"session_id_list",
"+=",
"send_result",
"return",
"session_id_list"
] | [
351,
4
] | [
372,
30
] | python | en | ['en', 'en', 'en'] | True |
Proxy.scatter | (
self,
tag: Union[str, Enum],
session_type: SessionType,
destination_payload_list: list,
timeout: int = -1
) | Scatters a list of data to peers, and return replied messages.
Args:
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
destination_payload_list ([Tuple(str, object)]): The destination-payload list.
The first item of the tuple in list is the message destination,
and the second item of the tuple in list is the message payload.
Returns:
List[Message]: List of replied message.
| Scatters a list of data to peers, and return replied messages. | def scatter(
self,
tag: Union[str, Enum],
session_type: SessionType,
destination_payload_list: list,
timeout: int = -1
) -> List[Message]:
"""Scatters a list of data to peers, and return replied messages.
Args:
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
destination_payload_list ([Tuple(str, object)]): The destination-payload list.
The first item of the tuple in list is the message destination,
and the second item of the tuple in list is the message payload.
Returns:
List[Message]: List of replied message.
"""
return self.receive_by_id(
targets=self._scatter(tag, session_type, destination_payload_list),
timeout=timeout
) | [
"def",
"scatter",
"(",
"self",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
",",
"session_type",
":",
"SessionType",
",",
"destination_payload_list",
":",
"list",
",",
"timeout",
":",
"int",
"=",
"-",
"1",
")",
"->",
"List",
"[",
"Message",
"]",
":",
"return",
"self",
".",
"receive_by_id",
"(",
"targets",
"=",
"self",
".",
"_scatter",
"(",
"tag",
",",
"session_type",
",",
"destination_payload_list",
")",
",",
"timeout",
"=",
"timeout",
")"
] | [
374,
4
] | [
396,
9
] | python | en | ['en', 'en', 'en'] | True |
Proxy.iscatter | (
self,
tag: Union[str, Enum],
session_type: SessionType,
destination_payload_list: list
) | Scatters a list of data to peers, and return list of message id.
Args:
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
destination_payload_list ([Tuple(str, object)]): The destination-payload list.
The first item of the tuple in list is the message's destination,
and the second item of the tuple in list is the message's payload.
Returns:
List[str]: List of message's session id.
| Scatters a list of data to peers, and return list of message id. | def iscatter(
self,
tag: Union[str, Enum],
session_type: SessionType,
destination_payload_list: list
) -> List[str]:
"""Scatters a list of data to peers, and return list of message id.
Args:
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
destination_payload_list ([Tuple(str, object)]): The destination-payload list.
The first item of the tuple in list is the message's destination,
and the second item of the tuple in list is the message's payload.
Returns:
List[str]: List of message's session id.
"""
return self._scatter(tag, session_type, destination_payload_list) | [
"def",
"iscatter",
"(",
"self",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
",",
"session_type",
":",
"SessionType",
",",
"destination_payload_list",
":",
"list",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_scatter",
"(",
"tag",
",",
"session_type",
",",
"destination_payload_list",
")"
] | [
398,
4
] | [
416,
73
] | python | en | ['en', 'en', 'en'] | True |
Proxy._broadcast | (
self,
component_type: str,
tag: Union[str, Enum],
session_type: SessionType,
payload=None
) | Broadcast message to all peers, and return list of session id. | Broadcast message to all peers, and return list of session id. | def _broadcast(
self,
component_type: str,
tag: Union[str, Enum],
session_type: SessionType,
payload=None
) -> List[str]:
"""Broadcast message to all peers, and return list of session id."""
if component_type not in list(self._onboard_peer_dict.keys()):
self._logger.error(
f"peer_type: {component_type} cannot be recognized. Please check the input of proxy.broadcast."
)
sys.exit(NON_RESTART_EXIT_CODE)
if self._enable_rejoin:
self._rejoin(component_type)
message = SessionMessage(
tag=tag,
source=self._name,
destination=component_type,
payload=payload,
session_type=session_type
)
self._driver.broadcast(component_type, message)
return [message.session_id for _ in range(len(self._onboard_peer_dict[component_type]))] | [
"def",
"_broadcast",
"(",
"self",
",",
"component_type",
":",
"str",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
",",
"session_type",
":",
"SessionType",
",",
"payload",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"component_type",
"not",
"in",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"f\"peer_type: {component_type} cannot be recognized. Please check the input of proxy.broadcast.\"",
")",
"sys",
".",
"exit",
"(",
"NON_RESTART_EXIT_CODE",
")",
"if",
"self",
".",
"_enable_rejoin",
":",
"self",
".",
"_rejoin",
"(",
"component_type",
")",
"message",
"=",
"SessionMessage",
"(",
"tag",
"=",
"tag",
",",
"source",
"=",
"self",
".",
"_name",
",",
"destination",
"=",
"component_type",
",",
"payload",
"=",
"payload",
",",
"session_type",
"=",
"session_type",
")",
"self",
".",
"_driver",
".",
"broadcast",
"(",
"component_type",
",",
"message",
")",
"return",
"[",
"message",
".",
"session_id",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"component_type",
"]",
")",
")",
"]"
] | [
418,
4
] | [
445,
96
] | python | en | ['en', 'en', 'en'] | True |
Proxy.broadcast | (
self,
component_type: str,
tag: Union[str, Enum],
session_type: SessionType,
payload=None,
timeout: int = None
) | Broadcast message to all peers, and return all replied messages.
Args:
component_type (str): Broadcast to all peers in this type.
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
payload (object): The true data. Defaults to None.
Returns:
List[Message]: List of replied messages.
| Broadcast message to all peers, and return all replied messages. | def broadcast(
self,
component_type: str,
tag: Union[str, Enum],
session_type: SessionType,
payload=None,
timeout: int = None
) -> List[Message]:
"""Broadcast message to all peers, and return all replied messages.
Args:
component_type (str): Broadcast to all peers in this type.
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
payload (object): The true data. Defaults to None.
Returns:
List[Message]: List of replied messages.
"""
return self.receive_by_id(
targets=self._broadcast(component_type, tag, session_type, payload),
timeout=timeout
) | [
"def",
"broadcast",
"(",
"self",
",",
"component_type",
":",
"str",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
",",
"session_type",
":",
"SessionType",
",",
"payload",
"=",
"None",
",",
"timeout",
":",
"int",
"=",
"None",
")",
"->",
"List",
"[",
"Message",
"]",
":",
"return",
"self",
".",
"receive_by_id",
"(",
"targets",
"=",
"self",
".",
"_broadcast",
"(",
"component_type",
",",
"tag",
",",
"session_type",
",",
"payload",
")",
",",
"timeout",
"=",
"timeout",
")"
] | [
447,
4
] | [
469,
9
] | python | en | ['en', 'en', 'en'] | True |
Proxy.ibroadcast | (
self,
component_type: str,
tag: Union[str, Enum],
session_type: SessionType,
payload=None
) | Broadcast message to all subscribers, and return list of message's session id.
Args:
component_type (str): Broadcast to all peers in this type.
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
payload (object): The true data. Defaults to None.
Returns:
List[str]: List of message's session id which related to the replied message.
| Broadcast message to all subscribers, and return list of message's session id. | def ibroadcast(
self,
component_type: str,
tag: Union[str, Enum],
session_type: SessionType,
payload=None
) -> List[str]:
"""Broadcast message to all subscribers, and return list of message's session id.
Args:
component_type (str): Broadcast to all peers in this type.
tag (str|Enum): Message's tag.
session_type (Enum): Message's session type.
payload (object): The true data. Defaults to None.
Returns:
List[str]: List of message's session id which related to the replied message.
"""
return self._broadcast(component_type, tag, session_type, payload) | [
"def",
"ibroadcast",
"(",
"self",
",",
"component_type",
":",
"str",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
",",
"session_type",
":",
"SessionType",
",",
"payload",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_broadcast",
"(",
"component_type",
",",
"tag",
",",
"session_type",
",",
"payload",
")"
] | [
471,
4
] | [
489,
74
] | python | en | ['en', 'en', 'en'] | True |
Proxy._send | (self, message: Message) | Send a message to a remote peer.
Args:
message: Message to be sent.
Returns:
Union[List[str], None]: The list of message's session id;
If enable rejoin, it will return None when sending message to the failed peers;
If enable rejoin and message cache, it may return list of session id which from
the pending messages in message cache.
| Send a message to a remote peer. | def _send(self, message: Message) -> Union[List[str], None]:
"""Send a message to a remote peer.
Args:
message: Message to be sent.
Returns:
Union[List[str], None]: The list of message's session id;
If enable rejoin, it will return None when sending message to the failed peers;
If enable rejoin and message cache, it may return list of session id which from
the pending messages in message cache.
"""
session_id_list = []
if self._enable_rejoin:
peer_type = self.get_peer_type(message.destination)
self._rejoin(peer_type)
# Check message cache.
if (
self._enable_message_cache
and message.destination in list(self._onboard_peer_dict[peer_type].keys())
and message.destination in list(self._message_cache_for_exited_peers.keys())
):
self._logger.info(f"Sending pending message to {message.destination}.")
for pending_message in self._message_cache_for_exited_peers[message.destination]:
self._driver.send(pending_message)
session_id_list.append(pending_message.session_id)
del self._message_cache_for_exited_peers[message.destination]
try:
self._driver.send(message)
session_id_list.append(message.session_id)
return session_id_list
except PendingToSend as e:
self._logger.warn(f"{e} Peer {message.destination} exited, but still have enough peers.")
if self._enable_message_cache:
self._push_message_to_message_cache(message) | [
"def",
"_send",
"(",
"self",
",",
"message",
":",
"Message",
")",
"->",
"Union",
"[",
"List",
"[",
"str",
"]",
",",
"None",
"]",
":",
"session_id_list",
"=",
"[",
"]",
"if",
"self",
".",
"_enable_rejoin",
":",
"peer_type",
"=",
"self",
".",
"get_peer_type",
"(",
"message",
".",
"destination",
")",
"self",
".",
"_rejoin",
"(",
"peer_type",
")",
"# Check message cache.",
"if",
"(",
"self",
".",
"_enable_message_cache",
"and",
"message",
".",
"destination",
"in",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
".",
"keys",
"(",
")",
")",
"and",
"message",
".",
"destination",
"in",
"list",
"(",
"self",
".",
"_message_cache_for_exited_peers",
".",
"keys",
"(",
")",
")",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"f\"Sending pending message to {message.destination}.\"",
")",
"for",
"pending_message",
"in",
"self",
".",
"_message_cache_for_exited_peers",
"[",
"message",
".",
"destination",
"]",
":",
"self",
".",
"_driver",
".",
"send",
"(",
"pending_message",
")",
"session_id_list",
".",
"append",
"(",
"pending_message",
".",
"session_id",
")",
"del",
"self",
".",
"_message_cache_for_exited_peers",
"[",
"message",
".",
"destination",
"]",
"try",
":",
"self",
".",
"_driver",
".",
"send",
"(",
"message",
")",
"session_id_list",
".",
"append",
"(",
"message",
".",
"session_id",
")",
"return",
"session_id_list",
"except",
"PendingToSend",
"as",
"e",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"f\"{e} Peer {message.destination} exited, but still have enough peers.\"",
")",
"if",
"self",
".",
"_enable_message_cache",
":",
"self",
".",
"_push_message_to_message_cache",
"(",
"message",
")"
] | [
491,
4
] | [
527,
60
] | python | en | ['en', 'en', 'en'] | True |
Proxy.isend | (self, message: Message) | Send a message to a remote peer.
Args:
message: Message to be sent.
Returns:
Union[List[str], None]: The list of message's session id;
If enable rejoin, it will return None when sending message to the failed peers.
If enable rejoin and message cache, it may return list of session id which from
the pending messages.
| Send a message to a remote peer. | def isend(self, message: Message) -> Union[List[str], None]:
"""Send a message to a remote peer.
Args:
message: Message to be sent.
Returns:
Union[List[str], None]: The list of message's session id;
If enable rejoin, it will return None when sending message to the failed peers.
If enable rejoin and message cache, it may return list of session id which from
the pending messages.
"""
return self._send(message) | [
"def",
"isend",
"(",
"self",
",",
"message",
":",
"Message",
")",
"->",
"Union",
"[",
"List",
"[",
"str",
"]",
",",
"None",
"]",
":",
"return",
"self",
".",
"_send",
"(",
"message",
")"
] | [
529,
4
] | [
541,
34
] | python | en | ['en', 'en', 'en'] | True |
Proxy.send | (
self,
message: Message,
timeout: int = None
) | Send a message to a remote peer.
Args:
message: Message to be sent.
Returns:
Union[List[Message], None]: The list of received message;
If enable rejoin, it will return None when sending message to the failed peers.
If enable rejoin and message cache, it may return list of messages which from
the pending messages.
| Send a message to a remote peer. | def send(
self,
message: Message,
timeout: int = None
) -> Union[List[Message], None]:
"""Send a message to a remote peer.
Args:
message: Message to be sent.
Returns:
Union[List[Message], None]: The list of received message;
If enable rejoin, it will return None when sending message to the failed peers.
If enable rejoin and message cache, it may return list of messages which from
the pending messages.
"""
return self.receive_by_id(self._send(message), timeout) | [
"def",
"send",
"(",
"self",
",",
"message",
":",
"Message",
",",
"timeout",
":",
"int",
"=",
"None",
")",
"->",
"Union",
"[",
"List",
"[",
"Message",
"]",
",",
"None",
"]",
":",
"return",
"self",
".",
"receive_by_id",
"(",
"self",
".",
"_send",
"(",
"message",
")",
",",
"timeout",
")"
] | [
543,
4
] | [
559,
63
] | python | en | ['en', 'en', 'en'] | True |
Proxy.reply | (
self,
message: Union[SessionMessage, Message],
tag: Union[str, Enum] = None,
payload=None,
ack_reply: bool = False
) | Reply a received message.
Args:
message (Message): The message need to reply.
tag (str|Enum): New message tag, if None, keeps the original message's tag. Defaults to None.
payload (object): New message payload, if None, keeps the original message's payload. Defaults to None.
ack_reply (bool): If True, it is acknowledge reply. Defaults to False.
Returns:
List[str]: Message belonged session id.
| Reply a received message. | def reply(
self,
message: Union[SessionMessage, Message],
tag: Union[str, Enum] = None,
payload=None,
ack_reply: bool = False
) -> List[str]:
"""Reply a received message.
Args:
message (Message): The message need to reply.
tag (str|Enum): New message tag, if None, keeps the original message's tag. Defaults to None.
payload (object): New message payload, if None, keeps the original message's payload. Defaults to None.
ack_reply (bool): If True, it is acknowledge reply. Defaults to False.
Returns:
List[str]: Message belonged session id.
"""
message.reply(tag=tag, payload=payload)
if isinstance(message, SessionMessage):
if message.session_type == SessionType.TASK:
session_stage = TaskSessionStage.RECEIVE if ack_reply else TaskSessionStage.COMPLETE
else:
session_stage = NotificationSessionStage.RECEIVE
message.session_stage = session_stage
return self.isend(message) | [
"def",
"reply",
"(",
"self",
",",
"message",
":",
"Union",
"[",
"SessionMessage",
",",
"Message",
"]",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
"=",
"None",
",",
"payload",
"=",
"None",
",",
"ack_reply",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"message",
".",
"reply",
"(",
"tag",
"=",
"tag",
",",
"payload",
"=",
"payload",
")",
"if",
"isinstance",
"(",
"message",
",",
"SessionMessage",
")",
":",
"if",
"message",
".",
"session_type",
"==",
"SessionType",
".",
"TASK",
":",
"session_stage",
"=",
"TaskSessionStage",
".",
"RECEIVE",
"if",
"ack_reply",
"else",
"TaskSessionStage",
".",
"COMPLETE",
"else",
":",
"session_stage",
"=",
"NotificationSessionStage",
".",
"RECEIVE",
"message",
".",
"session_stage",
"=",
"session_stage",
"return",
"self",
".",
"isend",
"(",
"message",
")"
] | [
561,
4
] | [
587,
34
] | python | en | ['en', 'en', 'en'] | True |
Proxy.forward | (
self,
message: Union[SessionMessage, Message],
destination: str,
tag: Union[str, Enum] = None,
payload=None
) | Forward a received message.
Args:
message (Message): The message need to forward.
destination (str): The receiver of message.
tag (str|Enum): New message tag, if None, keeps the original message's tag. Defaults to None.
payload (object): Message payload, if None, keeps the original message's payload. Defaults to None.
Returns:
List[str]: Message belonged session id.
| Forward a received message. | def forward(
self,
message: Union[SessionMessage, Message],
destination: str,
tag: Union[str, Enum] = None,
payload=None
) -> List[str]:
"""Forward a received message.
Args:
message (Message): The message need to forward.
destination (str): The receiver of message.
tag (str|Enum): New message tag, if None, keeps the original message's tag. Defaults to None.
payload (object): Message payload, if None, keeps the original message's payload. Defaults to None.
Returns:
List[str]: Message belonged session id.
"""
message.forward(destination=destination, tag=tag, payload=payload)
return self.isend(message) | [
"def",
"forward",
"(",
"self",
",",
"message",
":",
"Union",
"[",
"SessionMessage",
",",
"Message",
"]",
",",
"destination",
":",
"str",
",",
"tag",
":",
"Union",
"[",
"str",
",",
"Enum",
"]",
"=",
"None",
",",
"payload",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"message",
".",
"forward",
"(",
"destination",
"=",
"destination",
",",
"tag",
"=",
"tag",
",",
"payload",
"=",
"payload",
")",
"return",
"self",
".",
"isend",
"(",
"message",
")"
] | [
589,
4
] | [
608,
34
] | python | en | ['en', 'en', 'en'] | True |
Proxy._check_peers_update | (self) | Compare the peers' information on local with the peers' information on Redis.
For the different between two peers information dict's key (peer_name):
If some peers only appear on Redis, the proxy will connect with those peers;
If some peers only appear on local, the proxy will disconnect with those peers;
For the different between two peers information dict's value (peers_socket_address):
If some peers' information is different between Redis and local, the proxy will update those
peers (driver disconnect with the local information and connect with the peer's information on Redis).
| Compare the peers' information on local with the peers' information on Redis. | def _check_peers_update(self):
"""Compare the peers' information on local with the peers' information on Redis.
For the different between two peers information dict's key (peer_name):
If some peers only appear on Redis, the proxy will connect with those peers;
If some peers only appear on local, the proxy will disconnect with those peers;
For the different between two peers information dict's value (peers_socket_address):
If some peers' information is different between Redis and local, the proxy will update those
peers (driver disconnect with the local information and connect with the peer's information on Redis).
"""
for peer_type in self._peers_info_dict.keys():
# onboard_peers_dict_on_redis is the newest peers' information from the Redis.
onboard_peers_dict_on_redis = self._redis_connection.hgetall(
self._peers_info_dict[peer_type].hash_table_name
)
onboard_peers_dict_on_redis = {
key.decode(): json.loads(value) for key, value in onboard_peers_dict_on_redis.items()
}
# Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs.
# Equality comparison of the keys and values enforces reflexivity.
if self._onboard_peer_dict[peer_type] != onboard_peers_dict_on_redis:
union_peer_name = list(self._onboard_peer_dict[peer_type].keys()) + \
list(onboard_peers_dict_on_redis.keys())
for peer_name in union_peer_name:
# Add new peers (new key added on redis).
if peer_name not in list(self._onboard_peer_dict[peer_type].keys()):
self._logger.info(f"PEER_REJOIN: New peer {peer_name} join.")
self._driver.connect({peer_name: onboard_peers_dict_on_redis[peer_name]})
self._onboard_peer_dict[peer_type][peer_name] = onboard_peers_dict_on_redis[peer_name]
# Delete out of date peers (old key deleted on local)
elif peer_name not in onboard_peers_dict_on_redis.keys():
self._logger.info(f"PEER_REJOIN: Peer {peer_name} exited.")
self._driver.disconnect({peer_name: self._onboard_peer_dict[peer_type][peer_name]})
del self._onboard_peer_dict[peer_type][peer_name]
else:
# Peer's ip/port updated, re-connect (value update on redis).
if onboard_peers_dict_on_redis[peer_name] != self._onboard_peer_dict[peer_type][peer_name]:
self._logger.info(f"PEER_REJOIN: Peer {peer_name} rejoin.")
self._driver.disconnect({peer_name: self._onboard_peer_dict[peer_type][peer_name]})
self._driver.connect({peer_name: onboard_peers_dict_on_redis[peer_name]})
self._onboard_peer_dict[peer_type][peer_name] = onboard_peers_dict_on_redis[peer_name] | [
"def",
"_check_peers_update",
"(",
"self",
")",
":",
"for",
"peer_type",
"in",
"self",
".",
"_peers_info_dict",
".",
"keys",
"(",
")",
":",
"# onboard_peers_dict_on_redis is the newest peers' information from the Redis.",
"onboard_peers_dict_on_redis",
"=",
"self",
".",
"_redis_connection",
".",
"hgetall",
"(",
"self",
".",
"_peers_info_dict",
"[",
"peer_type",
"]",
".",
"hash_table_name",
")",
"onboard_peers_dict_on_redis",
"=",
"{",
"key",
".",
"decode",
"(",
")",
":",
"json",
".",
"loads",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"onboard_peers_dict_on_redis",
".",
"items",
"(",
")",
"}",
"# Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs.",
"# Equality comparison of the keys and values enforces reflexivity.",
"if",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"!=",
"onboard_peers_dict_on_redis",
":",
"union_peer_name",
"=",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
".",
"keys",
"(",
")",
")",
"+",
"list",
"(",
"onboard_peers_dict_on_redis",
".",
"keys",
"(",
")",
")",
"for",
"peer_name",
"in",
"union_peer_name",
":",
"# Add new peers (new key added on redis).",
"if",
"peer_name",
"not",
"in",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"f\"PEER_REJOIN: New peer {peer_name} join.\"",
")",
"self",
".",
"_driver",
".",
"connect",
"(",
"{",
"peer_name",
":",
"onboard_peers_dict_on_redis",
"[",
"peer_name",
"]",
"}",
")",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
"=",
"onboard_peers_dict_on_redis",
"[",
"peer_name",
"]",
"# Delete out of date peers (old key deleted on local)",
"elif",
"peer_name",
"not",
"in",
"onboard_peers_dict_on_redis",
".",
"keys",
"(",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"f\"PEER_REJOIN: Peer {peer_name} exited.\"",
")",
"self",
".",
"_driver",
".",
"disconnect",
"(",
"{",
"peer_name",
":",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
"}",
")",
"del",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
"else",
":",
"# Peer's ip/port updated, re-connect (value update on redis).",
"if",
"onboard_peers_dict_on_redis",
"[",
"peer_name",
"]",
"!=",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"f\"PEER_REJOIN: Peer {peer_name} rejoin.\"",
")",
"self",
".",
"_driver",
".",
"disconnect",
"(",
"{",
"peer_name",
":",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
"}",
")",
"self",
".",
"_driver",
".",
"connect",
"(",
"{",
"peer_name",
":",
"onboard_peers_dict_on_redis",
"[",
"peer_name",
"]",
"}",
")",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
"[",
"peer_name",
"]",
"=",
"onboard_peers_dict_on_redis",
"[",
"peer_name",
"]"
] | [
610,
4
] | [
651,
114
] | python | en | ['en', 'en', 'en'] | True |
Proxy._rejoin | (self, peer_type=None) | The logic about proxy rejoin.
Update onboard peers with the peers on Redis, if onboard peers expired.
If there are not enough peers for the given peer type, block until peers rejoin or timeout.
| The logic about proxy rejoin. | def _rejoin(self, peer_type=None):
"""The logic about proxy rejoin.
Update onboard peers with the peers on Redis, if onboard peers expired.
If there are not enough peers for the given peer type, block until peers rejoin or timeout.
"""
current_time = time.time()
if current_time - self._onboard_peers_start_time > self._peers_catch_lifetime:
self._check_peers_update()
self._onboard_peers_start_time = current_time
if len(self._onboard_peer_dict[peer_type].keys()) < self._minimal_peers[peer_type]:
self._wait_for_minimal_peer_number(peer_type) | [
"def",
"_rejoin",
"(",
"self",
",",
"peer_type",
"=",
"None",
")",
":",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"current_time",
"-",
"self",
".",
"_onboard_peers_start_time",
">",
"self",
".",
"_peers_catch_lifetime",
":",
"self",
".",
"_check_peers_update",
"(",
")",
"self",
".",
"_onboard_peers_start_time",
"=",
"current_time",
"if",
"len",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
".",
"keys",
"(",
")",
")",
"<",
"self",
".",
"_minimal_peers",
"[",
"peer_type",
"]",
":",
"self",
".",
"_wait_for_minimal_peer_number",
"(",
"peer_type",
")"
] | [
653,
4
] | [
666,
57
] | python | en | ['en', 'en', 'en'] | True |
Proxy._wait_for_minimal_peer_number | (self, peer_type) | Blocking until there are enough peers for the given peer type. | Blocking until there are enough peers for the given peer type. | def _wait_for_minimal_peer_number(self, peer_type):
"""Blocking until there are enough peers for the given peer type."""
start_time = time.time()
while time.time() - start_time < self._timeout_for_minimal_peer_number:
self._logger.warn(
f"No enough peers in {peer_type}! Wait for some peer restart. Remaining time: "
f"{start_time + self._timeout_for_minimal_peer_number - time.time()}"
)
self._check_peers_update()
if len(self._onboard_peer_dict[peer_type]) >= self._minimal_peers[peer_type]:
return
time.sleep(self._peers_catch_lifetime)
self._logger.error(f"Failure to get enough peers for {peer_type}. All components will exited.")
sys.exit(KILL_ALL_EXIT_CODE) | [
"def",
"_wait_for_minimal_peer_number",
"(",
"self",
",",
"peer_type",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"<",
"self",
".",
"_timeout_for_minimal_peer_number",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"f\"No enough peers in {peer_type}! Wait for some peer restart. Remaining time: \"",
"f\"{start_time + self._timeout_for_minimal_peer_number - time.time()}\"",
")",
"self",
".",
"_check_peers_update",
"(",
")",
"if",
"len",
"(",
"self",
".",
"_onboard_peer_dict",
"[",
"peer_type",
"]",
")",
">=",
"self",
".",
"_minimal_peers",
"[",
"peer_type",
"]",
":",
"return",
"time",
".",
"sleep",
"(",
"self",
".",
"_peers_catch_lifetime",
")",
"self",
".",
"_logger",
".",
"error",
"(",
"f\"Failure to get enough peers for {peer_type}. All components will exited.\"",
")",
"sys",
".",
"exit",
"(",
"KILL_ALL_EXIT_CODE",
")"
] | [
668,
4
] | [
685,
36
] | python | en | ['en', 'en', 'en'] | True |
Proxy.get_peer_type | (self, peer_name: str) | Get peer type from given peer name.
Args:
peer_name (str): The component name of a peer, which form by peer_type and UUID.
Returns:
str: The component type of a peer in current group.
| Get peer type from given peer name. | def get_peer_type(self, peer_name: str) -> str:
"""Get peer type from given peer name.
Args:
peer_name (str): The component name of a peer, which form by peer_type and UUID.
Returns:
str: The component type of a peer in current group.
"""
# peer_name is consist by peer_type + '_proxy_' + UUID where UUID is only compose by digits and letters.
# So the peer_type must be the part before last '_proxy_'.
peer_type = peer_name[:peer_name.rfind("_proxy_")]
if peer_type not in list(self._onboard_peer_dict.keys()):
self._logger.error(
f"The message's destination {peer_name} does not belong to any recognized peer type. "
f"Please check the input of message."
)
sys.exit(NON_RESTART_EXIT_CODE)
return peer_type | [
"def",
"get_peer_type",
"(",
"self",
",",
"peer_name",
":",
"str",
")",
"->",
"str",
":",
"# peer_name is consist by peer_type + '_proxy_' + UUID where UUID is only compose by digits and letters.",
"# So the peer_type must be the part before last '_proxy_'.",
"peer_type",
"=",
"peer_name",
"[",
":",
"peer_name",
".",
"rfind",
"(",
"\"_proxy_\"",
")",
"]",
"if",
"peer_type",
"not",
"in",
"list",
"(",
"self",
".",
"_onboard_peer_dict",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"f\"The message's destination {peer_name} does not belong to any recognized peer type. \"",
"f\"Please check the input of message.\"",
")",
"sys",
".",
"exit",
"(",
"NON_RESTART_EXIT_CODE",
")",
"return",
"peer_type"
] | [
687,
4
] | [
707,
24
] | python | en | ['en', 'en', 'en'] | True |
is_on | (hass, entity_id=None) | Load up the module to call the is_on method.
If there is no entity id given we will check all.
| Load up the module to call the is_on method. | def is_on(hass, entity_id=None):
"""Load up the module to call the is_on method.
If there is no entity id given we will check all.
"""
if entity_id:
entity_ids = hass.components.group.expand_entity_ids([entity_id])
else:
entity_ids = hass.states.entity_ids()
for ent_id in entity_ids:
domain = split_entity_id(ent_id)[0]
try:
component = getattr(hass.components, domain)
except ImportError:
_LOGGER.error("Failed to call %s.is_on: component not found", domain)
continue
if not hasattr(component, "is_on"):
_LOGGER.warning("Integration %s has no is_on method", domain)
continue
if component.is_on(ent_id):
return True
return False | [
"def",
"is_on",
"(",
"hass",
",",
"entity_id",
"=",
"None",
")",
":",
"if",
"entity_id",
":",
"entity_ids",
"=",
"hass",
".",
"components",
".",
"group",
".",
"expand_entity_ids",
"(",
"[",
"entity_id",
"]",
")",
"else",
":",
"entity_ids",
"=",
"hass",
".",
"states",
".",
"entity_ids",
"(",
")",
"for",
"ent_id",
"in",
"entity_ids",
":",
"domain",
"=",
"split_entity_id",
"(",
"ent_id",
")",
"[",
"0",
"]",
"try",
":",
"component",
"=",
"getattr",
"(",
"hass",
".",
"components",
",",
"domain",
")",
"except",
"ImportError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed to call %s.is_on: component not found\"",
",",
"domain",
")",
"continue",
"if",
"not",
"hasattr",
"(",
"component",
",",
"\"is_on\"",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Integration %s has no is_on method\"",
",",
"domain",
")",
"continue",
"if",
"component",
".",
"is_on",
"(",
"ent_id",
")",
":",
"return",
"True",
"return",
"False"
] | [
18,
0
] | [
45,
16
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the BMW sensors. | Set up the BMW sensors. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the BMW sensors."""
accounts = hass.data[BMW_DOMAIN]
_LOGGER.debug("Found BMW accounts: %s", ", ".join([a.name for a in accounts]))
devices = []
for account in accounts:
for vehicle in account.account.vehicles:
if vehicle.has_hv_battery:
_LOGGER.debug("BMW with a high voltage battery")
for key, value in sorted(SENSOR_TYPES_ELEC.items()):
if key in vehicle.available_attributes:
device = BMWConnectedDriveSensor(
account, vehicle, key, value[0], value[1], value[2]
)
devices.append(device)
elif vehicle.has_internal_combustion_engine:
_LOGGER.debug("BMW with an internal combustion engine")
for key, value in sorted(SENSOR_TYPES.items()):
if key in vehicle.available_attributes:
device = BMWConnectedDriveSensor(
account, vehicle, key, value[0], value[1], value[2]
)
devices.append(device)
add_entities(devices, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"accounts",
"=",
"hass",
".",
"data",
"[",
"BMW_DOMAIN",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Found BMW accounts: %s\"",
",",
"\", \"",
".",
"join",
"(",
"[",
"a",
".",
"name",
"for",
"a",
"in",
"accounts",
"]",
")",
")",
"devices",
"=",
"[",
"]",
"for",
"account",
"in",
"accounts",
":",
"for",
"vehicle",
"in",
"account",
".",
"account",
".",
"vehicles",
":",
"if",
"vehicle",
".",
"has_hv_battery",
":",
"_LOGGER",
".",
"debug",
"(",
"\"BMW with a high voltage battery\"",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"SENSOR_TYPES_ELEC",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"vehicle",
".",
"available_attributes",
":",
"device",
"=",
"BMWConnectedDriveSensor",
"(",
"account",
",",
"vehicle",
",",
"key",
",",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"1",
"]",
",",
"value",
"[",
"2",
"]",
")",
"devices",
".",
"append",
"(",
"device",
")",
"elif",
"vehicle",
".",
"has_internal_combustion_engine",
":",
"_LOGGER",
".",
"debug",
"(",
"\"BMW with an internal combustion engine\"",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"SENSOR_TYPES",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"vehicle",
".",
"available_attributes",
":",
"device",
"=",
"BMWConnectedDriveSensor",
"(",
"account",
",",
"vehicle",
",",
"key",
",",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"1",
"]",
",",
"value",
"[",
"2",
"]",
")",
"devices",
".",
"append",
"(",
"device",
")",
"add_entities",
"(",
"devices",
",",
"True",
")"
] | [
43,
0
] | [
66,
31
] | python | en | ['en', 'bg', 'en'] | True |
BMWConnectedDriveSensor.__init__ | (
self, account, vehicle, attribute: str, sensor_name, device_class, icon
) | Initialize sensor. | Initialize sensor. | def __init__(
self, account, vehicle, attribute: str, sensor_name, device_class, icon
):
"""Initialize sensor."""
self._account = account
self._vehicle = vehicle
self._attribute = attribute
self._name = f"{self._vehicle.name} {self._attribute}"
self._unique_id = f"{self._vehicle.vin}-{self._attribute}"
self._sensor_name = sensor_name
self._device_class = device_class
self._icon = icon
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"account",
",",
"vehicle",
",",
"attribute",
":",
"str",
",",
"sensor_name",
",",
"device_class",
",",
"icon",
")",
":",
"self",
".",
"_account",
"=",
"account",
"self",
".",
"_vehicle",
"=",
"vehicle",
"self",
".",
"_attribute",
"=",
"attribute",
"self",
".",
"_name",
"=",
"f\"{self._vehicle.name} {self._attribute}\"",
"self",
".",
"_unique_id",
"=",
"f\"{self._vehicle.vin}-{self._attribute}\"",
"self",
".",
"_sensor_name",
"=",
"sensor_name",
"self",
".",
"_device_class",
"=",
"device_class",
"self",
".",
"_icon",
"=",
"icon",
"self",
".",
"_state",
"=",
"None"
] | [
72,
4
] | [
84,
26
] | python | en | ['en', 'ro', 'it'] | False |
BMWConnectedDriveSensor.should_poll | (self) | Return False.
Data update is triggered from BMWConnectedDriveEntity.
| Return False. | def should_poll(self) -> bool:
"""Return False.
Data update is triggered from BMWConnectedDriveEntity.
"""
return False | [
"def",
"should_poll",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
87,
4
] | [
92,
20
] | python | en | ['en', 'ms', 'en'] | False |
BMWConnectedDriveSensor.unique_id | (self) | Return the unique ID of the binary sensor. | Return the unique ID of the binary sensor. | def unique_id(self):
"""Return the unique ID of the binary sensor."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
95,
4
] | [
97,
30
] | python | en | ['en', 'it', 'en'] | True |
BMWConnectedDriveSensor.name | (self) | Return the name of the binary sensor. | Return the name of the binary sensor. | def name(self):
"""Return the name of the binary sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
100,
4
] | [
102,
25
] | python | en | ['en', 'mi', 'en'] | True |
BMWConnectedDriveSensor.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
105,
4
] | [
107,
25
] | python | en | ['en', 'en', 'en'] | True |
BMWConnectedDriveSensor.device_class | (self) | Return the class of the binary sensor. | Return the class of the binary sensor. | def device_class(self):
"""Return the class of the binary sensor."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
110,
4
] | [
112,
33
] | python | en | ['en', 'tg', 'en'] | True |
BMWConnectedDriveSensor.is_on | (self) | Return the state of the binary sensor. | Return the state of the binary sensor. | def is_on(self):
"""Return the state of the binary sensor."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
115,
4
] | [
117,
26
] | python | en | ['en', 'ig', 'en'] | True |
BMWConnectedDriveSensor.device_state_attributes | (self) | Return the state attributes of the binary sensor. | Return the state attributes of the binary sensor. | def device_state_attributes(self):
"""Return the state attributes of the binary sensor."""
vehicle_state = self._vehicle.state
result = {
"car": self._vehicle.name,
ATTR_ATTRIBUTION: ATTRIBUTION,
}
if self._attribute == "lids":
for lid in vehicle_state.lids:
result[lid.name] = lid.state.value
elif self._attribute == "windows":
for window in vehicle_state.windows:
result[window.name] = window.state.value
elif self._attribute == "door_lock_state":
result["door_lock_state"] = vehicle_state.door_lock_state.value
result["last_update_reason"] = vehicle_state.last_update_reason
elif self._attribute == "lights_parking":
result["lights_parking"] = vehicle_state.parking_lights.value
elif self._attribute == "condition_based_services":
for report in vehicle_state.condition_based_services:
result.update(self._format_cbs_report(report))
elif self._attribute == "check_control_messages":
check_control_messages = vehicle_state.check_control_messages
has_check_control_messages = vehicle_state.has_check_control_messages
if has_check_control_messages:
cbs_list = []
for message in check_control_messages:
cbs_list.append(message["ccmDescriptionShort"])
result["check_control_messages"] = cbs_list
else:
result["check_control_messages"] = "OK"
elif self._attribute == "charging_status":
result["charging_status"] = vehicle_state.charging_status.value
result["last_charging_end_result"] = vehicle_state.last_charging_end_result
elif self._attribute == "connection_status":
result["connection_status"] = vehicle_state.connection_status
return sorted(result.items()) | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"vehicle_state",
"=",
"self",
".",
"_vehicle",
".",
"state",
"result",
"=",
"{",
"\"car\"",
":",
"self",
".",
"_vehicle",
".",
"name",
",",
"ATTR_ATTRIBUTION",
":",
"ATTRIBUTION",
",",
"}",
"if",
"self",
".",
"_attribute",
"==",
"\"lids\"",
":",
"for",
"lid",
"in",
"vehicle_state",
".",
"lids",
":",
"result",
"[",
"lid",
".",
"name",
"]",
"=",
"lid",
".",
"state",
".",
"value",
"elif",
"self",
".",
"_attribute",
"==",
"\"windows\"",
":",
"for",
"window",
"in",
"vehicle_state",
".",
"windows",
":",
"result",
"[",
"window",
".",
"name",
"]",
"=",
"window",
".",
"state",
".",
"value",
"elif",
"self",
".",
"_attribute",
"==",
"\"door_lock_state\"",
":",
"result",
"[",
"\"door_lock_state\"",
"]",
"=",
"vehicle_state",
".",
"door_lock_state",
".",
"value",
"result",
"[",
"\"last_update_reason\"",
"]",
"=",
"vehicle_state",
".",
"last_update_reason",
"elif",
"self",
".",
"_attribute",
"==",
"\"lights_parking\"",
":",
"result",
"[",
"\"lights_parking\"",
"]",
"=",
"vehicle_state",
".",
"parking_lights",
".",
"value",
"elif",
"self",
".",
"_attribute",
"==",
"\"condition_based_services\"",
":",
"for",
"report",
"in",
"vehicle_state",
".",
"condition_based_services",
":",
"result",
".",
"update",
"(",
"self",
".",
"_format_cbs_report",
"(",
"report",
")",
")",
"elif",
"self",
".",
"_attribute",
"==",
"\"check_control_messages\"",
":",
"check_control_messages",
"=",
"vehicle_state",
".",
"check_control_messages",
"has_check_control_messages",
"=",
"vehicle_state",
".",
"has_check_control_messages",
"if",
"has_check_control_messages",
":",
"cbs_list",
"=",
"[",
"]",
"for",
"message",
"in",
"check_control_messages",
":",
"cbs_list",
".",
"append",
"(",
"message",
"[",
"\"ccmDescriptionShort\"",
"]",
")",
"result",
"[",
"\"check_control_messages\"",
"]",
"=",
"cbs_list",
"else",
":",
"result",
"[",
"\"check_control_messages\"",
"]",
"=",
"\"OK\"",
"elif",
"self",
".",
"_attribute",
"==",
"\"charging_status\"",
":",
"result",
"[",
"\"charging_status\"",
"]",
"=",
"vehicle_state",
".",
"charging_status",
".",
"value",
"result",
"[",
"\"last_charging_end_result\"",
"]",
"=",
"vehicle_state",
".",
"last_charging_end_result",
"elif",
"self",
".",
"_attribute",
"==",
"\"connection_status\"",
":",
"result",
"[",
"\"connection_status\"",
"]",
"=",
"vehicle_state",
".",
"connection_status",
"return",
"sorted",
"(",
"result",
".",
"items",
"(",
")",
")"
] | [
120,
4
] | [
158,
37
] | python | en | ['en', 'en', 'en'] | True |
BMWConnectedDriveSensor.update | (self) | Read new state data from the library. | Read new state data from the library. | def update(self):
"""Read new state data from the library."""
vehicle_state = self._vehicle.state
# device class opening: On means open, Off means closed
if self._attribute == "lids":
_LOGGER.debug("Status of lid: %s", vehicle_state.all_lids_closed)
self._state = not vehicle_state.all_lids_closed
if self._attribute == "windows":
self._state = not vehicle_state.all_windows_closed
# device class lock: On means unlocked, Off means locked
if self._attribute == "door_lock_state":
# Possible values: LOCKED, SECURED, SELECTIVE_LOCKED, UNLOCKED
self._state = vehicle_state.door_lock_state not in [
LockState.LOCKED,
LockState.SECURED,
]
# device class light: On means light detected, Off means no light
if self._attribute == "lights_parking":
self._state = vehicle_state.are_parking_lights_on
# device class problem: On means problem detected, Off means no problem
if self._attribute == "condition_based_services":
self._state = not vehicle_state.are_all_cbs_ok
if self._attribute == "check_control_messages":
self._state = vehicle_state.has_check_control_messages
# device class power: On means power detected, Off means no power
if self._attribute == "charging_status":
self._state = vehicle_state.charging_status in [ChargingState.CHARGING]
# device class plug: On means device is plugged in,
# Off means device is unplugged
if self._attribute == "connection_status":
self._state = vehicle_state.connection_status == "CONNECTED" | [
"def",
"update",
"(",
"self",
")",
":",
"vehicle_state",
"=",
"self",
".",
"_vehicle",
".",
"state",
"# device class opening: On means open, Off means closed",
"if",
"self",
".",
"_attribute",
"==",
"\"lids\"",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Status of lid: %s\"",
",",
"vehicle_state",
".",
"all_lids_closed",
")",
"self",
".",
"_state",
"=",
"not",
"vehicle_state",
".",
"all_lids_closed",
"if",
"self",
".",
"_attribute",
"==",
"\"windows\"",
":",
"self",
".",
"_state",
"=",
"not",
"vehicle_state",
".",
"all_windows_closed",
"# device class lock: On means unlocked, Off means locked",
"if",
"self",
".",
"_attribute",
"==",
"\"door_lock_state\"",
":",
"# Possible values: LOCKED, SECURED, SELECTIVE_LOCKED, UNLOCKED",
"self",
".",
"_state",
"=",
"vehicle_state",
".",
"door_lock_state",
"not",
"in",
"[",
"LockState",
".",
"LOCKED",
",",
"LockState",
".",
"SECURED",
",",
"]",
"# device class light: On means light detected, Off means no light",
"if",
"self",
".",
"_attribute",
"==",
"\"lights_parking\"",
":",
"self",
".",
"_state",
"=",
"vehicle_state",
".",
"are_parking_lights_on",
"# device class problem: On means problem detected, Off means no problem",
"if",
"self",
".",
"_attribute",
"==",
"\"condition_based_services\"",
":",
"self",
".",
"_state",
"=",
"not",
"vehicle_state",
".",
"are_all_cbs_ok",
"if",
"self",
".",
"_attribute",
"==",
"\"check_control_messages\"",
":",
"self",
".",
"_state",
"=",
"vehicle_state",
".",
"has_check_control_messages",
"# device class power: On means power detected, Off means no power",
"if",
"self",
".",
"_attribute",
"==",
"\"charging_status\"",
":",
"self",
".",
"_state",
"=",
"vehicle_state",
".",
"charging_status",
"in",
"[",
"ChargingState",
".",
"CHARGING",
"]",
"# device class plug: On means device is plugged in,",
"# Off means device is unplugged",
"if",
"self",
".",
"_attribute",
"==",
"\"connection_status\"",
":",
"self",
".",
"_state",
"=",
"vehicle_state",
".",
"connection_status",
"==",
"\"CONNECTED\""
] | [
160,
4
] | [
191,
72
] | python | en | ['en', 'en', 'en'] | True |
BMWConnectedDriveSensor.update_callback | (self) | Schedule a state update. | Schedule a state update. | def update_callback(self):
"""Schedule a state update."""
self.schedule_update_ha_state(True) | [
"def",
"update_callback",
"(",
"self",
")",
":",
"self",
".",
"schedule_update_ha_state",
"(",
"True",
")"
] | [
208,
4
] | [
210,
43
] | python | en | ['en', 'co', 'en'] | True |
BMWConnectedDriveSensor.async_added_to_hass | (self) | Add callback after being added to hass.
Show latest data after startup.
| Add callback after being added to hass. | async def async_added_to_hass(self):
"""Add callback after being added to hass.
Show latest data after startup.
"""
self._account.add_update_listener(self.update_callback) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_account",
".",
"add_update_listener",
"(",
"self",
".",
"update_callback",
")"
] | [
212,
4
] | [
217,
63
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Push Camera platform. | Set up the Push Camera platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Push Camera platform."""
if PUSH_CAMERA_DATA not in hass.data:
hass.data[PUSH_CAMERA_DATA] = {}
webhook_id = config.get(CONF_WEBHOOK_ID)
cameras = [
PushCamera(
hass,
config[CONF_NAME],
config[CONF_BUFFER_SIZE],
config[CONF_TIMEOUT],
config[CONF_IMAGE_FIELD],
webhook_id,
)
]
async_add_entities(cameras) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"PUSH_CAMERA_DATA",
"not",
"in",
"hass",
".",
"data",
":",
"hass",
".",
"data",
"[",
"PUSH_CAMERA_DATA",
"]",
"=",
"{",
"}",
"webhook_id",
"=",
"config",
".",
"get",
"(",
"CONF_WEBHOOK_ID",
")",
"cameras",
"=",
"[",
"PushCamera",
"(",
"hass",
",",
"config",
"[",
"CONF_NAME",
"]",
",",
"config",
"[",
"CONF_BUFFER_SIZE",
"]",
",",
"config",
"[",
"CONF_TIMEOUT",
"]",
",",
"config",
"[",
"CONF_IMAGE_FIELD",
"]",
",",
"webhook_id",
",",
")",
"]",
"async_add_entities",
"(",
"cameras",
")"
] | [
48,
0
] | [
66,
31
] | python | en | ['en', 'su', 'en'] | True |
handle_webhook | (hass, webhook_id, request) | Handle incoming webhook POST with image files. | Handle incoming webhook POST with image files. | async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook POST with image files."""
try:
with async_timeout.timeout(5):
data = dict(await request.post())
except (asyncio.TimeoutError, aiohttp.web.HTTPException) as error:
_LOGGER.error("Could not get information from POST <%s>", error)
return
camera = hass.data[PUSH_CAMERA_DATA][webhook_id]
if camera.image_field not in data:
_LOGGER.warning("Webhook call without POST parameter <%s>", camera.image_field)
return
await camera.update_image(
data[camera.image_field].file.read(), data[camera.image_field].filename
) | [
"async",
"def",
"handle_webhook",
"(",
"hass",
",",
"webhook_id",
",",
"request",
")",
":",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"5",
")",
":",
"data",
"=",
"dict",
"(",
"await",
"request",
".",
"post",
"(",
")",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"web",
".",
"HTTPException",
")",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not get information from POST <%s>\"",
",",
"error",
")",
"return",
"camera",
"=",
"hass",
".",
"data",
"[",
"PUSH_CAMERA_DATA",
"]",
"[",
"webhook_id",
"]",
"if",
"camera",
".",
"image_field",
"not",
"in",
"data",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Webhook call without POST parameter <%s>\"",
",",
"camera",
".",
"image_field",
")",
"return",
"await",
"camera",
".",
"update_image",
"(",
"data",
"[",
"camera",
".",
"image_field",
"]",
".",
"file",
".",
"read",
"(",
")",
",",
"data",
"[",
"camera",
".",
"image_field",
"]",
".",
"filename",
")"
] | [
69,
0
] | [
86,
5
] | python | en | ['en', 'en', 'en'] | True |
PushCamera.__init__ | (self, hass, name, buffer_size, timeout, image_field, webhook_id) | Initialize push camera component. | Initialize push camera component. | def __init__(self, hass, name, buffer_size, timeout, image_field, webhook_id):
"""Initialize push camera component."""
super().__init__()
self._name = name
self._last_trip = None
self._filename = None
self._expired_listener = None
self._state = STATE_IDLE
self._timeout = timeout
self.queue = deque([], buffer_size)
self._current_image = None
self._image_field = image_field
self.webhook_id = webhook_id
self.webhook_url = hass.components.webhook.async_generate_url(webhook_id) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
",",
"buffer_size",
",",
"timeout",
",",
"image_field",
",",
"webhook_id",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_last_trip",
"=",
"None",
"self",
".",
"_filename",
"=",
"None",
"self",
".",
"_expired_listener",
"=",
"None",
"self",
".",
"_state",
"=",
"STATE_IDLE",
"self",
".",
"_timeout",
"=",
"timeout",
"self",
".",
"queue",
"=",
"deque",
"(",
"[",
"]",
",",
"buffer_size",
")",
"self",
".",
"_current_image",
"=",
"None",
"self",
".",
"_image_field",
"=",
"image_field",
"self",
".",
"webhook_id",
"=",
"webhook_id",
"self",
".",
"webhook_url",
"=",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_url",
"(",
"webhook_id",
")"
] | [
92,
4
] | [
105,
81
] | python | en | ['es', 'en', 'en'] | True |
PushCamera.async_added_to_hass | (self) | Call when entity is added to hass. | Call when entity is added to hass. | async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[PUSH_CAMERA_DATA][self.webhook_id] = self
try:
self.hass.components.webhook.async_register(
DOMAIN, self.name, self.webhook_id, handle_webhook
)
except ValueError:
_LOGGER.error(
"In <%s>, webhook_id <%s> already used", self.name, self.webhook_id
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"hass",
".",
"data",
"[",
"PUSH_CAMERA_DATA",
"]",
"[",
"self",
".",
"webhook_id",
"]",
"=",
"self",
"try",
":",
"self",
".",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"DOMAIN",
",",
"self",
".",
"name",
",",
"self",
".",
"webhook_id",
",",
"handle_webhook",
")",
"except",
"ValueError",
":",
"_LOGGER",
".",
"error",
"(",
"\"In <%s>, webhook_id <%s> already used\"",
",",
"self",
".",
"name",
",",
"self",
".",
"webhook_id",
")"
] | [
107,
4
] | [
118,
13
] | python | en | ['en', 'en', 'en'] | True |
PushCamera.image_field | (self) | HTTP field containing the image file. | HTTP field containing the image file. | def image_field(self):
"""HTTP field containing the image file."""
return self._image_field | [
"def",
"image_field",
"(",
"self",
")",
":",
"return",
"self",
".",
"_image_field"
] | [
121,
4
] | [
123,
32
] | python | en | ['en', 'en', 'en'] | True |
PushCamera.state | (self) | Return current state of the camera. | Return current state of the camera. | def state(self):
"""Return current state of the camera."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
126,
4
] | [
128,
26
] | python | en | ['en', 'en', 'en'] | True |
PushCamera.update_image | (self, image, filename) | Update the camera image. | Update the camera image. | async def update_image(self, image, filename):
"""Update the camera image."""
if self._state == STATE_IDLE:
self._state = STATE_RECORDING
self._last_trip = dt_util.utcnow()
self.queue.clear()
self._filename = filename
self.queue.appendleft(image)
@callback
def reset_state(now):
"""Set state to idle after no new images for a period of time."""
self._state = STATE_IDLE
self._expired_listener = None
_LOGGER.debug("Reset state")
self.async_write_ha_state()
if self._expired_listener:
self._expired_listener()
self._expired_listener = async_track_point_in_utc_time(
self.hass, reset_state, dt_util.utcnow() + self._timeout
)
self.async_write_ha_state() | [
"async",
"def",
"update_image",
"(",
"self",
",",
"image",
",",
"filename",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_IDLE",
":",
"self",
".",
"_state",
"=",
"STATE_RECORDING",
"self",
".",
"_last_trip",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"self",
".",
"queue",
".",
"clear",
"(",
")",
"self",
".",
"_filename",
"=",
"filename",
"self",
".",
"queue",
".",
"appendleft",
"(",
"image",
")",
"@",
"callback",
"def",
"reset_state",
"(",
"now",
")",
":",
"\"\"\"Set state to idle after no new images for a period of time.\"\"\"",
"self",
".",
"_state",
"=",
"STATE_IDLE",
"self",
".",
"_expired_listener",
"=",
"None",
"_LOGGER",
".",
"debug",
"(",
"\"Reset state\"",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"if",
"self",
".",
"_expired_listener",
":",
"self",
".",
"_expired_listener",
"(",
")",
"self",
".",
"_expired_listener",
"=",
"async_track_point_in_utc_time",
"(",
"self",
".",
"hass",
",",
"reset_state",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"self",
".",
"_timeout",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
130,
4
] | [
155,
35
] | python | en | ['en', 'en', 'en'] | True |
PushCamera.async_camera_image | (self) | Return a still image response. | Return a still image response. | async def async_camera_image(self):
"""Return a still image response."""
if self.queue:
if self._state == STATE_IDLE:
self.queue.rotate(1)
self._current_image = self.queue[0]
return self._current_image | [
"async",
"def",
"async_camera_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"queue",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_IDLE",
":",
"self",
".",
"queue",
".",
"rotate",
"(",
"1",
")",
"self",
".",
"_current_image",
"=",
"self",
".",
"queue",
"[",
"0",
"]",
"return",
"self",
".",
"_current_image"
] | [
157,
4
] | [
164,
34
] | python | en | ['en', 'sv', 'en'] | True |
PushCamera.name | (self) | Return the name of this camera. | Return the name of this camera. | def name(self):
"""Return the name of this camera."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
167,
4
] | [
169,
25
] | python | en | ['en', 'en', 'en'] | True |
PushCamera.motion_detection_enabled | (self) | Camera Motion Detection Status. | Camera Motion Detection Status. | def motion_detection_enabled(self):
"""Camera Motion Detection Status."""
return False | [
"def",
"motion_detection_enabled",
"(",
"self",
")",
":",
"return",
"False"
] | [
172,
4
] | [
174,
20
] | python | en | ['sv', 'ja', 'en'] | False |
PushCamera.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {
name: value
for name, value in (
(ATTR_LAST_TRIP, self._last_trip),
(ATTR_FILENAME, self._filename),
)
if value is not None
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"value",
"for",
"name",
",",
"value",
"in",
"(",
"(",
"ATTR_LAST_TRIP",
",",
"self",
".",
"_last_trip",
")",
",",
"(",
"ATTR_FILENAME",
",",
"self",
".",
"_filename",
")",
",",
")",
"if",
"value",
"is",
"not",
"None",
"}"
] | [
177,
4
] | [
186,
9
] | python | en | ['en', 'en', 'en'] | True |
FeatureSelector.fit | (self, X, y, **kwargs) |
Fit the training data to FeatureSelector
Paramters
---------
X : array-like numpy matrix
The training input samples, which shape is [n_samples, n_features].
y: array-like numpy matrix
The target values (class labels in classification, real numbers in
regression). Which shape is [n_samples].
|
Fit the training data to FeatureSelector | def fit(self, X, y, **kwargs):
"""
Fit the training data to FeatureSelector
Paramters
---------
X : array-like numpy matrix
The training input samples, which shape is [n_samples, n_features].
y: array-like numpy matrix
The target values (class labels in classification, real numbers in
regression). Which shape is [n_samples].
"""
self.X = X
self.y = y | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"X",
"=",
"X",
"self",
".",
"y",
"=",
"y"
] | [
33,
4
] | [
46,
18
] | python | en | ['en', 'error', 'th'] | False |
FeatureSelector.get_selected_features | (self) |
Fit the training data to FeatureSelector
Returns
-------
list :
Return the index of imprtant feature.
|
Fit the training data to FeatureSelector | def get_selected_features(self):
"""
Fit the training data to FeatureSelector
Returns
-------
list :
Return the index of imprtant feature.
"""
return self.selected_features_ | [
"def",
"get_selected_features",
"(",
"self",
")",
":",
"return",
"self",
".",
"selected_features_"
] | [
49,
4
] | [
58,
38
] | python | en | ['en', 'error', 'th'] | False |
async_setup | (hass: HomeAssistant, config: dict) | Set up the Tag component. | Set up the Tag component. | async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Tag component."""
hass.data[DOMAIN] = {}
id_manager = TagIDManager()
hass.data[DOMAIN][TAGS] = storage_collection = TagStorageCollection(
Store(hass, STORAGE_VERSION, STORAGE_KEY),
logging.getLogger(f"{__name__}.storage_collection"),
id_manager,
)
await storage_collection.async_load()
collection.StorageCollectionWebsocket(
storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS
).async_setup(hass)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"id_manager",
"=",
"TagIDManager",
"(",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"TAGS",
"]",
"=",
"storage_collection",
"=",
"TagStorageCollection",
"(",
"Store",
"(",
"hass",
",",
"STORAGE_VERSION",
",",
"STORAGE_KEY",
")",
",",
"logging",
".",
"getLogger",
"(",
"f\"{__name__}.storage_collection\"",
")",
",",
"id_manager",
",",
")",
"await",
"storage_collection",
".",
"async_load",
"(",
")",
"collection",
".",
"StorageCollectionWebsocket",
"(",
"storage_collection",
",",
"DOMAIN",
",",
"DOMAIN",
",",
"CREATE_FIELDS",
",",
"UPDATE_FIELDS",
")",
".",
"async_setup",
"(",
"hass",
")",
"return",
"True"
] | [
89,
0
] | [
103,
15
] | python | en | ['en', 'en', 'en'] | True |
async_scan_tag | (hass, tag_id, device_id, context=None) | Handle when a tag is scanned. | Handle when a tag is scanned. | async def async_scan_tag(hass, tag_id, device_id, context=None):
"""Handle when a tag is scanned."""
if DOMAIN not in hass.config.components:
raise HomeAssistantError("tag component has not been set up.")
hass.bus.async_fire(
EVENT_TAG_SCANNED, {TAG_ID: tag_id, DEVICE_ID: device_id}, context=context
)
helper = hass.data[DOMAIN][TAGS]
if tag_id in helper.data:
await helper.async_update_item(tag_id, {LAST_SCANNED: dt_util.utcnow()})
else:
await helper.async_create_item({TAG_ID: tag_id, LAST_SCANNED: dt_util.utcnow()})
_LOGGER.debug("Tag: %s scanned by device: %s", tag_id, device_id) | [
"async",
"def",
"async_scan_tag",
"(",
"hass",
",",
"tag_id",
",",
"device_id",
",",
"context",
"=",
"None",
")",
":",
"if",
"DOMAIN",
"not",
"in",
"hass",
".",
"config",
".",
"components",
":",
"raise",
"HomeAssistantError",
"(",
"\"tag component has not been set up.\"",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_TAG_SCANNED",
",",
"{",
"TAG_ID",
":",
"tag_id",
",",
"DEVICE_ID",
":",
"device_id",
"}",
",",
"context",
"=",
"context",
")",
"helper",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"TAGS",
"]",
"if",
"tag_id",
"in",
"helper",
".",
"data",
":",
"await",
"helper",
".",
"async_update_item",
"(",
"tag_id",
",",
"{",
"LAST_SCANNED",
":",
"dt_util",
".",
"utcnow",
"(",
")",
"}",
")",
"else",
":",
"await",
"helper",
".",
"async_create_item",
"(",
"{",
"TAG_ID",
":",
"tag_id",
",",
"LAST_SCANNED",
":",
"dt_util",
".",
"utcnow",
"(",
")",
"}",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Tag: %s scanned by device: %s\"",
",",
"tag_id",
",",
"device_id",
")"
] | [
107,
0
] | [
120,
69
] | python | en | ['en', 'en', 'en'] | True |
TagIDExistsError.__init__ | (self, item_id: str) | Initialize tag id exists error. | Initialize tag id exists error. | def __init__(self, item_id: str):
"""Initialize tag id exists error."""
super().__init__(f"Tag with id: {item_id} already exists.")
self.item_id = item_id | [
"def",
"__init__",
"(",
"self",
",",
"item_id",
":",
"str",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"f\"Tag with id: {item_id} already exists.\"",
")",
"self",
".",
"item_id",
"=",
"item_id"
] | [
42,
4
] | [
45,
30
] | python | da | ['da', 'en', 'it'] | False |
TagIDManager.generate_id | (self, suggestion: str) | Generate an ID. | Generate an ID. | def generate_id(self, suggestion: str) -> str:
"""Generate an ID."""
if self.has_id(suggestion):
raise TagIDExistsError(suggestion)
return suggestion | [
"def",
"generate_id",
"(",
"self",
",",
"suggestion",
":",
"str",
")",
"->",
"str",
":",
"if",
"self",
".",
"has_id",
"(",
"suggestion",
")",
":",
"raise",
"TagIDExistsError",
"(",
"suggestion",
")",
"return",
"suggestion"
] | [
51,
4
] | [
56,
25
] | python | en | ['en', 'yo', 'it'] | False |
TagStorageCollection._process_create_data | (self, data: typing.Dict) | Validate the config is valid. | Validate the config is valid. | async def _process_create_data(self, data: typing.Dict) -> typing.Dict:
"""Validate the config is valid."""
data = self.CREATE_SCHEMA(data)
if not data[TAG_ID]:
data[TAG_ID] = str(uuid.uuid4())
# make last_scanned JSON serializeable
if LAST_SCANNED in data:
data[LAST_SCANNED] = data[LAST_SCANNED].isoformat()
return data | [
"async",
"def",
"_process_create_data",
"(",
"self",
",",
"data",
":",
"typing",
".",
"Dict",
")",
"->",
"typing",
".",
"Dict",
":",
"data",
"=",
"self",
".",
"CREATE_SCHEMA",
"(",
"data",
")",
"if",
"not",
"data",
"[",
"TAG_ID",
"]",
":",
"data",
"[",
"TAG_ID",
"]",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# make last_scanned JSON serializeable",
"if",
"LAST_SCANNED",
"in",
"data",
":",
"data",
"[",
"LAST_SCANNED",
"]",
"=",
"data",
"[",
"LAST_SCANNED",
"]",
".",
"isoformat",
"(",
")",
"return",
"data"
] | [
65,
4
] | [
73,
19
] | python | en | ['en', 'en', 'en'] | True |
TagStorageCollection._get_suggested_id | (self, info: typing.Dict) | Suggest an ID based on the config. | Suggest an ID based on the config. | def _get_suggested_id(self, info: typing.Dict) -> str:
"""Suggest an ID based on the config."""
return info[TAG_ID] | [
"def",
"_get_suggested_id",
"(",
"self",
",",
"info",
":",
"typing",
".",
"Dict",
")",
"->",
"str",
":",
"return",
"info",
"[",
"TAG_ID",
"]"
] | [
76,
4
] | [
78,
27
] | python | en | ['en', 'en', 'en'] | True |
TagStorageCollection._update_data | (self, data: dict, update_data: typing.Dict) | Return a new updated data object. | Return a new updated data object. | async def _update_data(self, data: dict, update_data: typing.Dict) -> typing.Dict:
"""Return a new updated data object."""
data = {**data, **self.UPDATE_SCHEMA(update_data)}
# make last_scanned JSON serializeable
if LAST_SCANNED in update_data:
data[LAST_SCANNED] = data[LAST_SCANNED].isoformat()
return data | [
"async",
"def",
"_update_data",
"(",
"self",
",",
"data",
":",
"dict",
",",
"update_data",
":",
"typing",
".",
"Dict",
")",
"->",
"typing",
".",
"Dict",
":",
"data",
"=",
"{",
"*",
"*",
"data",
",",
"*",
"*",
"self",
".",
"UPDATE_SCHEMA",
"(",
"update_data",
")",
"}",
"# make last_scanned JSON serializeable",
"if",
"LAST_SCANNED",
"in",
"update_data",
":",
"data",
"[",
"LAST_SCANNED",
"]",
"=",
"data",
"[",
"LAST_SCANNED",
"]",
".",
"isoformat",
"(",
")",
"return",
"data"
] | [
80,
4
] | [
86,
19
] | python | en | ['en', 'en', 'en'] | True |
ecobee_fixture | () | Set up ecobee mock. | Set up ecobee mock. | def ecobee_fixture():
"""Set up ecobee mock."""
vals = {
"name": "Ecobee",
"program": {
"climates": [
{"name": "Climate1", "climateRef": "c1"},
{"name": "Climate2", "climateRef": "c2"},
],
"currentClimateRef": "c1",
},
"runtime": {
"actualTemperature": 300,
"actualHumidity": 15,
"desiredHeat": 400,
"desiredCool": 200,
"desiredFanMode": "on",
},
"settings": {
"hvacMode": "auto",
"heatStages": 1,
"coolStages": 1,
"fanMinOnTime": 10,
"heatCoolMinDelta": 50,
"holdAction": "nextTransition",
},
"equipmentStatus": "fan",
"events": [
{
"name": "Event1",
"running": True,
"type": "hold",
"holdClimateRef": "away",
"endDate": "2017-01-01 10:00:00",
"startDate": "2017-02-02 11:00:00",
}
],
}
mock_ecobee = mock.Mock()
mock_ecobee.__getitem__ = mock.Mock(side_effect=vals.__getitem__)
mock_ecobee.__setitem__ = mock.Mock(side_effect=vals.__setitem__)
return mock_ecobee | [
"def",
"ecobee_fixture",
"(",
")",
":",
"vals",
"=",
"{",
"\"name\"",
":",
"\"Ecobee\"",
",",
"\"program\"",
":",
"{",
"\"climates\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Climate1\"",
",",
"\"climateRef\"",
":",
"\"c1\"",
"}",
",",
"{",
"\"name\"",
":",
"\"Climate2\"",
",",
"\"climateRef\"",
":",
"\"c2\"",
"}",
",",
"]",
",",
"\"currentClimateRef\"",
":",
"\"c1\"",
",",
"}",
",",
"\"runtime\"",
":",
"{",
"\"actualTemperature\"",
":",
"300",
",",
"\"actualHumidity\"",
":",
"15",
",",
"\"desiredHeat\"",
":",
"400",
",",
"\"desiredCool\"",
":",
"200",
",",
"\"desiredFanMode\"",
":",
"\"on\"",
",",
"}",
",",
"\"settings\"",
":",
"{",
"\"hvacMode\"",
":",
"\"auto\"",
",",
"\"heatStages\"",
":",
"1",
",",
"\"coolStages\"",
":",
"1",
",",
"\"fanMinOnTime\"",
":",
"10",
",",
"\"heatCoolMinDelta\"",
":",
"50",
",",
"\"holdAction\"",
":",
"\"nextTransition\"",
",",
"}",
",",
"\"equipmentStatus\"",
":",
"\"fan\"",
",",
"\"events\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Event1\"",
",",
"\"running\"",
":",
"True",
",",
"\"type\"",
":",
"\"hold\"",
",",
"\"holdClimateRef\"",
":",
"\"away\"",
",",
"\"endDate\"",
":",
"\"2017-01-01 10:00:00\"",
",",
"\"startDate\"",
":",
"\"2017-02-02 11:00:00\"",
",",
"}",
"]",
",",
"}",
"mock_ecobee",
"=",
"mock",
".",
"Mock",
"(",
")",
"mock_ecobee",
".",
"__getitem__",
"=",
"mock",
".",
"Mock",
"(",
"side_effect",
"=",
"vals",
".",
"__getitem__",
")",
"mock_ecobee",
".",
"__setitem__",
"=",
"mock",
".",
"Mock",
"(",
"side_effect",
"=",
"vals",
".",
"__setitem__",
")",
"return",
"mock_ecobee"
] | [
11,
0
] | [
52,
22
] | python | en | ['en', 'nl', 'en'] | True |
data_fixture | (ecobee_fixture) | Set up data mock. | Set up data mock. | def data_fixture(ecobee_fixture):
"""Set up data mock."""
data = mock.Mock()
data.ecobee.get_thermostat.return_value = ecobee_fixture
return data | [
"def",
"data_fixture",
"(",
"ecobee_fixture",
")",
":",
"data",
"=",
"mock",
".",
"Mock",
"(",
")",
"data",
".",
"ecobee",
".",
"get_thermostat",
".",
"return_value",
"=",
"ecobee_fixture",
"return",
"data"
] | [
56,
0
] | [
60,
15
] | python | en | ['en', 'da', 'en'] | True |
thermostat_fixture | (data) | Set up ecobee thermostat object. | Set up ecobee thermostat object. | def thermostat_fixture(data):
"""Set up ecobee thermostat object."""
return ecobee.Thermostat(data, 1) | [
"def",
"thermostat_fixture",
"(",
"data",
")",
":",
"return",
"ecobee",
".",
"Thermostat",
"(",
"data",
",",
"1",
")"
] | [
64,
0
] | [
66,
37
] | python | en | ['en', 'en', 'en'] | True |
test_name | (thermostat) | Test name property. | Test name property. | async def test_name(thermostat):
"""Test name property."""
assert thermostat.name == "Ecobee" | [
"async",
"def",
"test_name",
"(",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"name",
"==",
"\"Ecobee\""
] | [
69,
0
] | [
71,
38
] | python | en | ['en', 'en', 'en'] | True |
test_current_temperature | (ecobee_fixture, thermostat) | Test current temperature. | Test current temperature. | async def test_current_temperature(ecobee_fixture, thermostat):
"""Test current temperature."""
assert thermostat.current_temperature == 30
ecobee_fixture["runtime"]["actualTemperature"] = const.HTTP_NOT_FOUND
assert thermostat.current_temperature == 40.4 | [
"async",
"def",
"test_current_temperature",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"current_temperature",
"==",
"30",
"ecobee_fixture",
"[",
"\"runtime\"",
"]",
"[",
"\"actualTemperature\"",
"]",
"=",
"const",
".",
"HTTP_NOT_FOUND",
"assert",
"thermostat",
".",
"current_temperature",
"==",
"40.4"
] | [
74,
0
] | [
78,
49
] | python | en | ['en', 'la', 'en'] | True |
test_target_temperature_low | (ecobee_fixture, thermostat) | Test target low temperature. | Test target low temperature. | async def test_target_temperature_low(ecobee_fixture, thermostat):
"""Test target low temperature."""
assert thermostat.target_temperature_low == 40
ecobee_fixture["runtime"]["desiredHeat"] = 502
assert thermostat.target_temperature_low == 50.2 | [
"async",
"def",
"test_target_temperature_low",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"target_temperature_low",
"==",
"40",
"ecobee_fixture",
"[",
"\"runtime\"",
"]",
"[",
"\"desiredHeat\"",
"]",
"=",
"502",
"assert",
"thermostat",
".",
"target_temperature_low",
"==",
"50.2"
] | [
81,
0
] | [
85,
52
] | python | en | ['en', 'la', 'en'] | True |
test_target_temperature_high | (ecobee_fixture, thermostat) | Test target high temperature. | Test target high temperature. | async def test_target_temperature_high(ecobee_fixture, thermostat):
"""Test target high temperature."""
assert thermostat.target_temperature_high == 20
ecobee_fixture["runtime"]["desiredCool"] = 103
assert thermostat.target_temperature_high == 10.3 | [
"async",
"def",
"test_target_temperature_high",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"target_temperature_high",
"==",
"20",
"ecobee_fixture",
"[",
"\"runtime\"",
"]",
"[",
"\"desiredCool\"",
"]",
"=",
"103",
"assert",
"thermostat",
".",
"target_temperature_high",
"==",
"10.3"
] | [
88,
0
] | [
92,
53
] | python | en | ['en', 'la', 'en'] | True |
test_target_temperature | (ecobee_fixture, thermostat) | Test target temperature. | Test target temperature. | async def test_target_temperature(ecobee_fixture, thermostat):
"""Test target temperature."""
assert thermostat.target_temperature is None
ecobee_fixture["settings"]["hvacMode"] = "heat"
assert thermostat.target_temperature == 40
ecobee_fixture["settings"]["hvacMode"] = "cool"
assert thermostat.target_temperature == 20
ecobee_fixture["settings"]["hvacMode"] = "auxHeatOnly"
assert thermostat.target_temperature == 40
ecobee_fixture["settings"]["hvacMode"] = "off"
assert thermostat.target_temperature is None | [
"async",
"def",
"test_target_temperature",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"target_temperature",
"is",
"None",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"heat\"",
"assert",
"thermostat",
".",
"target_temperature",
"==",
"40",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"cool\"",
"assert",
"thermostat",
".",
"target_temperature",
"==",
"20",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"auxHeatOnly\"",
"assert",
"thermostat",
".",
"target_temperature",
"==",
"40",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"off\"",
"assert",
"thermostat",
".",
"target_temperature",
"is",
"None"
] | [
95,
0
] | [
105,
48
] | python | en | ['en', 'la', 'en'] | True |
test_desired_fan_mode | (ecobee_fixture, thermostat) | Test desired fan mode property. | Test desired fan mode property. | async def test_desired_fan_mode(ecobee_fixture, thermostat):
"""Test desired fan mode property."""
assert thermostat.fan_mode == "on"
ecobee_fixture["runtime"]["desiredFanMode"] = "auto"
assert thermostat.fan_mode == "auto" | [
"async",
"def",
"test_desired_fan_mode",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"fan_mode",
"==",
"\"on\"",
"ecobee_fixture",
"[",
"\"runtime\"",
"]",
"[",
"\"desiredFanMode\"",
"]",
"=",
"\"auto\"",
"assert",
"thermostat",
".",
"fan_mode",
"==",
"\"auto\""
] | [
108,
0
] | [
112,
40
] | python | en | ['en', 'fy', 'en'] | True |
test_fan | (ecobee_fixture, thermostat) | Test fan property. | Test fan property. | async def test_fan(ecobee_fixture, thermostat):
"""Test fan property."""
assert const.STATE_ON == thermostat.fan
ecobee_fixture["equipmentStatus"] = ""
assert STATE_OFF == thermostat.fan
ecobee_fixture["equipmentStatus"] = "heatPump, heatPump2"
assert STATE_OFF == thermostat.fan | [
"async",
"def",
"test_fan",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"const",
".",
"STATE_ON",
"==",
"thermostat",
".",
"fan",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"\"",
"assert",
"STATE_OFF",
"==",
"thermostat",
".",
"fan",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"heatPump, heatPump2\"",
"assert",
"STATE_OFF",
"==",
"thermostat",
".",
"fan"
] | [
115,
0
] | [
121,
38
] | python | en | ['en', 'fy', 'en'] | True |
test_hvac_mode | (ecobee_fixture, thermostat) | Test current operation property. | Test current operation property. | async def test_hvac_mode(ecobee_fixture, thermostat):
"""Test current operation property."""
assert thermostat.hvac_mode == "heat_cool"
ecobee_fixture["settings"]["hvacMode"] = "heat"
assert thermostat.hvac_mode == "heat"
ecobee_fixture["settings"]["hvacMode"] = "cool"
assert thermostat.hvac_mode == "cool"
ecobee_fixture["settings"]["hvacMode"] = "auxHeatOnly"
assert thermostat.hvac_mode == "heat"
ecobee_fixture["settings"]["hvacMode"] = "off"
assert thermostat.hvac_mode == "off" | [
"async",
"def",
"test_hvac_mode",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"heat_cool\"",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"heat\"",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"heat\"",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"cool\"",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"cool\"",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"auxHeatOnly\"",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"heat\"",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"off\"",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"off\""
] | [
124,
0
] | [
134,
40
] | python | en | ['nl', 'en', 'en'] | True |
test_hvac_modes | (thermostat) | Test operation list property. | Test operation list property. | async def test_hvac_modes(thermostat):
"""Test operation list property."""
assert ["heat_cool", "heat", "cool", "off"] == thermostat.hvac_modes | [
"async",
"def",
"test_hvac_modes",
"(",
"thermostat",
")",
":",
"assert",
"[",
"\"heat_cool\"",
",",
"\"heat\"",
",",
"\"cool\"",
",",
"\"off\"",
"]",
"==",
"thermostat",
".",
"hvac_modes"
] | [
137,
0
] | [
139,
72
] | python | en | ['nl', 'en', 'en'] | True |
test_hvac_mode2 | (ecobee_fixture, thermostat) | Test operation mode property. | Test operation mode property. | async def test_hvac_mode2(ecobee_fixture, thermostat):
"""Test operation mode property."""
assert thermostat.hvac_mode == "heat_cool"
ecobee_fixture["settings"]["hvacMode"] = "heat"
assert thermostat.hvac_mode == "heat" | [
"async",
"def",
"test_hvac_mode2",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"heat_cool\"",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"heat\"",
"assert",
"thermostat",
".",
"hvac_mode",
"==",
"\"heat\""
] | [
142,
0
] | [
146,
41
] | python | en | ['nl', 'en', 'en'] | True |
test_device_state_attributes | (ecobee_fixture, thermostat) | Test device state attributes property. | Test device state attributes property. | async def test_device_state_attributes(ecobee_fixture, thermostat):
"""Test device state attributes property."""
ecobee_fixture["equipmentStatus"] = "heatPump2"
assert {
"fan": "off",
"climate_mode": "Climate1",
"fan_min_on_time": 10,
"equipment_running": "heatPump2",
} == thermostat.device_state_attributes
ecobee_fixture["equipmentStatus"] = "auxHeat2"
assert {
"fan": "off",
"climate_mode": "Climate1",
"fan_min_on_time": 10,
"equipment_running": "auxHeat2",
} == thermostat.device_state_attributes
ecobee_fixture["equipmentStatus"] = "compCool1"
assert {
"fan": "off",
"climate_mode": "Climate1",
"fan_min_on_time": 10,
"equipment_running": "compCool1",
} == thermostat.device_state_attributes
ecobee_fixture["equipmentStatus"] = ""
assert {
"fan": "off",
"climate_mode": "Climate1",
"fan_min_on_time": 10,
"equipment_running": "",
} == thermostat.device_state_attributes
ecobee_fixture["equipmentStatus"] = "Unknown"
assert {
"fan": "off",
"climate_mode": "Climate1",
"fan_min_on_time": 10,
"equipment_running": "Unknown",
} == thermostat.device_state_attributes
ecobee_fixture["program"]["currentClimateRef"] = "c2"
assert {
"fan": "off",
"climate_mode": "Climate2",
"fan_min_on_time": 10,
"equipment_running": "Unknown",
} == thermostat.device_state_attributes | [
"async",
"def",
"test_device_state_attributes",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"heatPump2\"",
"assert",
"{",
"\"fan\"",
":",
"\"off\"",
",",
"\"climate_mode\"",
":",
"\"Climate1\"",
",",
"\"fan_min_on_time\"",
":",
"10",
",",
"\"equipment_running\"",
":",
"\"heatPump2\"",
",",
"}",
"==",
"thermostat",
".",
"device_state_attributes",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"auxHeat2\"",
"assert",
"{",
"\"fan\"",
":",
"\"off\"",
",",
"\"climate_mode\"",
":",
"\"Climate1\"",
",",
"\"fan_min_on_time\"",
":",
"10",
",",
"\"equipment_running\"",
":",
"\"auxHeat2\"",
",",
"}",
"==",
"thermostat",
".",
"device_state_attributes",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"compCool1\"",
"assert",
"{",
"\"fan\"",
":",
"\"off\"",
",",
"\"climate_mode\"",
":",
"\"Climate1\"",
",",
"\"fan_min_on_time\"",
":",
"10",
",",
"\"equipment_running\"",
":",
"\"compCool1\"",
",",
"}",
"==",
"thermostat",
".",
"device_state_attributes",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"\"",
"assert",
"{",
"\"fan\"",
":",
"\"off\"",
",",
"\"climate_mode\"",
":",
"\"Climate1\"",
",",
"\"fan_min_on_time\"",
":",
"10",
",",
"\"equipment_running\"",
":",
"\"\"",
",",
"}",
"==",
"thermostat",
".",
"device_state_attributes",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"Unknown\"",
"assert",
"{",
"\"fan\"",
":",
"\"off\"",
",",
"\"climate_mode\"",
":",
"\"Climate1\"",
",",
"\"fan_min_on_time\"",
":",
"10",
",",
"\"equipment_running\"",
":",
"\"Unknown\"",
",",
"}",
"==",
"thermostat",
".",
"device_state_attributes",
"ecobee_fixture",
"[",
"\"program\"",
"]",
"[",
"\"currentClimateRef\"",
"]",
"=",
"\"c2\"",
"assert",
"{",
"\"fan\"",
":",
"\"off\"",
",",
"\"climate_mode\"",
":",
"\"Climate2\"",
",",
"\"fan_min_on_time\"",
":",
"10",
",",
"\"equipment_running\"",
":",
"\"Unknown\"",
",",
"}",
"==",
"thermostat",
".",
"device_state_attributes"
] | [
149,
0
] | [
195,
43
] | python | en | ['fr', 'en', 'en'] | True |
test_is_aux_heat_on | (ecobee_fixture, thermostat) | Test aux heat property. | Test aux heat property. | async def test_is_aux_heat_on(ecobee_fixture, thermostat):
"""Test aux heat property."""
assert not thermostat.is_aux_heat
ecobee_fixture["equipmentStatus"] = "fan, auxHeat"
assert thermostat.is_aux_heat | [
"async",
"def",
"test_is_aux_heat_on",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"not",
"thermostat",
".",
"is_aux_heat",
"ecobee_fixture",
"[",
"\"equipmentStatus\"",
"]",
"=",
"\"fan, auxHeat\"",
"assert",
"thermostat",
".",
"is_aux_heat"
] | [
198,
0
] | [
202,
33
] | python | fr | ['fr', 'fr', 'fr'] | True |
test_set_temperature | (ecobee_fixture, thermostat, data) | Test set temperature. | Test set temperature. | async def test_set_temperature(ecobee_fixture, thermostat, data):
"""Test set temperature."""
# Auto -> Auto
data.reset_mock()
thermostat.set_temperature(target_temp_low=20, target_temp_high=30)
data.ecobee.set_hold_temp.assert_has_calls([mock.call(1, 30, 20, "nextTransition")])
# Auto -> Hold
data.reset_mock()
thermostat.set_temperature(temperature=20)
data.ecobee.set_hold_temp.assert_has_calls([mock.call(1, 25, 15, "nextTransition")])
# Cool -> Hold
data.reset_mock()
ecobee_fixture["settings"]["hvacMode"] = "cool"
thermostat.set_temperature(temperature=20.5)
data.ecobee.set_hold_temp.assert_has_calls(
[mock.call(1, 20.5, 20.5, "nextTransition")]
)
# Heat -> Hold
data.reset_mock()
ecobee_fixture["settings"]["hvacMode"] = "heat"
thermostat.set_temperature(temperature=20)
data.ecobee.set_hold_temp.assert_has_calls([mock.call(1, 20, 20, "nextTransition")])
# Heat -> Auto
data.reset_mock()
ecobee_fixture["settings"]["hvacMode"] = "heat"
thermostat.set_temperature(target_temp_low=20, target_temp_high=30)
assert not data.ecobee.set_hold_temp.called | [
"async",
"def",
"test_set_temperature",
"(",
"ecobee_fixture",
",",
"thermostat",
",",
"data",
")",
":",
"# Auto -> Auto",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_temperature",
"(",
"target_temp_low",
"=",
"20",
",",
"target_temp_high",
"=",
"30",
")",
"data",
".",
"ecobee",
".",
"set_hold_temp",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"30",
",",
"20",
",",
"\"nextTransition\"",
")",
"]",
")",
"# Auto -> Hold",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_temperature",
"(",
"temperature",
"=",
"20",
")",
"data",
".",
"ecobee",
".",
"set_hold_temp",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"25",
",",
"15",
",",
"\"nextTransition\"",
")",
"]",
")",
"# Cool -> Hold",
"data",
".",
"reset_mock",
"(",
")",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"cool\"",
"thermostat",
".",
"set_temperature",
"(",
"temperature",
"=",
"20.5",
")",
"data",
".",
"ecobee",
".",
"set_hold_temp",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"20.5",
",",
"20.5",
",",
"\"nextTransition\"",
")",
"]",
")",
"# Heat -> Hold",
"data",
".",
"reset_mock",
"(",
")",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"heat\"",
"thermostat",
".",
"set_temperature",
"(",
"temperature",
"=",
"20",
")",
"data",
".",
"ecobee",
".",
"set_hold_temp",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"20",
",",
"20",
",",
"\"nextTransition\"",
")",
"]",
")",
"# Heat -> Auto",
"data",
".",
"reset_mock",
"(",
")",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"hvacMode\"",
"]",
"=",
"\"heat\"",
"thermostat",
".",
"set_temperature",
"(",
"target_temp_low",
"=",
"20",
",",
"target_temp_high",
"=",
"30",
")",
"assert",
"not",
"data",
".",
"ecobee",
".",
"set_hold_temp",
".",
"called"
] | [
205,
0
] | [
235,
47
] | python | en | ['en', 'la', 'en'] | True |
test_set_hvac_mode | (thermostat, data) | Test operation mode setter. | Test operation mode setter. | async def test_set_hvac_mode(thermostat, data):
"""Test operation mode setter."""
data.reset_mock()
thermostat.set_hvac_mode("heat_cool")
data.ecobee.set_hvac_mode.assert_has_calls([mock.call(1, "auto")])
data.reset_mock()
thermostat.set_hvac_mode("heat")
data.ecobee.set_hvac_mode.assert_has_calls([mock.call(1, "heat")]) | [
"async",
"def",
"test_set_hvac_mode",
"(",
"thermostat",
",",
"data",
")",
":",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_hvac_mode",
"(",
"\"heat_cool\"",
")",
"data",
".",
"ecobee",
".",
"set_hvac_mode",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"auto\"",
")",
"]",
")",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_hvac_mode",
"(",
"\"heat\"",
")",
"data",
".",
"ecobee",
".",
"set_hvac_mode",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"heat\"",
")",
"]",
")"
] | [
238,
0
] | [
245,
70
] | python | it | ['nl', 'no', 'it'] | False |
test_set_fan_min_on_time | (thermostat, data) | Test fan min on time setter. | Test fan min on time setter. | async def test_set_fan_min_on_time(thermostat, data):
"""Test fan min on time setter."""
data.reset_mock()
thermostat.set_fan_min_on_time(15)
data.ecobee.set_fan_min_on_time.assert_has_calls([mock.call(1, 15)])
data.reset_mock()
thermostat.set_fan_min_on_time(20)
data.ecobee.set_fan_min_on_time.assert_has_calls([mock.call(1, 20)]) | [
"async",
"def",
"test_set_fan_min_on_time",
"(",
"thermostat",
",",
"data",
")",
":",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_fan_min_on_time",
"(",
"15",
")",
"data",
".",
"ecobee",
".",
"set_fan_min_on_time",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"15",
")",
"]",
")",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_fan_min_on_time",
"(",
"20",
")",
"data",
".",
"ecobee",
".",
"set_fan_min_on_time",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"20",
")",
"]",
")"
] | [
248,
0
] | [
255,
72
] | python | en | ['en', 'fy', 'en'] | True |
test_resume_program | (thermostat, data) | Test resume program. | Test resume program. | async def test_resume_program(thermostat, data):
"""Test resume program."""
# False
data.reset_mock()
thermostat.resume_program(False)
data.ecobee.resume_program.assert_has_calls([mock.call(1, "false")])
data.reset_mock()
thermostat.resume_program(None)
data.ecobee.resume_program.assert_has_calls([mock.call(1, "false")])
data.reset_mock()
thermostat.resume_program(0)
data.ecobee.resume_program.assert_has_calls([mock.call(1, "false")])
# True
data.reset_mock()
thermostat.resume_program(True)
data.ecobee.resume_program.assert_has_calls([mock.call(1, "true")])
data.reset_mock()
thermostat.resume_program(1)
data.ecobee.resume_program.assert_has_calls([mock.call(1, "true")]) | [
"async",
"def",
"test_resume_program",
"(",
"thermostat",
",",
"data",
")",
":",
"# False",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"resume_program",
"(",
"False",
")",
"data",
".",
"ecobee",
".",
"resume_program",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"false\"",
")",
"]",
")",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"resume_program",
"(",
"None",
")",
"data",
".",
"ecobee",
".",
"resume_program",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"false\"",
")",
"]",
")",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"resume_program",
"(",
"0",
")",
"data",
".",
"ecobee",
".",
"resume_program",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"false\"",
")",
"]",
")",
"# True",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"resume_program",
"(",
"True",
")",
"data",
".",
"ecobee",
".",
"resume_program",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"true\"",
")",
"]",
")",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"resume_program",
"(",
"1",
")",
"data",
".",
"ecobee",
".",
"resume_program",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"true\"",
")",
"]",
")"
] | [
258,
0
] | [
277,
71
] | python | en | ['en', 'no', 'en'] | True |
test_hold_preference | (ecobee_fixture, thermostat) | Test hold preference. | Test hold preference. | async def test_hold_preference(ecobee_fixture, thermostat):
"""Test hold preference."""
assert thermostat.hold_preference() == "nextTransition"
for action in [
"useEndTime4hour",
"useEndTime2hour",
"nextPeriod",
"indefinite",
"askMe",
]:
ecobee_fixture["settings"]["holdAction"] = action
assert thermostat.hold_preference() == "nextTransition" | [
"async",
"def",
"test_hold_preference",
"(",
"ecobee_fixture",
",",
"thermostat",
")",
":",
"assert",
"thermostat",
".",
"hold_preference",
"(",
")",
"==",
"\"nextTransition\"",
"for",
"action",
"in",
"[",
"\"useEndTime4hour\"",
",",
"\"useEndTime2hour\"",
",",
"\"nextPeriod\"",
",",
"\"indefinite\"",
",",
"\"askMe\"",
",",
"]",
":",
"ecobee_fixture",
"[",
"\"settings\"",
"]",
"[",
"\"holdAction\"",
"]",
"=",
"action",
"assert",
"thermostat",
".",
"hold_preference",
"(",
")",
"==",
"\"nextTransition\""
] | [
280,
0
] | [
291,
63
] | python | en | ['en', 'en', 'en'] | True |
test_set_fan_mode_on | (thermostat, data) | Test set fan mode to on. | Test set fan mode to on. | async def test_set_fan_mode_on(thermostat, data):
"""Test set fan mode to on."""
data.reset_mock()
thermostat.set_fan_mode("on")
data.ecobee.set_fan_mode.assert_has_calls(
[mock.call(1, "on", 20, 40, "nextTransition")]
) | [
"async",
"def",
"test_set_fan_mode_on",
"(",
"thermostat",
",",
"data",
")",
":",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_fan_mode",
"(",
"\"on\"",
")",
"data",
".",
"ecobee",
".",
"set_fan_mode",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"on\"",
",",
"20",
",",
"40",
",",
"\"nextTransition\"",
")",
"]",
")"
] | [
294,
0
] | [
300,
5
] | python | en | ['en', 'fy', 'en'] | True |
test_set_fan_mode_auto | (thermostat, data) | Test set fan mode to auto. | Test set fan mode to auto. | async def test_set_fan_mode_auto(thermostat, data):
"""Test set fan mode to auto."""
data.reset_mock()
thermostat.set_fan_mode("auto")
data.ecobee.set_fan_mode.assert_has_calls(
[mock.call(1, "auto", 20, 40, "nextTransition")]
) | [
"async",
"def",
"test_set_fan_mode_auto",
"(",
"thermostat",
",",
"data",
")",
":",
"data",
".",
"reset_mock",
"(",
")",
"thermostat",
".",
"set_fan_mode",
"(",
"\"auto\"",
")",
"data",
".",
"ecobee",
".",
"set_fan_mode",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"1",
",",
"\"auto\"",
",",
"20",
",",
"40",
",",
"\"nextTransition\"",
")",
"]",
")"
] | [
303,
0
] | [
309,
5
] | python | en | ['en', 'fy', 'nl'] | False |
FirmataBoardPin.__init__ | (self, board: FirmataBoard, pin: FirmataPinType, pin_mode: str) | Initialize the pin. | Initialize the pin. | def __init__(self, board: FirmataBoard, pin: FirmataPinType, pin_mode: str):
"""Initialize the pin."""
self.board = board
self._pin = pin
self._pin_mode = pin_mode
self._pin_type, self._firmata_pin = self.board.get_pin_type(self._pin)
self._state = None
if self._pin_type == PIN_TYPE_ANALOG:
# Pymata wants the analog pin formatted as the # from "A#"
self._analog_pin = int(self._pin[1:]) | [
"def",
"__init__",
"(",
"self",
",",
"board",
":",
"FirmataBoard",
",",
"pin",
":",
"FirmataPinType",
",",
"pin_mode",
":",
"str",
")",
":",
"self",
".",
"board",
"=",
"board",
"self",
".",
"_pin",
"=",
"pin",
"self",
".",
"_pin_mode",
"=",
"pin_mode",
"self",
".",
"_pin_type",
",",
"self",
".",
"_firmata_pin",
"=",
"self",
".",
"board",
".",
"get_pin_type",
"(",
"self",
".",
"_pin",
")",
"self",
".",
"_state",
"=",
"None",
"if",
"self",
".",
"_pin_type",
"==",
"PIN_TYPE_ANALOG",
":",
"# Pymata wants the analog pin formatted as the # from \"A#\"",
"self",
".",
"_analog_pin",
"=",
"int",
"(",
"self",
".",
"_pin",
"[",
"1",
":",
"]",
")"
] | [
17,
4
] | [
27,
49
] | python | en | ['en', 'en', 'en'] | True |
FirmataBoardPin.setup | (self) | Set up a pin and make sure it is valid. | Set up a pin and make sure it is valid. | def setup(self):
"""Set up a pin and make sure it is valid."""
if not self.board.mark_pin_used(self._pin):
raise FirmataPinUsedException(f"Pin {self._pin} already used!") | [
"def",
"setup",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"board",
".",
"mark_pin_used",
"(",
"self",
".",
"_pin",
")",
":",
"raise",
"FirmataPinUsedException",
"(",
"f\"Pin {self._pin} already used!\"",
")"
] | [
29,
4
] | [
32,
75
] | python | en | ['en', 'en', 'en'] | True |
FirmataBinaryDigitalOutput.__init__ | (
self,
board: FirmataBoard,
pin: FirmataPinType,
pin_mode: str,
initial: bool,
negate: bool,
) | Initialize the digital output pin. | Initialize the digital output pin. | def __init__(
self,
board: FirmataBoard,
pin: FirmataPinType,
pin_mode: str,
initial: bool,
negate: bool,
):
"""Initialize the digital output pin."""
self._initial = initial
self._negate = negate
super().__init__(board, pin, pin_mode) | [
"def",
"__init__",
"(",
"self",
",",
"board",
":",
"FirmataBoard",
",",
"pin",
":",
"FirmataPinType",
",",
"pin_mode",
":",
"str",
",",
"initial",
":",
"bool",
",",
"negate",
":",
"bool",
",",
")",
":",
"self",
".",
"_initial",
"=",
"initial",
"self",
".",
"_negate",
"=",
"negate",
"super",
"(",
")",
".",
"__init__",
"(",
"board",
",",
"pin",
",",
"pin_mode",
")"
] | [
38,
4
] | [
49,
46
] | python | en | ['en', 'en', 'en'] | True |
FirmataBinaryDigitalOutput.start_pin | (self) | Set initial state on a pin. | Set initial state on a pin. | async def start_pin(self) -> None:
"""Set initial state on a pin."""
_LOGGER.debug(
"Setting initial state for digital output pin %s on board %s",
self._pin,
self.board.name,
)
api = self.board.api
# Only PIN_MODE_OUTPUT mode is supported as binary digital output
await api.set_pin_mode_digital_output(self._firmata_pin)
if self._initial:
new_pin_state = not self._negate
else:
new_pin_state = self._negate
await api.digital_pin_write(self._firmata_pin, int(new_pin_state))
self._state = self._initial | [
"async",
"def",
"start_pin",
"(",
"self",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting initial state for digital output pin %s on board %s\"",
",",
"self",
".",
"_pin",
",",
"self",
".",
"board",
".",
"name",
",",
")",
"api",
"=",
"self",
".",
"board",
".",
"api",
"# Only PIN_MODE_OUTPUT mode is supported as binary digital output",
"await",
"api",
".",
"set_pin_mode_digital_output",
"(",
"self",
".",
"_firmata_pin",
")",
"if",
"self",
".",
"_initial",
":",
"new_pin_state",
"=",
"not",
"self",
".",
"_negate",
"else",
":",
"new_pin_state",
"=",
"self",
".",
"_negate",
"await",
"api",
".",
"digital_pin_write",
"(",
"self",
".",
"_firmata_pin",
",",
"int",
"(",
"new_pin_state",
")",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_initial"
] | [
51,
4
] | [
67,
35
] | python | en | ['en', 'en', 'en'] | True |
FirmataBinaryDigitalOutput.is_on | (self) | Return true if digital output is on. | Return true if digital output is on. | def is_on(self) -> bool:
"""Return true if digital output is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_state"
] | [
70,
4
] | [
72,
26
] | python | en | ['en', 'cy', 'en'] | True |
FirmataBinaryDigitalOutput.turn_on | (self) | Turn on digital output. | Turn on digital output. | async def turn_on(self) -> None:
"""Turn on digital output."""
_LOGGER.debug("Turning digital output on pin %s on", self._pin)
new_pin_state = not self._negate
await self.board.api.digital_pin_write(self._firmata_pin, int(new_pin_state))
self._state = True | [
"async",
"def",
"turn_on",
"(",
"self",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Turning digital output on pin %s on\"",
",",
"self",
".",
"_pin",
")",
"new_pin_state",
"=",
"not",
"self",
".",
"_negate",
"await",
"self",
".",
"board",
".",
"api",
".",
"digital_pin_write",
"(",
"self",
".",
"_firmata_pin",
",",
"int",
"(",
"new_pin_state",
")",
")",
"self",
".",
"_state",
"=",
"True"
] | [
74,
4
] | [
79,
26
] | python | en | ['en', 'et', 'en'] | True |
FirmataBinaryDigitalOutput.turn_off | (self) | Turn off digital output. | Turn off digital output. | async def turn_off(self) -> None:
"""Turn off digital output."""
_LOGGER.debug("Turning digital output on pin %s off", self._pin)
new_pin_state = self._negate
await self.board.api.digital_pin_write(self._firmata_pin, int(new_pin_state))
self._state = False | [
"async",
"def",
"turn_off",
"(",
"self",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Turning digital output on pin %s off\"",
",",
"self",
".",
"_pin",
")",
"new_pin_state",
"=",
"self",
".",
"_negate",
"await",
"self",
".",
"board",
".",
"api",
".",
"digital_pin_write",
"(",
"self",
".",
"_firmata_pin",
",",
"int",
"(",
"new_pin_state",
")",
")",
"self",
".",
"_state",
"=",
"False"
] | [
81,
4
] | [
86,
27
] | python | en | ['en', 'cy', 'en'] | True |
FirmataPWMOutput.__init__ | (
self,
board: FirmataBoard,
pin: FirmataPinType,
pin_mode: str,
initial: bool,
minimum: int,
maximum: int,
) | Initialize the PWM/analog output pin. | Initialize the PWM/analog output pin. | def __init__(
self,
board: FirmataBoard,
pin: FirmataPinType,
pin_mode: str,
initial: bool,
minimum: int,
maximum: int,
):
"""Initialize the PWM/analog output pin."""
self._initial = initial
self._min = minimum
self._max = maximum
self._range = self._max - self._min
super().__init__(board, pin, pin_mode) | [
"def",
"__init__",
"(",
"self",
",",
"board",
":",
"FirmataBoard",
",",
"pin",
":",
"FirmataPinType",
",",
"pin_mode",
":",
"str",
",",
"initial",
":",
"bool",
",",
"minimum",
":",
"int",
",",
"maximum",
":",
"int",
",",
")",
":",
"self",
".",
"_initial",
"=",
"initial",
"self",
".",
"_min",
"=",
"minimum",
"self",
".",
"_max",
"=",
"maximum",
"self",
".",
"_range",
"=",
"self",
".",
"_max",
"-",
"self",
".",
"_min",
"super",
"(",
")",
".",
"__init__",
"(",
"board",
",",
"pin",
",",
"pin_mode",
")"
] | [
92,
4
] | [
106,
46
] | python | en | ['en', 'en', 'en'] | True |
FirmataPWMOutput.start_pin | (self) | Set initial state on a pin. | Set initial state on a pin. | async def start_pin(self) -> None:
"""Set initial state on a pin."""
_LOGGER.debug(
"Setting initial state for PWM/analog output pin %s on board %s to %d",
self._pin,
self.board.name,
self._initial,
)
api = self.board.api
await api.set_pin_mode_pwm_output(self._firmata_pin)
new_pin_state = round((self._initial * self._range) / 255) + self._min
await api.pwm_write(self._firmata_pin, new_pin_state)
self._state = self._initial | [
"async",
"def",
"start_pin",
"(",
"self",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting initial state for PWM/analog output pin %s on board %s to %d\"",
",",
"self",
".",
"_pin",
",",
"self",
".",
"board",
".",
"name",
",",
"self",
".",
"_initial",
",",
")",
"api",
"=",
"self",
".",
"board",
".",
"api",
"await",
"api",
".",
"set_pin_mode_pwm_output",
"(",
"self",
".",
"_firmata_pin",
")",
"new_pin_state",
"=",
"round",
"(",
"(",
"self",
".",
"_initial",
"*",
"self",
".",
"_range",
")",
"/",
"255",
")",
"+",
"self",
".",
"_min",
"await",
"api",
".",
"pwm_write",
"(",
"self",
".",
"_firmata_pin",
",",
"new_pin_state",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_initial"
] | [
108,
4
] | [
121,
35
] | python | en | ['en', 'en', 'en'] | True |
FirmataPWMOutput.state | (self) | Return PWM/analog state. | Return PWM/analog state. | def state(self) -> int:
"""Return PWM/analog state."""
return self._state | [
"def",
"state",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_state"
] | [
124,
4
] | [
126,
26
] | python | da | ['da', 'ig', 'en'] | False |
FirmataPWMOutput.set_level | (self, level: int) | Set PWM/analog output. | Set PWM/analog output. | async def set_level(self, level: int) -> None:
"""Set PWM/analog output."""
_LOGGER.debug("Setting PWM/analog output on pin %s to %d", self._pin, level)
new_pin_state = round((level * self._range) / 255) + self._min
await self.board.api.pwm_write(self._firmata_pin, new_pin_state)
self._state = level | [
"async",
"def",
"set_level",
"(",
"self",
",",
"level",
":",
"int",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting PWM/analog output on pin %s to %d\"",
",",
"self",
".",
"_pin",
",",
"level",
")",
"new_pin_state",
"=",
"round",
"(",
"(",
"level",
"*",
"self",
".",
"_range",
")",
"/",
"255",
")",
"+",
"self",
".",
"_min",
"await",
"self",
".",
"board",
".",
"api",
".",
"pwm_write",
"(",
"self",
".",
"_firmata_pin",
",",
"new_pin_state",
")",
"self",
".",
"_state",
"=",
"level"
] | [
128,
4
] | [
133,
27
] | python | da | ['da', 'el-Latn', 'en'] | False |
FirmataBinaryDigitalInput.__init__ | (
self, board: FirmataBoard, pin: FirmataPinType, pin_mode: str, negate: bool
) | Initialize the digital input pin. | Initialize the digital input pin. | def __init__(
self, board: FirmataBoard, pin: FirmataPinType, pin_mode: str, negate: bool
):
"""Initialize the digital input pin."""
self._negate = negate
self._forward_callback = None
super().__init__(board, pin, pin_mode) | [
"def",
"__init__",
"(",
"self",
",",
"board",
":",
"FirmataBoard",
",",
"pin",
":",
"FirmataPinType",
",",
"pin_mode",
":",
"str",
",",
"negate",
":",
"bool",
")",
":",
"self",
".",
"_negate",
"=",
"negate",
"self",
".",
"_forward_callback",
"=",
"None",
"super",
"(",
")",
".",
"__init__",
"(",
"board",
",",
"pin",
",",
"pin_mode",
")"
] | [
139,
4
] | [
145,
46
] | python | en | ['en', 'en', 'en'] | True |
FirmataBinaryDigitalInput.start_pin | (self, forward_callback: Callable[[], None]) | Get initial state and start reporting a pin. | Get initial state and start reporting a pin. | async def start_pin(self, forward_callback: Callable[[], None]) -> None:
"""Get initial state and start reporting a pin."""
_LOGGER.debug(
"Starting reporting updates for digital input pin %s on board %s",
self._pin,
self.board.name,
)
self._forward_callback = forward_callback
api = self.board.api
if self._pin_mode == PIN_MODE_INPUT:
await api.set_pin_mode_digital_input(self._pin, self.latch_callback)
elif self._pin_mode == PIN_MODE_PULLUP:
await api.set_pin_mode_digital_input_pullup(self._pin, self.latch_callback)
new_state = bool((await self.board.api.digital_read(self._firmata_pin))[0])
if self._negate:
new_state = not new_state
self._state = new_state
await api.enable_digital_reporting(self._pin)
self._forward_callback() | [
"async",
"def",
"start_pin",
"(",
"self",
",",
"forward_callback",
":",
"Callable",
"[",
"[",
"]",
",",
"None",
"]",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting reporting updates for digital input pin %s on board %s\"",
",",
"self",
".",
"_pin",
",",
"self",
".",
"board",
".",
"name",
",",
")",
"self",
".",
"_forward_callback",
"=",
"forward_callback",
"api",
"=",
"self",
".",
"board",
".",
"api",
"if",
"self",
".",
"_pin_mode",
"==",
"PIN_MODE_INPUT",
":",
"await",
"api",
".",
"set_pin_mode_digital_input",
"(",
"self",
".",
"_pin",
",",
"self",
".",
"latch_callback",
")",
"elif",
"self",
".",
"_pin_mode",
"==",
"PIN_MODE_PULLUP",
":",
"await",
"api",
".",
"set_pin_mode_digital_input_pullup",
"(",
"self",
".",
"_pin",
",",
"self",
".",
"latch_callback",
")",
"new_state",
"=",
"bool",
"(",
"(",
"await",
"self",
".",
"board",
".",
"api",
".",
"digital_read",
"(",
"self",
".",
"_firmata_pin",
")",
")",
"[",
"0",
"]",
")",
"if",
"self",
".",
"_negate",
":",
"new_state",
"=",
"not",
"new_state",
"self",
".",
"_state",
"=",
"new_state",
"await",
"api",
".",
"enable_digital_reporting",
"(",
"self",
".",
"_pin",
")",
"self",
".",
"_forward_callback",
"(",
")"
] | [
147,
4
] | [
167,
32
] | python | en | ['en', 'en', 'en'] | True |
FirmataBinaryDigitalInput.stop_pin | (self) | Stop reporting digital input pin. | Stop reporting digital input pin. | async def stop_pin(self) -> None:
"""Stop reporting digital input pin."""
_LOGGER.debug(
"Stopping reporting updates for digital input pin %s on board %s",
self._pin,
self.board.name,
)
api = self.board.api
await api.disable_digital_reporting(self._pin) | [
"async",
"def",
"stop_pin",
"(",
"self",
")",
"->",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Stopping reporting updates for digital input pin %s on board %s\"",
",",
"self",
".",
"_pin",
",",
"self",
".",
"board",
".",
"name",
",",
")",
"api",
"=",
"self",
".",
"board",
".",
"api",
"await",
"api",
".",
"disable_digital_reporting",
"(",
"self",
".",
"_pin",
")"
] | [
169,
4
] | [
177,
54
] | python | id | ['id', 'id', 'en'] | True |
FirmataBinaryDigitalInput.is_on | (self) | Return true if digital input is on. | Return true if digital input is on. | def is_on(self) -> bool:
"""Return true if digital input is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_state"
] | [
180,
4
] | [
182,
26
] | python | en | ['en', 'mt', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.