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_async_generate_path | (hass) | Test generating just the path component of the url correctly. | Test generating just the path component of the url correctly. | async def test_async_generate_path(hass):
"""Test generating just the path component of the url correctly."""
path = hass.components.webhook.async_generate_path("some_id")
assert path == "/api/webhook/some_id" | [
"async",
"def",
"test_async_generate_path",
"(",
"hass",
")",
":",
"path",
"=",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_path",
"(",
"\"some_id\"",
")",
"assert",
"path",
"==",
"\"/api/webhook/some_id\""
] | [
47,
0
] | [
50,
41
] | python | en | ['en', 'en', 'en'] | True |
test_posting_webhook_nonexisting | (hass, mock_client) | Test posting to a nonexisting webhook. | Test posting to a nonexisting webhook. | async def test_posting_webhook_nonexisting(hass, mock_client):
"""Test posting to a nonexisting webhook."""
resp = await mock_client.post("/api/webhook/non-existing")
assert resp.status == 200 | [
"async",
"def",
"test_posting_webhook_nonexisting",
"(",
"hass",
",",
"mock_client",
")",
":",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/non-existing\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
53,
0
] | [
56,
29
] | python | en | ['en', 'en', 'en'] | True |
test_posting_webhook_invalid_json | (hass, mock_client) | Test posting to a nonexisting webhook. | Test posting to a nonexisting webhook. | async def test_posting_webhook_invalid_json(hass, mock_client):
"""Test posting to a nonexisting webhook."""
hass.components.webhook.async_register("test", "Test hook", "hello", None)
resp = await mock_client.post("/api/webhook/hello", data="not-json")
assert resp.status == 200 | [
"async",
"def",
"test_posting_webhook_invalid_json",
"(",
"hass",
",",
"mock_client",
")",
":",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"\"test\"",
",",
"\"Test hook\"",
",",
"\"hello\"",
",",
"None",
")",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"\"/api/webhook/hello\"",
",",
"data",
"=",
"\"not-json\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
59,
0
] | [
63,
29
] | python | en | ['en', 'en', 'en'] | True |
test_posting_webhook_json | (hass, mock_client) | Test posting a webhook with JSON data. | Test posting a webhook with JSON data. | async def test_posting_webhook_json(hass, mock_client):
"""Test posting a webhook with JSON data."""
hooks = []
webhook_id = hass.components.webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append((args[0], args[1], await args[2].text()))
hass.components.webhook.async_register("test", "Test hook", webhook_id, handle)
resp = await mock_client.post(f"/api/webhook/{webhook_id}", json={"data": True})
assert resp.status == 200
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2] == '{"data": true}' | [
"async",
"def",
"test_posting_webhook_json",
"(",
"hass",
",",
"mock_client",
")",
":",
"hooks",
"=",
"[",
"]",
"webhook_id",
"=",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_id",
"(",
")",
"async",
"def",
"handle",
"(",
"*",
"args",
")",
":",
"\"\"\"Handle webhook.\"\"\"",
"hooks",
".",
"append",
"(",
"(",
"args",
"[",
"0",
"]",
",",
"args",
"[",
"1",
"]",
",",
"await",
"args",
"[",
"2",
"]",
".",
"text",
"(",
")",
")",
")",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"\"test\"",
",",
"\"Test hook\"",
",",
"webhook_id",
",",
"handle",
")",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
",",
"json",
"=",
"{",
"\"data\"",
":",
"True",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"assert",
"len",
"(",
"hooks",
")",
"==",
"1",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"0",
"]",
"is",
"hass",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"webhook_id",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"2",
"]",
"==",
"'{\"data\": true}'"
] | [
66,
0
] | [
82,
42
] | python | en | ['en', 'en', 'en'] | True |
test_posting_webhook_no_data | (hass, mock_client) | Test posting a webhook with no data. | Test posting a webhook with no data. | async def test_posting_webhook_no_data(hass, mock_client):
"""Test posting a webhook with no data."""
hooks = []
webhook_id = hass.components.webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
hass.components.webhook.async_register("test", "Test hook", webhook_id, handle)
resp = await mock_client.post(f"/api/webhook/{webhook_id}")
assert resp.status == 200
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "POST"
assert await hooks[0][2].text() == "" | [
"async",
"def",
"test_posting_webhook_no_data",
"(",
"hass",
",",
"mock_client",
")",
":",
"hooks",
"=",
"[",
"]",
"webhook_id",
"=",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_id",
"(",
")",
"async",
"def",
"handle",
"(",
"*",
"args",
")",
":",
"\"\"\"Handle webhook.\"\"\"",
"hooks",
".",
"append",
"(",
"args",
")",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"\"test\"",
",",
"\"Test hook\"",
",",
"webhook_id",
",",
"handle",
")",
"resp",
"=",
"await",
"mock_client",
".",
"post",
"(",
"f\"/api/webhook/{webhook_id}\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"assert",
"len",
"(",
"hooks",
")",
"==",
"1",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"0",
"]",
"is",
"hass",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"webhook_id",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"method",
"==",
"\"POST\"",
"assert",
"await",
"hooks",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"text",
"(",
")",
"==",
"\"\""
] | [
85,
0
] | [
102,
41
] | python | en | ['en', 'en', 'en'] | True |
test_webhook_put | (hass, mock_client) | Test sending a put request to a webhook. | Test sending a put request to a webhook. | async def test_webhook_put(hass, mock_client):
"""Test sending a put request to a webhook."""
hooks = []
webhook_id = hass.components.webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
hass.components.webhook.async_register("test", "Test hook", webhook_id, handle)
resp = await mock_client.put(f"/api/webhook/{webhook_id}")
assert resp.status == 200
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "PUT" | [
"async",
"def",
"test_webhook_put",
"(",
"hass",
",",
"mock_client",
")",
":",
"hooks",
"=",
"[",
"]",
"webhook_id",
"=",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_id",
"(",
")",
"async",
"def",
"handle",
"(",
"*",
"args",
")",
":",
"\"\"\"Handle webhook.\"\"\"",
"hooks",
".",
"append",
"(",
"args",
")",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"\"test\"",
",",
"\"Test hook\"",
",",
"webhook_id",
",",
"handle",
")",
"resp",
"=",
"await",
"mock_client",
".",
"put",
"(",
"f\"/api/webhook/{webhook_id}\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"assert",
"len",
"(",
"hooks",
")",
"==",
"1",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"0",
"]",
"is",
"hass",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"webhook_id",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"method",
"==",
"\"PUT\""
] | [
105,
0
] | [
121,
38
] | python | en | ['en', 'lb', 'en'] | True |
test_webhook_head | (hass, mock_client) | Test sending a head request to a webhook. | Test sending a head request to a webhook. | async def test_webhook_head(hass, mock_client):
"""Test sending a head request to a webhook."""
hooks = []
webhook_id = hass.components.webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
hass.components.webhook.async_register("test", "Test hook", webhook_id, handle)
resp = await mock_client.head(f"/api/webhook/{webhook_id}")
assert resp.status == 200
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "HEAD" | [
"async",
"def",
"test_webhook_head",
"(",
"hass",
",",
"mock_client",
")",
":",
"hooks",
"=",
"[",
"]",
"webhook_id",
"=",
"hass",
".",
"components",
".",
"webhook",
".",
"async_generate_id",
"(",
")",
"async",
"def",
"handle",
"(",
"*",
"args",
")",
":",
"\"\"\"Handle webhook.\"\"\"",
"hooks",
".",
"append",
"(",
"args",
")",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"\"test\"",
",",
"\"Test hook\"",
",",
"webhook_id",
",",
"handle",
")",
"resp",
"=",
"await",
"mock_client",
".",
"head",
"(",
"f\"/api/webhook/{webhook_id}\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"assert",
"len",
"(",
"hooks",
")",
"==",
"1",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"0",
"]",
"is",
"hass",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"1",
"]",
"==",
"webhook_id",
"assert",
"hooks",
"[",
"0",
"]",
"[",
"2",
"]",
".",
"method",
"==",
"\"HEAD\""
] | [
124,
0
] | [
140,
39
] | python | en | ['en', 'lb', 'en'] | True |
test_listing_webhook | (hass, hass_ws_client, hass_access_token) | Test unregistering a webhook. | Test unregistering a webhook. | async def test_listing_webhook(hass, hass_ws_client, hass_access_token):
"""Test unregistering a webhook."""
assert await async_setup_component(hass, "webhook", {})
client = await hass_ws_client(hass, hass_access_token)
hass.components.webhook.async_register("test", "Test hook", "my-id", None)
await client.send_json({"id": 5, "type": "webhook/list"})
msg = await client.receive_json()
assert msg["id"] == 5
assert msg["success"]
assert msg["result"] == [
{"webhook_id": "my-id", "domain": "test", "name": "Test hook"}
] | [
"async",
"def",
"test_listing_webhook",
"(",
"hass",
",",
"hass_ws_client",
",",
"hass_access_token",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"webhook\"",
",",
"{",
"}",
")",
"client",
"=",
"await",
"hass_ws_client",
"(",
"hass",
",",
"hass_access_token",
")",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"\"test\"",
",",
"\"Test hook\"",
",",
"\"my-id\"",
",",
"None",
")",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"5",
",",
"\"type\"",
":",
"\"webhook/list\"",
"}",
")",
"msg",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"msg",
"[",
"\"id\"",
"]",
"==",
"5",
"assert",
"msg",
"[",
"\"success\"",
"]",
"assert",
"msg",
"[",
"\"result\"",
"]",
"==",
"[",
"{",
"\"webhook_id\"",
":",
"\"my-id\"",
",",
"\"domain\"",
":",
"\"test\"",
",",
"\"name\"",
":",
"\"Test hook\"",
"}",
"]"
] | [
143,
0
] | [
157,
5
] | python | da | ['en', 'da', 'it'] | False |
create_tv_service | (accessory) |
Define tv characteristics.
The TV is not currently documented publicly - this is based on observing really TV's that have HomeKit support.
|
Define tv characteristics. | def create_tv_service(accessory):
"""
Define tv characteristics.
The TV is not currently documented publicly - this is based on observing really TV's that have HomeKit support.
"""
tv_service = accessory.add_service(ServicesTypes.TELEVISION)
tv_service.add_char(CharacteristicsTypes.ACTIVE, value=True)
cur_state = tv_service.add_char(CharacteristicsTypes.CURRENT_MEDIA_STATE)
cur_state.value = 0
remote = tv_service.add_char(CharacteristicsTypes.REMOTE_KEY)
remote.value = None
remote.perms.append(CharacteristicPermissions.paired_write)
# Add a HDMI 1 channel
input_source_1 = accessory.add_service(ServicesTypes.INPUT_SOURCE)
input_source_1.add_char(CharacteristicsTypes.IDENTIFIER, value=1)
input_source_1.add_char(CharacteristicsTypes.CONFIGURED_NAME, value="HDMI 1")
tv_service.add_linked_service(input_source_1)
# Add a HDMI 2 channel
input_source_2 = accessory.add_service(ServicesTypes.INPUT_SOURCE)
input_source_2.add_char(CharacteristicsTypes.IDENTIFIER, value=2)
input_source_2.add_char(CharacteristicsTypes.CONFIGURED_NAME, value="HDMI 2")
tv_service.add_linked_service(input_source_2)
# Support switching channels
active_identifier = tv_service.add_char(CharacteristicsTypes.ACTIVE_IDENTIFIER)
active_identifier.value = 1
active_identifier.perms.append(CharacteristicPermissions.paired_write)
return tv_service | [
"def",
"create_tv_service",
"(",
"accessory",
")",
":",
"tv_service",
"=",
"accessory",
".",
"add_service",
"(",
"ServicesTypes",
".",
"TELEVISION",
")",
"tv_service",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"ACTIVE",
",",
"value",
"=",
"True",
")",
"cur_state",
"=",
"tv_service",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"CURRENT_MEDIA_STATE",
")",
"cur_state",
".",
"value",
"=",
"0",
"remote",
"=",
"tv_service",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"REMOTE_KEY",
")",
"remote",
".",
"value",
"=",
"None",
"remote",
".",
"perms",
".",
"append",
"(",
"CharacteristicPermissions",
".",
"paired_write",
")",
"# Add a HDMI 1 channel",
"input_source_1",
"=",
"accessory",
".",
"add_service",
"(",
"ServicesTypes",
".",
"INPUT_SOURCE",
")",
"input_source_1",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"IDENTIFIER",
",",
"value",
"=",
"1",
")",
"input_source_1",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"CONFIGURED_NAME",
",",
"value",
"=",
"\"HDMI 1\"",
")",
"tv_service",
".",
"add_linked_service",
"(",
"input_source_1",
")",
"# Add a HDMI 2 channel",
"input_source_2",
"=",
"accessory",
".",
"add_service",
"(",
"ServicesTypes",
".",
"INPUT_SOURCE",
")",
"input_source_2",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"IDENTIFIER",
",",
"value",
"=",
"2",
")",
"input_source_2",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"CONFIGURED_NAME",
",",
"value",
"=",
"\"HDMI 2\"",
")",
"tv_service",
".",
"add_linked_service",
"(",
"input_source_2",
")",
"# Support switching channels",
"active_identifier",
"=",
"tv_service",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"ACTIVE_IDENTIFIER",
")",
"active_identifier",
".",
"value",
"=",
"1",
"active_identifier",
".",
"perms",
".",
"append",
"(",
"CharacteristicPermissions",
".",
"paired_write",
")",
"return",
"tv_service"
] | [
16,
0
] | [
50,
21
] | python | en | ['en', 'error', 'th'] | False |
create_tv_service_with_target_media_state | (accessory) | Define a TV service that can play/pause/stop without generate remote events. | Define a TV service that can play/pause/stop without generate remote events. | def create_tv_service_with_target_media_state(accessory):
"""Define a TV service that can play/pause/stop without generate remote events."""
service = create_tv_service(accessory)
tms = service.add_char(CharacteristicsTypes.TARGET_MEDIA_STATE)
tms.value = None
tms.perms.append(CharacteristicPermissions.paired_write)
return service | [
"def",
"create_tv_service_with_target_media_state",
"(",
"accessory",
")",
":",
"service",
"=",
"create_tv_service",
"(",
"accessory",
")",
"tms",
"=",
"service",
".",
"add_char",
"(",
"CharacteristicsTypes",
".",
"TARGET_MEDIA_STATE",
")",
"tms",
".",
"value",
"=",
"None",
"tms",
".",
"perms",
".",
"append",
"(",
"CharacteristicPermissions",
".",
"paired_write",
")",
"return",
"service"
] | [
53,
0
] | [
61,
18
] | python | en | ['en', 'en', 'en'] | True |
test_tv_read_state | (hass, utcnow) | Test that we can read the state of a HomeKit fan accessory. | Test that we can read the state of a HomeKit fan accessory. | async def test_tv_read_state(hass, utcnow):
"""Test that we can read the state of a HomeKit fan accessory."""
helper = await setup_test_component(hass, create_tv_service)
helper.characteristics[CURRENT_MEDIA_STATE].value = 0
state = await helper.poll_and_get_state()
assert state.state == "playing"
helper.characteristics[CURRENT_MEDIA_STATE].value = 1
state = await helper.poll_and_get_state()
assert state.state == "paused"
helper.characteristics[CURRENT_MEDIA_STATE].value = 2
state = await helper.poll_and_get_state()
assert state.state == "idle" | [
"async",
"def",
"test_tv_read_state",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service",
")",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"0",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"state",
"==",
"\"playing\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"1",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"state",
"==",
"\"paused\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"2",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"state",
"==",
"\"idle\""
] | [
64,
0
] | [
78,
32
] | python | en | ['en', 'en', 'en'] | True |
test_tv_read_sources | (hass, utcnow) | Test that we can read the input source of a HomeKit TV. | Test that we can read the input source of a HomeKit TV. | async def test_tv_read_sources(hass, utcnow):
"""Test that we can read the input source of a HomeKit TV."""
helper = await setup_test_component(hass, create_tv_service)
state = await helper.poll_and_get_state()
assert state.attributes["source"] == "HDMI 1"
assert state.attributes["source_list"] == ["HDMI 1", "HDMI 2"] | [
"async",
"def",
"test_tv_read_sources",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service",
")",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"source\"",
"]",
"==",
"\"HDMI 1\"",
"assert",
"state",
".",
"attributes",
"[",
"\"source_list\"",
"]",
"==",
"[",
"\"HDMI 1\"",
",",
"\"HDMI 2\"",
"]"
] | [
81,
0
] | [
87,
66
] | python | en | ['en', 'en', 'en'] | True |
test_play_remote_key | (hass, utcnow) | Test that we can play media on a media player. | Test that we can play media on a media player. | async def test_play_remote_key(hass, utcnow):
"""Test that we can play media on a media player."""
helper = await setup_test_component(hass, create_tv_service)
helper.characteristics[CURRENT_MEDIA_STATE].value = 1
await helper.poll_and_get_state()
await hass.services.async_call(
"media_player",
"media_play",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value == 11
# Second time should be a no-op
helper.characteristics[CURRENT_MEDIA_STATE].value = 0
await helper.poll_and_get_state()
helper.characteristics[REMOTE_KEY].value = None
await hass.services.async_call(
"media_player",
"media_play",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None | [
"async",
"def",
"test_play_remote_key",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service",
")",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"1",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_play\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"==",
"11",
"# Second time should be a no-op",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"0",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"=",
"None",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_play\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None"
] | [
90,
0
] | [
116,
59
] | python | en | ['en', 'en', 'en'] | True |
test_pause_remote_key | (hass, utcnow) | Test that we can pause a media player. | Test that we can pause a media player. | async def test_pause_remote_key(hass, utcnow):
"""Test that we can pause a media player."""
helper = await setup_test_component(hass, create_tv_service)
helper.characteristics[CURRENT_MEDIA_STATE].value = 0
await helper.poll_and_get_state()
await hass.services.async_call(
"media_player",
"media_pause",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value == 11
# Second time should be a no-op
helper.characteristics[CURRENT_MEDIA_STATE].value = 1
await helper.poll_and_get_state()
helper.characteristics[REMOTE_KEY].value = None
await hass.services.async_call(
"media_player",
"media_pause",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None | [
"async",
"def",
"test_pause_remote_key",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service",
")",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"0",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_pause\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"==",
"11",
"# Second time should be a no-op",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"1",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"=",
"None",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_pause\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None"
] | [
119,
0
] | [
145,
59
] | python | en | ['en', 'en', 'en'] | True |
test_play | (hass, utcnow) | Test that we can play media on a media player. | Test that we can play media on a media player. | async def test_play(hass, utcnow):
"""Test that we can play media on a media player."""
helper = await setup_test_component(hass, create_tv_service_with_target_media_state)
helper.characteristics[CURRENT_MEDIA_STATE].value = 1
await helper.poll_and_get_state()
await hass.services.async_call(
"media_player",
"media_play",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None
assert helper.characteristics[TARGET_MEDIA_STATE].value == 0
# Second time should be a no-op
helper.characteristics[CURRENT_MEDIA_STATE].value = 0
await helper.poll_and_get_state()
helper.characteristics[TARGET_MEDIA_STATE].value = None
await hass.services.async_call(
"media_player",
"media_play",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None
assert helper.characteristics[TARGET_MEDIA_STATE].value is None | [
"async",
"def",
"test_play",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service_with_target_media_state",
")",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"1",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_play\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"==",
"0",
"# Second time should be a no-op",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"0",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"=",
"None",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_play\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"is",
"None"
] | [
148,
0
] | [
176,
67
] | python | en | ['en', 'en', 'en'] | True |
test_pause | (hass, utcnow) | Test that we can turn pause a media player. | Test that we can turn pause a media player. | async def test_pause(hass, utcnow):
"""Test that we can turn pause a media player."""
helper = await setup_test_component(hass, create_tv_service_with_target_media_state)
helper.characteristics[CURRENT_MEDIA_STATE].value = 0
await helper.poll_and_get_state()
await hass.services.async_call(
"media_player",
"media_pause",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None
assert helper.characteristics[TARGET_MEDIA_STATE].value == 1
# Second time should be a no-op
helper.characteristics[CURRENT_MEDIA_STATE].value = 1
await helper.poll_and_get_state()
helper.characteristics[REMOTE_KEY].value = None
await hass.services.async_call(
"media_player",
"media_pause",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None | [
"async",
"def",
"test_pause",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service_with_target_media_state",
")",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"0",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_pause\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"==",
"1",
"# Second time should be a no-op",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"1",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"=",
"None",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_pause\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None"
] | [
179,
0
] | [
206,
59
] | python | en | ['en', 'en', 'en'] | True |
test_stop | (hass, utcnow) | Test that we can stop a media player. | Test that we can stop a media player. | async def test_stop(hass, utcnow):
"""Test that we can stop a media player."""
helper = await setup_test_component(hass, create_tv_service_with_target_media_state)
await hass.services.async_call(
"media_player",
"media_stop",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[TARGET_MEDIA_STATE].value == 2
# Second time should be a no-op
helper.characteristics[CURRENT_MEDIA_STATE].value = 2
await helper.poll_and_get_state()
helper.characteristics[TARGET_MEDIA_STATE].value = None
await hass.services.async_call(
"media_player",
"media_stop",
{"entity_id": "media_player.testdevice"},
blocking=True,
)
assert helper.characteristics[REMOTE_KEY].value is None
assert helper.characteristics[TARGET_MEDIA_STATE].value is None | [
"async",
"def",
"test_stop",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service_with_target_media_state",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_stop\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"==",
"2",
"# Second time should be a no-op",
"helper",
".",
"characteristics",
"[",
"CURRENT_MEDIA_STATE",
"]",
".",
"value",
"=",
"2",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"=",
"None",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"media_stop\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"REMOTE_KEY",
"]",
".",
"value",
"is",
"None",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_MEDIA_STATE",
"]",
".",
"value",
"is",
"None"
] | [
209,
0
] | [
233,
67
] | python | en | ['en', 'en', 'en'] | True |
test_tv_set_source | (hass, utcnow) | Test that we can set the input source of a HomeKit TV. | Test that we can set the input source of a HomeKit TV. | async def test_tv_set_source(hass, utcnow):
"""Test that we can set the input source of a HomeKit TV."""
helper = await setup_test_component(hass, create_tv_service)
await hass.services.async_call(
"media_player",
"select_source",
{"entity_id": "media_player.testdevice", "source": "HDMI 2"},
blocking=True,
)
assert helper.characteristics[ACTIVE_IDENTIFIER].value == 2
state = await helper.poll_and_get_state()
assert state.attributes["source"] == "HDMI 2" | [
"async",
"def",
"test_tv_set_source",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"select_source\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
",",
"\"source\"",
":",
"\"HDMI 2\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"ACTIVE_IDENTIFIER",
"]",
".",
"value",
"==",
"2",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"source\"",
"]",
"==",
"\"HDMI 2\""
] | [
236,
0
] | [
249,
49
] | python | en | ['en', 'en', 'en'] | True |
test_tv_set_source_fail | (hass, utcnow) | Test that we can set the input source of a HomeKit TV. | Test that we can set the input source of a HomeKit TV. | async def test_tv_set_source_fail(hass, utcnow):
"""Test that we can set the input source of a HomeKit TV."""
helper = await setup_test_component(hass, create_tv_service)
with pytest.raises(ValueError):
await hass.services.async_call(
"media_player",
"select_source",
{"entity_id": "media_player.testdevice", "source": "HDMI 999"},
blocking=True,
)
state = await helper.poll_and_get_state()
assert state.attributes["source"] == "HDMI 1" | [
"async",
"def",
"test_tv_set_source_fail",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_tv_service",
")",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"media_player\"",
",",
"\"select_source\"",
",",
"{",
"\"entity_id\"",
":",
"\"media_player.testdevice\"",
",",
"\"source\"",
":",
"\"HDMI 999\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"source\"",
"]",
"==",
"\"HDMI 1\""
] | [
252,
0
] | [
265,
49
] | python | en | ['en', 'en', 'en'] | True |
DoorBirdEntity.__init__ | (self, doorstation, doorstation_info) | Initialize the entity. | Initialize the entity. | def __init__(self, doorstation, doorstation_info):
"""Initialize the entity."""
super().__init__()
self._doorstation_info = doorstation_info
self._doorstation = doorstation
self._mac_addr = get_mac_address_from_doorstation_info(doorstation_info) | [
"def",
"__init__",
"(",
"self",
",",
"doorstation",
",",
"doorstation_info",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_doorstation_info",
"=",
"doorstation_info",
"self",
".",
"_doorstation",
"=",
"doorstation",
"self",
".",
"_mac_addr",
"=",
"get_mac_address_from_doorstation_info",
"(",
"doorstation_info",
")"
] | [
17,
4
] | [
22,
80
] | python | en | ['en', 'en', 'en'] | True |
DoorBirdEntity.device_info | (self) | Doorbird device info. | Doorbird device info. | def device_info(self):
"""Doorbird device info."""
firmware = self._doorstation_info[DOORBIRD_INFO_KEY_FIRMWARE]
firmware_build = self._doorstation_info[DOORBIRD_INFO_KEY_BUILD_NUMBER]
return {
"connections": {(dr.CONNECTION_NETWORK_MAC, self._mac_addr)},
"name": self._doorstation.name,
"manufacturer": MANUFACTURER,
"sw_version": f"{firmware} {firmware_build}",
"model": self._doorstation_info[DOORBIRD_INFO_KEY_DEVICE_TYPE],
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"firmware",
"=",
"self",
".",
"_doorstation_info",
"[",
"DOORBIRD_INFO_KEY_FIRMWARE",
"]",
"firmware_build",
"=",
"self",
".",
"_doorstation_info",
"[",
"DOORBIRD_INFO_KEY_BUILD_NUMBER",
"]",
"return",
"{",
"\"connections\"",
":",
"{",
"(",
"dr",
".",
"CONNECTION_NETWORK_MAC",
",",
"self",
".",
"_mac_addr",
")",
"}",
",",
"\"name\"",
":",
"self",
".",
"_doorstation",
".",
"name",
",",
"\"manufacturer\"",
":",
"MANUFACTURER",
",",
"\"sw_version\"",
":",
"f\"{firmware} {firmware_build}\"",
",",
"\"model\"",
":",
"self",
".",
"_doorstation_info",
"[",
"DOORBIRD_INFO_KEY_DEVICE_TYPE",
"]",
",",
"}"
] | [
25,
4
] | [
35,
9
] | python | da | ['da', 'nl', 'en'] | False |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up a sensor for an Amcrest IP Camera. | Set up a sensor for an Amcrest IP Camera. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up a sensor for an Amcrest IP Camera."""
if discovery_info is None:
return
name = discovery_info[CONF_NAME]
device = hass.data[DATA_AMCREST][DEVICES][name]
async_add_entities(
[
AmcrestSensor(name, device, sensor_type)
for sensor_type in discovery_info[CONF_SENSORS]
],
True,
) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"name",
"=",
"discovery_info",
"[",
"CONF_NAME",
"]",
"device",
"=",
"hass",
".",
"data",
"[",
"DATA_AMCREST",
"]",
"[",
"DEVICES",
"]",
"[",
"name",
"]",
"async_add_entities",
"(",
"[",
"AmcrestSensor",
"(",
"name",
",",
"device",
",",
"sensor_type",
")",
"for",
"sensor_type",
"in",
"discovery_info",
"[",
"CONF_SENSORS",
"]",
"]",
",",
"True",
",",
")"
] | [
26,
0
] | [
39,
5
] | python | en | ['en', 'da', 'en'] | True |
AmcrestSensor.__init__ | (self, name, device, sensor_type) | Initialize a sensor for Amcrest camera. | Initialize a sensor for Amcrest camera. | def __init__(self, name, device, sensor_type):
"""Initialize a sensor for Amcrest camera."""
self._name = f"{name} {SENSORS[sensor_type][0]}"
self._signal_name = name
self._api = device.api
self._sensor_type = sensor_type
self._state = None
self._attrs = {}
self._unit_of_measurement = SENSORS[sensor_type][1]
self._icon = SENSORS[sensor_type][2]
self._unsub_dispatcher = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"device",
",",
"sensor_type",
")",
":",
"self",
".",
"_name",
"=",
"f\"{name} {SENSORS[sensor_type][0]}\"",
"self",
".",
"_signal_name",
"=",
"name",
"self",
".",
"_api",
"=",
"device",
".",
"api",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_attrs",
"=",
"{",
"}",
"self",
".",
"_unit_of_measurement",
"=",
"SENSORS",
"[",
"sensor_type",
"]",
"[",
"1",
"]",
"self",
".",
"_icon",
"=",
"SENSORS",
"[",
"sensor_type",
"]",
"[",
"2",
"]",
"self",
".",
"_unsub_dispatcher",
"=",
"None"
] | [
45,
4
] | [
55,
37
] | python | en | ['en', 'pt', 'en'] | True |
AmcrestSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
58,
4
] | [
60,
25
] | python | en | ['en', 'mi', 'en'] | True |
AmcrestSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
63,
4
] | [
65,
26
] | python | en | ['en', 'en', 'en'] | True |
AmcrestSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return self._attrs | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attrs"
] | [
68,
4
] | [
70,
26
] | python | en | ['en', 'en', 'en'] | True |
AmcrestSensor.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"
] | [
73,
4
] | [
75,
25
] | python | en | ['en', 'en', 'en'] | True |
AmcrestSensor.unit_of_measurement | (self) | Return the units of measurement. | Return the units of measurement. | def unit_of_measurement(self):
"""Return the units of measurement."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
78,
4
] | [
80,
40
] | python | en | ['en', 'bg', 'en'] | True |
AmcrestSensor.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return self._api.available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_api",
".",
"available"
] | [
83,
4
] | [
85,
34
] | python | en | ['en', 'en', 'en'] | True |
AmcrestSensor.update | (self) | Get the latest data and updates the state. | Get the latest data and updates the state. | def update(self):
"""Get the latest data and updates the state."""
if not self.available:
return
_LOGGER.debug("Updating %s sensor", self._name)
try:
if self._sensor_type == SENSOR_PTZ_PRESET:
self._state = self._api.ptz_presets_count
elif self._sensor_type == SENSOR_SDCARD:
storage = self._api.storage_all
try:
self._attrs[
"Total"
] = f"{storage['total'][0]:.2f} {storage['total'][1]}"
except ValueError:
self._attrs[
"Total"
] = f"{storage['total'][0]} {storage['total'][1]}"
try:
self._attrs[
"Used"
] = f"{storage['used'][0]:.2f} {storage['used'][1]}"
except ValueError:
self._attrs["Used"] = f"{storage['used'][0]} {storage['used'][1]}"
try:
self._state = f"{storage['used_percent']:.2f}"
except ValueError:
self._state = storage["used_percent"]
except AmcrestError as error:
log_update_error(_LOGGER, "update", self.name, "sensor", error) | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"available",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Updating %s sensor\"",
",",
"self",
".",
"_name",
")",
"try",
":",
"if",
"self",
".",
"_sensor_type",
"==",
"SENSOR_PTZ_PRESET",
":",
"self",
".",
"_state",
"=",
"self",
".",
"_api",
".",
"ptz_presets_count",
"elif",
"self",
".",
"_sensor_type",
"==",
"SENSOR_SDCARD",
":",
"storage",
"=",
"self",
".",
"_api",
".",
"storage_all",
"try",
":",
"self",
".",
"_attrs",
"[",
"\"Total\"",
"]",
"=",
"f\"{storage['total'][0]:.2f} {storage['total'][1]}\"",
"except",
"ValueError",
":",
"self",
".",
"_attrs",
"[",
"\"Total\"",
"]",
"=",
"f\"{storage['total'][0]} {storage['total'][1]}\"",
"try",
":",
"self",
".",
"_attrs",
"[",
"\"Used\"",
"]",
"=",
"f\"{storage['used'][0]:.2f} {storage['used'][1]}\"",
"except",
"ValueError",
":",
"self",
".",
"_attrs",
"[",
"\"Used\"",
"]",
"=",
"f\"{storage['used'][0]} {storage['used'][1]}\"",
"try",
":",
"self",
".",
"_state",
"=",
"f\"{storage['used_percent']:.2f}\"",
"except",
"ValueError",
":",
"self",
".",
"_state",
"=",
"storage",
"[",
"\"used_percent\"",
"]",
"except",
"AmcrestError",
"as",
"error",
":",
"log_update_error",
"(",
"_LOGGER",
",",
"\"update\"",
",",
"self",
".",
"name",
",",
"\"sensor\"",
",",
"error",
")"
] | [
87,
4
] | [
118,
75
] | python | en | ['en', 'en', 'en'] | True |
AmcrestSensor.async_on_demand_update | (self) | Update state. | Update state. | async def async_on_demand_update(self):
"""Update state."""
self.async_schedule_update_ha_state(True) | [
"async",
"def",
"async_on_demand_update",
"(",
"self",
")",
":",
"self",
".",
"async_schedule_update_ha_state",
"(",
"True",
")"
] | [
120,
4
] | [
122,
49
] | python | en | ['en', 'co', 'en'] | False |
AmcrestSensor.async_added_to_hass | (self) | Subscribe to update signal. | Subscribe to update signal. | async def async_added_to_hass(self):
"""Subscribe to update signal."""
self._unsub_dispatcher = async_dispatcher_connect(
self.hass,
service_signal(SERVICE_UPDATE, self._signal_name),
self.async_on_demand_update,
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_unsub_dispatcher",
"=",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"service_signal",
"(",
"SERVICE_UPDATE",
",",
"self",
".",
"_signal_name",
")",
",",
"self",
".",
"async_on_demand_update",
",",
")"
] | [
124,
4
] | [
130,
9
] | python | en | ['en', 'en', 'en'] | True |
AmcrestSensor.async_will_remove_from_hass | (self) | Disconnect from update signal. | Disconnect from update signal. | async def async_will_remove_from_hass(self):
"""Disconnect from update signal."""
self._unsub_dispatcher() | [
"async",
"def",
"async_will_remove_from_hass",
"(",
"self",
")",
":",
"self",
".",
"_unsub_dispatcher",
"(",
")"
] | [
132,
4
] | [
134,
32
] | python | en | ['en', 'en', 'en'] | True |
valid_country | (value: Any) | Validate that the given country is supported. | Validate that the given country is supported. | def valid_country(value: Any) -> str:
"""Validate that the given country is supported."""
value = cv.string(value)
all_supported_countries = holidays.list_supported_countries()
try:
raw_value = value.encode("utf-8")
except UnicodeError as err:
raise vol.Invalid(
"The country name or the abbreviation must be a valid UTF-8 string."
) from err
if not raw_value:
raise vol.Invalid("Country name or the abbreviation must not be empty.")
if value not in all_supported_countries:
raise vol.Invalid("Country is not supported.")
return value | [
"def",
"valid_country",
"(",
"value",
":",
"Any",
")",
"->",
"str",
":",
"value",
"=",
"cv",
".",
"string",
"(",
"value",
")",
"all_supported_countries",
"=",
"holidays",
".",
"list_supported_countries",
"(",
")",
"try",
":",
"raw_value",
"=",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
"except",
"UnicodeError",
"as",
"err",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"\"The country name or the abbreviation must be a valid UTF-8 string.\"",
")",
"from",
"err",
"if",
"not",
"raw_value",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"\"Country name or the abbreviation must not be empty.\"",
")",
"if",
"value",
"not",
"in",
"all_supported_countries",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"\"Country is not supported.\"",
")",
"return",
"value"
] | [
32,
0
] | [
47,
16
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Workday sensor. | Set up the Workday sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Workday sensor."""
add_holidays = config.get(CONF_ADD_HOLIDAYS)
remove_holidays = config.get(CONF_REMOVE_HOLIDAYS)
country = config[CONF_COUNTRY]
days_offset = config[CONF_OFFSET]
excludes = config[CONF_EXCLUDES]
province = config.get(CONF_PROVINCE)
sensor_name = config[CONF_NAME]
workdays = config[CONF_WORKDAYS]
year = (get_date(datetime.today()) + timedelta(days=days_offset)).year
obj_holidays = getattr(holidays, country)(years=year)
if province:
# 'state' and 'prov' are not interchangeable, so need to make
# sure we use the right one
if hasattr(obj_holidays, "PROVINCES") and province in obj_holidays.PROVINCES:
obj_holidays = getattr(holidays, country)(prov=province, years=year)
elif hasattr(obj_holidays, "STATES") and province in obj_holidays.STATES:
obj_holidays = getattr(holidays, country)(state=province, years=year)
else:
_LOGGER.error(
"There is no province/state %s in country %s", province, country
)
return
# Add custom holidays
try:
obj_holidays.append(add_holidays)
except TypeError:
_LOGGER.debug("No custom holidays or invalid holidays")
# Remove holidays
try:
for date in remove_holidays:
obj_holidays.pop(date)
except TypeError:
_LOGGER.debug("No holidays to remove or invalid holidays")
_LOGGER.debug("Found the following holidays for your configuration:")
for date, name in sorted(obj_holidays.items()):
_LOGGER.debug("%s %s", date, name)
add_entities(
[IsWorkdaySensor(obj_holidays, workdays, excludes, days_offset, sensor_name)],
True,
) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"add_holidays",
"=",
"config",
".",
"get",
"(",
"CONF_ADD_HOLIDAYS",
")",
"remove_holidays",
"=",
"config",
".",
"get",
"(",
"CONF_REMOVE_HOLIDAYS",
")",
"country",
"=",
"config",
"[",
"CONF_COUNTRY",
"]",
"days_offset",
"=",
"config",
"[",
"CONF_OFFSET",
"]",
"excludes",
"=",
"config",
"[",
"CONF_EXCLUDES",
"]",
"province",
"=",
"config",
".",
"get",
"(",
"CONF_PROVINCE",
")",
"sensor_name",
"=",
"config",
"[",
"CONF_NAME",
"]",
"workdays",
"=",
"config",
"[",
"CONF_WORKDAYS",
"]",
"year",
"=",
"(",
"get_date",
"(",
"datetime",
".",
"today",
"(",
")",
")",
"+",
"timedelta",
"(",
"days",
"=",
"days_offset",
")",
")",
".",
"year",
"obj_holidays",
"=",
"getattr",
"(",
"holidays",
",",
"country",
")",
"(",
"years",
"=",
"year",
")",
"if",
"province",
":",
"# 'state' and 'prov' are not interchangeable, so need to make",
"# sure we use the right one",
"if",
"hasattr",
"(",
"obj_holidays",
",",
"\"PROVINCES\"",
")",
"and",
"province",
"in",
"obj_holidays",
".",
"PROVINCES",
":",
"obj_holidays",
"=",
"getattr",
"(",
"holidays",
",",
"country",
")",
"(",
"prov",
"=",
"province",
",",
"years",
"=",
"year",
")",
"elif",
"hasattr",
"(",
"obj_holidays",
",",
"\"STATES\"",
")",
"and",
"province",
"in",
"obj_holidays",
".",
"STATES",
":",
"obj_holidays",
"=",
"getattr",
"(",
"holidays",
",",
"country",
")",
"(",
"state",
"=",
"province",
",",
"years",
"=",
"year",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"There is no province/state %s in country %s\"",
",",
"province",
",",
"country",
")",
"return",
"# Add custom holidays",
"try",
":",
"obj_holidays",
".",
"append",
"(",
"add_holidays",
")",
"except",
"TypeError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"No custom holidays or invalid holidays\"",
")",
"# Remove holidays",
"try",
":",
"for",
"date",
"in",
"remove_holidays",
":",
"obj_holidays",
".",
"pop",
"(",
"date",
")",
"except",
"TypeError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"No holidays to remove or invalid holidays\"",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Found the following holidays for your configuration:\"",
")",
"for",
"date",
",",
"name",
"in",
"sorted",
"(",
"obj_holidays",
".",
"items",
"(",
")",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s %s\"",
",",
"date",
",",
"name",
")",
"add_entities",
"(",
"[",
"IsWorkdaySensor",
"(",
"obj_holidays",
",",
"workdays",
",",
"excludes",
",",
"days_offset",
",",
"sensor_name",
")",
"]",
",",
"True",
",",
")"
] | [
68,
0
] | [
115,
5
] | python | en | ['en', 'da', 'en'] | True |
day_to_string | (day) | Convert day index 0 - 7 to string. | Convert day index 0 - 7 to string. | def day_to_string(day):
"""Convert day index 0 - 7 to string."""
try:
return ALLOWED_DAYS[day]
except IndexError:
return None | [
"def",
"day_to_string",
"(",
"day",
")",
":",
"try",
":",
"return",
"ALLOWED_DAYS",
"[",
"day",
"]",
"except",
"IndexError",
":",
"return",
"None"
] | [
118,
0
] | [
123,
19
] | python | en | ['en', 'en', 'en'] | True |
get_date | (date) | Return date. Needed for testing. | Return date. Needed for testing. | def get_date(date):
"""Return date. Needed for testing."""
return date | [
"def",
"get_date",
"(",
"date",
")",
":",
"return",
"date"
] | [
126,
0
] | [
128,
15
] | python | en | ['en', 'no', 'en'] | True |
IsWorkdaySensor.__init__ | (self, obj_holidays, workdays, excludes, days_offset, name) | Initialize the Workday sensor. | Initialize the Workday sensor. | def __init__(self, obj_holidays, workdays, excludes, days_offset, name):
"""Initialize the Workday sensor."""
self._name = name
self._obj_holidays = obj_holidays
self._workdays = workdays
self._excludes = excludes
self._days_offset = days_offset
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"obj_holidays",
",",
"workdays",
",",
"excludes",
",",
"days_offset",
",",
"name",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_obj_holidays",
"=",
"obj_holidays",
"self",
".",
"_workdays",
"=",
"workdays",
"self",
".",
"_excludes",
"=",
"excludes",
"self",
".",
"_days_offset",
"=",
"days_offset",
"self",
".",
"_state",
"=",
"None"
] | [
134,
4
] | [
141,
26
] | python | en | ['en', 'en', 'en'] | True |
IsWorkdaySensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
144,
4
] | [
146,
25
] | python | en | ['en', 'mi', 'en'] | True |
IsWorkdaySensor.is_on | (self) | Return the state of the device. | Return the state of the device. | def is_on(self):
"""Return the state of the device."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
149,
4
] | [
151,
26
] | python | en | ['en', 'en', 'en'] | True |
IsWorkdaySensor.is_include | (self, day, now) | Check if given day is in the includes list. | Check if given day is in the includes list. | def is_include(self, day, now):
"""Check if given day is in the includes list."""
if day in self._workdays:
return True
if "holiday" in self._workdays and now in self._obj_holidays:
return True
return False | [
"def",
"is_include",
"(",
"self",
",",
"day",
",",
"now",
")",
":",
"if",
"day",
"in",
"self",
".",
"_workdays",
":",
"return",
"True",
"if",
"\"holiday\"",
"in",
"self",
".",
"_workdays",
"and",
"now",
"in",
"self",
".",
"_obj_holidays",
":",
"return",
"True",
"return",
"False"
] | [
153,
4
] | [
160,
20
] | python | en | ['en', 'en', 'en'] | True |
IsWorkdaySensor.is_exclude | (self, day, now) | Check if given day is in the excludes list. | Check if given day is in the excludes list. | def is_exclude(self, day, now):
"""Check if given day is in the excludes list."""
if day in self._excludes:
return True
if "holiday" in self._excludes and now in self._obj_holidays:
return True
return False | [
"def",
"is_exclude",
"(",
"self",
",",
"day",
",",
"now",
")",
":",
"if",
"day",
"in",
"self",
".",
"_excludes",
":",
"return",
"True",
"if",
"\"holiday\"",
"in",
"self",
".",
"_excludes",
"and",
"now",
"in",
"self",
".",
"_obj_holidays",
":",
"return",
"True",
"return",
"False"
] | [
162,
4
] | [
169,
20
] | python | en | ['en', 'en', 'en'] | True |
IsWorkdaySensor.state_attributes | (self) | Return the attributes of the entity. | Return the attributes of the entity. | def state_attributes(self):
"""Return the attributes of the entity."""
# return self._attributes
return {
CONF_WORKDAYS: self._workdays,
CONF_EXCLUDES: self._excludes,
CONF_OFFSET: self._days_offset,
} | [
"def",
"state_attributes",
"(",
"self",
")",
":",
"# return self._attributes",
"return",
"{",
"CONF_WORKDAYS",
":",
"self",
".",
"_workdays",
",",
"CONF_EXCLUDES",
":",
"self",
".",
"_excludes",
",",
"CONF_OFFSET",
":",
"self",
".",
"_days_offset",
",",
"}"
] | [
172,
4
] | [
179,
9
] | python | en | ['en', 'en', 'en'] | True |
IsWorkdaySensor.async_update | (self) | Get date and look whether it is a holiday. | Get date and look whether it is a holiday. | async def async_update(self):
"""Get date and look whether it is a holiday."""
# Default is no workday
self._state = False
# Get ISO day of the week (1 = Monday, 7 = Sunday)
date = get_date(datetime.today()) + timedelta(days=self._days_offset)
day = date.isoweekday() - 1
day_of_week = day_to_string(day)
if self.is_include(day_of_week, date):
self._state = True
if self.is_exclude(day_of_week, date):
self._state = False | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"# Default is no workday",
"self",
".",
"_state",
"=",
"False",
"# Get ISO day of the week (1 = Monday, 7 = Sunday)",
"date",
"=",
"get_date",
"(",
"datetime",
".",
"today",
"(",
")",
")",
"+",
"timedelta",
"(",
"days",
"=",
"self",
".",
"_days_offset",
")",
"day",
"=",
"date",
".",
"isoweekday",
"(",
")",
"-",
"1",
"day_of_week",
"=",
"day_to_string",
"(",
"day",
")",
"if",
"self",
".",
"is_include",
"(",
"day_of_week",
",",
"date",
")",
":",
"self",
".",
"_state",
"=",
"True",
"if",
"self",
".",
"is_exclude",
"(",
"day_of_week",
",",
"date",
")",
":",
"self",
".",
"_state",
"=",
"False"
] | [
181,
4
] | [
195,
31
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Mock a successful setup. | Mock a successful setup. | async def async_setup(hass, config):
"""Mock a successful setup."""
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"return",
"True"
] | [
6,
0
] | [
8,
15
] | python | en | ['en', 'ro', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up buienradar radar-loop camera component. | Set up buienradar radar-loop camera component. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up buienradar radar-loop camera component."""
dimension = config[CONF_DIMENSION]
delta = config[CONF_DELTA]
name = config[CONF_NAME]
country = config[CONF_COUNTRY]
async_add_entities([BuienradarCam(name, dimension, delta, country)]) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"dimension",
"=",
"config",
"[",
"CONF_DIMENSION",
"]",
"delta",
"=",
"config",
"[",
"CONF_DELTA",
"]",
"name",
"=",
"config",
"[",
"CONF_NAME",
"]",
"country",
"=",
"config",
"[",
"CONF_COUNTRY",
"]",
"async_add_entities",
"(",
"[",
"BuienradarCam",
"(",
"name",
",",
"dimension",
",",
"delta",
",",
"country",
")",
"]",
")"
] | [
41,
0
] | [
48,
72
] | python | ca | ['es', 'ca', 'en'] | False |
BuienradarCam.__init__ | (self, name: str, dimension: int, delta: float, country: str) |
Initialize the component.
This constructor must be run in the event loop.
|
Initialize the component. | def __init__(self, name: str, dimension: int, delta: float, country: str):
"""
Initialize the component.
This constructor must be run in the event loop.
"""
super().__init__()
self._name = name
# dimension (x and y) of returned radar image
self._dimension = dimension
# time a cached image stays valid for
self._delta = delta
# country location
self._country = country
# Condition that guards the loading indicator.
#
# Ensures that only one reader can cause an http request at the same
# time, and that all readers are notified after this request completes.
#
# invariant: this condition is private to and owned by this instance.
self._condition = asyncio.Condition()
self._last_image: Optional[bytes] = None
# value of the last seen last modified header
self._last_modified: Optional[str] = None
# loading status
self._loading = False
# deadline for image refresh - self.delta after last successful load
self._deadline: Optional[datetime] = None
self._unique_id = f"{self._dimension}_{self._country}" | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"dimension",
":",
"int",
",",
"delta",
":",
"float",
",",
"country",
":",
"str",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_name",
"=",
"name",
"# dimension (x and y) of returned radar image",
"self",
".",
"_dimension",
"=",
"dimension",
"# time a cached image stays valid for",
"self",
".",
"_delta",
"=",
"delta",
"# country location",
"self",
".",
"_country",
"=",
"country",
"# Condition that guards the loading indicator.",
"#",
"# Ensures that only one reader can cause an http request at the same",
"# time, and that all readers are notified after this request completes.",
"#",
"# invariant: this condition is private to and owned by this instance.",
"self",
".",
"_condition",
"=",
"asyncio",
".",
"Condition",
"(",
")",
"self",
".",
"_last_image",
":",
"Optional",
"[",
"bytes",
"]",
"=",
"None",
"# value of the last seen last modified header",
"self",
".",
"_last_modified",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
"# loading status",
"self",
".",
"_loading",
"=",
"False",
"# deadline for image refresh - self.delta after last successful load",
"self",
".",
"_deadline",
":",
"Optional",
"[",
"datetime",
"]",
"=",
"None",
"self",
".",
"_unique_id",
"=",
"f\"{self._dimension}_{self._country}\""
] | [
60,
4
] | [
95,
62
] | python | en | ['en', 'error', 'th'] | False |
BuienradarCam.name | (self) | Return the component name. | Return the component name. | def name(self) -> str:
"""Return the component name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_name"
] | [
98,
4
] | [
100,
25
] | python | en | ['en', 'en', 'en'] | True |
BuienradarCam.__retrieve_radar_image | (self) | Retrieve new radar image and return whether this succeeded. | Retrieve new radar image and return whether this succeeded. | async def __retrieve_radar_image(self) -> bool:
"""Retrieve new radar image and return whether this succeeded."""
session = async_get_clientsession(self.hass)
url = (
f"https://api.buienradar.nl/image/1.0/RadarMap{self._country}"
f"?w={self._dimension}&h={self._dimension}"
)
if self._last_modified:
headers = {"If-Modified-Since": self._last_modified}
else:
headers = {}
try:
async with session.get(url, timeout=5, headers=headers) as res:
res.raise_for_status()
if res.status == 304:
_LOGGER.debug("HTTP 304 - success")
return True
last_modified = res.headers.get("Last-Modified")
if last_modified:
self._last_modified = last_modified
self._last_image = await res.read()
_LOGGER.debug("HTTP 200 - Last-Modified: %s", last_modified)
return True
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Failed to fetch image, %s", type(err))
return False | [
"async",
"def",
"__retrieve_radar_image",
"(",
"self",
")",
"->",
"bool",
":",
"session",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
")",
"url",
"=",
"(",
"f\"https://api.buienradar.nl/image/1.0/RadarMap{self._country}\"",
"f\"?w={self._dimension}&h={self._dimension}\"",
")",
"if",
"self",
".",
"_last_modified",
":",
"headers",
"=",
"{",
"\"If-Modified-Since\"",
":",
"self",
".",
"_last_modified",
"}",
"else",
":",
"headers",
"=",
"{",
"}",
"try",
":",
"async",
"with",
"session",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"5",
",",
"headers",
"=",
"headers",
")",
"as",
"res",
":",
"res",
".",
"raise_for_status",
"(",
")",
"if",
"res",
".",
"status",
"==",
"304",
":",
"_LOGGER",
".",
"debug",
"(",
"\"HTTP 304 - success\"",
")",
"return",
"True",
"last_modified",
"=",
"res",
".",
"headers",
".",
"get",
"(",
"\"Last-Modified\"",
")",
"if",
"last_modified",
":",
"self",
".",
"_last_modified",
"=",
"last_modified",
"self",
".",
"_last_image",
"=",
"await",
"res",
".",
"read",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"HTTP 200 - Last-Modified: %s\"",
",",
"last_modified",
")",
"return",
"True",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"ClientError",
")",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed to fetch image, %s\"",
",",
"type",
"(",
"err",
")",
")",
"return",
"False"
] | [
108,
4
] | [
140,
24
] | python | en | ['en', 'en', 'en'] | True |
BuienradarCam.async_camera_image | (self) |
Return a still image response from the camera.
Uses ayncio conditions to make sure only one task enters the critical
section at the same time. Otherwise, two http requests would start
when two tabs with Home Assistant are open.
The condition is entered in two sections because otherwise the lock
would be held while doing the http request.
A boolean (_loading) is used to indicate the loading status instead of
_last_image since that is initialized to None.
For reference:
* :func:`asyncio.Condition.wait` releases the lock and acquires it
again before continuing.
* :func:`asyncio.Condition.notify_all` requires the lock to be held.
|
Return a still image response from the camera. | async def async_camera_image(self) -> Optional[bytes]:
"""
Return a still image response from the camera.
Uses ayncio conditions to make sure only one task enters the critical
section at the same time. Otherwise, two http requests would start
when two tabs with Home Assistant are open.
The condition is entered in two sections because otherwise the lock
would be held while doing the http request.
A boolean (_loading) is used to indicate the loading status instead of
_last_image since that is initialized to None.
For reference:
* :func:`asyncio.Condition.wait` releases the lock and acquires it
again before continuing.
* :func:`asyncio.Condition.notify_all` requires the lock to be held.
"""
if not self.__needs_refresh():
return self._last_image
# get lock, check iff loading, await notification if loading
async with self._condition:
# can not be tested - mocked http response returns immediately
if self._loading:
_LOGGER.debug("already loading - waiting for notification")
await self._condition.wait()
return self._last_image
# Set loading status **while holding lock**, makes other tasks wait
self._loading = True
try:
now = dt_util.utcnow()
was_updated = await self.__retrieve_radar_image()
# was updated? Set new deadline relative to now before loading
if was_updated:
self._deadline = now + timedelta(seconds=self._delta)
return self._last_image
finally:
# get lock, unset loading status, notify all waiting tasks
async with self._condition:
self._loading = False
self._condition.notify_all() | [
"async",
"def",
"async_camera_image",
"(",
"self",
")",
"->",
"Optional",
"[",
"bytes",
"]",
":",
"if",
"not",
"self",
".",
"__needs_refresh",
"(",
")",
":",
"return",
"self",
".",
"_last_image",
"# get lock, check iff loading, await notification if loading",
"async",
"with",
"self",
".",
"_condition",
":",
"# can not be tested - mocked http response returns immediately",
"if",
"self",
".",
"_loading",
":",
"_LOGGER",
".",
"debug",
"(",
"\"already loading - waiting for notification\"",
")",
"await",
"self",
".",
"_condition",
".",
"wait",
"(",
")",
"return",
"self",
".",
"_last_image",
"# Set loading status **while holding lock**, makes other tasks wait",
"self",
".",
"_loading",
"=",
"True",
"try",
":",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"was_updated",
"=",
"await",
"self",
".",
"__retrieve_radar_image",
"(",
")",
"# was updated? Set new deadline relative to now before loading",
"if",
"was_updated",
":",
"self",
".",
"_deadline",
"=",
"now",
"+",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"_delta",
")",
"return",
"self",
".",
"_last_image",
"finally",
":",
"# get lock, unset loading status, notify all waiting tasks",
"async",
"with",
"self",
".",
"_condition",
":",
"self",
".",
"_loading",
"=",
"False",
"self",
".",
"_condition",
".",
"notify_all",
"(",
")"
] | [
142,
4
] | [
187,
44
] | python | en | ['en', 'error', 'th'] | False |
BuienradarCam.unique_id | (self) | Return the unique id. | Return the unique id. | def unique_id(self):
"""Return the unique id."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
190,
4
] | [
192,
30
] | python | en | ['en', 'la', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Flexit Platform. | Set up the Flexit Platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Flexit Platform."""
modbus_slave = config.get(CONF_SLAVE)
name = config.get(CONF_NAME)
hub = hass.data[MODBUS_DOMAIN][config.get(CONF_HUB)]
add_entities([Flexit(hub, modbus_slave, name)], True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"modbus_slave",
"=",
"config",
".",
"get",
"(",
"CONF_SLAVE",
")",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"hub",
"=",
"hass",
".",
"data",
"[",
"MODBUS_DOMAIN",
"]",
"[",
"config",
".",
"get",
"(",
"CONF_HUB",
")",
"]",
"add_entities",
"(",
"[",
"Flexit",
"(",
"hub",
",",
"modbus_slave",
",",
"name",
")",
"]",
",",
"True",
")"
] | [
36,
0
] | [
41,
57
] | python | en | ['en', 'da', 'en'] | True |
Flexit.__init__ | (self, hub, modbus_slave, name) | Initialize the unit. | Initialize the unit. | def __init__(self, hub, modbus_slave, name):
"""Initialize the unit."""
self._hub = hub
self._name = name
self._slave = modbus_slave
self._target_temperature = None
self._current_temperature = None
self._current_fan_mode = None
self._current_operation = None
self._fan_modes = ["Off", "Low", "Medium", "High"]
self._current_operation = None
self._filter_hours = None
self._filter_alarm = None
self._heat_recovery = None
self._heater_enabled = False
self._heating = None
self._cooling = None
self._alarm = False
self.unit = pyflexit(hub, modbus_slave) | [
"def",
"__init__",
"(",
"self",
",",
"hub",
",",
"modbus_slave",
",",
"name",
")",
":",
"self",
".",
"_hub",
"=",
"hub",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_slave",
"=",
"modbus_slave",
"self",
".",
"_target_temperature",
"=",
"None",
"self",
".",
"_current_temperature",
"=",
"None",
"self",
".",
"_current_fan_mode",
"=",
"None",
"self",
".",
"_current_operation",
"=",
"None",
"self",
".",
"_fan_modes",
"=",
"[",
"\"Off\"",
",",
"\"Low\"",
",",
"\"Medium\"",
",",
"\"High\"",
"]",
"self",
".",
"_current_operation",
"=",
"None",
"self",
".",
"_filter_hours",
"=",
"None",
"self",
".",
"_filter_alarm",
"=",
"None",
"self",
".",
"_heat_recovery",
"=",
"None",
"self",
".",
"_heater_enabled",
"=",
"False",
"self",
".",
"_heating",
"=",
"None",
"self",
".",
"_cooling",
"=",
"None",
"self",
".",
"_alarm",
"=",
"False",
"self",
".",
"unit",
"=",
"pyflexit",
"(",
"hub",
",",
"modbus_slave",
")"
] | [
47,
4
] | [
65,
47
] | python | en | ['en', 'en', 'en'] | True |
Flexit.supported_features | (self) | Return the list of supported features. | Return the list of supported features. | def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_FLAGS"
] | [
68,
4
] | [
70,
28
] | python | en | ['en', 'en', 'en'] | True |
Flexit.update | (self) | Update unit attributes. | Update unit attributes. | def update(self):
"""Update unit attributes."""
if not self.unit.update():
_LOGGER.warning("Modbus read failed")
self._target_temperature = self.unit.get_target_temp
self._current_temperature = self.unit.get_temp
self._current_fan_mode = self._fan_modes[self.unit.get_fan_speed]
self._filter_hours = self.unit.get_filter_hours
# Mechanical heat recovery, 0-100%
self._heat_recovery = self.unit.get_heat_recovery
# Heater active 0-100%
self._heating = self.unit.get_heating
# Cooling active 0-100%
self._cooling = self.unit.get_cooling
# Filter alarm 0/1
self._filter_alarm = self.unit.get_filter_alarm
# Heater enabled or not. Does not mean it's necessarily heating
self._heater_enabled = self.unit.get_heater_enabled
# Current operation mode
self._current_operation = self.unit.get_operation | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"unit",
".",
"update",
"(",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Modbus read failed\"",
")",
"self",
".",
"_target_temperature",
"=",
"self",
".",
"unit",
".",
"get_target_temp",
"self",
".",
"_current_temperature",
"=",
"self",
".",
"unit",
".",
"get_temp",
"self",
".",
"_current_fan_mode",
"=",
"self",
".",
"_fan_modes",
"[",
"self",
".",
"unit",
".",
"get_fan_speed",
"]",
"self",
".",
"_filter_hours",
"=",
"self",
".",
"unit",
".",
"get_filter_hours",
"# Mechanical heat recovery, 0-100%",
"self",
".",
"_heat_recovery",
"=",
"self",
".",
"unit",
".",
"get_heat_recovery",
"# Heater active 0-100%",
"self",
".",
"_heating",
"=",
"self",
".",
"unit",
".",
"get_heating",
"# Cooling active 0-100%",
"self",
".",
"_cooling",
"=",
"self",
".",
"unit",
".",
"get_cooling",
"# Filter alarm 0/1",
"self",
".",
"_filter_alarm",
"=",
"self",
".",
"unit",
".",
"get_filter_alarm",
"# Heater enabled or not. Does not mean it's necessarily heating",
"self",
".",
"_heater_enabled",
"=",
"self",
".",
"unit",
".",
"get_heater_enabled",
"# Current operation mode",
"self",
".",
"_current_operation",
"=",
"self",
".",
"unit",
".",
"get_operation"
] | [
72,
4
] | [
92,
57
] | python | en | ['en', 'la', 'en'] | True |
Flexit.device_state_attributes | (self) | Return device specific state attributes. | Return device specific state attributes. | def device_state_attributes(self):
"""Return device specific state attributes."""
return {
"filter_hours": self._filter_hours,
"filter_alarm": self._filter_alarm,
"heat_recovery": self._heat_recovery,
"heating": self._heating,
"heater_enabled": self._heater_enabled,
"cooling": self._cooling,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"filter_hours\"",
":",
"self",
".",
"_filter_hours",
",",
"\"filter_alarm\"",
":",
"self",
".",
"_filter_alarm",
",",
"\"heat_recovery\"",
":",
"self",
".",
"_heat_recovery",
",",
"\"heating\"",
":",
"self",
".",
"_heating",
",",
"\"heater_enabled\"",
":",
"self",
".",
"_heater_enabled",
",",
"\"cooling\"",
":",
"self",
".",
"_cooling",
",",
"}"
] | [
95,
4
] | [
104,
9
] | python | en | ['fr', 'en', 'en'] | True |
Flexit.should_poll | (self) | Return the polling state. | Return the polling state. | def should_poll(self):
"""Return the polling state."""
return True | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"True"
] | [
107,
4
] | [
109,
19
] | python | en | ['en', 'en', 'en'] | True |
Flexit.name | (self) | Return the name of the climate device. | Return the name of the climate device. | def name(self):
"""Return the name of the climate device."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
112,
4
] | [
114,
25
] | python | en | ['en', 'en', 'en'] | True |
Flexit.temperature_unit | (self) | Return the unit of measurement. | Return the unit of measurement. | def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_CELSIUS"
] | [
117,
4
] | [
119,
27
] | python | en | ['en', 'la', 'en'] | True |
Flexit.current_temperature | (self) | Return the current temperature. | Return the current temperature. | def current_temperature(self):
"""Return the current temperature."""
return self._current_temperature | [
"def",
"current_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_current_temperature"
] | [
122,
4
] | [
124,
40
] | python | en | ['en', 'la', 'en'] | True |
Flexit.target_temperature | (self) | Return the temperature we try to reach. | Return the temperature we try to reach. | def target_temperature(self):
"""Return the temperature we try to reach."""
return self._target_temperature | [
"def",
"target_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_target_temperature"
] | [
127,
4
] | [
129,
39
] | python | en | ['en', 'en', 'en'] | True |
Flexit.hvac_mode | (self) | Return current operation ie. heat, cool, idle. | Return current operation ie. heat, cool, idle. | def hvac_mode(self):
"""Return current operation ie. heat, cool, idle."""
return self._current_operation | [
"def",
"hvac_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_current_operation"
] | [
132,
4
] | [
134,
38
] | python | en | ['nl', 'en', 'en'] | True |
Flexit.hvac_modes | (self) | Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
| Return the list of available hvac operation modes. | def hvac_modes(self) -> List[str]:
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
return [HVAC_MODE_COOL] | [
"def",
"hvac_modes",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"HVAC_MODE_COOL",
"]"
] | [
137,
4
] | [
142,
31
] | python | en | ['en', 'en', 'en'] | True |
Flexit.fan_mode | (self) | Return the fan setting. | Return the fan setting. | def fan_mode(self):
"""Return the fan setting."""
return self._current_fan_mode | [
"def",
"fan_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_current_fan_mode"
] | [
145,
4
] | [
147,
37
] | python | en | ['en', 'fy', 'en'] | True |
Flexit.fan_modes | (self) | Return the list of available fan modes. | Return the list of available fan modes. | def fan_modes(self):
"""Return the list of available fan modes."""
return self._fan_modes | [
"def",
"fan_modes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_fan_modes"
] | [
150,
4
] | [
152,
30
] | python | en | ['en', 'en', 'en'] | True |
Flexit.set_temperature | (self, **kwargs) | Set new target temperature. | Set new target temperature. | def set_temperature(self, **kwargs):
"""Set new target temperature."""
if kwargs.get(ATTR_TEMPERATURE) is not None:
self._target_temperature = kwargs.get(ATTR_TEMPERATURE)
self.unit.set_temp(self._target_temperature) | [
"def",
"set_temperature",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"is",
"not",
"None",
":",
"self",
".",
"_target_temperature",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"self",
".",
"unit",
".",
"set_temp",
"(",
"self",
".",
"_target_temperature",
")"
] | [
154,
4
] | [
158,
52
] | python | en | ['en', 'ca', 'en'] | True |
Flexit.set_fan_mode | (self, fan_mode) | Set new fan mode. | Set new fan mode. | def set_fan_mode(self, fan_mode):
"""Set new fan mode."""
self.unit.set_fan_speed(self._fan_modes.index(fan_mode)) | [
"def",
"set_fan_mode",
"(",
"self",
",",
"fan_mode",
")",
":",
"self",
".",
"unit",
".",
"set_fan_speed",
"(",
"self",
".",
"_fan_modes",
".",
"index",
"(",
"fan_mode",
")",
")"
] | [
160,
4
] | [
162,
64
] | python | en | ['id', 'fy', 'en'] | False |
conv3x3 | (in_planes, out_planes, stride=1) | 3x3 convolution with padding | 3x3 convolution with padding | def conv3x3(in_planes, out_planes, stride=1):
" 3x3 convolution with padding "
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"bias",
"=",
"False",
")"
] | [
14,
0
] | [
16,
96
] | python | en | ['en', 'ja', 'en'] | True |
_CrossNeuronBlock.forward | (self, x) |
:param x: (bt, c, h, w)
:return:
|
:param x: (bt, c, h, w)
:return:
| def forward(self, x):
'''
:param x: (bt, c, h, w)
:return:
'''
bt, c, h, w = x.shape
residual = x
x_stretch = x.view(bt, c, h * w)
spblock_h = int(np.ceil(h / self.spatial_height))
spblock_w = int(np.ceil(w / self.spatial_width))
stride_h = int((h - self.spatial_height) / (spblock_h - 1)) if spblock_h > 1 else 0
stride_w = int((w - self.spatial_width) / (spblock_w - 1)) if spblock_w > 1 else 0
if self.spatial_height == h and self.spatial_width == w:
x_stacked = x_stretch # (b) x c x (h * w)
x_stacked = x_stacked.view(bt * self.nblocks_channel, c // self.nblocks_channel, -1)
x_v = x_stacked.permute(0, 2, 1).contiguous() # (b) x (h * w) x c
if self.enc_dec:
x_v = self.fc_in(x_v) # (b) x (h * w) x c
x_m = x_v.mean(1).view(-1, 1, c // self.nblocks_channel) # (b * h * w) x 1 x c
score = -(x_m - x_m.permute(0, 2, 1).contiguous())**2 # (b * h * w) x c x c
# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)
# x_v = F.dropout(x_v, 0.1, self.training)
# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)
attn = F.softmax(score, dim=1) # (b * h * w) x c x c
if self.communication:
if self.enc_dec:
out = self.bn(self.fc_out(torch.bmm(x_v, attn))) # (b) x (h * w) x c
else:
out = self.bn(torch.bmm(x_v, attn)) # (b) x (h * w) x c
else:
out = self.bn(self.fc_out(x_v)) # (b) x (h * w) x c
out = out.permute(0, 2, 1).contiguous().view(bt, c, h, w)
return (residual + out)
else:
x = F.interpolate(x, (self.spatial_height, self.spatial_width))
x_stretch = x.view(bt, c, self.spatial_height * self.spatial_width)
x_stretch = x.view(bt * self.nblocks_channel, c // self.nblocks_channel, self.spatial_height * self.spatial_width)
x_stacked = x_stretch # (b) x c x (h * w)
x_v = x_stacked.permute(0, 2, 1).contiguous() # (b) x (h * w) x c
if self.enc_dec:
x_v = self.fc_in(x_v) # (b) x (h * w) x c
x_m = x_v.mean(1).view(-1, 1, c // self.nblocks_channel) # (b * h * w) x 1 x c
score = -(x_m - x_m.permute(0, 2, 1).contiguous())**2 # (b * h * w) x c x c
# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)
# x_v = F.dropout(x_v, 0.1, self.training)
# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)
attn = F.softmax(score, dim=1) # (b * h * w) x c x c
if self.communication:
if self.enc_dec:
out = self.bn(self.fc_out(torch.bmm(x_v, attn))) # (b) x (h * w) x c
else:
out = self.bn(torch.bmm(x_v, attn)) # (b) x (h * w) x c
else:
out = self.bn(self.fc_out(x_v)) # (b) x (h * w) x c
out = out.permute(0, 2, 1).contiguous().view(bt, c, self.spatial_height, self.spatial_width)
out = F.interpolate(out, (h, w))
return (residual + out) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"bt",
",",
"c",
",",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"residual",
"=",
"x",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
",",
"c",
",",
"h",
"*",
"w",
")",
"spblock_h",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"h",
"/",
"self",
".",
"spatial_height",
")",
")",
"spblock_w",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"w",
"/",
"self",
".",
"spatial_width",
")",
")",
"stride_h",
"=",
"int",
"(",
"(",
"h",
"-",
"self",
".",
"spatial_height",
")",
"/",
"(",
"spblock_h",
"-",
"1",
")",
")",
"if",
"spblock_h",
">",
"1",
"else",
"0",
"stride_w",
"=",
"int",
"(",
"(",
"w",
"-",
"self",
".",
"spatial_width",
")",
"/",
"(",
"spblock_w",
"-",
"1",
")",
")",
"if",
"spblock_w",
">",
"1",
"else",
"0",
"if",
"self",
".",
"spatial_height",
"==",
"h",
"and",
"self",
".",
"spatial_width",
"==",
"w",
":",
"x_stacked",
"=",
"x_stretch",
"# (b) x c x (h * w)",
"x_stacked",
"=",
"x_stacked",
".",
"view",
"(",
"bt",
"*",
"self",
".",
"nblocks_channel",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
",",
"-",
"1",
")",
"x_v",
"=",
"x_stacked",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
"# (b) x (h * w) x c",
"if",
"self",
".",
"enc_dec",
":",
"x_v",
"=",
"self",
".",
"fc_in",
"(",
"x_v",
")",
"# (b) x (h * w) x c",
"x_m",
"=",
"x_v",
".",
"mean",
"(",
"1",
")",
".",
"view",
"(",
"-",
"1",
",",
"1",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
")",
"# (b * h * w) x 1 x c",
"score",
"=",
"-",
"(",
"x_m",
"-",
"x_m",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
")",
"**",
"2",
"# (b * h * w) x c x c",
"# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)",
"# x_v = F.dropout(x_v, 0.1, self.training)",
"# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)",
"attn",
"=",
"F",
".",
"softmax",
"(",
"score",
",",
"dim",
"=",
"1",
")",
"# (b * h * w) x c x c",
"if",
"self",
".",
"communication",
":",
"if",
"self",
".",
"enc_dec",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"x_v",
")",
")",
"# (b) x (h * w) x c",
"out",
"=",
"out",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"bt",
",",
"c",
",",
"h",
",",
"w",
")",
"return",
"(",
"residual",
"+",
"out",
")",
"else",
":",
"x",
"=",
"F",
".",
"interpolate",
"(",
"x",
",",
"(",
"self",
".",
"spatial_height",
",",
"self",
".",
"spatial_width",
")",
")",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
",",
"c",
",",
"self",
".",
"spatial_height",
"*",
"self",
".",
"spatial_width",
")",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
"*",
"self",
".",
"nblocks_channel",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
",",
"self",
".",
"spatial_height",
"*",
"self",
".",
"spatial_width",
")",
"x_stacked",
"=",
"x_stretch",
"# (b) x c x (h * w)",
"x_v",
"=",
"x_stacked",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
"# (b) x (h * w) x c",
"if",
"self",
".",
"enc_dec",
":",
"x_v",
"=",
"self",
".",
"fc_in",
"(",
"x_v",
")",
"# (b) x (h * w) x c",
"x_m",
"=",
"x_v",
".",
"mean",
"(",
"1",
")",
".",
"view",
"(",
"-",
"1",
",",
"1",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
")",
"# (b * h * w) x 1 x c",
"score",
"=",
"-",
"(",
"x_m",
"-",
"x_m",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
")",
"**",
"2",
"# (b * h * w) x c x c",
"# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)",
"# x_v = F.dropout(x_v, 0.1, self.training)",
"# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)",
"attn",
"=",
"F",
".",
"softmax",
"(",
"score",
",",
"dim",
"=",
"1",
")",
"# (b * h * w) x c x c",
"if",
"self",
".",
"communication",
":",
"if",
"self",
".",
"enc_dec",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"x_v",
")",
")",
"# (b) x (h * w) x c",
"out",
"=",
"out",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"bt",
",",
"c",
",",
"self",
".",
"spatial_height",
",",
"self",
".",
"spatial_width",
")",
"out",
"=",
"F",
".",
"interpolate",
"(",
"out",
",",
"(",
"h",
",",
"w",
")",
")",
"return",
"(",
"residual",
"+",
"out",
")"
] | [
77,
4
] | [
141,
35
] | python | en | ['en', 'error', 'th'] | False |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the Zigbee Home Automation cover from config entry. | Set up the Zigbee Home Automation cover from config entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Zigbee Home Automation cover from config entry."""
entities_to_create = hass.data[DATA_ZHA][DOMAIN]
unsub = async_dispatcher_connect(
hass,
SIGNAL_ADD_ENTITIES,
functools.partial(
discovery.async_add_entities, async_add_entities, entities_to_create
),
)
hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"entities_to_create",
"=",
"hass",
".",
"data",
"[",
"DATA_ZHA",
"]",
"[",
"DOMAIN",
"]",
"unsub",
"=",
"async_dispatcher_connect",
"(",
"hass",
",",
"SIGNAL_ADD_ENTITIES",
",",
"functools",
".",
"partial",
"(",
"discovery",
".",
"async_add_entities",
",",
"async_add_entities",
",",
"entities_to_create",
")",
",",
")",
"hass",
".",
"data",
"[",
"DATA_ZHA",
"]",
"[",
"DATA_ZHA_DISPATCHERS",
"]",
".",
"append",
"(",
"unsub",
")"
] | [
41,
0
] | [
52,
59
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Seven segments OCR platform. | Set up the Seven segments OCR platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Seven segments OCR platform."""
entities = []
for camera in config[CONF_SOURCE]:
entities.append(
ImageProcessingSsocr(
hass, camera[CONF_ENTITY_ID], config, camera.get(CONF_NAME)
)
)
async_add_entities(entities) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"entities",
"=",
"[",
"]",
"for",
"camera",
"in",
"config",
"[",
"CONF_SOURCE",
"]",
":",
"entities",
".",
"append",
"(",
"ImageProcessingSsocr",
"(",
"hass",
",",
"camera",
"[",
"CONF_ENTITY_ID",
"]",
",",
"config",
",",
"camera",
".",
"get",
"(",
"CONF_NAME",
")",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
48,
0
] | [
58,
32
] | python | en | ['en', 'ca', 'en'] | True |
ImageProcessingSsocr.__init__ | (self, hass, camera_entity, config, name) | Initialize seven segments processing. | Initialize seven segments processing. | def __init__(self, hass, camera_entity, config, name):
"""Initialize seven segments processing."""
self.hass = hass
self._camera_entity = camera_entity
if name:
self._name = name
else:
self._name = "SevenSegment OCR {}".format(split_entity_id(camera_entity)[1])
self._state = None
self.filepath = os.path.join(
self.hass.config.config_dir,
"ssocr-{}.png".format(self._name.replace(" ", "_")),
)
crop = [
"crop",
str(config[CONF_X_POS]),
str(config[CONF_Y_POS]),
str(config[CONF_WIDTH]),
str(config[CONF_HEIGHT]),
]
digits = ["-d", str(config.get(CONF_DIGITS, -1))]
rotate = ["rotate", str(config[CONF_ROTATE])]
threshold = ["-t", str(config[CONF_THRESHOLD])]
extra_arguments = config[CONF_EXTRA_ARGUMENTS].split(" ")
self._command = (
[config[CONF_SSOCR_BIN]]
+ crop
+ digits
+ threshold
+ rotate
+ extra_arguments
)
self._command.append(self.filepath) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"camera_entity",
",",
"config",
",",
"name",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"_camera_entity",
"=",
"camera_entity",
"if",
"name",
":",
"self",
".",
"_name",
"=",
"name",
"else",
":",
"self",
".",
"_name",
"=",
"\"SevenSegment OCR {}\"",
".",
"format",
"(",
"split_entity_id",
"(",
"camera_entity",
")",
"[",
"1",
"]",
")",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"hass",
".",
"config",
".",
"config_dir",
",",
"\"ssocr-{}.png\"",
".",
"format",
"(",
"self",
".",
"_name",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
")",
",",
")",
"crop",
"=",
"[",
"\"crop\"",
",",
"str",
"(",
"config",
"[",
"CONF_X_POS",
"]",
")",
",",
"str",
"(",
"config",
"[",
"CONF_Y_POS",
"]",
")",
",",
"str",
"(",
"config",
"[",
"CONF_WIDTH",
"]",
")",
",",
"str",
"(",
"config",
"[",
"CONF_HEIGHT",
"]",
")",
",",
"]",
"digits",
"=",
"[",
"\"-d\"",
",",
"str",
"(",
"config",
".",
"get",
"(",
"CONF_DIGITS",
",",
"-",
"1",
")",
")",
"]",
"rotate",
"=",
"[",
"\"rotate\"",
",",
"str",
"(",
"config",
"[",
"CONF_ROTATE",
"]",
")",
"]",
"threshold",
"=",
"[",
"\"-t\"",
",",
"str",
"(",
"config",
"[",
"CONF_THRESHOLD",
"]",
")",
"]",
"extra_arguments",
"=",
"config",
"[",
"CONF_EXTRA_ARGUMENTS",
"]",
".",
"split",
"(",
"\" \"",
")",
"self",
".",
"_command",
"=",
"(",
"[",
"config",
"[",
"CONF_SSOCR_BIN",
"]",
"]",
"+",
"crop",
"+",
"digits",
"+",
"threshold",
"+",
"rotate",
"+",
"extra_arguments",
")",
"self",
".",
"_command",
".",
"append",
"(",
"self",
".",
"filepath",
")"
] | [
64,
4
] | [
98,
43
] | python | en | ['no', 'en', 'en'] | True |
ImageProcessingSsocr.device_class | (self) | Return the class of this device, from component DEVICE_CLASSES. | Return the class of this device, from component DEVICE_CLASSES. | def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return "ocr" | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"\"ocr\""
] | [
101,
4
] | [
103,
20
] | python | en | ['en', 'en', 'en'] | True |
ImageProcessingSsocr.camera_entity | (self) | Return camera entity id from process pictures. | Return camera entity id from process pictures. | def camera_entity(self):
"""Return camera entity id from process pictures."""
return self._camera_entity | [
"def",
"camera_entity",
"(",
"self",
")",
":",
"return",
"self",
".",
"_camera_entity"
] | [
106,
4
] | [
108,
34
] | python | en | ['en', 'en', 'en'] | True |
ImageProcessingSsocr.name | (self) | Return the name of the image processor. | Return the name of the image processor. | def name(self):
"""Return the name of the image processor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
111,
4
] | [
113,
25
] | python | en | ['en', 'en', 'en'] | True |
ImageProcessingSsocr.state | (self) | Return the state of the entity. | Return the state of the entity. | def state(self):
"""Return the state of the entity."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
116,
4
] | [
118,
26
] | python | en | ['en', 'en', 'en'] | True |
ImageProcessingSsocr.process_image | (self, image) | Process the image. | Process the image. | def process_image(self, image):
"""Process the image."""
stream = io.BytesIO(image)
img = Image.open(stream)
img.save(self.filepath, "png")
ocr = subprocess.Popen(
self._command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out = ocr.communicate()
if out[0] != b"":
self._state = out[0].strip().decode("utf-8")
else:
self._state = None
_LOGGER.warning(
"Unable to detect value: %s", out[1].strip().decode("utf-8")
) | [
"def",
"process_image",
"(",
"self",
",",
"image",
")",
":",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
"image",
")",
"img",
"=",
"Image",
".",
"open",
"(",
"stream",
")",
"img",
".",
"save",
"(",
"self",
".",
"filepath",
",",
"\"png\"",
")",
"ocr",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"_command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
"=",
"ocr",
".",
"communicate",
"(",
")",
"if",
"out",
"[",
"0",
"]",
"!=",
"b\"\"",
":",
"self",
".",
"_state",
"=",
"out",
"[",
"0",
"]",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"self",
".",
"_state",
"=",
"None",
"_LOGGER",
".",
"warning",
"(",
"\"Unable to detect value: %s\"",
",",
"out",
"[",
"1",
"]",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
")"
] | [
120,
4
] | [
136,
13
] | python | en | ['en', 'en', 'en'] | True |
load_tf_weights_in_gpt2 | (model, config, gpt2_checkpoint_path) | Load tf checkpoints in a pytorch model | Load tf checkpoints in a pytorch model | def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
"""Load tf checkpoints in a pytorch model"""
try:
import re
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(gpt2_checkpoint_path)
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info("Loading TF weight {} with shape {}".format(name, shape))
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array.squeeze())
for name, array in zip(names, arrays):
name = name[6:] # skip "model/"
name = name.split("/")
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+\d+", m_name):
scope_names = re.split(r"(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "w" or scope_names[0] == "g":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "b":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "wpe" or scope_names[0] == "wte":
pointer = getattr(pointer, scope_names[0])
pointer = getattr(pointer, "weight")
else:
pointer = getattr(pointer, scope_names[0])
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info("Initialize PyTorch weight {}".format(name))
pointer.data = torch.from_numpy(array)
return model | [
"def",
"load_tf_weights_in_gpt2",
"(",
"model",
",",
"config",
",",
"gpt2_checkpoint_path",
")",
":",
"try",
":",
"import",
"re",
"import",
"tensorflow",
"as",
"tf",
"except",
"ImportError",
":",
"logger",
".",
"error",
"(",
"\"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"",
"\"https://www.tensorflow.org/install/ for installation instructions.\"",
")",
"raise",
"tf_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"gpt2_checkpoint_path",
")",
"logger",
".",
"info",
"(",
"\"Converting TensorFlow checkpoint from {}\"",
".",
"format",
"(",
"tf_path",
")",
")",
"# Load weights from TF model",
"init_vars",
"=",
"tf",
".",
"train",
".",
"list_variables",
"(",
"tf_path",
")",
"names",
"=",
"[",
"]",
"arrays",
"=",
"[",
"]",
"for",
"name",
",",
"shape",
"in",
"init_vars",
":",
"logger",
".",
"info",
"(",
"\"Loading TF weight {} with shape {}\"",
".",
"format",
"(",
"name",
",",
"shape",
")",
")",
"array",
"=",
"tf",
".",
"train",
".",
"load_variable",
"(",
"tf_path",
",",
"name",
")",
"names",
".",
"append",
"(",
"name",
")",
"arrays",
".",
"append",
"(",
"array",
".",
"squeeze",
"(",
")",
")",
"for",
"name",
",",
"array",
"in",
"zip",
"(",
"names",
",",
"arrays",
")",
":",
"name",
"=",
"name",
"[",
"6",
":",
"]",
"# skip \"model/\"",
"name",
"=",
"name",
".",
"split",
"(",
"\"/\"",
")",
"pointer",
"=",
"model",
"for",
"m_name",
"in",
"name",
":",
"if",
"re",
".",
"fullmatch",
"(",
"r\"[A-Za-z]+\\d+\"",
",",
"m_name",
")",
":",
"scope_names",
"=",
"re",
".",
"split",
"(",
"r\"(\\d+)\"",
",",
"m_name",
")",
"else",
":",
"scope_names",
"=",
"[",
"m_name",
"]",
"if",
"scope_names",
"[",
"0",
"]",
"==",
"\"w\"",
"or",
"scope_names",
"[",
"0",
"]",
"==",
"\"g\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"weight\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"b\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"bias\"",
")",
"elif",
"scope_names",
"[",
"0",
"]",
"==",
"\"wpe\"",
"or",
"scope_names",
"[",
"0",
"]",
"==",
"\"wte\"",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"scope_names",
"[",
"0",
"]",
")",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"\"weight\"",
")",
"else",
":",
"pointer",
"=",
"getattr",
"(",
"pointer",
",",
"scope_names",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"scope_names",
")",
">=",
"2",
":",
"num",
"=",
"int",
"(",
"scope_names",
"[",
"1",
"]",
")",
"pointer",
"=",
"pointer",
"[",
"num",
"]",
"try",
":",
"assert",
"(",
"pointer",
".",
"shape",
"==",
"array",
".",
"shape",
")",
",",
"f\"Pointer shape {pointer.shape} and array shape {array.shape} mismatched\"",
"except",
"AssertionError",
"as",
"e",
":",
"e",
".",
"args",
"+=",
"(",
"pointer",
".",
"shape",
",",
"array",
".",
"shape",
")",
"raise",
"logger",
".",
"info",
"(",
"\"Initialize PyTorch weight {}\"",
".",
"format",
"(",
"name",
")",
")",
"pointer",
".",
"data",
"=",
"torch",
".",
"from_numpy",
"(",
"array",
")",
"return",
"model"
] | [
67,
0
] | [
121,
16
] | python | en | ['en', 'en', 'en'] | True |
GPT2PreTrainedModel._init_weights | (self, module) | Initialize the weights. | Initialize the weights. | def _init_weights(self, module):
"""Initialize the weights."""
if isinstance(module, (nn.Linear, Conv1D)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0) | [
"def",
"_init_weights",
"(",
"self",
",",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"(",
"nn",
".",
"Linear",
",",
"Conv1D",
")",
")",
":",
"# Slightly different from the TF version which uses truncated_normal for initialization",
"# cf https://github.com/pytorch/pytorch/pull/5617",
"module",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"self",
".",
"config",
".",
"initializer_range",
")",
"if",
"module",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"elif",
"isinstance",
"(",
"module",
",",
"nn",
".",
"Embedding",
")",
":",
"module",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"self",
".",
"config",
".",
"initializer_range",
")",
"if",
"module",
".",
"padding_idx",
"is",
"not",
"None",
":",
"module",
".",
"weight",
".",
"data",
"[",
"module",
".",
"padding_idx",
"]",
".",
"zero_",
"(",
")",
"elif",
"isinstance",
"(",
"module",
",",
"nn",
".",
"LayerNorm",
")",
":",
"module",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"module",
".",
"weight",
".",
"data",
".",
"fill_",
"(",
"1.0",
")"
] | [
346,
4
] | [
360,
41
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Philips TV platform. | Set up the Philips TV platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Philips TV platform."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
api_version = config.get(CONF_API_VERSION)
turn_on_action = config.get(CONF_ON_ACTION)
tvapi = PhilipsTV(host, api_version)
domain = __name__.split(".")[-2]
on_script = Script(hass, turn_on_action, name, domain) if turn_on_action else None
add_entities([PhilipsTVMediaPlayer(tvapi, name, on_script)]) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"host",
"=",
"config",
".",
"get",
"(",
"CONF_HOST",
")",
"api_version",
"=",
"config",
".",
"get",
"(",
"CONF_API_VERSION",
")",
"turn_on_action",
"=",
"config",
".",
"get",
"(",
"CONF_ON_ACTION",
")",
"tvapi",
"=",
"PhilipsTV",
"(",
"host",
",",
"api_version",
")",
"domain",
"=",
"__name__",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"2",
"]",
"on_script",
"=",
"Script",
"(",
"hass",
",",
"turn_on_action",
",",
"name",
",",
"domain",
")",
"if",
"turn_on_action",
"else",
"None",
"add_entities",
"(",
"[",
"PhilipsTVMediaPlayer",
"(",
"tvapi",
",",
"name",
",",
"on_script",
")",
"]",
")"
] | [
81,
0
] | [
92,
64
] | python | en | ['en', 'da', 'en'] | True |
PhilipsTVMediaPlayer.__init__ | (self, tv: PhilipsTV, name: str, on_script: Script) | Initialize the Philips TV. | Initialize the Philips TV. | def __init__(self, tv: PhilipsTV, name: str, on_script: Script):
"""Initialize the Philips TV."""
self._tv = tv
self._name = name
self._sources = {}
self._channels = {}
self._on_script = on_script
self._supports = SUPPORT_PHILIPS_JS
if self._on_script:
self._supports |= SUPPORT_TURN_ON
self._update_task = None | [
"def",
"__init__",
"(",
"self",
",",
"tv",
":",
"PhilipsTV",
",",
"name",
":",
"str",
",",
"on_script",
":",
"Script",
")",
":",
"self",
".",
"_tv",
"=",
"tv",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_sources",
"=",
"{",
"}",
"self",
".",
"_channels",
"=",
"{",
"}",
"self",
".",
"_on_script",
"=",
"on_script",
"self",
".",
"_supports",
"=",
"SUPPORT_PHILIPS_JS",
"if",
"self",
".",
"_on_script",
":",
"self",
".",
"_supports",
"|=",
"SUPPORT_TURN_ON",
"self",
".",
"_update_task",
"=",
"None"
] | [
98,
4
] | [
108,
32
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer._update_soon | (self, delay) | Reschedule update task. | Reschedule update task. | def _update_soon(self, delay):
"""Reschedule update task."""
if self._update_task:
self._update_task()
self._update_task = None
self.schedule_update_ha_state(force_refresh=False)
def update_forced(event_time):
self.schedule_update_ha_state(force_refresh=True)
def update_and_restart(event_time):
update_forced(event_time)
self._update_task = track_time_interval(
self.hass, update_forced, timedelta(seconds=DEFAULT_SCAN_INTERVAL)
)
call_later(self.hass, delay, update_and_restart) | [
"def",
"_update_soon",
"(",
"self",
",",
"delay",
")",
":",
"if",
"self",
".",
"_update_task",
":",
"self",
".",
"_update_task",
"(",
")",
"self",
".",
"_update_task",
"=",
"None",
"self",
".",
"schedule_update_ha_state",
"(",
"force_refresh",
"=",
"False",
")",
"def",
"update_forced",
"(",
"event_time",
")",
":",
"self",
".",
"schedule_update_ha_state",
"(",
"force_refresh",
"=",
"True",
")",
"def",
"update_and_restart",
"(",
"event_time",
")",
":",
"update_forced",
"(",
"event_time",
")",
"self",
".",
"_update_task",
"=",
"track_time_interval",
"(",
"self",
".",
"hass",
",",
"update_forced",
",",
"timedelta",
"(",
"seconds",
"=",
"DEFAULT_SCAN_INTERVAL",
")",
")",
"call_later",
"(",
"self",
".",
"hass",
",",
"delay",
",",
"update_and_restart",
")"
] | [
110,
4
] | [
127,
56
] | python | de | ['de', 'nl', 'en'] | False |
PhilipsTVMediaPlayer.async_added_to_hass | (self) | Start running updates once we are added to hass. | Start running updates once we are added to hass. | async def async_added_to_hass(self):
"""Start running updates once we are added to hass."""
await self.hass.async_add_executor_job(self._update_soon, 0) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_update_soon",
",",
"0",
")"
] | [
129,
4
] | [
131,
68
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.name | (self) | Return the device name. | Return the device name. | def name(self):
"""Return the device name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
134,
4
] | [
136,
25
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.should_poll | (self) | Device should be polled. | Device should be polled. | def should_poll(self):
"""Device should be polled."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
139,
4
] | [
141,
20
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.supported_features | (self) | Flag media player features that are supported. | Flag media player features that are supported. | def supported_features(self):
"""Flag media player features that are supported."""
return self._supports | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"self",
".",
"_supports"
] | [
144,
4
] | [
146,
29
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.state | (self) | Get the device state. An exception means OFF state. | Get the device state. An exception means OFF state. | def state(self):
"""Get the device state. An exception means OFF state."""
if self._tv.on:
return STATE_ON
return STATE_OFF | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tv",
".",
"on",
":",
"return",
"STATE_ON",
"return",
"STATE_OFF"
] | [
149,
4
] | [
153,
24
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.source | (self) | Return the current input source. | Return the current input source. | def source(self):
"""Return the current input source."""
return self._sources.get(self._tv.source_id) | [
"def",
"source",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sources",
".",
"get",
"(",
"self",
".",
"_tv",
".",
"source_id",
")"
] | [
156,
4
] | [
158,
52
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.source_list | (self) | List of available input sources. | List of available input sources. | def source_list(self):
"""List of available input sources."""
return list(self._sources.values()) | [
"def",
"source_list",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_sources",
".",
"values",
"(",
")",
")"
] | [
161,
4
] | [
163,
43
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.select_source | (self, source) | Set the input source. | Set the input source. | def select_source(self, source):
"""Set the input source."""
data = source.split(PREFIX_SEPARATOR, 1)
if data[0] == PREFIX_SOURCE: # Legacy way to set source
source_id = _inverted(self._sources).get(data[1])
if source_id:
self._tv.setSource(source_id)
elif data[0] == PREFIX_CHANNEL: # Legacy way to set channel
channel_id = _inverted(self._channels).get(data[1])
if channel_id:
self._tv.setChannel(channel_id)
else:
source_id = _inverted(self._sources).get(source)
if source_id:
self._tv.setSource(source_id)
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"select_source",
"(",
"self",
",",
"source",
")",
":",
"data",
"=",
"source",
".",
"split",
"(",
"PREFIX_SEPARATOR",
",",
"1",
")",
"if",
"data",
"[",
"0",
"]",
"==",
"PREFIX_SOURCE",
":",
"# Legacy way to set source",
"source_id",
"=",
"_inverted",
"(",
"self",
".",
"_sources",
")",
".",
"get",
"(",
"data",
"[",
"1",
"]",
")",
"if",
"source_id",
":",
"self",
".",
"_tv",
".",
"setSource",
"(",
"source_id",
")",
"elif",
"data",
"[",
"0",
"]",
"==",
"PREFIX_CHANNEL",
":",
"# Legacy way to set channel",
"channel_id",
"=",
"_inverted",
"(",
"self",
".",
"_channels",
")",
".",
"get",
"(",
"data",
"[",
"1",
"]",
")",
"if",
"channel_id",
":",
"self",
".",
"_tv",
".",
"setChannel",
"(",
"channel_id",
")",
"else",
":",
"source_id",
"=",
"_inverted",
"(",
"self",
".",
"_sources",
")",
".",
"get",
"(",
"source",
")",
"if",
"source_id",
":",
"self",
".",
"_tv",
".",
"setSource",
"(",
"source_id",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
165,
4
] | [
180,
47
] | python | en | ['en', 'su', 'en'] | True |
PhilipsTVMediaPlayer.volume_level | (self) | Volume level of the media player (0..1). | Volume level of the media player (0..1). | def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._tv.volume | [
"def",
"volume_level",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tv",
".",
"volume"
] | [
183,
4
] | [
185,
30
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.is_volume_muted | (self) | Boolean if volume is currently muted. | Boolean if volume is currently muted. | def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._tv.muted | [
"def",
"is_volume_muted",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tv",
".",
"muted"
] | [
188,
4
] | [
190,
29
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.turn_on | (self) | Turn on the device. | Turn on the device. | def turn_on(self):
"""Turn on the device."""
if self._on_script:
self._on_script.run(context=self._context)
self._update_soon(DELAY_ACTION_ON) | [
"def",
"turn_on",
"(",
"self",
")",
":",
"if",
"self",
".",
"_on_script",
":",
"self",
".",
"_on_script",
".",
"run",
"(",
"context",
"=",
"self",
".",
"_context",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_ON",
")"
] | [
192,
4
] | [
196,
46
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.turn_off | (self) | Turn off the device. | Turn off the device. | def turn_off(self):
"""Turn off the device."""
self._tv.sendKey("Standby")
self._tv.on = False
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"turn_off",
"(",
"self",
")",
":",
"self",
".",
"_tv",
".",
"sendKey",
"(",
"\"Standby\"",
")",
"self",
".",
"_tv",
".",
"on",
"=",
"False",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
198,
4
] | [
202,
47
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.volume_up | (self) | Send volume up command. | Send volume up command. | def volume_up(self):
"""Send volume up command."""
self._tv.sendKey("VolumeUp")
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"volume_up",
"(",
"self",
")",
":",
"self",
".",
"_tv",
".",
"sendKey",
"(",
"\"VolumeUp\"",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
204,
4
] | [
207,
47
] | python | en | ['en', 'en', 'en'] | True |
PhilipsTVMediaPlayer.volume_down | (self) | Send volume down command. | Send volume down command. | def volume_down(self):
"""Send volume down command."""
self._tv.sendKey("VolumeDown")
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"volume_down",
"(",
"self",
")",
":",
"self",
".",
"_tv",
".",
"sendKey",
"(",
"\"VolumeDown\"",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
209,
4
] | [
212,
47
] | python | en | ['en', 'it', 'en'] | True |
PhilipsTVMediaPlayer.mute_volume | (self, mute) | Send mute command. | Send mute command. | def mute_volume(self, mute):
"""Send mute command."""
self._tv.setVolume(None, mute)
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"mute_volume",
"(",
"self",
",",
"mute",
")",
":",
"self",
".",
"_tv",
".",
"setVolume",
"(",
"None",
",",
"mute",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
214,
4
] | [
217,
47
] | python | en | ['en', 'co', 'en'] | True |
PhilipsTVMediaPlayer.set_volume_level | (self, volume) | Set volume level, range 0..1. | Set volume level, range 0..1. | def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
self._tv.setVolume(volume, self._tv.muted)
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"set_volume_level",
"(",
"self",
",",
"volume",
")",
":",
"self",
".",
"_tv",
".",
"setVolume",
"(",
"volume",
",",
"self",
".",
"_tv",
".",
"muted",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
219,
4
] | [
222,
47
] | python | en | ['fr', 'zu', 'en'] | False |
PhilipsTVMediaPlayer.media_previous_track | (self) | Send rewind command. | Send rewind command. | def media_previous_track(self):
"""Send rewind command."""
self._tv.sendKey("Previous")
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"media_previous_track",
"(",
"self",
")",
":",
"self",
".",
"_tv",
".",
"sendKey",
"(",
"\"Previous\"",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
224,
4
] | [
227,
47
] | python | en | ['en', 'co', 'en'] | True |
PhilipsTVMediaPlayer.media_next_track | (self) | Send fast forward command. | Send fast forward command. | def media_next_track(self):
"""Send fast forward command."""
self._tv.sendKey("Next")
self._update_soon(DELAY_ACTION_DEFAULT) | [
"def",
"media_next_track",
"(",
"self",
")",
":",
"self",
".",
"_tv",
".",
"sendKey",
"(",
"\"Next\"",
")",
"self",
".",
"_update_soon",
"(",
"DELAY_ACTION_DEFAULT",
")"
] | [
229,
4
] | [
232,
47
] | python | en | ['en', 'cy', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.