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 |
---|---|---|---|---|---|---|---|---|---|---|---|
OVOEnergyLastElectricityReading.device_state_attributes | (self) | Return the attributes of the sensor. | Return the attributes of the sensor. | def device_state_attributes(self) -> object:
"""Return the attributes of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.electricity:
return None
return {
"start_time": usage.electricity[-1].interval.start,
"end_time": usage.electricity[-1].interval.end,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"object",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"electricity",
":",
"return",
"None",
"return",
"{",
"\"start_time\"",
":",
"usage",
".",
"electricity",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"start",
",",
"\"end_time\"",
":",
"usage",
".",
"electricity",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"end",
",",
"}"
] | [
105,
4
] | [
113,
9
] | python | en | ['en', 'en', 'en'] | True |
OVOEnergyLastGasReading.__init__ | (self, coordinator: DataUpdateCoordinator, client: OVOEnergy) | Initialize OVO Energy sensor. | Initialize OVO Energy sensor. | def __init__(self, coordinator: DataUpdateCoordinator, client: OVOEnergy):
"""Initialize OVO Energy sensor."""
super().__init__(
coordinator,
client,
f"{DOMAIN}_{client.account_id}_last_gas_reading",
"OVO Last Gas Reading",
"mdi:gas-cylinder",
"kWh",
) | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
":",
"DataUpdateCoordinator",
",",
"client",
":",
"OVOEnergy",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
",",
"client",
",",
"f\"{DOMAIN}_{client.account_id}_last_gas_reading\"",
",",
"\"OVO Last Gas Reading\"",
",",
"\"mdi:gas-cylinder\"",
",",
"\"kWh\"",
",",
")"
] | [
119,
4
] | [
129,
9
] | python | hu | ['hu', 'pt', 'it'] | False |
OVOEnergyLastGasReading.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self) -> str:
"""Return the state of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.gas:
return None
return usage.gas[-1].consumption | [
"def",
"state",
"(",
"self",
")",
"->",
"str",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"gas",
":",
"return",
"None",
"return",
"usage",
".",
"gas",
"[",
"-",
"1",
"]",
".",
"consumption"
] | [
132,
4
] | [
137,
40
] | python | en | ['en', 'en', 'en'] | True |
OVOEnergyLastGasReading.device_state_attributes | (self) | Return the attributes of the sensor. | Return the attributes of the sensor. | def device_state_attributes(self) -> object:
"""Return the attributes of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.gas:
return None
return {
"start_time": usage.gas[-1].interval.start,
"end_time": usage.gas[-1].interval.end,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"object",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"gas",
":",
"return",
"None",
"return",
"{",
"\"start_time\"",
":",
"usage",
".",
"gas",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"start",
",",
"\"end_time\"",
":",
"usage",
".",
"gas",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"end",
",",
"}"
] | [
140,
4
] | [
148,
9
] | python | en | ['en', 'en', 'en'] | True |
OVOEnergyLastElectricityCost.__init__ | (
self, coordinator: DataUpdateCoordinator, client: OVOEnergy, currency: str
) | Initialize OVO Energy sensor. | Initialize OVO Energy sensor. | def __init__(
self, coordinator: DataUpdateCoordinator, client: OVOEnergy, currency: str
):
"""Initialize OVO Energy sensor."""
super().__init__(
coordinator,
client,
f"{DOMAIN}_{client.account_id}_last_electricity_cost",
"OVO Last Electricity Cost",
"mdi:cash-multiple",
currency,
) | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
":",
"DataUpdateCoordinator",
",",
"client",
":",
"OVOEnergy",
",",
"currency",
":",
"str",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
",",
"client",
",",
"f\"{DOMAIN}_{client.account_id}_last_electricity_cost\"",
",",
"\"OVO Last Electricity Cost\"",
",",
"\"mdi:cash-multiple\"",
",",
"currency",
",",
")"
] | [
154,
4
] | [
165,
9
] | python | hu | ['hu', 'pt', 'it'] | False |
OVOEnergyLastElectricityCost.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self) -> str:
"""Return the state of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.electricity:
return None
return usage.electricity[-1].cost.amount | [
"def",
"state",
"(",
"self",
")",
"->",
"str",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"electricity",
":",
"return",
"None",
"return",
"usage",
".",
"electricity",
"[",
"-",
"1",
"]",
".",
"cost",
".",
"amount"
] | [
168,
4
] | [
173,
48
] | python | en | ['en', 'en', 'en'] | True |
OVOEnergyLastElectricityCost.device_state_attributes | (self) | Return the attributes of the sensor. | Return the attributes of the sensor. | def device_state_attributes(self) -> object:
"""Return the attributes of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.electricity:
return None
return {
"start_time": usage.electricity[-1].interval.start,
"end_time": usage.electricity[-1].interval.end,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"object",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"electricity",
":",
"return",
"None",
"return",
"{",
"\"start_time\"",
":",
"usage",
".",
"electricity",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"start",
",",
"\"end_time\"",
":",
"usage",
".",
"electricity",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"end",
",",
"}"
] | [
176,
4
] | [
184,
9
] | python | en | ['en', 'en', 'en'] | True |
OVOEnergyLastGasCost.__init__ | (
self, coordinator: DataUpdateCoordinator, client: OVOEnergy, currency: str
) | Initialize OVO Energy sensor. | Initialize OVO Energy sensor. | def __init__(
self, coordinator: DataUpdateCoordinator, client: OVOEnergy, currency: str
):
"""Initialize OVO Energy sensor."""
super().__init__(
coordinator,
client,
f"{DOMAIN}_{client.account_id}_last_gas_cost",
"OVO Last Gas Cost",
"mdi:cash-multiple",
currency,
) | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
":",
"DataUpdateCoordinator",
",",
"client",
":",
"OVOEnergy",
",",
"currency",
":",
"str",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
",",
"client",
",",
"f\"{DOMAIN}_{client.account_id}_last_gas_cost\"",
",",
"\"OVO Last Gas Cost\"",
",",
"\"mdi:cash-multiple\"",
",",
"currency",
",",
")"
] | [
190,
4
] | [
201,
9
] | python | hu | ['hu', 'pt', 'it'] | False |
OVOEnergyLastGasCost.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self) -> str:
"""Return the state of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.gas:
return None
return usage.gas[-1].cost.amount | [
"def",
"state",
"(",
"self",
")",
"->",
"str",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"gas",
":",
"return",
"None",
"return",
"usage",
".",
"gas",
"[",
"-",
"1",
"]",
".",
"cost",
".",
"amount"
] | [
204,
4
] | [
209,
40
] | python | en | ['en', 'en', 'en'] | True |
OVOEnergyLastGasCost.device_state_attributes | (self) | Return the attributes of the sensor. | Return the attributes of the sensor. | def device_state_attributes(self) -> object:
"""Return the attributes of the sensor."""
usage: OVODailyUsage = self.coordinator.data
if usage is None or not usage.gas:
return None
return {
"start_time": usage.gas[-1].interval.start,
"end_time": usage.gas[-1].interval.end,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"object",
":",
"usage",
":",
"OVODailyUsage",
"=",
"self",
".",
"coordinator",
".",
"data",
"if",
"usage",
"is",
"None",
"or",
"not",
"usage",
".",
"gas",
":",
"return",
"None",
"return",
"{",
"\"start_time\"",
":",
"usage",
".",
"gas",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"start",
",",
"\"end_time\"",
":",
"usage",
".",
"gas",
"[",
"-",
"1",
"]",
".",
"interval",
".",
"end",
",",
"}"
] | [
212,
4
] | [
220,
9
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistant, config: dict) | Plum Lightpad Platform initialization. | Plum Lightpad Platform initialization. | async def async_setup(hass: HomeAssistant, config: dict):
"""Plum Lightpad Platform initialization."""
if DOMAIN not in config:
return True
conf = config[DOMAIN]
_LOGGER.info("Found Plum Lightpad configuration in config, importing...")
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=conf
)
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"if",
"DOMAIN",
"not",
"in",
"config",
":",
"return",
"True",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"_LOGGER",
".",
"info",
"(",
"\"Found Plum Lightpad configuration in config, importing...\"",
")",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"conf",
")",
")",
"return",
"True"
] | [
33,
0
] | [
47,
15
] | python | en | ['pt', 'lv', 'en'] | False |
async_setup_entry | (hass: HomeAssistant, entry: ConfigEntry) | Set up Plum Lightpad from a config entry. | Set up Plum Lightpad from a config entry. | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Plum Lightpad from a config entry."""
_LOGGER.debug("Setting up config entry with ID = %s", entry.unique_id)
username = entry.data.get(CONF_USERNAME)
password = entry.data.get(CONF_PASSWORD)
try:
plum = await load_plum(username, password, hass)
except ContentTypeError as ex:
_LOGGER.error("Unable to authenticate to Plum cloud: %s", ex)
return False
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Plum cloud: %s", ex)
raise ConfigEntryNotReady from ex
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = plum
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
def cleanup(event):
"""Clean up resources."""
plum.cleanup()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, cleanup)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting up config entry with ID = %s\"",
",",
"entry",
".",
"unique_id",
")",
"username",
"=",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_USERNAME",
")",
"password",
"=",
"entry",
".",
"data",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"try",
":",
"plum",
"=",
"await",
"load_plum",
"(",
"username",
",",
"password",
",",
"hass",
")",
"except",
"ContentTypeError",
"as",
"ex",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to authenticate to Plum cloud: %s\"",
",",
"ex",
")",
"return",
"False",
"except",
"(",
"ConnectTimeout",
",",
"HTTPError",
")",
"as",
"ex",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to connect to Plum cloud: %s\"",
",",
"ex",
")",
"raise",
"ConfigEntryNotReady",
"from",
"ex",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"=",
"plum",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"component",
")",
")",
"def",
"cleanup",
"(",
"event",
")",
":",
"\"\"\"Clean up resources.\"\"\"",
"plum",
".",
"cleanup",
"(",
")",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"cleanup",
")",
"return",
"True"
] | [
50,
0
] | [
79,
15
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the sensor platform. | Set up the sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the sensor platform."""
platform = hass.data.get(WIRELESSTAG_DOMAIN)
sensors = []
tags = platform.tags
for tag in tags.values():
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type in tag.allowed_sensor_types:
sensors.append(
WirelessTagSensor(platform, tag, sensor_type, hass.config)
)
add_entities(sensors, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"platform",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"WIRELESSTAG_DOMAIN",
")",
"sensors",
"=",
"[",
"]",
"tags",
"=",
"platform",
".",
"tags",
"for",
"tag",
"in",
"tags",
".",
"values",
"(",
")",
":",
"for",
"sensor_type",
"in",
"config",
".",
"get",
"(",
"CONF_MONITORED_CONDITIONS",
")",
":",
"if",
"sensor_type",
"in",
"tag",
".",
"allowed_sensor_types",
":",
"sensors",
".",
"append",
"(",
"WirelessTagSensor",
"(",
"platform",
",",
"tag",
",",
"sensor_type",
",",
"hass",
".",
"config",
")",
")",
"add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
31,
0
] | [
43,
31
] | python | en | ['en', 'da', 'en'] | True |
WirelessTagSensor.__init__ | (self, api, tag, sensor_type, config) | Initialize a WirelessTag sensor. | Initialize a WirelessTag sensor. | def __init__(self, api, tag, sensor_type, config):
"""Initialize a WirelessTag sensor."""
super().__init__(api, tag)
self._sensor_type = sensor_type
self._name = self._tag.name
# I want to see entity_id as:
# sensor.wirelesstag_bedroom_temperature
# and not as sensor.bedroom for temperature and
# sensor.bedroom_2 for humidity
self._entity_id = (
f"sensor.{WIRELESSTAG_DOMAIN}_{self.underscored_name}_{self._sensor_type}"
) | [
"def",
"__init__",
"(",
"self",
",",
"api",
",",
"tag",
",",
"sensor_type",
",",
"config",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"api",
",",
"tag",
")",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_name",
"=",
"self",
".",
"_tag",
".",
"name",
"# I want to see entity_id as:",
"# sensor.wirelesstag_bedroom_temperature",
"# and not as sensor.bedroom for temperature and",
"# sensor.bedroom_2 for humidity",
"self",
".",
"_entity_id",
"=",
"(",
"f\"sensor.{WIRELESSTAG_DOMAIN}_{self.underscored_name}_{self._sensor_type}\"",
")"
] | [
49,
4
] | [
62,
9
] | python | en | ['en', 'pl', 'en'] | True |
WirelessTagSensor.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
async_dispatcher_connect(
self.hass,
SIGNAL_TAG_UPDATE.format(self.tag_id, self.tag_manager_mac),
self._update_tag_info_callback,
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"SIGNAL_TAG_UPDATE",
".",
"format",
"(",
"self",
".",
"tag_id",
",",
"self",
".",
"tag_manager_mac",
")",
",",
"self",
".",
"_update_tag_info_callback",
",",
")",
")"
] | [
64,
4
] | [
72,
9
] | python | en | ['en', 'no', 'en'] | False |
WirelessTagSensor.entity_id | (self) | Overridden version. | Overridden version. | def entity_id(self):
"""Overridden version."""
return self._entity_id | [
"def",
"entity_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_entity_id"
] | [
75,
4
] | [
77,
30
] | python | nl | ['nl', 'nl', 'en'] | False |
WirelessTagSensor.underscored_name | (self) | Provide name savvy to be used in entity_id name of self. | Provide name savvy to be used in entity_id name of self. | def underscored_name(self):
"""Provide name savvy to be used in entity_id name of self."""
return self.name.lower().replace(" ", "_") | [
"def",
"underscored_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")"
] | [
80,
4
] | [
82,
50
] | python | en | ['en', 'en', 'en'] | True |
WirelessTagSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
85,
4
] | [
87,
26
] | python | en | ['en', 'en', 'en'] | True |
WirelessTagSensor.device_class | (self) | Return the class of the sensor. | Return the class of the sensor. | def device_class(self):
"""Return the class of the sensor."""
return self._sensor_type | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_type"
] | [
90,
4
] | [
92,
32
] | python | en | ['en', 'pt', 'en'] | True |
WirelessTagSensor.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._sensor.unit | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor",
".",
"unit"
] | [
95,
4
] | [
97,
32
] | python | en | ['en', 'la', 'en'] | True |
WirelessTagSensor.principal_value | (self) | Return sensor current value. | Return sensor current value. | def principal_value(self):
"""Return sensor current value."""
return self._sensor.value | [
"def",
"principal_value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor",
".",
"value"
] | [
100,
4
] | [
102,
33
] | python | da | ['nl', 'da', 'en'] | False |
WirelessTagSensor._sensor | (self) | Return tag sensor entity. | Return tag sensor entity. | def _sensor(self):
"""Return tag sensor entity."""
return self._tag.sensor[self._sensor_type] | [
"def",
"_sensor",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tag",
".",
"sensor",
"[",
"self",
".",
"_sensor_type",
"]"
] | [
105,
4
] | [
107,
50
] | python | cy | ['da', 'cy', 'en'] | False |
WirelessTagSensor._update_tag_info_callback | (self, event) | Handle push notification sent by tag manager. | Handle push notification sent by tag manager. | def _update_tag_info_callback(self, event):
"""Handle push notification sent by tag manager."""
_LOGGER.debug("Entity to update state: %s event data: %s", self, event.data)
new_value = self._sensor.value_from_update_event(event.data)
self._state = self.decorate_value(new_value)
self.async_write_ha_state() | [
"def",
"_update_tag_info_callback",
"(",
"self",
",",
"event",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Entity to update state: %s event data: %s\"",
",",
"self",
",",
"event",
".",
"data",
")",
"new_value",
"=",
"self",
".",
"_sensor",
".",
"value_from_update_event",
"(",
"event",
".",
"data",
")",
"self",
".",
"_state",
"=",
"self",
".",
"decorate_value",
"(",
"new_value",
")",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
110,
4
] | [
115,
35
] | python | en | ['en', 'en', 'en'] | True |
load_corpus | (name, download=True) |
Loads and wrangles the passed in text corpus by name.
If download is specified, this method will download any missing files.
Note: This function is slightly different to the `load_data` function
used above to load pandas dataframes into memory.
|
Loads and wrangles the passed in text corpus by name.
If download is specified, this method will download any missing files. | def load_corpus(name, download=True):
"""
Loads and wrangles the passed in text corpus by name.
If download is specified, this method will download any missing files.
Note: This function is slightly different to the `load_data` function
used above to load pandas dataframes into memory.
"""
# Get the path from the datasets
path = corpora[name]
# Check if the data exists, otherwise download or raise
if not os.path.exists(path):
raise ValueError((
"'{}' dataset has not been downloaded, "
"use the download.py module to fetch datasets"
).format(name))
# Read the directories in the directory as the categories.
categories = [
cat for cat in os.listdir(path)
if os.path.isdir(os.path.join(path, cat))
]
files = [] # holds the file names relative to the root
data = [] # holds the text read from the file
target = [] # holds the string of the category
# Load the data from the files in the corpus
for cat in categories:
for name in os.listdir(os.path.join(path, cat)):
files.append(os.path.join(path, cat, name))
target.append(cat)
with open(os.path.join(path, cat, name), 'r') as f:
data.append(f.read())
# Return the data bunch for use similar to the newsgroups example
return Bunch(
categories=categories,
files=files,
data=data,
target=target,
) | [
"def",
"load_corpus",
"(",
"name",
",",
"download",
"=",
"True",
")",
":",
"# Get the path from the datasets",
"path",
"=",
"corpora",
"[",
"name",
"]",
"# Check if the data exists, otherwise download or raise",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"'{}' dataset has not been downloaded, \"",
"\"use the download.py module to fetch datasets\"",
")",
".",
"format",
"(",
"name",
")",
")",
"# Read the directories in the directory as the categories.",
"categories",
"=",
"[",
"cat",
"for",
"cat",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cat",
")",
")",
"]",
"files",
"=",
"[",
"]",
"# holds the file names relative to the root",
"data",
"=",
"[",
"]",
"# holds the text read from the file",
"target",
"=",
"[",
"]",
"# holds the string of the category",
"# Load the data from the files in the corpus",
"for",
"cat",
"in",
"categories",
":",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cat",
")",
")",
":",
"files",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cat",
",",
"name",
")",
")",
"target",
".",
"append",
"(",
"cat",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cat",
",",
"name",
")",
",",
"'r'",
")",
"as",
"f",
":",
"data",
".",
"append",
"(",
"f",
".",
"read",
"(",
")",
")",
"# Return the data bunch for use similar to the newsgroups example",
"return",
"Bunch",
"(",
"categories",
"=",
"categories",
",",
"files",
"=",
"files",
",",
"data",
"=",
"data",
",",
"target",
"=",
"target",
",",
")"
] | [
22,
0
] | [
66,
5
] | python | en | ['en', 'error', 'th'] | False |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Xiaomi vacuum cleaner robot platform. | Set up the Xiaomi vacuum cleaner robot platform. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Xiaomi vacuum cleaner robot platform."""
if DATA_KEY not in hass.data:
hass.data[DATA_KEY] = {}
host = config[CONF_HOST]
token = config[CONF_TOKEN]
name = config[CONF_NAME]
# Create handler
_LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])
vacuum = Vacuum(host, token)
mirobo = MiroboVacuum(name, vacuum)
hass.data[DATA_KEY][host] = mirobo
async_add_entities([mirobo], update_before_add=True)
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
SERVICE_START_REMOTE_CONTROL,
{},
MiroboVacuum.async_remote_control_start.__name__,
)
platform.async_register_entity_service(
SERVICE_STOP_REMOTE_CONTROL,
{},
MiroboVacuum.async_remote_control_stop.__name__,
)
platform.async_register_entity_service(
SERVICE_MOVE_REMOTE_CONTROL,
{
vol.Optional(ATTR_RC_VELOCITY): vol.All(
vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)
),
vol.Optional(ATTR_RC_ROTATION): vol.All(
vol.Coerce(int), vol.Clamp(min=-179, max=179)
),
vol.Optional(ATTR_RC_DURATION): cv.positive_int,
},
MiroboVacuum.async_remote_control_move.__name__,
)
platform.async_register_entity_service(
SERVICE_MOVE_REMOTE_CONTROL_STEP,
{
vol.Optional(ATTR_RC_VELOCITY): vol.All(
vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)
),
vol.Optional(ATTR_RC_ROTATION): vol.All(
vol.Coerce(int), vol.Clamp(min=-179, max=179)
),
vol.Optional(ATTR_RC_DURATION): cv.positive_int,
},
MiroboVacuum.async_remote_control_move_step.__name__,
)
platform.async_register_entity_service(
SERVICE_CLEAN_ZONE,
{
vol.Required(ATTR_ZONE_ARRAY): vol.All(
list,
[
vol.ExactSequence(
[
vol.Coerce(int),
vol.Coerce(int),
vol.Coerce(int),
vol.Coerce(int),
]
)
],
),
vol.Required(ATTR_ZONE_REPEATER): vol.All(
vol.Coerce(int), vol.Clamp(min=1, max=3)
),
},
MiroboVacuum.async_clean_zone.__name__,
)
platform.async_register_entity_service(
SERVICE_GOTO,
{
vol.Required("x_coord"): vol.Coerce(int),
vol.Required("y_coord"): vol.Coerce(int),
},
MiroboVacuum.async_goto.__name__,
)
platform.async_register_entity_service(
SERVICE_CLEAN_SEGMENT,
{vol.Required("segments"): vol.Any(vol.Coerce(int), [vol.Coerce(int)])},
MiroboVacuum.async_clean_segment.__name__,
) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"DATA_KEY",
"not",
"in",
"hass",
".",
"data",
":",
"hass",
".",
"data",
"[",
"DATA_KEY",
"]",
"=",
"{",
"}",
"host",
"=",
"config",
"[",
"CONF_HOST",
"]",
"token",
"=",
"config",
"[",
"CONF_TOKEN",
"]",
"name",
"=",
"config",
"[",
"CONF_NAME",
"]",
"# Create handler",
"_LOGGER",
".",
"info",
"(",
"\"Initializing with host %s (token %s...)\"",
",",
"host",
",",
"token",
"[",
":",
"5",
"]",
")",
"vacuum",
"=",
"Vacuum",
"(",
"host",
",",
"token",
")",
"mirobo",
"=",
"MiroboVacuum",
"(",
"name",
",",
"vacuum",
")",
"hass",
".",
"data",
"[",
"DATA_KEY",
"]",
"[",
"host",
"]",
"=",
"mirobo",
"async_add_entities",
"(",
"[",
"mirobo",
"]",
",",
"update_before_add",
"=",
"True",
")",
"platform",
"=",
"entity_platform",
".",
"current_platform",
".",
"get",
"(",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_START_REMOTE_CONTROL",
",",
"{",
"}",
",",
"MiroboVacuum",
".",
"async_remote_control_start",
".",
"__name__",
",",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_STOP_REMOTE_CONTROL",
",",
"{",
"}",
",",
"MiroboVacuum",
".",
"async_remote_control_stop",
".",
"__name__",
",",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_MOVE_REMOTE_CONTROL",
",",
"{",
"vol",
".",
"Optional",
"(",
"ATTR_RC_VELOCITY",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"Coerce",
"(",
"float",
")",
",",
"vol",
".",
"Clamp",
"(",
"min",
"=",
"-",
"0.29",
",",
"max",
"=",
"0.29",
")",
")",
",",
"vol",
".",
"Optional",
"(",
"ATTR_RC_ROTATION",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Clamp",
"(",
"min",
"=",
"-",
"179",
",",
"max",
"=",
"179",
")",
")",
",",
"vol",
".",
"Optional",
"(",
"ATTR_RC_DURATION",
")",
":",
"cv",
".",
"positive_int",
",",
"}",
",",
"MiroboVacuum",
".",
"async_remote_control_move",
".",
"__name__",
",",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_MOVE_REMOTE_CONTROL_STEP",
",",
"{",
"vol",
".",
"Optional",
"(",
"ATTR_RC_VELOCITY",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"Coerce",
"(",
"float",
")",
",",
"vol",
".",
"Clamp",
"(",
"min",
"=",
"-",
"0.29",
",",
"max",
"=",
"0.29",
")",
")",
",",
"vol",
".",
"Optional",
"(",
"ATTR_RC_ROTATION",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Clamp",
"(",
"min",
"=",
"-",
"179",
",",
"max",
"=",
"179",
")",
")",
",",
"vol",
".",
"Optional",
"(",
"ATTR_RC_DURATION",
")",
":",
"cv",
".",
"positive_int",
",",
"}",
",",
"MiroboVacuum",
".",
"async_remote_control_move_step",
".",
"__name__",
",",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_CLEAN_ZONE",
",",
"{",
"vol",
".",
"Required",
"(",
"ATTR_ZONE_ARRAY",
")",
":",
"vol",
".",
"All",
"(",
"list",
",",
"[",
"vol",
".",
"ExactSequence",
"(",
"[",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"]",
")",
"]",
",",
")",
",",
"vol",
".",
"Required",
"(",
"ATTR_ZONE_REPEATER",
")",
":",
"vol",
".",
"All",
"(",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Clamp",
"(",
"min",
"=",
"1",
",",
"max",
"=",
"3",
")",
")",
",",
"}",
",",
"MiroboVacuum",
".",
"async_clean_zone",
".",
"__name__",
",",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_GOTO",
",",
"{",
"vol",
".",
"Required",
"(",
"\"x_coord\"",
")",
":",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"vol",
".",
"Required",
"(",
"\"y_coord\"",
")",
":",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"}",
",",
"MiroboVacuum",
".",
"async_goto",
".",
"__name__",
",",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_CLEAN_SEGMENT",
",",
"{",
"vol",
".",
"Required",
"(",
"\"segments\"",
")",
":",
"vol",
".",
"Any",
"(",
"vol",
".",
"Coerce",
"(",
"int",
")",
",",
"[",
"vol",
".",
"Coerce",
"(",
"int",
")",
"]",
")",
"}",
",",
"MiroboVacuum",
".",
"async_clean_segment",
".",
"__name__",
",",
")"
] | [
116,
0
] | [
211,
5
] | python | en | ['en', 'nl', 'en'] | True |
MiroboVacuum.__init__ | (self, name, vacuum) | Initialize the Xiaomi vacuum cleaner robot handler. | Initialize the Xiaomi vacuum cleaner robot handler. | def __init__(self, name, vacuum):
"""Initialize the Xiaomi vacuum cleaner robot handler."""
self._name = name
self._vacuum = vacuum
self.vacuum_state = None
self._available = False
self.consumable_state = None
self.clean_history = None
self.dnd_state = None
self.last_clean = None
self._fan_speeds = None
self._fan_speeds_reverse = None
self._timers = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"vacuum",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_vacuum",
"=",
"vacuum",
"self",
".",
"vacuum_state",
"=",
"None",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"consumable_state",
"=",
"None",
"self",
".",
"clean_history",
"=",
"None",
"self",
".",
"dnd_state",
"=",
"None",
"self",
".",
"last_clean",
"=",
"None",
"self",
".",
"_fan_speeds",
"=",
"None",
"self",
".",
"_fan_speeds_reverse",
"=",
"None",
"self",
".",
"_timers",
"=",
"None"
] | [
217,
4
] | [
232,
27
] | python | en | ['en', 'nl', 'en'] | True |
MiroboVacuum.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
235,
4
] | [
237,
25
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.state | (self) | Return the status of the vacuum cleaner. | Return the status of the vacuum cleaner. | def state(self):
"""Return the status of the vacuum cleaner."""
if self.vacuum_state is not None:
# The vacuum reverts back to an idle state after erroring out.
# We want to keep returning an error until it has been cleared.
if self.vacuum_state.got_error:
return STATE_ERROR
try:
return STATE_CODE_TO_STATE[int(self.vacuum_state.state_code)]
except KeyError:
_LOGGER.error(
"STATE not supported: %s, state_code: %s",
self.vacuum_state.state,
self.vacuum_state.state_code,
)
return None | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"vacuum_state",
"is",
"not",
"None",
":",
"# The vacuum reverts back to an idle state after erroring out.",
"# We want to keep returning an error until it has been cleared.",
"if",
"self",
".",
"vacuum_state",
".",
"got_error",
":",
"return",
"STATE_ERROR",
"try",
":",
"return",
"STATE_CODE_TO_STATE",
"[",
"int",
"(",
"self",
".",
"vacuum_state",
".",
"state_code",
")",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"STATE not supported: %s, state_code: %s\"",
",",
"self",
".",
"vacuum_state",
".",
"state",
",",
"self",
".",
"vacuum_state",
".",
"state_code",
",",
")",
"return",
"None"
] | [
240,
4
] | [
255,
27
] | python | en | ['en', 'la', 'en'] | True |
MiroboVacuum.battery_level | (self) | Return the battery level of the vacuum cleaner. | Return the battery level of the vacuum cleaner. | def battery_level(self):
"""Return the battery level of the vacuum cleaner."""
if self.vacuum_state is not None:
return self.vacuum_state.battery | [
"def",
"battery_level",
"(",
"self",
")",
":",
"if",
"self",
".",
"vacuum_state",
"is",
"not",
"None",
":",
"return",
"self",
".",
"vacuum_state",
".",
"battery"
] | [
258,
4
] | [
261,
44
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.fan_speed | (self) | Return the fan speed of the vacuum cleaner. | Return the fan speed of the vacuum cleaner. | def fan_speed(self):
"""Return the fan speed of the vacuum cleaner."""
if self.vacuum_state is not None:
speed = self.vacuum_state.fanspeed
if speed in self._fan_speeds_reverse:
return self._fan_speeds_reverse[speed]
_LOGGER.debug("Unable to find reverse for %s", speed)
return speed | [
"def",
"fan_speed",
"(",
"self",
")",
":",
"if",
"self",
".",
"vacuum_state",
"is",
"not",
"None",
":",
"speed",
"=",
"self",
".",
"vacuum_state",
".",
"fanspeed",
"if",
"speed",
"in",
"self",
".",
"_fan_speeds_reverse",
":",
"return",
"self",
".",
"_fan_speeds_reverse",
"[",
"speed",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Unable to find reverse for %s\"",
",",
"speed",
")",
"return",
"speed"
] | [
264,
4
] | [
273,
24
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.fan_speed_list | (self) | Get the list of available fan speed steps of the vacuum cleaner. | Get the list of available fan speed steps of the vacuum cleaner. | def fan_speed_list(self):
"""Get the list of available fan speed steps of the vacuum cleaner."""
return list(self._fan_speeds) if self._fan_speeds else [] | [
"def",
"fan_speed_list",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_fan_speeds",
")",
"if",
"self",
".",
"_fan_speeds",
"else",
"[",
"]"
] | [
276,
4
] | [
278,
65
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.timers | (self) | Get the list of added timers of the vacuum cleaner. | Get the list of added timers of the vacuum cleaner. | def timers(self):
"""Get the list of added timers of the vacuum cleaner."""
return [
{
"enabled": timer.enabled,
"cron": timer.cron,
"next_schedule": as_utc(timer.next_schedule),
}
for timer in self._timers
] | [
"def",
"timers",
"(",
"self",
")",
":",
"return",
"[",
"{",
"\"enabled\"",
":",
"timer",
".",
"enabled",
",",
"\"cron\"",
":",
"timer",
".",
"cron",
",",
"\"next_schedule\"",
":",
"as_utc",
"(",
"timer",
".",
"next_schedule",
")",
",",
"}",
"for",
"timer",
"in",
"self",
".",
"_timers",
"]"
] | [
281,
4
] | [
290,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.device_state_attributes | (self) | Return the specific state attributes of this vacuum cleaner. | Return the specific state attributes of this vacuum cleaner. | def device_state_attributes(self):
"""Return the specific state attributes of this vacuum cleaner."""
attrs = {}
if self.vacuum_state is not None:
attrs.update(
{
ATTR_DO_NOT_DISTURB: STATE_ON
if self.dnd_state.enabled
else STATE_OFF,
ATTR_DO_NOT_DISTURB_START: str(self.dnd_state.start),
ATTR_DO_NOT_DISTURB_END: str(self.dnd_state.end),
# Not working --> 'Cleaning mode':
# STATE_ON if self.vacuum_state.in_cleaning else STATE_OFF,
ATTR_CLEANING_TIME: int(
self.vacuum_state.clean_time.total_seconds() / 60
),
ATTR_CLEANED_AREA: int(self.vacuum_state.clean_area),
ATTR_CLEANING_COUNT: int(self.clean_history.count),
ATTR_CLEANED_TOTAL_AREA: int(self.clean_history.total_area),
ATTR_CLEANING_TOTAL_TIME: int(
self.clean_history.total_duration.total_seconds() / 60
),
ATTR_MAIN_BRUSH_LEFT: int(
self.consumable_state.main_brush_left.total_seconds() / 3600
),
ATTR_SIDE_BRUSH_LEFT: int(
self.consumable_state.side_brush_left.total_seconds() / 3600
),
ATTR_FILTER_LEFT: int(
self.consumable_state.filter_left.total_seconds() / 3600
),
ATTR_SENSOR_DIRTY_LEFT: int(
self.consumable_state.sensor_dirty_left.total_seconds() / 3600
),
ATTR_STATUS: str(self.vacuum_state.state),
}
)
if self.last_clean:
attrs[ATTR_CLEAN_START] = self.last_clean.start
attrs[ATTR_CLEAN_STOP] = self.last_clean.end
if self.vacuum_state.got_error:
attrs[ATTR_ERROR] = self.vacuum_state.error
if self.timers:
attrs[ATTR_TIMERS] = self.timers
return attrs | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attrs",
"=",
"{",
"}",
"if",
"self",
".",
"vacuum_state",
"is",
"not",
"None",
":",
"attrs",
".",
"update",
"(",
"{",
"ATTR_DO_NOT_DISTURB",
":",
"STATE_ON",
"if",
"self",
".",
"dnd_state",
".",
"enabled",
"else",
"STATE_OFF",
",",
"ATTR_DO_NOT_DISTURB_START",
":",
"str",
"(",
"self",
".",
"dnd_state",
".",
"start",
")",
",",
"ATTR_DO_NOT_DISTURB_END",
":",
"str",
"(",
"self",
".",
"dnd_state",
".",
"end",
")",
",",
"# Not working --> 'Cleaning mode':",
"# STATE_ON if self.vacuum_state.in_cleaning else STATE_OFF,",
"ATTR_CLEANING_TIME",
":",
"int",
"(",
"self",
".",
"vacuum_state",
".",
"clean_time",
".",
"total_seconds",
"(",
")",
"/",
"60",
")",
",",
"ATTR_CLEANED_AREA",
":",
"int",
"(",
"self",
".",
"vacuum_state",
".",
"clean_area",
")",
",",
"ATTR_CLEANING_COUNT",
":",
"int",
"(",
"self",
".",
"clean_history",
".",
"count",
")",
",",
"ATTR_CLEANED_TOTAL_AREA",
":",
"int",
"(",
"self",
".",
"clean_history",
".",
"total_area",
")",
",",
"ATTR_CLEANING_TOTAL_TIME",
":",
"int",
"(",
"self",
".",
"clean_history",
".",
"total_duration",
".",
"total_seconds",
"(",
")",
"/",
"60",
")",
",",
"ATTR_MAIN_BRUSH_LEFT",
":",
"int",
"(",
"self",
".",
"consumable_state",
".",
"main_brush_left",
".",
"total_seconds",
"(",
")",
"/",
"3600",
")",
",",
"ATTR_SIDE_BRUSH_LEFT",
":",
"int",
"(",
"self",
".",
"consumable_state",
".",
"side_brush_left",
".",
"total_seconds",
"(",
")",
"/",
"3600",
")",
",",
"ATTR_FILTER_LEFT",
":",
"int",
"(",
"self",
".",
"consumable_state",
".",
"filter_left",
".",
"total_seconds",
"(",
")",
"/",
"3600",
")",
",",
"ATTR_SENSOR_DIRTY_LEFT",
":",
"int",
"(",
"self",
".",
"consumable_state",
".",
"sensor_dirty_left",
".",
"total_seconds",
"(",
")",
"/",
"3600",
")",
",",
"ATTR_STATUS",
":",
"str",
"(",
"self",
".",
"vacuum_state",
".",
"state",
")",
",",
"}",
")",
"if",
"self",
".",
"last_clean",
":",
"attrs",
"[",
"ATTR_CLEAN_START",
"]",
"=",
"self",
".",
"last_clean",
".",
"start",
"attrs",
"[",
"ATTR_CLEAN_STOP",
"]",
"=",
"self",
".",
"last_clean",
".",
"end",
"if",
"self",
".",
"vacuum_state",
".",
"got_error",
":",
"attrs",
"[",
"ATTR_ERROR",
"]",
"=",
"self",
".",
"vacuum_state",
".",
"error",
"if",
"self",
".",
"timers",
":",
"attrs",
"[",
"ATTR_TIMERS",
"]",
"=",
"self",
".",
"timers",
"return",
"attrs"
] | [
293,
4
] | [
340,
20
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self) -> bool:
"""Return True if entity is available."""
return self._available | [
"def",
"available",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_available"
] | [
343,
4
] | [
345,
30
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.supported_features | (self) | Flag vacuum cleaner robot features that are supported. | Flag vacuum cleaner robot features that are supported. | def supported_features(self):
"""Flag vacuum cleaner robot features that are supported."""
return SUPPORT_XIAOMI | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_XIAOMI"
] | [
348,
4
] | [
350,
29
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum._try_command | (self, mask_error, func, *args, **kwargs) | Call a vacuum command handling error messages. | Call a vacuum command handling error messages. | async def _try_command(self, mask_error, func, *args, **kwargs):
"""Call a vacuum command handling error messages."""
try:
await self.hass.async_add_executor_job(partial(func, *args, **kwargs))
return True
except DeviceException as exc:
_LOGGER.error(mask_error, exc)
return False | [
"async",
"def",
"_try_command",
"(",
"self",
",",
"mask_error",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"partial",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"True",
"except",
"DeviceException",
"as",
"exc",
":",
"_LOGGER",
".",
"error",
"(",
"mask_error",
",",
"exc",
")",
"return",
"False"
] | [
352,
4
] | [
359,
24
] | python | en | ['en', 'ca', 'en'] | True |
MiroboVacuum.async_start | (self) | Start or resume the cleaning task. | Start or resume the cleaning task. | async def async_start(self):
"""Start or resume the cleaning task."""
await self._try_command(
"Unable to start the vacuum: %s", self._vacuum.resume_or_start
) | [
"async",
"def",
"async_start",
"(",
"self",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to start the vacuum: %s\"",
",",
"self",
".",
"_vacuum",
".",
"resume_or_start",
")"
] | [
361,
4
] | [
365,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_pause | (self) | Pause the cleaning task. | Pause the cleaning task. | async def async_pause(self):
"""Pause the cleaning task."""
await self._try_command("Unable to set start/pause: %s", self._vacuum.pause) | [
"async",
"def",
"async_pause",
"(",
"self",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to set start/pause: %s\"",
",",
"self",
".",
"_vacuum",
".",
"pause",
")"
] | [
367,
4
] | [
369,
84
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_stop | (self, **kwargs) | Stop the vacuum cleaner. | Stop the vacuum cleaner. | async def async_stop(self, **kwargs):
"""Stop the vacuum cleaner."""
await self._try_command("Unable to stop: %s", self._vacuum.stop) | [
"async",
"def",
"async_stop",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to stop: %s\"",
",",
"self",
".",
"_vacuum",
".",
"stop",
")"
] | [
371,
4
] | [
373,
72
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_set_fan_speed | (self, fan_speed, **kwargs) | Set fan speed. | Set fan speed. | async def async_set_fan_speed(self, fan_speed, **kwargs):
"""Set fan speed."""
if fan_speed in self._fan_speeds:
fan_speed = self._fan_speeds[fan_speed]
else:
try:
fan_speed = int(fan_speed)
except ValueError as exc:
_LOGGER.error(
"Fan speed step not recognized (%s). Valid speeds are: %s",
exc,
self.fan_speed_list,
)
return
await self._try_command(
"Unable to set fan speed: %s", self._vacuum.set_fan_speed, fan_speed
) | [
"async",
"def",
"async_set_fan_speed",
"(",
"self",
",",
"fan_speed",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"fan_speed",
"in",
"self",
".",
"_fan_speeds",
":",
"fan_speed",
"=",
"self",
".",
"_fan_speeds",
"[",
"fan_speed",
"]",
"else",
":",
"try",
":",
"fan_speed",
"=",
"int",
"(",
"fan_speed",
")",
"except",
"ValueError",
"as",
"exc",
":",
"_LOGGER",
".",
"error",
"(",
"\"Fan speed step not recognized (%s). Valid speeds are: %s\"",
",",
"exc",
",",
"self",
".",
"fan_speed_list",
",",
")",
"return",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to set fan speed: %s\"",
",",
"self",
".",
"_vacuum",
".",
"set_fan_speed",
",",
"fan_speed",
")"
] | [
375,
4
] | [
391,
9
] | python | fy | ['sv', 'fy', 'ur'] | False |
MiroboVacuum.async_return_to_base | (self, **kwargs) | Set the vacuum cleaner to return to the dock. | Set the vacuum cleaner to return to the dock. | async def async_return_to_base(self, **kwargs):
"""Set the vacuum cleaner to return to the dock."""
await self._try_command("Unable to return home: %s", self._vacuum.home) | [
"async",
"def",
"async_return_to_base",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to return home: %s\"",
",",
"self",
".",
"_vacuum",
".",
"home",
")"
] | [
393,
4
] | [
395,
79
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_clean_spot | (self, **kwargs) | Perform a spot clean-up. | Perform a spot clean-up. | async def async_clean_spot(self, **kwargs):
"""Perform a spot clean-up."""
await self._try_command(
"Unable to start the vacuum for a spot clean-up: %s", self._vacuum.spot
) | [
"async",
"def",
"async_clean_spot",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to start the vacuum for a spot clean-up: %s\"",
",",
"self",
".",
"_vacuum",
".",
"spot",
")"
] | [
397,
4
] | [
401,
9
] | python | en | ['pt', 'en', 'en'] | True |
MiroboVacuum.async_locate | (self, **kwargs) | Locate the vacuum cleaner. | Locate the vacuum cleaner. | async def async_locate(self, **kwargs):
"""Locate the vacuum cleaner."""
await self._try_command("Unable to locate the botvac: %s", self._vacuum.find) | [
"async",
"def",
"async_locate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to locate the botvac: %s\"",
",",
"self",
".",
"_vacuum",
".",
"find",
")"
] | [
403,
4
] | [
405,
85
] | python | en | ['en', 'la', 'en'] | True |
MiroboVacuum.async_send_command | (self, command, params=None, **kwargs) | Send raw command. | Send raw command. | async def async_send_command(self, command, params=None, **kwargs):
"""Send raw command."""
await self._try_command(
"Unable to send command to the vacuum: %s",
self._vacuum.raw_command,
command,
params,
) | [
"async",
"def",
"async_send_command",
"(",
"self",
",",
"command",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to send command to the vacuum: %s\"",
",",
"self",
".",
"_vacuum",
".",
"raw_command",
",",
"command",
",",
"params",
",",
")"
] | [
407,
4
] | [
414,
9
] | python | en | ['en', 'zh', 'en'] | True |
MiroboVacuum.async_remote_control_start | (self) | Start remote control mode. | Start remote control mode. | async def async_remote_control_start(self):
"""Start remote control mode."""
await self._try_command(
"Unable to start remote control the vacuum: %s", self._vacuum.manual_start
) | [
"async",
"def",
"async_remote_control_start",
"(",
"self",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to start remote control the vacuum: %s\"",
",",
"self",
".",
"_vacuum",
".",
"manual_start",
")"
] | [
416,
4
] | [
420,
9
] | python | en | ['en', 'it', 'en'] | True |
MiroboVacuum.async_remote_control_stop | (self) | Stop remote control mode. | Stop remote control mode. | async def async_remote_control_stop(self):
"""Stop remote control mode."""
await self._try_command(
"Unable to stop remote control the vacuum: %s", self._vacuum.manual_stop
) | [
"async",
"def",
"async_remote_control_stop",
"(",
"self",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to stop remote control the vacuum: %s\"",
",",
"self",
".",
"_vacuum",
".",
"manual_stop",
")"
] | [
422,
4
] | [
426,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_remote_control_move | (
self, rotation: int = 0, velocity: float = 0.3, duration: int = 1500
) | Move vacuum with remote control mode. | Move vacuum with remote control mode. | async def async_remote_control_move(
self, rotation: int = 0, velocity: float = 0.3, duration: int = 1500
):
"""Move vacuum with remote control mode."""
await self._try_command(
"Unable to move with remote control the vacuum: %s",
self._vacuum.manual_control,
velocity=velocity,
rotation=rotation,
duration=duration,
) | [
"async",
"def",
"async_remote_control_move",
"(",
"self",
",",
"rotation",
":",
"int",
"=",
"0",
",",
"velocity",
":",
"float",
"=",
"0.3",
",",
"duration",
":",
"int",
"=",
"1500",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to move with remote control the vacuum: %s\"",
",",
"self",
".",
"_vacuum",
".",
"manual_control",
",",
"velocity",
"=",
"velocity",
",",
"rotation",
"=",
"rotation",
",",
"duration",
"=",
"duration",
",",
")"
] | [
428,
4
] | [
438,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_remote_control_move_step | (
self, rotation: int = 0, velocity: float = 0.2, duration: int = 1500
) | Move vacuum one step with remote control mode. | Move vacuum one step with remote control mode. | async def async_remote_control_move_step(
self, rotation: int = 0, velocity: float = 0.2, duration: int = 1500
):
"""Move vacuum one step with remote control mode."""
await self._try_command(
"Unable to remote control the vacuum: %s",
self._vacuum.manual_control_once,
velocity=velocity,
rotation=rotation,
duration=duration,
) | [
"async",
"def",
"async_remote_control_move_step",
"(",
"self",
",",
"rotation",
":",
"int",
"=",
"0",
",",
"velocity",
":",
"float",
"=",
"0.2",
",",
"duration",
":",
"int",
"=",
"1500",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to remote control the vacuum: %s\"",
",",
"self",
".",
"_vacuum",
".",
"manual_control_once",
",",
"velocity",
"=",
"velocity",
",",
"rotation",
"=",
"rotation",
",",
"duration",
"=",
"duration",
",",
")"
] | [
440,
4
] | [
450,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_goto | (self, x_coord: int, y_coord: int) | Goto the specified coordinates. | Goto the specified coordinates. | async def async_goto(self, x_coord: int, y_coord: int):
"""Goto the specified coordinates."""
await self._try_command(
"Unable to send the vacuum cleaner to the specified coordinates: %s",
self._vacuum.goto,
x_coord=x_coord,
y_coord=y_coord,
) | [
"async",
"def",
"async_goto",
"(",
"self",
",",
"x_coord",
":",
"int",
",",
"y_coord",
":",
"int",
")",
":",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to send the vacuum cleaner to the specified coordinates: %s\"",
",",
"self",
".",
"_vacuum",
".",
"goto",
",",
"x_coord",
"=",
"x_coord",
",",
"y_coord",
"=",
"y_coord",
",",
")"
] | [
452,
4
] | [
459,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_clean_segment | (self, segments) | Clean the specified segments(s). | Clean the specified segments(s). | async def async_clean_segment(self, segments):
"""Clean the specified segments(s)."""
if isinstance(segments, int):
segments = [segments]
await self._try_command(
"Unable to start cleaning of the specified segments: %s",
self._vacuum.segment_clean,
segments=segments,
) | [
"async",
"def",
"async_clean_segment",
"(",
"self",
",",
"segments",
")",
":",
"if",
"isinstance",
"(",
"segments",
",",
"int",
")",
":",
"segments",
"=",
"[",
"segments",
"]",
"await",
"self",
".",
"_try_command",
"(",
"\"Unable to start cleaning of the specified segments: %s\"",
",",
"self",
".",
"_vacuum",
".",
"segment_clean",
",",
"segments",
"=",
"segments",
",",
")"
] | [
461,
4
] | [
470,
9
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.update | (self) | Fetch state from the device. | Fetch state from the device. | def update(self):
"""Fetch state from the device."""
try:
state = self._vacuum.status()
self.vacuum_state = state
self._fan_speeds = self._vacuum.fan_speed_presets()
self._fan_speeds_reverse = {v: k for k, v in self._fan_speeds.items()}
self.consumable_state = self._vacuum.consumable_status()
self.clean_history = self._vacuum.clean_history()
self.last_clean = self._vacuum.last_clean_details()
self.dnd_state = self._vacuum.dnd_status()
self._available = True
except (OSError, DeviceException) as exc:
if self._available:
self._available = False
_LOGGER.warning("Got exception while fetching the state: %s", exc)
# Fetch timers separately, see #38285
try:
self._timers = self._vacuum.timer()
except DeviceException as exc:
_LOGGER.debug(
"Unable to fetch timers, this may happen on some devices: %s", exc
)
self._timers = [] | [
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"state",
"=",
"self",
".",
"_vacuum",
".",
"status",
"(",
")",
"self",
".",
"vacuum_state",
"=",
"state",
"self",
".",
"_fan_speeds",
"=",
"self",
".",
"_vacuum",
".",
"fan_speed_presets",
"(",
")",
"self",
".",
"_fan_speeds_reverse",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_fan_speeds",
".",
"items",
"(",
")",
"}",
"self",
".",
"consumable_state",
"=",
"self",
".",
"_vacuum",
".",
"consumable_status",
"(",
")",
"self",
".",
"clean_history",
"=",
"self",
".",
"_vacuum",
".",
"clean_history",
"(",
")",
"self",
".",
"last_clean",
"=",
"self",
".",
"_vacuum",
".",
"last_clean_details",
"(",
")",
"self",
".",
"dnd_state",
"=",
"self",
".",
"_vacuum",
".",
"dnd_status",
"(",
")",
"self",
".",
"_available",
"=",
"True",
"except",
"(",
"OSError",
",",
"DeviceException",
")",
"as",
"exc",
":",
"if",
"self",
".",
"_available",
":",
"self",
".",
"_available",
"=",
"False",
"_LOGGER",
".",
"warning",
"(",
"\"Got exception while fetching the state: %s\"",
",",
"exc",
")",
"# Fetch timers separately, see #38285",
"try",
":",
"self",
".",
"_timers",
"=",
"self",
".",
"_vacuum",
".",
"timer",
"(",
")",
"except",
"DeviceException",
"as",
"exc",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Unable to fetch timers, this may happen on some devices: %s\"",
",",
"exc",
")",
"self",
".",
"_timers",
"=",
"[",
"]"
] | [
472,
4
] | [
499,
29
] | python | en | ['en', 'en', 'en'] | True |
MiroboVacuum.async_clean_zone | (self, zone, repeats=1) | Clean selected area for the number of repeats indicated. | Clean selected area for the number of repeats indicated. | async def async_clean_zone(self, zone, repeats=1):
"""Clean selected area for the number of repeats indicated."""
for _zone in zone:
_zone.append(repeats)
_LOGGER.debug("Zone with repeats: %s", zone)
try:
await self.hass.async_add_executor_job(self._vacuum.zoned_clean, zone)
except (OSError, DeviceException) as exc:
_LOGGER.error("Unable to send zoned_clean command to the vacuum: %s", exc) | [
"async",
"def",
"async_clean_zone",
"(",
"self",
",",
"zone",
",",
"repeats",
"=",
"1",
")",
":",
"for",
"_zone",
"in",
"zone",
":",
"_zone",
".",
"append",
"(",
"repeats",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Zone with repeats: %s\"",
",",
"zone",
")",
"try",
":",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_vacuum",
".",
"zoned_clean",
",",
"zone",
")",
"except",
"(",
"OSError",
",",
"DeviceException",
")",
"as",
"exc",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to send zoned_clean command to the vacuum: %s\"",
",",
"exc",
")"
] | [
501,
4
] | [
509,
86
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) | Get all light devices and setup them via config entry. | Get all light devices and setup them via config entry. | async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) -> None:
"""Get all light devices and setup them via config entry."""
entities = []
for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]:
for device in gateway.multi_level_switch_devices:
for multi_level_switch in device.multi_level_switch_property.values():
if multi_level_switch.switch_type == "dimmer":
entities.append(
DevoloLightDeviceEntity(
homecontrol=gateway,
device_instance=device,
element_uid=multi_level_switch.element_uid,
)
)
async_add_entities(entities, False) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
")",
"->",
"None",
":",
"entities",
"=",
"[",
"]",
"for",
"gateway",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"\"gateways\"",
"]",
":",
"for",
"device",
"in",
"gateway",
".",
"multi_level_switch_devices",
":",
"for",
"multi_level_switch",
"in",
"device",
".",
"multi_level_switch_property",
".",
"values",
"(",
")",
":",
"if",
"multi_level_switch",
".",
"switch_type",
"==",
"\"dimmer\"",
":",
"entities",
".",
"append",
"(",
"DevoloLightDeviceEntity",
"(",
"homecontrol",
"=",
"gateway",
",",
"device_instance",
"=",
"device",
",",
"element_uid",
"=",
"multi_level_switch",
".",
"element_uid",
",",
")",
")",
"async_add_entities",
"(",
"entities",
",",
"False",
")"
] | [
13,
0
] | [
31,
39
] | python | en | ['en', 'pt', 'en'] | True |
DevoloLightDeviceEntity.__init__ | (self, homecontrol, device_instance, element_uid) | Initialize a devolo multi level switch. | Initialize a devolo multi level switch. | def __init__(self, homecontrol, device_instance, element_uid):
"""Initialize a devolo multi level switch."""
super().__init__(
homecontrol=homecontrol,
device_instance=device_instance,
element_uid=element_uid,
)
self._binary_switch_property = device_instance.binary_switch_property.get(
element_uid.replace("Dimmer", "BinarySwitch")
) | [
"def",
"__init__",
"(",
"self",
",",
"homecontrol",
",",
"device_instance",
",",
"element_uid",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"homecontrol",
"=",
"homecontrol",
",",
"device_instance",
"=",
"device_instance",
",",
"element_uid",
"=",
"element_uid",
",",
")",
"self",
".",
"_binary_switch_property",
"=",
"device_instance",
".",
"binary_switch_property",
".",
"get",
"(",
"element_uid",
".",
"replace",
"(",
"\"Dimmer\"",
",",
"\"BinarySwitch\"",
")",
")"
] | [
37,
4
] | [
47,
9
] | python | it | ['it', 'it', 'en'] | True |
DevoloLightDeviceEntity.brightness | (self) | Return the brightness value of the light. | Return the brightness value of the light. | def brightness(self):
"""Return the brightness value of the light."""
return round(self._value / 100 * 255) | [
"def",
"brightness",
"(",
"self",
")",
":",
"return",
"round",
"(",
"self",
".",
"_value",
"/",
"100",
"*",
"255",
")"
] | [
50,
4
] | [
52,
45
] | python | en | ['en', 'no', 'en'] | True |
DevoloLightDeviceEntity.is_on | (self) | Return the state of the light. | Return the state of the light. | def is_on(self):
"""Return the state of the light."""
return bool(self._value) | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_value",
")"
] | [
55,
4
] | [
57,
32
] | python | en | ['en', 'en', 'en'] | True |
DevoloLightDeviceEntity.supported_features | (self) | Return the supported features. | Return the supported features. | def supported_features(self):
"""Return the supported features."""
return SUPPORT_BRIGHTNESS | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_BRIGHTNESS"
] | [
60,
4
] | [
62,
33
] | python | en | ['en', 'en', 'en'] | True |
DevoloLightDeviceEntity.turn_on | (self, **kwargs) | Turn device on. | Turn device on. | def turn_on(self, **kwargs) -> None:
"""Turn device on."""
if kwargs.get(ATTR_BRIGHTNESS) is not None:
self._multi_level_switch_property.set(
round(kwargs[ATTR_BRIGHTNESS] / 255 * 100)
)
else:
if self._binary_switch_property is not None:
# Turn on the light device to the latest known value. The value is known by the device itself.
self._binary_switch_property.set(True)
else:
# If there is no binary switch attached to the device, turn it on to 100 %.
self._multi_level_switch_property.set(100) | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"kwargs",
".",
"get",
"(",
"ATTR_BRIGHTNESS",
")",
"is",
"not",
"None",
":",
"self",
".",
"_multi_level_switch_property",
".",
"set",
"(",
"round",
"(",
"kwargs",
"[",
"ATTR_BRIGHTNESS",
"]",
"/",
"255",
"*",
"100",
")",
")",
"else",
":",
"if",
"self",
".",
"_binary_switch_property",
"is",
"not",
"None",
":",
"# Turn on the light device to the latest known value. The value is known by the device itself.",
"self",
".",
"_binary_switch_property",
".",
"set",
"(",
"True",
")",
"else",
":",
"# If there is no binary switch attached to the device, turn it on to 100 %.",
"self",
".",
"_multi_level_switch_property",
".",
"set",
"(",
"100",
")"
] | [
64,
4
] | [
76,
58
] | python | en | ['es', 'en', 'en'] | True |
DevoloLightDeviceEntity.turn_off | (self, **kwargs) | Turn device off. | Turn device off. | def turn_off(self, **kwargs) -> None:
"""Turn device off."""
if self._binary_switch_property is not None:
self._binary_switch_property.set(False)
else:
self._multi_level_switch_property.set(0) | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"self",
".",
"_binary_switch_property",
"is",
"not",
"None",
":",
"self",
".",
"_binary_switch_property",
".",
"set",
"(",
"False",
")",
"else",
":",
"self",
".",
"_multi_level_switch_property",
".",
"set",
"(",
"0",
")"
] | [
78,
4
] | [
83,
52
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Transport NSW sensor. | Set up the Transport NSW sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Transport NSW sensor."""
stop_id = config[CONF_STOP_ID]
api_key = config[CONF_API_KEY]
route = config.get(CONF_ROUTE)
destination = config.get(CONF_DESTINATION)
name = config.get(CONF_NAME)
data = PublicTransportData(stop_id, route, destination, api_key)
add_entities([TransportNSWSensor(data, stop_id, name)], True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"stop_id",
"=",
"config",
"[",
"CONF_STOP_ID",
"]",
"api_key",
"=",
"config",
"[",
"CONF_API_KEY",
"]",
"route",
"=",
"config",
".",
"get",
"(",
"CONF_ROUTE",
")",
"destination",
"=",
"config",
".",
"get",
"(",
"CONF_DESTINATION",
")",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"data",
"=",
"PublicTransportData",
"(",
"stop_id",
",",
"route",
",",
"destination",
",",
"api_key",
")",
"add_entities",
"(",
"[",
"TransportNSWSensor",
"(",
"data",
",",
"stop_id",
",",
"name",
")",
"]",
",",
"True",
")"
] | [
55,
0
] | [
64,
65
] | python | en | ['en', 'da', 'en'] | True |
TransportNSWSensor.__init__ | (self, data, stop_id, name) | Initialize the sensor. | Initialize the sensor. | def __init__(self, data, stop_id, name):
"""Initialize the sensor."""
self.data = data
self._name = name
self._stop_id = stop_id
self._times = self._state = None
self._icon = ICONS[None] | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"stop_id",
",",
"name",
")",
":",
"self",
".",
"data",
"=",
"data",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_stop_id",
"=",
"stop_id",
"self",
".",
"_times",
"=",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_icon",
"=",
"ICONS",
"[",
"None",
"]"
] | [
70,
4
] | [
76,
32
] | python | en | ['en', 'en', 'en'] | True |
TransportNSWSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
79,
4
] | [
81,
25
] | python | en | ['en', 'mi', 'en'] | True |
TransportNSWSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
84,
4
] | [
86,
26
] | python | en | ['en', 'en', 'en'] | True |
TransportNSWSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
if self._times is not None:
return {
ATTR_DUE_IN: self._times[ATTR_DUE_IN],
ATTR_STOP_ID: self._stop_id,
ATTR_ROUTE: self._times[ATTR_ROUTE],
ATTR_DELAY: self._times[ATTR_DELAY],
ATTR_REAL_TIME: self._times[ATTR_REAL_TIME],
ATTR_DESTINATION: self._times[ATTR_DESTINATION],
ATTR_MODE: self._times[ATTR_MODE],
ATTR_ATTRIBUTION: ATTRIBUTION,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_times",
"is",
"not",
"None",
":",
"return",
"{",
"ATTR_DUE_IN",
":",
"self",
".",
"_times",
"[",
"ATTR_DUE_IN",
"]",
",",
"ATTR_STOP_ID",
":",
"self",
".",
"_stop_id",
",",
"ATTR_ROUTE",
":",
"self",
".",
"_times",
"[",
"ATTR_ROUTE",
"]",
",",
"ATTR_DELAY",
":",
"self",
".",
"_times",
"[",
"ATTR_DELAY",
"]",
",",
"ATTR_REAL_TIME",
":",
"self",
".",
"_times",
"[",
"ATTR_REAL_TIME",
"]",
",",
"ATTR_DESTINATION",
":",
"self",
".",
"_times",
"[",
"ATTR_DESTINATION",
"]",
",",
"ATTR_MODE",
":",
"self",
".",
"_times",
"[",
"ATTR_MODE",
"]",
",",
"ATTR_ATTRIBUTION",
":",
"ATTRIBUTION",
",",
"}"
] | [
89,
4
] | [
101,
13
] | python | en | ['en', 'en', 'en'] | True |
TransportNSWSensor.unit_of_measurement | (self) | Return the unit this state is expressed in. | Return the unit this state is expressed in. | def unit_of_measurement(self):
"""Return the unit this state is expressed in."""
return TIME_MINUTES | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"TIME_MINUTES"
] | [
104,
4
] | [
106,
27
] | python | en | ['en', 'en', 'en'] | True |
TransportNSWSensor.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_icon"
] | [
109,
4
] | [
111,
25
] | python | en | ['en', 'en', 'en'] | True |
TransportNSWSensor.update | (self) | Get the latest data from Transport NSW and update the states. | Get the latest data from Transport NSW and update the states. | def update(self):
"""Get the latest data from Transport NSW and update the states."""
self.data.update()
self._times = self.data.info
self._state = self._times[ATTR_DUE_IN]
self._icon = ICONS[self._times[ATTR_MODE]] | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"data",
".",
"update",
"(",
")",
"self",
".",
"_times",
"=",
"self",
".",
"data",
".",
"info",
"self",
".",
"_state",
"=",
"self",
".",
"_times",
"[",
"ATTR_DUE_IN",
"]",
"self",
".",
"_icon",
"=",
"ICONS",
"[",
"self",
".",
"_times",
"[",
"ATTR_MODE",
"]",
"]"
] | [
113,
4
] | [
118,
50
] | python | en | ['en', 'en', 'en'] | True |
PublicTransportData.__init__ | (self, stop_id, route, destination, api_key) | Initialize the data object. | Initialize the data object. | def __init__(self, stop_id, route, destination, api_key):
"""Initialize the data object."""
self._stop_id = stop_id
self._route = route
self._destination = destination
self._api_key = api_key
self.info = {
ATTR_ROUTE: self._route,
ATTR_DUE_IN: "n/a",
ATTR_DELAY: "n/a",
ATTR_REAL_TIME: "n/a",
ATTR_DESTINATION: "n/a",
ATTR_MODE: None,
}
self.tnsw = TransportNSW() | [
"def",
"__init__",
"(",
"self",
",",
"stop_id",
",",
"route",
",",
"destination",
",",
"api_key",
")",
":",
"self",
".",
"_stop_id",
"=",
"stop_id",
"self",
".",
"_route",
"=",
"route",
"self",
".",
"_destination",
"=",
"destination",
"self",
".",
"_api_key",
"=",
"api_key",
"self",
".",
"info",
"=",
"{",
"ATTR_ROUTE",
":",
"self",
".",
"_route",
",",
"ATTR_DUE_IN",
":",
"\"n/a\"",
",",
"ATTR_DELAY",
":",
"\"n/a\"",
",",
"ATTR_REAL_TIME",
":",
"\"n/a\"",
",",
"ATTR_DESTINATION",
":",
"\"n/a\"",
",",
"ATTR_MODE",
":",
"None",
",",
"}",
"self",
".",
"tnsw",
"=",
"TransportNSW",
"(",
")"
] | [
124,
4
] | [
138,
34
] | python | en | ['en', 'en', 'en'] | True |
PublicTransportData.update | (self) | Get the next leave time. | Get the next leave time. | def update(self):
"""Get the next leave time."""
_data = self.tnsw.get_departures(
self._stop_id, self._route, self._destination, self._api_key
)
self.info = {
ATTR_ROUTE: _data["route"],
ATTR_DUE_IN: _data["due"],
ATTR_DELAY: _data["delay"],
ATTR_REAL_TIME: _data["real_time"],
ATTR_DESTINATION: _data["destination"],
ATTR_MODE: _data["mode"],
} | [
"def",
"update",
"(",
"self",
")",
":",
"_data",
"=",
"self",
".",
"tnsw",
".",
"get_departures",
"(",
"self",
".",
"_stop_id",
",",
"self",
".",
"_route",
",",
"self",
".",
"_destination",
",",
"self",
".",
"_api_key",
")",
"self",
".",
"info",
"=",
"{",
"ATTR_ROUTE",
":",
"_data",
"[",
"\"route\"",
"]",
",",
"ATTR_DUE_IN",
":",
"_data",
"[",
"\"due\"",
"]",
",",
"ATTR_DELAY",
":",
"_data",
"[",
"\"delay\"",
"]",
",",
"ATTR_REAL_TIME",
":",
"_data",
"[",
"\"real_time\"",
"]",
",",
"ATTR_DESTINATION",
":",
"_data",
"[",
"\"destination\"",
"]",
",",
"ATTR_MODE",
":",
"_data",
"[",
"\"mode\"",
"]",
",",
"}"
] | [
140,
4
] | [
152,
9
] | python | en | ['en', 'en', 'en'] | True |
HTMLCorpusReader.__init__ | (self, root, fileids=DOC_PATTERN, encoding='utf8',
tags=TAGS, **kwargs) |
Initialize the corpus reader. Categorization arguments
(``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to
the ``CategorizedCorpusReader`` constructor. The remaining
arguments are passed to the ``CorpusReader`` constructor.
|
Initialize the corpus reader. Categorization arguments
(``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to
the ``CategorizedCorpusReader`` constructor. The remaining
arguments are passed to the ``CorpusReader`` constructor.
| def __init__(self, root, fileids=DOC_PATTERN, encoding='utf8',
tags=TAGS, **kwargs):
"""
Initialize the corpus reader. Categorization arguments
(``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to
the ``CategorizedCorpusReader`` constructor. The remaining
arguments are passed to the ``CorpusReader`` constructor.
"""
# Add the default category pattern if not passed into the class.
if not any(key.startswith('cat_') for key in kwargs.keys()):
kwargs['cat_pattern'] = CAT_PATTERN
# Initialize the NLTK corpus reader objects
CategorizedCorpusReader.__init__(self, kwargs)
CorpusReader.__init__(self, root, fileids, encoding)
# Save the tags that we specifically want to extract.
self.tags = tags | [
"def",
"__init__",
"(",
"self",
",",
"root",
",",
"fileids",
"=",
"DOC_PATTERN",
",",
"encoding",
"=",
"'utf8'",
",",
"tags",
"=",
"TAGS",
",",
"*",
"*",
"kwargs",
")",
":",
"# Add the default category pattern if not passed into the class.",
"if",
"not",
"any",
"(",
"key",
".",
"startswith",
"(",
"'cat_'",
")",
"for",
"key",
"in",
"kwargs",
".",
"keys",
"(",
")",
")",
":",
"kwargs",
"[",
"'cat_pattern'",
"]",
"=",
"CAT_PATTERN",
"# Initialize the NLTK corpus reader objects",
"CategorizedCorpusReader",
".",
"__init__",
"(",
"self",
",",
"kwargs",
")",
"CorpusReader",
".",
"__init__",
"(",
"self",
",",
"root",
",",
"fileids",
",",
"encoding",
")",
"# Save the tags that we specifically want to extract.",
"self",
".",
"tags",
"=",
"tags"
] | [
19,
4
] | [
36,
24
] | python | en | ['en', 'error', 'th'] | False |
HTMLCorpusReader.resolve | (self, fileids, categories) |
Returns a list of fileids or categories depending on what is passed
to each internal corpus reader function. Implemented similarly to
the NLTK ``CategorizedPlaintextCorpusReader``.
|
Returns a list of fileids or categories depending on what is passed
to each internal corpus reader function. Implemented similarly to
the NLTK ``CategorizedPlaintextCorpusReader``.
| def resolve(self, fileids, categories):
"""
Returns a list of fileids or categories depending on what is passed
to each internal corpus reader function. Implemented similarly to
the NLTK ``CategorizedPlaintextCorpusReader``.
"""
if fileids is not None and categories is not None:
raise ValueError("Specify fileids or categories, not both")
if categories is not None:
return self.fileids(categories)
return fileids | [
"def",
"resolve",
"(",
"self",
",",
"fileids",
",",
"categories",
")",
":",
"if",
"fileids",
"is",
"not",
"None",
"and",
"categories",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Specify fileids or categories, not both\"",
")",
"if",
"categories",
"is",
"not",
"None",
":",
"return",
"self",
".",
"fileids",
"(",
"categories",
")",
"return",
"fileids"
] | [
38,
4
] | [
49,
22
] | python | en | ['en', 'error', 'th'] | False |
HTMLCorpusReader.docs | (self, fileids=None, categories=None) |
Returns the complete text of an HTML document, closing the document
after we are done reading it and yielding it in a memory safe fashion.
|
Returns the complete text of an HTML document, closing the document
after we are done reading it and yielding it in a memory safe fashion.
| def docs(self, fileids=None, categories=None):
"""
Returns the complete text of an HTML document, closing the document
after we are done reading it and yielding it in a memory safe fashion.
"""
# Resolve the fileids and the categories
fileids = self.resolve(fileids, categories)
# Create a generator, loading one document into memory at a time.
for path, encoding in self.abspaths(fileids, include_encoding=True):
with codecs.open(path, 'r', encoding=encoding) as f:
yield f.read() | [
"def",
"docs",
"(",
"self",
",",
"fileids",
"=",
"None",
",",
"categories",
"=",
"None",
")",
":",
"# Resolve the fileids and the categories",
"fileids",
"=",
"self",
".",
"resolve",
"(",
"fileids",
",",
"categories",
")",
"# Create a generator, loading one document into memory at a time.",
"for",
"path",
",",
"encoding",
"in",
"self",
".",
"abspaths",
"(",
"fileids",
",",
"include_encoding",
"=",
"True",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"yield",
"f",
".",
"read",
"(",
")"
] | [
51,
4
] | [
62,
30
] | python | en | ['en', 'error', 'th'] | False |
HTMLCorpusReader.sizes | (self, fileids=None, categories=None) |
Returns a list of tuples, the fileid and size on disk of the file.
This function is used to detect oddly large files in the corpus.
|
Returns a list of tuples, the fileid and size on disk of the file.
This function is used to detect oddly large files in the corpus.
| def sizes(self, fileids=None, categories=None):
"""
Returns a list of tuples, the fileid and size on disk of the file.
This function is used to detect oddly large files in the corpus.
"""
# Resolve the fileids and the categories
fileids = self.resolve(fileids, categories)
# Create a generator, getting every path and computing filesize
for path in self.abspaths(fileids):
yield os.path.getsize(path) | [
"def",
"sizes",
"(",
"self",
",",
"fileids",
"=",
"None",
",",
"categories",
"=",
"None",
")",
":",
"# Resolve the fileids and the categories",
"fileids",
"=",
"self",
".",
"resolve",
"(",
"fileids",
",",
"categories",
")",
"# Create a generator, getting every path and computing filesize",
"for",
"path",
"in",
"self",
".",
"abspaths",
"(",
"fileids",
")",
":",
"yield",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")"
] | [
64,
4
] | [
74,
39
] | python | en | ['en', 'error', 'th'] | False |
SqliteCorpusReader.scores | (self) |
Returns the review score
|
Returns the review score
| def scores(self):
"""
Returns the review score
"""
self._cur.execute("SELECT score FROM reviews")
for score in iter(self._cur.fetchone, None):
yield score | [
"def",
"scores",
"(",
"self",
")",
":",
"self",
".",
"_cur",
".",
"execute",
"(",
"\"SELECT score FROM reviews\"",
")",
"for",
"score",
"in",
"iter",
"(",
"self",
".",
"_cur",
".",
"fetchone",
",",
"None",
")",
":",
"yield",
"score"
] | [
81,
4
] | [
87,
23
] | python | en | ['en', 'error', 'th'] | False |
SqliteCorpusReader.texts | (self) |
Returns the full review texts
|
Returns the full review texts
| def texts(self):
"""
Returns the full review texts
"""
self._cur.execute("SELECT content FROM content")
for text in iter(self._cur.fetchone, None):
yield text | [
"def",
"texts",
"(",
"self",
")",
":",
"self",
".",
"_cur",
".",
"execute",
"(",
"\"SELECT content FROM content\"",
")",
"for",
"text",
"in",
"iter",
"(",
"self",
".",
"_cur",
".",
"fetchone",
",",
"None",
")",
":",
"yield",
"text"
] | [
89,
4
] | [
95,
22
] | python | en | ['en', 'error', 'th'] | False |
SqliteCorpusReader.ids | (self) |
Returns the review ids
|
Returns the review ids
| def ids(self):
"""
Returns the review ids
"""
self._cur.execute("SELECT reviewid FROM content")
for idx in iter(self._cur.fetchone, None):
yield idx | [
"def",
"ids",
"(",
"self",
")",
":",
"self",
".",
"_cur",
".",
"execute",
"(",
"\"SELECT reviewid FROM content\"",
")",
"for",
"idx",
"in",
"iter",
"(",
"self",
".",
"_cur",
".",
"fetchone",
",",
"None",
")",
":",
"yield",
"idx"
] | [
97,
4
] | [
103,
21
] | python | en | ['en', 'error', 'th'] | False |
normalize_metadata | (metadata: dict) | Normalize object metadata by stripping the prefix. | Normalize object metadata by stripping the prefix. | def normalize_metadata(metadata: dict) -> dict:
"""Normalize object metadata by stripping the prefix."""
new_metadata = {}
for meta_key, meta_value in metadata.items():
match = _METADATA_RE.match(meta_key)
if not match:
continue
new_metadata[match.group(1).lower()] = meta_value
return new_metadata | [
"def",
"normalize_metadata",
"(",
"metadata",
":",
"dict",
")",
"->",
"dict",
":",
"new_metadata",
"=",
"{",
"}",
"for",
"meta_key",
",",
"meta_value",
"in",
"metadata",
".",
"items",
"(",
")",
":",
"match",
"=",
"_METADATA_RE",
".",
"match",
"(",
"meta_key",
")",
"if",
"not",
"match",
":",
"continue",
"new_metadata",
"[",
"match",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"]",
"=",
"meta_value",
"return",
"new_metadata"
] | [
19,
0
] | [
29,
23
] | python | en | ['en', 'en', 'en'] | True |
create_minio_client | (
endpoint: str, access_key: str, secret_key: str, secure: bool
) | Create Minio client. | Create Minio client. | def create_minio_client(
endpoint: str, access_key: str, secret_key: str, secure: bool
) -> Minio:
"""Create Minio client."""
return Minio(endpoint, access_key, secret_key, secure) | [
"def",
"create_minio_client",
"(",
"endpoint",
":",
"str",
",",
"access_key",
":",
"str",
",",
"secret_key",
":",
"str",
",",
"secure",
":",
"bool",
")",
"->",
"Minio",
":",
"return",
"Minio",
"(",
"endpoint",
",",
"access_key",
",",
"secret_key",
",",
"secure",
")"
] | [
32,
0
] | [
36,
58
] | python | en | ['lt', 'la', 'en'] | False |
get_minio_notification_response | (
minio_client, bucket_name: str, prefix: str, suffix: str, events: List[str]
) | Start listening to minio events. Copied from minio-py. | Start listening to minio events. Copied from minio-py. | def get_minio_notification_response(
minio_client, bucket_name: str, prefix: str, suffix: str, events: List[str]
):
"""Start listening to minio events. Copied from minio-py."""
query = {"prefix": prefix, "suffix": suffix, "events": events}
# pylint: disable=protected-access
return minio_client._url_open(
"GET", bucket_name=bucket_name, query=query, preload_content=False
) | [
"def",
"get_minio_notification_response",
"(",
"minio_client",
",",
"bucket_name",
":",
"str",
",",
"prefix",
":",
"str",
",",
"suffix",
":",
"str",
",",
"events",
":",
"List",
"[",
"str",
"]",
")",
":",
"query",
"=",
"{",
"\"prefix\"",
":",
"prefix",
",",
"\"suffix\"",
":",
"suffix",
",",
"\"events\"",
":",
"events",
"}",
"# pylint: disable=protected-access",
"return",
"minio_client",
".",
"_url_open",
"(",
"\"GET\"",
",",
"bucket_name",
"=",
"bucket_name",
",",
"query",
"=",
"query",
",",
"preload_content",
"=",
"False",
")"
] | [
39,
0
] | [
47,
5
] | python | en | ['en', 'en', 'en'] | True |
iterate_objects | (event) |
Iterate over file records of notification event.
Most of the time it should still be only one record.
|
Iterate over file records of notification event. | def iterate_objects(event):
"""
Iterate over file records of notification event.
Most of the time it should still be only one record.
"""
records = event.get("Records", [])
for record in records:
event_name = record.get("eventName")
bucket = record.get("s3", {}).get("bucket", {}).get("name")
key = record.get("s3", {}).get("object", {}).get("key")
metadata = normalize_metadata(
record.get("s3", {}).get("object", {}).get("userMetadata", {})
)
if not bucket or not key:
_LOGGER.warning("Invalid bucket and/or key, %s, %s", bucket, key)
continue
key = unquote(key)
yield event_name, bucket, key, metadata | [
"def",
"iterate_objects",
"(",
"event",
")",
":",
"records",
"=",
"event",
".",
"get",
"(",
"\"Records\"",
",",
"[",
"]",
")",
"for",
"record",
"in",
"records",
":",
"event_name",
"=",
"record",
".",
"get",
"(",
"\"eventName\"",
")",
"bucket",
"=",
"record",
".",
"get",
"(",
"\"s3\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"bucket\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"name\"",
")",
"key",
"=",
"record",
".",
"get",
"(",
"\"s3\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"object\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"key\"",
")",
"metadata",
"=",
"normalize_metadata",
"(",
"record",
".",
"get",
"(",
"\"s3\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"object\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"userMetadata\"",
",",
"{",
"}",
")",
")",
"if",
"not",
"bucket",
"or",
"not",
"key",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Invalid bucket and/or key, %s, %s\"",
",",
"bucket",
",",
"key",
")",
"continue",
"key",
"=",
"unquote",
"(",
"key",
")",
"yield",
"event_name",
",",
"bucket",
",",
"key",
",",
"metadata"
] | [
186,
0
] | [
208,
47
] | python | en | ['en', 'error', 'th'] | False |
MinioEventStreamIterator.__iter__ | (self) | Return self. | Return self. | def __iter__(self) -> Iterator:
"""Return self."""
return self | [
"def",
"__iter__",
"(",
"self",
")",
"->",
"Iterator",
":",
"return",
"self"
] | [
53,
4
] | [
55,
19
] | python | en | ['en', 'ig', 'en'] | False |
MinioEventStreamIterator.__next__ | (self) | Get next not empty line. | Get next not empty line. | def __next__(self):
"""Get next not empty line."""
while True:
line = next(self._stream)
if line.strip():
event = json.loads(line.decode("utf-8"))
if event["Records"] is not None:
return event | [
"def",
"__next__",
"(",
"self",
")",
":",
"while",
"True",
":",
"line",
"=",
"next",
"(",
"self",
".",
"_stream",
")",
"if",
"line",
".",
"strip",
"(",
")",
":",
"event",
"=",
"json",
".",
"loads",
"(",
"line",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"if",
"event",
"[",
"\"Records\"",
"]",
"is",
"not",
"None",
":",
"return",
"event"
] | [
62,
4
] | [
69,
32
] | python | en | ['en', 'nl', 'en'] | True |
MinioEventStreamIterator.close | (self) | Close the response. | Close the response. | def close(self):
"""Close the response."""
self._response.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_response",
".",
"close",
"(",
")"
] | [
71,
4
] | [
73,
30
] | python | en | ['en', 'en', 'en'] | True |
MinioEventThread.__init__ | (
self,
queue: Queue,
endpoint: str,
access_key: str,
secret_key: str,
secure: bool,
bucket_name: str,
prefix: str,
suffix: str,
events: List[str],
) | Copy over all Minio client options. | Copy over all Minio client options. | def __init__(
self,
queue: Queue,
endpoint: str,
access_key: str,
secret_key: str,
secure: bool,
bucket_name: str,
prefix: str,
suffix: str,
events: List[str],
):
"""Copy over all Minio client options."""
super().__init__()
self._queue = queue
self._endpoint = endpoint
self._access_key = access_key
self._secret_key = secret_key
self._secure = secure
self._bucket_name = bucket_name
self._prefix = prefix
self._suffix = suffix
self._events = events
self._event_stream_it = None
self._should_stop = False | [
"def",
"__init__",
"(",
"self",
",",
"queue",
":",
"Queue",
",",
"endpoint",
":",
"str",
",",
"access_key",
":",
"str",
",",
"secret_key",
":",
"str",
",",
"secure",
":",
"bool",
",",
"bucket_name",
":",
"str",
",",
"prefix",
":",
"str",
",",
"suffix",
":",
"str",
",",
"events",
":",
"List",
"[",
"str",
"]",
",",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_queue",
"=",
"queue",
"self",
".",
"_endpoint",
"=",
"endpoint",
"self",
".",
"_access_key",
"=",
"access_key",
"self",
".",
"_secret_key",
"=",
"secret_key",
"self",
".",
"_secure",
"=",
"secure",
"self",
".",
"_bucket_name",
"=",
"bucket_name",
"self",
".",
"_prefix",
"=",
"prefix",
"self",
".",
"_suffix",
"=",
"suffix",
"self",
".",
"_events",
"=",
"events",
"self",
".",
"_event_stream_it",
"=",
"None",
"self",
".",
"_should_stop",
"=",
"False"
] | [
79,
4
] | [
103,
33
] | python | en | ['en', 'en', 'en'] | True |
MinioEventThread.__enter__ | (self) | Start the thread. | Start the thread. | def __enter__(self):
"""Start the thread."""
self.start() | [
"def",
"__enter__",
"(",
"self",
")",
":",
"self",
".",
"start",
"(",
")"
] | [
105,
4
] | [
107,
20
] | python | en | ['en', 'fi', 'en'] | True |
MinioEventThread.__exit__ | (self, exc_type, exc_val, exc_tb) | Stop and join the thread. | Stop and join the thread. | def __exit__(self, exc_type, exc_val, exc_tb):
"""Stop and join the thread."""
self.stop() | [
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc_val",
",",
"exc_tb",
")",
":",
"self",
".",
"stop",
"(",
")"
] | [
109,
4
] | [
111,
19
] | python | en | ['en', 'en', 'en'] | True |
MinioEventThread.run | (self) | Create MinioClient and run the loop. | Create MinioClient and run the loop. | def run(self):
"""Create MinioClient and run the loop."""
_LOGGER.info("Running MinioEventThread")
self._should_stop = False
minio_client = create_minio_client(
self._endpoint, self._access_key, self._secret_key, self._secure
)
while not self._should_stop:
_LOGGER.info("Connecting to minio event stream")
response = None
try:
response = get_minio_notification_response(
minio_client,
self._bucket_name,
self._prefix,
self._suffix,
self._events,
)
self._event_stream_it = MinioEventStreamIterator(response)
self._iterate_event_stream(self._event_stream_it, minio_client)
except json.JSONDecodeError:
if response:
response.close()
except HTTPError as error:
_LOGGER.error("Failed to connect to Minio endpoint: %s", error)
# Wait before attempting to connect again.
time.sleep(1)
except AttributeError:
# When response is closed, iterator will fail to access
# the underlying socket descriptor.
break | [
"def",
"run",
"(",
"self",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Running MinioEventThread\"",
")",
"self",
".",
"_should_stop",
"=",
"False",
"minio_client",
"=",
"create_minio_client",
"(",
"self",
".",
"_endpoint",
",",
"self",
".",
"_access_key",
",",
"self",
".",
"_secret_key",
",",
"self",
".",
"_secure",
")",
"while",
"not",
"self",
".",
"_should_stop",
":",
"_LOGGER",
".",
"info",
"(",
"\"Connecting to minio event stream\"",
")",
"response",
"=",
"None",
"try",
":",
"response",
"=",
"get_minio_notification_response",
"(",
"minio_client",
",",
"self",
".",
"_bucket_name",
",",
"self",
".",
"_prefix",
",",
"self",
".",
"_suffix",
",",
"self",
".",
"_events",
",",
")",
"self",
".",
"_event_stream_it",
"=",
"MinioEventStreamIterator",
"(",
"response",
")",
"self",
".",
"_iterate_event_stream",
"(",
"self",
".",
"_event_stream_it",
",",
"minio_client",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"if",
"response",
":",
"response",
".",
"close",
"(",
")",
"except",
"HTTPError",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed to connect to Minio endpoint: %s\"",
",",
"error",
")",
"# Wait before attempting to connect again.",
"time",
".",
"sleep",
"(",
"1",
")",
"except",
"AttributeError",
":",
"# When response is closed, iterator will fail to access",
"# the underlying socket descriptor.",
"break"
] | [
113,
4
] | [
149,
21
] | python | en | ['en', 'en', 'en'] | True |
MinioEventThread.stop | (self) | Cancel event stream and join the thread. | Cancel event stream and join the thread. | def stop(self):
"""Cancel event stream and join the thread."""
_LOGGER.debug("Stopping event thread")
self._should_stop = True
if self._event_stream_it is not None:
self._event_stream_it.close()
self._event_stream_it = None
_LOGGER.debug("Joining event thread")
self.join()
_LOGGER.debug("Event thread joined") | [
"def",
"stop",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Stopping event thread\"",
")",
"self",
".",
"_should_stop",
"=",
"True",
"if",
"self",
".",
"_event_stream_it",
"is",
"not",
"None",
":",
"self",
".",
"_event_stream_it",
".",
"close",
"(",
")",
"self",
".",
"_event_stream_it",
"=",
"None",
"_LOGGER",
".",
"debug",
"(",
"\"Joining event thread\"",
")",
"self",
".",
"join",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Event thread joined\"",
")"
] | [
173,
4
] | [
183,
44
] | python | en | ['en', 'en', 'en'] | True |
mock_hub_discover | () | Mock the hub discover method. | Mock the hub discover method. | def mock_hub_discover():
"""Mock the hub discover method."""
with patch("aiopulse.Hub.discover") as mock_discover:
yield mock_discover | [
"def",
"mock_hub_discover",
"(",
")",
":",
"with",
"patch",
"(",
"\"aiopulse.Hub.discover\"",
")",
"as",
"mock_discover",
":",
"yield",
"mock_discover"
] | [
21,
0
] | [
24,
27
] | python | en | ['en', 'ceb', 'en'] | True |
mock_hub_run | () | Mock the hub run method. | Mock the hub run method. | def mock_hub_run():
"""Mock the hub run method."""
with patch("aiopulse.Hub.run") as mock_run:
yield mock_run | [
"def",
"mock_hub_run",
"(",
")",
":",
"with",
"patch",
"(",
"\"aiopulse.Hub.run\"",
")",
"as",
"mock_run",
":",
"yield",
"mock_run"
] | [
28,
0
] | [
31,
22
] | python | en | ['en', 'uz', 'en'] | True |
async_generator | (items) | Async yields items provided in a list. | Async yields items provided in a list. | async def async_generator(items):
"""Async yields items provided in a list."""
for item in items:
yield item | [
"async",
"def",
"async_generator",
"(",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"yield",
"item"
] | [
34,
0
] | [
37,
18
] | python | en | ['en', 'en', 'en'] | True |
test_show_form_no_hubs | (hass, mock_hub_discover) | Test that flow aborts if no hubs are discovered. | Test that flow aborts if no hubs are discovered. | async def test_show_form_no_hubs(hass, mock_hub_discover):
"""Test that flow aborts if no hubs are discovered."""
mock_hub_discover.return_value = async_generator([])
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "no_devices_found"
# Check we performed the discovery
assert len(mock_hub_discover.mock_calls) == 1 | [
"async",
"def",
"test_show_form_no_hubs",
"(",
"hass",
",",
"mock_hub_discover",
")",
":",
"mock_hub_discover",
".",
"return_value",
"=",
"async_generator",
"(",
"[",
"]",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"no_devices_found\"",
"# Check we performed the discovery",
"assert",
"len",
"(",
"mock_hub_discover",
".",
"mock_calls",
")",
"==",
"1"
] | [
40,
0
] | [
52,
49
] | python | en | ['en', 'en', 'en'] | True |
test_show_form_one_hub | (hass, mock_hub_discover, mock_hub_run) | Test that a config is created when one hub discovered. | Test that a config is created when one hub discovered. | async def test_show_form_one_hub(hass, mock_hub_discover, mock_hub_run):
"""Test that a config is created when one hub discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
mock_hub_discover.return_value = async_generator([dummy_hub_1])
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == dummy_hub_1.id
assert result["result"].data == {
"host": DUMMY_HOST1,
}
# Check we performed the discovery
assert len(mock_hub_discover.mock_calls) == 1 | [
"async",
"def",
"test_show_form_one_hub",
"(",
"hass",
",",
"mock_hub_discover",
",",
"mock_hub_run",
")",
":",
"dummy_hub_1",
"=",
"aiopulse",
".",
"Hub",
"(",
"DUMMY_HOST1",
")",
"dummy_hub_1",
".",
"id",
"=",
"\"ABC123\"",
"mock_hub_discover",
".",
"return_value",
"=",
"async_generator",
"(",
"[",
"dummy_hub_1",
"]",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"dummy_hub_1",
".",
"id",
"assert",
"result",
"[",
"\"result\"",
"]",
".",
"data",
"==",
"{",
"\"host\"",
":",
"DUMMY_HOST1",
",",
"}",
"# Check we performed the discovery",
"assert",
"len",
"(",
"mock_hub_discover",
".",
"mock_calls",
")",
"==",
"1"
] | [
55,
0
] | [
74,
49
] | python | en | ['en', 'en', 'en'] | True |
test_show_form_two_hubs | (hass, mock_hub_discover) | Test that the form is served when more than one hub discovered. | Test that the form is served when more than one hub discovered. | async def test_show_form_two_hubs(hass, mock_hub_discover):
"""Test that the form is served when more than one hub discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
dummy_hub_2 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_2.id = "DEF456"
mock_hub_discover.return_value = async_generator([dummy_hub_1, dummy_hub_2])
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
# Check we performed the discovery
assert len(mock_hub_discover.mock_calls) == 1 | [
"async",
"def",
"test_show_form_two_hubs",
"(",
"hass",
",",
"mock_hub_discover",
")",
":",
"dummy_hub_1",
"=",
"aiopulse",
".",
"Hub",
"(",
"DUMMY_HOST1",
")",
"dummy_hub_1",
".",
"id",
"=",
"\"ABC123\"",
"dummy_hub_2",
"=",
"aiopulse",
".",
"Hub",
"(",
"DUMMY_HOST1",
")",
"dummy_hub_2",
".",
"id",
"=",
"\"DEF456\"",
"mock_hub_discover",
".",
"return_value",
"=",
"async_generator",
"(",
"[",
"dummy_hub_1",
",",
"dummy_hub_2",
"]",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"# Check we performed the discovery",
"assert",
"len",
"(",
"mock_hub_discover",
".",
"mock_calls",
")",
"==",
"1"
] | [
77,
0
] | [
96,
49
] | python | en | ['en', 'en', 'en'] | True |
test_create_second_entry | (hass, mock_hub_run, mock_hub_discover) | Test that a config is created when a second hub is discovered. | Test that a config is created when a second hub is discovered. | async def test_create_second_entry(hass, mock_hub_run, mock_hub_discover):
"""Test that a config is created when a second hub is discovered."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
dummy_hub_2 = aiopulse.Hub(DUMMY_HOST2)
dummy_hub_2.id = "DEF456"
mock_hub_discover.return_value = async_generator([dummy_hub_1, dummy_hub_2])
MockConfigEntry(domain=DOMAIN, unique_id=dummy_hub_1.id, data=CONFIG).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == dummy_hub_2.id
assert result["result"].data == {
"host": DUMMY_HOST2,
} | [
"async",
"def",
"test_create_second_entry",
"(",
"hass",
",",
"mock_hub_run",
",",
"mock_hub_discover",
")",
":",
"dummy_hub_1",
"=",
"aiopulse",
".",
"Hub",
"(",
"DUMMY_HOST1",
")",
"dummy_hub_1",
".",
"id",
"=",
"\"ABC123\"",
"dummy_hub_2",
"=",
"aiopulse",
".",
"Hub",
"(",
"DUMMY_HOST2",
")",
"dummy_hub_2",
".",
"id",
"=",
"\"DEF456\"",
"mock_hub_discover",
".",
"return_value",
"=",
"async_generator",
"(",
"[",
"dummy_hub_1",
",",
"dummy_hub_2",
"]",
")",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"unique_id",
"=",
"dummy_hub_1",
".",
"id",
",",
"data",
"=",
"CONFIG",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"dummy_hub_2",
".",
"id",
"assert",
"result",
"[",
"\"result\"",
"]",
".",
"data",
"==",
"{",
"\"host\"",
":",
"DUMMY_HOST2",
",",
"}"
] | [
99,
0
] | [
122,
5
] | python | en | ['en', 'en', 'en'] | True |
test_already_configured | (hass, mock_hub_discover) | Test that flow aborts when all hubs are configured. | Test that flow aborts when all hubs are configured. | async def test_already_configured(hass, mock_hub_discover):
"""Test that flow aborts when all hubs are configured."""
dummy_hub_1 = aiopulse.Hub(DUMMY_HOST1)
dummy_hub_1.id = "ABC123"
mock_hub_discover.return_value = async_generator([dummy_hub_1])
MockConfigEntry(domain=DOMAIN, unique_id=dummy_hub_1.id, data=CONFIG).add_to_hass(
hass
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == "abort"
assert result["reason"] == "no_devices_found" | [
"async",
"def",
"test_already_configured",
"(",
"hass",
",",
"mock_hub_discover",
")",
":",
"dummy_hub_1",
"=",
"aiopulse",
".",
"Hub",
"(",
"DUMMY_HOST1",
")",
"dummy_hub_1",
".",
"id",
"=",
"\"ABC123\"",
"mock_hub_discover",
".",
"return_value",
"=",
"async_generator",
"(",
"[",
"dummy_hub_1",
"]",
")",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"unique_id",
"=",
"dummy_hub_1",
".",
"id",
",",
"data",
"=",
"CONFIG",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"no_devices_found\""
] | [
125,
0
] | [
142,
49
] | python | en | ['en', 'en', 'en'] | True |
connect_lights | (lights: List[pyzerproc.Light]) | Attempt to connect to lights, and return the connected lights. | Attempt to connect to lights, and return the connected lights. | def connect_lights(lights: List[pyzerproc.Light]) -> List[pyzerproc.Light]:
"""Attempt to connect to lights, and return the connected lights."""
connected = []
for light in lights:
try:
light.connect(auto_reconnect=True)
connected.append(light)
except pyzerproc.ZerprocException:
_LOGGER.debug("Unable to connect to '%s'", light.address, exc_info=True)
return connected | [
"def",
"connect_lights",
"(",
"lights",
":",
"List",
"[",
"pyzerproc",
".",
"Light",
"]",
")",
"->",
"List",
"[",
"pyzerproc",
".",
"Light",
"]",
":",
"connected",
"=",
"[",
"]",
"for",
"light",
"in",
"lights",
":",
"try",
":",
"light",
".",
"connect",
"(",
"auto_reconnect",
"=",
"True",
")",
"connected",
".",
"append",
"(",
"light",
")",
"except",
"pyzerproc",
".",
"ZerprocException",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Unable to connect to '%s'\"",
",",
"light",
".",
"address",
",",
"exc_info",
"=",
"True",
")",
"return",
"connected"
] | [
33,
0
] | [
43,
20
] | python | en | ['en', 'en', 'en'] | True |
discover_entities | (hass: HomeAssistant) | Attempt to discover new lights. | Attempt to discover new lights. | def discover_entities(hass: HomeAssistant) -> List[Entity]:
"""Attempt to discover new lights."""
lights = pyzerproc.discover()
# Filter out already discovered lights
new_lights = [
light for light in lights if light.address not in hass.data[DOMAIN]["addresses"]
]
entities = []
for light in connect_lights(new_lights):
# Double-check the light hasn't been added in another thread
if light.address not in hass.data[DOMAIN]["addresses"]:
hass.data[DOMAIN]["addresses"].add(light.address)
entities.append(ZerprocLight(light))
return entities | [
"def",
"discover_entities",
"(",
"hass",
":",
"HomeAssistant",
")",
"->",
"List",
"[",
"Entity",
"]",
":",
"lights",
"=",
"pyzerproc",
".",
"discover",
"(",
")",
"# Filter out already discovered lights",
"new_lights",
"=",
"[",
"light",
"for",
"light",
"in",
"lights",
"if",
"light",
".",
"address",
"not",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"addresses\"",
"]",
"]",
"entities",
"=",
"[",
"]",
"for",
"light",
"in",
"connect_lights",
"(",
"new_lights",
")",
":",
"# Double-check the light hasn't been added in another thread",
"if",
"light",
".",
"address",
"not",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"addresses\"",
"]",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"addresses\"",
"]",
".",
"add",
"(",
"light",
".",
"address",
")",
"entities",
".",
"append",
"(",
"ZerprocLight",
"(",
"light",
")",
")",
"return",
"entities"
] | [
46,
0
] | [
62,
19
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType,
config_entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) | Set up Abode light devices. | Set up Abode light devices. | async def async_setup_entry(
hass: HomeAssistantType,
config_entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) -> None:
"""Set up Abode light devices."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
if "addresses" not in hass.data[DOMAIN]:
hass.data[DOMAIN]["addresses"] = set()
warned = False
async def discover(*args):
"""Wrap discovery to include params."""
nonlocal warned
try:
entities = await hass.async_add_executor_job(discover_entities, hass)
async_add_entities(entities, update_before_add=True)
warned = False
except pyzerproc.ZerprocException:
if warned is False:
_LOGGER.warning("Error discovering Zerproc lights", exc_info=True)
warned = True
# Initial discovery
hass.async_create_task(discover())
# Perform recurring discovery of new devices
async_track_time_interval(hass, discover, DISCOVERY_INTERVAL) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"config_entry",
":",
"ConfigEntry",
",",
"async_add_entities",
":",
"Callable",
"[",
"[",
"List",
"[",
"Entity",
"]",
",",
"bool",
"]",
",",
"None",
"]",
",",
")",
"->",
"None",
":",
"if",
"DOMAIN",
"not",
"in",
"hass",
".",
"data",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"if",
"\"addresses\"",
"not",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"addresses\"",
"]",
"=",
"set",
"(",
")",
"warned",
"=",
"False",
"async",
"def",
"discover",
"(",
"*",
"args",
")",
":",
"\"\"\"Wrap discovery to include params.\"\"\"",
"nonlocal",
"warned",
"try",
":",
"entities",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"discover_entities",
",",
"hass",
")",
"async_add_entities",
"(",
"entities",
",",
"update_before_add",
"=",
"True",
")",
"warned",
"=",
"False",
"except",
"pyzerproc",
".",
"ZerprocException",
":",
"if",
"warned",
"is",
"False",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Error discovering Zerproc lights\"",
",",
"exc_info",
"=",
"True",
")",
"warned",
"=",
"True",
"# Initial discovery",
"hass",
".",
"async_create_task",
"(",
"discover",
"(",
")",
")",
"# Perform recurring discovery of new devices",
"async_track_time_interval",
"(",
"hass",
",",
"discover",
",",
"DISCOVERY_INTERVAL",
")"
] | [
65,
0
] | [
94,
65
] | python | en | ['fr', 'en', 'en'] | True |
ZerprocLight.__init__ | (self, light) | Initialize a Zerproc light. | Initialize a Zerproc light. | def __init__(self, light):
"""Initialize a Zerproc light."""
self._light = light
self._name = None
self._is_on = None
self._hs_color = None
self._brightness = None
self._available = True | [
"def",
"__init__",
"(",
"self",
",",
"light",
")",
":",
"self",
".",
"_light",
"=",
"light",
"self",
".",
"_name",
"=",
"None",
"self",
".",
"_is_on",
"=",
"None",
"self",
".",
"_hs_color",
"=",
"None",
"self",
".",
"_brightness",
"=",
"None",
"self",
".",
"_available",
"=",
"True"
] | [
100,
4
] | [
107,
30
] | python | en | ['en', 'lb', 'it'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.