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
NetatmoThermostat.async_added_to_hass
(self)
Entity created.
Entity created.
async def async_added_to_hass(self) -> None: """Entity created.""" await super().async_added_to_hass() for event_type in ( EVENT_TYPE_SET_POINT, EVENT_TYPE_THERM_MODE, EVENT_TYPE_CANCEL_SET_POINT, ): self._listeners.append( async_dispatcher_connect( self.hass, f"signal-{DOMAIN}-webhook-{event_type}", self.handle_event, ) )
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "for", "event_type", "in", "(", "EVENT_TYPE_SET_POINT", ",", "EVENT_TYPE_THERM_MODE", ",", "EVENT_TYPE_CANCEL_SET_POINT", ",", ")", ":", "self", ".", "_listeners", ".", "append", "(", "async_dispatcher_connect", "(", "self", ".", "hass", ",", "f\"signal-{DOMAIN}-webhook-{event_type}\"", ",", "self", ".", "handle_event", ",", ")", ")" ]
[ 220, 4 ]
[ 235, 13 ]
python
en
['en', 'sm', 'en']
False
NetatmoThermostat.handle_event
(self, event)
Handle webhook events.
Handle webhook events.
async def handle_event(self, event): """Handle webhook events.""" data = event["data"] if not data.get("home"): return home = data["home"] if self._home_id == home["id"] and data["event_type"] == EVENT_TYPE_THERM_MODE: self._preset = NETATMO_MAP_PRESET[home[EVENT_TYPE_THERM_MODE]] self._hvac_mode = HVAC_MAP_NETATMO[self._preset] if self._preset == PRESET_FROST_GUARD: self._target_temperature = self._hg_temperature elif self._preset == PRESET_AWAY: self._target_temperature = self._away_temperature elif self._preset == PRESET_SCHEDULE: self.async_update_callback() self.async_write_ha_state() return if not home.get("rooms"): return for room in home["rooms"]: if data["event_type"] == EVENT_TYPE_SET_POINT: if self._id == room["id"]: if room["therm_setpoint_mode"] == STATE_NETATMO_OFF: self._hvac_mode = HVAC_MODE_OFF elif room["therm_setpoint_mode"] == STATE_NETATMO_MAX: self._hvac_mode = HVAC_MODE_HEAT self._target_temperature = DEFAULT_MAX_TEMP else: self._target_temperature = room["therm_setpoint_temperature"] self.async_write_ha_state() break elif data["event_type"] == EVENT_TYPE_CANCEL_SET_POINT: if self._id == room["id"]: self.async_update_callback() self.async_write_ha_state() break
[ "async", "def", "handle_event", "(", "self", ",", "event", ")", ":", "data", "=", "event", "[", "\"data\"", "]", "if", "not", "data", ".", "get", "(", "\"home\"", ")", ":", "return", "home", "=", "data", "[", "\"home\"", "]", "if", "self", ".", "_home_id", "==", "home", "[", "\"id\"", "]", "and", "data", "[", "\"event_type\"", "]", "==", "EVENT_TYPE_THERM_MODE", ":", "self", ".", "_preset", "=", "NETATMO_MAP_PRESET", "[", "home", "[", "EVENT_TYPE_THERM_MODE", "]", "]", "self", ".", "_hvac_mode", "=", "HVAC_MAP_NETATMO", "[", "self", ".", "_preset", "]", "if", "self", ".", "_preset", "==", "PRESET_FROST_GUARD", ":", "self", ".", "_target_temperature", "=", "self", ".", "_hg_temperature", "elif", "self", ".", "_preset", "==", "PRESET_AWAY", ":", "self", ".", "_target_temperature", "=", "self", ".", "_away_temperature", "elif", "self", ".", "_preset", "==", "PRESET_SCHEDULE", ":", "self", ".", "async_update_callback", "(", ")", "self", ".", "async_write_ha_state", "(", ")", "return", "if", "not", "home", ".", "get", "(", "\"rooms\"", ")", ":", "return", "for", "room", "in", "home", "[", "\"rooms\"", "]", ":", "if", "data", "[", "\"event_type\"", "]", "==", "EVENT_TYPE_SET_POINT", ":", "if", "self", ".", "_id", "==", "room", "[", "\"id\"", "]", ":", "if", "room", "[", "\"therm_setpoint_mode\"", "]", "==", "STATE_NETATMO_OFF", ":", "self", ".", "_hvac_mode", "=", "HVAC_MODE_OFF", "elif", "room", "[", "\"therm_setpoint_mode\"", "]", "==", "STATE_NETATMO_MAX", ":", "self", ".", "_hvac_mode", "=", "HVAC_MODE_HEAT", "self", ".", "_target_temperature", "=", "DEFAULT_MAX_TEMP", "else", ":", "self", ".", "_target_temperature", "=", "room", "[", "\"therm_setpoint_temperature\"", "]", "self", ".", "async_write_ha_state", "(", ")", "break", "elif", "data", "[", "\"event_type\"", "]", "==", "EVENT_TYPE_CANCEL_SET_POINT", ":", "if", "self", ".", "_id", "==", "room", "[", "\"id\"", "]", ":", "self", ".", "async_update_callback", "(", ")", "self", ".", "async_write_ha_state", "(", ")", "break" ]
[ 237, 4 ]
[ 277, 25 ]
python
en
['eu', 'xh', 'en']
False
NetatmoThermostat.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self): """Return the list of supported features.""" return self._support_flags
[ "def", "supported_features", "(", "self", ")", ":", "return", "self", ".", "_support_flags" ]
[ 280, 4 ]
[ 282, 34 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 285, 4 ]
[ 287, 27 ]
python
en
['en', 'la', 'en']
True
NetatmoThermostat.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return self._current_temperature
[ "def", "current_temperature", "(", "self", ")", ":", "return", "self", ".", "_current_temperature" ]
[ 290, 4 ]
[ 292, 40 ]
python
en
['en', 'la', 'en']
True
NetatmoThermostat.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "_target_temperature" ]
[ 295, 4 ]
[ 297, 39 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.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 PRECISION_HALVES
[ "def", "target_temperature_step", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "PRECISION_HALVES" ]
[ 300, 4 ]
[ 302, 31 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.hvac_mode
(self)
Return hvac operation ie. heat, cool mode.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self): """Return hvac operation ie. heat, cool mode.""" return self._hvac_mode
[ "def", "hvac_mode", "(", "self", ")", ":", "return", "self", ".", "_hvac_mode" ]
[ 305, 4 ]
[ 307, 30 ]
python
bg
['en', 'bg', 'bg']
True
NetatmoThermostat.hvac_modes
(self)
Return the list of available hvac operation modes.
Return the list of available hvac operation modes.
def hvac_modes(self): """Return the list of available hvac operation modes.""" return self._operation_list
[ "def", "hvac_modes", "(", "self", ")", ":", "return", "self", ".", "_operation_list" ]
[ 310, 4 ]
[ 312, 35 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.hvac_action
(self)
Return the current running hvac operation if supported.
Return the current running hvac operation if supported.
def hvac_action(self) -> Optional[str]: """Return the current running hvac operation if supported.""" if self._model == NA_THERM and self._boilerstatus is not None: return CURRENT_HVAC_MAP_NETATMO[self._boilerstatus] # Maybe it is a valve if self._room_status and self._room_status.get("heating_power_request", 0) > 0: return CURRENT_HVAC_HEAT return CURRENT_HVAC_IDLE
[ "def", "hvac_action", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "_model", "==", "NA_THERM", "and", "self", ".", "_boilerstatus", "is", "not", "None", ":", "return", "CURRENT_HVAC_MAP_NETATMO", "[", "self", ".", "_boilerstatus", "]", "# Maybe it is a valve", "if", "self", ".", "_room_status", "and", "self", ".", "_room_status", ".", "get", "(", "\"heating_power_request\"", ",", "0", ")", ">", "0", ":", "return", "CURRENT_HVAC_HEAT", "return", "CURRENT_HVAC_IDLE" ]
[ 315, 4 ]
[ 322, 32 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.set_hvac_mode
(self, hvac_mode: str)
Set new target hvac mode.
Set new target hvac mode.
def set_hvac_mode(self, hvac_mode: str) -> None: """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_OFF: self.turn_off() elif hvac_mode == HVAC_MODE_AUTO: if self.hvac_mode == HVAC_MODE_OFF: self.turn_on() self.set_preset_mode(PRESET_SCHEDULE) elif hvac_mode == HVAC_MODE_HEAT: self.set_preset_mode(PRESET_BOOST)
[ "def", "set_hvac_mode", "(", "self", ",", "hvac_mode", ":", "str", ")", "->", "None", ":", "if", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "self", ".", "turn_off", "(", ")", "elif", "hvac_mode", "==", "HVAC_MODE_AUTO", ":", "if", "self", ".", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "self", ".", "turn_on", "(", ")", "self", ".", "set_preset_mode", "(", "PRESET_SCHEDULE", ")", "elif", "hvac_mode", "==", "HVAC_MODE_HEAT", ":", "self", ".", "set_preset_mode", "(", "PRESET_BOOST", ")" ]
[ 324, 4 ]
[ 333, 46 ]
python
da
['da', 'su', 'en']
False
NetatmoThermostat.set_preset_mode
(self, preset_mode: str)
Set new preset mode.
Set new preset mode.
def set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" if self.target_temperature == 0: self._home_status.set_room_thermpoint( self._id, STATE_NETATMO_HOME, ) if preset_mode in [PRESET_BOOST, STATE_NETATMO_MAX] and self._model == NA_VALVE: self._home_status.set_room_thermpoint( self._id, STATE_NETATMO_MANUAL, DEFAULT_MAX_TEMP, ) elif preset_mode in [PRESET_BOOST, STATE_NETATMO_MAX]: self._home_status.set_room_thermpoint( self._id, PRESET_MAP_NETATMO[preset_mode] ) elif preset_mode in [PRESET_SCHEDULE, PRESET_FROST_GUARD, PRESET_AWAY]: self._home_status.set_thermmode(PRESET_MAP_NETATMO[preset_mode]) else: _LOGGER.error("Preset mode '%s' not available", preset_mode) self.async_write_ha_state()
[ "def", "set_preset_mode", "(", "self", ",", "preset_mode", ":", "str", ")", "->", "None", ":", "if", "self", ".", "target_temperature", "==", "0", ":", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "STATE_NETATMO_HOME", ",", ")", "if", "preset_mode", "in", "[", "PRESET_BOOST", ",", "STATE_NETATMO_MAX", "]", "and", "self", ".", "_model", "==", "NA_VALVE", ":", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "STATE_NETATMO_MANUAL", ",", "DEFAULT_MAX_TEMP", ",", ")", "elif", "preset_mode", "in", "[", "PRESET_BOOST", ",", "STATE_NETATMO_MAX", "]", ":", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "PRESET_MAP_NETATMO", "[", "preset_mode", "]", ")", "elif", "preset_mode", "in", "[", "PRESET_SCHEDULE", ",", "PRESET_FROST_GUARD", ",", "PRESET_AWAY", "]", ":", "self", ".", "_home_status", ".", "set_thermmode", "(", "PRESET_MAP_NETATMO", "[", "preset_mode", "]", ")", "else", ":", "_LOGGER", ".", "error", "(", "\"Preset mode '%s' not available\"", ",", "preset_mode", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 335, 4 ]
[ 358, 35 ]
python
en
['en', 'sr', 'en']
True
NetatmoThermostat.preset_mode
(self)
Return the current preset mode, e.g., home, away, temp.
Return the current preset mode, e.g., home, away, temp.
def preset_mode(self) -> Optional[str]: """Return the current preset mode, e.g., home, away, temp.""" return self._preset
[ "def", "preset_mode", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_preset" ]
[ 361, 4 ]
[ 363, 27 ]
python
en
['en', 'pt', 'en']
True
NetatmoThermostat.preset_modes
(self)
Return a list of available preset modes.
Return a list of available preset modes.
def preset_modes(self) -> Optional[List[str]]: """Return a list of available preset modes.""" return SUPPORT_PRESET
[ "def", "preset_modes", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "return", "SUPPORT_PRESET" ]
[ 366, 4 ]
[ 368, 29 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.set_temperature
(self, **kwargs)
Set new target temperature for 2 hours.
Set new target temperature for 2 hours.
def set_temperature(self, **kwargs): """Set new target temperature for 2 hours.""" temp = kwargs.get(ATTR_TEMPERATURE) if temp is None: return self._home_status.set_room_thermpoint(self._id, STATE_NETATMO_MANUAL, temp) self.async_write_ha_state()
[ "def", "set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "temp", "=", "kwargs", ".", "get", "(", "ATTR_TEMPERATURE", ")", "if", "temp", "is", "None", ":", "return", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "STATE_NETATMO_MANUAL", ",", "temp", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 370, 4 ]
[ 377, 35 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.device_state_attributes
(self)
Return the state attributes of the thermostat.
Return the state attributes of the thermostat.
def device_state_attributes(self): """Return the state attributes of the thermostat.""" attr = {} if self._battery_level is not None: attr[ATTR_BATTERY_LEVEL] = self._battery_level if self._model == NA_VALVE: attr[ATTR_HEATING_POWER_REQUEST] = self._room_status.get( "heating_power_request", 0 ) return attr
[ "def", "device_state_attributes", "(", "self", ")", ":", "attr", "=", "{", "}", "if", "self", ".", "_battery_level", "is", "not", "None", ":", "attr", "[", "ATTR_BATTERY_LEVEL", "]", "=", "self", ".", "_battery_level", "if", "self", ".", "_model", "==", "NA_VALVE", ":", "attr", "[", "ATTR_HEATING_POWER_REQUEST", "]", "=", "self", ".", "_room_status", ".", "get", "(", "\"heating_power_request\"", ",", "0", ")", "return", "attr" ]
[ 380, 4 ]
[ 392, 19 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.turn_off
(self)
Turn the entity off.
Turn the entity off.
def turn_off(self): """Turn the entity off.""" if self._model == NA_VALVE: self._home_status.set_room_thermpoint( self._id, STATE_NETATMO_MANUAL, DEFAULT_MIN_TEMP, ) elif self.hvac_mode != HVAC_MODE_OFF: self._home_status.set_room_thermpoint(self._id, STATE_NETATMO_OFF) self.async_write_ha_state()
[ "def", "turn_off", "(", "self", ")", ":", "if", "self", ".", "_model", "==", "NA_VALVE", ":", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "STATE_NETATMO_MANUAL", ",", "DEFAULT_MIN_TEMP", ",", ")", "elif", "self", ".", "hvac_mode", "!=", "HVAC_MODE_OFF", ":", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "STATE_NETATMO_OFF", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 394, 4 ]
[ 404, 35 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.turn_on
(self)
Turn the entity on.
Turn the entity on.
def turn_on(self): """Turn the entity on.""" self._home_status.set_room_thermpoint(self._id, STATE_NETATMO_HOME) self.async_write_ha_state()
[ "def", "turn_on", "(", "self", ")", ":", "self", ".", "_home_status", ".", "set_room_thermpoint", "(", "self", ".", "_id", ",", "STATE_NETATMO_HOME", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 406, 4 ]
[ 409, 35 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.available
(self)
If the device hasn't been able to connect, mark as unavailable.
If the device hasn't been able to connect, mark as unavailable.
def available(self) -> bool: """If the device hasn't been able to connect, mark as unavailable.""" return bool(self._connected)
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "_connected", ")" ]
[ 412, 4 ]
[ 414, 36 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat.async_update_callback
(self)
Update the entity's state.
Update the entity's state.
def async_update_callback(self): """Update the entity's state.""" self._home_status = self.data_handler.data[self._home_status_class] self._room_status = self._home_status.rooms.get(self._id) self._room_data = self._data.rooms.get(self._home_id, {}).get(self._id) if not self._room_status or not self._room_data: if self._connected: _LOGGER.info( "The thermostat in room %s seems to be out of reach", self._device_name, ) self._connected = False return roomstatus = {"roomID": self._room_status.get("id", {})} if self._room_status.get("reachable"): roomstatus.update(self._build_room_status()) self._away_temperature = self._data.get_away_temp(self._home_id) self._hg_temperature = self._data.get_hg_temp(self._home_id) self._setpoint_duration = self._data.setpoint_duration[self._home_id] if "current_temperature" not in roomstatus: return if self._model is None: self._model = roomstatus["module_type"] self._current_temperature = roomstatus["current_temperature"] self._target_temperature = roomstatus["target_temperature"] self._preset = NETATMO_MAP_PRESET[roomstatus["setpoint_mode"]] self._hvac_mode = HVAC_MAP_NETATMO[self._preset] self._battery_level = roomstatus.get("battery_level") self._connected = True self._away = self._hvac_mode == HVAC_MAP_NETATMO[STATE_NETATMO_AWAY]
[ "def", "async_update_callback", "(", "self", ")", ":", "self", ".", "_home_status", "=", "self", ".", "data_handler", ".", "data", "[", "self", ".", "_home_status_class", "]", "self", ".", "_room_status", "=", "self", ".", "_home_status", ".", "rooms", ".", "get", "(", "self", ".", "_id", ")", "self", ".", "_room_data", "=", "self", ".", "_data", ".", "rooms", ".", "get", "(", "self", ".", "_home_id", ",", "{", "}", ")", ".", "get", "(", "self", ".", "_id", ")", "if", "not", "self", ".", "_room_status", "or", "not", "self", ".", "_room_data", ":", "if", "self", ".", "_connected", ":", "_LOGGER", ".", "info", "(", "\"The thermostat in room %s seems to be out of reach\"", ",", "self", ".", "_device_name", ",", ")", "self", ".", "_connected", "=", "False", "return", "roomstatus", "=", "{", "\"roomID\"", ":", "self", ".", "_room_status", ".", "get", "(", "\"id\"", ",", "{", "}", ")", "}", "if", "self", ".", "_room_status", ".", "get", "(", "\"reachable\"", ")", ":", "roomstatus", ".", "update", "(", "self", ".", "_build_room_status", "(", ")", ")", "self", ".", "_away_temperature", "=", "self", ".", "_data", ".", "get_away_temp", "(", "self", ".", "_home_id", ")", "self", ".", "_hg_temperature", "=", "self", ".", "_data", ".", "get_hg_temp", "(", "self", ".", "_home_id", ")", "self", ".", "_setpoint_duration", "=", "self", ".", "_data", ".", "setpoint_duration", "[", "self", ".", "_home_id", "]", "if", "\"current_temperature\"", "not", "in", "roomstatus", ":", "return", "if", "self", ".", "_model", "is", "None", ":", "self", ".", "_model", "=", "roomstatus", "[", "\"module_type\"", "]", "self", ".", "_current_temperature", "=", "roomstatus", "[", "\"current_temperature\"", "]", "self", ".", "_target_temperature", "=", "roomstatus", "[", "\"target_temperature\"", "]", "self", ".", "_preset", "=", "NETATMO_MAP_PRESET", "[", "roomstatus", "[", "\"setpoint_mode\"", "]", "]", "self", ".", "_hvac_mode", "=", "HVAC_MAP_NETATMO", "[", "self", ".", "_preset", "]", "self", ".", "_battery_level", "=", "roomstatus", ".", "get", "(", "\"battery_level\"", ")", "self", ".", "_connected", "=", "True", "self", ".", "_away", "=", "self", ".", "_hvac_mode", "==", "HVAC_MAP_NETATMO", "[", "STATE_NETATMO_AWAY", "]" ]
[ 417, 4 ]
[ 453, 76 ]
python
en
['en', 'en', 'en']
True
NetatmoThermostat._build_room_status
(self)
Construct room status.
Construct room status.
def _build_room_status(self): """Construct room status.""" try: roomstatus = { "roomname": self._room_data["name"], "target_temperature": self._room_status["therm_setpoint_temperature"], "setpoint_mode": self._room_status["therm_setpoint_mode"], "current_temperature": self._room_status["therm_measured_temperature"], "module_type": self._data.get_thermostat_type( home_id=self._home_id, room_id=self._id ), "module_id": None, "heating_status": None, "heating_power_request": None, } batterylevel = None for module_id in self._room_data["module_ids"]: if ( self._data.modules[self._home_id][module_id]["type"] == NA_THERM or roomstatus["module_id"] is None ): roomstatus["module_id"] = module_id if roomstatus["module_type"] == NA_THERM: self._boilerstatus = self._home_status.boiler_status( roomstatus["module_id"] ) roomstatus["heating_status"] = self._boilerstatus batterylevel = self._home_status.thermostats[ roomstatus["module_id"] ].get("battery_level") elif roomstatus["module_type"] == NA_VALVE: roomstatus["heating_power_request"] = self._room_status[ "heating_power_request" ] roomstatus["heating_status"] = roomstatus["heating_power_request"] > 0 if self._boilerstatus is not None: roomstatus["heating_status"] = ( self._boilerstatus and roomstatus["heating_status"] ) batterylevel = self._home_status.valves[roomstatus["module_id"]].get( "battery_level" ) if batterylevel: batterypct = interpolate(batterylevel, roomstatus["module_type"]) if ( not roomstatus.get("battery_level") or batterypct < roomstatus["battery_level"] ): roomstatus["battery_level"] = batterypct return roomstatus except KeyError as err: _LOGGER.error("Update of room %s failed. Error: %s", self._id, err) return {}
[ "def", "_build_room_status", "(", "self", ")", ":", "try", ":", "roomstatus", "=", "{", "\"roomname\"", ":", "self", ".", "_room_data", "[", "\"name\"", "]", ",", "\"target_temperature\"", ":", "self", ".", "_room_status", "[", "\"therm_setpoint_temperature\"", "]", ",", "\"setpoint_mode\"", ":", "self", ".", "_room_status", "[", "\"therm_setpoint_mode\"", "]", ",", "\"current_temperature\"", ":", "self", ".", "_room_status", "[", "\"therm_measured_temperature\"", "]", ",", "\"module_type\"", ":", "self", ".", "_data", ".", "get_thermostat_type", "(", "home_id", "=", "self", ".", "_home_id", ",", "room_id", "=", "self", ".", "_id", ")", ",", "\"module_id\"", ":", "None", ",", "\"heating_status\"", ":", "None", ",", "\"heating_power_request\"", ":", "None", ",", "}", "batterylevel", "=", "None", "for", "module_id", "in", "self", ".", "_room_data", "[", "\"module_ids\"", "]", ":", "if", "(", "self", ".", "_data", ".", "modules", "[", "self", ".", "_home_id", "]", "[", "module_id", "]", "[", "\"type\"", "]", "==", "NA_THERM", "or", "roomstatus", "[", "\"module_id\"", "]", "is", "None", ")", ":", "roomstatus", "[", "\"module_id\"", "]", "=", "module_id", "if", "roomstatus", "[", "\"module_type\"", "]", "==", "NA_THERM", ":", "self", ".", "_boilerstatus", "=", "self", ".", "_home_status", ".", "boiler_status", "(", "roomstatus", "[", "\"module_id\"", "]", ")", "roomstatus", "[", "\"heating_status\"", "]", "=", "self", ".", "_boilerstatus", "batterylevel", "=", "self", ".", "_home_status", ".", "thermostats", "[", "roomstatus", "[", "\"module_id\"", "]", "]", ".", "get", "(", "\"battery_level\"", ")", "elif", "roomstatus", "[", "\"module_type\"", "]", "==", "NA_VALVE", ":", "roomstatus", "[", "\"heating_power_request\"", "]", "=", "self", ".", "_room_status", "[", "\"heating_power_request\"", "]", "roomstatus", "[", "\"heating_status\"", "]", "=", "roomstatus", "[", "\"heating_power_request\"", "]", ">", "0", "if", "self", ".", "_boilerstatus", "is", "not", "None", ":", "roomstatus", "[", "\"heating_status\"", "]", "=", "(", "self", ".", "_boilerstatus", "and", "roomstatus", "[", "\"heating_status\"", "]", ")", "batterylevel", "=", "self", ".", "_home_status", ".", "valves", "[", "roomstatus", "[", "\"module_id\"", "]", "]", ".", "get", "(", "\"battery_level\"", ")", "if", "batterylevel", ":", "batterypct", "=", "interpolate", "(", "batterylevel", ",", "roomstatus", "[", "\"module_type\"", "]", ")", "if", "(", "not", "roomstatus", ".", "get", "(", "\"battery_level\"", ")", "or", "batterypct", "<", "roomstatus", "[", "\"battery_level\"", "]", ")", ":", "roomstatus", "[", "\"battery_level\"", "]", "=", "batterypct", "return", "roomstatus", "except", "KeyError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Update of room %s failed. Error: %s\"", ",", "self", ".", "_id", ",", "err", ")", "return", "{", "}" ]
[ 455, 4 ]
[ 512, 17 ]
python
en
['sv', 'la', 'en']
False
due_in_minutes
(timestamp)
Get the time in minutes from a timestamp. The timestamp should be in the format day.month.year hour:minute
Get the time in minutes from a timestamp.
def due_in_minutes(timestamp): """Get the time in minutes from a timestamp. The timestamp should be in the format day.month.year hour:minute """ diff = datetime.strptime(timestamp, "%d.%m.%y %H:%M") - dt_util.now().replace( tzinfo=None ) return int(diff.total_seconds() // 60)
[ "def", "due_in_minutes", "(", "timestamp", ")", ":", "diff", "=", "datetime", ".", "strptime", "(", "timestamp", ",", "\"%d.%m.%y %H:%M\"", ")", "-", "dt_util", ".", "now", "(", ")", ".", "replace", "(", "tzinfo", "=", "None", ")", "return", "int", "(", "diff", ".", "total_seconds", "(", ")", "//", "60", ")" ]
[ 63, 0 ]
[ 72, 42 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_devices, discovery_info=None)
Set up the Rejseplanen transport sensor.
Set up the Rejseplanen transport sensor.
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Rejseplanen transport sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route = config.get(CONF_ROUTE) direction = config[CONF_DIRECTION] departure_type = config[CONF_DEPARTURE_TYPE] data = PublicTransportData(stop_id, route, direction, departure_type) add_devices( [RejseplanenTransportSensor(data, stop_id, route, direction, name)], True )
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_devices", ",", "discovery_info", "=", "None", ")", ":", "name", "=", "config", "[", "CONF_NAME", "]", "stop_id", "=", "config", "[", "CONF_STOP_ID", "]", "route", "=", "config", ".", "get", "(", "CONF_ROUTE", ")", "direction", "=", "config", "[", "CONF_DIRECTION", "]", "departure_type", "=", "config", "[", "CONF_DEPARTURE_TYPE", "]", "data", "=", "PublicTransportData", "(", "stop_id", ",", "route", ",", "direction", ",", "departure_type", ")", "add_devices", "(", "[", "RejseplanenTransportSensor", "(", "data", ",", "stop_id", ",", "route", ",", "direction", ",", "name", ")", "]", ",", "True", ")" ]
[ 75, 0 ]
[ 86, 5 ]
python
da
['en', 'da', 'pt']
False
RejseplanenTransportSensor.__init__
(self, data, stop_id, route, direction, name)
Initialize the sensor.
Initialize the sensor.
def __init__(self, data, stop_id, route, direction, name): """Initialize the sensor.""" self.data = data self._name = name self._stop_id = stop_id self._route = route self._direction = direction self._times = self._state = None
[ "def", "__init__", "(", "self", ",", "data", ",", "stop_id", ",", "route", ",", "direction", ",", "name", ")", ":", "self", ".", "data", "=", "data", "self", ".", "_name", "=", "name", "self", ".", "_stop_id", "=", "stop_id", "self", ".", "_route", "=", "route", "self", ".", "_direction", "=", "direction", "self", ".", "_times", "=", "self", ".", "_state", "=", "None" ]
[ 92, 4 ]
[ 99, 40 ]
python
en
['en', 'en', 'en']
True
RejseplanenTransportSensor.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" ]
[ 102, 4 ]
[ 104, 25 ]
python
en
['en', 'mi', 'en']
True
RejseplanenTransportSensor.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" ]
[ 107, 4 ]
[ 109, 26 ]
python
en
['en', 'en', 'en']
True
RejseplanenTransportSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" if not self._times: return {ATTR_STOP_ID: self._stop_id, ATTR_ATTRIBUTION: ATTRIBUTION} next_up = [] if len(self._times) > 1: next_up = self._times[1:] attributes = { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_NEXT_UP: next_up, ATTR_STOP_ID: self._stop_id, } if self._times[0] is not None: attributes.update(self._times[0]) return attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "if", "not", "self", ".", "_times", ":", "return", "{", "ATTR_STOP_ID", ":", "self", ".", "_stop_id", ",", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", "}", "next_up", "=", "[", "]", "if", "len", "(", "self", ".", "_times", ")", ">", "1", ":", "next_up", "=", "self", ".", "_times", "[", "1", ":", "]", "attributes", "=", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "ATTR_NEXT_UP", ":", "next_up", ",", "ATTR_STOP_ID", ":", "self", ".", "_stop_id", ",", "}", "if", "self", ".", "_times", "[", "0", "]", "is", "not", "None", ":", "attributes", ".", "update", "(", "self", ".", "_times", "[", "0", "]", ")", "return", "attributes" ]
[ 112, 4 ]
[ 130, 25 ]
python
en
['en', 'en', 'en']
True
RejseplanenTransportSensor.unit_of_measurement
(self)
Return the unit this state is expressed in.
Return the unit this state is expressed in.
def unit_of_measurement(self): """Return the unit this state is expressed in.""" return TIME_MINUTES
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "TIME_MINUTES" ]
[ 133, 4 ]
[ 135, 27 ]
python
en
['en', 'en', 'en']
True
RejseplanenTransportSensor.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" ]
[ 138, 4 ]
[ 140, 19 ]
python
en
['en', 'en', 'en']
True
RejseplanenTransportSensor.update
(self)
Get the latest data from rejseplanen.dk and update the states.
Get the latest data from rejseplanen.dk and update the states.
def update(self): """Get the latest data from rejseplanen.dk and update the states.""" self.data.update() self._times = self.data.info if not self._times: self._state = None else: try: self._state = self._times[0][ATTR_DUE_IN] except TypeError: pass
[ "def", "update", "(", "self", ")", ":", "self", ".", "data", ".", "update", "(", ")", "self", ".", "_times", "=", "self", ".", "data", ".", "info", "if", "not", "self", ".", "_times", ":", "self", ".", "_state", "=", "None", "else", ":", "try", ":", "self", ".", "_state", "=", "self", ".", "_times", "[", "0", "]", "[", "ATTR_DUE_IN", "]", "except", "TypeError", ":", "pass" ]
[ 142, 4 ]
[ 153, 20 ]
python
en
['en', 'en', 'en']
True
PublicTransportData.__init__
(self, stop_id, route, direction, departure_type)
Initialize the data object.
Initialize the data object.
def __init__(self, stop_id, route, direction, departure_type): """Initialize the data object.""" self.stop_id = stop_id self.route = route self.direction = direction self.departure_type = departure_type self.info = []
[ "def", "__init__", "(", "self", ",", "stop_id", ",", "route", ",", "direction", ",", "departure_type", ")", ":", "self", ".", "stop_id", "=", "stop_id", "self", ".", "route", "=", "route", "self", ".", "direction", "=", "direction", "self", ".", "departure_type", "=", "departure_type", "self", ".", "info", "=", "[", "]" ]
[ 159, 4 ]
[ 165, 22 ]
python
en
['en', 'en', 'en']
True
PublicTransportData.update
(self)
Get the latest data from rejseplanen.
Get the latest data from rejseplanen.
def update(self): """Get the latest data from rejseplanen.""" self.info = [] def intersection(lst1, lst2): """Return items contained in both lists.""" return list(set(lst1) & set(lst2)) # Limit search to selected types, to get more results all_types = not bool(self.departure_type) use_train = all_types or bool(intersection(TRAIN_TYPES, self.departure_type)) use_bus = all_types or bool(intersection(BUS_TYPES, self.departure_type)) use_metro = all_types or bool(intersection(METRO_TYPES, self.departure_type)) try: results = rjpl.departureBoard( int(self.stop_id), timeout=5, useTrain=use_train, useBus=use_bus, useMetro=use_metro, ) except rjpl.rjplAPIError as error: _LOGGER.debug("API returned error: %s", error) return except (rjpl.rjplConnectionError, rjpl.rjplHTTPError): _LOGGER.debug("Error occurred while connecting to the API") return # Filter result results = [d for d in results if "cancelled" not in d] if self.route: results = [d for d in results if d["name"] in self.route] if self.direction: results = [d for d in results if d["direction"] in self.direction] if self.departure_type: results = [d for d in results if d["type"] in self.departure_type] for item in results: route = item.get("name") scheduled_date = item.get("date") scheduled_time = item.get("time") real_time_date = due_at_date = item.get("rtDate") real_time_time = due_at_time = item.get("rtTime") if due_at_date is None: due_at_date = scheduled_date if due_at_time is None: due_at_time = scheduled_time if ( due_at_date is not None and due_at_time is not None and route is not None ): due_at = f"{due_at_date} {due_at_time}" scheduled_at = f"{scheduled_date} {scheduled_time}" departure_data = { ATTR_DIRECTION: item.get("direction"), ATTR_DUE_IN: due_in_minutes(due_at), ATTR_DUE_AT: due_at, ATTR_FINAL_STOP: item.get("finalStop"), ATTR_ROUTE: route, ATTR_SCHEDULED_AT: scheduled_at, ATTR_STOP_NAME: item.get("stop"), ATTR_TYPE: item.get("type"), } if real_time_date is not None and real_time_time is not None: departure_data[ ATTR_REAL_TIME_AT ] = f"{real_time_date} {real_time_time}" if item.get("rtTrack") is not None: departure_data[ATTR_TRACK] = item.get("rtTrack") self.info.append(departure_data) if not self.info: _LOGGER.debug("No departures with given parameters") # Sort the data by time self.info = sorted(self.info, key=itemgetter(ATTR_DUE_IN))
[ "def", "update", "(", "self", ")", ":", "self", ".", "info", "=", "[", "]", "def", "intersection", "(", "lst1", ",", "lst2", ")", ":", "\"\"\"Return items contained in both lists.\"\"\"", "return", "list", "(", "set", "(", "lst1", ")", "&", "set", "(", "lst2", ")", ")", "# Limit search to selected types, to get more results", "all_types", "=", "not", "bool", "(", "self", ".", "departure_type", ")", "use_train", "=", "all_types", "or", "bool", "(", "intersection", "(", "TRAIN_TYPES", ",", "self", ".", "departure_type", ")", ")", "use_bus", "=", "all_types", "or", "bool", "(", "intersection", "(", "BUS_TYPES", ",", "self", ".", "departure_type", ")", ")", "use_metro", "=", "all_types", "or", "bool", "(", "intersection", "(", "METRO_TYPES", ",", "self", ".", "departure_type", ")", ")", "try", ":", "results", "=", "rjpl", ".", "departureBoard", "(", "int", "(", "self", ".", "stop_id", ")", ",", "timeout", "=", "5", ",", "useTrain", "=", "use_train", ",", "useBus", "=", "use_bus", ",", "useMetro", "=", "use_metro", ",", ")", "except", "rjpl", ".", "rjplAPIError", "as", "error", ":", "_LOGGER", ".", "debug", "(", "\"API returned error: %s\"", ",", "error", ")", "return", "except", "(", "rjpl", ".", "rjplConnectionError", ",", "rjpl", ".", "rjplHTTPError", ")", ":", "_LOGGER", ".", "debug", "(", "\"Error occurred while connecting to the API\"", ")", "return", "# Filter result", "results", "=", "[", "d", "for", "d", "in", "results", "if", "\"cancelled\"", "not", "in", "d", "]", "if", "self", ".", "route", ":", "results", "=", "[", "d", "for", "d", "in", "results", "if", "d", "[", "\"name\"", "]", "in", "self", ".", "route", "]", "if", "self", ".", "direction", ":", "results", "=", "[", "d", "for", "d", "in", "results", "if", "d", "[", "\"direction\"", "]", "in", "self", ".", "direction", "]", "if", "self", ".", "departure_type", ":", "results", "=", "[", "d", "for", "d", "in", "results", "if", "d", "[", "\"type\"", "]", "in", "self", ".", "departure_type", "]", "for", "item", "in", "results", ":", "route", "=", "item", ".", "get", "(", "\"name\"", ")", "scheduled_date", "=", "item", ".", "get", "(", "\"date\"", ")", "scheduled_time", "=", "item", ".", "get", "(", "\"time\"", ")", "real_time_date", "=", "due_at_date", "=", "item", ".", "get", "(", "\"rtDate\"", ")", "real_time_time", "=", "due_at_time", "=", "item", ".", "get", "(", "\"rtTime\"", ")", "if", "due_at_date", "is", "None", ":", "due_at_date", "=", "scheduled_date", "if", "due_at_time", "is", "None", ":", "due_at_time", "=", "scheduled_time", "if", "(", "due_at_date", "is", "not", "None", "and", "due_at_time", "is", "not", "None", "and", "route", "is", "not", "None", ")", ":", "due_at", "=", "f\"{due_at_date} {due_at_time}\"", "scheduled_at", "=", "f\"{scheduled_date} {scheduled_time}\"", "departure_data", "=", "{", "ATTR_DIRECTION", ":", "item", ".", "get", "(", "\"direction\"", ")", ",", "ATTR_DUE_IN", ":", "due_in_minutes", "(", "due_at", ")", ",", "ATTR_DUE_AT", ":", "due_at", ",", "ATTR_FINAL_STOP", ":", "item", ".", "get", "(", "\"finalStop\"", ")", ",", "ATTR_ROUTE", ":", "route", ",", "ATTR_SCHEDULED_AT", ":", "scheduled_at", ",", "ATTR_STOP_NAME", ":", "item", ".", "get", "(", "\"stop\"", ")", ",", "ATTR_TYPE", ":", "item", ".", "get", "(", "\"type\"", ")", ",", "}", "if", "real_time_date", "is", "not", "None", "and", "real_time_time", "is", "not", "None", ":", "departure_data", "[", "ATTR_REAL_TIME_AT", "]", "=", "f\"{real_time_date} {real_time_time}\"", "if", "item", ".", "get", "(", "\"rtTrack\"", ")", "is", "not", "None", ":", "departure_data", "[", "ATTR_TRACK", "]", "=", "item", ".", "get", "(", "\"rtTrack\"", ")", "self", ".", "info", ".", "append", "(", "departure_data", ")", "if", "not", "self", ".", "info", ":", "_LOGGER", ".", "debug", "(", "\"No departures with given parameters\"", ")", "# Sort the data by time", "self", ".", "info", "=", "sorted", "(", "self", ".", "info", ",", "key", "=", "itemgetter", "(", "ATTR_DUE_IN", ")", ")" ]
[ 167, 4 ]
[ 250, 66 ]
python
en
['en', 'en', 'en']
True
get_pairs
(word)
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings)
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings)
def get_pairs(word): """ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings) """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
[ "def", "get_pairs", "(", "word", ")", ":", "pairs", "=", "set", "(", ")", "prev_char", "=", "word", "[", "0", "]", "for", "char", "in", "word", "[", "1", ":", "]", ":", "pairs", ".", "add", "(", "(", "prev_char", ",", "char", ")", ")", "prev_char", "=", "char", "return", "pairs" ]
[ 58, 0 ]
[ 68, 16 ]
python
en
['en', 'error', 'th']
False
replace_unicode_punct
(text)
Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
def replace_unicode_punct(text): """ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl """ text = text.replace(",", ",") text = re.sub(r"。\s*", ". ", text) text = text.replace("、", ",") text = text.replace("”", '"') text = text.replace("“", '"') text = text.replace("∶", ":") text = text.replace(":", ":") text = text.replace("?", "?") text = text.replace("《", '"') text = text.replace("》", '"') text = text.replace(")", ")") text = text.replace("!", "!") text = text.replace("(", "(") text = text.replace(";", ";") text = text.replace("1", "1") text = text.replace("」", '"') text = text.replace("「", '"') text = text.replace("0", "0") text = text.replace("3", "3") text = text.replace("2", "2") text = text.replace("5", "5") text = text.replace("6", "6") text = text.replace("9", "9") text = text.replace("7", "7") text = text.replace("8", "8") text = text.replace("4", "4") text = re.sub(r".\s*", ". ", text) text = text.replace("~", "~") text = text.replace("’", "'") text = text.replace("…", "...") text = text.replace("━", "-") text = text.replace("〈", "<") text = text.replace("〉", ">") text = text.replace("【", "[") text = text.replace("】", "]") text = text.replace("%", "%") return text
[ "def", "replace_unicode_punct", "(", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "\",\", ", "\"", "\")", "", "text", "=", "re", ".", "sub", "(", "r\"。\\s*\", ", "\"", " \", ", "t", "xt)", "", "text", "=", "text", ".", "replace", "(", "\"、\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"”\", ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "\"“\", ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "\"∶\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\":\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"?\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"《\", ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "\"》\", ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "\")\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"!\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"(\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\";\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"1\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"」\", ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "\"「\", ", "'", "')", "", "text", "=", "text", ".", "replace", "(", "\"0\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"3\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"2\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"5\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"6\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"9\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"7\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"8\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"4\", ", "\"", "\")", "", "text", "=", "re", ".", "sub", "(", "r\".\\s*\", ", "\"", " \", ", "t", "xt)", "", "text", "=", "text", ".", "replace", "(", "\"~\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"’\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"…\", ", "\"", "..\")", "", "text", "=", "text", ".", "replace", "(", "\"━\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"〈\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"〉\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"【\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"】\", ", "\"", "\")", "", "text", "=", "text", ".", "replace", "(", "\"%\", ", "\"", "\")", "", "return", "text" ]
[ 71, 0 ]
[ 111, 15 ]
python
en
['en', 'error', 'th']
False
remove_non_printing_char
(text)
Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
def remove_non_printing_char(text): """ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl """ output = [] for char in text: cat = unicodedata.category(char) if cat.startswith("C"): continue output.append(char) return "".join(output)
[ "def", "remove_non_printing_char", "(", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cat", "=", "unicodedata", ".", "category", "(", "char", ")", "if", "cat", ".", "startswith", "(", "\"C\"", ")", ":", "continue", "output", ".", "append", "(", "char", ")", "return", "\"\"", ".", "join", "(", "output", ")" ]
[ 114, 0 ]
[ 124, 26 ]
python
en
['en', 'error', 'th']
False
FSMTTokenizer._tokenize
(self, text, lang="en", bypass_tokenizer=False)
Tokenize a string given language code using Moses. Details of tokenization: - [sacremoses](https://github.com/alvations/sacremoses): port of Moses - Install with `pip install sacremoses` Args: - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported languages. However, we don't enforce it. - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False) (bool). If True, we only apply BPE. Returns: List of tokens.
Tokenize a string given language code using Moses.
def _tokenize(self, text, lang="en", bypass_tokenizer=False): """ Tokenize a string given language code using Moses. Details of tokenization: - [sacremoses](https://github.com/alvations/sacremoses): port of Moses - Install with `pip install sacremoses` Args: - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported languages. However, we don't enforce it. - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False) (bool). If True, we only apply BPE. Returns: List of tokens. """ # ignore `lang` which is currently isn't explicitly passed in tokenization_utils.py and always results in lang=en # if lang != self.src_lang: # raise ValueError(f"Expected lang={self.src_lang}, but got {lang}") lang = self.src_lang if self.do_lower_case: text = text.lower() if bypass_tokenizer: text = text.split() else: text = self.moses_pipeline(text, lang=lang) text = self.moses_tokenize(text, lang=lang) split_tokens = [] for token in text: if token: split_tokens.extend([t for t in self.bpe(token).split(" ")]) return split_tokens
[ "def", "_tokenize", "(", "self", ",", "text", ",", "lang", "=", "\"en\"", ",", "bypass_tokenizer", "=", "False", ")", ":", "# ignore `lang` which is currently isn't explicitly passed in tokenization_utils.py and always results in lang=en", "# if lang != self.src_lang:", "# raise ValueError(f\"Expected lang={self.src_lang}, but got {lang}\")", "lang", "=", "self", ".", "src_lang", "if", "self", ".", "do_lower_case", ":", "text", "=", "text", ".", "lower", "(", ")", "if", "bypass_tokenizer", ":", "text", "=", "text", ".", "split", "(", ")", "else", ":", "text", "=", "self", ".", "moses_pipeline", "(", "text", ",", "lang", "=", "lang", ")", "text", "=", "self", ".", "moses_tokenize", "(", "text", ",", "lang", "=", "lang", ")", "split_tokens", "=", "[", "]", "for", "token", "in", "text", ":", "if", "token", ":", "split_tokens", ".", "extend", "(", "[", "t", "for", "t", "in", "self", ".", "bpe", "(", "token", ")", ".", "split", "(", "\" \"", ")", "]", ")", "return", "split_tokens" ]
[ 335, 4 ]
[ 373, 27 ]
python
en
['en', 'error', 'th']
False
FSMTTokenizer._convert_token_to_id
(self, token)
Converts a token (str) in an id using the vocab.
Converts a token (str) in an id using the vocab.
def _convert_token_to_id(self, token): """ Converts a token (str) in an id using the vocab. """ return self.encoder.get(token, self.encoder.get(self.unk_token))
[ "def", "_convert_token_to_id", "(", "self", ",", "token", ")", ":", "return", "self", ".", "encoder", ".", "get", "(", "token", ",", "self", ".", "encoder", ".", "get", "(", "self", ".", "unk_token", ")", ")" ]
[ 375, 4 ]
[ 377, 72 ]
python
en
['en', 'en', 'en']
True
FSMTTokenizer._convert_id_to_token
(self, index)
Converts an index (integer) in a token (str) using the vocab.
Converts an index (integer) in a token (str) using the vocab.
def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" return self.decoder.get(index, self.unk_token)
[ "def", "_convert_id_to_token", "(", "self", ",", "index", ")", ":", "return", "self", ".", "decoder", ".", "get", "(", "index", ",", "self", ".", "unk_token", ")" ]
[ 379, 4 ]
[ 381, 54 ]
python
en
['en', 'en', 'en']
True
FSMTTokenizer.convert_tokens_to_string
(self, tokens)
Converts a sequence of tokens (string) in a single string.
Converts a sequence of tokens (string) in a single string.
def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. """ # remove BPE tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens] tokens = "".join(tokens).split() # detokenize text = self.moses_detokenize(tokens, self.tgt_lang) return text
[ "def", "convert_tokens_to_string", "(", "self", ",", "tokens", ")", ":", "# remove BPE", "tokens", "=", "[", "t", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ".", "replace", "(", "\"</w>\"", ",", "\" \"", ")", "for", "t", "in", "tokens", "]", "tokens", "=", "\"\"", ".", "join", "(", "tokens", ")", ".", "split", "(", ")", "# detokenize", "text", "=", "self", ".", "moses_detokenize", "(", "tokens", ",", "self", ".", "tgt_lang", ")", "return", "text" ]
[ 383, 4 ]
[ 391, 19 ]
python
en
['en', 'en', 'en']
True
FSMTTokenizer.build_inputs_with_special_tokens
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A FAIRSEQ Transformer sequence has the following format: - single sequence: ``<s> X </s>`` - pair of sequences: ``<s> A </s> B </s>`` Args: token_ids_0 (:obj:`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A FAIRSEQ Transformer sequence has the following format:
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A FAIRSEQ Transformer sequence has the following format: - single sequence: ``<s> X </s>`` - pair of sequences: ``<s> A </s> B </s>`` Args: token_ids_0 (:obj:`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens. """ sep = [self.sep_token_id] # no bos used in fairseq if token_ids_1 is None: return token_ids_0 + sep return token_ids_0 + sep + token_ids_1 + sep
[ "def", "build_inputs_with_special_tokens", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "sep", "=", "[", "self", ".", "sep_token_id", "]", "# no bos used in fairseq", "if", "token_ids_1", "is", "None", ":", "return", "token_ids_0", "+", "sep", "return", "token_ids_0", "+", "sep", "+", "token_ids_1", "+", "sep" ]
[ 393, 4 ]
[ 417, 52 ]
python
en
['en', 'error', 'th']
False
FSMTTokenizer.get_special_tokens_mask
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False )
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the token list is already formatted with special tokens for the model. Returns: :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method.
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the token list is already formatted with special tokens for the model. Returns: :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: if token_ids_1 is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return list( map( lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0, ) ) # no bos used in fairseq if token_ids_1 is not None: return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] return ([0] * len(token_ids_0)) + [1]
[ "def", "get_special_tokens_mask", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ",", "already_has_special_tokens", ":", "bool", "=", "False", ")", "->", "List", "[", "int", "]", ":", "if", "already_has_special_tokens", ":", "if", "token_ids_1", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You should not supply a second sequence if the provided sequence of \"", "\"ids is already formatted with special tokens for the model.\"", ")", "return", "list", "(", "map", "(", "lambda", "x", ":", "1", "if", "x", "in", "[", "self", ".", "sep_token_id", ",", "self", ".", "cls_token_id", "]", "else", "0", ",", "token_ids_0", ",", ")", ")", "# no bos used in fairseq", "if", "token_ids_1", "is", "not", "None", ":", "return", "(", "[", "0", "]", "*", "len", "(", "token_ids_0", ")", ")", "+", "[", "1", "]", "+", "(", "[", "0", "]", "*", "len", "(", "token_ids_1", ")", ")", "+", "[", "1", "]", "return", "(", "[", "0", "]", "*", "len", "(", "token_ids_0", ")", ")", "+", "[", "1", "]" ]
[ 419, 4 ]
[ 453, 45 ]
python
en
['en', 'error', 'th']
False
FSMTTokenizer.create_token_type_ids_from_sequences
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A FAIRSEQ Transformer sequence pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given sequence(s). Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FAIRSEQ_TRANSFORMER sequence pair mask has the following format:
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A FAIRSEQ Transformer sequence pair mask has the following format:
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A FAIRSEQ Transformer sequence pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given sequence(s). Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FAIRSEQ_TRANSFORMER sequence pair mask has the following format: """ sep = [self.sep_token_id] # no bos used in fairseq if token_ids_1 is None: return len(token_ids_0 + sep) * [0] return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
[ "def", "create_token_type_ids_from_sequences", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "sep", "=", "[", "self", ".", "sep_token_id", "]", "# no bos used in fairseq", "if", "token_ids_1", "is", "None", ":", "return", "len", "(", "token_ids_0", "+", "sep", ")", "*", "[", "0", "]", "return", "len", "(", "token_ids_0", "+", "sep", ")", "*", "[", "0", "]", "+", "len", "(", "token_ids_1", "+", "sep", ")", "*", "[", "1", "]" ]
[ 455, 4 ]
[ 487, 74 ]
python
en
['en', 'error', 'th']
False
test_setup_with_no_config
(hass)
Test that we do not discover anything or try to set up a hub.
Test that we do not discover anything or try to set up a hub.
async def test_setup_with_no_config(hass): """Test that we do not discover anything or try to set up a hub.""" assert await async_setup_component(hass, mikrotik.DOMAIN, {}) is True assert mikrotik.DOMAIN not in hass.data
[ "async", "def", "test_setup_with_no_config", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "mikrotik", ".", "DOMAIN", ",", "{", "}", ")", "is", "True", "assert", "mikrotik", ".", "DOMAIN", "not", "in", "hass", ".", "data" ]
[ 10, 0 ]
[ 13, 43 ]
python
en
['en', 'en', 'en']
True
test_successful_config_entry
(hass)
Test config entry successful setup.
Test config entry successful setup.
async def test_successful_config_entry(hass): """Test config entry successful setup.""" entry = MockConfigEntry( domain=mikrotik.DOMAIN, data=MOCK_DATA, ) entry.add_to_hass(hass) mock_registry = Mock() with patch.object(mikrotik, "MikrotikHub") as mock_hub, patch( "homeassistant.helpers.device_registry.async_get_registry", return_value=mock_registry, ): mock_hub.return_value.async_setup = AsyncMock(return_value=True) mock_hub.return_value.serial_num = "12345678" mock_hub.return_value.model = "RB750" mock_hub.return_value.hostname = "mikrotik" mock_hub.return_value.firmware = "3.65" assert await mikrotik.async_setup_entry(hass, entry) is True assert len(mock_hub.mock_calls) == 2 p_hass, p_entry = mock_hub.mock_calls[0][1] assert p_hass is hass assert p_entry is entry assert len(mock_registry.mock_calls) == 1 assert mock_registry.mock_calls[0][2] == { "config_entry_id": entry.entry_id, "connections": {("mikrotik", "12345678")}, "manufacturer": mikrotik.ATTR_MANUFACTURER, "model": "RB750", "name": "mikrotik", "sw_version": "3.65", }
[ "async", "def", "test_successful_config_entry", "(", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mikrotik", ".", "DOMAIN", ",", "data", "=", "MOCK_DATA", ",", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "mock_registry", "=", "Mock", "(", ")", "with", "patch", ".", "object", "(", "mikrotik", ",", "\"MikrotikHub\"", ")", "as", "mock_hub", ",", "patch", "(", "\"homeassistant.helpers.device_registry.async_get_registry\"", ",", "return_value", "=", "mock_registry", ",", ")", ":", "mock_hub", ".", "return_value", ".", "async_setup", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "mock_hub", ".", "return_value", ".", "serial_num", "=", "\"12345678\"", "mock_hub", ".", "return_value", ".", "model", "=", "\"RB750\"", "mock_hub", ".", "return_value", ".", "hostname", "=", "\"mikrotik\"", "mock_hub", ".", "return_value", ".", "firmware", "=", "\"3.65\"", "assert", "await", "mikrotik", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "is", "True", "assert", "len", "(", "mock_hub", ".", "mock_calls", ")", "==", "2", "p_hass", ",", "p_entry", "=", "mock_hub", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "assert", "p_hass", "is", "hass", "assert", "p_entry", "is", "entry", "assert", "len", "(", "mock_registry", ".", "mock_calls", ")", "==", "1", "assert", "mock_registry", ".", "mock_calls", "[", "0", "]", "[", "2", "]", "==", "{", "\"config_entry_id\"", ":", "entry", ".", "entry_id", ",", "\"connections\"", ":", "{", "(", "\"mikrotik\"", ",", "\"12345678\"", ")", "}", ",", "\"manufacturer\"", ":", "mikrotik", ".", "ATTR_MANUFACTURER", ",", "\"model\"", ":", "\"RB750\"", ",", "\"name\"", ":", "\"mikrotik\"", ",", "\"sw_version\"", ":", "\"3.65\"", ",", "}" ]
[ 16, 0 ]
[ 50, 5 ]
python
en
['en', 'en', 'en']
True
test_hub_fail_setup
(hass)
Test that a failed setup will not store the hub.
Test that a failed setup will not store the hub.
async def test_hub_fail_setup(hass): """Test that a failed setup will not store the hub.""" entry = MockConfigEntry( domain=mikrotik.DOMAIN, data=MOCK_DATA, ) entry.add_to_hass(hass) with patch.object(mikrotik, "MikrotikHub") as mock_hub: mock_hub.return_value.async_setup = AsyncMock(return_value=False) assert await mikrotik.async_setup_entry(hass, entry) is False assert mikrotik.DOMAIN not in hass.data
[ "async", "def", "test_hub_fail_setup", "(", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mikrotik", ".", "DOMAIN", ",", "data", "=", "MOCK_DATA", ",", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch", ".", "object", "(", "mikrotik", ",", "\"MikrotikHub\"", ")", "as", "mock_hub", ":", "mock_hub", ".", "return_value", ".", "async_setup", "=", "AsyncMock", "(", "return_value", "=", "False", ")", "assert", "await", "mikrotik", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "is", "False", "assert", "mikrotik", ".", "DOMAIN", "not", "in", "hass", ".", "data" ]
[ 53, 0 ]
[ 65, 43 ]
python
en
['en', 'en', 'en']
True
test_unload_entry
(hass)
Test being able to unload an entry.
Test being able to unload an entry.
async def test_unload_entry(hass): """Test being able to unload an entry.""" entry = MockConfigEntry( domain=mikrotik.DOMAIN, data=MOCK_DATA, ) entry.add_to_hass(hass) with patch.object(mikrotik, "MikrotikHub") as mock_hub, patch( "homeassistant.helpers.device_registry.async_get_registry", return_value=Mock(), ): mock_hub.return_value.async_setup = AsyncMock(return_value=True) mock_hub.return_value.serial_num = "12345678" mock_hub.return_value.model = "RB750" mock_hub.return_value.hostname = "mikrotik" mock_hub.return_value.firmware = "3.65" assert await mikrotik.async_setup_entry(hass, entry) is True assert len(mock_hub.return_value.mock_calls) == 1 assert await mikrotik.async_unload_entry(hass, entry) assert entry.entry_id not in hass.data[mikrotik.DOMAIN]
[ "async", "def", "test_unload_entry", "(", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mikrotik", ".", "DOMAIN", ",", "data", "=", "MOCK_DATA", ",", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch", ".", "object", "(", "mikrotik", ",", "\"MikrotikHub\"", ")", "as", "mock_hub", ",", "patch", "(", "\"homeassistant.helpers.device_registry.async_get_registry\"", ",", "return_value", "=", "Mock", "(", ")", ",", ")", ":", "mock_hub", ".", "return_value", ".", "async_setup", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "mock_hub", ".", "return_value", ".", "serial_num", "=", "\"12345678\"", "mock_hub", ".", "return_value", ".", "model", "=", "\"RB750\"", "mock_hub", ".", "return_value", ".", "hostname", "=", "\"mikrotik\"", "mock_hub", ".", "return_value", ".", "firmware", "=", "\"3.65\"", "assert", "await", "mikrotik", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "is", "True", "assert", "len", "(", "mock_hub", ".", "return_value", ".", "mock_calls", ")", "==", "1", "assert", "await", "mikrotik", ".", "async_unload_entry", "(", "hass", ",", "entry", ")", "assert", "entry", ".", "entry_id", "not", "in", "hass", ".", "data", "[", "mikrotik", ".", "DOMAIN", "]" ]
[ 68, 0 ]
[ 90, 59 ]
python
en
['en', 'en', 'en']
True
setup_sensor
(hass)
Set up demo sensor component.
Set up demo sensor component.
async def setup_sensor(hass): """Set up demo sensor component.""" with assert_setup_component(1, DOMAIN): with patch( "coinmarketcap.Market.ticker", return_value=json.loads(load_fixture("coinmarketcap.json")), ): await async_setup_component(hass, DOMAIN, VALID_CONFIG) await hass.async_block_till_done()
[ "async", "def", "setup_sensor", "(", "hass", ")", ":", "with", "assert_setup_component", "(", "1", ",", "DOMAIN", ")", ":", "with", "patch", "(", "\"coinmarketcap.Market.ticker\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"coinmarketcap.json\"", ")", ")", ",", ")", ":", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "VALID_CONFIG", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 22, 0 ]
[ 30, 46 ]
python
en
['lb', 'pt', 'en']
False
test_setup
(hass, setup_sensor)
Test the setup with custom settings.
Test the setup with custom settings.
async def test_setup(hass, setup_sensor): """Test the setup with custom settings.""" state = hass.states.get("sensor.ethereum") assert state is not None assert state.name == "Ethereum" assert state.state == "493.455" assert state.attributes.get("symbol") == "ETH" assert state.attributes.get("unit_of_measurement") == "EUR"
[ "async", "def", "test_setup", "(", "hass", ",", "setup_sensor", ")", ":", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.ethereum\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "name", "==", "\"Ethereum\"", "assert", "state", ".", "state", "==", "\"493.455\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"symbol\"", ")", "==", "\"ETH\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"unit_of_measurement\"", ")", "==", "\"EUR\"" ]
[ 33, 0 ]
[ 41, 63 ]
python
en
['en', 'haw', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Set up the Synology NAS Sensor.
Set up the Synology NAS Sensor.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Synology NAS Sensor.""" api = hass.data[DOMAIN][entry.unique_id][SYNO_API] entities = [ SynoDSMUtilSensor(api, sensor_type, UTILISATION_SENSORS[sensor_type]) for sensor_type in UTILISATION_SENSORS ] # Handle all volumes if api.storage.volumes_ids: for volume in entry.data.get(CONF_VOLUMES, api.storage.volumes_ids): entities += [ SynoDSMStorageSensor( api, sensor_type, STORAGE_VOL_SENSORS[sensor_type], volume ) for sensor_type in STORAGE_VOL_SENSORS ] # Handle all disks if api.storage.disks_ids: for disk in entry.data.get(CONF_DISKS, api.storage.disks_ids): entities += [ SynoDSMStorageSensor( api, sensor_type, STORAGE_DISK_SENSORS[sensor_type], disk ) for sensor_type in STORAGE_DISK_SENSORS ] entities += [ SynoDSMInfoSensor(api, sensor_type, INFORMATION_SENSORS[sensor_type]) for sensor_type in INFORMATION_SENSORS ] async_add_entities(entities)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "api", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "unique_id", "]", "[", "SYNO_API", "]", "entities", "=", "[", "SynoDSMUtilSensor", "(", "api", ",", "sensor_type", ",", "UTILISATION_SENSORS", "[", "sensor_type", "]", ")", "for", "sensor_type", "in", "UTILISATION_SENSORS", "]", "# Handle all volumes", "if", "api", ".", "storage", ".", "volumes_ids", ":", "for", "volume", "in", "entry", ".", "data", ".", "get", "(", "CONF_VOLUMES", ",", "api", ".", "storage", ".", "volumes_ids", ")", ":", "entities", "+=", "[", "SynoDSMStorageSensor", "(", "api", ",", "sensor_type", ",", "STORAGE_VOL_SENSORS", "[", "sensor_type", "]", ",", "volume", ")", "for", "sensor_type", "in", "STORAGE_VOL_SENSORS", "]", "# Handle all disks", "if", "api", ".", "storage", ".", "disks_ids", ":", "for", "disk", "in", "entry", ".", "data", ".", "get", "(", "CONF_DISKS", ",", "api", ".", "storage", ".", "disks_ids", ")", ":", "entities", "+=", "[", "SynoDSMStorageSensor", "(", "api", ",", "sensor_type", ",", "STORAGE_DISK_SENSORS", "[", "sensor_type", "]", ",", "disk", ")", "for", "sensor_type", "in", "STORAGE_DISK_SENSORS", "]", "entities", "+=", "[", "SynoDSMInfoSensor", "(", "api", ",", "sensor_type", ",", "INFORMATION_SENSORS", "[", "sensor_type", "]", ")", "for", "sensor_type", "in", "INFORMATION_SENSORS", "]", "async_add_entities", "(", "entities", ")" ]
[ 30, 0 ]
[ 67, 32 ]
python
en
['en', 'pt', 'en']
True
SynoDSMUtilSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" attr = getattr(self._api.utilisation, self.entity_type) if callable(attr): attr = attr() if attr is None: return None # Data (RAM) if self._unit == DATA_MEGABYTES: return round(attr / 1024.0 ** 2, 1) # Network if self._unit == DATA_RATE_KILOBYTES_PER_SECOND: return round(attr / 1024.0, 1) return attr
[ "def", "state", "(", "self", ")", ":", "attr", "=", "getattr", "(", "self", ".", "_api", ".", "utilisation", ",", "self", ".", "entity_type", ")", "if", "callable", "(", "attr", ")", ":", "attr", "=", "attr", "(", ")", "if", "attr", "is", "None", ":", "return", "None", "# Data (RAM)", "if", "self", ".", "_unit", "==", "DATA_MEGABYTES", ":", "return", "round", "(", "attr", "/", "1024.0", "**", "2", ",", "1", ")", "# Network", "if", "self", ".", "_unit", "==", "DATA_RATE_KILOBYTES_PER_SECOND", ":", "return", "round", "(", "attr", "/", "1024.0", ",", "1", ")", "return", "attr" ]
[ 74, 4 ]
[ 90, 19 ]
python
en
['en', 'en', 'en']
True
SynoDSMUtilSensor.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 bool(self._api.utilisation)
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "_api", ".", "utilisation", ")" ]
[ 93, 4 ]
[ 95, 42 ]
python
en
['en', 'en', 'en']
True
SynoDSMStorageSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" attr = getattr(self._api.storage, self.entity_type)(self._device_id) if attr is None: return None # Data (disk space) if self._unit == DATA_TERABYTES: return round(attr / 1024.0 ** 4, 2) # Temperature if self.entity_type in TEMP_SENSORS_KEYS: return display_temp(self.hass, attr, TEMP_CELSIUS, PRECISION_TENTHS) return attr
[ "def", "state", "(", "self", ")", ":", "attr", "=", "getattr", "(", "self", ".", "_api", ".", "storage", ",", "self", ".", "entity_type", ")", "(", "self", ".", "_device_id", ")", "if", "attr", "is", "None", ":", "return", "None", "# Data (disk space)", "if", "self", ".", "_unit", "==", "DATA_TERABYTES", ":", "return", "round", "(", "attr", "/", "1024.0", "**", "4", ",", "2", ")", "# Temperature", "if", "self", ".", "entity_type", "in", "TEMP_SENSORS_KEYS", ":", "return", "display_temp", "(", "self", ".", "hass", ",", "attr", ",", "TEMP_CELSIUS", ",", "PRECISION_TENTHS", ")", "return", "attr" ]
[ 102, 4 ]
[ 116, 19 ]
python
en
['en', 'en', 'en']
True
SynoDSMInfoSensor.__init__
(self, api: SynoApi, entity_type: str, entity_info: Dict[str, str])
Initialize the Synology SynoDSMInfoSensor entity.
Initialize the Synology SynoDSMInfoSensor entity.
def __init__(self, api: SynoApi, entity_type: str, entity_info: Dict[str, str]): """Initialize the Synology SynoDSMInfoSensor entity.""" super().__init__(api, entity_type, entity_info) self._previous_uptime = None self._last_boot = None
[ "def", "__init__", "(", "self", ",", "api", ":", "SynoApi", ",", "entity_type", ":", "str", ",", "entity_info", ":", "Dict", "[", "str", ",", "str", "]", ")", ":", "super", "(", ")", ".", "__init__", "(", "api", ",", "entity_type", ",", "entity_info", ")", "self", ".", "_previous_uptime", "=", "None", "self", ".", "_last_boot", "=", "None" ]
[ 122, 4 ]
[ 126, 30 ]
python
en
['en', 'zu', 'en']
True
SynoDSMInfoSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" attr = getattr(self._api.information, self.entity_type) if attr is None: return None # Temperature if self.entity_type in TEMP_SENSORS_KEYS: return display_temp(self.hass, attr, TEMP_CELSIUS, PRECISION_TENTHS) if self.entity_type == "uptime": # reboot happened or entity creation if self._previous_uptime is None or self._previous_uptime > attr: last_boot = utcnow() - timedelta(seconds=attr) self._last_boot = last_boot.replace(microsecond=0).isoformat() self._previous_uptime = attr return self._last_boot return attr
[ "def", "state", "(", "self", ")", ":", "attr", "=", "getattr", "(", "self", ".", "_api", ".", "information", ",", "self", ".", "entity_type", ")", "if", "attr", "is", "None", ":", "return", "None", "# Temperature", "if", "self", ".", "entity_type", "in", "TEMP_SENSORS_KEYS", ":", "return", "display_temp", "(", "self", ".", "hass", ",", "attr", ",", "TEMP_CELSIUS", ",", "PRECISION_TENTHS", ")", "if", "self", ".", "entity_type", "==", "\"uptime\"", ":", "# reboot happened or entity creation", "if", "self", ".", "_previous_uptime", "is", "None", "or", "self", ".", "_previous_uptime", ">", "attr", ":", "last_boot", "=", "utcnow", "(", ")", "-", "timedelta", "(", "seconds", "=", "attr", ")", "self", ".", "_last_boot", "=", "last_boot", ".", "replace", "(", "microsecond", "=", "0", ")", ".", "isoformat", "(", ")", "self", ".", "_previous_uptime", "=", "attr", "return", "self", ".", "_last_boot", "return", "attr" ]
[ 129, 4 ]
[ 147, 19 ]
python
en
['en', 'en', 'en']
True
async_attach_trigger
(hass, config, action, automation_info)
Listen for state changes based on configuration.
Listen for state changes based on configuration.
async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" hours = config.get(CONF_HOURS) minutes = config.get(CONF_MINUTES) seconds = config.get(CONF_SECONDS) job = HassJob(action) # If larger units are specified, default the smaller units to zero if minutes is None and hours is not None: minutes = 0 if seconds is None and minutes is not None: seconds = 0 @callback def time_automation_listener(now): """Listen for time changes and calls action.""" hass.async_run_hass_job( job, { "trigger": { "platform": "time_pattern", "now": now, "description": "time pattern", } }, ) return async_track_time_change( hass, time_automation_listener, hour=hours, minute=minutes, second=seconds )
[ "async", "def", "async_attach_trigger", "(", "hass", ",", "config", ",", "action", ",", "automation_info", ")", ":", "hours", "=", "config", ".", "get", "(", "CONF_HOURS", ")", "minutes", "=", "config", ".", "get", "(", "CONF_MINUTES", ")", "seconds", "=", "config", ".", "get", "(", "CONF_SECONDS", ")", "job", "=", "HassJob", "(", "action", ")", "# If larger units are specified, default the smaller units to zero", "if", "minutes", "is", "None", "and", "hours", "is", "not", "None", ":", "minutes", "=", "0", "if", "seconds", "is", "None", "and", "minutes", "is", "not", "None", ":", "seconds", "=", "0", "@", "callback", "def", "time_automation_listener", "(", "now", ")", ":", "\"\"\"Listen for time changes and calls action.\"\"\"", "hass", ".", "async_run_hass_job", "(", "job", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"time_pattern\"", ",", "\"now\"", ":", "now", ",", "\"description\"", ":", "\"time pattern\"", ",", "}", "}", ",", ")", "return", "async_track_time_change", "(", "hass", ",", "time_automation_listener", ",", "hour", "=", "hours", ",", "minute", "=", "minutes", ",", "second", "=", "seconds", ")" ]
[ 57, 0 ]
[ 86, 5 ]
python
en
['en', 'en', 'en']
True
TimePattern.__init__
(self, maximum)
Initialize time pattern.
Initialize time pattern.
def __init__(self, maximum): """Initialize time pattern.""" self.maximum = maximum
[ "def", "__init__", "(", "self", ",", "maximum", ")", ":", "self", ".", "maximum", "=", "maximum" ]
[ 21, 4 ]
[ 23, 30 ]
python
en
['en', 'en', 'en']
True
TimePattern.__call__
(self, value)
Validate input.
Validate input.
def __call__(self, value): """Validate input.""" try: if value == "*": return value if isinstance(value, str) and value.startswith("/"): number = int(value[1:]) else: value = number = int(value) if not (0 <= number <= self.maximum): raise vol.Invalid(f"must be a value between 0 and {self.maximum}") except ValueError as err: raise vol.Invalid("invalid time_pattern value") from err return value
[ "def", "__call__", "(", "self", ",", "value", ")", ":", "try", ":", "if", "value", "==", "\"*\"", ":", "return", "value", "if", "isinstance", "(", "value", ",", "str", ")", "and", "value", ".", "startswith", "(", "\"/\"", ")", ":", "number", "=", "int", "(", "value", "[", "1", ":", "]", ")", "else", ":", "value", "=", "number", "=", "int", "(", "value", ")", "if", "not", "(", "0", "<=", "number", "<=", "self", ".", "maximum", ")", ":", "raise", "vol", ".", "Invalid", "(", "f\"must be a value between 0 and {self.maximum}\"", ")", "except", "ValueError", "as", "err", ":", "raise", "vol", ".", "Invalid", "(", "\"invalid time_pattern value\"", ")", "from", "err", "return", "value" ]
[ 25, 4 ]
[ 41, 20 ]
python
en
['en', 'et', 'en']
False
async_setup
(hass, config)
Set up the keyboard_remote.
Set up the keyboard_remote.
async def async_setup(hass, config): """Set up the keyboard_remote.""" config = config.get(DOMAIN) remote = KeyboardRemote(hass, config) remote.setup() return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "config", "=", "config", ".", "get", "(", "DOMAIN", ")", "remote", "=", "KeyboardRemote", "(", "hass", ",", "config", ")", "remote", ".", "setup", "(", ")", "return", "True" ]
[ 60, 0 ]
[ 67, 15 ]
python
en
['en', 'en', 'en']
True
KeyboardRemote.__init__
(self, hass, config)
Create handlers and setup dictionaries to keep track of them.
Create handlers and setup dictionaries to keep track of them.
def __init__(self, hass, config): """Create handlers and setup dictionaries to keep track of them.""" self.hass = hass self.handlers_by_name = {} self.handlers_by_descriptor = {} self.active_handlers_by_descriptor = {} self.watcher = None self.monitor_task = None for dev_block in config: handler = self.DeviceHandler(hass, dev_block) descriptor = dev_block.get(DEVICE_DESCRIPTOR) if descriptor is not None: self.handlers_by_descriptor[descriptor] = handler else: name = dev_block.get(DEVICE_NAME) self.handlers_by_name[name] = handler
[ "def", "__init__", "(", "self", ",", "hass", ",", "config", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "handlers_by_name", "=", "{", "}", "self", ".", "handlers_by_descriptor", "=", "{", "}", "self", ".", "active_handlers_by_descriptor", "=", "{", "}", "self", ".", "watcher", "=", "None", "self", ".", "monitor_task", "=", "None", "for", "dev_block", "in", "config", ":", "handler", "=", "self", ".", "DeviceHandler", "(", "hass", ",", "dev_block", ")", "descriptor", "=", "dev_block", ".", "get", "(", "DEVICE_DESCRIPTOR", ")", "if", "descriptor", "is", "not", "None", ":", "self", ".", "handlers_by_descriptor", "[", "descriptor", "]", "=", "handler", "else", ":", "name", "=", "dev_block", ".", "get", "(", "DEVICE_NAME", ")", "self", ".", "handlers_by_name", "[", "name", "]", "=", "handler" ]
[ 73, 4 ]
[ 89, 53 ]
python
en
['en', 'en', 'en']
True
KeyboardRemote.setup
(self)
Listen for Home Assistant start and stop events.
Listen for Home Assistant start and stop events.
def setup(self): """Listen for Home Assistant start and stop events.""" self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, self.async_start_monitoring ) self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, self.async_stop_monitoring )
[ "def", "setup", "(", "self", ")", ":", "self", ".", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_START", ",", "self", ".", "async_start_monitoring", ")", "self", ".", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "self", ".", "async_stop_monitoring", ")" ]
[ 91, 4 ]
[ 99, 9 ]
python
en
['en', 'en', 'en']
True
KeyboardRemote.async_start_monitoring
(self, event)
Start monitoring of events and devices. Start inotify watching for events, start event monitoring for those already connected, and start monitoring for device connection/disconnection.
Start monitoring of events and devices.
async def async_start_monitoring(self, event): """Start monitoring of events and devices. Start inotify watching for events, start event monitoring for those already connected, and start monitoring for device connection/disconnection. """ # start watching self.watcher = aionotify.Watcher() self.watcher.watch( alias="devinput", path=DEVINPUT, flags=aionotify.Flags.CREATE | aionotify.Flags.ATTRIB | aionotify.Flags.DELETE, ) await self.watcher.setup(self.hass.loop) # add initial devices (do this AFTER starting watcher in order to # avoid race conditions leading to missing device connections) initial_start_monitoring = set() descriptors = await self.hass.async_add_executor_job(list_devices, DEVINPUT) for descriptor in descriptors: dev, handler = await self.hass.async_add_executor_job( self.get_device_handler, descriptor ) if handler is None: continue self.active_handlers_by_descriptor[descriptor] = handler initial_start_monitoring.add(handler.async_start_monitoring(dev)) if initial_start_monitoring: await asyncio.wait(initial_start_monitoring) self.monitor_task = self.hass.async_create_task(self.async_monitor_devices())
[ "async", "def", "async_start_monitoring", "(", "self", ",", "event", ")", ":", "# start watching", "self", ".", "watcher", "=", "aionotify", ".", "Watcher", "(", ")", "self", ".", "watcher", ".", "watch", "(", "alias", "=", "\"devinput\"", ",", "path", "=", "DEVINPUT", ",", "flags", "=", "aionotify", ".", "Flags", ".", "CREATE", "|", "aionotify", ".", "Flags", ".", "ATTRIB", "|", "aionotify", ".", "Flags", ".", "DELETE", ",", ")", "await", "self", ".", "watcher", ".", "setup", "(", "self", ".", "hass", ".", "loop", ")", "# add initial devices (do this AFTER starting watcher in order to", "# avoid race conditions leading to missing device connections)", "initial_start_monitoring", "=", "set", "(", ")", "descriptors", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "list_devices", ",", "DEVINPUT", ")", "for", "descriptor", "in", "descriptors", ":", "dev", ",", "handler", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "get_device_handler", ",", "descriptor", ")", "if", "handler", "is", "None", ":", "continue", "self", ".", "active_handlers_by_descriptor", "[", "descriptor", "]", "=", "handler", "initial_start_monitoring", ".", "add", "(", "handler", ".", "async_start_monitoring", "(", "dev", ")", ")", "if", "initial_start_monitoring", ":", "await", "asyncio", ".", "wait", "(", "initial_start_monitoring", ")", "self", ".", "monitor_task", "=", "self", ".", "hass", ".", "async_create_task", "(", "self", ".", "async_monitor_devices", "(", ")", ")" ]
[ 101, 4 ]
[ 137, 85 ]
python
en
['en', 'en', 'en']
True
KeyboardRemote.async_stop_monitoring
(self, event)
Stop and cleanup running monitoring tasks.
Stop and cleanup running monitoring tasks.
async def async_stop_monitoring(self, event): """Stop and cleanup running monitoring tasks.""" _LOGGER.debug("Cleanup on shutdown") if self.monitor_task is not None: if not self.monitor_task.done(): self.monitor_task.cancel() await self.monitor_task handler_stop_monitoring = set() for handler in self.active_handlers_by_descriptor.values(): handler_stop_monitoring.add(handler.async_stop_monitoring()) if handler_stop_monitoring: await asyncio.wait(handler_stop_monitoring)
[ "async", "def", "async_stop_monitoring", "(", "self", ",", "event", ")", ":", "_LOGGER", ".", "debug", "(", "\"Cleanup on shutdown\"", ")", "if", "self", ".", "monitor_task", "is", "not", "None", ":", "if", "not", "self", ".", "monitor_task", ".", "done", "(", ")", ":", "self", ".", "monitor_task", ".", "cancel", "(", ")", "await", "self", ".", "monitor_task", "handler_stop_monitoring", "=", "set", "(", ")", "for", "handler", "in", "self", ".", "active_handlers_by_descriptor", ".", "values", "(", ")", ":", "handler_stop_monitoring", ".", "add", "(", "handler", ".", "async_stop_monitoring", "(", ")", ")", "if", "handler_stop_monitoring", ":", "await", "asyncio", ".", "wait", "(", "handler_stop_monitoring", ")" ]
[ 139, 4 ]
[ 154, 55 ]
python
en
['en', 'en', 'en']
True
KeyboardRemote.get_device_handler
(self, descriptor)
Find the correct device handler given a descriptor (path).
Find the correct device handler given a descriptor (path).
def get_device_handler(self, descriptor): """Find the correct device handler given a descriptor (path).""" # devices are often added and then correct permissions set after try: dev = InputDevice(descriptor) except (OSError, PermissionError): return (None, None) handler = None if descriptor in self.handlers_by_descriptor: handler = self.handlers_by_descriptor[descriptor] elif dev.name in self.handlers_by_name: handler = self.handlers_by_name[dev.name] else: # check for symlinked paths matching descriptor for test_descriptor, test_handler in self.handlers_by_descriptor.items(): if test_handler.dev is not None: fullpath = test_handler.dev.path else: fullpath = os.path.realpath(test_descriptor) if fullpath == descriptor: handler = test_handler return (dev, handler)
[ "def", "get_device_handler", "(", "self", ",", "descriptor", ")", ":", "# devices are often added and then correct permissions set after", "try", ":", "dev", "=", "InputDevice", "(", "descriptor", ")", "except", "(", "OSError", ",", "PermissionError", ")", ":", "return", "(", "None", ",", "None", ")", "handler", "=", "None", "if", "descriptor", "in", "self", ".", "handlers_by_descriptor", ":", "handler", "=", "self", ".", "handlers_by_descriptor", "[", "descriptor", "]", "elif", "dev", ".", "name", "in", "self", ".", "handlers_by_name", ":", "handler", "=", "self", ".", "handlers_by_name", "[", "dev", ".", "name", "]", "else", ":", "# check for symlinked paths matching descriptor", "for", "test_descriptor", ",", "test_handler", "in", "self", ".", "handlers_by_descriptor", ".", "items", "(", ")", ":", "if", "test_handler", ".", "dev", "is", "not", "None", ":", "fullpath", "=", "test_handler", ".", "dev", ".", "path", "else", ":", "fullpath", "=", "os", ".", "path", ".", "realpath", "(", "test_descriptor", ")", "if", "fullpath", "==", "descriptor", ":", "handler", "=", "test_handler", "return", "(", "dev", ",", "handler", ")" ]
[ 156, 4 ]
[ 180, 29 ]
python
en
['en', 'en', 'en']
True
KeyboardRemote.async_monitor_devices
(self)
Monitor asynchronously for device connection/disconnection or permissions changes.
Monitor asynchronously for device connection/disconnection or permissions changes.
async def async_monitor_devices(self): """Monitor asynchronously for device connection/disconnection or permissions changes.""" try: while True: event = await self.watcher.get_event() descriptor = f"{DEVINPUT}/{event.name}" descriptor_active = descriptor in self.active_handlers_by_descriptor if (event.flags & aionotify.Flags.DELETE) and descriptor_active: handler = self.active_handlers_by_descriptor[descriptor] del self.active_handlers_by_descriptor[descriptor] await handler.async_stop_monitoring() elif ( (event.flags & aionotify.Flags.CREATE) or (event.flags & aionotify.Flags.ATTRIB) ) and not descriptor_active: dev, handler = await self.hass.async_add_executor_job( self.get_device_handler, descriptor ) if handler is None: continue self.active_handlers_by_descriptor[descriptor] = handler await handler.async_start_monitoring(dev) except asyncio.CancelledError: return
[ "async", "def", "async_monitor_devices", "(", "self", ")", ":", "try", ":", "while", "True", ":", "event", "=", "await", "self", ".", "watcher", ".", "get_event", "(", ")", "descriptor", "=", "f\"{DEVINPUT}/{event.name}\"", "descriptor_active", "=", "descriptor", "in", "self", ".", "active_handlers_by_descriptor", "if", "(", "event", ".", "flags", "&", "aionotify", ".", "Flags", ".", "DELETE", ")", "and", "descriptor_active", ":", "handler", "=", "self", ".", "active_handlers_by_descriptor", "[", "descriptor", "]", "del", "self", ".", "active_handlers_by_descriptor", "[", "descriptor", "]", "await", "handler", ".", "async_stop_monitoring", "(", ")", "elif", "(", "(", "event", ".", "flags", "&", "aionotify", ".", "Flags", ".", "CREATE", ")", "or", "(", "event", ".", "flags", "&", "aionotify", ".", "Flags", ".", "ATTRIB", ")", ")", "and", "not", "descriptor_active", ":", "dev", ",", "handler", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "get_device_handler", ",", "descriptor", ")", "if", "handler", "is", "None", ":", "continue", "self", ".", "active_handlers_by_descriptor", "[", "descriptor", "]", "=", "handler", "await", "handler", ".", "async_start_monitoring", "(", "dev", ")", "except", "asyncio", ".", "CancelledError", ":", "return" ]
[ 182, 4 ]
[ 208, 18 ]
python
en
['en', 'en', 'en']
True
_fused_prox_jacobian
(y_hat, dout=None)
reference naive implementation: construct the jacobian
reference naive implementation: construct the jacobian
def _fused_prox_jacobian(y_hat, dout=None): """reference naive implementation: construct the jacobian""" dim = y_hat.shape[0] groups = torch.zeros(dim) J = torch.zeros(dim, dim) current_group = 0 for i in range(1, dim): if y_hat[i] == y_hat[i - 1]: groups[i] = groups[i - 1] else: current_group += 1 groups[i] = current_group for i in range(dim): for j in range(dim): if groups[i] == groups[j]: n_fused = (groups == groups[i]).sum() J[i, j] = 1 / n_fused.to(y_hat.dtype) if dout is not None: return torch.mv(J, dout) else: return J
[ "def", "_fused_prox_jacobian", "(", "y_hat", ",", "dout", "=", "None", ")", ":", "dim", "=", "y_hat", ".", "shape", "[", "0", "]", "groups", "=", "torch", ".", "zeros", "(", "dim", ")", "J", "=", "torch", ".", "zeros", "(", "dim", ",", "dim", ")", "current_group", "=", "0", "for", "i", "in", "range", "(", "1", ",", "dim", ")", ":", "if", "y_hat", "[", "i", "]", "==", "y_hat", "[", "i", "-", "1", "]", ":", "groups", "[", "i", "]", "=", "groups", "[", "i", "-", "1", "]", "else", ":", "current_group", "+=", "1", "groups", "[", "i", "]", "=", "current_group", "for", "i", "in", "range", "(", "dim", ")", ":", "for", "j", "in", "range", "(", "dim", ")", ":", "if", "groups", "[", "i", "]", "==", "groups", "[", "j", "]", ":", "n_fused", "=", "(", "groups", "==", "groups", "[", "i", "]", ")", ".", "sum", "(", ")", "J", "[", "i", ",", "j", "]", "=", "1", "/", "n_fused", ".", "to", "(", "y_hat", ".", "dtype", ")", "if", "dout", "is", "not", "None", ":", "return", "torch", ".", "mv", "(", "J", ",", "dout", ")", "else", ":", "return", "J" ]
[ 11, 0 ]
[ 34, 16 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the GitHub sensor platform.
Set up the GitHub sensor platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the GitHub sensor platform.""" sensors = [] for repository in config[CONF_REPOS]: data = GitHubData( repository=repository, access_token=config.get(CONF_ACCESS_TOKEN), server_url=config.get(CONF_URL), ) if data.setup_error is True: _LOGGER.error( "Error setting up GitHub platform. %s", "Check previous errors for details", ) else: sensors.append(GitHubSensor(data)) add_entities(sensors, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "sensors", "=", "[", "]", "for", "repository", "in", "config", "[", "CONF_REPOS", "]", ":", "data", "=", "GitHubData", "(", "repository", "=", "repository", ",", "access_token", "=", "config", ".", "get", "(", "CONF_ACCESS_TOKEN", ")", ",", "server_url", "=", "config", ".", "get", "(", "CONF_URL", ")", ",", ")", "if", "data", ".", "setup_error", "is", "True", ":", "_LOGGER", ".", "error", "(", "\"Error setting up GitHub platform. %s\"", ",", "\"Check previous errors for details\"", ",", ")", "else", ":", "sensors", ".", "append", "(", "GitHubSensor", "(", "data", ")", ")", "add_entities", "(", "sensors", ",", "True", ")" ]
[ 55, 0 ]
[ 71, 31 ]
python
en
['en', 'ceb', 'en']
True
GitHubSensor.__init__
(self, github_data)
Initialize the GitHub sensor.
Initialize the GitHub sensor.
def __init__(self, github_data): """Initialize the GitHub sensor.""" self._unique_id = github_data.repository_path self._name = None self._state = None self._available = False self._repository_path = None self._latest_commit_message = None self._latest_commit_sha = None self._latest_release_tag = None self._latest_release_url = None self._open_issue_count = None self._latest_open_issue_url = None self._pull_request_count = None self._latest_open_pr_url = None self._stargazers = None self._forks = None self._clones = None self._clones_unique = None self._views = None self._views_unique = None self._github_data = github_data
[ "def", "__init__", "(", "self", ",", "github_data", ")", ":", "self", ".", "_unique_id", "=", "github_data", ".", "repository_path", "self", ".", "_name", "=", "None", "self", ".", "_state", "=", "None", "self", ".", "_available", "=", "False", "self", ".", "_repository_path", "=", "None", "self", ".", "_latest_commit_message", "=", "None", "self", ".", "_latest_commit_sha", "=", "None", "self", ".", "_latest_release_tag", "=", "None", "self", ".", "_latest_release_url", "=", "None", "self", ".", "_open_issue_count", "=", "None", "self", ".", "_latest_open_issue_url", "=", "None", "self", ".", "_pull_request_count", "=", "None", "self", ".", "_latest_open_pr_url", "=", "None", "self", ".", "_stargazers", "=", "None", "self", ".", "_forks", "=", "None", "self", ".", "_clones", "=", "None", "self", ".", "_clones_unique", "=", "None", "self", ".", "_views", "=", "None", "self", ".", "_views_unique", "=", "None", "self", ".", "_github_data", "=", "github_data" ]
[ 77, 4 ]
[ 98, 39 ]
python
en
['en', 'xh', 'en']
True
GitHubSensor.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" ]
[ 101, 4 ]
[ 103, 25 ]
python
en
['en', 'mi', 'en']
True
GitHubSensor.unique_id
(self)
Return unique ID for the sensor.
Return unique ID for the sensor.
def unique_id(self): """Return unique ID for the sensor.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 106, 4 ]
[ 108, 30 ]
python
en
['en', 'it', 'en']
True
GitHubSensor.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" ]
[ 111, 4 ]
[ 113, 26 ]
python
en
['en', 'en', 'en']
True
GitHubSensor.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self): """Return True if entity is available.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 116, 4 ]
[ 118, 30 ]
python
en
['en', 'en', 'en']
True
GitHubSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" attrs = { ATTR_PATH: self._repository_path, ATTR_NAME: self._name, ATTR_LATEST_COMMIT_MESSAGE: self._latest_commit_message, ATTR_LATEST_COMMIT_SHA: self._latest_commit_sha, ATTR_LATEST_RELEASE_URL: self._latest_release_url, ATTR_LATEST_OPEN_ISSUE_URL: self._latest_open_issue_url, ATTR_OPEN_ISSUES: self._open_issue_count, ATTR_LATEST_OPEN_PULL_REQUEST_URL: self._latest_open_pr_url, ATTR_OPEN_PULL_REQUESTS: self._pull_request_count, ATTR_STARGAZERS: self._stargazers, ATTR_FORKS: self._forks, } if self._latest_release_tag is not None: attrs[ATTR_LATEST_RELEASE_TAG] = self._latest_release_tag if self._clones is not None: attrs[ATTR_CLONES] = self._clones if self._clones_unique is not None: attrs[ATTR_CLONES_UNIQUE] = self._clones_unique if self._views is not None: attrs[ATTR_VIEWS] = self._views if self._views_unique is not None: attrs[ATTR_VIEWS_UNIQUE] = self._views_unique return attrs
[ "def", "device_state_attributes", "(", "self", ")", ":", "attrs", "=", "{", "ATTR_PATH", ":", "self", ".", "_repository_path", ",", "ATTR_NAME", ":", "self", ".", "_name", ",", "ATTR_LATEST_COMMIT_MESSAGE", ":", "self", ".", "_latest_commit_message", ",", "ATTR_LATEST_COMMIT_SHA", ":", "self", ".", "_latest_commit_sha", ",", "ATTR_LATEST_RELEASE_URL", ":", "self", ".", "_latest_release_url", ",", "ATTR_LATEST_OPEN_ISSUE_URL", ":", "self", ".", "_latest_open_issue_url", ",", "ATTR_OPEN_ISSUES", ":", "self", ".", "_open_issue_count", ",", "ATTR_LATEST_OPEN_PULL_REQUEST_URL", ":", "self", ".", "_latest_open_pr_url", ",", "ATTR_OPEN_PULL_REQUESTS", ":", "self", ".", "_pull_request_count", ",", "ATTR_STARGAZERS", ":", "self", ".", "_stargazers", ",", "ATTR_FORKS", ":", "self", ".", "_forks", ",", "}", "if", "self", ".", "_latest_release_tag", "is", "not", "None", ":", "attrs", "[", "ATTR_LATEST_RELEASE_TAG", "]", "=", "self", ".", "_latest_release_tag", "if", "self", ".", "_clones", "is", "not", "None", ":", "attrs", "[", "ATTR_CLONES", "]", "=", "self", ".", "_clones", "if", "self", ".", "_clones_unique", "is", "not", "None", ":", "attrs", "[", "ATTR_CLONES_UNIQUE", "]", "=", "self", ".", "_clones_unique", "if", "self", ".", "_views", "is", "not", "None", ":", "attrs", "[", "ATTR_VIEWS", "]", "=", "self", ".", "_views", "if", "self", ".", "_views_unique", "is", "not", "None", ":", "attrs", "[", "ATTR_VIEWS_UNIQUE", "]", "=", "self", ".", "_views_unique", "return", "attrs" ]
[ 121, 4 ]
[ 146, 20 ]
python
en
['en', 'en', 'en']
True
GitHubSensor.icon
(self)
Return the icon to use in the frontend.
Return the icon to use in the frontend.
def icon(self): """Return the icon to use in the frontend.""" return "mdi:github"
[ "def", "icon", "(", "self", ")", ":", "return", "\"mdi:github\"" ]
[ 149, 4 ]
[ 151, 27 ]
python
en
['en', 'en', 'en']
True
GitHubSensor.update
(self)
Collect updated data from GitHub API.
Collect updated data from GitHub API.
def update(self): """Collect updated data from GitHub API.""" self._github_data.update() self._name = self._github_data.name self._repository_path = self._github_data.repository_path self._available = self._github_data.available self._latest_commit_message = self._github_data.latest_commit_message self._latest_commit_sha = self._github_data.latest_commit_sha if self._github_data.latest_release_url is not None: self._latest_release_tag = self._github_data.latest_release_url.split( "tag/" )[1] else: self._latest_release_tag = None self._latest_release_url = self._github_data.latest_release_url self._state = self._github_data.latest_commit_sha[0:7] self._open_issue_count = self._github_data.open_issue_count self._latest_open_issue_url = self._github_data.latest_open_issue_url self._pull_request_count = self._github_data.pull_request_count self._latest_open_pr_url = self._github_data.latest_open_pr_url self._stargazers = self._github_data.stargazers self._forks = self._github_data.forks self._clones = self._github_data.clones self._clones_unique = self._github_data.clones_unique self._views = self._github_data.views self._views_unique = self._github_data.views_unique
[ "def", "update", "(", "self", ")", ":", "self", ".", "_github_data", ".", "update", "(", ")", "self", ".", "_name", "=", "self", ".", "_github_data", ".", "name", "self", ".", "_repository_path", "=", "self", ".", "_github_data", ".", "repository_path", "self", ".", "_available", "=", "self", ".", "_github_data", ".", "available", "self", ".", "_latest_commit_message", "=", "self", ".", "_github_data", ".", "latest_commit_message", "self", ".", "_latest_commit_sha", "=", "self", ".", "_github_data", ".", "latest_commit_sha", "if", "self", ".", "_github_data", ".", "latest_release_url", "is", "not", "None", ":", "self", ".", "_latest_release_tag", "=", "self", ".", "_github_data", ".", "latest_release_url", ".", "split", "(", "\"tag/\"", ")", "[", "1", "]", "else", ":", "self", ".", "_latest_release_tag", "=", "None", "self", ".", "_latest_release_url", "=", "self", ".", "_github_data", ".", "latest_release_url", "self", ".", "_state", "=", "self", ".", "_github_data", ".", "latest_commit_sha", "[", "0", ":", "7", "]", "self", ".", "_open_issue_count", "=", "self", ".", "_github_data", ".", "open_issue_count", "self", ".", "_latest_open_issue_url", "=", "self", ".", "_github_data", ".", "latest_open_issue_url", "self", ".", "_pull_request_count", "=", "self", ".", "_github_data", ".", "pull_request_count", "self", ".", "_latest_open_pr_url", "=", "self", ".", "_github_data", ".", "latest_open_pr_url", "self", ".", "_stargazers", "=", "self", ".", "_github_data", ".", "stargazers", "self", ".", "_forks", "=", "self", ".", "_github_data", ".", "forks", "self", ".", "_clones", "=", "self", ".", "_github_data", ".", "clones", "self", ".", "_clones_unique", "=", "self", ".", "_github_data", ".", "clones_unique", "self", ".", "_views", "=", "self", ".", "_github_data", ".", "views", "self", ".", "_views_unique", "=", "self", ".", "_github_data", ".", "views_unique" ]
[ 153, 4 ]
[ 179, 59 ]
python
en
['en', 'en', 'en']
True
GitHubData.__init__
(self, repository, access_token=None, server_url=None)
Set up GitHub.
Set up GitHub.
def __init__(self, repository, access_token=None, server_url=None): """Set up GitHub.""" self._github = github self.setup_error = False try: if server_url is not None: server_url += "/api/v3" self._github_obj = github.Github(access_token, base_url=server_url) else: self._github_obj = github.Github(access_token) self.repository_path = repository[CONF_PATH] repo = self._github_obj.get_repo(self.repository_path) except self._github.GithubException as err: _LOGGER.error("GitHub error for %s: %s", self.repository_path, err) self.setup_error = True return self.name = repository.get(CONF_NAME, repo.name) self.available = False self.latest_commit_message = None self.latest_commit_sha = None self.latest_release_url = None self.open_issue_count = None self.latest_open_issue_url = None self.pull_request_count = None self.latest_open_pr_url = None self.stargazers = None self.forks = None self.clones = None self.clones_unique = None self.views = None self.views_unique = None
[ "def", "__init__", "(", "self", ",", "repository", ",", "access_token", "=", "None", ",", "server_url", "=", "None", ")", ":", "self", ".", "_github", "=", "github", "self", ".", "setup_error", "=", "False", "try", ":", "if", "server_url", "is", "not", "None", ":", "server_url", "+=", "\"/api/v3\"", "self", ".", "_github_obj", "=", "github", ".", "Github", "(", "access_token", ",", "base_url", "=", "server_url", ")", "else", ":", "self", ".", "_github_obj", "=", "github", ".", "Github", "(", "access_token", ")", "self", ".", "repository_path", "=", "repository", "[", "CONF_PATH", "]", "repo", "=", "self", ".", "_github_obj", ".", "get_repo", "(", "self", ".", "repository_path", ")", "except", "self", ".", "_github", ".", "GithubException", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"GitHub error for %s: %s\"", ",", "self", ".", "repository_path", ",", "err", ")", "self", ".", "setup_error", "=", "True", "return", "self", ".", "name", "=", "repository", ".", "get", "(", "CONF_NAME", ",", "repo", ".", "name", ")", "self", ".", "available", "=", "False", "self", ".", "latest_commit_message", "=", "None", "self", ".", "latest_commit_sha", "=", "None", "self", ".", "latest_release_url", "=", "None", "self", ".", "open_issue_count", "=", "None", "self", ".", "latest_open_issue_url", "=", "None", "self", ".", "pull_request_count", "=", "None", "self", ".", "latest_open_pr_url", "=", "None", "self", ".", "stargazers", "=", "None", "self", ".", "forks", "=", "None", "self", ".", "clones", "=", "None", "self", ".", "clones_unique", "=", "None", "self", ".", "views", "=", "None", "self", ".", "views_unique", "=", "None" ]
[ 185, 4 ]
[ 220, 32 ]
python
en
['en', 'ceb', 'en']
True
GitHubData.update
(self)
Update GitHub Sensor.
Update GitHub Sensor.
def update(self): """Update GitHub Sensor.""" try: repo = self._github_obj.get_repo(self.repository_path) self.stargazers = repo.stargazers_count self.forks = repo.forks_count open_issues = repo.get_issues(state="open", sort="created") if open_issues is not None: self.open_issue_count = open_issues.totalCount if open_issues.totalCount > 0: self.latest_open_issue_url = open_issues[0].html_url open_pull_requests = repo.get_pulls(state="open", sort="created") if open_pull_requests is not None: self.pull_request_count = open_pull_requests.totalCount if open_pull_requests.totalCount > 0: self.latest_open_pr_url = open_pull_requests[0].html_url latest_commit = repo.get_commits()[0] self.latest_commit_sha = latest_commit.sha self.latest_commit_message = latest_commit.commit.message releases = repo.get_releases() if releases and releases.totalCount > 0: self.latest_release_url = releases[0].html_url if repo.permissions.push: clones = repo.get_clones_traffic() if clones is not None: self.clones = clones.get("count") self.clones_unique = clones.get("uniques") views = repo.get_views_traffic() if views is not None: self.views = views.get("count") self.views_unique = views.get("uniques") self.available = True except self._github.GithubException as err: _LOGGER.error("GitHub error for %s: %s", self.repository_path, err) self.available = False
[ "def", "update", "(", "self", ")", ":", "try", ":", "repo", "=", "self", ".", "_github_obj", ".", "get_repo", "(", "self", ".", "repository_path", ")", "self", ".", "stargazers", "=", "repo", ".", "stargazers_count", "self", ".", "forks", "=", "repo", ".", "forks_count", "open_issues", "=", "repo", ".", "get_issues", "(", "state", "=", "\"open\"", ",", "sort", "=", "\"created\"", ")", "if", "open_issues", "is", "not", "None", ":", "self", ".", "open_issue_count", "=", "open_issues", ".", "totalCount", "if", "open_issues", ".", "totalCount", ">", "0", ":", "self", ".", "latest_open_issue_url", "=", "open_issues", "[", "0", "]", ".", "html_url", "open_pull_requests", "=", "repo", ".", "get_pulls", "(", "state", "=", "\"open\"", ",", "sort", "=", "\"created\"", ")", "if", "open_pull_requests", "is", "not", "None", ":", "self", ".", "pull_request_count", "=", "open_pull_requests", ".", "totalCount", "if", "open_pull_requests", ".", "totalCount", ">", "0", ":", "self", ".", "latest_open_pr_url", "=", "open_pull_requests", "[", "0", "]", ".", "html_url", "latest_commit", "=", "repo", ".", "get_commits", "(", ")", "[", "0", "]", "self", ".", "latest_commit_sha", "=", "latest_commit", ".", "sha", "self", ".", "latest_commit_message", "=", "latest_commit", ".", "commit", ".", "message", "releases", "=", "repo", ".", "get_releases", "(", ")", "if", "releases", "and", "releases", ".", "totalCount", ">", "0", ":", "self", ".", "latest_release_url", "=", "releases", "[", "0", "]", ".", "html_url", "if", "repo", ".", "permissions", ".", "push", ":", "clones", "=", "repo", ".", "get_clones_traffic", "(", ")", "if", "clones", "is", "not", "None", ":", "self", ".", "clones", "=", "clones", ".", "get", "(", "\"count\"", ")", "self", ".", "clones_unique", "=", "clones", ".", "get", "(", "\"uniques\"", ")", "views", "=", "repo", ".", "get_views_traffic", "(", ")", "if", "views", "is", "not", "None", ":", "self", ".", "views", "=", "views", ".", "get", "(", "\"count\"", ")", "self", ".", "views_unique", "=", "views", ".", "get", "(", "\"uniques\"", ")", "self", ".", "available", "=", "True", "except", "self", ".", "_github", ".", "GithubException", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"GitHub error for %s: %s\"", ",", "self", ".", "repository_path", ",", "err", ")", "self", ".", "available", "=", "False" ]
[ 222, 4 ]
[ 264, 34 ]
python
en
['pl', 'xh', 'en']
False
entity_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
[ "def", "entity_reg", "(", "hass", ")", ":", "return", "mock_registry", "(", "hass", ")" ]
[ 11, 0 ]
[ 13, 30 ]
python
en
['en', 'fy', 'en']
True
test_file_value
(hass, entity_reg)
Test the File sensor.
Test the File sensor.
async def test_file_value(hass, entity_reg): """Test the File sensor.""" config = { "sensor": {"platform": "file", "name": "file1", "file_path": "mock.file1"} } m_open = mock_open(read_data="43\n45\n21") with patch( "homeassistant.components.file.sensor.open", m_open, create=True ), patch.object(hass.config, "is_allowed_path", return_value=True): assert await async_setup_component(hass, "sensor", config) await hass.async_block_till_done() state = hass.states.get("sensor.file1") assert state.state == "21"
[ "async", "def", "test_file_value", "(", "hass", ",", "entity_reg", ")", ":", "config", "=", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"file\"", ",", "\"name\"", ":", "\"file1\"", ",", "\"file_path\"", ":", "\"mock.file1\"", "}", "}", "m_open", "=", "mock_open", "(", "read_data", "=", "\"43\\n45\\n21\"", ")", "with", "patch", "(", "\"homeassistant.components.file.sensor.open\"", ",", "m_open", ",", "create", "=", "True", ")", ",", "patch", ".", "object", "(", "hass", ".", "config", ",", "\"is_allowed_path\"", ",", "return_value", "=", "True", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.file1\"", ")", "assert", "state", ".", "state", "==", "\"21\"" ]
[ 18, 0 ]
[ 32, 30 ]
python
en
['en', 'sm', 'en']
True
test_file_value_template
(hass, entity_reg)
Test the File sensor with JSON entries.
Test the File sensor with JSON entries.
async def test_file_value_template(hass, entity_reg): """Test the File sensor with JSON entries.""" config = { "sensor": { "platform": "file", "name": "file2", "file_path": "mock.file2", "value_template": "{{ value_json.temperature }}", } } data = '{"temperature": 29, "humidity": 31}\n' '{"temperature": 26, "humidity": 36}' m_open = mock_open(read_data=data) with patch( "homeassistant.components.file.sensor.open", m_open, create=True ), patch.object(hass.config, "is_allowed_path", return_value=True): assert await async_setup_component(hass, "sensor", config) await hass.async_block_till_done() state = hass.states.get("sensor.file2") assert state.state == "26"
[ "async", "def", "test_file_value_template", "(", "hass", ",", "entity_reg", ")", ":", "config", "=", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"file\"", ",", "\"name\"", ":", "\"file2\"", ",", "\"file_path\"", ":", "\"mock.file2\"", ",", "\"value_template\"", ":", "\"{{ value_json.temperature }}\"", ",", "}", "}", "data", "=", "'{\"temperature\": 29, \"humidity\": 31}\\n'", "'{\"temperature\": 26, \"humidity\": 36}'", "m_open", "=", "mock_open", "(", "read_data", "=", "data", ")", "with", "patch", "(", "\"homeassistant.components.file.sensor.open\"", ",", "m_open", ",", "create", "=", "True", ")", ",", "patch", ".", "object", "(", "hass", ".", "config", ",", "\"is_allowed_path\"", ",", "return_value", "=", "True", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.file2\"", ")", "assert", "state", ".", "state", "==", "\"26\"" ]
[ 37, 0 ]
[ 58, 30 ]
python
en
['en', 'en', 'en']
True
test_file_empty
(hass, entity_reg)
Test the File sensor with an empty file.
Test the File sensor with an empty file.
async def test_file_empty(hass, entity_reg): """Test the File sensor with an empty file.""" config = {"sensor": {"platform": "file", "name": "file3", "file_path": "mock.file"}} m_open = mock_open(read_data="") with patch( "homeassistant.components.file.sensor.open", m_open, create=True ), patch.object(hass.config, "is_allowed_path", return_value=True): assert await async_setup_component(hass, "sensor", config) await hass.async_block_till_done() state = hass.states.get("sensor.file3") assert state.state == STATE_UNKNOWN
[ "async", "def", "test_file_empty", "(", "hass", ",", "entity_reg", ")", ":", "config", "=", "{", "\"sensor\"", ":", "{", "\"platform\"", ":", "\"file\"", ",", "\"name\"", ":", "\"file3\"", ",", "\"file_path\"", ":", "\"mock.file\"", "}", "}", "m_open", "=", "mock_open", "(", "read_data", "=", "\"\"", ")", "with", "patch", "(", "\"homeassistant.components.file.sensor.open\"", ",", "m_open", ",", "create", "=", "True", ")", ",", "patch", ".", "object", "(", "hass", ".", "config", ",", "\"is_allowed_path\"", ",", "return_value", "=", "True", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sensor\"", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.file3\"", ")", "assert", "state", ".", "state", "==", "STATE_UNKNOWN" ]
[ 63, 0 ]
[ 75, 39 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], )
Set up Elgato Key Light based on a config entry.
Set up Elgato Key Light based on a config entry.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up Elgato Key Light based on a config entry.""" elgato: Elgato = hass.data[DOMAIN][entry.entry_id][DATA_ELGATO_CLIENT] info = await elgato.info() async_add_entities([ElgatoLight(entry.entry_id, elgato, info)], True)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "Callable", "[", "[", "List", "[", "Entity", "]", ",", "bool", "]", ",", "None", "]", ",", ")", "->", "None", ":", "elgato", ":", "Elgato", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "DATA_ELGATO_CLIENT", "]", "info", "=", "await", "elgato", ".", "info", "(", ")", "async_add_entities", "(", "[", "ElgatoLight", "(", "entry", ".", "entry_id", ",", "elgato", ",", "info", ")", "]", ",", "True", ")" ]
[ 36, 0 ]
[ 44, 73 ]
python
en
['en', 'zu', 'en']
True
ElgatoLight.__init__
( self, entry_id: str, elgato: Elgato, info: Info, )
Initialize Elgato Key Light.
Initialize Elgato Key Light.
def __init__( self, entry_id: str, elgato: Elgato, info: Info, ): """Initialize Elgato Key Light.""" self._brightness: Optional[int] = None self._info: Info = info self._state: Optional[bool] = None self._temperature: Optional[int] = None self._available = True self.elgato = elgato
[ "def", "__init__", "(", "self", ",", "entry_id", ":", "str", ",", "elgato", ":", "Elgato", ",", "info", ":", "Info", ",", ")", ":", "self", ".", "_brightness", ":", "Optional", "[", "int", "]", "=", "None", "self", ".", "_info", ":", "Info", "=", "info", "self", ".", "_state", ":", "Optional", "[", "bool", "]", "=", "None", "self", ".", "_temperature", ":", "Optional", "[", "int", "]", "=", "None", "self", ".", "_available", "=", "True", "self", ".", "elgato", "=", "elgato" ]
[ 50, 4 ]
[ 62, 28 ]
python
it
['it', 'zu', 'it']
True
ElgatoLight.name
(self)
Return the name of the entity.
Return the name of the entity.
def name(self) -> str: """Return the name of the entity.""" # Return the product name, if display name is not set if not self._info.display_name: return self._info.product_name return self._info.display_name
[ "def", "name", "(", "self", ")", "->", "str", ":", "# Return the product name, if display name is not set", "if", "not", "self", ".", "_info", ".", "display_name", ":", "return", "self", ".", "_info", ".", "product_name", "return", "self", ".", "_info", ".", "display_name" ]
[ 65, 4 ]
[ 70, 38 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self) -> bool: """Return True if entity is available.""" return self._available
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_available" ]
[ 73, 4 ]
[ 75, 30 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.unique_id
(self)
Return the unique ID for this sensor.
Return the unique ID for this sensor.
def unique_id(self) -> str: """Return the unique ID for this sensor.""" return self._info.serial_number
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_info", ".", "serial_number" ]
[ 78, 4 ]
[ 80, 39 ]
python
en
['en', 'la', 'en']
True
ElgatoLight.brightness
(self)
Return the brightness of this light between 1..255.
Return the brightness of this light between 1..255.
def brightness(self) -> Optional[int]: """Return the brightness of this light between 1..255.""" return self._brightness
[ "def", "brightness", "(", "self", ")", "->", "Optional", "[", "int", "]", ":", "return", "self", ".", "_brightness" ]
[ 83, 4 ]
[ 85, 31 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.color_temp
(self)
Return the CT color value in mireds.
Return the CT color value in mireds.
def color_temp(self): """Return the CT color value in mireds.""" return self._temperature
[ "def", "color_temp", "(", "self", ")", ":", "return", "self", ".", "_temperature" ]
[ 88, 4 ]
[ 90, 32 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.min_mireds
(self)
Return the coldest color_temp that this light supports.
Return the coldest color_temp that this light supports.
def min_mireds(self): """Return the coldest color_temp that this light supports.""" return 143
[ "def", "min_mireds", "(", "self", ")", ":", "return", "143" ]
[ 93, 4 ]
[ 95, 18 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.max_mireds
(self)
Return the warmest color_temp that this light supports.
Return the warmest color_temp that this light supports.
def max_mireds(self): """Return the warmest color_temp that this light supports.""" return 344
[ "def", "max_mireds", "(", "self", ")", ":", "return", "344" ]
[ 98, 4 ]
[ 100, 18 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> int: """Flag supported features.""" return SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_BRIGHTNESS", "|", "SUPPORT_COLOR_TEMP" ]
[ 103, 4 ]
[ 105, 54 ]
python
en
['da', 'en', 'en']
True
ElgatoLight.is_on
(self)
Return the state of the light.
Return the state of the light.
def is_on(self) -> bool: """Return the state of the light.""" return bool(self._state)
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "_state", ")" ]
[ 108, 4 ]
[ 110, 32 ]
python
en
['en', 'en', 'en']
True
ElgatoLight.async_turn_off
(self, **kwargs: Any)
Turn off the light.
Turn off the light.
async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" await self.async_turn_on(on=False)
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "await", "self", ".", "async_turn_on", "(", "on", "=", "False", ")" ]
[ 112, 4 ]
[ 114, 42 ]
python
en
['en', 'zh', 'en']
True
ElgatoLight.async_turn_on
(self, **kwargs: Any)
Turn on the light.
Turn on the light.
async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" data = {} data[ATTR_ON] = True if ATTR_ON in kwargs: data[ATTR_ON] = kwargs[ATTR_ON] if ATTR_COLOR_TEMP in kwargs: data[ATTR_TEMPERATURE] = kwargs[ATTR_COLOR_TEMP] if ATTR_BRIGHTNESS in kwargs: data[ATTR_BRIGHTNESS] = round((kwargs[ATTR_BRIGHTNESS] / 255) * 100) try: await self.elgato.light(**data) except ElgatoError: _LOGGER.error("An error occurred while updating the Elgato Key Light") self._available = False
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "data", "=", "{", "}", "data", "[", "ATTR_ON", "]", "=", "True", "if", "ATTR_ON", "in", "kwargs", ":", "data", "[", "ATTR_ON", "]", "=", "kwargs", "[", "ATTR_ON", "]", "if", "ATTR_COLOR_TEMP", "in", "kwargs", ":", "data", "[", "ATTR_TEMPERATURE", "]", "=", "kwargs", "[", "ATTR_COLOR_TEMP", "]", "if", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "data", "[", "ATTR_BRIGHTNESS", "]", "=", "round", "(", "(", "kwargs", "[", "ATTR_BRIGHTNESS", "]", "/", "255", ")", "*", "100", ")", "try", ":", "await", "self", ".", "elgato", ".", "light", "(", "*", "*", "data", ")", "except", "ElgatoError", ":", "_LOGGER", ".", "error", "(", "\"An error occurred while updating the Elgato Key Light\"", ")", "self", ".", "_available", "=", "False" ]
[ 116, 4 ]
[ 134, 35 ]
python
en
['en', 'et', 'en']
True
ElgatoLight.async_update
(self)
Update Elgato entity.
Update Elgato entity.
async def async_update(self) -> None: """Update Elgato entity.""" try: state: State = await self.elgato.state() except ElgatoError: if self._available: _LOGGER.error("An error occurred while updating the Elgato Key Light") self._available = False return self._available = True self._brightness = round((state.brightness * 255) / 100) self._state = state.on self._temperature = state.temperature
[ "async", "def", "async_update", "(", "self", ")", "->", "None", ":", "try", ":", "state", ":", "State", "=", "await", "self", ".", "elgato", ".", "state", "(", ")", "except", "ElgatoError", ":", "if", "self", ".", "_available", ":", "_LOGGER", ".", "error", "(", "\"An error occurred while updating the Elgato Key Light\"", ")", "self", ".", "_available", "=", "False", "return", "self", ".", "_available", "=", "True", "self", ".", "_brightness", "=", "round", "(", "(", "state", ".", "brightness", "*", "255", ")", "/", "100", ")", "self", ".", "_state", "=", "state", ".", "on", "self", ".", "_temperature", "=", "state", ".", "temperature" ]
[ 136, 4 ]
[ 149, 45 ]
python
es
['es', 'sr', 'it']
False
ElgatoLight.device_info
(self)
Return device information about this Elgato Key Light.
Return device information about this Elgato Key Light.
def device_info(self) -> Dict[str, Any]: """Return device information about this Elgato Key Light.""" return { ATTR_IDENTIFIERS: {(DOMAIN, self._info.serial_number)}, ATTR_NAME: self._info.product_name, ATTR_MANUFACTURER: "Elgato", ATTR_MODEL: self._info.product_name, ATTR_SOFTWARE_VERSION: f"{self._info.firmware_version} ({self._info.firmware_build_number})", }
[ "def", "device_info", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "ATTR_IDENTIFIERS", ":", "{", "(", "DOMAIN", ",", "self", ".", "_info", ".", "serial_number", ")", "}", ",", "ATTR_NAME", ":", "self", ".", "_info", ".", "product_name", ",", "ATTR_MANUFACTURER", ":", "\"Elgato\"", ",", "ATTR_MODEL", ":", "self", ".", "_info", ".", "product_name", ",", "ATTR_SOFTWARE_VERSION", ":", "f\"{self._info.firmware_version} ({self._info.firmware_build_number})\"", ",", "}" ]
[ 152, 4 ]
[ 160, 9 ]
python
en
['en', 'en', 'en']
True
ScriptVariables.__init__
(self, variables: Dict[str, Any])
Initialize script variables.
Initialize script variables.
def __init__(self, variables: Dict[str, Any]): """Initialize script variables.""" self.variables = variables self._has_template: Optional[bool] = None
[ "def", "__init__", "(", "self", ",", "variables", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "self", ".", "variables", "=", "variables", "self", ".", "_has_template", ":", "Optional", "[", "bool", "]", "=", "None" ]
[ 11, 4 ]
[ 14, 49 ]
python
en
['nl', 'fr', 'en']
False
ScriptVariables.async_render
( self, hass: HomeAssistant, run_variables: Optional[Mapping[str, Any]], *, render_as_defaults: bool = True, )
Render script variables. The run variables are used to compute the static variables. If `render_as_defaults` is True, the run variables will not be overridden.
Render script variables.
def async_render( self, hass: HomeAssistant, run_variables: Optional[Mapping[str, Any]], *, render_as_defaults: bool = True, ) -> Dict[str, Any]: """Render script variables. The run variables are used to compute the static variables. If `render_as_defaults` is True, the run variables will not be overridden. """ if self._has_template is None: self._has_template = template.is_complex(self.variables) template.attach(hass, self.variables) if not self._has_template: if render_as_defaults: rendered_variables = dict(self.variables) if run_variables is not None: rendered_variables.update(run_variables) else: rendered_variables = ( {} if run_variables is None else dict(run_variables) ) rendered_variables.update(self.variables) return rendered_variables rendered_variables = {} if run_variables is None else dict(run_variables) for key, value in self.variables.items(): # We can skip if we're going to override this key with # run variables anyway if render_as_defaults and key in rendered_variables: continue rendered_variables[key] = template.render_complex(value, rendered_variables) return rendered_variables
[ "def", "async_render", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "run_variables", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", ",", "*", ",", "render_as_defaults", ":", "bool", "=", "True", ",", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "if", "self", ".", "_has_template", "is", "None", ":", "self", ".", "_has_template", "=", "template", ".", "is_complex", "(", "self", ".", "variables", ")", "template", ".", "attach", "(", "hass", ",", "self", ".", "variables", ")", "if", "not", "self", ".", "_has_template", ":", "if", "render_as_defaults", ":", "rendered_variables", "=", "dict", "(", "self", ".", "variables", ")", "if", "run_variables", "is", "not", "None", ":", "rendered_variables", ".", "update", "(", "run_variables", ")", "else", ":", "rendered_variables", "=", "(", "{", "}", "if", "run_variables", "is", "None", "else", "dict", "(", "run_variables", ")", ")", "rendered_variables", ".", "update", "(", "self", ".", "variables", ")", "return", "rendered_variables", "rendered_variables", "=", "{", "}", "if", "run_variables", "is", "None", "else", "dict", "(", "run_variables", ")", "for", "key", ",", "value", "in", "self", ".", "variables", ".", "items", "(", ")", ":", "# We can skip if we're going to override this key with", "# run variables anyway", "if", "render_as_defaults", "and", "key", "in", "rendered_variables", ":", "continue", "rendered_variables", "[", "key", "]", "=", "template", ".", "render_complex", "(", "value", ",", "rendered_variables", ")", "return", "rendered_variables" ]
[ 17, 4 ]
[ 59, 33 ]
python
af
['da', 'af', 'en']
False
ScriptVariables.as_dict
(self)
Return dict version of this class.
Return dict version of this class.
def as_dict(self) -> dict: """Return dict version of this class.""" return self.variables
[ "def", "as_dict", "(", "self", ")", "->", "dict", ":", "return", "self", ".", "variables" ]
[ 61, 4 ]
[ 63, 29 ]
python
en
['en', 'en', 'en']
True
async_get_triggers
(hass: HomeAssistant, device_id: str)
List device triggers for Kodi devices.
List device triggers for Kodi devices.
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> List[dict]: """List device triggers for Kodi devices.""" registry = await entity_registry.async_get_registry(hass) triggers = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain == "media_player": triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turn_on", } ) triggers.append( { CONF_PLATFORM: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "turn_off", } ) return triggers
[ "async", "def", "async_get_triggers", "(", "hass", ":", "HomeAssistant", ",", "device_id", ":", "str", ")", "->", "List", "[", "dict", "]", ":", "registry", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "triggers", "=", "[", "]", "# Get all the integrations entities for this device", "for", "entry", "in", "entity_registry", ".", "async_entries_for_device", "(", "registry", ",", "device_id", ")", ":", "if", "entry", ".", "domain", "==", "\"media_player\"", ":", "triggers", ".", "append", "(", "{", "CONF_PLATFORM", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"turn_on\"", ",", "}", ")", "triggers", ".", "append", "(", "{", "CONF_PLATFORM", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"turn_off\"", ",", "}", ")", "return", "triggers" ]
[ 31, 0 ]
[ 58, 19 ]
python
en
['da', 'en', 'en']
True
async_attach_trigger
( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, )
Attach a trigger.
Attach a trigger.
async def async_attach_trigger( hass: HomeAssistant, config: ConfigType, action: AutomationActionType, automation_info: dict, ) -> CALLBACK_TYPE: """Attach a trigger.""" config = TRIGGER_SCHEMA(config) if config[CONF_TYPE] == "turn_on": return _attach_trigger(hass, config, action, EVENT_TURN_ON) if config[CONF_TYPE] == "turn_off": return _attach_trigger(hass, config, action, EVENT_TURN_OFF) return lambda: None
[ "async", "def", "async_attach_trigger", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "action", ":", "AutomationActionType", ",", "automation_info", ":", "dict", ",", ")", "->", "CALLBACK_TYPE", ":", "config", "=", "TRIGGER_SCHEMA", "(", "config", ")", "if", "config", "[", "CONF_TYPE", "]", "==", "\"turn_on\"", ":", "return", "_attach_trigger", "(", "hass", ",", "config", ",", "action", ",", "EVENT_TURN_ON", ")", "if", "config", "[", "CONF_TYPE", "]", "==", "\"turn_off\"", ":", "return", "_attach_trigger", "(", "hass", ",", "config", ",", "action", ",", "EVENT_TURN_OFF", ")", "return", "lambda", ":", "None" ]
[ 79, 0 ]
[ 94, 23 ]
python
en
['en', 'lb', 'en']
True