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
GoogleConfig.async_call_homegraph_api_key
(self, url, data)
Call a homegraph api with api key authentication.
Call a homegraph api with api key authentication.
async def async_call_homegraph_api_key(self, url, data): """Call a homegraph api with api key authentication.""" websession = async_get_clientsession(self.hass) try: res = await websession.post( url, params={"key": self._config.get(CONF_API_KEY)}, json=data ) _LOGGER.debug( "Response on %s with data %s was %s", url, data, await res.text() ) res.raise_for_status() return res.status except ClientResponseError as error: _LOGGER.error("Request for %s failed: %d", url, error.status) return error.status except (asyncio.TimeoutError, ClientError): _LOGGER.error("Could not contact %s", url) return HTTP_INTERNAL_SERVER_ERROR
[ "async", "def", "async_call_homegraph_api_key", "(", "self", ",", "url", ",", "data", ")", ":", "websession", "=", "async_get_clientsession", "(", "self", ".", "hass", ")", "try", ":", "res", "=", "await", "websession", ".", "post", "(", "url", ",", "params", "=", "{", "\"key\"", ":", "self", ".", "_config", ".", "get", "(", "CONF_API_KEY", ")", "}", ",", "json", "=", "data", ")", "_LOGGER", ".", "debug", "(", "\"Response on %s with data %s was %s\"", ",", "url", ",", "data", ",", "await", "res", ".", "text", "(", ")", ")", "res", ".", "raise_for_status", "(", ")", "return", "res", ".", "status", "except", "ClientResponseError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Request for %s failed: %d\"", ",", "url", ",", "error", ".", "status", ")", "return", "error", ".", "status", "except", "(", "asyncio", ".", "TimeoutError", ",", "ClientError", ")", ":", "_LOGGER", ".", "error", "(", "\"Could not contact %s\"", ",", "url", ")", "return", "HTTP_INTERNAL_SERVER_ERROR" ]
[ 166, 4 ]
[ 183, 45 ]
python
en
['en', 'pt', 'en']
True
GoogleConfig.async_call_homegraph_api
(self, url, data)
Call a homegraph api with authentication.
Call a homegraph api with authentication.
async def async_call_homegraph_api(self, url, data): """Call a homegraph api with authentication.""" session = async_get_clientsession(self.hass) async def _call(): headers = { "Authorization": f"Bearer {self._access_token}", "X-GFE-SSL": "yes", } async with session.post(url, headers=headers, json=data) as res: _LOGGER.debug( "Response on %s with data %s was %s", url, data, await res.text() ) res.raise_for_status() return res.status try: await self._async_update_token() try: return await _call() except ClientResponseError as error: if error.status == HTTP_UNAUTHORIZED: _LOGGER.warning( "Request for %s unauthorized, renewing token and retrying", url ) await self._async_update_token(True) return await _call() raise except ClientResponseError as error: _LOGGER.error("Request for %s failed: %d", url, error.status) return error.status except (asyncio.TimeoutError, ClientError): _LOGGER.error("Could not contact %s", url) return HTTP_INTERNAL_SERVER_ERROR
[ "async", "def", "async_call_homegraph_api", "(", "self", ",", "url", ",", "data", ")", ":", "session", "=", "async_get_clientsession", "(", "self", ".", "hass", ")", "async", "def", "_call", "(", ")", ":", "headers", "=", "{", "\"Authorization\"", ":", "f\"Bearer {self._access_token}\"", ",", "\"X-GFE-SSL\"", ":", "\"yes\"", ",", "}", "async", "with", "session", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "json", "=", "data", ")", "as", "res", ":", "_LOGGER", ".", "debug", "(", "\"Response on %s with data %s was %s\"", ",", "url", ",", "data", ",", "await", "res", ".", "text", "(", ")", ")", "res", ".", "raise_for_status", "(", ")", "return", "res", ".", "status", "try", ":", "await", "self", ".", "_async_update_token", "(", ")", "try", ":", "return", "await", "_call", "(", ")", "except", "ClientResponseError", "as", "error", ":", "if", "error", ".", "status", "==", "HTTP_UNAUTHORIZED", ":", "_LOGGER", ".", "warning", "(", "\"Request for %s unauthorized, renewing token and retrying\"", ",", "url", ")", "await", "self", ".", "_async_update_token", "(", "True", ")", "return", "await", "_call", "(", ")", "raise", "except", "ClientResponseError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Request for %s failed: %d\"", ",", "url", ",", "error", ".", "status", ")", "return", "error", ".", "status", "except", "(", "asyncio", ".", "TimeoutError", ",", "ClientError", ")", ":", "_LOGGER", ".", "error", "(", "\"Could not contact %s\"", ",", "url", ")", "return", "HTTP_INTERNAL_SERVER_ERROR" ]
[ 185, 4 ]
[ 218, 45 ]
python
en
['en', 'en', 'en']
True
GoogleConfig.async_report_state
(self, message, agent_user_id: str)
Send a state report to Google.
Send a state report to Google.
async def async_report_state(self, message, agent_user_id: str): """Send a state report to Google.""" data = { "requestId": uuid4().hex, "agentUserId": agent_user_id, "payload": message, } await self.async_call_homegraph_api(REPORT_STATE_BASE_URL, data)
[ "async", "def", "async_report_state", "(", "self", ",", "message", ",", "agent_user_id", ":", "str", ")", ":", "data", "=", "{", "\"requestId\"", ":", "uuid4", "(", ")", ".", "hex", ",", "\"agentUserId\"", ":", "agent_user_id", ",", "\"payload\"", ":", "message", ",", "}", "await", "self", ".", "async_call_homegraph_api", "(", "REPORT_STATE_BASE_URL", ",", "data", ")" ]
[ 220, 4 ]
[ 227, 72 ]
python
en
['en', 'en', 'en']
True
GoogleAssistantView.__init__
(self, config)
Initialize the Google Assistant request handler.
Initialize the Google Assistant request handler.
def __init__(self, config): """Initialize the Google Assistant request handler.""" self.config = config
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "self", ".", "config", "=", "config" ]
[ 237, 4 ]
[ 239, 28 ]
python
en
['en', 'en', 'en']
True
GoogleAssistantView.post
(self, request: Request)
Handle Google Assistant requests.
Handle Google Assistant requests.
async def post(self, request: Request) -> Response: """Handle Google Assistant requests.""" message: dict = await request.json() result = await async_handle_message( request.app["hass"], self.config, request["hass_user"].id, message, SOURCE_CLOUD, ) return self.json(result)
[ "async", "def", "post", "(", "self", ",", "request", ":", "Request", ")", "->", "Response", ":", "message", ":", "dict", "=", "await", "request", ".", "json", "(", ")", "result", "=", "await", "async_handle_message", "(", "request", ".", "app", "[", "\"hass\"", "]", ",", "self", ".", "config", ",", "request", "[", "\"hass_user\"", "]", ".", "id", ",", "message", ",", "SOURCE_CLOUD", ",", ")", "return", "self", ".", "json", "(", "result", ")" ]
[ 241, 4 ]
[ 251, 32 ]
python
en
['fr', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the OASA Telematics sensor.
Set up the OASA Telematics sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the OASA Telematics sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route_id = config.get(CONF_ROUTE_ID) data = OASATelematicsData(stop_id, route_id) add_entities([OASATelematicsSensor(data, stop_id, route_id, name)], True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "name", "=", "config", "[", "CONF_NAME", "]", "stop_id", "=", "config", "[", "CONF_STOP_ID", "]", "route_id", "=", "config", ".", "get", "(", "CONF_ROUTE_ID", ")", "data", "=", "OASATelematicsData", "(", "stop_id", ",", "route_id", ")", "add_entities", "(", "[", "OASATelematicsSensor", "(", "data", ",", "stop_id", ",", "route_id", ",", "name", ")", "]", ",", "True", ")" ]
[ 43, 0 ]
[ 51, 77 ]
python
en
['en', 'ca', 'en']
True
OASATelematicsSensor.__init__
(self, data, stop_id, route_id, name)
Initialize the sensor.
Initialize the sensor.
def __init__(self, data, stop_id, route_id, name): """Initialize the sensor.""" self.data = data self._name = name self._stop_id = stop_id self._route_id = route_id self._name_data = self._times = self._state = None
[ "def", "__init__", "(", "self", ",", "data", ",", "stop_id", ",", "route_id", ",", "name", ")", ":", "self", ".", "data", "=", "data", "self", ".", "_name", "=", "name", "self", ".", "_stop_id", "=", "stop_id", "self", ".", "_route_id", "=", "route_id", "self", ".", "_name_data", "=", "self", ".", "_times", "=", "self", ".", "_state", "=", "None" ]
[ 57, 4 ]
[ 63, 58 ]
python
en
['en', 'en', 'en']
True
OASATelematicsSensor.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" ]
[ 66, 4 ]
[ 68, 25 ]
python
en
['en', 'mi', 'en']
True
OASATelematicsSensor.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_TIMESTAMP" ]
[ 71, 4 ]
[ 73, 37 ]
python
en
['en', 'en', 'en']
True
OASATelematicsSensor.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" ]
[ 76, 4 ]
[ 78, 26 ]
python
en
['en', 'en', 'en']
True
OASATelematicsSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" params = {} if self._times is not None: next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: next_arrival = next_arrival_data[ATTR_NEXT_ARRIVAL] params.update({ATTR_NEXT_ARRIVAL: next_arrival.isoformat()}) if len(self._times) > 1: second_next_arrival_time = self._times[1][ATTR_NEXT_ARRIVAL] if second_next_arrival_time is not None: second_arrival = second_next_arrival_time params.update( {ATTR_SECOND_NEXT_ARRIVAL: second_arrival.isoformat()} ) params.update( { ATTR_ROUTE_ID: self._times[0][ATTR_ROUTE_ID], ATTR_STOP_ID: self._stop_id, ATTR_ATTRIBUTION: ATTRIBUTION, } ) params.update( { ATTR_ROUTE_NAME: self._name_data[ATTR_ROUTE_NAME], ATTR_STOP_NAME: self._name_data[ATTR_STOP_NAME], } ) return {k: v for k, v in params.items() if v}
[ "def", "device_state_attributes", "(", "self", ")", ":", "params", "=", "{", "}", "if", "self", ".", "_times", "is", "not", "None", ":", "next_arrival_data", "=", "self", ".", "_times", "[", "0", "]", "if", "ATTR_NEXT_ARRIVAL", "in", "next_arrival_data", ":", "next_arrival", "=", "next_arrival_data", "[", "ATTR_NEXT_ARRIVAL", "]", "params", ".", "update", "(", "{", "ATTR_NEXT_ARRIVAL", ":", "next_arrival", ".", "isoformat", "(", ")", "}", ")", "if", "len", "(", "self", ".", "_times", ")", ">", "1", ":", "second_next_arrival_time", "=", "self", ".", "_times", "[", "1", "]", "[", "ATTR_NEXT_ARRIVAL", "]", "if", "second_next_arrival_time", "is", "not", "None", ":", "second_arrival", "=", "second_next_arrival_time", "params", ".", "update", "(", "{", "ATTR_SECOND_NEXT_ARRIVAL", ":", "second_arrival", ".", "isoformat", "(", ")", "}", ")", "params", ".", "update", "(", "{", "ATTR_ROUTE_ID", ":", "self", ".", "_times", "[", "0", "]", "[", "ATTR_ROUTE_ID", "]", ",", "ATTR_STOP_ID", ":", "self", ".", "_stop_id", ",", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "}", ")", "params", ".", "update", "(", "{", "ATTR_ROUTE_NAME", ":", "self", ".", "_name_data", "[", "ATTR_ROUTE_NAME", "]", ",", "ATTR_STOP_NAME", ":", "self", ".", "_name_data", "[", "ATTR_STOP_NAME", "]", ",", "}", ")", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", "if", "v", "}" ]
[ 81, 4 ]
[ 109, 53 ]
python
en
['en', 'en', 'en']
True
OASATelematicsSensor.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 ICON
[ "def", "icon", "(", "self", ")", ":", "return", "ICON" ]
[ 112, 4 ]
[ 114, 19 ]
python
en
['en', 'en', 'en']
True
OASATelematicsSensor.update
(self)
Get the latest data from OASA API and update the states.
Get the latest data from OASA API and update the states.
def update(self): """Get the latest data from OASA API and update the states.""" self.data.update() self._times = self.data.info self._name_data = self.data.name_data next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: self._state = next_arrival_data[ATTR_NEXT_ARRIVAL].isoformat()
[ "def", "update", "(", "self", ")", ":", "self", ".", "data", ".", "update", "(", ")", "self", ".", "_times", "=", "self", ".", "data", ".", "info", "self", ".", "_name_data", "=", "self", ".", "data", ".", "name_data", "next_arrival_data", "=", "self", ".", "_times", "[", "0", "]", "if", "ATTR_NEXT_ARRIVAL", "in", "next_arrival_data", ":", "self", ".", "_state", "=", "next_arrival_data", "[", "ATTR_NEXT_ARRIVAL", "]", ".", "isoformat", "(", ")" ]
[ 116, 4 ]
[ 123, 74 ]
python
en
['en', 'en', 'en']
True
OASATelematicsData.__init__
(self, stop_id, route_id)
Initialize the data object.
Initialize the data object.
def __init__(self, stop_id, route_id): """Initialize the data object.""" self.stop_id = stop_id self.route_id = route_id self.info = self.empty_result() self.oasa_api = oasatelematics self.name_data = { ATTR_ROUTE_NAME: self.get_route_name(), ATTR_STOP_NAME: self.get_stop_name(), }
[ "def", "__init__", "(", "self", ",", "stop_id", ",", "route_id", ")", ":", "self", ".", "stop_id", "=", "stop_id", "self", ".", "route_id", "=", "route_id", "self", ".", "info", "=", "self", ".", "empty_result", "(", ")", "self", ".", "oasa_api", "=", "oasatelematics", "self", ".", "name_data", "=", "{", "ATTR_ROUTE_NAME", ":", "self", ".", "get_route_name", "(", ")", ",", "ATTR_STOP_NAME", ":", "self", ".", "get_stop_name", "(", ")", ",", "}" ]
[ 129, 4 ]
[ 138, 9 ]
python
en
['en', 'en', 'en']
True
OASATelematicsData.empty_result
(self)
Object returned when no arrivals are found.
Object returned when no arrivals are found.
def empty_result(self): """Object returned when no arrivals are found.""" return [{ATTR_ROUTE_ID: self.route_id}]
[ "def", "empty_result", "(", "self", ")", ":", "return", "[", "{", "ATTR_ROUTE_ID", ":", "self", ".", "route_id", "}", "]" ]
[ 140, 4 ]
[ 142, 47 ]
python
en
['en', 'en', 'en']
True
OASATelematicsData.get_route_name
(self)
Get the route name from the API.
Get the route name from the API.
def get_route_name(self): """Get the route name from the API.""" try: route = self.oasa_api.getRouteName(self.route_id) if route: return route[0].get("route_departure_eng") except TypeError: _LOGGER.error("Cannot get route name from OASA API") return None
[ "def", "get_route_name", "(", "self", ")", ":", "try", ":", "route", "=", "self", ".", "oasa_api", ".", "getRouteName", "(", "self", ".", "route_id", ")", "if", "route", ":", "return", "route", "[", "0", "]", ".", "get", "(", "\"route_departure_eng\"", ")", "except", "TypeError", ":", "_LOGGER", ".", "error", "(", "\"Cannot get route name from OASA API\"", ")", "return", "None" ]
[ 144, 4 ]
[ 152, 19 ]
python
en
['en', 'en', 'en']
True
OASATelematicsData.get_stop_name
(self)
Get the stop name from the API.
Get the stop name from the API.
def get_stop_name(self): """Get the stop name from the API.""" try: name_data = self.oasa_api.getStopNameAndXY(self.stop_id) if name_data: return name_data[0].get("stop_descr_matrix_eng") except TypeError: _LOGGER.error("Cannot get stop name from OASA API") return None
[ "def", "get_stop_name", "(", "self", ")", ":", "try", ":", "name_data", "=", "self", ".", "oasa_api", ".", "getStopNameAndXY", "(", "self", ".", "stop_id", ")", "if", "name_data", ":", "return", "name_data", "[", "0", "]", ".", "get", "(", "\"stop_descr_matrix_eng\"", ")", "except", "TypeError", ":", "_LOGGER", ".", "error", "(", "\"Cannot get stop name from OASA API\"", ")", "return", "None" ]
[ 154, 4 ]
[ 162, 19 ]
python
en
['en', 'en', 'en']
True
OASATelematicsData.update
(self)
Get the latest arrival data from telematics.oasa.gr API.
Get the latest arrival data from telematics.oasa.gr API.
def update(self): """Get the latest arrival data from telematics.oasa.gr API.""" self.info = [] results = self.oasa_api.getStopArrivals(self.stop_id) if not results: self.info = self.empty_result() return # Parse results results = [r for r in results if r.get("route_code") in self.route_id] current_time = dt_util.utcnow() for result in results: btime2 = result.get("btime2") if btime2 is not None: arrival_min = int(btime2) timestamp = current_time + timedelta(minutes=arrival_min) arrival_data = { ATTR_NEXT_ARRIVAL: timestamp, ATTR_ROUTE_ID: self.route_id, } self.info.append(arrival_data) if not self.info: _LOGGER.debug("No arrivals with given parameters") self.info = self.empty_result() return # Sort the data by time sort = sorted(self.info, key=itemgetter(ATTR_NEXT_ARRIVAL)) self.info = sort
[ "def", "update", "(", "self", ")", ":", "self", ".", "info", "=", "[", "]", "results", "=", "self", ".", "oasa_api", ".", "getStopArrivals", "(", "self", ".", "stop_id", ")", "if", "not", "results", ":", "self", ".", "info", "=", "self", ".", "empty_result", "(", ")", "return", "# Parse results", "results", "=", "[", "r", "for", "r", "in", "results", "if", "r", ".", "get", "(", "\"route_code\"", ")", "in", "self", ".", "route_id", "]", "current_time", "=", "dt_util", ".", "utcnow", "(", ")", "for", "result", "in", "results", ":", "btime2", "=", "result", ".", "get", "(", "\"btime2\"", ")", "if", "btime2", "is", "not", "None", ":", "arrival_min", "=", "int", "(", "btime2", ")", "timestamp", "=", "current_time", "+", "timedelta", "(", "minutes", "=", "arrival_min", ")", "arrival_data", "=", "{", "ATTR_NEXT_ARRIVAL", ":", "timestamp", ",", "ATTR_ROUTE_ID", ":", "self", ".", "route_id", ",", "}", "self", ".", "info", ".", "append", "(", "arrival_data", ")", "if", "not", "self", ".", "info", ":", "_LOGGER", ".", "debug", "(", "\"No arrivals with given parameters\"", ")", "self", ".", "info", "=", "self", ".", "empty_result", "(", ")", "return", "# Sort the data by time", "sort", "=", "sorted", "(", "self", ".", "info", ",", "key", "=", "itemgetter", "(", "ATTR_NEXT_ARRIVAL", ")", ")", "self", ".", "info", "=", "sort" ]
[ 164, 4 ]
[ 196, 24 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Flux lights.
Set up the Flux lights.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Flux lights.""" lights = [] light_ips = [] for ipaddr, device_config in config.get(CONF_DEVICES, {}).items(): device = {} device["name"] = device_config[CONF_NAME] device["ipaddr"] = ipaddr device[CONF_PROTOCOL] = device_config.get(CONF_PROTOCOL) device[ATTR_MODE] = device_config[ATTR_MODE] device[CONF_CUSTOM_EFFECT] = device_config.get(CONF_CUSTOM_EFFECT) light = FluxLight(device) lights.append(light) light_ips.append(ipaddr) if not config.get(CONF_AUTOMATIC_ADD, False): add_entities(lights, True) return # Find the bulbs on the LAN scanner = BulbScanner() scanner.scan(timeout=10) for device in scanner.getBulbInfo(): ipaddr = device["ipaddr"] if ipaddr in light_ips: continue device["name"] = f"{device['id']} {ipaddr}" device[ATTR_MODE] = None device[CONF_PROTOCOL] = None device[CONF_CUSTOM_EFFECT] = None light = FluxLight(device) lights.append(light) add_entities(lights, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "lights", "=", "[", "]", "light_ips", "=", "[", "]", "for", "ipaddr", ",", "device_config", "in", "config", ".", "get", "(", "CONF_DEVICES", ",", "{", "}", ")", ".", "items", "(", ")", ":", "device", "=", "{", "}", "device", "[", "\"name\"", "]", "=", "device_config", "[", "CONF_NAME", "]", "device", "[", "\"ipaddr\"", "]", "=", "ipaddr", "device", "[", "CONF_PROTOCOL", "]", "=", "device_config", ".", "get", "(", "CONF_PROTOCOL", ")", "device", "[", "ATTR_MODE", "]", "=", "device_config", "[", "ATTR_MODE", "]", "device", "[", "CONF_CUSTOM_EFFECT", "]", "=", "device_config", ".", "get", "(", "CONF_CUSTOM_EFFECT", ")", "light", "=", "FluxLight", "(", "device", ")", "lights", ".", "append", "(", "light", ")", "light_ips", ".", "append", "(", "ipaddr", ")", "if", "not", "config", ".", "get", "(", "CONF_AUTOMATIC_ADD", ",", "False", ")", ":", "add_entities", "(", "lights", ",", "True", ")", "return", "# Find the bulbs on the LAN", "scanner", "=", "BulbScanner", "(", ")", "scanner", ".", "scan", "(", "timeout", "=", "10", ")", "for", "device", "in", "scanner", ".", "getBulbInfo", "(", ")", ":", "ipaddr", "=", "device", "[", "\"ipaddr\"", "]", "if", "ipaddr", "in", "light_ips", ":", "continue", "device", "[", "\"name\"", "]", "=", "f\"{device['id']} {ipaddr}\"", "device", "[", "ATTR_MODE", "]", "=", "None", "device", "[", "CONF_PROTOCOL", "]", "=", "None", "device", "[", "CONF_CUSTOM_EFFECT", "]", "=", "None", "light", "=", "FluxLight", "(", "device", ")", "lights", ".", "append", "(", "light", ")", "add_entities", "(", "lights", ",", "True", ")" ]
[ 141, 0 ]
[ 175, 30 ]
python
en
['en', 'da', 'en']
True
FluxLight.__init__
(self, device)
Initialize the light.
Initialize the light.
def __init__(self, device): """Initialize the light.""" self._name = device["name"] self._ipaddr = device["ipaddr"] self._protocol = device[CONF_PROTOCOL] self._mode = device[ATTR_MODE] self._custom_effect = device[CONF_CUSTOM_EFFECT] self._bulb = None self._error_reported = False
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "self", ".", "_name", "=", "device", "[", "\"name\"", "]", "self", ".", "_ipaddr", "=", "device", "[", "\"ipaddr\"", "]", "self", ".", "_protocol", "=", "device", "[", "CONF_PROTOCOL", "]", "self", ".", "_mode", "=", "device", "[", "ATTR_MODE", "]", "self", ".", "_custom_effect", "=", "device", "[", "CONF_CUSTOM_EFFECT", "]", "self", ".", "_bulb", "=", "None", "self", ".", "_error_reported", "=", "False" ]
[ 181, 4 ]
[ 189, 36 ]
python
en
['en', 'en', 'en']
True
FluxLight._connect
(self)
Connect to Flux light.
Connect to Flux light.
def _connect(self): """Connect to Flux light.""" self._bulb = WifiLedBulb(self._ipaddr, timeout=5) if self._protocol: self._bulb.setProtocol(self._protocol) # After bulb object is created the status is updated. We can # now set the correct mode if it was not explicitly defined. if not self._mode: if self._bulb.rgbwcapable: self._mode = MODE_RGBW else: self._mode = MODE_RGB
[ "def", "_connect", "(", "self", ")", ":", "self", ".", "_bulb", "=", "WifiLedBulb", "(", "self", ".", "_ipaddr", ",", "timeout", "=", "5", ")", "if", "self", ".", "_protocol", ":", "self", ".", "_bulb", ".", "setProtocol", "(", "self", ".", "_protocol", ")", "# After bulb object is created the status is updated. We can", "# now set the correct mode if it was not explicitly defined.", "if", "not", "self", ".", "_mode", ":", "if", "self", ".", "_bulb", ".", "rgbwcapable", ":", "self", ".", "_mode", "=", "MODE_RGBW", "else", ":", "self", ".", "_mode", "=", "MODE_RGB" ]
[ 191, 4 ]
[ 204, 37 ]
python
en
['en', 'en', 'en']
True
FluxLight._disconnect
(self)
Disconnect from Flux light.
Disconnect from Flux light.
def _disconnect(self): """Disconnect from Flux light.""" self._bulb = None
[ "def", "_disconnect", "(", "self", ")", ":", "self", ".", "_bulb", "=", "None" ]
[ 206, 4 ]
[ 208, 25 ]
python
en
['en', 'en', 'en']
True
FluxLight.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._bulb is not None
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_bulb", "is", "not", "None" ]
[ 211, 4 ]
[ 213, 37 ]
python
en
['en', 'en', 'en']
True
FluxLight.name
(self)
Return the name of the device if any.
Return the name of the device if any.
def name(self): """Return the name of the device if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 216, 4 ]
[ 218, 25 ]
python
en
['en', 'en', 'en']
True
FluxLight.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._bulb.isOn()
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_bulb", ".", "isOn", "(", ")" ]
[ 221, 4 ]
[ 223, 32 ]
python
en
['en', 'fy', 'en']
True
FluxLight.brightness
(self)
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
def brightness(self): """Return the brightness of this light between 0..255.""" if self._mode == MODE_WHITE: return self.white_value return self._bulb.brightness
[ "def", "brightness", "(", "self", ")", ":", "if", "self", ".", "_mode", "==", "MODE_WHITE", ":", "return", "self", ".", "white_value", "return", "self", ".", "_bulb", ".", "brightness" ]
[ 226, 4 ]
[ 231, 36 ]
python
en
['en', 'en', 'en']
True
FluxLight.hs_color
(self)
Return the color property.
Return the color property.
def hs_color(self): """Return the color property.""" return color_util.color_RGB_to_hs(*self._bulb.getRgb())
[ "def", "hs_color", "(", "self", ")", ":", "return", "color_util", ".", "color_RGB_to_hs", "(", "*", "self", ".", "_bulb", ".", "getRgb", "(", ")", ")" ]
[ 234, 4 ]
[ 236, 63 ]
python
en
['en', 'en', 'en']
True
FluxLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" if self._mode == MODE_RGBW: return SUPPORT_FLUX_LED | SUPPORT_WHITE_VALUE | SUPPORT_COLOR_TEMP if self._mode == MODE_WHITE: return SUPPORT_BRIGHTNESS return SUPPORT_FLUX_LED
[ "def", "supported_features", "(", "self", ")", ":", "if", "self", ".", "_mode", "==", "MODE_RGBW", ":", "return", "SUPPORT_FLUX_LED", "|", "SUPPORT_WHITE_VALUE", "|", "SUPPORT_COLOR_TEMP", "if", "self", ".", "_mode", "==", "MODE_WHITE", ":", "return", "SUPPORT_BRIGHTNESS", "return", "SUPPORT_FLUX_LED" ]
[ 239, 4 ]
[ 247, 31 ]
python
en
['da', 'en', 'en']
True
FluxLight.white_value
(self)
Return the white value of this light between 0..255.
Return the white value of this light between 0..255.
def white_value(self): """Return the white value of this light between 0..255.""" return self._bulb.getRgbw()[3]
[ "def", "white_value", "(", "self", ")", ":", "return", "self", ".", "_bulb", ".", "getRgbw", "(", ")", "[", "3", "]" ]
[ 250, 4 ]
[ 252, 38 ]
python
en
['en', 'en', 'en']
True
FluxLight.effect_list
(self)
Return the list of supported effects.
Return the list of supported effects.
def effect_list(self): """Return the list of supported effects.""" if self._custom_effect: return FLUX_EFFECT_LIST + [EFFECT_CUSTOM] return FLUX_EFFECT_LIST
[ "def", "effect_list", "(", "self", ")", ":", "if", "self", ".", "_custom_effect", ":", "return", "FLUX_EFFECT_LIST", "+", "[", "EFFECT_CUSTOM", "]", "return", "FLUX_EFFECT_LIST" ]
[ 255, 4 ]
[ 260, 31 ]
python
en
['en', 'en', 'en']
True
FluxLight.effect
(self)
Return the current effect.
Return the current effect.
def effect(self): """Return the current effect.""" current_mode = self._bulb.raw_state[3] if current_mode == EFFECT_CUSTOM_CODE: return EFFECT_CUSTOM for effect, code in EFFECT_MAP.items(): if current_mode == code: return effect return None
[ "def", "effect", "(", "self", ")", ":", "current_mode", "=", "self", ".", "_bulb", ".", "raw_state", "[", "3", "]", "if", "current_mode", "==", "EFFECT_CUSTOM_CODE", ":", "return", "EFFECT_CUSTOM", "for", "effect", ",", "code", "in", "EFFECT_MAP", ".", "items", "(", ")", ":", "if", "current_mode", "==", "code", ":", "return", "effect", "return", "None" ]
[ 263, 4 ]
[ 274, 19 ]
python
en
['en', 'en', 'en']
True
FluxLight.turn_on
(self, **kwargs)
Turn the specified or all lights on.
Turn the specified or all lights on.
def turn_on(self, **kwargs): """Turn the specified or all lights on.""" if not self.is_on: self._bulb.turnOn() hs_color = kwargs.get(ATTR_HS_COLOR) if hs_color: rgb = color_util.color_hs_to_RGB(*hs_color) else: rgb = None brightness = kwargs.get(ATTR_BRIGHTNESS) effect = kwargs.get(ATTR_EFFECT) white = kwargs.get(ATTR_WHITE_VALUE) color_temp = kwargs.get(ATTR_COLOR_TEMP) # handle special modes if color_temp is not None: if brightness is None: brightness = self.brightness if color_temp > COLOR_TEMP_WARM_VS_COLD_WHITE_CUT_OFF: self._bulb.setRgbw(w=brightness) else: self._bulb.setRgbw(w2=brightness) return # Show warning if effect set with rgb, brightness, or white level if effect and (brightness or white or rgb): _LOGGER.warning( "RGB, brightness and white level are ignored when" " an effect is specified for a flux bulb" ) # Random color effect if effect == EFFECT_RANDOM: self._bulb.setRgb( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) ) return if effect == EFFECT_CUSTOM: if self._custom_effect: self._bulb.setCustomPattern( self._custom_effect[CONF_COLORS], self._custom_effect[CONF_SPEED_PCT], self._custom_effect[CONF_TRANSITION], ) return # Effect selection if effect in EFFECT_MAP: self._bulb.setPresetPattern(EFFECT_MAP[effect], 50) return # Preserve current brightness on color/white level change if brightness is None: brightness = self.brightness # Preserve color on brightness/white level change if rgb is None: rgb = self._bulb.getRgb() if white is None and self._mode == MODE_RGBW: white = self.white_value # handle W only mode (use brightness instead of white value) if self._mode == MODE_WHITE: self._bulb.setRgbw(0, 0, 0, w=brightness) # handle RGBW mode elif self._mode == MODE_RGBW: self._bulb.setRgbw(*tuple(rgb), w=white, brightness=brightness) # handle RGB mode else: self._bulb.setRgb(*tuple(rgb), brightness=brightness)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_on", ":", "self", ".", "_bulb", ".", "turnOn", "(", ")", "hs_color", "=", "kwargs", ".", "get", "(", "ATTR_HS_COLOR", ")", "if", "hs_color", ":", "rgb", "=", "color_util", ".", "color_hs_to_RGB", "(", "*", "hs_color", ")", "else", ":", "rgb", "=", "None", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ")", "effect", "=", "kwargs", ".", "get", "(", "ATTR_EFFECT", ")", "white", "=", "kwargs", ".", "get", "(", "ATTR_WHITE_VALUE", ")", "color_temp", "=", "kwargs", ".", "get", "(", "ATTR_COLOR_TEMP", ")", "# handle special modes", "if", "color_temp", "is", "not", "None", ":", "if", "brightness", "is", "None", ":", "brightness", "=", "self", ".", "brightness", "if", "color_temp", ">", "COLOR_TEMP_WARM_VS_COLD_WHITE_CUT_OFF", ":", "self", ".", "_bulb", ".", "setRgbw", "(", "w", "=", "brightness", ")", "else", ":", "self", ".", "_bulb", ".", "setRgbw", "(", "w2", "=", "brightness", ")", "return", "# Show warning if effect set with rgb, brightness, or white level", "if", "effect", "and", "(", "brightness", "or", "white", "or", "rgb", ")", ":", "_LOGGER", ".", "warning", "(", "\"RGB, brightness and white level are ignored when\"", "\" an effect is specified for a flux bulb\"", ")", "# Random color effect", "if", "effect", "==", "EFFECT_RANDOM", ":", "self", ".", "_bulb", ".", "setRgb", "(", "random", ".", "randint", "(", "0", ",", "255", ")", ",", "random", ".", "randint", "(", "0", ",", "255", ")", ",", "random", ".", "randint", "(", "0", ",", "255", ")", ")", "return", "if", "effect", "==", "EFFECT_CUSTOM", ":", "if", "self", ".", "_custom_effect", ":", "self", ".", "_bulb", ".", "setCustomPattern", "(", "self", ".", "_custom_effect", "[", "CONF_COLORS", "]", ",", "self", ".", "_custom_effect", "[", "CONF_SPEED_PCT", "]", ",", "self", ".", "_custom_effect", "[", "CONF_TRANSITION", "]", ",", ")", "return", "# Effect selection", "if", "effect", "in", "EFFECT_MAP", ":", "self", ".", "_bulb", ".", "setPresetPattern", "(", "EFFECT_MAP", "[", "effect", "]", ",", "50", ")", "return", "# Preserve current brightness on color/white level change", "if", "brightness", "is", "None", ":", "brightness", "=", "self", ".", "brightness", "# Preserve color on brightness/white level change", "if", "rgb", "is", "None", ":", "rgb", "=", "self", ".", "_bulb", ".", "getRgb", "(", ")", "if", "white", "is", "None", "and", "self", ".", "_mode", "==", "MODE_RGBW", ":", "white", "=", "self", ".", "white_value", "# handle W only mode (use brightness instead of white value)", "if", "self", ".", "_mode", "==", "MODE_WHITE", ":", "self", ".", "_bulb", ".", "setRgbw", "(", "0", ",", "0", ",", "0", ",", "w", "=", "brightness", ")", "# handle RGBW mode", "elif", "self", ".", "_mode", "==", "MODE_RGBW", ":", "self", ".", "_bulb", ".", "setRgbw", "(", "*", "tuple", "(", "rgb", ")", ",", "w", "=", "white", ",", "brightness", "=", "brightness", ")", "# handle RGB mode", "else", ":", "self", ".", "_bulb", ".", "setRgb", "(", "*", "tuple", "(", "rgb", ")", ",", "brightness", "=", "brightness", ")" ]
[ 276, 4 ]
[ 352, 65 ]
python
en
['en', 'en', 'en']
True
FluxLight.turn_off
(self, **kwargs)
Turn the specified or all lights off.
Turn the specified or all lights off.
def turn_off(self, **kwargs): """Turn the specified or all lights off.""" self._bulb.turnOff()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_bulb", ".", "turnOff", "(", ")" ]
[ 354, 4 ]
[ 356, 28 ]
python
en
['en', 'en', 'en']
True
FluxLight.update
(self)
Synchronize state with bulb.
Synchronize state with bulb.
def update(self): """Synchronize state with bulb.""" if not self.available: try: self._connect() self._error_reported = False except OSError: self._disconnect() if not self._error_reported: _LOGGER.warning( "Failed to connect to bulb %s, %s", self._ipaddr, self._name ) self._error_reported = True return self._bulb.update_state(retry=2)
[ "def", "update", "(", "self", ")", ":", "if", "not", "self", ".", "available", ":", "try", ":", "self", ".", "_connect", "(", ")", "self", ".", "_error_reported", "=", "False", "except", "OSError", ":", "self", ".", "_disconnect", "(", ")", "if", "not", "self", ".", "_error_reported", ":", "_LOGGER", ".", "warning", "(", "\"Failed to connect to bulb %s, %s\"", ",", "self", ".", "_ipaddr", ",", "self", ".", "_name", ")", "self", ".", "_error_reported", "=", "True", "return", "self", ".", "_bulb", ".", "update_state", "(", "retry", "=", "2", ")" ]
[ 358, 4 ]
[ 373, 40 ]
python
en
['en', 'en', 'en']
True
test_show_user_form
(hass: HomeAssistant)
Test that the user set up form is served.
Test that the user set up form is served.
async def test_show_user_form(hass: HomeAssistant) -> None: """Test that the user set up form is served.""" result = await hass.config_entries.flow.async_init( config_flow.DOMAIN, context={"source": SOURCE_USER}, ) assert result["step_id"] == "user" assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
[ "async", "def", "test_show_user_form", "(", "hass", ":", "HomeAssistant", ")", "->", "None", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "config_flow", ".", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM" ]
[ 16, 0 ]
[ 24, 61 ]
python
en
['en', 'en', 'en']
True
test_connection_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we show user form on BSBLan connection error.
Test we show user form on BSBLan connection error.
async def test_connection_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we show user form on BSBLan connection error.""" aioclient_mock.post( "http://example.local:80/1234/JQ?Parameter=6224,6225,6226", exc=aiohttp.ClientError, ) result = await hass.config_entries.flow.async_init( config_flow.DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "example.local", CONF_PASSKEY: "1234", CONF_PORT: 80}, ) assert result["errors"] == {"base": "cannot_connect"} assert result["step_id"] == "user" assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
[ "async", "def", "test_connection_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "aioclient_mock", ".", "post", "(", "\"http://example.local:80/1234/JQ?Parameter=6224,6225,6226\"", ",", "exc", "=", "aiohttp", ".", "ClientError", ",", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "config_flow", ".", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", "data", "=", "{", "CONF_HOST", ":", "\"example.local\"", ",", "CONF_PASSKEY", ":", "\"1234\"", ",", "CONF_PORT", ":", "80", "}", ",", ")", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM" ]
[ 27, 0 ]
[ 44, 61 ]
python
en
['en', 'en', 'en']
True
test_user_device_exists_abort
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort zeroconf flow if BSBLan device already configured.
Test we abort zeroconf flow if BSBLan device already configured.
async def test_user_device_exists_abort( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort zeroconf flow if BSBLan device already configured.""" await init_integration(hass, aioclient_mock) result = await hass.config_entries.flow.async_init( config_flow.DOMAIN, context={"source": SOURCE_USER}, data={CONF_HOST: "example.local", CONF_PASSKEY: "1234", CONF_PORT: 80}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
[ "async", "def", "test_user_device_exists_abort", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "await", "init_integration", "(", "hass", ",", "aioclient_mock", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "config_flow", ".", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", "data", "=", "{", "CONF_HOST", ":", "\"example.local\"", ",", "CONF_PASSKEY", ":", "\"1234\"", ",", "CONF_PORT", ":", "80", "}", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT" ]
[ 47, 0 ]
[ 59, 62 ]
python
de
['nl', 'de', 'en']
False
test_full_user_flow_implementation
( hass: HomeAssistant, aioclient_mock )
Test the full manual user flow from start to finish.
Test the full manual user flow from start to finish.
async def test_full_user_flow_implementation( hass: HomeAssistant, aioclient_mock ) -> None: """Test the full manual user flow from start to finish.""" aioclient_mock.post( "http://example.local:80/1234/JQ?Parameter=6224,6225,6226", text=load_fixture("bsblan/info.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) result = await hass.config_entries.flow.async_init( config_flow.DOMAIN, context={"source": SOURCE_USER}, ) assert result["step_id"] == "user" assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_HOST: "example.local", CONF_PASSKEY: "1234", CONF_PORT: 80}, ) assert result["data"][CONF_HOST] == "example.local" assert result["data"][CONF_PASSKEY] == "1234" assert result["data"][CONF_PORT] == 80 assert result["data"][CONF_DEVICE_IDENT] == "RVS21.831F/127" assert result["title"] == "RVS21.831F/127" assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY entries = hass.config_entries.async_entries(config_flow.DOMAIN) assert entries[0].unique_id == "RVS21.831F/127"
[ "async", "def", "test_full_user_flow_implementation", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ")", "->", "None", ":", "aioclient_mock", ".", "post", "(", "\"http://example.local:80/1234/JQ?Parameter=6224,6225,6226\"", ",", "text", "=", "load_fixture", "(", "\"bsblan/info.json\"", ")", ",", "headers", "=", "{", "\"Content-Type\"", ":", "CONTENT_TYPE_JSON", "}", ",", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "config_flow", ".", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "user_input", "=", "{", "CONF_HOST", ":", "\"example.local\"", ",", "CONF_PASSKEY", ":", "\"1234\"", ",", "CONF_PORT", ":", "80", "}", ",", ")", "assert", "result", "[", "\"data\"", "]", "[", "CONF_HOST", "]", "==", "\"example.local\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_PASSKEY", "]", "==", "\"1234\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_PORT", "]", "==", "80", "assert", "result", "[", "\"data\"", "]", "[", "CONF_DEVICE_IDENT", "]", "==", "\"RVS21.831F/127\"", "assert", "result", "[", "\"title\"", "]", "==", "\"RVS21.831F/127\"", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "entries", "=", "hass", ".", "config_entries", ".", "async_entries", "(", "config_flow", ".", "DOMAIN", ")", "assert", "entries", "[", "0", "]", ".", "unique_id", "==", "\"RVS21.831F/127\"" ]
[ 62, 0 ]
[ 93, 51 ]
python
en
['en', 'en', 'en']
True
build_item_response
(entity, player, payload)
Create response payload for search described by payload.
Create response payload for search described by payload.
async def build_item_response(entity, player, payload): """Create response payload for search described by payload.""" internal_request = is_internal_request(entity.hass) search_id = payload["search_id"] search_type = payload["search_type"] media_class = CONTENT_TYPE_MEDIA_CLASS[search_type] if search_id and search_id != search_type: browse_id = (SQUEEZEBOX_ID_BY_TYPE[search_type], search_id) else: browse_id = None result = await player.async_browse( MEDIA_TYPE_TO_SQUEEZEBOX[search_type], limit=BROWSE_LIMIT, browse_id=browse_id, ) children = None if result is not None and result.get("items"): item_type = CONTENT_TYPE_TO_CHILD_TYPE[search_type] child_media_class = CONTENT_TYPE_MEDIA_CLASS[item_type] children = [] for item in result["items"]: item_id = str(item["id"]) item_thumbnail = None artwork_track_id = item.get("artwork_track_id") if artwork_track_id: if internal_request: item_thumbnail = player.generate_image_url_from_track_id( artwork_track_id ) else: item_thumbnail = entity.get_browse_image_url( item_type, item_id, artwork_track_id ) children.append( BrowseMedia( title=item["title"], media_class=child_media_class["item"], media_content_id=item_id, media_content_type=item_type, can_play=True, can_expand=child_media_class["children"] is not None, thumbnail=item_thumbnail, ) ) if children is None: raise BrowseError(f"Media not found: {search_type} / {search_id}") return BrowseMedia( title=result.get("title"), media_class=media_class["item"], children_media_class=media_class["children"], media_content_id=search_id, media_content_type=search_type, can_play=True, children=children, can_expand=True, )
[ "async", "def", "build_item_response", "(", "entity", ",", "player", ",", "payload", ")", ":", "internal_request", "=", "is_internal_request", "(", "entity", ".", "hass", ")", "search_id", "=", "payload", "[", "\"search_id\"", "]", "search_type", "=", "payload", "[", "\"search_type\"", "]", "media_class", "=", "CONTENT_TYPE_MEDIA_CLASS", "[", "search_type", "]", "if", "search_id", "and", "search_id", "!=", "search_type", ":", "browse_id", "=", "(", "SQUEEZEBOX_ID_BY_TYPE", "[", "search_type", "]", ",", "search_id", ")", "else", ":", "browse_id", "=", "None", "result", "=", "await", "player", ".", "async_browse", "(", "MEDIA_TYPE_TO_SQUEEZEBOX", "[", "search_type", "]", ",", "limit", "=", "BROWSE_LIMIT", ",", "browse_id", "=", "browse_id", ",", ")", "children", "=", "None", "if", "result", "is", "not", "None", "and", "result", ".", "get", "(", "\"items\"", ")", ":", "item_type", "=", "CONTENT_TYPE_TO_CHILD_TYPE", "[", "search_type", "]", "child_media_class", "=", "CONTENT_TYPE_MEDIA_CLASS", "[", "item_type", "]", "children", "=", "[", "]", "for", "item", "in", "result", "[", "\"items\"", "]", ":", "item_id", "=", "str", "(", "item", "[", "\"id\"", "]", ")", "item_thumbnail", "=", "None", "artwork_track_id", "=", "item", ".", "get", "(", "\"artwork_track_id\"", ")", "if", "artwork_track_id", ":", "if", "internal_request", ":", "item_thumbnail", "=", "player", ".", "generate_image_url_from_track_id", "(", "artwork_track_id", ")", "else", ":", "item_thumbnail", "=", "entity", ".", "get_browse_image_url", "(", "item_type", ",", "item_id", ",", "artwork_track_id", ")", "children", ".", "append", "(", "BrowseMedia", "(", "title", "=", "item", "[", "\"title\"", "]", ",", "media_class", "=", "child_media_class", "[", "\"item\"", "]", ",", "media_content_id", "=", "item_id", ",", "media_content_type", "=", "item_type", ",", "can_play", "=", "True", ",", "can_expand", "=", "child_media_class", "[", "\"children\"", "]", "is", "not", "None", ",", "thumbnail", "=", "item_thumbnail", ",", ")", ")", "if", "children", "is", "None", ":", "raise", "BrowseError", "(", "f\"Media not found: {search_type} / {search_id}\"", ")", "return", "BrowseMedia", "(", "title", "=", "result", ".", "get", "(", "\"title\"", ")", ",", "media_class", "=", "media_class", "[", "\"item\"", "]", ",", "children_media_class", "=", "media_class", "[", "\"children\"", "]", ",", "media_content_id", "=", "search_id", ",", "media_content_type", "=", "search_type", ",", "can_play", "=", "True", ",", "children", "=", "children", ",", "can_expand", "=", "True", ",", ")" ]
[ 68, 0 ]
[ 134, 5 ]
python
en
['en', 'en', 'en']
True
library_payload
(player)
Create response payload to describe contents of library.
Create response payload to describe contents of library.
async def library_payload(player): """Create response payload to describe contents of library.""" library_info = { "title": "Music Library", "media_class": MEDIA_CLASS_DIRECTORY, "media_content_id": "library", "media_content_type": "library", "can_play": False, "can_expand": True, "children": [], } for item in LIBRARY: media_class = CONTENT_TYPE_MEDIA_CLASS[item] result = await player.async_browse( MEDIA_TYPE_TO_SQUEEZEBOX[item], limit=1, ) if result is not None and result.get("items") is not None: library_info["children"].append( BrowseMedia( title=item, media_class=media_class["children"], media_content_id=item, media_content_type=item, can_play=True, can_expand=True, ) ) response = BrowseMedia(**library_info) return response
[ "async", "def", "library_payload", "(", "player", ")", ":", "library_info", "=", "{", "\"title\"", ":", "\"Music Library\"", ",", "\"media_class\"", ":", "MEDIA_CLASS_DIRECTORY", ",", "\"media_content_id\"", ":", "\"library\"", ",", "\"media_content_type\"", ":", "\"library\"", ",", "\"can_play\"", ":", "False", ",", "\"can_expand\"", ":", "True", ",", "\"children\"", ":", "[", "]", ",", "}", "for", "item", "in", "LIBRARY", ":", "media_class", "=", "CONTENT_TYPE_MEDIA_CLASS", "[", "item", "]", "result", "=", "await", "player", ".", "async_browse", "(", "MEDIA_TYPE_TO_SQUEEZEBOX", "[", "item", "]", ",", "limit", "=", "1", ",", ")", "if", "result", "is", "not", "None", "and", "result", ".", "get", "(", "\"items\"", ")", "is", "not", "None", ":", "library_info", "[", "\"children\"", "]", ".", "append", "(", "BrowseMedia", "(", "title", "=", "item", ",", "media_class", "=", "media_class", "[", "\"children\"", "]", ",", "media_content_id", "=", "item", ",", "media_content_type", "=", "item", ",", "can_play", "=", "True", ",", "can_expand", "=", "True", ",", ")", ")", "response", "=", "BrowseMedia", "(", "*", "*", "library_info", ")", "return", "response" ]
[ 137, 0 ]
[ 169, 19 ]
python
en
['en', 'en', 'en']
True
generate_playlist
(player, payload)
Generate playlist from browsing payload.
Generate playlist from browsing payload.
async def generate_playlist(player, payload): """Generate playlist from browsing payload.""" media_type = payload["search_type"] media_id = payload["search_id"] if media_type not in SQUEEZEBOX_ID_BY_TYPE: return None browse_id = (SQUEEZEBOX_ID_BY_TYPE[media_type], media_id) result = await player.async_browse( "titles", limit=BROWSE_LIMIT, browse_id=browse_id ) return result.get("items")
[ "async", "def", "generate_playlist", "(", "player", ",", "payload", ")", ":", "media_type", "=", "payload", "[", "\"search_type\"", "]", "media_id", "=", "payload", "[", "\"search_id\"", "]", "if", "media_type", "not", "in", "SQUEEZEBOX_ID_BY_TYPE", ":", "return", "None", "browse_id", "=", "(", "SQUEEZEBOX_ID_BY_TYPE", "[", "media_type", "]", ",", "media_id", ")", "result", "=", "await", "player", ".", "async_browse", "(", "\"titles\"", ",", "limit", "=", "BROWSE_LIMIT", ",", "browse_id", "=", "browse_id", ")", "return", "result", ".", "get", "(", "\"items\"", ")" ]
[ 172, 0 ]
[ 184, 30 ]
python
en
['en', 'en', 'en']
True
download_coco_dataset
(dataset_dir)
Download the coco dataset. Args: dataset_dir: Path where coco dataset should be downloaded.
Download the coco dataset.
def download_coco_dataset(dataset_dir): """Download the coco dataset. Args: dataset_dir: Path where coco dataset should be downloaded. """ dataset_utils.download_and_uncompress_zipfile(FLAGS.coco_train_url, dataset_dir) dataset_utils.download_and_uncompress_zipfile(FLAGS.coco_validation_url, dataset_dir) dataset_utils.download_and_uncompress_zipfile(FLAGS.coco_annotations_url, dataset_dir)
[ "def", "download_coco_dataset", "(", "dataset_dir", ")", ":", "dataset_utils", ".", "download_and_uncompress_zipfile", "(", "FLAGS", ".", "coco_train_url", ",", "dataset_dir", ")", "dataset_utils", ".", "download_and_uncompress_zipfile", "(", "FLAGS", ".", "coco_validation_url", ",", "dataset_dir", ")", "dataset_utils", ".", "download_and_uncompress_zipfile", "(", "FLAGS", ".", "coco_annotations_url", ",", "dataset_dir", ")" ]
[ 56, 0 ]
[ 67, 60 ]
python
en
['en', 'en', 'en']
True
create_labels_file
(foreground_class_of_interest, visualwakewords_labels_file)
Generate visualwakewords labels file. Args: foreground_class_of_interest: category from COCO dataset that is filtered by the visualwakewords dataset visualwakewords_labels_file: output visualwakewords label file
Generate visualwakewords labels file.
def create_labels_file(foreground_class_of_interest, visualwakewords_labels_file): """Generate visualwakewords labels file. Args: foreground_class_of_interest: category from COCO dataset that is filtered by the visualwakewords dataset visualwakewords_labels_file: output visualwakewords label file """ labels_to_class_names = {0: 'background', 1: foreground_class_of_interest} with open(visualwakewords_labels_file, 'w') as fp: for label in labels_to_class_names: fp.write(str(label) + ':' + str(labels_to_class_names[label]) + '\n')
[ "def", "create_labels_file", "(", "foreground_class_of_interest", ",", "visualwakewords_labels_file", ")", ":", "labels_to_class_names", "=", "{", "0", ":", "'background'", ",", "1", ":", "foreground_class_of_interest", "}", "with", "open", "(", "visualwakewords_labels_file", ",", "'w'", ")", "as", "fp", ":", "for", "label", "in", "labels_to_class_names", ":", "fp", ".", "write", "(", "str", "(", "label", ")", "+", "':'", "+", "str", "(", "labels_to_class_names", "[", "label", "]", ")", "+", "'\\n'", ")" ]
[ 70, 0 ]
[ 82, 75 ]
python
en
['en', 'id', 'en']
True
create_visual_wakeword_annotations
(annotations_file, visualwakewords_annotations_file, small_object_area_threshold, foreground_class_of_interest)
Generate visual wakewords annotations file. Loads COCO annotation json files to generate visualwakewords annotations file. Args: annotations_file: JSON file containing COCO bounding box annotations visualwakewords_annotations_file: path to output annotations file small_object_area_threshold: threshold on fraction of image area below which small object bounding boxes are filtered foreground_class_of_interest: category from COCO dataset that is filtered by the visual wakewords dataset
Generate visual wakewords annotations file.
def create_visual_wakeword_annotations(annotations_file, visualwakewords_annotations_file, small_object_area_threshold, foreground_class_of_interest): """Generate visual wakewords annotations file. Loads COCO annotation json files to generate visualwakewords annotations file. Args: annotations_file: JSON file containing COCO bounding box annotations visualwakewords_annotations_file: path to output annotations file small_object_area_threshold: threshold on fraction of image area below which small object bounding boxes are filtered foreground_class_of_interest: category from COCO dataset that is filtered by the visual wakewords dataset """ # default object of interest is person foreground_class_of_interest_id = 1 with tf.gfile.GFile(annotations_file, 'r') as fid: groundtruth_data = json.load(fid) images = groundtruth_data['images'] # Create category index category_index = {} for category in groundtruth_data['categories']: if category['name'] == foreground_class_of_interest: foreground_class_of_interest_id = category['id'] category_index[category['id']] = category # Create annotations index, a map of image_id to it's annotations tf.logging.info('Building annotations index...') annotations_index = collections.defaultdict( lambda: collections.defaultdict(list)) # structure is { "image_id": {"objects" : [list of the image annotations]}} for annotation in groundtruth_data['annotations']: annotations_index[annotation['image_id']]['objects'].append(annotation) missing_annotation_count = len(images) - len(annotations_index) tf.logging.info('%d images are missing annotations.', missing_annotation_count) # Create filtered annotations index annotations_index_filtered = {} for idx, image in enumerate(images): if idx % 100 == 0: tf.logging.info('On image %d of %d', idx, len(images)) annotations = annotations_index[image['id']] annotations_filtered = _filter_annotations( annotations, image, small_object_area_threshold, foreground_class_of_interest_id) annotations_index_filtered[image['id']] = annotations_filtered with open(visualwakewords_annotations_file, 'w') as fp: json.dump( { 'images': images, 'annotations': annotations_index_filtered, 'categories': category_index }, fp)
[ "def", "create_visual_wakeword_annotations", "(", "annotations_file", ",", "visualwakewords_annotations_file", ",", "small_object_area_threshold", ",", "foreground_class_of_interest", ")", ":", "# default object of interest is person", "foreground_class_of_interest_id", "=", "1", "with", "tf", ".", "gfile", ".", "GFile", "(", "annotations_file", ",", "'r'", ")", "as", "fid", ":", "groundtruth_data", "=", "json", ".", "load", "(", "fid", ")", "images", "=", "groundtruth_data", "[", "'images'", "]", "# Create category index", "category_index", "=", "{", "}", "for", "category", "in", "groundtruth_data", "[", "'categories'", "]", ":", "if", "category", "[", "'name'", "]", "==", "foreground_class_of_interest", ":", "foreground_class_of_interest_id", "=", "category", "[", "'id'", "]", "category_index", "[", "category", "[", "'id'", "]", "]", "=", "category", "# Create annotations index, a map of image_id to it's annotations", "tf", ".", "logging", ".", "info", "(", "'Building annotations index...'", ")", "annotations_index", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "collections", ".", "defaultdict", "(", "list", ")", ")", "# structure is { \"image_id\": {\"objects\" : [list of the image annotations]}}", "for", "annotation", "in", "groundtruth_data", "[", "'annotations'", "]", ":", "annotations_index", "[", "annotation", "[", "'image_id'", "]", "]", "[", "'objects'", "]", ".", "append", "(", "annotation", ")", "missing_annotation_count", "=", "len", "(", "images", ")", "-", "len", "(", "annotations_index", ")", "tf", ".", "logging", ".", "info", "(", "'%d images are missing annotations.'", ",", "missing_annotation_count", ")", "# Create filtered annotations index", "annotations_index_filtered", "=", "{", "}", "for", "idx", ",", "image", "in", "enumerate", "(", "images", ")", ":", "if", "idx", "%", "100", "==", "0", ":", "tf", ".", "logging", ".", "info", "(", "'On image %d of %d'", ",", "idx", ",", "len", "(", "images", ")", ")", "annotations", "=", "annotations_index", "[", "image", "[", "'id'", "]", "]", "annotations_filtered", "=", "_filter_annotations", "(", "annotations", ",", "image", ",", "small_object_area_threshold", ",", "foreground_class_of_interest_id", ")", "annotations_index_filtered", "[", "image", "[", "'id'", "]", "]", "=", "annotations_filtered", "with", "open", "(", "visualwakewords_annotations_file", ",", "'w'", ")", "as", "fp", ":", "json", ".", "dump", "(", "{", "'images'", ":", "images", ",", "'annotations'", ":", "annotations_index_filtered", ",", "'categories'", ":", "category_index", "}", ",", "fp", ")" ]
[ 85, 0 ]
[ 139, 16 ]
python
en
['en', 'en', 'en']
True
_filter_annotations
(annotations, image, small_object_area_threshold, foreground_class_of_interest_id)
Filters COCO annotations to visual wakewords annotations. Args: annotations: dicts with keys: { u'objects': [{u'id', u'image_id', u'category_id', u'segmentation', u'area', u'bbox' : [x,y,width,height], u'iscrowd'}] } Notice that bounding box coordinates in the official COCO dataset are given as [x, y, width, height] tuples using absolute coordinates where x, y represent the top-left (0-indexed) corner. image: dict with keys: [u'license', u'file_name', u'coco_url', u'height', u'width', u'date_captured', u'flickr_url', u'id'] small_object_area_threshold: threshold on fraction of image area below which small objects are filtered foreground_class_of_interest_id: category of COCO dataset which visual wakewords filters Returns: annotations_filtered: dict with keys: { u'objects': [{"area", "bbox" : [x,y,width,height]}], u'label', }
Filters COCO annotations to visual wakewords annotations.
def _filter_annotations(annotations, image, small_object_area_threshold, foreground_class_of_interest_id): """Filters COCO annotations to visual wakewords annotations. Args: annotations: dicts with keys: { u'objects': [{u'id', u'image_id', u'category_id', u'segmentation', u'area', u'bbox' : [x,y,width,height], u'iscrowd'}] } Notice that bounding box coordinates in the official COCO dataset are given as [x, y, width, height] tuples using absolute coordinates where x, y represent the top-left (0-indexed) corner. image: dict with keys: [u'license', u'file_name', u'coco_url', u'height', u'width', u'date_captured', u'flickr_url', u'id'] small_object_area_threshold: threshold on fraction of image area below which small objects are filtered foreground_class_of_interest_id: category of COCO dataset which visual wakewords filters Returns: annotations_filtered: dict with keys: { u'objects': [{"area", "bbox" : [x,y,width,height]}], u'label', } """ objects = [] image_area = image['height'] * image['width'] for annotation in annotations['objects']: normalized_object_area = annotation['area'] / image_area category_id = int(annotation['category_id']) # Filter valid bounding boxes if category_id == foreground_class_of_interest_id and \ normalized_object_area > small_object_area_threshold: objects.append({ u'area': annotation['area'], u'bbox': annotation['bbox'], }) label = 1 if objects else 0 return { 'objects': objects, 'label': label, }
[ "def", "_filter_annotations", "(", "annotations", ",", "image", ",", "small_object_area_threshold", ",", "foreground_class_of_interest_id", ")", ":", "objects", "=", "[", "]", "image_area", "=", "image", "[", "'height'", "]", "*", "image", "[", "'width'", "]", "for", "annotation", "in", "annotations", "[", "'objects'", "]", ":", "normalized_object_area", "=", "annotation", "[", "'area'", "]", "/", "image_area", "category_id", "=", "int", "(", "annotation", "[", "'category_id'", "]", ")", "# Filter valid bounding boxes", "if", "category_id", "==", "foreground_class_of_interest_id", "and", "normalized_object_area", ">", "small_object_area_threshold", ":", "objects", ".", "append", "(", "{", "u'area'", ":", "annotation", "[", "'area'", "]", ",", "u'bbox'", ":", "annotation", "[", "'bbox'", "]", ",", "}", ")", "label", "=", "1", "if", "objects", "else", "0", "return", "{", "'objects'", ":", "objects", ",", "'label'", ":", "label", ",", "}" ]
[ 142, 0 ]
[ 183, 3 ]
python
en
['en', 'en', 'en']
True
create_tf_record_for_visualwakewords_dataset
(annotations_file, image_dir, output_path, num_shards)
Loads Visual WakeWords annotations/images and converts to tf.Record format. Args: annotations_file: JSON file containing bounding box annotations. image_dir: Directory containing the image files. output_path: Path to output tf.Record file. num_shards: number of output file shards.
Loads Visual WakeWords annotations/images and converts to tf.Record format.
def create_tf_record_for_visualwakewords_dataset(annotations_file, image_dir, output_path, num_shards): """Loads Visual WakeWords annotations/images and converts to tf.Record format. Args: annotations_file: JSON file containing bounding box annotations. image_dir: Directory containing the image files. output_path: Path to output tf.Record file. num_shards: number of output file shards. """ with contextlib2.ExitStack() as tf_record_close_stack, \ tf.gfile.GFile(annotations_file, 'r') as fid: output_tfrecords = dataset_utils.open_sharded_output_tfrecords( tf_record_close_stack, output_path, num_shards) groundtruth_data = json.load(fid) images = groundtruth_data['images'] annotations_index = groundtruth_data['annotations'] annotations_index = {int(k): v for k, v in annotations_index.iteritems()} # convert 'unicode' key to 'int' key after we parse the json file for idx, image in enumerate(images): if idx % 100 == 0: tf.logging.info('On image %d of %d', idx, len(images)) annotations = annotations_index[image['id']] tf_example = _create_tf_example(image, annotations, image_dir) shard_idx = idx % num_shards output_tfrecords[shard_idx].write(tf_example.SerializeToString())
[ "def", "create_tf_record_for_visualwakewords_dataset", "(", "annotations_file", ",", "image_dir", ",", "output_path", ",", "num_shards", ")", ":", "with", "contextlib2", ".", "ExitStack", "(", ")", "as", "tf_record_close_stack", ",", "tf", ".", "gfile", ".", "GFile", "(", "annotations_file", ",", "'r'", ")", "as", "fid", ":", "output_tfrecords", "=", "dataset_utils", ".", "open_sharded_output_tfrecords", "(", "tf_record_close_stack", ",", "output_path", ",", "num_shards", ")", "groundtruth_data", "=", "json", ".", "load", "(", "fid", ")", "images", "=", "groundtruth_data", "[", "'images'", "]", "annotations_index", "=", "groundtruth_data", "[", "'annotations'", "]", "annotations_index", "=", "{", "int", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "annotations_index", ".", "iteritems", "(", ")", "}", "# convert 'unicode' key to 'int' key after we parse the json file", "for", "idx", ",", "image", "in", "enumerate", "(", "images", ")", ":", "if", "idx", "%", "100", "==", "0", ":", "tf", ".", "logging", ".", "info", "(", "'On image %d of %d'", ",", "idx", ",", "len", "(", "images", ")", ")", "annotations", "=", "annotations_index", "[", "image", "[", "'id'", "]", "]", "tf_example", "=", "_create_tf_example", "(", "image", ",", "annotations", ",", "image_dir", ")", "shard_idx", "=", "idx", "%", "num_shards", "output_tfrecords", "[", "shard_idx", "]", ".", "write", "(", "tf_example", ".", "SerializeToString", "(", ")", ")" ]
[ 186, 0 ]
[ 212, 71 ]
python
en
['en', 'en', 'en']
True
_create_tf_example
(image, annotations, image_dir)
Converts image and annotations to a tf.Example proto. Args: image: dict with keys: [u'license', u'file_name', u'coco_url', u'height', u'width', u'date_captured', u'flickr_url', u'id'] annotations: dict with objects (a list of image annotations) and a label. {u'objects':[{"area", "bbox" : [x,y,width,height}], u'label'}. Notice that bounding box coordinates in the COCO dataset are given as[x, y, width, height] tuples using absolute coordinates where x, y represent the top-left (0-indexed) corner. This function also converts to the format that can be used by the Tensorflow Object Detection API (which is [ymin, xmin, ymax, xmax] with coordinates normalized relative to image size). image_dir: directory containing the image files. Returns: tf_example: The converted tf.Example Raises: ValueError: if the image pointed to by data['filename'] is not a valid JPEG
Converts image and annotations to a tf.Example proto.
def _create_tf_example(image, annotations, image_dir): """Converts image and annotations to a tf.Example proto. Args: image: dict with keys: [u'license', u'file_name', u'coco_url', u'height', u'width', u'date_captured', u'flickr_url', u'id'] annotations: dict with objects (a list of image annotations) and a label. {u'objects':[{"area", "bbox" : [x,y,width,height}], u'label'}. Notice that bounding box coordinates in the COCO dataset are given as[x, y, width, height] tuples using absolute coordinates where x, y represent the top-left (0-indexed) corner. This function also converts to the format that can be used by the Tensorflow Object Detection API (which is [ymin, xmin, ymax, xmax] with coordinates normalized relative to image size). image_dir: directory containing the image files. Returns: tf_example: The converted tf.Example Raises: ValueError: if the image pointed to by data['filename'] is not a valid JPEG """ image_height = image['height'] image_width = image['width'] filename = image['file_name'] image_id = image['id'] full_path = os.path.join(image_dir, filename) with tf.gfile.GFile(full_path, 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = PIL.Image.open(encoded_jpg_io) key = hashlib.sha256(encoded_jpg).hexdigest() xmin, xmax, ymin, ymax, area = [], [], [], [], [] for obj in annotations['objects']: (x, y, width, height) = tuple(obj['bbox']) xmin.append(float(x) / image_width) xmax.append(float(x + width) / image_width) ymin.append(float(y) / image_height) ymax.append(float(y + height) / image_height) area.append(obj['area']) feature_dict = { 'image/height': dataset_utils.int64_feature(image_height), 'image/width': dataset_utils.int64_feature(image_width), 'image/filename': dataset_utils.bytes_feature(filename.encode('utf8')), 'image/source_id': dataset_utils.bytes_feature(str(image_id).encode('utf8')), 'image/key/sha256': dataset_utils.bytes_feature(key.encode('utf8')), 'image/encoded': dataset_utils.bytes_feature(encoded_jpg), 'image/format': dataset_utils.bytes_feature('jpeg'.encode('utf8')), 'image/class/label': dataset_utils.int64_feature(annotations['label']), 'image/object/bbox/xmin': dataset_utils.float_list_feature(xmin), 'image/object/bbox/xmax': dataset_utils.float_list_feature(xmax), 'image/object/bbox/ymin': dataset_utils.float_list_feature(ymin), 'image/object/bbox/ymax': dataset_utils.float_list_feature(ymax), 'image/object/area': dataset_utils.float_list_feature(area), } example = tf.train.Example(features=tf.train.Features(feature=feature_dict)) return example
[ "def", "_create_tf_example", "(", "image", ",", "annotations", ",", "image_dir", ")", ":", "image_height", "=", "image", "[", "'height'", "]", "image_width", "=", "image", "[", "'width'", "]", "filename", "=", "image", "[", "'file_name'", "]", "image_id", "=", "image", "[", "'id'", "]", "full_path", "=", "os", ".", "path", ".", "join", "(", "image_dir", ",", "filename", ")", "with", "tf", ".", "gfile", ".", "GFile", "(", "full_path", ",", "'rb'", ")", "as", "fid", ":", "encoded_jpg", "=", "fid", ".", "read", "(", ")", "encoded_jpg_io", "=", "io", ".", "BytesIO", "(", "encoded_jpg", ")", "image", "=", "PIL", ".", "Image", ".", "open", "(", "encoded_jpg_io", ")", "key", "=", "hashlib", ".", "sha256", "(", "encoded_jpg", ")", ".", "hexdigest", "(", ")", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ",", "area", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "for", "obj", "in", "annotations", "[", "'objects'", "]", ":", "(", "x", ",", "y", ",", "width", ",", "height", ")", "=", "tuple", "(", "obj", "[", "'bbox'", "]", ")", "xmin", ".", "append", "(", "float", "(", "x", ")", "/", "image_width", ")", "xmax", ".", "append", "(", "float", "(", "x", "+", "width", ")", "/", "image_width", ")", "ymin", ".", "append", "(", "float", "(", "y", ")", "/", "image_height", ")", "ymax", ".", "append", "(", "float", "(", "y", "+", "height", ")", "/", "image_height", ")", "area", ".", "append", "(", "obj", "[", "'area'", "]", ")", "feature_dict", "=", "{", "'image/height'", ":", "dataset_utils", ".", "int64_feature", "(", "image_height", ")", ",", "'image/width'", ":", "dataset_utils", ".", "int64_feature", "(", "image_width", ")", ",", "'image/filename'", ":", "dataset_utils", ".", "bytes_feature", "(", "filename", ".", "encode", "(", "'utf8'", ")", ")", ",", "'image/source_id'", ":", "dataset_utils", ".", "bytes_feature", "(", "str", "(", "image_id", ")", ".", "encode", "(", "'utf8'", ")", ")", ",", "'image/key/sha256'", ":", "dataset_utils", ".", "bytes_feature", "(", "key", ".", "encode", "(", "'utf8'", ")", ")", ",", "'image/encoded'", ":", "dataset_utils", ".", "bytes_feature", "(", "encoded_jpg", ")", ",", "'image/format'", ":", "dataset_utils", ".", "bytes_feature", "(", "'jpeg'", ".", "encode", "(", "'utf8'", ")", ")", ",", "'image/class/label'", ":", "dataset_utils", ".", "int64_feature", "(", "annotations", "[", "'label'", "]", ")", ",", "'image/object/bbox/xmin'", ":", "dataset_utils", ".", "float_list_feature", "(", "xmin", ")", ",", "'image/object/bbox/xmax'", ":", "dataset_utils", ".", "float_list_feature", "(", "xmax", ")", ",", "'image/object/bbox/ymin'", ":", "dataset_utils", ".", "float_list_feature", "(", "ymin", ")", ",", "'image/object/bbox/ymax'", ":", "dataset_utils", ".", "float_list_feature", "(", "ymax", ")", ",", "'image/object/area'", ":", "dataset_utils", ".", "float_list_feature", "(", "area", ")", ",", "}", "example", "=", "tf", ".", "train", ".", "Example", "(", "features", "=", "tf", ".", "train", ".", "Features", "(", "feature", "=", "feature_dict", ")", ")", "return", "example" ]
[ 215, 0 ]
[ 285, 16 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Set up MelCloud device climate based on config_entry.
Set up MelCloud device climate based on config_entry.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ): """Set up MelCloud device climate based on config_entry.""" mel_devices = hass.data[DOMAIN][entry.entry_id] async_add_entities( [ AtaDeviceClimate(mel_device, mel_device.device) for mel_device in mel_devices[DEVICE_TYPE_ATA] ] + [ AtwDeviceZoneClimate(mel_device, mel_device.device, zone) for mel_device in mel_devices[DEVICE_TYPE_ATW] for zone in mel_device.device.zones ], True, ) platform = entity_platform.current_platform.get() platform.async_register_entity_service( SERVICE_SET_VANE_HORIZONTAL, {vol.Required(CONF_POSITION): cv.string}, "async_set_vane_horizontal", ) platform.async_register_entity_service( SERVICE_SET_VANE_VERTICAL, {vol.Required(CONF_POSITION): cv.string}, "async_set_vane_vertical", )
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", ":", "mel_devices", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "async_add_entities", "(", "[", "AtaDeviceClimate", "(", "mel_device", ",", "mel_device", ".", "device", ")", "for", "mel_device", "in", "mel_devices", "[", "DEVICE_TYPE_ATA", "]", "]", "+", "[", "AtwDeviceZoneClimate", "(", "mel_device", ",", "mel_device", ".", "device", ",", "zone", ")", "for", "mel_device", "in", "mel_devices", "[", "DEVICE_TYPE_ATW", "]", "for", "zone", "in", "mel_device", ".", "device", ".", "zones", "]", ",", "True", ",", ")", "platform", "=", "entity_platform", ".", "current_platform", ".", "get", "(", ")", "platform", ".", "async_register_entity_service", "(", "SERVICE_SET_VANE_HORIZONTAL", ",", "{", "vol", ".", "Required", "(", "CONF_POSITION", ")", ":", "cv", ".", "string", "}", ",", "\"async_set_vane_horizontal\"", ",", ")", "platform", ".", "async_register_entity_service", "(", "SERVICE_SET_VANE_VERTICAL", ",", "{", "vol", ".", "Required", "(", "CONF_POSITION", ")", ":", "cv", ".", "string", "}", ",", "\"async_set_vane_vertical\"", ",", ")" ]
[ 66, 0 ]
[ 94, 5 ]
python
en
['en', 'en', 'en']
True
MelCloudClimate.__init__
(self, device: MelCloudDevice)
Initialize the climate.
Initialize the climate.
def __init__(self, device: MelCloudDevice): """Initialize the climate.""" self.api = device self._base_device = self.api.device self._name = device.name
[ "def", "__init__", "(", "self", ",", "device", ":", "MelCloudDevice", ")", ":", "self", ".", "api", "=", "device", "self", ".", "_base_device", "=", "self", ".", "api", ".", "device", "self", ".", "_name", "=", "device", ".", "name" ]
[ 100, 4 ]
[ 104, 32 ]
python
en
['en', 'en', 'en']
True
MelCloudClimate.async_update
(self)
Update state from MELCloud.
Update state from MELCloud.
async def async_update(self): """Update state from MELCloud.""" await self.api.async_update()
[ "async", "def", "async_update", "(", "self", ")", ":", "await", "self", ".", "api", ".", "async_update", "(", ")" ]
[ 106, 4 ]
[ 108, 37 ]
python
en
['en', 'en', 'en']
True
MelCloudClimate.device_info
(self)
Return a device description for device registry.
Return a device description for device registry.
def device_info(self): """Return a device description for device registry.""" return self.api.device_info
[ "def", "device_info", "(", "self", ")", ":", "return", "self", ".", "api", ".", "device_info" ]
[ 111, 4 ]
[ 113, 35 ]
python
en
['ro', 'fr', 'en']
False
MelCloudClimate.target_temperature_step
(self)
Return the supported step of target temperature.
Return the supported step of target temperature.
def target_temperature_step(self) -> Optional[float]: """Return the supported step of target temperature.""" return self._base_device.temperature_increment
[ "def", "target_temperature_step", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_base_device", ".", "temperature_increment" ]
[ 116, 4 ]
[ 118, 54 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.__init__
(self, device: MelCloudDevice, ata_device: AtaDevice)
Initialize the climate.
Initialize the climate.
def __init__(self, device: MelCloudDevice, ata_device: AtaDevice) -> None: """Initialize the climate.""" super().__init__(device) self._device = ata_device
[ "def", "__init__", "(", "self", ",", "device", ":", "MelCloudDevice", ",", "ata_device", ":", "AtaDevice", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "device", ")", "self", ".", "_device", "=", "ata_device" ]
[ 124, 4 ]
[ 127, 33 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self) -> Optional[str]: """Return a unique ID.""" return f"{self.api.device.serial}-{self.api.device.mac}"
[ "def", "unique_id", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "f\"{self.api.device.serial}-{self.api.device.mac}\"" ]
[ 130, 4 ]
[ 132, 64 ]
python
ca
['fr', 'ca', 'en']
False
AtaDeviceClimate.name
(self)
Return the display name of this entity.
Return the display name of this entity.
def name(self): """Return the display name of this entity.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 135, 4 ]
[ 137, 25 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.device_state_attributes
(self)
Return the optional state attributes with device specific additions.
Return the optional state attributes with device specific additions.
def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the optional state attributes with device specific additions.""" attr = {} vane_horizontal = self._device.vane_horizontal if vane_horizontal: attr.update( { ATTR_VANE_HORIZONTAL: vane_horizontal, ATTR_VANE_HORIZONTAL_POSITIONS: self._device.vane_horizontal_positions, } ) vane_vertical = self._device.vane_vertical if vane_vertical: attr.update( { ATTR_VANE_VERTICAL: vane_vertical, ATTR_VANE_VERTICAL_POSITIONS: self._device.vane_vertical_positions, } ) return attr
[ "def", "device_state_attributes", "(", "self", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "attr", "=", "{", "}", "vane_horizontal", "=", "self", ".", "_device", ".", "vane_horizontal", "if", "vane_horizontal", ":", "attr", ".", "update", "(", "{", "ATTR_VANE_HORIZONTAL", ":", "vane_horizontal", ",", "ATTR_VANE_HORIZONTAL_POSITIONS", ":", "self", ".", "_device", ".", "vane_horizontal_positions", ",", "}", ")", "vane_vertical", "=", "self", ".", "_device", ".", "vane_vertical", "if", "vane_vertical", ":", "attr", ".", "update", "(", "{", "ATTR_VANE_VERTICAL", ":", "vane_vertical", ",", "ATTR_VANE_VERTICAL_POSITIONS", ":", "self", ".", "_device", ".", "vane_vertical_positions", ",", "}", ")", "return", "attr" ]
[ 140, 4 ]
[ 161, 19 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.temperature_unit
(self)
Return the unit of measurement used by the platform.
Return the unit of measurement used by the platform.
def temperature_unit(self) -> str: """Return the unit of measurement used by the platform.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", "->", "str", ":", "return", "TEMP_CELSIUS" ]
[ 164, 4 ]
[ 166, 27 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.hvac_mode
(self)
Return hvac operation ie. heat, cool mode.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode.""" mode = self._device.operation_mode if not self._device.power or mode is None: return HVAC_MODE_OFF return ATA_HVAC_MODE_LOOKUP.get(mode)
[ "def", "hvac_mode", "(", "self", ")", "->", "str", ":", "mode", "=", "self", ".", "_device", ".", "operation_mode", "if", "not", "self", ".", "_device", ".", "power", "or", "mode", "is", "None", ":", "return", "HVAC_MODE_OFF", "return", "ATA_HVAC_MODE_LOOKUP", ".", "get", "(", "mode", ")" ]
[ 169, 4 ]
[ 174, 45 ]
python
bg
['en', 'bg', 'bg']
True
AtaDeviceClimate.async_set_hvac_mode
(self, hvac_mode: str)
Set new target hvac mode.
Set new target hvac mode.
async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_OFF: await self._device.set({"power": False}) return operation_mode = ATA_HVAC_MODE_REVERSE_LOOKUP.get(hvac_mode) if operation_mode is None: raise ValueError(f"Invalid hvac_mode [{hvac_mode}]") props = {"operation_mode": operation_mode} if self.hvac_mode == HVAC_MODE_OFF: props["power"] = True await self._device.set(props)
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ":", "str", ")", "->", "None", ":", "if", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "await", "self", ".", "_device", ".", "set", "(", "{", "\"power\"", ":", "False", "}", ")", "return", "operation_mode", "=", "ATA_HVAC_MODE_REVERSE_LOOKUP", ".", "get", "(", "hvac_mode", ")", "if", "operation_mode", "is", "None", ":", "raise", "ValueError", "(", "f\"Invalid hvac_mode [{hvac_mode}]\"", ")", "props", "=", "{", "\"operation_mode\"", ":", "operation_mode", "}", "if", "self", ".", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "props", "[", "\"power\"", "]", "=", "True", "await", "self", ".", "_device", ".", "set", "(", "props", ")" ]
[ 176, 4 ]
[ 189, 37 ]
python
da
['da', 'su', 'en']
False
AtaDeviceClimate.hvac_modes
(self)
Return the list of available hvac operation modes.
Return the list of available hvac operation modes.
def hvac_modes(self) -> List[str]: """Return the list of available hvac operation modes.""" return [HVAC_MODE_OFF] + [ ATA_HVAC_MODE_LOOKUP.get(mode) for mode in self._device.operation_modes ]
[ "def", "hvac_modes", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "HVAC_MODE_OFF", "]", "+", "[", "ATA_HVAC_MODE_LOOKUP", ".", "get", "(", "mode", ")", "for", "mode", "in", "self", ".", "_device", ".", "operation_modes", "]" ]
[ 192, 4 ]
[ 196, 9 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self) -> Optional[float]: """Return the current temperature.""" return self._device.room_temperature
[ "def", "current_temperature", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_device", ".", "room_temperature" ]
[ 199, 4 ]
[ 201, 44 ]
python
en
['en', 'la', 'en']
True
AtaDeviceClimate.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self) -> Optional[float]: """Return the temperature we try to reach.""" return self._device.target_temperature
[ "def", "target_temperature", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_device", ".", "target_temperature" ]
[ 204, 4 ]
[ 206, 46 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.async_set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" await self._device.set( {"target_temperature": kwargs.get("temperature", self.target_temperature)} )
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_device", ".", "set", "(", "{", "\"target_temperature\"", ":", "kwargs", ".", "get", "(", "\"temperature\"", ",", "self", ".", "target_temperature", ")", "}", ")" ]
[ 208, 4 ]
[ 212, 9 ]
python
en
['en', 'ca', 'en']
True
AtaDeviceClimate.fan_mode
(self)
Return the fan setting.
Return the fan setting.
def fan_mode(self) -> Optional[str]: """Return the fan setting.""" return self._device.fan_speed
[ "def", "fan_mode", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_device", ".", "fan_speed" ]
[ 215, 4 ]
[ 217, 37 ]
python
en
['en', 'fy', 'en']
True
AtaDeviceClimate.async_set_fan_mode
(self, fan_mode: str)
Set new target fan mode.
Set new target fan mode.
async def async_set_fan_mode(self, fan_mode: str) -> None: """Set new target fan mode.""" await self._device.set({"fan_speed": fan_mode})
[ "async", "def", "async_set_fan_mode", "(", "self", ",", "fan_mode", ":", "str", ")", "->", "None", ":", "await", "self", ".", "_device", ".", "set", "(", "{", "\"fan_speed\"", ":", "fan_mode", "}", ")" ]
[ 219, 4 ]
[ 221, 55 ]
python
en
['sv', 'fy', 'en']
False
AtaDeviceClimate.fan_modes
(self)
Return the list of available fan modes.
Return the list of available fan modes.
def fan_modes(self) -> Optional[List[str]]: """Return the list of available fan modes.""" return self._device.fan_speeds
[ "def", "fan_modes", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "return", "self", ".", "_device", ".", "fan_speeds" ]
[ 224, 4 ]
[ 226, 38 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.async_set_vane_horizontal
(self, position: str)
Set horizontal vane position.
Set horizontal vane position.
async def async_set_vane_horizontal(self, position: str) -> None: """Set horizontal vane position.""" if position not in self._device.vane_horizontal_positions: raise ValueError( f"Invalid horizontal vane position {position}. Valid positions: [{self._device.vane_horizontal_positions}]." ) await self._device.set({ata.PROPERTY_VANE_HORIZONTAL: position})
[ "async", "def", "async_set_vane_horizontal", "(", "self", ",", "position", ":", "str", ")", "->", "None", ":", "if", "position", "not", "in", "self", ".", "_device", ".", "vane_horizontal_positions", ":", "raise", "ValueError", "(", "f\"Invalid horizontal vane position {position}. Valid positions: [{self._device.vane_horizontal_positions}].\"", ")", "await", "self", ".", "_device", ".", "set", "(", "{", "ata", ".", "PROPERTY_VANE_HORIZONTAL", ":", "position", "}", ")" ]
[ 228, 4 ]
[ 234, 72 ]
python
nl
['nl', 'sr', 'nl']
True
AtaDeviceClimate.async_set_vane_vertical
(self, position: str)
Set vertical vane position.
Set vertical vane position.
async def async_set_vane_vertical(self, position: str) -> None: """Set vertical vane position.""" if position not in self._device.vane_vertical_positions: raise ValueError( f"Invalid vertical vane position {position}. Valid positions: [{self._device.vane_vertical_positions}]." ) await self._device.set({ata.PROPERTY_VANE_VERTICAL: position})
[ "async", "def", "async_set_vane_vertical", "(", "self", ",", "position", ":", "str", ")", "->", "None", ":", "if", "position", "not", "in", "self", ".", "_device", ".", "vane_vertical_positions", ":", "raise", "ValueError", "(", "f\"Invalid vertical vane position {position}. Valid positions: [{self._device.vane_vertical_positions}].\"", ")", "await", "self", ".", "_device", ".", "set", "(", "{", "ata", ".", "PROPERTY_VANE_VERTICAL", ":", "position", "}", ")" ]
[ 236, 4 ]
[ 242, 70 ]
python
da
['en', 'da', 'nl']
False
AtaDeviceClimate.swing_mode
(self)
Return vertical vane position or mode.
Return vertical vane position or mode.
def swing_mode(self) -> Optional[str]: """Return vertical vane position or mode.""" return self._device.vane_vertical
[ "def", "swing_mode", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_device", ".", "vane_vertical" ]
[ 245, 4 ]
[ 247, 41 ]
python
en
['en', 'no', 'nl']
False
AtaDeviceClimate.async_set_swing_mode
(self, swing_mode)
Set vertical vane position or mode.
Set vertical vane position or mode.
async def async_set_swing_mode(self, swing_mode) -> None: """Set vertical vane position or mode.""" await self.async_set_vane_vertical(swing_mode)
[ "async", "def", "async_set_swing_mode", "(", "self", ",", "swing_mode", ")", "->", "None", ":", "await", "self", ".", "async_set_vane_vertical", "(", "swing_mode", ")" ]
[ 249, 4 ]
[ 251, 54 ]
python
da
['en', 'da', 'nl']
False
AtaDeviceClimate.swing_modes
(self)
Return a list of available vertical vane positions and modes.
Return a list of available vertical vane positions and modes.
def swing_modes(self) -> Optional[str]: """Return a list of available vertical vane positions and modes.""" return self._device.vane_vertical_positions
[ "def", "swing_modes", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_device", ".", "vane_vertical_positions" ]
[ 254, 4 ]
[ 256, 51 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_FAN_MODE | SUPPORT_TARGET_TEMPERATURE | SUPPORT_SWING_MODE
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_FAN_MODE", "|", "SUPPORT_TARGET_TEMPERATURE", "|", "SUPPORT_SWING_MODE" ]
[ 259, 4 ]
[ 261, 81 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.async_turn_on
(self)
Turn the entity on.
Turn the entity on.
async def async_turn_on(self) -> None: """Turn the entity on.""" await self._device.set({"power": True})
[ "async", "def", "async_turn_on", "(", "self", ")", "->", "None", ":", "await", "self", ".", "_device", ".", "set", "(", "{", "\"power\"", ":", "True", "}", ")" ]
[ 263, 4 ]
[ 265, 47 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.async_turn_off
(self)
Turn the entity off.
Turn the entity off.
async def async_turn_off(self) -> None: """Turn the entity off.""" await self._device.set({"power": False})
[ "async", "def", "async_turn_off", "(", "self", ")", "->", "None", ":", "await", "self", ".", "_device", ".", "set", "(", "{", "\"power\"", ":", "False", "}", ")" ]
[ 267, 4 ]
[ 269, 48 ]
python
en
['en', 'en', 'en']
True
AtaDeviceClimate.min_temp
(self)
Return the minimum temperature.
Return the minimum temperature.
def min_temp(self) -> float: """Return the minimum temperature.""" min_value = self._device.target_temperature_min if min_value is not None: return min_value return DEFAULT_MIN_TEMP
[ "def", "min_temp", "(", "self", ")", "->", "float", ":", "min_value", "=", "self", ".", "_device", ".", "target_temperature_min", "if", "min_value", "is", "not", "None", ":", "return", "min_value", "return", "DEFAULT_MIN_TEMP" ]
[ 272, 4 ]
[ 278, 31 ]
python
en
['en', 'la', 'en']
True
AtaDeviceClimate.max_temp
(self)
Return the maximum temperature.
Return the maximum temperature.
def max_temp(self) -> float: """Return the maximum temperature.""" max_value = self._device.target_temperature_max if max_value is not None: return max_value return DEFAULT_MAX_TEMP
[ "def", "max_temp", "(", "self", ")", "->", "float", ":", "max_value", "=", "self", ".", "_device", ".", "target_temperature_max", "if", "max_value", "is", "not", "None", ":", "return", "max_value", "return", "DEFAULT_MAX_TEMP" ]
[ 281, 4 ]
[ 287, 31 ]
python
en
['en', 'la', 'en']
True
AtwDeviceZoneClimate.__init__
( self, device: MelCloudDevice, atw_device: AtwDevice, atw_zone: Zone )
Initialize the climate.
Initialize the climate.
def __init__( self, device: MelCloudDevice, atw_device: AtwDevice, atw_zone: Zone ) -> None: """Initialize the climate.""" super().__init__(device) self._device = atw_device self._zone = atw_zone
[ "def", "__init__", "(", "self", ",", "device", ":", "MelCloudDevice", ",", "atw_device", ":", "AtwDevice", ",", "atw_zone", ":", "Zone", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "device", ")", "self", ".", "_device", "=", "atw_device", "self", ".", "_zone", "=", "atw_zone" ]
[ 293, 4 ]
[ 299, 29 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self) -> Optional[str]: """Return a unique ID.""" return f"{self.api.device.serial}-{self._zone.zone_index}"
[ "def", "unique_id", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "f\"{self.api.device.serial}-{self._zone.zone_index}\"" ]
[ 302, 4 ]
[ 304, 66 ]
python
ca
['fr', 'ca', 'en']
False
AtwDeviceZoneClimate.name
(self)
Return the display name of this entity.
Return the display name of this entity.
def name(self) -> str: """Return the display name of this entity.""" return f"{self._name} {self._zone.name}"
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "f\"{self._name} {self._zone.name}\"" ]
[ 307, 4 ]
[ 309, 48 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.device_state_attributes
(self)
Return the optional state attributes with device specific additions.
Return the optional state attributes with device specific additions.
def device_state_attributes(self) -> Dict[str, Any]: """Return the optional state attributes with device specific additions.""" data = { ATTR_STATUS: ATW_ZONE_HVAC_MODE_LOOKUP.get( self._zone.status, self._zone.status ) } return data
[ "def", "device_state_attributes", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "data", "=", "{", "ATTR_STATUS", ":", "ATW_ZONE_HVAC_MODE_LOOKUP", ".", "get", "(", "self", ".", "_zone", ".", "status", ",", "self", ".", "_zone", ".", "status", ")", "}", "return", "data" ]
[ 312, 4 ]
[ 319, 19 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.temperature_unit
(self)
Return the unit of measurement used by the platform.
Return the unit of measurement used by the platform.
def temperature_unit(self) -> str: """Return the unit of measurement used by the platform.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", "->", "str", ":", "return", "TEMP_CELSIUS" ]
[ 322, 4 ]
[ 324, 27 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.hvac_mode
(self)
Return hvac operation ie. heat, cool mode.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode.""" mode = self._zone.operation_mode if not self._device.power or mode is None: return HVAC_MODE_OFF return ATW_ZONE_HVAC_MODE_LOOKUP.get(mode, HVAC_MODE_OFF)
[ "def", "hvac_mode", "(", "self", ")", "->", "str", ":", "mode", "=", "self", ".", "_zone", ".", "operation_mode", "if", "not", "self", ".", "_device", ".", "power", "or", "mode", "is", "None", ":", "return", "HVAC_MODE_OFF", "return", "ATW_ZONE_HVAC_MODE_LOOKUP", ".", "get", "(", "mode", ",", "HVAC_MODE_OFF", ")" ]
[ 327, 4 ]
[ 332, 65 ]
python
bg
['en', 'bg', 'bg']
True
AtwDeviceZoneClimate.async_set_hvac_mode
(self, hvac_mode: str)
Set new target hvac mode.
Set new target hvac mode.
async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_OFF: await self._device.set({"power": False}) return operation_mode = ATW_ZONE_HVAC_MODE_REVERSE_LOOKUP.get(hvac_mode) if operation_mode is None: raise ValueError(f"Invalid hvac_mode [{hvac_mode}]") if self._zone.zone_index == 1: props = {PROPERTY_ZONE_1_OPERATION_MODE: operation_mode} else: props = {PROPERTY_ZONE_2_OPERATION_MODE: operation_mode} if self.hvac_mode == HVAC_MODE_OFF: props["power"] = True await self._device.set(props)
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ":", "str", ")", "->", "None", ":", "if", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "await", "self", ".", "_device", ".", "set", "(", "{", "\"power\"", ":", "False", "}", ")", "return", "operation_mode", "=", "ATW_ZONE_HVAC_MODE_REVERSE_LOOKUP", ".", "get", "(", "hvac_mode", ")", "if", "operation_mode", "is", "None", ":", "raise", "ValueError", "(", "f\"Invalid hvac_mode [{hvac_mode}]\"", ")", "if", "self", ".", "_zone", ".", "zone_index", "==", "1", ":", "props", "=", "{", "PROPERTY_ZONE_1_OPERATION_MODE", ":", "operation_mode", "}", "else", ":", "props", "=", "{", "PROPERTY_ZONE_2_OPERATION_MODE", ":", "operation_mode", "}", "if", "self", ".", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "props", "[", "\"power\"", "]", "=", "True", "await", "self", ".", "_device", ".", "set", "(", "props", ")" ]
[ 334, 4 ]
[ 350, 37 ]
python
da
['da', 'su', 'en']
False
AtwDeviceZoneClimate.hvac_modes
(self)
Return the list of available hvac operation modes.
Return the list of available hvac operation modes.
def hvac_modes(self) -> List[str]: """Return the list of available hvac operation modes.""" return [self.hvac_mode]
[ "def", "hvac_modes", "(", "self", ")", "->", "List", "[", "str", "]", ":", "return", "[", "self", ".", "hvac_mode", "]" ]
[ 353, 4 ]
[ 355, 31 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self) -> Optional[float]: """Return the current temperature.""" return self._zone.room_temperature
[ "def", "current_temperature", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_zone", ".", "room_temperature" ]
[ 358, 4 ]
[ 360, 42 ]
python
en
['en', 'la', 'en']
True
AtwDeviceZoneClimate.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self) -> Optional[float]: """Return the temperature we try to reach.""" return self._zone.target_temperature
[ "def", "target_temperature", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "_zone", ".", "target_temperature" ]
[ 363, 4 ]
[ 365, 44 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.async_set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" await self._zone.set_target_temperature( kwargs.get("temperature", self.target_temperature) )
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_zone", ".", "set_target_temperature", "(", "kwargs", ".", "get", "(", "\"temperature\"", ",", "self", ".", "target_temperature", ")", ")" ]
[ 367, 4 ]
[ 371, 9 ]
python
en
['en', 'ca', 'en']
True
AtwDeviceZoneClimate.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_TARGET_TEMPERATURE" ]
[ 374, 4 ]
[ 376, 41 ]
python
en
['en', 'en', 'en']
True
AtwDeviceZoneClimate.min_temp
(self)
Return the minimum temperature. MELCloud API does not expose radiator zone temperature limits.
Return the minimum temperature.
def min_temp(self) -> float: """Return the minimum temperature. MELCloud API does not expose radiator zone temperature limits. """ return 10
[ "def", "min_temp", "(", "self", ")", "->", "float", ":", "return", "10" ]
[ 379, 4 ]
[ 384, 17 ]
python
en
['en', 'la', 'en']
True
AtwDeviceZoneClimate.max_temp
(self)
Return the maximum temperature. MELCloud API does not expose radiator zone temperature limits.
Return the maximum temperature.
def max_temp(self) -> float: """Return the maximum temperature. MELCloud API does not expose radiator zone temperature limits. """ return 30
[ "def", "max_temp", "(", "self", ")", "->", "float", ":", "return", "30" ]
[ 387, 4 ]
[ 392, 17 ]
python
en
['en', 'la', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Set up ESPHome covers based on a config entry.
Set up ESPHome covers based on a config entry.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome covers based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="cover", info_type=CoverInfo, entity_type=EsphomeCover, state_type=CoverState, )
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "await", "platform_async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ",", "component_key", "=", "\"cover\"", ",", "info_type", "=", "CoverInfo", ",", "entity_type", "=", "EsphomeCover", ",", "state_type", "=", "CoverState", ",", ")" ]
[ 23, 0 ]
[ 35, 5 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> int: """Flag supported features.""" flags = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP if self._static_info.supports_position: flags |= SUPPORT_SET_POSITION if self._static_info.supports_tilt: flags |= SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION return flags
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "flags", "=", "SUPPORT_OPEN", "|", "SUPPORT_CLOSE", "|", "SUPPORT_STOP", "if", "self", ".", "_static_info", ".", "supports_position", ":", "flags", "|=", "SUPPORT_SET_POSITION", "if", "self", ".", "_static_info", ".", "supports_tilt", ":", "flags", "|=", "SUPPORT_OPEN_TILT", "|", "SUPPORT_CLOSE_TILT", "|", "SUPPORT_SET_TILT_POSITION", "return", "flags" ]
[ 46, 4 ]
[ 53, 20 ]
python
en
['da', 'en', 'en']
True
EsphomeCover.device_class
(self)
Return the class of this device, from component DEVICE_CLASSES.
Return the class of this device, from component DEVICE_CLASSES.
def device_class(self) -> str: """Return the class of this device, from component DEVICE_CLASSES.""" return self._static_info.device_class
[ "def", "device_class", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_static_info", ".", "device_class" ]
[ 56, 4 ]
[ 58, 45 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.assumed_state
(self)
Return true if we do optimistic updates.
Return true if we do optimistic updates.
def assumed_state(self) -> bool: """Return true if we do optimistic updates.""" return self._static_info.assumed_state
[ "def", "assumed_state", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_static_info", ".", "assumed_state" ]
[ 61, 4 ]
[ 63, 46 ]
python
en
['pt', 'la', 'en']
False
EsphomeCover.is_closed
(self)
Return if the cover is closed or not.
Return if the cover is closed or not.
def is_closed(self) -> Optional[bool]: """Return if the cover is closed or not.""" # Check closed state with api version due to a protocol change return self._state.is_closed(self._client.api_version)
[ "def", "is_closed", "(", "self", ")", "->", "Optional", "[", "bool", "]", ":", "# Check closed state with api version due to a protocol change", "return", "self", ".", "_state", ".", "is_closed", "(", "self", ".", "_client", ".", "api_version", ")" ]
[ 73, 4 ]
[ 76, 62 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.is_opening
(self)
Return if the cover is opening or not.
Return if the cover is opening or not.
def is_opening(self) -> bool: """Return if the cover is opening or not.""" return self._state.current_operation == CoverOperation.IS_OPENING
[ "def", "is_opening", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_state", ".", "current_operation", "==", "CoverOperation", ".", "IS_OPENING" ]
[ 79, 4 ]
[ 81, 73 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.is_closing
(self)
Return if the cover is closing or not.
Return if the cover is closing or not.
def is_closing(self) -> bool: """Return if the cover is closing or not.""" return self._state.current_operation == CoverOperation.IS_CLOSING
[ "def", "is_closing", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_state", ".", "current_operation", "==", "CoverOperation", ".", "IS_CLOSING" ]
[ 84, 4 ]
[ 86, 73 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.current_cover_position
(self)
Return current position of cover. 0 is closed, 100 is open.
Return current position of cover. 0 is closed, 100 is open.
def current_cover_position(self) -> Optional[int]: """Return current position of cover. 0 is closed, 100 is open.""" if not self._static_info.supports_position: return None return round(self._state.position * 100.0)
[ "def", "current_cover_position", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "if", "not", "self", ".", "_static_info", ".", "supports_position", ":", "return", "None", "return", "round", "(", "self", ".", "_state", ".", "position", "*", "100.0", ")" ]
[ 89, 4 ]
[ 93, 50 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.current_cover_tilt_position
(self)
Return current position of cover tilt. 0 is closed, 100 is open.
Return current position of cover tilt. 0 is closed, 100 is open.
def current_cover_tilt_position(self) -> Optional[float]: """Return current position of cover tilt. 0 is closed, 100 is open.""" if not self._static_info.supports_tilt: return None return self._state.tilt * 100.0
[ "def", "current_cover_tilt_position", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "not", "self", ".", "_static_info", ".", "supports_tilt", ":", "return", "None", "return", "self", ".", "_state", ".", "tilt", "*", "100.0" ]
[ 96, 4 ]
[ 100, 39 ]
python
en
['en', 'en', 'en']
True
EsphomeCover.async_open_cover
(self, **kwargs)
Open the cover.
Open the cover.
async def async_open_cover(self, **kwargs) -> None: """Open the cover.""" await self._client.cover_command(key=self._static_info.key, position=1.0)
[ "async", "def", "async_open_cover", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "await", "self", ".", "_client", ".", "cover_command", "(", "key", "=", "self", ".", "_static_info", ".", "key", ",", "position", "=", "1.0", ")" ]
[ 102, 4 ]
[ 104, 81 ]
python
en
['en', 'en', 'en']
True