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 |
---|---|---|---|---|---|---|---|---|---|---|---|
evaluate | (data_file, pred_file) |
Evaluate.
|
Evaluate.
| def evaluate(data_file, pred_file):
'''
Evaluate.
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' + expected_version +
', but got dataset with v-' + dataset_json['version'],
file=sys.stderr)
dataset = dataset_json['data']
with open(pred_file) as prediction_file:
predictions = json.load(prediction_file)
# print(json.dumps(evaluate(dataset, predictions)))
result = _evaluate(dataset, predictions)
# print('em:', result['exact_match'], 'f1:', result['f1'])
return result['exact_match'] | [
"def",
"evaluate",
"(",
"data_file",
",",
"pred_file",
")",
":",
"expected_version",
"=",
"'1.1'",
"with",
"open",
"(",
"data_file",
")",
"as",
"dataset_file",
":",
"dataset_json",
"=",
"json",
".",
"load",
"(",
"dataset_file",
")",
"if",
"dataset_json",
"[",
"'version'",
"]",
"!=",
"expected_version",
":",
"print",
"(",
"'Evaluation expects v-'",
"+",
"expected_version",
"+",
"', but got dataset with v-'",
"+",
"dataset_json",
"[",
"'version'",
"]",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"dataset",
"=",
"dataset_json",
"[",
"'data'",
"]",
"with",
"open",
"(",
"pred_file",
")",
"as",
"prediction_file",
":",
"predictions",
"=",
"json",
".",
"load",
"(",
"prediction_file",
")",
"# print(json.dumps(evaluate(dataset, predictions)))",
"result",
"=",
"_evaluate",
"(",
"dataset",
",",
"predictions",
")",
"# print('em:', result['exact_match'], 'f1:', result['f1'])",
"return",
"result",
"[",
"'exact_match'",
"]"
] | [
117,
0
] | [
134,
32
] | python | en | ['en', 'error', 'th'] | False |
evaluate_with_predictions | (data_file, predictions) |
Evalutate with predictions/
|
Evalutate with predictions/
| def evaluate_with_predictions(data_file, predictions):
'''
Evalutate with predictions/
'''
expected_version = '1.1'
with open(data_file) as dataset_file:
dataset_json = json.load(dataset_file)
if dataset_json['version'] != expected_version:
print('Evaluation expects v-' + expected_version +
', but got dataset with v-' + dataset_json['version'],
file=sys.stderr)
dataset = dataset_json['data']
result = _evaluate(dataset, predictions)
return result['exact_match'] | [
"def",
"evaluate_with_predictions",
"(",
"data_file",
",",
"predictions",
")",
":",
"expected_version",
"=",
"'1.1'",
"with",
"open",
"(",
"data_file",
")",
"as",
"dataset_file",
":",
"dataset_json",
"=",
"json",
".",
"load",
"(",
"dataset_file",
")",
"if",
"dataset_json",
"[",
"'version'",
"]",
"!=",
"expected_version",
":",
"print",
"(",
"'Evaluation expects v-'",
"+",
"expected_version",
"+",
"', but got dataset with v-'",
"+",
"dataset_json",
"[",
"'version'",
"]",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"dataset",
"=",
"dataset_json",
"[",
"'data'",
"]",
"result",
"=",
"_evaluate",
"(",
"dataset",
",",
"predictions",
")",
"return",
"result",
"[",
"'exact_match'",
"]"
] | [
136,
0
] | [
149,
32
] | python | en | ['en', 'error', 'th'] | False |
nix_prefetch_url | (url, algo='sha256') | Prefetches the content of the given URL. | Prefetches the content of the given URL. | def nix_prefetch_url(url, algo='sha256'):
"""Prefetches the content of the given URL."""
print(f'nix-prefetch-url {url}')
out = subprocess.check_output(['nix-prefetch-url', '--type', algo, url])
return out.decode('utf-8').rstrip() | [
"def",
"nix_prefetch_url",
"(",
"url",
",",
"algo",
"=",
"'sha256'",
")",
":",
"print",
"(",
"f'nix-prefetch-url {url}'",
")",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'nix-prefetch-url'",
",",
"'--type'",
",",
"algo",
",",
"url",
"]",
")",
"return",
"out",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rstrip",
"(",
")"
] | [
23,
0
] | [
27,
39
] | python | en | ['en', 'en', 'en'] | True |
_handle_async_response | (func, hass, connection, msg) | Create a response and handle exception. | Create a response and handle exception. | async def _handle_async_response(func, hass, connection, msg):
"""Create a response and handle exception."""
try:
await func(hass, connection, msg)
except Exception as err: # pylint: disable=broad-except
connection.async_handle_exception(msg, err) | [
"async",
"def",
"_handle_async_response",
"(",
"func",
",",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"try",
":",
"await",
"func",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
"except",
"Exception",
"as",
"err",
":",
"# pylint: disable=broad-except",
"connection",
".",
"async_handle_exception",
"(",
"msg",
",",
"err",
")"
] | [
14,
0
] | [
19,
51
] | python | en | ['en', 'en', 'en'] | True |
async_response | (
func: Callable[[HomeAssistant, ActiveConnection, dict], Awaitable[None]]
) | Decorate an async function to handle WebSocket API messages. | Decorate an async function to handle WebSocket API messages. | def async_response(
func: Callable[[HomeAssistant, ActiveConnection, dict], Awaitable[None]]
) -> const.WebSocketCommandHandler:
"""Decorate an async function to handle WebSocket API messages."""
@callback
@wraps(func)
def schedule_handler(hass, connection, msg):
"""Schedule the handler."""
# As the webserver is now started before the start
# event we do not want to block for websocket responders
asyncio.create_task(_handle_async_response(func, hass, connection, msg))
return schedule_handler | [
"def",
"async_response",
"(",
"func",
":",
"Callable",
"[",
"[",
"HomeAssistant",
",",
"ActiveConnection",
",",
"dict",
"]",
",",
"Awaitable",
"[",
"None",
"]",
"]",
")",
"->",
"const",
".",
"WebSocketCommandHandler",
":",
"@",
"callback",
"@",
"wraps",
"(",
"func",
")",
"def",
"schedule_handler",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"\"\"\"Schedule the handler.\"\"\"",
"# As the webserver is now started before the start",
"# event we do not want to block for websocket responders",
"asyncio",
".",
"create_task",
"(",
"_handle_async_response",
"(",
"func",
",",
"hass",
",",
"connection",
",",
"msg",
")",
")",
"return",
"schedule_handler"
] | [
22,
0
] | [
35,
27
] | python | en | ['en', 'en', 'en'] | True |
require_admin | (func: const.WebSocketCommandHandler) | Websocket decorator to require user to be an admin. | Websocket decorator to require user to be an admin. | def require_admin(func: const.WebSocketCommandHandler) -> const.WebSocketCommandHandler:
"""Websocket decorator to require user to be an admin."""
@wraps(func)
def with_admin(hass, connection, msg):
"""Check admin and call function."""
user = connection.user
if user is None or not user.is_admin:
raise Unauthorized()
func(hass, connection, msg)
return with_admin | [
"def",
"require_admin",
"(",
"func",
":",
"const",
".",
"WebSocketCommandHandler",
")",
"->",
"const",
".",
"WebSocketCommandHandler",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"with_admin",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"\"\"\"Check admin and call function.\"\"\"",
"user",
"=",
"connection",
".",
"user",
"if",
"user",
"is",
"None",
"or",
"not",
"user",
".",
"is_admin",
":",
"raise",
"Unauthorized",
"(",
")",
"func",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
"return",
"with_admin"
] | [
38,
0
] | [
51,
21
] | python | en | ['en', 'en', 'en'] | True |
ws_require_user | (
only_owner=False,
only_system_user=False,
allow_system_user=True,
only_active_user=True,
only_inactive_user=False,
) | Decorate function validating login user exist in current WS connection.
Will write out error message if not authenticated.
| Decorate function validating login user exist in current WS connection. | def ws_require_user(
only_owner=False,
only_system_user=False,
allow_system_user=True,
only_active_user=True,
only_inactive_user=False,
):
"""Decorate function validating login user exist in current WS connection.
Will write out error message if not authenticated.
"""
def validator(func):
"""Decorate func."""
@wraps(func)
def check_current_user(hass, connection, msg):
"""Check current user."""
def output_error(message_id, message):
"""Output error message."""
connection.send_message(
messages.error_message(msg["id"], message_id, message)
)
if connection.user is None:
output_error("no_user", "Not authenticated as a user")
return
if only_owner and not connection.user.is_owner:
output_error("only_owner", "Only allowed as owner")
return
if only_system_user and not connection.user.system_generated:
output_error("only_system_user", "Only allowed as system user")
return
if not allow_system_user and connection.user.system_generated:
output_error("not_system_user", "Not allowed as system user")
return
if only_active_user and not connection.user.is_active:
output_error("only_active_user", "Only allowed as active user")
return
if only_inactive_user and connection.user.is_active:
output_error("only_inactive_user", "Not allowed as active user")
return
return func(hass, connection, msg)
return check_current_user
return validator | [
"def",
"ws_require_user",
"(",
"only_owner",
"=",
"False",
",",
"only_system_user",
"=",
"False",
",",
"allow_system_user",
"=",
"True",
",",
"only_active_user",
"=",
"True",
",",
"only_inactive_user",
"=",
"False",
",",
")",
":",
"def",
"validator",
"(",
"func",
")",
":",
"\"\"\"Decorate func.\"\"\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"check_current_user",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"\"\"\"Check current user.\"\"\"",
"def",
"output_error",
"(",
"message_id",
",",
"message",
")",
":",
"\"\"\"Output error message.\"\"\"",
"connection",
".",
"send_message",
"(",
"messages",
".",
"error_message",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"message_id",
",",
"message",
")",
")",
"if",
"connection",
".",
"user",
"is",
"None",
":",
"output_error",
"(",
"\"no_user\"",
",",
"\"Not authenticated as a user\"",
")",
"return",
"if",
"only_owner",
"and",
"not",
"connection",
".",
"user",
".",
"is_owner",
":",
"output_error",
"(",
"\"only_owner\"",
",",
"\"Only allowed as owner\"",
")",
"return",
"if",
"only_system_user",
"and",
"not",
"connection",
".",
"user",
".",
"system_generated",
":",
"output_error",
"(",
"\"only_system_user\"",
",",
"\"Only allowed as system user\"",
")",
"return",
"if",
"not",
"allow_system_user",
"and",
"connection",
".",
"user",
".",
"system_generated",
":",
"output_error",
"(",
"\"not_system_user\"",
",",
"\"Not allowed as system user\"",
")",
"return",
"if",
"only_active_user",
"and",
"not",
"connection",
".",
"user",
".",
"is_active",
":",
"output_error",
"(",
"\"only_active_user\"",
",",
"\"Only allowed as active user\"",
")",
"return",
"if",
"only_inactive_user",
"and",
"connection",
".",
"user",
".",
"is_active",
":",
"output_error",
"(",
"\"only_inactive_user\"",
",",
"\"Not allowed as active user\"",
")",
"return",
"return",
"func",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
"return",
"check_current_user",
"return",
"validator"
] | [
54,
0
] | [
107,
20
] | python | en | ['de', 'en', 'en'] | True |
websocket_command | (
schema: dict,
) | Tag a function as a websocket command. | Tag a function as a websocket command. | def websocket_command(
schema: dict,
) -> Callable[[const.WebSocketCommandHandler], const.WebSocketCommandHandler]:
"""Tag a function as a websocket command."""
command = schema["type"]
def decorate(func):
"""Decorate ws command function."""
# pylint: disable=protected-access
func._ws_schema = messages.BASE_COMMAND_MESSAGE_SCHEMA.extend(schema)
func._ws_command = command
return func
return decorate | [
"def",
"websocket_command",
"(",
"schema",
":",
"dict",
",",
")",
"->",
"Callable",
"[",
"[",
"const",
".",
"WebSocketCommandHandler",
"]",
",",
"const",
".",
"WebSocketCommandHandler",
"]",
":",
"command",
"=",
"schema",
"[",
"\"type\"",
"]",
"def",
"decorate",
"(",
"func",
")",
":",
"\"\"\"Decorate ws command function.\"\"\"",
"# pylint: disable=protected-access",
"func",
".",
"_ws_schema",
"=",
"messages",
".",
"BASE_COMMAND_MESSAGE_SCHEMA",
".",
"extend",
"(",
"schema",
")",
"func",
".",
"_ws_command",
"=",
"command",
"return",
"func",
"return",
"decorate"
] | [
110,
0
] | [
123,
19
] | python | en | ['en', 'en', 'en'] | True |
pytest_configure | (config) | Register marker for tests that log exceptions. | Register marker for tests that log exceptions. | def pytest_configure(config):
"""Register marker for tests that log exceptions."""
config.addinivalue_line(
"markers", "no_fail_on_log_exception: mark test to not fail on logged exception"
) | [
"def",
"pytest_configure",
"(",
"config",
")",
":",
"config",
".",
"addinivalue_line",
"(",
"\"markers\"",
",",
"\"no_fail_on_log_exception: mark test to not fail on logged exception\"",
")"
] | [
52,
0
] | [
56,
5
] | python | en | ['en', 'en', 'en'] | True |
check_real | (func) | Force a function to require a keyword _test_real to be passed in. | Force a function to require a keyword _test_real to be passed in. | def check_real(func):
"""Force a function to require a keyword _test_real to be passed in."""
@functools.wraps(func)
async def guard_func(*args, **kwargs):
real = kwargs.pop("_test_real", None)
if not real:
raise Exception(
'Forgot to mock or pass "_test_real=True" to %s', func.__name__
)
return await func(*args, **kwargs)
return guard_func | [
"def",
"check_real",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"async",
"def",
"guard_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"real",
"=",
"kwargs",
".",
"pop",
"(",
"\"_test_real\"",
",",
"None",
")",
"if",
"not",
"real",
":",
"raise",
"Exception",
"(",
"'Forgot to mock or pass \"_test_real=True\" to %s'",
",",
"func",
".",
"__name__",
")",
"return",
"await",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"guard_func"
] | [
59,
0
] | [
73,
21
] | python | en | ['en', 'en', 'en'] | True |
verify_cleanup | () | Verify that the test has cleaned up resources correctly. | Verify that the test has cleaned up resources correctly. | def verify_cleanup():
"""Verify that the test has cleaned up resources correctly."""
threads_before = frozenset(threading.enumerate())
yield
if len(INSTANCES) >= 2:
count = len(INSTANCES)
for inst in INSTANCES:
inst.stop()
pytest.exit(f"Detected non stopped instances ({count}), aborting test run")
threads = frozenset(threading.enumerate()) - threads_before
assert not threads | [
"def",
"verify_cleanup",
"(",
")",
":",
"threads_before",
"=",
"frozenset",
"(",
"threading",
".",
"enumerate",
"(",
")",
")",
"yield",
"if",
"len",
"(",
"INSTANCES",
")",
">=",
"2",
":",
"count",
"=",
"len",
"(",
"INSTANCES",
")",
"for",
"inst",
"in",
"INSTANCES",
":",
"inst",
".",
"stop",
"(",
")",
"pytest",
".",
"exit",
"(",
"f\"Detected non stopped instances ({count}), aborting test run\"",
")",
"threads",
"=",
"frozenset",
"(",
"threading",
".",
"enumerate",
"(",
")",
")",
"-",
"threads_before",
"assert",
"not",
"threads"
] | [
82,
0
] | [
95,
22
] | python | en | ['en', 'en', 'en'] | True |
hass_storage | () | Fixture to mock storage. | Fixture to mock storage. | def hass_storage():
"""Fixture to mock storage."""
with mock_storage() as stored_data:
yield stored_data | [
"def",
"hass_storage",
"(",
")",
":",
"with",
"mock_storage",
"(",
")",
"as",
"stored_data",
":",
"yield",
"stored_data"
] | [
99,
0
] | [
102,
25
] | python | en | ['en', 'nl', 'en'] | True |
hass | (loop, hass_storage, request) | Fixture to provide a test instance of Home Assistant. | Fixture to provide a test instance of Home Assistant. | def hass(loop, hass_storage, request):
"""Fixture to provide a test instance of Home Assistant."""
def exc_handle(loop, context):
"""Handle exceptions by rethrowing them, which will fail the test."""
# Most of these contexts will contain an exception, but not all.
# The docs note the key as "optional"
# See https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_exception_handler
if "exception" in context:
exceptions.append(context["exception"])
else:
exceptions.append(
Exception(
"Received exception handler without exception, but with message: %s"
% context["message"]
)
)
orig_exception_handler(loop, context)
exceptions = []
hass = loop.run_until_complete(async_test_home_assistant(loop))
orig_exception_handler = loop.get_exception_handler()
loop.set_exception_handler(exc_handle)
yield hass
loop.run_until_complete(hass.async_stop(force=True))
for ex in exceptions:
if (
request.module.__name__,
request.function.__name__,
) in IGNORE_UNCAUGHT_EXCEPTIONS:
continue
if isinstance(ex, ServiceNotFound):
continue
raise ex | [
"def",
"hass",
"(",
"loop",
",",
"hass_storage",
",",
"request",
")",
":",
"def",
"exc_handle",
"(",
"loop",
",",
"context",
")",
":",
"\"\"\"Handle exceptions by rethrowing them, which will fail the test.\"\"\"",
"# Most of these contexts will contain an exception, but not all.",
"# The docs note the key as \"optional\"",
"# See https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_exception_handler",
"if",
"\"exception\"",
"in",
"context",
":",
"exceptions",
".",
"append",
"(",
"context",
"[",
"\"exception\"",
"]",
")",
"else",
":",
"exceptions",
".",
"append",
"(",
"Exception",
"(",
"\"Received exception handler without exception, but with message: %s\"",
"%",
"context",
"[",
"\"message\"",
"]",
")",
")",
"orig_exception_handler",
"(",
"loop",
",",
"context",
")",
"exceptions",
"=",
"[",
"]",
"hass",
"=",
"loop",
".",
"run_until_complete",
"(",
"async_test_home_assistant",
"(",
"loop",
")",
")",
"orig_exception_handler",
"=",
"loop",
".",
"get_exception_handler",
"(",
")",
"loop",
".",
"set_exception_handler",
"(",
"exc_handle",
")",
"yield",
"hass",
"loop",
".",
"run_until_complete",
"(",
"hass",
".",
"async_stop",
"(",
"force",
"=",
"True",
")",
")",
"for",
"ex",
"in",
"exceptions",
":",
"if",
"(",
"request",
".",
"module",
".",
"__name__",
",",
"request",
".",
"function",
".",
"__name__",
",",
")",
"in",
"IGNORE_UNCAUGHT_EXCEPTIONS",
":",
"continue",
"if",
"isinstance",
"(",
"ex",
",",
"ServiceNotFound",
")",
":",
"continue",
"raise",
"ex"
] | [
106,
0
] | [
141,
16
] | python | en | ['en', 'en', 'en'] | True |
stop_hass | () | Make sure all hass are stopped. | Make sure all hass are stopped. | async def stop_hass():
"""Make sure all hass are stopped."""
orig_hass = ha.HomeAssistant
created = []
def mock_hass():
hass_inst = orig_hass()
created.append(hass_inst)
return hass_inst
with patch("homeassistant.core.HomeAssistant", mock_hass):
yield
for hass_inst in created:
if hass_inst.state == ha.CoreState.stopped:
continue
with patch.object(hass_inst.loop, "stop"):
await hass_inst.async_block_till_done()
await hass_inst.async_stop(force=True) | [
"async",
"def",
"stop_hass",
"(",
")",
":",
"orig_hass",
"=",
"ha",
".",
"HomeAssistant",
"created",
"=",
"[",
"]",
"def",
"mock_hass",
"(",
")",
":",
"hass_inst",
"=",
"orig_hass",
"(",
")",
"created",
".",
"append",
"(",
"hass_inst",
")",
"return",
"hass_inst",
"with",
"patch",
"(",
"\"homeassistant.core.HomeAssistant\"",
",",
"mock_hass",
")",
":",
"yield",
"for",
"hass_inst",
"in",
"created",
":",
"if",
"hass_inst",
".",
"state",
"==",
"ha",
".",
"CoreState",
".",
"stopped",
":",
"continue",
"with",
"patch",
".",
"object",
"(",
"hass_inst",
".",
"loop",
",",
"\"stop\"",
")",
":",
"await",
"hass_inst",
".",
"async_block_till_done",
"(",
")",
"await",
"hass_inst",
".",
"async_stop",
"(",
"force",
"=",
"True",
")"
] | [
145,
0
] | [
165,
50
] | python | en | ['en', 'en', 'en'] | True |
requests_mock | () | Fixture to provide a requests mocker. | Fixture to provide a requests mocker. | def requests_mock():
"""Fixture to provide a requests mocker."""
with _requests_mock.mock() as m:
yield m | [
"def",
"requests_mock",
"(",
")",
":",
"with",
"_requests_mock",
".",
"mock",
"(",
")",
"as",
"m",
":",
"yield",
"m"
] | [
169,
0
] | [
172,
15
] | python | en | ['en', 'en', 'en'] | True |
aioclient_mock | () | Fixture to mock aioclient calls. | Fixture to mock aioclient calls. | def aioclient_mock():
"""Fixture to mock aioclient calls."""
with mock_aiohttp_client() as mock_session:
yield mock_session | [
"def",
"aioclient_mock",
"(",
")",
":",
"with",
"mock_aiohttp_client",
"(",
")",
"as",
"mock_session",
":",
"yield",
"mock_session"
] | [
176,
0
] | [
179,
26
] | python | en | ['en', 'ca', 'en'] | True |
mock_device_tracker_conf | () | Prevent device tracker from reading/writing data. | Prevent device tracker from reading/writing data. | def mock_device_tracker_conf():
"""Prevent device tracker from reading/writing data."""
devices = []
async def mock_update_config(path, id, entity):
devices.append(entity)
with patch(
"homeassistant.components.device_tracker.legacy"
".DeviceTracker.async_update_config",
side_effect=mock_update_config,
), patch(
"homeassistant.components.device_tracker.legacy.async_load_config",
side_effect=lambda *args: devices,
):
yield devices | [
"def",
"mock_device_tracker_conf",
"(",
")",
":",
"devices",
"=",
"[",
"]",
"async",
"def",
"mock_update_config",
"(",
"path",
",",
"id",
",",
"entity",
")",
":",
"devices",
".",
"append",
"(",
"entity",
")",
"with",
"patch",
"(",
"\"homeassistant.components.device_tracker.legacy\"",
"\".DeviceTracker.async_update_config\"",
",",
"side_effect",
"=",
"mock_update_config",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.device_tracker.legacy.async_load_config\"",
",",
"side_effect",
"=",
"lambda",
"*",
"args",
":",
"devices",
",",
")",
":",
"yield",
"devices"
] | [
183,
0
] | [
198,
21
] | python | en | ['en', 'en', 'en'] | True |
hass_access_token | (hass, hass_admin_user) | Return an access token to access Home Assistant. | Return an access token to access Home Assistant. | def hass_access_token(hass, hass_admin_user):
"""Return an access token to access Home Assistant."""
refresh_token = hass.loop.run_until_complete(
hass.auth.async_create_refresh_token(hass_admin_user, CLIENT_ID)
)
return hass.auth.async_create_access_token(refresh_token) | [
"def",
"hass_access_token",
"(",
"hass",
",",
"hass_admin_user",
")",
":",
"refresh_token",
"=",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"hass",
".",
"auth",
".",
"async_create_refresh_token",
"(",
"hass_admin_user",
",",
"CLIENT_ID",
")",
")",
"return",
"hass",
".",
"auth",
".",
"async_create_access_token",
"(",
"refresh_token",
")"
] | [
202,
0
] | [
207,
61
] | python | en | ['en', 'en', 'en'] | True |
hass_owner_user | (hass, local_auth) | Return a Home Assistant admin user. | Return a Home Assistant admin user. | def hass_owner_user(hass, local_auth):
"""Return a Home Assistant admin user."""
return MockUser(is_owner=True).add_to_hass(hass) | [
"def",
"hass_owner_user",
"(",
"hass",
",",
"local_auth",
")",
":",
"return",
"MockUser",
"(",
"is_owner",
"=",
"True",
")",
".",
"add_to_hass",
"(",
"hass",
")"
] | [
211,
0
] | [
213,
52
] | python | en | ['en', 'en', 'en'] | True |
hass_admin_user | (hass, local_auth) | Return a Home Assistant admin user. | Return a Home Assistant admin user. | def hass_admin_user(hass, local_auth):
"""Return a Home Assistant admin user."""
admin_group = hass.loop.run_until_complete(
hass.auth.async_get_group(GROUP_ID_ADMIN)
)
return MockUser(groups=[admin_group]).add_to_hass(hass) | [
"def",
"hass_admin_user",
"(",
"hass",
",",
"local_auth",
")",
":",
"admin_group",
"=",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"hass",
".",
"auth",
".",
"async_get_group",
"(",
"GROUP_ID_ADMIN",
")",
")",
"return",
"MockUser",
"(",
"groups",
"=",
"[",
"admin_group",
"]",
")",
".",
"add_to_hass",
"(",
"hass",
")"
] | [
217,
0
] | [
222,
59
] | python | en | ['en', 'en', 'en'] | True |
hass_read_only_user | (hass, local_auth) | Return a Home Assistant read only user. | Return a Home Assistant read only user. | def hass_read_only_user(hass, local_auth):
"""Return a Home Assistant read only user."""
read_only_group = hass.loop.run_until_complete(
hass.auth.async_get_group(GROUP_ID_READ_ONLY)
)
return MockUser(groups=[read_only_group]).add_to_hass(hass) | [
"def",
"hass_read_only_user",
"(",
"hass",
",",
"local_auth",
")",
":",
"read_only_group",
"=",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"hass",
".",
"auth",
".",
"async_get_group",
"(",
"GROUP_ID_READ_ONLY",
")",
")",
"return",
"MockUser",
"(",
"groups",
"=",
"[",
"read_only_group",
"]",
")",
".",
"add_to_hass",
"(",
"hass",
")"
] | [
226,
0
] | [
231,
63
] | python | en | ['en', 'en', 'en'] | True |
hass_read_only_access_token | (hass, hass_read_only_user) | Return a Home Assistant read only user. | Return a Home Assistant read only user. | def hass_read_only_access_token(hass, hass_read_only_user):
"""Return a Home Assistant read only user."""
refresh_token = hass.loop.run_until_complete(
hass.auth.async_create_refresh_token(hass_read_only_user, CLIENT_ID)
)
return hass.auth.async_create_access_token(refresh_token) | [
"def",
"hass_read_only_access_token",
"(",
"hass",
",",
"hass_read_only_user",
")",
":",
"refresh_token",
"=",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"hass",
".",
"auth",
".",
"async_create_refresh_token",
"(",
"hass_read_only_user",
",",
"CLIENT_ID",
")",
")",
"return",
"hass",
".",
"auth",
".",
"async_create_access_token",
"(",
"refresh_token",
")"
] | [
235,
0
] | [
240,
61
] | python | en | ['en', 'en', 'en'] | True |
legacy_auth | (hass) | Load legacy API password provider. | Load legacy API password provider. | def legacy_auth(hass):
"""Load legacy API password provider."""
prv = legacy_api_password.LegacyApiPasswordAuthProvider(
hass,
hass.auth._store,
{"type": "legacy_api_password", "api_password": "test-password"},
)
hass.auth._providers[(prv.type, prv.id)] = prv
return prv | [
"def",
"legacy_auth",
"(",
"hass",
")",
":",
"prv",
"=",
"legacy_api_password",
".",
"LegacyApiPasswordAuthProvider",
"(",
"hass",
",",
"hass",
".",
"auth",
".",
"_store",
",",
"{",
"\"type\"",
":",
"\"legacy_api_password\"",
",",
"\"api_password\"",
":",
"\"test-password\"",
"}",
",",
")",
"hass",
".",
"auth",
".",
"_providers",
"[",
"(",
"prv",
".",
"type",
",",
"prv",
".",
"id",
")",
"]",
"=",
"prv",
"return",
"prv"
] | [
244,
0
] | [
252,
14
] | python | en | ['fr', 'mg', 'en'] | False |
local_auth | (hass) | Load local auth provider. | Load local auth provider. | def local_auth(hass):
"""Load local auth provider."""
prv = homeassistant.HassAuthProvider(
hass, hass.auth._store, {"type": "homeassistant"}
)
hass.auth._providers[(prv.type, prv.id)] = prv
return prv | [
"def",
"local_auth",
"(",
"hass",
")",
":",
"prv",
"=",
"homeassistant",
".",
"HassAuthProvider",
"(",
"hass",
",",
"hass",
".",
"auth",
".",
"_store",
",",
"{",
"\"type\"",
":",
"\"homeassistant\"",
"}",
")",
"hass",
".",
"auth",
".",
"_providers",
"[",
"(",
"prv",
".",
"type",
",",
"prv",
".",
"id",
")",
"]",
"=",
"prv",
"return",
"prv"
] | [
256,
0
] | [
262,
14
] | python | en | ['en', 'it', 'fr'] | False |
hass_client | (hass, aiohttp_client, hass_access_token) | Return an authenticated HTTP client. | Return an authenticated HTTP client. | def hass_client(hass, aiohttp_client, hass_access_token):
"""Return an authenticated HTTP client."""
async def auth_client():
"""Return an authenticated client."""
return await aiohttp_client(
hass.http.app, headers={"Authorization": f"Bearer {hass_access_token}"}
)
return auth_client | [
"def",
"hass_client",
"(",
"hass",
",",
"aiohttp_client",
",",
"hass_access_token",
")",
":",
"async",
"def",
"auth_client",
"(",
")",
":",
"\"\"\"Return an authenticated client.\"\"\"",
"return",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
",",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"f\"Bearer {hass_access_token}\"",
"}",
")",
"return",
"auth_client"
] | [
266,
0
] | [
275,
22
] | python | en | ['en', 'en', 'en'] | True |
current_request | (hass) | Mock current request. | Mock current request. | def current_request(hass):
"""Mock current request."""
with patch("homeassistant.helpers.network.current_request") as mock_request_context:
mocked_request = make_mocked_request(
"GET",
"/some/request",
headers={"Host": "example.com"},
sslcontext=ssl.SSLContext(ssl.PROTOCOL_TLS),
)
mock_request_context.get = Mock(return_value=mocked_request)
yield mock_request_context | [
"def",
"current_request",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.helpers.network.current_request\"",
")",
"as",
"mock_request_context",
":",
"mocked_request",
"=",
"make_mocked_request",
"(",
"\"GET\"",
",",
"\"/some/request\"",
",",
"headers",
"=",
"{",
"\"Host\"",
":",
"\"example.com\"",
"}",
",",
"sslcontext",
"=",
"ssl",
".",
"SSLContext",
"(",
"ssl",
".",
"PROTOCOL_TLS",
")",
",",
")",
"mock_request_context",
".",
"get",
"=",
"Mock",
"(",
"return_value",
"=",
"mocked_request",
")",
"yield",
"mock_request_context"
] | [
279,
0
] | [
289,
34
] | python | en | ['en', 'en', 'en'] | True |
hass_ws_client | (aiohttp_client, hass_access_token, hass) | Websocket client fixture connected to websocket server. | Websocket client fixture connected to websocket server. | def hass_ws_client(aiohttp_client, hass_access_token, hass):
"""Websocket client fixture connected to websocket server."""
async def create_client(hass=hass, access_token=hass_access_token):
"""Create a websocket client."""
assert await async_setup_component(hass, "websocket_api", {})
client = await aiohttp_client(hass.http.app)
with patch("homeassistant.components.http.auth.setup_auth"):
websocket = await client.ws_connect(URL)
auth_resp = await websocket.receive_json()
assert auth_resp["type"] == TYPE_AUTH_REQUIRED
if access_token is None:
await websocket.send_json(
{"type": TYPE_AUTH, "access_token": "incorrect"}
)
else:
await websocket.send_json(
{"type": TYPE_AUTH, "access_token": access_token}
)
auth_ok = await websocket.receive_json()
assert auth_ok["type"] == TYPE_AUTH_OK
# wrap in client
websocket.client = client
return websocket
return create_client | [
"def",
"hass_ws_client",
"(",
"aiohttp_client",
",",
"hass_access_token",
",",
"hass",
")",
":",
"async",
"def",
"create_client",
"(",
"hass",
"=",
"hass",
",",
"access_token",
"=",
"hass_access_token",
")",
":",
"\"\"\"Create a websocket client.\"\"\"",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"websocket_api\"",
",",
"{",
"}",
")",
"client",
"=",
"await",
"aiohttp_client",
"(",
"hass",
".",
"http",
".",
"app",
")",
"with",
"patch",
"(",
"\"homeassistant.components.http.auth.setup_auth\"",
")",
":",
"websocket",
"=",
"await",
"client",
".",
"ws_connect",
"(",
"URL",
")",
"auth_resp",
"=",
"await",
"websocket",
".",
"receive_json",
"(",
")",
"assert",
"auth_resp",
"[",
"\"type\"",
"]",
"==",
"TYPE_AUTH_REQUIRED",
"if",
"access_token",
"is",
"None",
":",
"await",
"websocket",
".",
"send_json",
"(",
"{",
"\"type\"",
":",
"TYPE_AUTH",
",",
"\"access_token\"",
":",
"\"incorrect\"",
"}",
")",
"else",
":",
"await",
"websocket",
".",
"send_json",
"(",
"{",
"\"type\"",
":",
"TYPE_AUTH",
",",
"\"access_token\"",
":",
"access_token",
"}",
")",
"auth_ok",
"=",
"await",
"websocket",
".",
"receive_json",
"(",
")",
"assert",
"auth_ok",
"[",
"\"type\"",
"]",
"==",
"TYPE_AUTH_OK",
"# wrap in client",
"websocket",
".",
"client",
"=",
"client",
"return",
"websocket",
"return",
"create_client"
] | [
293,
0
] | [
323,
24
] | python | en | ['en', 'da', 'en'] | True |
fail_on_log_exception | (request, monkeypatch) | Fixture to fail if a callback wrapped by catch_log_exception or coroutine wrapped by async_create_catching_coro throws. | Fixture to fail if a callback wrapped by catch_log_exception or coroutine wrapped by async_create_catching_coro throws. | def fail_on_log_exception(request, monkeypatch):
"""Fixture to fail if a callback wrapped by catch_log_exception or coroutine wrapped by async_create_catching_coro throws."""
if "no_fail_on_log_exception" in request.keywords:
return
def log_exception(format_err, *args):
raise
monkeypatch.setattr("homeassistant.util.logging.log_exception", log_exception) | [
"def",
"fail_on_log_exception",
"(",
"request",
",",
"monkeypatch",
")",
":",
"if",
"\"no_fail_on_log_exception\"",
"in",
"request",
".",
"keywords",
":",
"return",
"def",
"log_exception",
"(",
"format_err",
",",
"*",
"args",
")",
":",
"raise",
"monkeypatch",
".",
"setattr",
"(",
"\"homeassistant.util.logging.log_exception\"",
",",
"log_exception",
")"
] | [
327,
0
] | [
335,
82
] | python | en | ['en', 'en', 'en'] | True |
mqtt_config | () | Fixture to allow overriding MQTT config. | Fixture to allow overriding MQTT config. | def mqtt_config():
"""Fixture to allow overriding MQTT config."""
return None | [
"def",
"mqtt_config",
"(",
")",
":",
"return",
"None"
] | [
339,
0
] | [
341,
15
] | python | en | ['en', 'ca', 'en'] | True |
mqtt_client_mock | (hass) | Fixture to mock MQTT client. | Fixture to mock MQTT client. | def mqtt_client_mock(hass):
"""Fixture to mock MQTT client."""
mid = 0
def get_mid():
nonlocal mid
mid += 1
return mid
class FakeInfo:
def __init__(self, mid):
self.mid = mid
self.rc = 0
with patch("paho.mqtt.client.Client") as mock_client:
@ha.callback
def _async_fire_mqtt_message(topic, payload, qos, retain):
async_fire_mqtt_message(hass, topic, payload, qos, retain)
mid = get_mid()
mock_client.on_publish(0, 0, mid)
return FakeInfo(mid)
def _subscribe(topic, qos=0):
mid = get_mid()
mock_client.on_subscribe(0, 0, mid)
return (0, mid)
def _unsubscribe(topic):
mid = get_mid()
mock_client.on_unsubscribe(0, 0, mid)
return (0, mid)
mock_client = mock_client.return_value
mock_client.connect.return_value = 0
mock_client.subscribe.side_effect = _subscribe
mock_client.unsubscribe.side_effect = _unsubscribe
mock_client.publish.side_effect = _async_fire_mqtt_message
yield mock_client | [
"def",
"mqtt_client_mock",
"(",
"hass",
")",
":",
"mid",
"=",
"0",
"def",
"get_mid",
"(",
")",
":",
"nonlocal",
"mid",
"mid",
"+=",
"1",
"return",
"mid",
"class",
"FakeInfo",
":",
"def",
"__init__",
"(",
"self",
",",
"mid",
")",
":",
"self",
".",
"mid",
"=",
"mid",
"self",
".",
"rc",
"=",
"0",
"with",
"patch",
"(",
"\"paho.mqtt.client.Client\"",
")",
"as",
"mock_client",
":",
"@",
"ha",
".",
"callback",
"def",
"_async_fire_mqtt_message",
"(",
"topic",
",",
"payload",
",",
"qos",
",",
"retain",
")",
":",
"async_fire_mqtt_message",
"(",
"hass",
",",
"topic",
",",
"payload",
",",
"qos",
",",
"retain",
")",
"mid",
"=",
"get_mid",
"(",
")",
"mock_client",
".",
"on_publish",
"(",
"0",
",",
"0",
",",
"mid",
")",
"return",
"FakeInfo",
"(",
"mid",
")",
"def",
"_subscribe",
"(",
"topic",
",",
"qos",
"=",
"0",
")",
":",
"mid",
"=",
"get_mid",
"(",
")",
"mock_client",
".",
"on_subscribe",
"(",
"0",
",",
"0",
",",
"mid",
")",
"return",
"(",
"0",
",",
"mid",
")",
"def",
"_unsubscribe",
"(",
"topic",
")",
":",
"mid",
"=",
"get_mid",
"(",
")",
"mock_client",
".",
"on_unsubscribe",
"(",
"0",
",",
"0",
",",
"mid",
")",
"return",
"(",
"0",
",",
"mid",
")",
"mock_client",
"=",
"mock_client",
".",
"return_value",
"mock_client",
".",
"connect",
".",
"return_value",
"=",
"0",
"mock_client",
".",
"subscribe",
".",
"side_effect",
"=",
"_subscribe",
"mock_client",
".",
"unsubscribe",
".",
"side_effect",
"=",
"_unsubscribe",
"mock_client",
".",
"publish",
".",
"side_effect",
"=",
"_async_fire_mqtt_message",
"yield",
"mock_client"
] | [
345,
0
] | [
384,
25
] | python | en | ['en', 'ca', 'en'] | True |
mqtt_mock | (hass, mqtt_client_mock, mqtt_config) | Fixture to mock MQTT component. | Fixture to mock MQTT component. | async def mqtt_mock(hass, mqtt_client_mock, mqtt_config):
"""Fixture to mock MQTT component."""
if mqtt_config is None:
mqtt_config = {mqtt.CONF_BROKER: "mock-broker"}
result = await async_setup_component(hass, mqtt.DOMAIN, {mqtt.DOMAIN: mqtt_config})
assert result
await hass.async_block_till_done()
# Workaround: asynctest==0.13 fails on @functools.lru_cache
spec = dir(hass.data["mqtt"])
spec.remove("_matching_subscriptions")
mqtt_component_mock = MagicMock(
return_value=hass.data["mqtt"],
spec_set=spec,
wraps=hass.data["mqtt"],
)
mqtt_component_mock._mqttc = mqtt_client_mock
hass.data["mqtt"] = mqtt_component_mock
component = hass.data["mqtt"]
component.reset_mock()
return component | [
"async",
"def",
"mqtt_mock",
"(",
"hass",
",",
"mqtt_client_mock",
",",
"mqtt_config",
")",
":",
"if",
"mqtt_config",
"is",
"None",
":",
"mqtt_config",
"=",
"{",
"mqtt",
".",
"CONF_BROKER",
":",
"\"mock-broker\"",
"}",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"mqtt",
".",
"DOMAIN",
",",
"{",
"mqtt",
".",
"DOMAIN",
":",
"mqtt_config",
"}",
")",
"assert",
"result",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"# Workaround: asynctest==0.13 fails on @functools.lru_cache",
"spec",
"=",
"dir",
"(",
"hass",
".",
"data",
"[",
"\"mqtt\"",
"]",
")",
"spec",
".",
"remove",
"(",
"\"_matching_subscriptions\"",
")",
"mqtt_component_mock",
"=",
"MagicMock",
"(",
"return_value",
"=",
"hass",
".",
"data",
"[",
"\"mqtt\"",
"]",
",",
"spec_set",
"=",
"spec",
",",
"wraps",
"=",
"hass",
".",
"data",
"[",
"\"mqtt\"",
"]",
",",
")",
"mqtt_component_mock",
".",
"_mqttc",
"=",
"mqtt_client_mock",
"hass",
".",
"data",
"[",
"\"mqtt\"",
"]",
"=",
"mqtt_component_mock",
"component",
"=",
"hass",
".",
"data",
"[",
"\"mqtt\"",
"]",
"component",
".",
"reset_mock",
"(",
")",
"return",
"component"
] | [
388,
0
] | [
411,
20
] | python | en | ['en', 'ca', 'en'] | True |
mock_zeroconf | () | Mock zeroconf. | Mock zeroconf. | def mock_zeroconf():
"""Mock zeroconf."""
with patch("homeassistant.components.zeroconf.HaZeroconf") as mock_zc:
yield mock_zc.return_value | [
"def",
"mock_zeroconf",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.zeroconf.HaZeroconf\"",
")",
"as",
"mock_zc",
":",
"yield",
"mock_zc",
".",
"return_value"
] | [
415,
0
] | [
418,
34
] | python | en | ['eu', 'sr', 'en'] | False |
legacy_patchable_time | () | Allow time to be patchable by using event listeners instead of asyncio loop. | Allow time to be patchable by using event listeners instead of asyncio loop. | def legacy_patchable_time():
"""Allow time to be patchable by using event listeners instead of asyncio loop."""
@ha.callback
@loader.bind_hass
def async_track_point_in_utc_time(hass, action, point_in_time):
"""Add a listener that fires once after a specific point in UTC time."""
# Ensure point_in_time is UTC
point_in_time = event.dt_util.as_utc(point_in_time)
# Since this is called once, we accept a HassJob so we can avoid
# having to figure out how to call the action every time its called.
job = action if isinstance(action, ha.HassJob) else ha.HassJob(action)
@ha.callback
def point_in_time_listener(event):
"""Listen for matching time_changed events."""
now = event.data[ATTR_NOW]
if now < point_in_time or hasattr(point_in_time_listener, "run"):
return
# Set variable so that we will never run twice.
# Because the event bus might have to wait till a thread comes
# available to execute this listener it might occur that the
# listener gets lined up twice to be executed. This will make
# sure the second time it does nothing.
setattr(point_in_time_listener, "run", True)
async_unsub()
hass.async_run_hass_job(job, now)
async_unsub = hass.bus.async_listen(EVENT_TIME_CHANGED, point_in_time_listener)
return async_unsub
@ha.callback
@loader.bind_hass
def async_track_utc_time_change(
hass, action, hour=None, minute=None, second=None, local=False
):
"""Add a listener that will fire if time matches a pattern."""
job = ha.HassJob(action)
# We do not have to wrap the function with time pattern matching logic
# if no pattern given
if all(val is None for val in (hour, minute, second)):
@ha.callback
def time_change_listener(ev) -> None:
"""Fire every time event that comes in."""
hass.async_run_hass_job(job, ev.data[ATTR_NOW])
return hass.bus.async_listen(EVENT_TIME_CHANGED, time_change_listener)
matching_seconds = event.dt_util.parse_time_expression(second, 0, 59)
matching_minutes = event.dt_util.parse_time_expression(minute, 0, 59)
matching_hours = event.dt_util.parse_time_expression(hour, 0, 23)
next_time = None
def calculate_next(now) -> None:
"""Calculate and set the next time the trigger should fire."""
nonlocal next_time
localized_now = event.dt_util.as_local(now) if local else now
next_time = event.dt_util.find_next_time_expression_time(
localized_now, matching_seconds, matching_minutes, matching_hours
)
# Make sure rolling back the clock doesn't prevent the timer from
# triggering.
last_now = None
@ha.callback
def pattern_time_change_listener(ev) -> None:
"""Listen for matching time_changed events."""
nonlocal next_time, last_now
now = ev.data[ATTR_NOW]
if last_now is None or now < last_now:
# Time rolled back or next time not yet calculated
calculate_next(now)
last_now = now
if next_time <= now:
hass.async_run_hass_job(
job, event.dt_util.as_local(now) if local else now
)
calculate_next(now + datetime.timedelta(seconds=1))
# We can't use async_track_point_in_utc_time here because it would
# break in the case that the system time abruptly jumps backwards.
# Our custom last_now logic takes care of resolving that scenario.
return hass.bus.async_listen(EVENT_TIME_CHANGED, pattern_time_change_listener)
with patch(
"homeassistant.helpers.event.async_track_point_in_utc_time",
async_track_point_in_utc_time,
), patch(
"homeassistant.helpers.event.async_track_utc_time_change",
async_track_utc_time_change,
):
yield | [
"def",
"legacy_patchable_time",
"(",
")",
":",
"@",
"ha",
".",
"callback",
"@",
"loader",
".",
"bind_hass",
"def",
"async_track_point_in_utc_time",
"(",
"hass",
",",
"action",
",",
"point_in_time",
")",
":",
"\"\"\"Add a listener that fires once after a specific point in UTC time.\"\"\"",
"# Ensure point_in_time is UTC",
"point_in_time",
"=",
"event",
".",
"dt_util",
".",
"as_utc",
"(",
"point_in_time",
")",
"# Since this is called once, we accept a HassJob so we can avoid",
"# having to figure out how to call the action every time its called.",
"job",
"=",
"action",
"if",
"isinstance",
"(",
"action",
",",
"ha",
".",
"HassJob",
")",
"else",
"ha",
".",
"HassJob",
"(",
"action",
")",
"@",
"ha",
".",
"callback",
"def",
"point_in_time_listener",
"(",
"event",
")",
":",
"\"\"\"Listen for matching time_changed events.\"\"\"",
"now",
"=",
"event",
".",
"data",
"[",
"ATTR_NOW",
"]",
"if",
"now",
"<",
"point_in_time",
"or",
"hasattr",
"(",
"point_in_time_listener",
",",
"\"run\"",
")",
":",
"return",
"# Set variable so that we will never run twice.",
"# Because the event bus might have to wait till a thread comes",
"# available to execute this listener it might occur that the",
"# listener gets lined up twice to be executed. This will make",
"# sure the second time it does nothing.",
"setattr",
"(",
"point_in_time_listener",
",",
"\"run\"",
",",
"True",
")",
"async_unsub",
"(",
")",
"hass",
".",
"async_run_hass_job",
"(",
"job",
",",
"now",
")",
"async_unsub",
"=",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_TIME_CHANGED",
",",
"point_in_time_listener",
")",
"return",
"async_unsub",
"@",
"ha",
".",
"callback",
"@",
"loader",
".",
"bind_hass",
"def",
"async_track_utc_time_change",
"(",
"hass",
",",
"action",
",",
"hour",
"=",
"None",
",",
"minute",
"=",
"None",
",",
"second",
"=",
"None",
",",
"local",
"=",
"False",
")",
":",
"\"\"\"Add a listener that will fire if time matches a pattern.\"\"\"",
"job",
"=",
"ha",
".",
"HassJob",
"(",
"action",
")",
"# We do not have to wrap the function with time pattern matching logic",
"# if no pattern given",
"if",
"all",
"(",
"val",
"is",
"None",
"for",
"val",
"in",
"(",
"hour",
",",
"minute",
",",
"second",
")",
")",
":",
"@",
"ha",
".",
"callback",
"def",
"time_change_listener",
"(",
"ev",
")",
"->",
"None",
":",
"\"\"\"Fire every time event that comes in.\"\"\"",
"hass",
".",
"async_run_hass_job",
"(",
"job",
",",
"ev",
".",
"data",
"[",
"ATTR_NOW",
"]",
")",
"return",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_TIME_CHANGED",
",",
"time_change_listener",
")",
"matching_seconds",
"=",
"event",
".",
"dt_util",
".",
"parse_time_expression",
"(",
"second",
",",
"0",
",",
"59",
")",
"matching_minutes",
"=",
"event",
".",
"dt_util",
".",
"parse_time_expression",
"(",
"minute",
",",
"0",
",",
"59",
")",
"matching_hours",
"=",
"event",
".",
"dt_util",
".",
"parse_time_expression",
"(",
"hour",
",",
"0",
",",
"23",
")",
"next_time",
"=",
"None",
"def",
"calculate_next",
"(",
"now",
")",
"->",
"None",
":",
"\"\"\"Calculate and set the next time the trigger should fire.\"\"\"",
"nonlocal",
"next_time",
"localized_now",
"=",
"event",
".",
"dt_util",
".",
"as_local",
"(",
"now",
")",
"if",
"local",
"else",
"now",
"next_time",
"=",
"event",
".",
"dt_util",
".",
"find_next_time_expression_time",
"(",
"localized_now",
",",
"matching_seconds",
",",
"matching_minutes",
",",
"matching_hours",
")",
"# Make sure rolling back the clock doesn't prevent the timer from",
"# triggering.",
"last_now",
"=",
"None",
"@",
"ha",
".",
"callback",
"def",
"pattern_time_change_listener",
"(",
"ev",
")",
"->",
"None",
":",
"\"\"\"Listen for matching time_changed events.\"\"\"",
"nonlocal",
"next_time",
",",
"last_now",
"now",
"=",
"ev",
".",
"data",
"[",
"ATTR_NOW",
"]",
"if",
"last_now",
"is",
"None",
"or",
"now",
"<",
"last_now",
":",
"# Time rolled back or next time not yet calculated",
"calculate_next",
"(",
"now",
")",
"last_now",
"=",
"now",
"if",
"next_time",
"<=",
"now",
":",
"hass",
".",
"async_run_hass_job",
"(",
"job",
",",
"event",
".",
"dt_util",
".",
"as_local",
"(",
"now",
")",
"if",
"local",
"else",
"now",
")",
"calculate_next",
"(",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
")",
"# We can't use async_track_point_in_utc_time here because it would",
"# break in the case that the system time abruptly jumps backwards.",
"# Our custom last_now logic takes care of resolving that scenario.",
"return",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_TIME_CHANGED",
",",
"pattern_time_change_listener",
")",
"with",
"patch",
"(",
"\"homeassistant.helpers.event.async_track_point_in_utc_time\"",
",",
"async_track_point_in_utc_time",
",",
")",
",",
"patch",
"(",
"\"homeassistant.helpers.event.async_track_utc_time_change\"",
",",
"async_track_utc_time_change",
",",
")",
":",
"yield"
] | [
422,
0
] | [
527,
13
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Add a GIOS entities from a config_entry. | Add a GIOS entities from a config_entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Add a GIOS entities from a config_entry."""
name = config_entry.data[CONF_NAME]
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities([GiosAirQuality(coordinator, name)], False) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"name",
"=",
"config_entry",
".",
"data",
"[",
"CONF_NAME",
"]",
"coordinator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"async_add_entities",
"(",
"[",
"GiosAirQuality",
"(",
"coordinator",
",",
"name",
")",
"]",
",",
"False",
")"
] | [
29,
0
] | [
35,
66
] | python | en | ['en', 'en', 'en'] | True |
round_state | (func) | Round state. | Round state. | def round_state(func):
"""Round state."""
def _decorator(self):
res = func(self)
if isinstance(res, float):
return round(res)
return res
return _decorator | [
"def",
"round_state",
"(",
"func",
")",
":",
"def",
"_decorator",
"(",
"self",
")",
":",
"res",
"=",
"func",
"(",
"self",
")",
"if",
"isinstance",
"(",
"res",
",",
"float",
")",
":",
"return",
"round",
"(",
"res",
")",
"return",
"res",
"return",
"_decorator"
] | [
38,
0
] | [
47,
21
] | python | en | ['en', 'sn', 'en'] | False |
GiosAirQuality.__init__ | (self, coordinator, name) | Initialize. | Initialize. | def __init__(self, coordinator, name):
"""Initialize."""
super().__init__(coordinator)
self._name = name
self._attrs = {} | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
",",
"name",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
")",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_attrs",
"=",
"{",
"}"
] | [
53,
4
] | [
57,
24
] | python | en | ['en', 'en', 'it'] | False |
GiosAirQuality.name | (self) | Return the name. | Return the name. | def name(self):
"""Return the name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
60,
4
] | [
62,
25
] | python | en | ['en', 'ig', 'en'] | True |
GiosAirQuality.icon | (self) | Return the icon. | Return the icon. | def icon(self):
"""Return the icon."""
if self.air_quality_index in ICONS_MAP:
return ICONS_MAP[self.air_quality_index]
return "mdi:blur" | [
"def",
"icon",
"(",
"self",
")",
":",
"if",
"self",
".",
"air_quality_index",
"in",
"ICONS_MAP",
":",
"return",
"ICONS_MAP",
"[",
"self",
".",
"air_quality_index",
"]",
"return",
"\"mdi:blur\""
] | [
65,
4
] | [
69,
25
] | python | en | ['en', 'sr', 'en'] | True |
GiosAirQuality.air_quality_index | (self) | Return the air quality index. | Return the air quality index. | def air_quality_index(self):
"""Return the air quality index."""
return self._get_sensor_value("AQI") | [
"def",
"air_quality_index",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"AQI\"",
")"
] | [
72,
4
] | [
74,
44
] | python | en | ['en', 'en', 'en'] | True |
GiosAirQuality.particulate_matter_2_5 | (self) | Return the particulate matter 2.5 level. | Return the particulate matter 2.5 level. | def particulate_matter_2_5(self):
"""Return the particulate matter 2.5 level."""
return self._get_sensor_value("PM2.5") | [
"def",
"particulate_matter_2_5",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"PM2.5\"",
")"
] | [
78,
4
] | [
80,
46
] | python | en | ['en', 'en', 'en'] | True |
GiosAirQuality.particulate_matter_10 | (self) | Return the particulate matter 10 level. | Return the particulate matter 10 level. | def particulate_matter_10(self):
"""Return the particulate matter 10 level."""
return self._get_sensor_value("PM10") | [
"def",
"particulate_matter_10",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"PM10\"",
")"
] | [
84,
4
] | [
86,
45
] | python | en | ['en', 'en', 'en'] | True |
GiosAirQuality.ozone | (self) | Return the O3 (ozone) level. | Return the O3 (ozone) level. | def ozone(self):
"""Return the O3 (ozone) level."""
return self._get_sensor_value("O3") | [
"def",
"ozone",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"O3\"",
")"
] | [
90,
4
] | [
92,
43
] | python | en | ['en', 'ig', 'en'] | True |
GiosAirQuality.carbon_monoxide | (self) | Return the CO (carbon monoxide) level. | Return the CO (carbon monoxide) level. | def carbon_monoxide(self):
"""Return the CO (carbon monoxide) level."""
return self._get_sensor_value("CO") | [
"def",
"carbon_monoxide",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"CO\"",
")"
] | [
96,
4
] | [
98,
43
] | python | en | ['en', 'fr', 'en'] | True |
GiosAirQuality.sulphur_dioxide | (self) | Return the SO2 (sulphur dioxide) level. | Return the SO2 (sulphur dioxide) level. | def sulphur_dioxide(self):
"""Return the SO2 (sulphur dioxide) level."""
return self._get_sensor_value("SO2") | [
"def",
"sulphur_dioxide",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"SO2\"",
")"
] | [
102,
4
] | [
104,
44
] | python | en | ['en', 'no', 'en'] | True |
GiosAirQuality.nitrogen_dioxide | (self) | Return the NO2 (nitrogen dioxide) level. | Return the NO2 (nitrogen dioxide) level. | def nitrogen_dioxide(self):
"""Return the NO2 (nitrogen dioxide) level."""
return self._get_sensor_value("NO2") | [
"def",
"nitrogen_dioxide",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_sensor_value",
"(",
"\"NO2\"",
")"
] | [
108,
4
] | [
110,
44
] | python | en | ['en', 'da', 'en'] | True |
GiosAirQuality.attribution | (self) | Return the attribution. | Return the attribution. | def attribution(self):
"""Return the attribution."""
return ATTRIBUTION | [
"def",
"attribution",
"(",
"self",
")",
":",
"return",
"ATTRIBUTION"
] | [
113,
4
] | [
115,
26
] | python | en | ['en', 'ja', 'en'] | True |
GiosAirQuality.unique_id | (self) | Return a unique_id for this entity. | Return a unique_id for this entity. | def unique_id(self):
"""Return a unique_id for this entity."""
return self.coordinator.gios.station_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"coordinator",
".",
"gios",
".",
"station_id"
] | [
118,
4
] | [
120,
47
] | python | en | ['en', 'en', 'en'] | True |
GiosAirQuality.device_info | (self) | Return the device info. | Return the device info. | def device_info(self):
"""Return the device info."""
return {
"identifiers": {(DOMAIN, self.coordinator.gios.station_id)},
"name": DEFAULT_NAME,
"manufacturer": MANUFACTURER,
"entry_type": "service",
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"coordinator",
".",
"gios",
".",
"station_id",
")",
"}",
",",
"\"name\"",
":",
"DEFAULT_NAME",
",",
"\"manufacturer\"",
":",
"MANUFACTURER",
",",
"\"entry_type\"",
":",
"\"service\"",
",",
"}"
] | [
123,
4
] | [
130,
9
] | python | en | ['en', 'en', 'en'] | True |
GiosAirQuality.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
# Different measuring stations have different sets of sensors. We don't know
# what data we will get.
for sensor in SENSOR_MAP:
if sensor in self.coordinator.data:
self._attrs[f"{SENSOR_MAP[sensor]}_index"] = self.coordinator.data[
sensor
]["index"]
self._attrs[ATTR_STATION] = self.coordinator.gios.station_name
return self._attrs | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"# Different measuring stations have different sets of sensors. We don't know",
"# what data we will get.",
"for",
"sensor",
"in",
"SENSOR_MAP",
":",
"if",
"sensor",
"in",
"self",
".",
"coordinator",
".",
"data",
":",
"self",
".",
"_attrs",
"[",
"f\"{SENSOR_MAP[sensor]}_index\"",
"]",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"sensor",
"]",
"[",
"\"index\"",
"]",
"self",
".",
"_attrs",
"[",
"ATTR_STATION",
"]",
"=",
"self",
".",
"coordinator",
".",
"gios",
".",
"station_name",
"return",
"self",
".",
"_attrs"
] | [
133,
4
] | [
143,
26
] | python | en | ['en', 'en', 'en'] | True |
GiosAirQuality._get_sensor_value | (self, sensor) | Return value of specified sensor. | Return value of specified sensor. | def _get_sensor_value(self, sensor):
"""Return value of specified sensor."""
if sensor in self.coordinator.data:
return self.coordinator.data[sensor]["value"]
return None | [
"def",
"_get_sensor_value",
"(",
"self",
",",
"sensor",
")",
":",
"if",
"sensor",
"in",
"self",
".",
"coordinator",
".",
"data",
":",
"return",
"self",
".",
"coordinator",
".",
"data",
"[",
"sensor",
"]",
"[",
"\"value\"",
"]",
"return",
"None"
] | [
145,
4
] | [
149,
19
] | python | en | ['en', 'da', 'en'] | True |
alter_time | (retval) | Manage multiple time mocks. | Manage multiple time mocks. | def alter_time(retval):
"""Manage multiple time mocks."""
patch1 = patch("homeassistant.util.dt.utcnow", return_value=retval)
patch2 = patch("homeassistant.util.dt.now", return_value=retval)
with patch1, patch2:
yield | [
"def",
"alter_time",
"(",
"retval",
")",
":",
"patch1",
"=",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"retval",
")",
"patch2",
"=",
"patch",
"(",
"\"homeassistant.util.dt.now\"",
",",
"return_value",
"=",
"retval",
")",
"with",
"patch1",
",",
"patch2",
":",
"yield"
] | [
26,
0
] | [
32,
13
] | python | da | ['pl', 'da', 'en'] | False |
test_state | (hass) | Test utility sensor state. | Test utility sensor state. | async def test_state(hass):
"""Test utility sensor state."""
config = {
"utility_meter": {
"energy_bill": {
"source": "sensor.energy",
"tariffs": ["onpeak", "midpeak", "offpeak"],
}
}
}
assert await async_setup_component(hass, DOMAIN, config)
assert await async_setup_component(hass, SENSOR_DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(
entity_id, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}
)
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id,
3,
{ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill_onpeak")
assert state is not None
assert state.state == "1"
state = hass.states.get("sensor.energy_bill_midpeak")
assert state is not None
assert state.state == "0"
state = hass.states.get("sensor.energy_bill_offpeak")
assert state is not None
assert state.state == "0"
await hass.services.async_call(
DOMAIN,
SERVICE_SELECT_TARIFF,
{ATTR_ENTITY_ID: "utility_meter.energy_bill", ATTR_TARIFF: "offpeak"},
blocking=True,
)
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=20)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id,
6,
{ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill_onpeak")
assert state is not None
assert state.state == "1"
state = hass.states.get("sensor.energy_bill_midpeak")
assert state is not None
assert state.state == "0"
state = hass.states.get("sensor.energy_bill_offpeak")
assert state is not None
assert state.state == "3"
await hass.services.async_call(
DOMAIN,
SERVICE_CALIBRATE_METER,
{ATTR_ENTITY_ID: "sensor.energy_bill_midpeak", ATTR_VALUE: "100"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill_midpeak")
assert state is not None
assert state.state == "100"
await hass.services.async_call(
DOMAIN,
SERVICE_CALIBRATE_METER,
{ATTR_ENTITY_ID: "sensor.energy_bill_midpeak", ATTR_VALUE: "0.123"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill_midpeak")
assert state is not None
assert state.state == "0.123" | [
"async",
"def",
"test_state",
"(",
"hass",
")",
":",
"config",
"=",
"{",
"\"utility_meter\"",
":",
"{",
"\"energy_bill\"",
":",
"{",
"\"source\"",
":",
"\"sensor.energy\"",
",",
"\"tariffs\"",
":",
"[",
"\"onpeak\"",
",",
"\"midpeak\"",
",",
"\"offpeak\"",
"]",
",",
"}",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"SENSOR_DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"entity_id",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"\"energy_bill\"",
"]",
"[",
"\"source\"",
"]",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"2",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"now",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"3",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
",",
"force_update",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_onpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"1\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_midpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"0\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_offpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"0\"",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SELECT_TARIFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"utility_meter.energy_bill\"",
",",
"ATTR_TARIFF",
":",
"\"offpeak\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"20",
")",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"now",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"6",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
",",
"force_update",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_onpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"1\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_midpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"0\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_offpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"3\"",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_CALIBRATE_METER",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"sensor.energy_bill_midpeak\"",
",",
"ATTR_VALUE",
":",
"\"100\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_midpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"100\"",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_CALIBRATE_METER",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"sensor.energy_bill_midpeak\"",
",",
"ATTR_VALUE",
":",
"\"0.123\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill_midpeak\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"0.123\""
] | [
35,
0
] | [
130,
33
] | python | en | ['en', 'el-Latn', 'en'] | True |
test_net_consumption | (hass) | Test utility sensor state. | Test utility sensor state. | async def test_net_consumption(hass):
"""Test utility sensor state."""
config = {
"utility_meter": {
"energy_bill": {"source": "sensor.energy", "net_consumption": True}
}
}
assert await async_setup_component(hass, DOMAIN, config)
assert await async_setup_component(hass, SENSOR_DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(
entity_id, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}
)
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id,
1,
{ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill")
assert state is not None
assert state.state == "-1" | [
"async",
"def",
"test_net_consumption",
"(",
"hass",
")",
":",
"config",
"=",
"{",
"\"utility_meter\"",
":",
"{",
"\"energy_bill\"",
":",
"{",
"\"source\"",
":",
"\"sensor.energy\"",
",",
"\"net_consumption\"",
":",
"True",
"}",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"SENSOR_DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"entity_id",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"\"energy_bill\"",
"]",
"[",
"\"source\"",
"]",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"2",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"now",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"1",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
",",
"force_update",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"-1\""
] | [
133,
0
] | [
165,
30
] | python | en | ['en', 'el-Latn', 'en'] | True |
test_non_net_consumption | (hass) | Test utility sensor state. | Test utility sensor state. | async def test_non_net_consumption(hass):
"""Test utility sensor state."""
config = {
"utility_meter": {
"energy_bill": {"source": "sensor.energy", "net_consumption": False}
}
}
assert await async_setup_component(hass, DOMAIN, config)
assert await async_setup_component(hass, SENSOR_DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
hass.states.async_set(
entity_id, 2, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}
)
await hass.async_block_till_done()
now = dt_util.utcnow() + timedelta(seconds=10)
with patch("homeassistant.util.dt.utcnow", return_value=now):
hass.states.async_set(
entity_id,
1,
{ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill")
assert state is not None
assert state.state == "0" | [
"async",
"def",
"test_non_net_consumption",
"(",
"hass",
")",
":",
"config",
"=",
"{",
"\"utility_meter\"",
":",
"{",
"\"energy_bill\"",
":",
"{",
"\"source\"",
":",
"\"sensor.energy\"",
",",
"\"net_consumption\"",
":",
"False",
"}",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"SENSOR_DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"entity_id",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"\"energy_bill\"",
"]",
"[",
"\"source\"",
"]",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"2",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"now",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"1",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
",",
"force_update",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"0\""
] | [
168,
0
] | [
200,
29
] | python | en | ['en', 'el-Latn', 'en'] | True |
gen_config | (cycle, offset=None) | Generate configuration. | Generate configuration. | def gen_config(cycle, offset=None):
"""Generate configuration."""
config = {
"utility_meter": {"energy_bill": {"source": "sensor.energy", "cycle": cycle}}
}
if offset:
config["utility_meter"]["energy_bill"]["offset"] = {
"days": offset.days,
"seconds": offset.seconds,
}
return config | [
"def",
"gen_config",
"(",
"cycle",
",",
"offset",
"=",
"None",
")",
":",
"config",
"=",
"{",
"\"utility_meter\"",
":",
"{",
"\"energy_bill\"",
":",
"{",
"\"source\"",
":",
"\"sensor.energy\"",
",",
"\"cycle\"",
":",
"cycle",
"}",
"}",
"}",
"if",
"offset",
":",
"config",
"[",
"\"utility_meter\"",
"]",
"[",
"\"energy_bill\"",
"]",
"[",
"\"offset\"",
"]",
"=",
"{",
"\"days\"",
":",
"offset",
".",
"days",
",",
"\"seconds\"",
":",
"offset",
".",
"seconds",
",",
"}",
"return",
"config"
] | [
203,
0
] | [
214,
17
] | python | en | ['en', 'la', 'en'] | False |
_test_self_reset | (hass, config, start_time, expect_reset=True) | Test energy sensor self reset. | Test energy sensor self reset. | async def _test_self_reset(hass, config, start_time, expect_reset=True):
"""Test energy sensor self reset."""
assert await async_setup_component(hass, DOMAIN, config)
assert await async_setup_component(hass, SENSOR_DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
entity_id = config[DOMAIN]["energy_bill"]["source"]
now = dt_util.parse_datetime(start_time)
with alter_time(now):
async_fire_time_changed(hass, now)
hass.states.async_set(
entity_id, 1, {ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR}
)
await hass.async_block_till_done()
now += timedelta(seconds=30)
with alter_time(now):
async_fire_time_changed(hass, now)
hass.states.async_set(
entity_id,
3,
{ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
now += timedelta(seconds=30)
with alter_time(now):
async_fire_time_changed(hass, now)
await hass.async_block_till_done()
hass.states.async_set(
entity_id,
6,
{ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR},
force_update=True,
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill")
if expect_reset:
assert state.attributes.get("last_period") == "2"
assert state.state == "3"
else:
assert state.attributes.get("last_period") == 0
assert state.state == "5" | [
"async",
"def",
"_test_self_reset",
"(",
"hass",
",",
"config",
",",
"start_time",
",",
"expect_reset",
"=",
"True",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"SENSOR_DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"entity_id",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"\"energy_bill\"",
"]",
"[",
"\"source\"",
"]",
"now",
"=",
"dt_util",
".",
"parse_datetime",
"(",
"start_time",
")",
"with",
"alter_time",
"(",
"now",
")",
":",
"async_fire_time_changed",
"(",
"hass",
",",
"now",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"1",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"now",
"+=",
"timedelta",
"(",
"seconds",
"=",
"30",
")",
"with",
"alter_time",
"(",
"now",
")",
":",
"async_fire_time_changed",
"(",
"hass",
",",
"now",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"3",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
",",
"force_update",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"now",
"+=",
"timedelta",
"(",
"seconds",
"=",
"30",
")",
"with",
"alter_time",
"(",
"now",
")",
":",
"async_fire_time_changed",
"(",
"hass",
",",
"now",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"entity_id",
",",
"6",
",",
"{",
"ATTR_UNIT_OF_MEASUREMENT",
":",
"ENERGY_KILO_WATT_HOUR",
"}",
",",
"force_update",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.energy_bill\"",
")",
"if",
"expect_reset",
":",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"\"last_period\"",
")",
"==",
"\"2\"",
"assert",
"state",
".",
"state",
"==",
"\"3\"",
"else",
":",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"\"last_period\"",
")",
"==",
"0",
"assert",
"state",
".",
"state",
"==",
"\"5\""
] | [
217,
0
] | [
263,
33
] | python | be | ['hu', 'be', 'en'] | False |
test_self_reset_quarter_hourly | (hass, legacy_patchable_time) | Test quarter-hourly reset of meter. | Test quarter-hourly reset of meter. | async def test_self_reset_quarter_hourly(hass, legacy_patchable_time):
"""Test quarter-hourly reset of meter."""
await _test_self_reset(
hass, gen_config("quarter-hourly"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_quarter_hourly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"quarter-hourly\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
266,
0
] | [
270,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_reset_quarter_hourly_first_quarter | (hass, legacy_patchable_time) | Test quarter-hourly reset of meter. | Test quarter-hourly reset of meter. | async def test_self_reset_quarter_hourly_first_quarter(hass, legacy_patchable_time):
"""Test quarter-hourly reset of meter."""
await _test_self_reset(
hass, gen_config("quarter-hourly"), "2017-12-31T23:14:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_quarter_hourly_first_quarter",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"quarter-hourly\"",
")",
",",
"\"2017-12-31T23:14:00.000000+00:00\"",
")"
] | [
273,
0
] | [
277,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_reset_quarter_hourly_second_quarter | (hass, legacy_patchable_time) | Test quarter-hourly reset of meter. | Test quarter-hourly reset of meter. | async def test_self_reset_quarter_hourly_second_quarter(hass, legacy_patchable_time):
"""Test quarter-hourly reset of meter."""
await _test_self_reset(
hass, gen_config("quarter-hourly"), "2017-12-31T23:29:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_quarter_hourly_second_quarter",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"quarter-hourly\"",
")",
",",
"\"2017-12-31T23:29:00.000000+00:00\"",
")"
] | [
280,
0
] | [
284,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_reset_quarter_hourly_third_quarter | (hass, legacy_patchable_time) | Test quarter-hourly reset of meter. | Test quarter-hourly reset of meter. | async def test_self_reset_quarter_hourly_third_quarter(hass, legacy_patchable_time):
"""Test quarter-hourly reset of meter."""
await _test_self_reset(
hass, gen_config("quarter-hourly"), "2017-12-31T23:44:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_quarter_hourly_third_quarter",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"quarter-hourly\"",
")",
",",
"\"2017-12-31T23:44:00.000000+00:00\"",
")"
] | [
287,
0
] | [
291,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_reset_hourly | (hass, legacy_patchable_time) | Test hourly reset of meter. | Test hourly reset of meter. | async def test_self_reset_hourly(hass, legacy_patchable_time):
"""Test hourly reset of meter."""
await _test_self_reset(
hass, gen_config("hourly"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_hourly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"hourly\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
294,
0
] | [
298,
5
] | python | en | ['en', 'nl', 'en'] | True |
test_self_reset_daily | (hass, legacy_patchable_time) | Test daily reset of meter. | Test daily reset of meter. | async def test_self_reset_daily(hass, legacy_patchable_time):
"""Test daily reset of meter."""
await _test_self_reset(
hass, gen_config("daily"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_daily",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"daily\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
301,
0
] | [
305,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_reset_weekly | (hass, legacy_patchable_time) | Test weekly reset of meter. | Test weekly reset of meter. | async def test_self_reset_weekly(hass, legacy_patchable_time):
"""Test weekly reset of meter."""
await _test_self_reset(
hass, gen_config("weekly"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_weekly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"weekly\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
308,
0
] | [
312,
5
] | python | en | ['en', 'af', 'en'] | True |
test_self_reset_monthly | (hass, legacy_patchable_time) | Test monthly reset of meter. | Test monthly reset of meter. | async def test_self_reset_monthly(hass, legacy_patchable_time):
"""Test monthly reset of meter."""
await _test_self_reset(
hass, gen_config("monthly"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_monthly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"monthly\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
315,
0
] | [
319,
5
] | python | en | ['en', 'nl', 'en'] | True |
test_self_reset_bimonthly | (hass, legacy_patchable_time) | Test bimonthly reset of meter occurs on even months. | Test bimonthly reset of meter occurs on even months. | async def test_self_reset_bimonthly(hass, legacy_patchable_time):
"""Test bimonthly reset of meter occurs on even months."""
await _test_self_reset(
hass, gen_config("bimonthly"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_bimonthly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"bimonthly\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
322,
0
] | [
326,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_no_reset_bimonthly | (hass, legacy_patchable_time) | Test bimonthly reset of meter does not occur on odd months. | Test bimonthly reset of meter does not occur on odd months. | async def test_self_no_reset_bimonthly(hass, legacy_patchable_time):
"""Test bimonthly reset of meter does not occur on odd months."""
await _test_self_reset(
hass,
gen_config("bimonthly"),
"2018-01-01T23:59:00.000000+00:00",
expect_reset=False,
) | [
"async",
"def",
"test_self_no_reset_bimonthly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"bimonthly\"",
")",
",",
"\"2018-01-01T23:59:00.000000+00:00\"",
",",
"expect_reset",
"=",
"False",
",",
")"
] | [
329,
0
] | [
336,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_reset_quarterly | (hass, legacy_patchable_time) | Test quarterly reset of meter. | Test quarterly reset of meter. | async def test_self_reset_quarterly(hass, legacy_patchable_time):
"""Test quarterly reset of meter."""
await _test_self_reset(
hass, gen_config("quarterly"), "2017-03-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_quarterly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"quarterly\"",
")",
",",
"\"2017-03-31T23:59:00.000000+00:00\"",
")"
] | [
339,
0
] | [
343,
5
] | python | en | ['en', 'la', 'en'] | True |
test_self_reset_yearly | (hass, legacy_patchable_time) | Test yearly reset of meter. | Test yearly reset of meter. | async def test_self_reset_yearly(hass, legacy_patchable_time):
"""Test yearly reset of meter."""
await _test_self_reset(
hass, gen_config("yearly"), "2017-12-31T23:59:00.000000+00:00"
) | [
"async",
"def",
"test_self_reset_yearly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"yearly\"",
")",
",",
"\"2017-12-31T23:59:00.000000+00:00\"",
")"
] | [
346,
0
] | [
350,
5
] | python | en | ['en', 'en', 'en'] | True |
test_self_no_reset_yearly | (hass, legacy_patchable_time) | Test yearly reset of meter does not occur after 1st January. | Test yearly reset of meter does not occur after 1st January. | async def test_self_no_reset_yearly(hass, legacy_patchable_time):
"""Test yearly reset of meter does not occur after 1st January."""
await _test_self_reset(
hass,
gen_config("yearly"),
"2018-01-01T23:59:00.000000+00:00",
expect_reset=False,
) | [
"async",
"def",
"test_self_no_reset_yearly",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"yearly\"",
")",
",",
"\"2018-01-01T23:59:00.000000+00:00\"",
",",
"expect_reset",
"=",
"False",
",",
")"
] | [
353,
0
] | [
360,
5
] | python | en | ['en', 'en', 'en'] | True |
test_reset_yearly_offset | (hass, legacy_patchable_time) | Test yearly reset of meter. | Test yearly reset of meter. | async def test_reset_yearly_offset(hass, legacy_patchable_time):
"""Test yearly reset of meter."""
await _test_self_reset(
hass,
gen_config("yearly", timedelta(days=1, minutes=10)),
"2018-01-02T00:09:00.000000+00:00",
) | [
"async",
"def",
"test_reset_yearly_offset",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"yearly\"",
",",
"timedelta",
"(",
"days",
"=",
"1",
",",
"minutes",
"=",
"10",
")",
")",
",",
"\"2018-01-02T00:09:00.000000+00:00\"",
",",
")"
] | [
363,
0
] | [
369,
5
] | python | en | ['en', 'en', 'en'] | True |
test_no_reset_yearly_offset | (hass, legacy_patchable_time) | Test yearly reset of meter. | Test yearly reset of meter. | async def test_no_reset_yearly_offset(hass, legacy_patchable_time):
"""Test yearly reset of meter."""
await _test_self_reset(
hass,
gen_config("yearly", timedelta(31)),
"2018-01-30T23:59:00.000000+00:00",
expect_reset=False,
) | [
"async",
"def",
"test_no_reset_yearly_offset",
"(",
"hass",
",",
"legacy_patchable_time",
")",
":",
"await",
"_test_self_reset",
"(",
"hass",
",",
"gen_config",
"(",
"\"yearly\"",
",",
"timedelta",
"(",
"31",
")",
")",
",",
"\"2018-01-30T23:59:00.000000+00:00\"",
",",
"expect_reset",
"=",
"False",
",",
")"
] | [
372,
0
] | [
379,
5
] | python | en | ['en', 'en', 'en'] | True |
_async_has_devices | (hass) | Return if there are devices that can be discovered. | Return if there are devices that can be discovered. | async def _async_has_devices(hass) -> bool:
"""Return if there are devices that can be discovered."""
try:
devices = await hass.async_add_executor_job(pyzerproc.discover)
return len(devices) > 0
except pyzerproc.ZerprocException:
_LOGGER.error("Unable to discover nearby Zerproc devices", exc_info=True)
return False | [
"async",
"def",
"_async_has_devices",
"(",
"hass",
")",
"->",
"bool",
":",
"try",
":",
"devices",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"pyzerproc",
".",
"discover",
")",
"return",
"len",
"(",
"devices",
")",
">",
"0",
"except",
"pyzerproc",
".",
"ZerprocException",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to discover nearby Zerproc devices\"",
",",
"exc_info",
"=",
"True",
")",
"return",
"False"
] | [
13,
0
] | [
20,
20
] | python | en | ['en', 'en', 'en'] | True |
DropPath.__init__ | (self, p=0.) |
Drop path with probability.
Parameters
----------
p : float
Probability of an path to be zeroed.
|
Drop path with probability. | def __init__(self, p=0.):
"""
Drop path with probability.
Parameters
----------
p : float
Probability of an path to be zeroed.
"""
super().__init__()
self.p = p | [
"def",
"__init__",
"(",
"self",
",",
"p",
"=",
"0.",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"p",
"=",
"p"
] | [
30,
4
] | [
40,
18
] | python | en | ['en', 'error', 'th'] | False |
fill_in_schema_dict | (some_input) | Fill in schema dict defaults from user_input. | Fill in schema dict defaults from user_input. | def fill_in_schema_dict(some_input):
"""Fill in schema dict defaults from user_input."""
schema_dict = {}
for field, _type in DATA_SCHEMA_DICT.items():
if some_input.get(str(field)):
schema_dict[
vol.Optional(str(field), default=some_input[str(field)])
] = _type
else:
schema_dict[field] = _type
return schema_dict | [
"def",
"fill_in_schema_dict",
"(",
"some_input",
")",
":",
"schema_dict",
"=",
"{",
"}",
"for",
"field",
",",
"_type",
"in",
"DATA_SCHEMA_DICT",
".",
"items",
"(",
")",
":",
"if",
"some_input",
".",
"get",
"(",
"str",
"(",
"field",
")",
")",
":",
"schema_dict",
"[",
"vol",
".",
"Optional",
"(",
"str",
"(",
"field",
")",
",",
"default",
"=",
"some_input",
"[",
"str",
"(",
"field",
")",
"]",
")",
"]",
"=",
"_type",
"else",
":",
"schema_dict",
"[",
"field",
"]",
"=",
"_type",
"return",
"schema_dict"
] | [
85,
0
] | [
95,
22
] | python | en | ['en', 'en', 'en'] | True |
ForkedDaapdOptionsFlowHandler.__init__ | (self, config_entry) | Initialize. | Initialize. | def __init__(self, config_entry):
"""Initialize."""
self.config_entry = config_entry | [
"def",
"__init__",
"(",
"self",
",",
"config_entry",
")",
":",
"self",
".",
"config_entry",
"=",
"config_entry"
] | [
45,
4
] | [
47,
40
] | python | en | ['en', 'en', 'it'] | False |
ForkedDaapdOptionsFlowHandler.async_step_init | (self, user_input=None) | Manage the options. | Manage the options. | async def async_step_init(self, user_input=None):
"""Manage the options."""
if user_input is not None:
return self.async_create_entry(title="options", data=user_input)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional(
CONF_TTS_PAUSE_TIME,
default=self.config_entry.options.get(
CONF_TTS_PAUSE_TIME, DEFAULT_TTS_PAUSE_TIME
),
): float,
vol.Optional(
CONF_TTS_VOLUME,
default=self.config_entry.options.get(
CONF_TTS_VOLUME, DEFAULT_TTS_VOLUME
),
): float,
vol.Optional(
CONF_LIBRESPOT_JAVA_PORT,
default=self.config_entry.options.get(
CONF_LIBRESPOT_JAVA_PORT, 24879
),
): int,
vol.Optional(
CONF_MAX_PLAYLISTS,
default=self.config_entry.options.get(CONF_MAX_PLAYLISTS, 10),
): int,
}
),
) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"\"options\"",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Optional",
"(",
"CONF_TTS_PAUSE_TIME",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_TTS_PAUSE_TIME",
",",
"DEFAULT_TTS_PAUSE_TIME",
")",
",",
")",
":",
"float",
",",
"vol",
".",
"Optional",
"(",
"CONF_TTS_VOLUME",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_TTS_VOLUME",
",",
"DEFAULT_TTS_VOLUME",
")",
",",
")",
":",
"float",
",",
"vol",
".",
"Optional",
"(",
"CONF_LIBRESPOT_JAVA_PORT",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_LIBRESPOT_JAVA_PORT",
",",
"24879",
")",
",",
")",
":",
"int",
",",
"vol",
".",
"Optional",
"(",
"CONF_MAX_PLAYLISTS",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_MAX_PLAYLISTS",
",",
"10",
")",
",",
")",
":",
"int",
",",
"}",
")",
",",
")"
] | [
49,
4
] | [
82,
9
] | python | en | ['en', 'en', 'en'] | True |
ForkedDaapdFlowHandler.__init__ | (self) | Initialize. | Initialize. | def __init__(self):
"""Initialize."""
self.discovery_schema = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"discovery_schema",
"=",
"None"
] | [
104,
4
] | [
106,
36
] | python | en | ['en', 'en', 'it'] | False |
ForkedDaapdFlowHandler.async_get_options_flow | (config_entry) | Return options flow handler. | Return options flow handler. | def async_get_options_flow(config_entry):
"""Return options flow handler."""
return ForkedDaapdOptionsFlowHandler(config_entry) | [
"def",
"async_get_options_flow",
"(",
"config_entry",
")",
":",
"return",
"ForkedDaapdOptionsFlowHandler",
"(",
"config_entry",
")"
] | [
110,
4
] | [
112,
58
] | python | en | ['en', 'nl', 'en'] | True |
ForkedDaapdFlowHandler.validate_input | (self, user_input) | Validate the user input. | Validate the user input. | async def validate_input(self, user_input):
"""Validate the user input."""
websession = async_get_clientsession(self.hass)
validate_result = await ForkedDaapdAPI.test_connection(
websession=websession,
host=user_input[CONF_HOST],
port=user_input[CONF_PORT],
password=user_input[CONF_PASSWORD],
)
validate_result[0] = TEST_CONNECTION_ERROR_DICT.get(
validate_result[0], "unknown_error"
)
return validate_result | [
"async",
"def",
"validate_input",
"(",
"self",
",",
"user_input",
")",
":",
"websession",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
")",
"validate_result",
"=",
"await",
"ForkedDaapdAPI",
".",
"test_connection",
"(",
"websession",
"=",
"websession",
",",
"host",
"=",
"user_input",
"[",
"CONF_HOST",
"]",
",",
"port",
"=",
"user_input",
"[",
"CONF_PORT",
"]",
",",
"password",
"=",
"user_input",
"[",
"CONF_PASSWORD",
"]",
",",
")",
"validate_result",
"[",
"0",
"]",
"=",
"TEST_CONNECTION_ERROR_DICT",
".",
"get",
"(",
"validate_result",
"[",
"0",
"]",
",",
"\"unknown_error\"",
")",
"return",
"validate_result"
] | [
114,
4
] | [
126,
30
] | python | en | ['en', 'en', 'en'] | True |
ForkedDaapdFlowHandler.async_step_user | (self, user_input=None) | Handle a forked-daapd config flow start.
Manage device specific parameters.
| Handle a forked-daapd config flow start. | async def async_step_user(self, user_input=None):
"""Handle a forked-daapd config flow start.
Manage device specific parameters.
"""
if user_input is not None:
# check for any entries with same host, abort if found
for entry in self._async_current_entries():
if entry.data.get(CONF_HOST) == user_input[CONF_HOST]:
return self.async_abort(reason="already_configured")
validate_result = await self.validate_input(user_input)
if validate_result[0] == "ok": # success
_LOGGER.debug("Connected successfully. Creating entry")
return self.async_create_entry(
title=validate_result[1], data=user_input
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(fill_in_schema_dict(user_input)),
errors={"base": validate_result[0]},
)
if self.discovery_schema: # stop at form to allow user to set up manually
return self.async_show_form(
step_id="user", data_schema=self.discovery_schema, errors={}
)
return self.async_show_form(
step_id="user", data_schema=vol.Schema(DATA_SCHEMA_DICT), errors={}
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"# check for any entries with same host, abort if found",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"if",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_HOST",
")",
"==",
"user_input",
"[",
"CONF_HOST",
"]",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"validate_result",
"=",
"await",
"self",
".",
"validate_input",
"(",
"user_input",
")",
"if",
"validate_result",
"[",
"0",
"]",
"==",
"\"ok\"",
":",
"# success",
"_LOGGER",
".",
"debug",
"(",
"\"Connected successfully. Creating entry\"",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"validate_result",
"[",
"1",
"]",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"fill_in_schema_dict",
"(",
"user_input",
")",
")",
",",
"errors",
"=",
"{",
"\"base\"",
":",
"validate_result",
"[",
"0",
"]",
"}",
",",
")",
"if",
"self",
".",
"discovery_schema",
":",
"# stop at form to allow user to set up manually",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"self",
".",
"discovery_schema",
",",
"errors",
"=",
"{",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"DATA_SCHEMA_DICT",
")",
",",
"errors",
"=",
"{",
"}",
")"
] | [
128,
4
] | [
155,
9
] | python | en | ['en', 'en', 'en'] | True |
ForkedDaapdFlowHandler.async_step_zeroconf | (self, discovery_info) | Prepare configuration for a discovered forked-daapd device. | Prepare configuration for a discovered forked-daapd device. | async def async_step_zeroconf(self, discovery_info):
"""Prepare configuration for a discovered forked-daapd device."""
version_num = 0
if discovery_info.get("properties") and discovery_info["properties"].get(
"Machine Name"
):
try:
version_num = int(
discovery_info["properties"].get("mtd-version", "0").split(".")[0]
)
except ValueError:
pass
if version_num < 27:
return self.async_abort(reason="not_forked_daapd")
await self.async_set_unique_id(discovery_info["properties"]["Machine Name"])
self._abort_if_unique_id_configured()
# Update title and abort if we already have an entry for this host
for entry in self._async_current_entries():
if entry.data.get(CONF_HOST) != discovery_info["host"]:
continue
self.hass.config_entries.async_update_entry(
entry,
title=discovery_info["properties"]["Machine Name"],
)
return self.async_abort(reason="already_configured")
zeroconf_data = {
CONF_HOST: discovery_info["host"],
CONF_PORT: int(discovery_info["port"]),
CONF_NAME: discovery_info["properties"]["Machine Name"],
}
self.discovery_schema = vol.Schema(fill_in_schema_dict(zeroconf_data))
# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167
self.context.update({"title_placeholders": zeroconf_data})
return await self.async_step_user() | [
"async",
"def",
"async_step_zeroconf",
"(",
"self",
",",
"discovery_info",
")",
":",
"version_num",
"=",
"0",
"if",
"discovery_info",
".",
"get",
"(",
"\"properties\"",
")",
"and",
"discovery_info",
"[",
"\"properties\"",
"]",
".",
"get",
"(",
"\"Machine Name\"",
")",
":",
"try",
":",
"version_num",
"=",
"int",
"(",
"discovery_info",
"[",
"\"properties\"",
"]",
".",
"get",
"(",
"\"mtd-version\"",
",",
"\"0\"",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
")",
"except",
"ValueError",
":",
"pass",
"if",
"version_num",
"<",
"27",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"not_forked_daapd\"",
")",
"await",
"self",
".",
"async_set_unique_id",
"(",
"discovery_info",
"[",
"\"properties\"",
"]",
"[",
"\"Machine Name\"",
"]",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"# Update title and abort if we already have an entry for this host",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"if",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_HOST",
")",
"!=",
"discovery_info",
"[",
"\"host\"",
"]",
":",
"continue",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"entry",
",",
"title",
"=",
"discovery_info",
"[",
"\"properties\"",
"]",
"[",
"\"Machine Name\"",
"]",
",",
")",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"zeroconf_data",
"=",
"{",
"CONF_HOST",
":",
"discovery_info",
"[",
"\"host\"",
"]",
",",
"CONF_PORT",
":",
"int",
"(",
"discovery_info",
"[",
"\"port\"",
"]",
")",
",",
"CONF_NAME",
":",
"discovery_info",
"[",
"\"properties\"",
"]",
"[",
"\"Machine Name\"",
"]",
",",
"}",
"self",
".",
"discovery_schema",
"=",
"vol",
".",
"Schema",
"(",
"fill_in_schema_dict",
"(",
"zeroconf_data",
")",
")",
"# pylint: disable=no-member # https://github.com/PyCQA/pylint/issues/3167",
"self",
".",
"context",
".",
"update",
"(",
"{",
"\"title_placeholders\"",
":",
"zeroconf_data",
"}",
")",
"return",
"await",
"self",
".",
"async_step_user",
"(",
")"
] | [
157,
4
] | [
192,
43
] | python | en | ['en', 'en', 'en'] | True |
async_setup_ha_cast | (
hass: core.HomeAssistant, entry: config_entries.ConfigEntry
) | Set up Home Assistant Cast. | Set up Home Assistant Cast. | async def async_setup_ha_cast(
hass: core.HomeAssistant, entry: config_entries.ConfigEntry
):
"""Set up Home Assistant Cast."""
user_id: Optional[str] = entry.data.get("user_id")
user: Optional[auth.models.User] = None
if user_id is not None:
user = await hass.auth.async_get_user(user_id)
if user is None:
user = await hass.auth.async_create_system_user(
"Home Assistant Cast", [auth.GROUP_ID_ADMIN]
)
hass.config_entries.async_update_entry(
entry, data={**entry.data, "user_id": user.id}
)
if user.refresh_tokens:
refresh_token: auth.models.RefreshToken = list(user.refresh_tokens.values())[0]
else:
refresh_token = await hass.auth.async_create_refresh_token(user)
async def handle_show_view(call: core.ServiceCall):
"""Handle a Show View service call."""
hass_url = get_url(hass, require_ssl=True, prefer_external=True)
controller = HomeAssistantController(
# If you are developing Home Assistant Cast, uncomment and set to your dev app id.
# app_id="5FE44367",
hass_url=hass_url,
client_id=None,
refresh_token=refresh_token.token,
)
dispatcher.async_dispatcher_send(
hass,
SIGNAL_HASS_CAST_SHOW_VIEW,
controller,
call.data[ATTR_ENTITY_ID],
call.data[ATTR_VIEW_PATH],
call.data.get(ATTR_URL_PATH),
)
hass.helpers.service.async_register_admin_service(
DOMAIN,
SERVICE_SHOW_VIEW,
handle_show_view,
vol.Schema(
{
ATTR_ENTITY_ID: cv.entity_id,
ATTR_VIEW_PATH: str,
vol.Optional(ATTR_URL_PATH): str,
}
),
) | [
"async",
"def",
"async_setup_ha_cast",
"(",
"hass",
":",
"core",
".",
"HomeAssistant",
",",
"entry",
":",
"config_entries",
".",
"ConfigEntry",
")",
":",
"user_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"entry",
".",
"data",
".",
"get",
"(",
"\"user_id\"",
")",
"user",
":",
"Optional",
"[",
"auth",
".",
"models",
".",
"User",
"]",
"=",
"None",
"if",
"user_id",
"is",
"not",
"None",
":",
"user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_get_user",
"(",
"user_id",
")",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_system_user",
"(",
"\"Home Assistant Cast\"",
",",
"[",
"auth",
".",
"GROUP_ID_ADMIN",
"]",
")",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"entry",
",",
"data",
"=",
"{",
"*",
"*",
"entry",
".",
"data",
",",
"\"user_id\"",
":",
"user",
".",
"id",
"}",
")",
"if",
"user",
".",
"refresh_tokens",
":",
"refresh_token",
":",
"auth",
".",
"models",
".",
"RefreshToken",
"=",
"list",
"(",
"user",
".",
"refresh_tokens",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"else",
":",
"refresh_token",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_refresh_token",
"(",
"user",
")",
"async",
"def",
"handle_show_view",
"(",
"call",
":",
"core",
".",
"ServiceCall",
")",
":",
"\"\"\"Handle a Show View service call.\"\"\"",
"hass_url",
"=",
"get_url",
"(",
"hass",
",",
"require_ssl",
"=",
"True",
",",
"prefer_external",
"=",
"True",
")",
"controller",
"=",
"HomeAssistantController",
"(",
"# If you are developing Home Assistant Cast, uncomment and set to your dev app id.",
"# app_id=\"5FE44367\",",
"hass_url",
"=",
"hass_url",
",",
"client_id",
"=",
"None",
",",
"refresh_token",
"=",
"refresh_token",
".",
"token",
",",
")",
"dispatcher",
".",
"async_dispatcher_send",
"(",
"hass",
",",
"SIGNAL_HASS_CAST_SHOW_VIEW",
",",
"controller",
",",
"call",
".",
"data",
"[",
"ATTR_ENTITY_ID",
"]",
",",
"call",
".",
"data",
"[",
"ATTR_VIEW_PATH",
"]",
",",
"call",
".",
"data",
".",
"get",
"(",
"ATTR_URL_PATH",
")",
",",
")",
"hass",
".",
"helpers",
".",
"service",
".",
"async_register_admin_service",
"(",
"DOMAIN",
",",
"SERVICE_SHOW_VIEW",
",",
"handle_show_view",
",",
"vol",
".",
"Schema",
"(",
"{",
"ATTR_ENTITY_ID",
":",
"cv",
".",
"entity_id",
",",
"ATTR_VIEW_PATH",
":",
"str",
",",
"vol",
".",
"Optional",
"(",
"ATTR_URL_PATH",
")",
":",
"str",
",",
"}",
")",
",",
")"
] | [
18,
0
] | [
73,
5
] | python | en | ['en', 'fr', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the HomeMatic binary sensor platform. | Set up the HomeMatic binary sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the HomeMatic binary sensor platform."""
if discovery_info is None:
return
devices = []
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
if discovery_info[ATTR_DISCOVERY_TYPE] == DISCOVER_BATTERY:
devices.append(HMBatterySensor(conf))
else:
devices.append(HMBinarySensor(conf))
add_entities(devices, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"devices",
"=",
"[",
"]",
"for",
"conf",
"in",
"discovery_info",
"[",
"ATTR_DISCOVER_DEVICES",
"]",
":",
"if",
"discovery_info",
"[",
"ATTR_DISCOVERY_TYPE",
"]",
"==",
"DISCOVER_BATTERY",
":",
"devices",
".",
"append",
"(",
"HMBatterySensor",
"(",
"conf",
")",
")",
"else",
":",
"devices",
".",
"append",
"(",
"HMBinarySensor",
"(",
"conf",
")",
")",
"add_entities",
"(",
"devices",
",",
"True",
")"
] | [
33,
0
] | [
45,
31
] | python | en | ['en', 'pt', 'en'] | True |
HMBinarySensor.is_on | (self) | Return true if switch is on. | Return true if switch is on. | def is_on(self):
"""Return true if switch is on."""
if not self.available:
return False
return bool(self._hm_get_state()) | [
"def",
"is_on",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"available",
":",
"return",
"False",
"return",
"bool",
"(",
"self",
".",
"_hm_get_state",
"(",
")",
")"
] | [
52,
4
] | [
56,
41
] | python | en | ['en', 'fy', 'en'] | True |
HMBinarySensor.device_class | (self) | Return the class of this sensor from DEVICE_CLASSES. | Return the class of this sensor from DEVICE_CLASSES. | def device_class(self):
"""Return the class of this sensor from DEVICE_CLASSES."""
# If state is MOTION (Only RemoteMotion working)
if self._state == "MOTION":
return DEVICE_CLASS_MOTION
return SENSOR_TYPES_CLASS.get(self._hmdevice.__class__.__name__) | [
"def",
"device_class",
"(",
"self",
")",
":",
"# If state is MOTION (Only RemoteMotion working)",
"if",
"self",
".",
"_state",
"==",
"\"MOTION\"",
":",
"return",
"DEVICE_CLASS_MOTION",
"return",
"SENSOR_TYPES_CLASS",
".",
"get",
"(",
"self",
".",
"_hmdevice",
".",
"__class__",
".",
"__name__",
")"
] | [
59,
4
] | [
64,
72
] | python | en | ['en', 'en', 'en'] | True |
HMBinarySensor._init_data_struct | (self) | Generate the data dictionary (self._data) from metadata. | Generate the data dictionary (self._data) from metadata. | def _init_data_struct(self):
"""Generate the data dictionary (self._data) from metadata."""
# Add state to data struct
if self._state:
self._data.update({self._state: None}) | [
"def",
"_init_data_struct",
"(",
"self",
")",
":",
"# Add state to data struct",
"if",
"self",
".",
"_state",
":",
"self",
".",
"_data",
".",
"update",
"(",
"{",
"self",
".",
"_state",
":",
"None",
"}",
")"
] | [
66,
4
] | [
70,
50
] | python | en | ['en', 'en', 'en'] | True |
HMBatterySensor.device_class | (self) | Return battery as a device class. | Return battery as a device class. | def device_class(self):
"""Return battery as a device class."""
return DEVICE_CLASS_BATTERY | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_BATTERY"
] | [
77,
4
] | [
79,
35
] | python | en | ['en', 'en', 'en'] | True |
HMBatterySensor.is_on | (self) | Return True if battery is low. | Return True if battery is low. | def is_on(self):
"""Return True if battery is low."""
return bool(self._hm_get_state()) | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_hm_get_state",
"(",
")",
")"
] | [
82,
4
] | [
84,
41
] | python | en | ['en', 'fy', 'en'] | True |
HMBatterySensor._init_data_struct | (self) | Generate the data dictionary (self._data) from metadata. | Generate the data dictionary (self._data) from metadata. | def _init_data_struct(self):
"""Generate the data dictionary (self._data) from metadata."""
# Add state to data struct
if self._state:
self._data.update({self._state: None}) | [
"def",
"_init_data_struct",
"(",
"self",
")",
":",
"# Add state to data struct",
"if",
"self",
".",
"_state",
":",
"self",
".",
"_data",
".",
"update",
"(",
"{",
"self",
".",
"_state",
":",
"None",
"}",
")"
] | [
86,
4
] | [
90,
50
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the Arduino component. | Set up the Arduino component. | def setup(hass, config):
"""Set up the Arduino component."""
_LOGGER.warning(
"The %s integration has been deprecated. Please move your "
"configuration to the firmata integration. "
"https://www.home-assistant.io/integrations/firmata",
DOMAIN,
)
port = config[DOMAIN][CONF_PORT]
try:
board = ArduinoBoard(port)
except (serial.serialutil.SerialException, FileNotFoundError):
_LOGGER.error("Your port %s is not accessible", port)
return False
try:
if board.get_firmata()[1] <= 2:
_LOGGER.error("The StandardFirmata sketch should be 2.2 or newer")
return False
except IndexError:
_LOGGER.warning(
"The version of the StandardFirmata sketch was not"
"detected. This may lead to side effects"
)
def stop_arduino(event):
"""Stop the Arduino service."""
board.disconnect()
def start_arduino(event):
"""Start the Arduino service."""
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_arduino)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_arduino)
hass.data[DOMAIN] = board
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"\"The %s integration has been deprecated. Please move your \"",
"\"configuration to the firmata integration. \"",
"\"https://www.home-assistant.io/integrations/firmata\"",
",",
"DOMAIN",
",",
")",
"port",
"=",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_PORT",
"]",
"try",
":",
"board",
"=",
"ArduinoBoard",
"(",
"port",
")",
"except",
"(",
"serial",
".",
"serialutil",
".",
"SerialException",
",",
"FileNotFoundError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Your port %s is not accessible\"",
",",
"port",
")",
"return",
"False",
"try",
":",
"if",
"board",
".",
"get_firmata",
"(",
")",
"[",
"1",
"]",
"<=",
"2",
":",
"_LOGGER",
".",
"error",
"(",
"\"The StandardFirmata sketch should be 2.2 or newer\"",
")",
"return",
"False",
"except",
"IndexError",
":",
"_LOGGER",
".",
"warning",
"(",
"\"The version of the StandardFirmata sketch was not\"",
"\"detected. This may lead to side effects\"",
")",
"def",
"stop_arduino",
"(",
"event",
")",
":",
"\"\"\"Stop the Arduino service.\"\"\"",
"board",
".",
"disconnect",
"(",
")",
"def",
"start_arduino",
"(",
"event",
")",
":",
"\"\"\"Start the Arduino service.\"\"\"",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"stop_arduino",
")",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"start_arduino",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"board",
"return",
"True"
] | [
23,
0
] | [
61,
15
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.__init__ | (self, port) | Initialize the board. | Initialize the board. | def __init__(self, port):
"""Initialize the board."""
self._port = port
self._board = PyMata(self._port, verbose=False) | [
"def",
"__init__",
"(",
"self",
",",
"port",
")",
":",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"_board",
"=",
"PyMata",
"(",
"self",
".",
"_port",
",",
"verbose",
"=",
"False",
")"
] | [
67,
4
] | [
71,
55
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.set_mode | (self, pin, direction, mode) | Set the mode and the direction of a given pin. | Set the mode and the direction of a given pin. | def set_mode(self, pin, direction, mode):
"""Set the mode and the direction of a given pin."""
if mode == "analog" and direction == "in":
self._board.set_pin_mode(pin, self._board.INPUT, self._board.ANALOG)
elif mode == "analog" and direction == "out":
self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.ANALOG)
elif mode == "digital" and direction == "in":
self._board.set_pin_mode(pin, self._board.INPUT, self._board.DIGITAL)
elif mode == "digital" and direction == "out":
self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL)
elif mode == "pwm":
self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.PWM) | [
"def",
"set_mode",
"(",
"self",
",",
"pin",
",",
"direction",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"\"analog\"",
"and",
"direction",
"==",
"\"in\"",
":",
"self",
".",
"_board",
".",
"set_pin_mode",
"(",
"pin",
",",
"self",
".",
"_board",
".",
"INPUT",
",",
"self",
".",
"_board",
".",
"ANALOG",
")",
"elif",
"mode",
"==",
"\"analog\"",
"and",
"direction",
"==",
"\"out\"",
":",
"self",
".",
"_board",
".",
"set_pin_mode",
"(",
"pin",
",",
"self",
".",
"_board",
".",
"OUTPUT",
",",
"self",
".",
"_board",
".",
"ANALOG",
")",
"elif",
"mode",
"==",
"\"digital\"",
"and",
"direction",
"==",
"\"in\"",
":",
"self",
".",
"_board",
".",
"set_pin_mode",
"(",
"pin",
",",
"self",
".",
"_board",
".",
"INPUT",
",",
"self",
".",
"_board",
".",
"DIGITAL",
")",
"elif",
"mode",
"==",
"\"digital\"",
"and",
"direction",
"==",
"\"out\"",
":",
"self",
".",
"_board",
".",
"set_pin_mode",
"(",
"pin",
",",
"self",
".",
"_board",
".",
"OUTPUT",
",",
"self",
".",
"_board",
".",
"DIGITAL",
")",
"elif",
"mode",
"==",
"\"pwm\"",
":",
"self",
".",
"_board",
".",
"set_pin_mode",
"(",
"pin",
",",
"self",
".",
"_board",
".",
"OUTPUT",
",",
"self",
".",
"_board",
".",
"PWM",
")"
] | [
73,
4
] | [
84,
78
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.get_analog_inputs | (self) | Get the values from the pins. | Get the values from the pins. | def get_analog_inputs(self):
"""Get the values from the pins."""
self._board.capability_query()
return self._board.get_analog_response_table() | [
"def",
"get_analog_inputs",
"(",
"self",
")",
":",
"self",
".",
"_board",
".",
"capability_query",
"(",
")",
"return",
"self",
".",
"_board",
".",
"get_analog_response_table",
"(",
")"
] | [
86,
4
] | [
89,
54
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.set_digital_out_high | (self, pin) | Set a given digital pin to high. | Set a given digital pin to high. | def set_digital_out_high(self, pin):
"""Set a given digital pin to high."""
self._board.digital_write(pin, 1) | [
"def",
"set_digital_out_high",
"(",
"self",
",",
"pin",
")",
":",
"self",
".",
"_board",
".",
"digital_write",
"(",
"pin",
",",
"1",
")"
] | [
91,
4
] | [
93,
41
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.set_digital_out_low | (self, pin) | Set a given digital pin to low. | Set a given digital pin to low. | def set_digital_out_low(self, pin):
"""Set a given digital pin to low."""
self._board.digital_write(pin, 0) | [
"def",
"set_digital_out_low",
"(",
"self",
",",
"pin",
")",
":",
"self",
".",
"_board",
".",
"digital_write",
"(",
"pin",
",",
"0",
")"
] | [
95,
4
] | [
97,
41
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.get_digital_in | (self, pin) | Get the value from a given digital pin. | Get the value from a given digital pin. | def get_digital_in(self, pin):
"""Get the value from a given digital pin."""
self._board.digital_read(pin) | [
"def",
"get_digital_in",
"(",
"self",
",",
"pin",
")",
":",
"self",
".",
"_board",
".",
"digital_read",
"(",
"pin",
")"
] | [
99,
4
] | [
101,
37
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.get_analog_in | (self, pin) | Get the value from a given analog pin. | Get the value from a given analog pin. | def get_analog_in(self, pin):
"""Get the value from a given analog pin."""
self._board.analog_read(pin) | [
"def",
"get_analog_in",
"(",
"self",
",",
"pin",
")",
":",
"self",
".",
"_board",
".",
"analog_read",
"(",
"pin",
")"
] | [
103,
4
] | [
105,
36
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.get_firmata | (self) | Return the version of the Firmata firmware. | Return the version of the Firmata firmware. | def get_firmata(self):
"""Return the version of the Firmata firmware."""
return self._board.get_firmata_version() | [
"def",
"get_firmata",
"(",
"self",
")",
":",
"return",
"self",
".",
"_board",
".",
"get_firmata_version",
"(",
")"
] | [
107,
4
] | [
109,
48
] | python | en | ['en', 'en', 'en'] | True |
ArduinoBoard.disconnect | (self) | Disconnect the board and close the serial connection. | Disconnect the board and close the serial connection. | def disconnect(self):
"""Disconnect the board and close the serial connection."""
self._board.reset()
self._board.close() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"self",
".",
"_board",
".",
"reset",
"(",
")",
"self",
".",
"_board",
".",
"close",
"(",
")"
] | [
111,
4
] | [
114,
27
] | python | en | ['en', 'en', 'en'] | True |
test_create_sensors | (hass) | Test creation of sensors. | Test creation of sensors. | async def test_create_sensors(hass):
"""Test creation of sensors."""
await async_init_integration(hass)
state = hass.states.get("sensor.nick_office_temperature")
assert state.state == "23"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"device_class": "temperature",
"friendly_name": "Nick Office Temperature",
"unit_of_measurement": TEMP_CELSIUS,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.nick_office_zone_setpoint_status")
assert state.state == "Permanent Hold"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"friendly_name": "Nick Office Zone Setpoint Status",
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.nick_office_zone_status")
assert state.state == "Relieving Air"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"friendly_name": "Nick Office Zone Status",
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.master_suite_air_cleaner_mode")
assert state.state == "auto"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"friendly_name": "Master Suite Air Cleaner Mode",
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.master_suite_current_compressor_speed")
assert state.state == "69.0"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"friendly_name": "Master Suite Current Compressor Speed",
"unit_of_measurement": PERCENTAGE,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.master_suite_outdoor_temperature")
assert state.state == "30.6"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"device_class": "temperature",
"friendly_name": "Master Suite Outdoor Temperature",
"unit_of_measurement": TEMP_CELSIUS,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.master_suite_relative_humidity")
assert state.state == "52.0"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"device_class": "humidity",
"friendly_name": "Master Suite Relative Humidity",
"unit_of_measurement": PERCENTAGE,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.master_suite_requested_compressor_speed")
assert state.state == "69.0"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"friendly_name": "Master Suite Requested Compressor Speed",
"unit_of_measurement": PERCENTAGE,
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
)
state = hass.states.get("sensor.master_suite_system_status")
assert state.state == "Cooling"
expected_attributes = {
"attribution": "Data provided by mynexia.com",
"friendly_name": "Master Suite System Status",
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(
state.attributes[key] == expected_attributes[key] for key in expected_attributes
) | [
"async",
"def",
"test_create_sensors",
"(",
"hass",
")",
":",
"await",
"async_init_integration",
"(",
"hass",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.nick_office_temperature\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"23\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"device_class\"",
":",
"\"temperature\"",
",",
"\"friendly_name\"",
":",
"\"Nick Office Temperature\"",
",",
"\"unit_of_measurement\"",
":",
"TEMP_CELSIUS",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.nick_office_zone_setpoint_status\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"Permanent Hold\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"friendly_name\"",
":",
"\"Nick Office Zone Setpoint Status\"",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.nick_office_zone_status\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"Relieving Air\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"friendly_name\"",
":",
"\"Nick Office Zone Status\"",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.master_suite_air_cleaner_mode\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"auto\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"friendly_name\"",
":",
"\"Master Suite Air Cleaner Mode\"",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.master_suite_current_compressor_speed\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"69.0\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"friendly_name\"",
":",
"\"Master Suite Current Compressor Speed\"",
",",
"\"unit_of_measurement\"",
":",
"PERCENTAGE",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.master_suite_outdoor_temperature\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"30.6\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"device_class\"",
":",
"\"temperature\"",
",",
"\"friendly_name\"",
":",
"\"Master Suite Outdoor Temperature\"",
",",
"\"unit_of_measurement\"",
":",
"TEMP_CELSIUS",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.master_suite_relative_humidity\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"52.0\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"device_class\"",
":",
"\"humidity\"",
",",
"\"friendly_name\"",
":",
"\"Master Suite Relative Humidity\"",
",",
"\"unit_of_measurement\"",
":",
"PERCENTAGE",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.master_suite_requested_compressor_speed\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"69.0\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"friendly_name\"",
":",
"\"Master Suite Requested Compressor Speed\"",
",",
"\"unit_of_measurement\"",
":",
"PERCENTAGE",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.master_suite_system_status\"",
")",
"assert",
"state",
".",
"state",
"==",
"\"Cooling\"",
"expected_attributes",
"=",
"{",
"\"attribution\"",
":",
"\"Data provided by mynexia.com\"",
",",
"\"friendly_name\"",
":",
"\"Master Suite System Status\"",
",",
"}",
"# Only test for a subset of attributes in case",
"# HA changes the implementation and a new one appears",
"assert",
"all",
"(",
"state",
".",
"attributes",
"[",
"key",
"]",
"==",
"expected_attributes",
"[",
"key",
"]",
"for",
"key",
"in",
"expected_attributes",
")"
] | [
7,
0
] | [
134,
5
] | python | en | ['en', 'bg', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.