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
list | start_point
list | end_point
list | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
CimDataDumpUtil._dump_csv_file | (self, file_path: str, headers: List[str], line_generator: callable) | helper method to dump csv file
Args:
file_path(str): path of output csv file
headers(List[str]): list of header
line_generator(callable): generator function to generate line to write
| helper method to dump csv file | def _dump_csv_file(self, file_path: str, headers: List[str], line_generator: callable):
"""helper method to dump csv file
Args:
file_path(str): path of output csv file
headers(List[str]): list of header
line_generator(callable): generator function to generate line to write
"""
with open(file_path, "wt+", newline="") as fp:
writer = csv.writer(fp)
writer.writerow(headers)
for line in line_generator():
writer.writerow(line) | [
"def",
"_dump_csv_file",
"(",
"self",
",",
"file_path",
":",
"str",
",",
"headers",
":",
"List",
"[",
"str",
"]",
",",
"line_generator",
":",
"callable",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"\"wt+\"",
",",
"newline",
"=",
"\"\"",
")",
"as",
"fp",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"fp",
")",
"writer",
".",
"writerow",
"(",
"headers",
")",
"for",
"line",
"in",
"line_generator",
"(",
")",
":",
"writer",
".",
"writerow",
"(",
"line",
")"
] | [
209,
4
] | [
223,
37
] | python | en | ['en', 'et', 'en'] | True |
_CrossNeuronBlock.forward | (self, x) |
:param x: (bt, c, h, w)
:return:
|
:param x: (bt, c, h, w)
:return:
| def forward(self, x):
'''
:param x: (bt, c, h, w)
:return:
'''
bt, c, h, w = x.shape
residual = x
x_stretch = x.view(bt, c, h * w)
spblock_h = int(np.ceil(h / self.spatial_height))
spblock_w = int(np.ceil(w / self.spatial_width))
stride_h = int((h - self.spatial_height) / (spblock_h - 1)) if spblock_h > 1 else 0
stride_w = int((w - self.spatial_width) / (spblock_w - 1)) if spblock_w > 1 else 0
if self.spatial_height == h and self.spatial_width == w:
x_stacked = x_stretch # (b) x c x (h * w)
x_stacked = x_stacked.view(bt * self.nblocks_channel, c // self.nblocks_channel, -1)
x_v = x_stacked.permute(0, 2, 1).contiguous() # (b) x (h * w) x c
if self.enc_dec:
x_v = self.fc_in(x_v) # (b) x (h * w) x c
x_m = x_v.mean(1).view(-1, 1, c // self.nblocks_channel) # (b * h * w) x 1 x c
score = -(x_m - x_m.permute(0, 2, 1).contiguous())**2 # (b * h * w) x c x c
# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)
# x_v = F.dropout(x_v, 0.1, self.training)
# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)
attn = F.softmax(score, dim=1) # (b * h * w) x c x c
if self.communication:
if self.enc_dec:
out = self.bn(self.fc_out(torch.bmm(x_v, attn))) # (b) x (h * w) x c
else:
out = self.bn(torch.bmm(x_v, attn)) # (b) x (h * w) x c
else:
out = self.bn(self.fc_out(x_v)) # (b) x (h * w) x c
out = F.dropout(out.permute(0, 2, 1).contiguous().view(bt, c, h, w), 0.0, self.training)
return F.relu(residual + out)
else:
x = F.interpolate(x, (self.spatial_height, self.spatial_width))
x_stretch = x.view(bt, c, self.spatial_height * self.spatial_width)
x_stretch = x.view(bt * self.nblocks_channel, c // self.nblocks_channel, self.spatial_height * self.spatial_width)
x_stacked = x_stretch # (b) x c x (h * w)
x_v = x_stacked.permute(0, 2, 1).contiguous() # (b) x (h * w) x c
if self.enc_dec:
x_v = self.fc_in(x_v) # (b) x (h * w) x c
x_m = x_v.mean(1).view(-1, 1, c // self.nblocks_channel) # (b * h * w) x 1 x c
score = -(x_m - x_m.permute(0, 2, 1).contiguous())**2 # (b * h * w) x c x c
# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)
# x_v = F.dropout(x_v, 0.1, self.training)
# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)
attn = F.softmax(score, dim=1) # (b * h * w) x c x c
if self.communication:
if self.enc_dec:
out = self.bn(self.fc_out(torch.bmm(x_v, attn))) # (b) x (h * w) x c
else:
out = self.bn(torch.bmm(x_v, attn)) # (b) x (h * w) x c
else:
out = self.bn(self.fc_out(x_v)) # (b) x (h * w) x c
out = out.permute(0, 2, 1).contiguous().view(bt, c, self.spatial_height, self.spatial_width)
out = F.dropout(F.interpolate(out, (h, w)), 0.0, self.training)
return F.relu(residual + out) | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"bt",
",",
"c",
",",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"residual",
"=",
"x",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
",",
"c",
",",
"h",
"*",
"w",
")",
"spblock_h",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"h",
"/",
"self",
".",
"spatial_height",
")",
")",
"spblock_w",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"w",
"/",
"self",
".",
"spatial_width",
")",
")",
"stride_h",
"=",
"int",
"(",
"(",
"h",
"-",
"self",
".",
"spatial_height",
")",
"/",
"(",
"spblock_h",
"-",
"1",
")",
")",
"if",
"spblock_h",
">",
"1",
"else",
"0",
"stride_w",
"=",
"int",
"(",
"(",
"w",
"-",
"self",
".",
"spatial_width",
")",
"/",
"(",
"spblock_w",
"-",
"1",
")",
")",
"if",
"spblock_w",
">",
"1",
"else",
"0",
"if",
"self",
".",
"spatial_height",
"==",
"h",
"and",
"self",
".",
"spatial_width",
"==",
"w",
":",
"x_stacked",
"=",
"x_stretch",
"# (b) x c x (h * w)",
"x_stacked",
"=",
"x_stacked",
".",
"view",
"(",
"bt",
"*",
"self",
".",
"nblocks_channel",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
",",
"-",
"1",
")",
"x_v",
"=",
"x_stacked",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
"# (b) x (h * w) x c",
"if",
"self",
".",
"enc_dec",
":",
"x_v",
"=",
"self",
".",
"fc_in",
"(",
"x_v",
")",
"# (b) x (h * w) x c",
"x_m",
"=",
"x_v",
".",
"mean",
"(",
"1",
")",
".",
"view",
"(",
"-",
"1",
",",
"1",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
")",
"# (b * h * w) x 1 x c",
"score",
"=",
"-",
"(",
"x_m",
"-",
"x_m",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
")",
"**",
"2",
"# (b * h * w) x c x c",
"# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)",
"# x_v = F.dropout(x_v, 0.1, self.training)",
"# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)",
"attn",
"=",
"F",
".",
"softmax",
"(",
"score",
",",
"dim",
"=",
"1",
")",
"# (b * h * w) x c x c",
"if",
"self",
".",
"communication",
":",
"if",
"self",
".",
"enc_dec",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"x_v",
")",
")",
"# (b) x (h * w) x c",
"out",
"=",
"F",
".",
"dropout",
"(",
"out",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"bt",
",",
"c",
",",
"h",
",",
"w",
")",
",",
"0.0",
",",
"self",
".",
"training",
")",
"return",
"F",
".",
"relu",
"(",
"residual",
"+",
"out",
")",
"else",
":",
"x",
"=",
"F",
".",
"interpolate",
"(",
"x",
",",
"(",
"self",
".",
"spatial_height",
",",
"self",
".",
"spatial_width",
")",
")",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
",",
"c",
",",
"self",
".",
"spatial_height",
"*",
"self",
".",
"spatial_width",
")",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
"*",
"self",
".",
"nblocks_channel",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
",",
"self",
".",
"spatial_height",
"*",
"self",
".",
"spatial_width",
")",
"x_stacked",
"=",
"x_stretch",
"# (b) x c x (h * w)",
"x_v",
"=",
"x_stacked",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
"# (b) x (h * w) x c",
"if",
"self",
".",
"enc_dec",
":",
"x_v",
"=",
"self",
".",
"fc_in",
"(",
"x_v",
")",
"# (b) x (h * w) x c",
"x_m",
"=",
"x_v",
".",
"mean",
"(",
"1",
")",
".",
"view",
"(",
"-",
"1",
",",
"1",
",",
"c",
"//",
"self",
".",
"nblocks_channel",
")",
"# (b * h * w) x 1 x c",
"score",
"=",
"-",
"(",
"x_m",
"-",
"x_m",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
")",
"**",
"2",
"# (b * h * w) x c x c",
"# score = torch.bmm(x_v.transpose(1, 2).contiguous(), x_v)",
"# x_v = F.dropout(x_v, 0.1, self.training)",
"# score.masked_fill_(self.mask.unsqueeze(0).expand_as(score).type_as(score).eq(0), -np.inf)",
"attn",
"=",
"F",
".",
"softmax",
"(",
"score",
",",
"dim",
"=",
"1",
")",
"# (b * h * w) x c x c",
"if",
"self",
".",
"communication",
":",
"if",
"self",
".",
"enc_dec",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"torch",
".",
"bmm",
"(",
"x_v",
",",
"attn",
")",
")",
"# (b) x (h * w) x c",
"else",
":",
"out",
"=",
"self",
".",
"bn",
"(",
"self",
".",
"fc_out",
"(",
"x_v",
")",
")",
"# (b) x (h * w) x c",
"out",
"=",
"out",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"bt",
",",
"c",
",",
"self",
".",
"spatial_height",
",",
"self",
".",
"spatial_width",
")",
"out",
"=",
"F",
".",
"dropout",
"(",
"F",
".",
"interpolate",
"(",
"out",
",",
"(",
"h",
",",
"w",
")",
")",
",",
"0.0",
",",
"self",
".",
"training",
")",
"return",
"F",
".",
"relu",
"(",
"residual",
"+",
"out",
")"
] | [
72,
4
] | [
136,
41
] | python | en | ['en', 'error', 'th'] | False |
get_mac_address_from_doorstation_info | (doorstation_info) | Get the mac address depending on the device type. | Get the mac address depending on the device type. | def get_mac_address_from_doorstation_info(doorstation_info):
"""Get the mac address depending on the device type."""
if "PRIMARY_MAC_ADDR" in doorstation_info:
return doorstation_info["PRIMARY_MAC_ADDR"]
return doorstation_info["WIFI_MAC_ADDR"] | [
"def",
"get_mac_address_from_doorstation_info",
"(",
"doorstation_info",
")",
":",
"if",
"\"PRIMARY_MAC_ADDR\"",
"in",
"doorstation_info",
":",
"return",
"doorstation_info",
"[",
"\"PRIMARY_MAC_ADDR\"",
"]",
"return",
"doorstation_info",
"[",
"\"WIFI_MAC_ADDR\"",
"]"
] | [
5,
0
] | [
9,
44
] | python | en | ['en', 'en', 'en'] | True |
get_doorstation_by_token | (hass, token) | Get doorstation by token. | Get doorstation by token. | def get_doorstation_by_token(hass, token):
"""Get doorstation by token."""
return _get_doorstation_by_attr(hass, "token", token) | [
"def",
"get_doorstation_by_token",
"(",
"hass",
",",
"token",
")",
":",
"return",
"_get_doorstation_by_attr",
"(",
"hass",
",",
"\"token\"",
",",
"token",
")"
] | [
12,
0
] | [
14,
57
] | python | nl | ['en', 'nl', 'nl'] | True |
get_doorstation_by_slug | (hass, slug) | Get doorstation by slug. | Get doorstation by slug. | def get_doorstation_by_slug(hass, slug):
"""Get doorstation by slug."""
return _get_doorstation_by_attr(hass, "slug", slug) | [
"def",
"get_doorstation_by_slug",
"(",
"hass",
",",
"slug",
")",
":",
"return",
"_get_doorstation_by_attr",
"(",
"hass",
",",
"\"slug\"",
",",
"slug",
")"
] | [
17,
0
] | [
19,
55
] | python | en | ['en', 'da', 'en'] | True |
get_all_doorstations | (hass) | Get all doorstations. | Get all doorstations. | def get_all_doorstations(hass):
"""Get all doorstations."""
return [
entry[DOOR_STATION]
for entry in hass.data[DOMAIN].values()
if DOOR_STATION in entry
] | [
"def",
"get_all_doorstations",
"(",
"hass",
")",
":",
"return",
"[",
"entry",
"[",
"DOOR_STATION",
"]",
"for",
"entry",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"values",
"(",
")",
"if",
"DOOR_STATION",
"in",
"entry",
"]"
] | [
35,
0
] | [
41,
5
] | python | en | ['en', 'sv', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Threshold sensor. | Set up the Threshold sensor. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Threshold sensor."""
entity_id = config.get(CONF_ENTITY_ID)
name = config.get(CONF_NAME)
lower = config.get(CONF_LOWER)
upper = config.get(CONF_UPPER)
hysteresis = config.get(CONF_HYSTERESIS)
device_class = config.get(CONF_DEVICE_CLASS)
async_add_entities(
[
ThresholdSensor(
hass, entity_id, name, lower, upper, hysteresis, device_class
)
],
True,
) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"entity_id",
"=",
"config",
".",
"get",
"(",
"CONF_ENTITY_ID",
")",
"name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
"lower",
"=",
"config",
".",
"get",
"(",
"CONF_LOWER",
")",
"upper",
"=",
"config",
".",
"get",
"(",
"CONF_UPPER",
")",
"hysteresis",
"=",
"config",
".",
"get",
"(",
"CONF_HYSTERESIS",
")",
"device_class",
"=",
"config",
".",
"get",
"(",
"CONF_DEVICE_CLASS",
")",
"async_add_entities",
"(",
"[",
"ThresholdSensor",
"(",
"hass",
",",
"entity_id",
",",
"name",
",",
"lower",
",",
"upper",
",",
"hysteresis",
",",
"device_class",
")",
"]",
",",
"True",
",",
")"
] | [
58,
0
] | [
74,
5
] | python | en | ['en', 'bg-Latn', 'en'] | True |
ThresholdSensor.__init__ | (self, hass, entity_id, name, lower, upper, hysteresis, device_class) | Initialize the Threshold sensor. | Initialize the Threshold sensor. | def __init__(self, hass, entity_id, name, lower, upper, hysteresis, device_class):
"""Initialize the Threshold sensor."""
self._hass = hass
self._entity_id = entity_id
self._name = name
self._threshold_lower = lower
self._threshold_upper = upper
self._hysteresis = hysteresis
self._device_class = device_class
self._state_position = None
self._state = False
self.sensor_value = None
@callback
def async_threshold_sensor_state_listener(event):
"""Handle sensor state changes."""
new_state = event.data.get("new_state")
if new_state is None:
return
try:
self.sensor_value = (
None if new_state.state == STATE_UNKNOWN else float(new_state.state)
)
except (ValueError, TypeError):
self.sensor_value = None
_LOGGER.warning("State is not numerical")
hass.async_add_job(self.async_update_ha_state, True)
async_track_state_change_event(
hass, [entity_id], async_threshold_sensor_state_listener
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"entity_id",
",",
"name",
",",
"lower",
",",
"upper",
",",
"hysteresis",
",",
"device_class",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_entity_id",
"=",
"entity_id",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_threshold_lower",
"=",
"lower",
"self",
".",
"_threshold_upper",
"=",
"upper",
"self",
".",
"_hysteresis",
"=",
"hysteresis",
"self",
".",
"_device_class",
"=",
"device_class",
"self",
".",
"_state_position",
"=",
"None",
"self",
".",
"_state",
"=",
"False",
"self",
".",
"sensor_value",
"=",
"None",
"@",
"callback",
"def",
"async_threshold_sensor_state_listener",
"(",
"event",
")",
":",
"\"\"\"Handle sensor state changes.\"\"\"",
"new_state",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"new_state\"",
")",
"if",
"new_state",
"is",
"None",
":",
"return",
"try",
":",
"self",
".",
"sensor_value",
"=",
"(",
"None",
"if",
"new_state",
".",
"state",
"==",
"STATE_UNKNOWN",
"else",
"float",
"(",
"new_state",
".",
"state",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"self",
".",
"sensor_value",
"=",
"None",
"_LOGGER",
".",
"warning",
"(",
"\"State is not numerical\"",
")",
"hass",
".",
"async_add_job",
"(",
"self",
".",
"async_update_ha_state",
",",
"True",
")",
"async_track_state_change_event",
"(",
"hass",
",",
"[",
"entity_id",
"]",
",",
"async_threshold_sensor_state_listener",
")"
] | [
80,
4
] | [
113,
9
] | python | en | ['en', 'en', 'en'] | True |
ThresholdSensor.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"
] | [
116,
4
] | [
118,
25
] | python | en | ['en', 'mi', 'en'] | True |
ThresholdSensor.is_on | (self) | Return true if sensor is on. | Return true if sensor is on. | def is_on(self):
"""Return true if sensor is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
121,
4
] | [
123,
26
] | python | en | ['en', 'et', 'en'] | True |
ThresholdSensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
126,
4
] | [
128,
20
] | python | en | ['en', 'en', 'en'] | True |
ThresholdSensor.device_class | (self) | Return the sensor class of the sensor. | Return the sensor class of the sensor. | def device_class(self):
"""Return the sensor class of the sensor."""
return self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
131,
4
] | [
133,
33
] | python | en | ['en', 'sq', 'en'] | True |
ThresholdSensor.threshold_type | (self) | Return the type of threshold this sensor represents. | Return the type of threshold this sensor represents. | def threshold_type(self):
"""Return the type of threshold this sensor represents."""
if self._threshold_lower is not None and self._threshold_upper is not None:
return TYPE_RANGE
if self._threshold_lower is not None:
return TYPE_LOWER
if self._threshold_upper is not None:
return TYPE_UPPER | [
"def",
"threshold_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_threshold_lower",
"is",
"not",
"None",
"and",
"self",
".",
"_threshold_upper",
"is",
"not",
"None",
":",
"return",
"TYPE_RANGE",
"if",
"self",
".",
"_threshold_lower",
"is",
"not",
"None",
":",
"return",
"TYPE_LOWER",
"if",
"self",
".",
"_threshold_upper",
"is",
"not",
"None",
":",
"return",
"TYPE_UPPER"
] | [
136,
4
] | [
143,
29
] | python | en | ['en', 'en', 'en'] | True |
ThresholdSensor.device_state_attributes | (self) | Return the state attributes of the sensor. | Return the state attributes of the sensor. | def device_state_attributes(self):
"""Return the state attributes of the sensor."""
return {
ATTR_ENTITY_ID: self._entity_id,
ATTR_HYSTERESIS: self._hysteresis,
ATTR_LOWER: self._threshold_lower,
ATTR_POSITION: self._state_position,
ATTR_SENSOR_VALUE: self.sensor_value,
ATTR_TYPE: self.threshold_type,
ATTR_UPPER: self._threshold_upper,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"ATTR_ENTITY_ID",
":",
"self",
".",
"_entity_id",
",",
"ATTR_HYSTERESIS",
":",
"self",
".",
"_hysteresis",
",",
"ATTR_LOWER",
":",
"self",
".",
"_threshold_lower",
",",
"ATTR_POSITION",
":",
"self",
".",
"_state_position",
",",
"ATTR_SENSOR_VALUE",
":",
"self",
".",
"sensor_value",
",",
"ATTR_TYPE",
":",
"self",
".",
"threshold_type",
",",
"ATTR_UPPER",
":",
"self",
".",
"_threshold_upper",
",",
"}"
] | [
146,
4
] | [
156,
9
] | python | en | ['en', 'en', 'en'] | True |
ThresholdSensor.async_update | (self) | Get the latest data and updates the states. | Get the latest data and updates the states. | async def async_update(self):
"""Get the latest data and updates the states."""
def below(threshold):
"""Determine if the sensor value is below a threshold."""
return self.sensor_value < (threshold - self._hysteresis)
def above(threshold):
"""Determine if the sensor value is above a threshold."""
return self.sensor_value > (threshold + self._hysteresis)
if self.sensor_value is None:
self._state_position = POSITION_UNKNOWN
self._state = False
elif self.threshold_type == TYPE_LOWER:
if below(self._threshold_lower):
self._state_position = POSITION_BELOW
self._state = True
elif above(self._threshold_lower):
self._state_position = POSITION_ABOVE
self._state = False
elif self.threshold_type == TYPE_UPPER:
if above(self._threshold_upper):
self._state_position = POSITION_ABOVE
self._state = True
elif below(self._threshold_upper):
self._state_position = POSITION_BELOW
self._state = False
elif self.threshold_type == TYPE_RANGE:
if below(self._threshold_lower):
self._state_position = POSITION_BELOW
self._state = False
if above(self._threshold_upper):
self._state_position = POSITION_ABOVE
self._state = False
elif above(self._threshold_lower) and below(self._threshold_upper):
self._state_position = POSITION_IN_RANGE
self._state = True | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"def",
"below",
"(",
"threshold",
")",
":",
"\"\"\"Determine if the sensor value is below a threshold.\"\"\"",
"return",
"self",
".",
"sensor_value",
"<",
"(",
"threshold",
"-",
"self",
".",
"_hysteresis",
")",
"def",
"above",
"(",
"threshold",
")",
":",
"\"\"\"Determine if the sensor value is above a threshold.\"\"\"",
"return",
"self",
".",
"sensor_value",
">",
"(",
"threshold",
"+",
"self",
".",
"_hysteresis",
")",
"if",
"self",
".",
"sensor_value",
"is",
"None",
":",
"self",
".",
"_state_position",
"=",
"POSITION_UNKNOWN",
"self",
".",
"_state",
"=",
"False",
"elif",
"self",
".",
"threshold_type",
"==",
"TYPE_LOWER",
":",
"if",
"below",
"(",
"self",
".",
"_threshold_lower",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_BELOW",
"self",
".",
"_state",
"=",
"True",
"elif",
"above",
"(",
"self",
".",
"_threshold_lower",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_ABOVE",
"self",
".",
"_state",
"=",
"False",
"elif",
"self",
".",
"threshold_type",
"==",
"TYPE_UPPER",
":",
"if",
"above",
"(",
"self",
".",
"_threshold_upper",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_ABOVE",
"self",
".",
"_state",
"=",
"True",
"elif",
"below",
"(",
"self",
".",
"_threshold_upper",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_BELOW",
"self",
".",
"_state",
"=",
"False",
"elif",
"self",
".",
"threshold_type",
"==",
"TYPE_RANGE",
":",
"if",
"below",
"(",
"self",
".",
"_threshold_lower",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_BELOW",
"self",
".",
"_state",
"=",
"False",
"if",
"above",
"(",
"self",
".",
"_threshold_upper",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_ABOVE",
"self",
".",
"_state",
"=",
"False",
"elif",
"above",
"(",
"self",
".",
"_threshold_lower",
")",
"and",
"below",
"(",
"self",
".",
"_threshold_upper",
")",
":",
"self",
".",
"_state_position",
"=",
"POSITION_IN_RANGE",
"self",
".",
"_state",
"=",
"True"
] | [
158,
4
] | [
198,
34
] | python | en | ['en', 'en', 'en'] | True |
_async_reproduce_state | (
hass: HomeAssistantType,
state: State,
*,
context: Optional[Context] = None,
reproduce_options: Optional[Dict[str, Any]] = None,
) | Reproduce a single state. | Reproduce a single state. | async def _async_reproduce_state(
hass: HomeAssistantType,
state: State,
*,
context: Optional[Context] = None,
reproduce_options: Optional[Dict[str, Any]] = None,
) -> None:
"""Reproduce a single state."""
cur_state = hass.states.get(state.entity_id)
if cur_state is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id)
return
if state.state not in VALID_STATES:
_LOGGER.warning(
"Invalid state specified for %s: %s", state.entity_id, state.state
)
return
# Return if we are already at the right state.
if cur_state.state == state.state and all(
check_attr_equal(cur_state.attributes, state.attributes, attr)
for attr in ATTRIBUTES
):
return
service_data = {ATTR_ENTITY_ID: state.entity_id}
service_calls = {} # service: service_data
if state.state == STATE_ON:
# The fan should be on
if cur_state.state != STATE_ON:
# Turn on the fan at first
service_calls[SERVICE_TURN_ON] = service_data
for attr, service in ATTRIBUTES.items():
# Call services to adjust the attributes
if attr in state.attributes and not check_attr_equal(
state.attributes, cur_state.attributes, attr
):
data = service_data.copy()
data[attr] = state.attributes[attr]
service_calls[service] = data
elif state.state == STATE_OFF:
service_calls[SERVICE_TURN_OFF] = service_data
for service, data in service_calls.items():
await hass.services.async_call(
DOMAIN, service, data, context=context, blocking=True
) | [
"async",
"def",
"_async_reproduce_state",
"(",
"hass",
":",
"HomeAssistantType",
",",
"state",
":",
"State",
",",
"*",
",",
"context",
":",
"Optional",
"[",
"Context",
"]",
"=",
"None",
",",
"reproduce_options",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"cur_state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"state",
".",
"entity_id",
")",
"if",
"cur_state",
"is",
"None",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Unable to find entity %s\"",
",",
"state",
".",
"entity_id",
")",
"return",
"if",
"state",
".",
"state",
"not",
"in",
"VALID_STATES",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Invalid state specified for %s: %s\"",
",",
"state",
".",
"entity_id",
",",
"state",
".",
"state",
")",
"return",
"# Return if we are already at the right state.",
"if",
"cur_state",
".",
"state",
"==",
"state",
".",
"state",
"and",
"all",
"(",
"check_attr_equal",
"(",
"cur_state",
".",
"attributes",
",",
"state",
".",
"attributes",
",",
"attr",
")",
"for",
"attr",
"in",
"ATTRIBUTES",
")",
":",
"return",
"service_data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"state",
".",
"entity_id",
"}",
"service_calls",
"=",
"{",
"}",
"# service: service_data",
"if",
"state",
".",
"state",
"==",
"STATE_ON",
":",
"# The fan should be on",
"if",
"cur_state",
".",
"state",
"!=",
"STATE_ON",
":",
"# Turn on the fan at first",
"service_calls",
"[",
"SERVICE_TURN_ON",
"]",
"=",
"service_data",
"for",
"attr",
",",
"service",
"in",
"ATTRIBUTES",
".",
"items",
"(",
")",
":",
"# Call services to adjust the attributes",
"if",
"attr",
"in",
"state",
".",
"attributes",
"and",
"not",
"check_attr_equal",
"(",
"state",
".",
"attributes",
",",
"cur_state",
".",
"attributes",
",",
"attr",
")",
":",
"data",
"=",
"service_data",
".",
"copy",
"(",
")",
"data",
"[",
"attr",
"]",
"=",
"state",
".",
"attributes",
"[",
"attr",
"]",
"service_calls",
"[",
"service",
"]",
"=",
"data",
"elif",
"state",
".",
"state",
"==",
"STATE_OFF",
":",
"service_calls",
"[",
"SERVICE_TURN_OFF",
"]",
"=",
"service_data",
"for",
"service",
",",
"data",
"in",
"service_calls",
".",
"items",
"(",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"service",
",",
"data",
",",
"context",
"=",
"context",
",",
"blocking",
"=",
"True",
")"
] | [
36,
0
] | [
87,
9
] | python | en | ['en', 'en', 'en'] | True |
async_reproduce_states | (
hass: HomeAssistantType,
states: Iterable[State],
*,
context: Optional[Context] = None,
reproduce_options: Optional[Dict[str, Any]] = None,
) | Reproduce Fan states. | Reproduce Fan states. | async def async_reproduce_states(
hass: HomeAssistantType,
states: Iterable[State],
*,
context: Optional[Context] = None,
reproduce_options: Optional[Dict[str, Any]] = None,
) -> None:
"""Reproduce Fan states."""
await asyncio.gather(
*(
_async_reproduce_state(
hass, state, context=context, reproduce_options=reproduce_options
)
for state in states
)
) | [
"async",
"def",
"async_reproduce_states",
"(",
"hass",
":",
"HomeAssistantType",
",",
"states",
":",
"Iterable",
"[",
"State",
"]",
",",
"*",
",",
"context",
":",
"Optional",
"[",
"Context",
"]",
"=",
"None",
",",
"reproduce_options",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"(",
"_async_reproduce_state",
"(",
"hass",
",",
"state",
",",
"context",
"=",
"context",
",",
"reproduce_options",
"=",
"reproduce_options",
")",
"for",
"state",
"in",
"states",
")",
")"
] | [
90,
0
] | [
105,
5
] | python | en | ['en', 'en', 'en'] | True |
check_attr_equal | (
attr1: MappingProxyType, attr2: MappingProxyType, attr_str: str
) | Return true if the given attributes are equal. | Return true if the given attributes are equal. | def check_attr_equal(
attr1: MappingProxyType, attr2: MappingProxyType, attr_str: str
) -> bool:
"""Return true if the given attributes are equal."""
return attr1.get(attr_str) == attr2.get(attr_str) | [
"def",
"check_attr_equal",
"(",
"attr1",
":",
"MappingProxyType",
",",
"attr2",
":",
"MappingProxyType",
",",
"attr_str",
":",
"str",
")",
"->",
"bool",
":",
"return",
"attr1",
".",
"get",
"(",
"attr_str",
")",
"==",
"attr2",
".",
"get",
"(",
"attr_str",
")"
] | [
108,
0
] | [
112,
53
] | python | en | ['en', 'en', 'en'] | True |
no_request_delay | () | Make the request refresh delay 0 for instant tests. | Make the request refresh delay 0 for instant tests. | def no_request_delay():
"""Make the request refresh delay 0 for instant tests."""
with patch("homeassistant.components.hue.light.REQUEST_REFRESH_DELAY", 0):
yield | [
"def",
"no_request_delay",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.hue.light.REQUEST_REFRESH_DELAY\"",
",",
"0",
")",
":",
"yield"
] | [
18,
0
] | [
21,
13
] | python | en | ['en', 'en', 'en'] | True |
create_mock_bridge | (hass) | Create a mock Hue bridge. | Create a mock Hue bridge. | def create_mock_bridge(hass):
"""Create a mock Hue bridge."""
bridge = Mock(
hass=hass,
available=True,
authorized=True,
allow_unreachable=False,
allow_groups=False,
api=Mock(),
reset_jobs=[],
spec=hue.HueBridge,
)
bridge.sensor_manager = hue_sensor_base.SensorManager(bridge)
bridge.mock_requests = []
# We're using a deque so we can schedule multiple responses
# and also means that `popleft()` will blow up if we get more updates
# than expected.
bridge.mock_light_responses = deque()
bridge.mock_group_responses = deque()
bridge.mock_sensor_responses = deque()
async def mock_request(method, path, **kwargs):
kwargs["method"] = method
kwargs["path"] = path
bridge.mock_requests.append(kwargs)
if path == "lights":
return bridge.mock_light_responses.popleft()
if path == "groups":
return bridge.mock_group_responses.popleft()
if path == "sensors":
return bridge.mock_sensor_responses.popleft()
return None
async def async_request_call(task):
await task()
bridge.async_request_call = async_request_call
bridge.api.config.apiversion = "9.9.9"
bridge.api.lights = Lights({}, mock_request)
bridge.api.groups = Groups({}, mock_request)
bridge.api.sensors = Sensors({}, mock_request)
return bridge | [
"def",
"create_mock_bridge",
"(",
"hass",
")",
":",
"bridge",
"=",
"Mock",
"(",
"hass",
"=",
"hass",
",",
"available",
"=",
"True",
",",
"authorized",
"=",
"True",
",",
"allow_unreachable",
"=",
"False",
",",
"allow_groups",
"=",
"False",
",",
"api",
"=",
"Mock",
"(",
")",
",",
"reset_jobs",
"=",
"[",
"]",
",",
"spec",
"=",
"hue",
".",
"HueBridge",
",",
")",
"bridge",
".",
"sensor_manager",
"=",
"hue_sensor_base",
".",
"SensorManager",
"(",
"bridge",
")",
"bridge",
".",
"mock_requests",
"=",
"[",
"]",
"# We're using a deque so we can schedule multiple responses",
"# and also means that `popleft()` will blow up if we get more updates",
"# than expected.",
"bridge",
".",
"mock_light_responses",
"=",
"deque",
"(",
")",
"bridge",
".",
"mock_group_responses",
"=",
"deque",
"(",
")",
"bridge",
".",
"mock_sensor_responses",
"=",
"deque",
"(",
")",
"async",
"def",
"mock_request",
"(",
"method",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"method\"",
"]",
"=",
"method",
"kwargs",
"[",
"\"path\"",
"]",
"=",
"path",
"bridge",
".",
"mock_requests",
".",
"append",
"(",
"kwargs",
")",
"if",
"path",
"==",
"\"lights\"",
":",
"return",
"bridge",
".",
"mock_light_responses",
".",
"popleft",
"(",
")",
"if",
"path",
"==",
"\"groups\"",
":",
"return",
"bridge",
".",
"mock_group_responses",
".",
"popleft",
"(",
")",
"if",
"path",
"==",
"\"sensors\"",
":",
"return",
"bridge",
".",
"mock_sensor_responses",
".",
"popleft",
"(",
")",
"return",
"None",
"async",
"def",
"async_request_call",
"(",
"task",
")",
":",
"await",
"task",
"(",
")",
"bridge",
".",
"async_request_call",
"=",
"async_request_call",
"bridge",
".",
"api",
".",
"config",
".",
"apiversion",
"=",
"\"9.9.9\"",
"bridge",
".",
"api",
".",
"lights",
"=",
"Lights",
"(",
"{",
"}",
",",
"mock_request",
")",
"bridge",
".",
"api",
".",
"groups",
"=",
"Groups",
"(",
"{",
"}",
",",
"mock_request",
")",
"bridge",
".",
"api",
".",
"sensors",
"=",
"Sensors",
"(",
"{",
"}",
",",
"mock_request",
")",
"return",
"bridge"
] | [
24,
0
] | [
66,
17
] | python | en | ['en', 'st', 'en'] | True |
mock_api | (hass) | Mock the Hue api. | Mock the Hue api. | def mock_api(hass):
"""Mock the Hue api."""
api = Mock(initialize=AsyncMock())
api.mock_requests = []
api.mock_light_responses = deque()
api.mock_group_responses = deque()
api.mock_sensor_responses = deque()
api.mock_scene_responses = deque()
async def mock_request(method, path, **kwargs):
kwargs["method"] = method
kwargs["path"] = path
api.mock_requests.append(kwargs)
if path == "lights":
return api.mock_light_responses.popleft()
if path == "groups":
return api.mock_group_responses.popleft()
if path == "sensors":
return api.mock_sensor_responses.popleft()
if path == "scenes":
return api.mock_scene_responses.popleft()
return None
api.config.apiversion = "9.9.9"
api.lights = Lights({}, mock_request)
api.groups = Groups({}, mock_request)
api.sensors = Sensors({}, mock_request)
api.scenes = Scenes({}, mock_request)
return api | [
"def",
"mock_api",
"(",
"hass",
")",
":",
"api",
"=",
"Mock",
"(",
"initialize",
"=",
"AsyncMock",
"(",
")",
")",
"api",
".",
"mock_requests",
"=",
"[",
"]",
"api",
".",
"mock_light_responses",
"=",
"deque",
"(",
")",
"api",
".",
"mock_group_responses",
"=",
"deque",
"(",
")",
"api",
".",
"mock_sensor_responses",
"=",
"deque",
"(",
")",
"api",
".",
"mock_scene_responses",
"=",
"deque",
"(",
")",
"async",
"def",
"mock_request",
"(",
"method",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"method\"",
"]",
"=",
"method",
"kwargs",
"[",
"\"path\"",
"]",
"=",
"path",
"api",
".",
"mock_requests",
".",
"append",
"(",
"kwargs",
")",
"if",
"path",
"==",
"\"lights\"",
":",
"return",
"api",
".",
"mock_light_responses",
".",
"popleft",
"(",
")",
"if",
"path",
"==",
"\"groups\"",
":",
"return",
"api",
".",
"mock_group_responses",
".",
"popleft",
"(",
")",
"if",
"path",
"==",
"\"sensors\"",
":",
"return",
"api",
".",
"mock_sensor_responses",
".",
"popleft",
"(",
")",
"if",
"path",
"==",
"\"scenes\"",
":",
"return",
"api",
".",
"mock_scene_responses",
".",
"popleft",
"(",
")",
"return",
"None",
"api",
".",
"config",
".",
"apiversion",
"=",
"\"9.9.9\"",
"api",
".",
"lights",
"=",
"Lights",
"(",
"{",
"}",
",",
"mock_request",
")",
"api",
".",
"groups",
"=",
"Groups",
"(",
"{",
"}",
",",
"mock_request",
")",
"api",
".",
"sensors",
"=",
"Sensors",
"(",
"{",
"}",
",",
"mock_request",
")",
"api",
".",
"scenes",
"=",
"Scenes",
"(",
"{",
"}",
",",
"mock_request",
")",
"return",
"api"
] | [
70,
0
] | [
99,
14
] | python | en | ['en', 'haw', 'en'] | True |
mock_bridge | (hass) | Mock a Hue bridge. | Mock a Hue bridge. | def mock_bridge(hass):
"""Mock a Hue bridge."""
return create_mock_bridge(hass) | [
"def",
"mock_bridge",
"(",
"hass",
")",
":",
"return",
"create_mock_bridge",
"(",
"hass",
")"
] | [
103,
0
] | [
105,
35
] | python | en | ['en', 'st', 'en'] | True |
setup_bridge_for_sensors | (hass, mock_bridge, hostname=None) | Load the Hue platform with the provided bridge for sensor-related platforms. | Load the Hue platform with the provided bridge for sensor-related platforms. | async def setup_bridge_for_sensors(hass, mock_bridge, hostname=None):
"""Load the Hue platform with the provided bridge for sensor-related platforms."""
if hostname is None:
hostname = "mock-host"
hass.config.components.add(hue.DOMAIN)
config_entry = config_entries.ConfigEntry(
1,
hue.DOMAIN,
"Mock Title",
{"host": hostname},
"test",
config_entries.CONN_CLASS_LOCAL_POLL,
system_options={},
)
mock_bridge.config_entry = config_entry
hass.data[hue.DOMAIN] = {config_entry.entry_id: mock_bridge}
await hass.config_entries.async_forward_entry_setup(config_entry, "binary_sensor")
await hass.config_entries.async_forward_entry_setup(config_entry, "sensor")
# simulate a full setup by manually adding the bridge config entry
hass.config_entries._entries.append(config_entry)
# and make sure it completes before going further
await hass.async_block_till_done() | [
"async",
"def",
"setup_bridge_for_sensors",
"(",
"hass",
",",
"mock_bridge",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"hostname",
"is",
"None",
":",
"hostname",
"=",
"\"mock-host\"",
"hass",
".",
"config",
".",
"components",
".",
"add",
"(",
"hue",
".",
"DOMAIN",
")",
"config_entry",
"=",
"config_entries",
".",
"ConfigEntry",
"(",
"1",
",",
"hue",
".",
"DOMAIN",
",",
"\"Mock Title\"",
",",
"{",
"\"host\"",
":",
"hostname",
"}",
",",
"\"test\"",
",",
"config_entries",
".",
"CONN_CLASS_LOCAL_POLL",
",",
"system_options",
"=",
"{",
"}",
",",
")",
"mock_bridge",
".",
"config_entry",
"=",
"config_entry",
"hass",
".",
"data",
"[",
"hue",
".",
"DOMAIN",
"]",
"=",
"{",
"config_entry",
".",
"entry_id",
":",
"mock_bridge",
"}",
"await",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"config_entry",
",",
"\"binary_sensor\"",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"config_entry",
",",
"\"sensor\"",
")",
"# simulate a full setup by manually adding the bridge config entry",
"hass",
".",
"config_entries",
".",
"_entries",
".",
"append",
"(",
"config_entry",
")",
"# and make sure it completes before going further",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
108,
0
] | [
130,
38
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
) | Set up for AlarmDecoder sensor. | Set up for AlarmDecoder sensor. | async def async_setup_entry(
hass: HomeAssistantType, entry: ConfigEntry, async_add_entities
):
"""Set up for AlarmDecoder sensor."""
zones = entry.options.get(OPTIONS_ZONES, DEFAULT_ZONE_OPTIONS)
entities = []
for zone_num in zones:
zone_info = zones[zone_num]
zone_type = zone_info[CONF_ZONE_TYPE]
zone_name = zone_info[CONF_ZONE_NAME]
zone_rfid = zone_info.get(CONF_ZONE_RFID)
zone_loop = zone_info.get(CONF_ZONE_LOOP)
relay_addr = zone_info.get(CONF_RELAY_ADDR)
relay_chan = zone_info.get(CONF_RELAY_CHAN)
entity = AlarmDecoderBinarySensor(
zone_num, zone_name, zone_type, zone_rfid, zone_loop, relay_addr, relay_chan
)
entities.append(entity)
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
")",
":",
"zones",
"=",
"entry",
".",
"options",
".",
"get",
"(",
"OPTIONS_ZONES",
",",
"DEFAULT_ZONE_OPTIONS",
")",
"entities",
"=",
"[",
"]",
"for",
"zone_num",
"in",
"zones",
":",
"zone_info",
"=",
"zones",
"[",
"zone_num",
"]",
"zone_type",
"=",
"zone_info",
"[",
"CONF_ZONE_TYPE",
"]",
"zone_name",
"=",
"zone_info",
"[",
"CONF_ZONE_NAME",
"]",
"zone_rfid",
"=",
"zone_info",
".",
"get",
"(",
"CONF_ZONE_RFID",
")",
"zone_loop",
"=",
"zone_info",
".",
"get",
"(",
"CONF_ZONE_LOOP",
")",
"relay_addr",
"=",
"zone_info",
".",
"get",
"(",
"CONF_RELAY_ADDR",
")",
"relay_chan",
"=",
"zone_info",
".",
"get",
"(",
"CONF_RELAY_CHAN",
")",
"entity",
"=",
"AlarmDecoderBinarySensor",
"(",
"zone_num",
",",
"zone_name",
",",
"zone_type",
",",
"zone_rfid",
",",
"zone_loop",
",",
"relay_addr",
",",
"relay_chan",
")",
"entities",
".",
"append",
"(",
"entity",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
35,
0
] | [
56,
32
] | python | en | ['en', 'da', 'en'] | True |
AlarmDecoderBinarySensor.__init__ | (
self,
zone_number,
zone_name,
zone_type,
zone_rfid,
zone_loop,
relay_addr,
relay_chan,
) | Initialize the binary_sensor. | Initialize the binary_sensor. | def __init__(
self,
zone_number,
zone_name,
zone_type,
zone_rfid,
zone_loop,
relay_addr,
relay_chan,
):
"""Initialize the binary_sensor."""
self._zone_number = int(zone_number)
self._zone_type = zone_type
self._state = None
self._name = zone_name
self._rfid = zone_rfid
self._loop = zone_loop
self._rfstate = None
self._relay_addr = relay_addr
self._relay_chan = relay_chan | [
"def",
"__init__",
"(",
"self",
",",
"zone_number",
",",
"zone_name",
",",
"zone_type",
",",
"zone_rfid",
",",
"zone_loop",
",",
"relay_addr",
",",
"relay_chan",
",",
")",
":",
"self",
".",
"_zone_number",
"=",
"int",
"(",
"zone_number",
")",
"self",
".",
"_zone_type",
"=",
"zone_type",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_name",
"=",
"zone_name",
"self",
".",
"_rfid",
"=",
"zone_rfid",
"self",
".",
"_loop",
"=",
"zone_loop",
"self",
".",
"_rfstate",
"=",
"None",
"self",
".",
"_relay_addr",
"=",
"relay_addr",
"self",
".",
"_relay_chan",
"=",
"relay_chan"
] | [
62,
4
] | [
81,
37
] | python | en | ['en', 'haw', 'en'] | True |
AlarmDecoderBinarySensor.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_ZONE_FAULT, self._fault_callback
)
)
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_ZONE_RESTORE, self._restore_callback
)
)
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_RFX_MESSAGE, self._rfx_message_callback
)
)
self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_REL_MESSAGE, self._rel_message_callback
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"SIGNAL_ZONE_FAULT",
",",
"self",
".",
"_fault_callback",
")",
")",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"SIGNAL_ZONE_RESTORE",
",",
"self",
".",
"_restore_callback",
")",
")",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"SIGNAL_RFX_MESSAGE",
",",
"self",
".",
"_rfx_message_callback",
")",
")",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"hass",
".",
"helpers",
".",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"SIGNAL_REL_MESSAGE",
",",
"self",
".",
"_rel_message_callback",
")",
")"
] | [
83,
4
] | [
107,
9
] | python | en | ['en', 'no', 'en'] | False |
AlarmDecoderBinarySensor.name | (self) | Return the name of the entity. | Return the name of the entity. | def name(self):
"""Return the name of the entity."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
110,
4
] | [
112,
25
] | python | en | ['en', 'en', 'en'] | True |
AlarmDecoderBinarySensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
115,
4
] | [
117,
20
] | python | en | ['en', 'en', 'en'] | True |
AlarmDecoderBinarySensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
attr = {CONF_ZONE_NUMBER: self._zone_number}
if self._rfid and self._rfstate is not None:
attr[ATTR_RF_BIT0] = bool(self._rfstate & 0x01)
attr[ATTR_RF_LOW_BAT] = bool(self._rfstate & 0x02)
attr[ATTR_RF_SUPERVISED] = bool(self._rfstate & 0x04)
attr[ATTR_RF_BIT3] = bool(self._rfstate & 0x08)
attr[ATTR_RF_LOOP3] = bool(self._rfstate & 0x10)
attr[ATTR_RF_LOOP2] = bool(self._rfstate & 0x20)
attr[ATTR_RF_LOOP4] = bool(self._rfstate & 0x40)
attr[ATTR_RF_LOOP1] = bool(self._rfstate & 0x80)
return attr | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attr",
"=",
"{",
"CONF_ZONE_NUMBER",
":",
"self",
".",
"_zone_number",
"}",
"if",
"self",
".",
"_rfid",
"and",
"self",
".",
"_rfstate",
"is",
"not",
"None",
":",
"attr",
"[",
"ATTR_RF_BIT0",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x01",
")",
"attr",
"[",
"ATTR_RF_LOW_BAT",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x02",
")",
"attr",
"[",
"ATTR_RF_SUPERVISED",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x04",
")",
"attr",
"[",
"ATTR_RF_BIT3",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x08",
")",
"attr",
"[",
"ATTR_RF_LOOP3",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x10",
")",
"attr",
"[",
"ATTR_RF_LOOP2",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x20",
")",
"attr",
"[",
"ATTR_RF_LOOP4",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x40",
")",
"attr",
"[",
"ATTR_RF_LOOP1",
"]",
"=",
"bool",
"(",
"self",
".",
"_rfstate",
"&",
"0x80",
")",
"return",
"attr"
] | [
120,
4
] | [
132,
19
] | python | en | ['en', 'en', 'en'] | True |
AlarmDecoderBinarySensor.is_on | (self) | Return true if sensor is on. | Return true if sensor is on. | def is_on(self):
"""Return true if sensor is on."""
return self._state == 1 | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state",
"==",
"1"
] | [
135,
4
] | [
137,
31
] | python | en | ['en', 'et', 'en'] | True |
AlarmDecoderBinarySensor.device_class | (self) | Return the class of this sensor, from DEVICE_CLASSES. | Return the class of this sensor, from DEVICE_CLASSES. | def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
return self._zone_type | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_zone_type"
] | [
140,
4
] | [
142,
30
] | python | en | ['en', 'en', 'en'] | True |
AlarmDecoderBinarySensor._fault_callback | (self, zone) | Update the zone's state, if needed. | Update the zone's state, if needed. | def _fault_callback(self, zone):
"""Update the zone's state, if needed."""
if zone is None or int(zone) == self._zone_number:
self._state = 1
self.schedule_update_ha_state() | [
"def",
"_fault_callback",
"(",
"self",
",",
"zone",
")",
":",
"if",
"zone",
"is",
"None",
"or",
"int",
"(",
"zone",
")",
"==",
"self",
".",
"_zone_number",
":",
"self",
".",
"_state",
"=",
"1",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
144,
4
] | [
148,
43
] | python | en | ['en', 'en', 'en'] | True |
AlarmDecoderBinarySensor._restore_callback | (self, zone) | Update the zone's state, if needed. | Update the zone's state, if needed. | def _restore_callback(self, zone):
"""Update the zone's state, if needed."""
if zone is None or (int(zone) == self._zone_number and not self._loop):
self._state = 0
self.schedule_update_ha_state() | [
"def",
"_restore_callback",
"(",
"self",
",",
"zone",
")",
":",
"if",
"zone",
"is",
"None",
"or",
"(",
"int",
"(",
"zone",
")",
"==",
"self",
".",
"_zone_number",
"and",
"not",
"self",
".",
"_loop",
")",
":",
"self",
".",
"_state",
"=",
"0",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
150,
4
] | [
154,
43
] | python | en | ['en', 'en', 'en'] | True |
AlarmDecoderBinarySensor._rfx_message_callback | (self, message) | Update RF state. | Update RF state. | def _rfx_message_callback(self, message):
"""Update RF state."""
if self._rfid and message and message.serial_number == self._rfid:
self._rfstate = message.value
if self._loop:
self._state = 1 if message.loop[self._loop - 1] else 0
self.schedule_update_ha_state() | [
"def",
"_rfx_message_callback",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_rfid",
"and",
"message",
"and",
"message",
".",
"serial_number",
"==",
"self",
".",
"_rfid",
":",
"self",
".",
"_rfstate",
"=",
"message",
".",
"value",
"if",
"self",
".",
"_loop",
":",
"self",
".",
"_state",
"=",
"1",
"if",
"message",
".",
"loop",
"[",
"self",
".",
"_loop",
"-",
"1",
"]",
"else",
"0",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
156,
4
] | [
162,
43
] | python | en | ['en', 'co', 'en'] | True |
AlarmDecoderBinarySensor._rel_message_callback | (self, message) | Update relay / expander state. | Update relay / expander state. | def _rel_message_callback(self, message):
"""Update relay / expander state."""
if self._relay_addr == message.address and self._relay_chan == message.channel:
_LOGGER.debug(
"%s %d:%d value:%d",
"Relay" if message.type == message.RELAY else "ZoneExpander",
message.address,
message.channel,
message.value,
)
self._state = message.value
self.schedule_update_ha_state() | [
"def",
"_rel_message_callback",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_relay_addr",
"==",
"message",
".",
"address",
"and",
"self",
".",
"_relay_chan",
"==",
"message",
".",
"channel",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s %d:%d value:%d\"",
",",
"\"Relay\"",
"if",
"message",
".",
"type",
"==",
"message",
".",
"RELAY",
"else",
"\"ZoneExpander\"",
",",
"message",
".",
"address",
",",
"message",
".",
"channel",
",",
"message",
".",
"value",
",",
")",
"self",
".",
"_state",
"=",
"message",
".",
"value",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
164,
4
] | [
176,
43
] | python | en | ['sv', 'en', 'en'] | True |
setup | (hass, config) | Set up the Logentries component. | Set up the Logentries component. | def setup(hass, config):
"""Set up the Logentries component."""
conf = config[DOMAIN]
token = conf.get(CONF_TOKEN)
le_wh = f"{DEFAULT_HOST}{token}"
def logentries_event_listener(event):
"""Listen for new messages on the bus and sends them to Logentries."""
state = event.data.get("new_state")
if state is None:
return
try:
_state = state_helper.state_as_number(state)
except ValueError:
_state = state.state
json_body = [
{
"domain": state.domain,
"entity_id": state.object_id,
"attributes": dict(state.attributes),
"time": str(event.time_fired),
"value": _state,
}
]
try:
payload = {"host": le_wh, "event": json_body}
requests.post(le_wh, data=json.dumps(payload), timeout=10)
except requests.exceptions.RequestException as error:
_LOGGER.exception("Error sending to Logentries: %s", error)
hass.bus.listen(EVENT_STATE_CHANGED, logentries_event_listener)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"token",
"=",
"conf",
".",
"get",
"(",
"CONF_TOKEN",
")",
"le_wh",
"=",
"f\"{DEFAULT_HOST}{token}\"",
"def",
"logentries_event_listener",
"(",
"event",
")",
":",
"\"\"\"Listen for new messages on the bus and sends them to Logentries.\"\"\"",
"state",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"new_state\"",
")",
"if",
"state",
"is",
"None",
":",
"return",
"try",
":",
"_state",
"=",
"state_helper",
".",
"state_as_number",
"(",
"state",
")",
"except",
"ValueError",
":",
"_state",
"=",
"state",
".",
"state",
"json_body",
"=",
"[",
"{",
"\"domain\"",
":",
"state",
".",
"domain",
",",
"\"entity_id\"",
":",
"state",
".",
"object_id",
",",
"\"attributes\"",
":",
"dict",
"(",
"state",
".",
"attributes",
")",
",",
"\"time\"",
":",
"str",
"(",
"event",
".",
"time_fired",
")",
",",
"\"value\"",
":",
"_state",
",",
"}",
"]",
"try",
":",
"payload",
"=",
"{",
"\"host\"",
":",
"le_wh",
",",
"\"event\"",
":",
"json_body",
"}",
"requests",
".",
"post",
"(",
"le_wh",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
",",
"timeout",
"=",
"10",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"error",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Error sending to Logentries: %s\"",
",",
"error",
")",
"hass",
".",
"bus",
".",
"listen",
"(",
"EVENT_STATE_CHANGED",
",",
"logentries_event_listener",
")",
"return",
"True"
] | [
22,
0
] | [
54,
15
] | python | en | ['en', 'en', 'en'] | True |
test_setup | (hass: HomeAssistantType, fritz: Mock) | Test setup of integration. | Test setup of integration. | async def test_setup(hass: HomeAssistantType, fritz: Mock):
"""Test setup of integration."""
assert await async_setup_component(hass, FB_DOMAIN, MOCK_CONFIG)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries()
assert entries
assert entries[0].data[CONF_HOST] == "fake_host"
assert entries[0].data[CONF_PASSWORD] == "fake_pass"
assert entries[0].data[CONF_USERNAME] == "fake_user"
assert fritz.call_count == 1
assert fritz.call_args_list == [
call(host="fake_host", password="fake_pass", user="fake_user")
] | [
"async",
"def",
"test_setup",
"(",
"hass",
":",
"HomeAssistantType",
",",
"fritz",
":",
"Mock",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"FB_DOMAIN",
",",
"MOCK_CONFIG",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"entries",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
")",
"assert",
"entries",
"assert",
"entries",
"[",
"0",
"]",
".",
"data",
"[",
"CONF_HOST",
"]",
"==",
"\"fake_host\"",
"assert",
"entries",
"[",
"0",
"]",
".",
"data",
"[",
"CONF_PASSWORD",
"]",
"==",
"\"fake_pass\"",
"assert",
"entries",
"[",
"0",
"]",
".",
"data",
"[",
"CONF_USERNAME",
"]",
"==",
"\"fake_user\"",
"assert",
"fritz",
".",
"call_count",
"==",
"1",
"assert",
"fritz",
".",
"call_args_list",
"==",
"[",
"call",
"(",
"host",
"=",
"\"fake_host\"",
",",
"password",
"=",
"\"fake_pass\"",
",",
"user",
"=",
"\"fake_user\"",
")",
"]"
] | [
14,
0
] | [
26,
5
] | python | en | ['en', 'da', 'en'] | True |
test_setup_duplicate_config | (hass: HomeAssistantType, fritz: Mock, caplog) | Test duplicate config of integration. | Test duplicate config of integration. | async def test_setup_duplicate_config(hass: HomeAssistantType, fritz: Mock, caplog):
"""Test duplicate config of integration."""
DUPLICATE = {
FB_DOMAIN: {
CONF_DEVICES: [
MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0],
MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0],
]
}
}
assert not await async_setup_component(hass, FB_DOMAIN, DUPLICATE)
await hass.async_block_till_done()
assert not hass.states.async_entity_ids()
assert not hass.states.async_all()
assert "duplicate host entries found" in caplog.text | [
"async",
"def",
"test_setup_duplicate_config",
"(",
"hass",
":",
"HomeAssistantType",
",",
"fritz",
":",
"Mock",
",",
"caplog",
")",
":",
"DUPLICATE",
"=",
"{",
"FB_DOMAIN",
":",
"{",
"CONF_DEVICES",
":",
"[",
"MOCK_CONFIG",
"[",
"FB_DOMAIN",
"]",
"[",
"CONF_DEVICES",
"]",
"[",
"0",
"]",
",",
"MOCK_CONFIG",
"[",
"FB_DOMAIN",
"]",
"[",
"CONF_DEVICES",
"]",
"[",
"0",
"]",
",",
"]",
"}",
"}",
"assert",
"not",
"await",
"async_setup_component",
"(",
"hass",
",",
"FB_DOMAIN",
",",
"DUPLICATE",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"not",
"hass",
".",
"states",
".",
"async_entity_ids",
"(",
")",
"assert",
"not",
"hass",
".",
"states",
".",
"async_all",
"(",
")",
"assert",
"\"duplicate host entries found\"",
"in",
"caplog",
".",
"text"
] | [
29,
0
] | [
43,
56
] | python | en | ['en', 'en', 'en'] | True |
test_unload | (hass: HomeAssistantType, fritz: Mock) | Test unload of integration. | Test unload of integration. | async def test_unload(hass: HomeAssistantType, fritz: Mock):
"""Test unload of integration."""
fritz().get_devices.return_value = [FritzDeviceSwitchMock()]
entity_id = f"{SWITCH_DOMAIN}.fake_name"
entry = MockConfigEntry(
domain=FB_DOMAIN,
data=MOCK_CONFIG[FB_DOMAIN][CONF_DEVICES][0],
unique_id=entity_id,
)
entry.add_to_hass(hass)
config_entries = hass.config_entries.async_entries(FB_DOMAIN)
assert len(config_entries) == 1
assert entry is config_entries[0]
assert await async_setup_component(hass, FB_DOMAIN, {}) is True
await hass.async_block_till_done()
assert entry.state == ENTRY_STATE_LOADED
state = hass.states.get(entity_id)
assert state
await hass.config_entries.async_unload(entry.entry_id)
assert fritz().logout.call_count == 1
assert entry.state == ENTRY_STATE_NOT_LOADED
state = hass.states.get(entity_id)
assert state is None | [
"async",
"def",
"test_unload",
"(",
"hass",
":",
"HomeAssistantType",
",",
"fritz",
":",
"Mock",
")",
":",
"fritz",
"(",
")",
".",
"get_devices",
".",
"return_value",
"=",
"[",
"FritzDeviceSwitchMock",
"(",
")",
"]",
"entity_id",
"=",
"f\"{SWITCH_DOMAIN}.fake_name\"",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"FB_DOMAIN",
",",
"data",
"=",
"MOCK_CONFIG",
"[",
"FB_DOMAIN",
"]",
"[",
"CONF_DEVICES",
"]",
"[",
"0",
"]",
",",
"unique_id",
"=",
"entity_id",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"config_entries",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"FB_DOMAIN",
")",
"assert",
"len",
"(",
"config_entries",
")",
"==",
"1",
"assert",
"entry",
"is",
"config_entries",
"[",
"0",
"]",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"FB_DOMAIN",
",",
"{",
"}",
")",
"is",
"True",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"state",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"fritz",
"(",
")",
".",
"logout",
".",
"call_count",
"==",
"1",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_NOT_LOADED",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"state",
"is",
"None"
] | [
46,
0
] | [
74,
24
] | python | en | ['en', 'da', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the APCUPSd sensors. | Set up the APCUPSd sensors. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the APCUPSd sensors."""
apcups_data = hass.data[DOMAIN]
entities = []
for resource in config[CONF_RESOURCES]:
sensor_type = resource.lower()
if sensor_type not in SENSOR_TYPES:
SENSOR_TYPES[sensor_type] = [
sensor_type.title(),
"",
"mdi:information-outline",
]
if sensor_type.upper() not in apcups_data.status:
_LOGGER.warning(
"Sensor type: %s does not appear in the APCUPSd status output",
sensor_type,
)
entities.append(APCUPSdSensor(apcups_data, sensor_type))
add_entities(entities, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"apcups_data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"entities",
"=",
"[",
"]",
"for",
"resource",
"in",
"config",
"[",
"CONF_RESOURCES",
"]",
":",
"sensor_type",
"=",
"resource",
".",
"lower",
"(",
")",
"if",
"sensor_type",
"not",
"in",
"SENSOR_TYPES",
":",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"=",
"[",
"sensor_type",
".",
"title",
"(",
")",
",",
"\"\"",
",",
"\"mdi:information-outline\"",
",",
"]",
"if",
"sensor_type",
".",
"upper",
"(",
")",
"not",
"in",
"apcups_data",
".",
"status",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Sensor type: %s does not appear in the APCUPSd status output\"",
",",
"sensor_type",
",",
")",
"entities",
".",
"append",
"(",
"APCUPSdSensor",
"(",
"apcups_data",
",",
"sensor_type",
")",
")",
"add_entities",
"(",
"entities",
",",
"True",
")"
] | [
119,
0
] | [
142,
32
] | python | en | ['en', 'ca', 'en'] | True |
infer_unit | (value) | If the value ends with any of the units from ALL_UNITS.
Split the unit off the end of the value and return the value, unit tuple
pair. Else return the original value and None as the unit.
| If the value ends with any of the units from ALL_UNITS. | def infer_unit(value):
"""If the value ends with any of the units from ALL_UNITS.
Split the unit off the end of the value and return the value, unit tuple
pair. Else return the original value and None as the unit.
"""
for unit in ALL_UNITS:
if value.endswith(unit):
return value[: -len(unit)], INFERRED_UNITS.get(unit, unit.strip())
return value, None | [
"def",
"infer_unit",
"(",
"value",
")",
":",
"for",
"unit",
"in",
"ALL_UNITS",
":",
"if",
"value",
".",
"endswith",
"(",
"unit",
")",
":",
"return",
"value",
"[",
":",
"-",
"len",
"(",
"unit",
")",
"]",
",",
"INFERRED_UNITS",
".",
"get",
"(",
"unit",
",",
"unit",
".",
"strip",
"(",
")",
")",
"return",
"value",
",",
"None"
] | [
145,
0
] | [
155,
22
] | python | en | ['en', 'en', 'en'] | True |
APCUPSdSensor.__init__ | (self, data, sensor_type) | Initialize the sensor. | Initialize the sensor. | def __init__(self, data, sensor_type):
"""Initialize the sensor."""
self._data = data
self.type = sensor_type
self._name = SENSOR_PREFIX + SENSOR_TYPES[sensor_type][0]
self._unit = SENSOR_TYPES[sensor_type][1]
self._inferred_unit = None
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"sensor_type",
")",
":",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"type",
"=",
"sensor_type",
"self",
".",
"_name",
"=",
"SENSOR_PREFIX",
"+",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"0",
"]",
"self",
".",
"_unit",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"1",
"]",
"self",
".",
"_inferred_unit",
"=",
"None",
"self",
".",
"_state",
"=",
"None"
] | [
161,
4
] | [
168,
26
] | python | en | ['en', 'en', 'en'] | True |
APCUPSdSensor.name | (self) | Return the name of the UPS sensor. | Return the name of the UPS sensor. | def name(self):
"""Return the name of the UPS sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
171,
4
] | [
173,
25
] | python | en | ['en', 'mi', 'en'] | True |
APCUPSdSensor.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 SENSOR_TYPES[self.type][2] | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"SENSOR_TYPES",
"[",
"self",
".",
"type",
"]",
"[",
"2",
"]"
] | [
176,
4
] | [
178,
41
] | python | en | ['en', 'en', 'en'] | True |
APCUPSdSensor.state | (self) | Return true if the UPS is online, else False. | Return true if the UPS is online, else False. | def state(self):
"""Return true if the UPS is online, else False."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
181,
4
] | [
183,
26
] | python | en | ['en', 'da', 'en'] | True |
APCUPSdSensor.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
if not self._unit:
return self._inferred_unit
return self._unit | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_unit",
":",
"return",
"self",
".",
"_inferred_unit",
"return",
"self",
".",
"_unit"
] | [
186,
4
] | [
190,
25
] | python | en | ['en', 'en', 'en'] | True |
APCUPSdSensor.update | (self) | Get the latest status and use it to update our sensor state. | Get the latest status and use it to update our sensor state. | def update(self):
"""Get the latest status and use it to update our sensor state."""
if self.type.upper() not in self._data.status:
self._state = None
self._inferred_unit = None
else:
self._state, self._inferred_unit = infer_unit(
self._data.status[self.type.upper()]
) | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
".",
"upper",
"(",
")",
"not",
"in",
"self",
".",
"_data",
".",
"status",
":",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_inferred_unit",
"=",
"None",
"else",
":",
"self",
".",
"_state",
",",
"self",
".",
"_inferred_unit",
"=",
"infer_unit",
"(",
"self",
".",
"_data",
".",
"status",
"[",
"self",
".",
"type",
".",
"upper",
"(",
")",
"]",
")"
] | [
192,
4
] | [
200,
13
] | python | en | ['en', 'en', 'en'] | True |
get_scanner | (hass, config) | Validate the configuration and return Synology SRM scanner. | Validate the configuration and return Synology SRM scanner. | def get_scanner(hass, config):
"""Validate the configuration and return Synology SRM scanner."""
scanner = SynologySrmDeviceScanner(config[DOMAIN])
return scanner if scanner.success_init else None | [
"def",
"get_scanner",
"(",
"hass",
",",
"config",
")",
":",
"scanner",
"=",
"SynologySrmDeviceScanner",
"(",
"config",
"[",
"DOMAIN",
"]",
")",
"return",
"scanner",
"if",
"scanner",
".",
"success_init",
"else",
"None"
] | [
68,
0
] | [
72,
52
] | python | en | ['en', 'en', 'en'] | True |
SynologySrmDeviceScanner.__init__ | (self, config) | Initialize the scanner. | Initialize the scanner. | def __init__(self, config):
"""Initialize the scanner."""
self.client = synology_srm.Client(
host=config[CONF_HOST],
port=config[CONF_PORT],
username=config[CONF_USERNAME],
password=config[CONF_PASSWORD],
https=config[CONF_SSL],
)
if not config[CONF_VERIFY_SSL]:
self.client.http.disable_https_verify()
self.devices = []
self.success_init = self._update_info()
_LOGGER.info("Synology SRM scanner initialized") | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"client",
"=",
"synology_srm",
".",
"Client",
"(",
"host",
"=",
"config",
"[",
"CONF_HOST",
"]",
",",
"port",
"=",
"config",
"[",
"CONF_PORT",
"]",
",",
"username",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
",",
"password",
"=",
"config",
"[",
"CONF_PASSWORD",
"]",
",",
"https",
"=",
"config",
"[",
"CONF_SSL",
"]",
",",
")",
"if",
"not",
"config",
"[",
"CONF_VERIFY_SSL",
"]",
":",
"self",
".",
"client",
".",
"http",
".",
"disable_https_verify",
"(",
")",
"self",
".",
"devices",
"=",
"[",
"]",
"self",
".",
"success_init",
"=",
"self",
".",
"_update_info",
"(",
")",
"_LOGGER",
".",
"info",
"(",
"\"Synology SRM scanner initialized\"",
")"
] | [
78,
4
] | [
95,
56
] | python | en | ['en', 'en', 'en'] | True |
SynologySrmDeviceScanner.scan_devices | (self) | Scan for new devices and return a list with found device IDs. | Scan for new devices and return a list with found device IDs. | def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return [device["mac"] for device in self.devices] | [
"def",
"scan_devices",
"(",
"self",
")",
":",
"self",
".",
"_update_info",
"(",
")",
"return",
"[",
"device",
"[",
"\"mac\"",
"]",
"for",
"device",
"in",
"self",
".",
"devices",
"]"
] | [
97,
4
] | [
101,
57
] | python | en | ['en', 'en', 'en'] | True |
SynologySrmDeviceScanner.get_extra_attributes | (self, device) | Get the extra attributes of a device. | Get the extra attributes of a device. | def get_extra_attributes(self, device) -> dict:
"""Get the extra attributes of a device."""
device = next(
(result for result in self.devices if result["mac"] == device), None
)
filtered_attributes = {}
if not device:
return filtered_attributes
for attribute, alias in ATTRIBUTE_ALIAS.items():
value = device.get(attribute)
if value is None:
continue
attr = alias or attribute
filtered_attributes[attr] = value
return filtered_attributes | [
"def",
"get_extra_attributes",
"(",
"self",
",",
"device",
")",
"->",
"dict",
":",
"device",
"=",
"next",
"(",
"(",
"result",
"for",
"result",
"in",
"self",
".",
"devices",
"if",
"result",
"[",
"\"mac\"",
"]",
"==",
"device",
")",
",",
"None",
")",
"filtered_attributes",
"=",
"{",
"}",
"if",
"not",
"device",
":",
"return",
"filtered_attributes",
"for",
"attribute",
",",
"alias",
"in",
"ATTRIBUTE_ALIAS",
".",
"items",
"(",
")",
":",
"value",
"=",
"device",
".",
"get",
"(",
"attribute",
")",
"if",
"value",
"is",
"None",
":",
"continue",
"attr",
"=",
"alias",
"or",
"attribute",
"filtered_attributes",
"[",
"attr",
"]",
"=",
"value",
"return",
"filtered_attributes"
] | [
103,
4
] | [
117,
34
] | python | en | ['en', 'en', 'en'] | True |
SynologySrmDeviceScanner.get_device_name | (self, device) | Return the name of the given device or None if we don't know. | Return the name of the given device or None if we don't know. | def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
filter_named = [
result["hostname"] for result in self.devices if result["mac"] == device
]
if filter_named:
return filter_named[0]
return None | [
"def",
"get_device_name",
"(",
"self",
",",
"device",
")",
":",
"filter_named",
"=",
"[",
"result",
"[",
"\"hostname\"",
"]",
"for",
"result",
"in",
"self",
".",
"devices",
"if",
"result",
"[",
"\"mac\"",
"]",
"==",
"device",
"]",
"if",
"filter_named",
":",
"return",
"filter_named",
"[",
"0",
"]",
"return",
"None"
] | [
119,
4
] | [
128,
19
] | python | en | ['en', 'en', 'en'] | True |
SynologySrmDeviceScanner._update_info | (self) | Check the router for connected devices. | Check the router for connected devices. | def _update_info(self):
"""Check the router for connected devices."""
_LOGGER.debug("Scanning for connected devices")
try:
self.devices = self.client.core.get_network_nsm_device({"is_online": True})
except synology_srm.http.SynologyException as ex:
_LOGGER.error("Error with the Synology SRM: %s", ex)
return False
_LOGGER.debug("Found %d device(s) connected to the router", len(self.devices))
return True | [
"def",
"_update_info",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Scanning for connected devices\"",
")",
"try",
":",
"self",
".",
"devices",
"=",
"self",
".",
"client",
".",
"core",
".",
"get_network_nsm_device",
"(",
"{",
"\"is_online\"",
":",
"True",
"}",
")",
"except",
"synology_srm",
".",
"http",
".",
"SynologyException",
"as",
"ex",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error with the Synology SRM: %s\"",
",",
"ex",
")",
"return",
"False",
"_LOGGER",
".",
"debug",
"(",
"\"Found %d device(s) connected to the router\"",
",",
"len",
"(",
"self",
".",
"devices",
")",
")",
"return",
"True"
] | [
130,
4
] | [
142,
19
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.__init__ | (
self, hass, refresh_token, intents, default_convs, error_suppressed_convs
) | Set up the client. | Set up the client. | def __init__(
self, hass, refresh_token, intents, default_convs, error_suppressed_convs
):
"""Set up the client."""
self.hass = hass
self._connected = False
self._refresh_token = refresh_token
self._intents = intents
self._conversation_intents = None
self._client = None
self._user_list = None
self._conversation_list = None
self._default_convs = default_convs
self._default_conv_ids = None
self._error_suppressed_convs = error_suppressed_convs
self._error_suppressed_conv_ids = None
dispatcher.async_dispatcher_connect(
self.hass,
EVENT_HANGOUTS_MESSAGE_RECEIVED,
self._async_handle_conversation_message,
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"refresh_token",
",",
"intents",
",",
"default_convs",
",",
"error_suppressed_convs",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"_connected",
"=",
"False",
"self",
".",
"_refresh_token",
"=",
"refresh_token",
"self",
".",
"_intents",
"=",
"intents",
"self",
".",
"_conversation_intents",
"=",
"None",
"self",
".",
"_client",
"=",
"None",
"self",
".",
"_user_list",
"=",
"None",
"self",
".",
"_conversation_list",
"=",
"None",
"self",
".",
"_default_convs",
"=",
"default_convs",
"self",
".",
"_default_conv_ids",
"=",
"None",
"self",
".",
"_error_suppressed_convs",
"=",
"error_suppressed_convs",
"self",
".",
"_error_suppressed_conv_ids",
"=",
"None",
"dispatcher",
".",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"EVENT_HANGOUTS_MESSAGE_RECEIVED",
",",
"self",
".",
"_async_handle_conversation_message",
",",
")"
] | [
38,
4
] | [
62,
9
] | python | en | ['en', 'fr', 'en'] | True |
HangoutsBot.async_update_conversation_commands | (self) | Refresh the commands for every conversation. | Refresh the commands for every conversation. | def async_update_conversation_commands(self):
"""Refresh the commands for every conversation."""
self._conversation_intents = {}
for intent_type, data in self._intents.items():
if data.get(CONF_CONVERSATIONS):
conversations = []
for conversation in data.get(CONF_CONVERSATIONS):
conv_id = self._resolve_conversation_id(conversation)
if conv_id is not None:
conversations.append(conv_id)
data[f"_{CONF_CONVERSATIONS}"] = conversations
elif self._default_conv_ids:
data[f"_{CONF_CONVERSATIONS}"] = self._default_conv_ids
else:
data[f"_{CONF_CONVERSATIONS}"] = [
conv.id_ for conv in self._conversation_list.get_all()
]
for conv_id in data[f"_{CONF_CONVERSATIONS}"]:
if conv_id not in self._conversation_intents:
self._conversation_intents[conv_id] = {}
self._conversation_intents[conv_id][intent_type] = data
try:
self._conversation_list.on_event.remove_observer(
self._async_handle_conversation_event
)
except ValueError:
pass
self._conversation_list.on_event.add_observer(
self._async_handle_conversation_event
) | [
"def",
"async_update_conversation_commands",
"(",
"self",
")",
":",
"self",
".",
"_conversation_intents",
"=",
"{",
"}",
"for",
"intent_type",
",",
"data",
"in",
"self",
".",
"_intents",
".",
"items",
"(",
")",
":",
"if",
"data",
".",
"get",
"(",
"CONF_CONVERSATIONS",
")",
":",
"conversations",
"=",
"[",
"]",
"for",
"conversation",
"in",
"data",
".",
"get",
"(",
"CONF_CONVERSATIONS",
")",
":",
"conv_id",
"=",
"self",
".",
"_resolve_conversation_id",
"(",
"conversation",
")",
"if",
"conv_id",
"is",
"not",
"None",
":",
"conversations",
".",
"append",
"(",
"conv_id",
")",
"data",
"[",
"f\"_{CONF_CONVERSATIONS}\"",
"]",
"=",
"conversations",
"elif",
"self",
".",
"_default_conv_ids",
":",
"data",
"[",
"f\"_{CONF_CONVERSATIONS}\"",
"]",
"=",
"self",
".",
"_default_conv_ids",
"else",
":",
"data",
"[",
"f\"_{CONF_CONVERSATIONS}\"",
"]",
"=",
"[",
"conv",
".",
"id_",
"for",
"conv",
"in",
"self",
".",
"_conversation_list",
".",
"get_all",
"(",
")",
"]",
"for",
"conv_id",
"in",
"data",
"[",
"f\"_{CONF_CONVERSATIONS}\"",
"]",
":",
"if",
"conv_id",
"not",
"in",
"self",
".",
"_conversation_intents",
":",
"self",
".",
"_conversation_intents",
"[",
"conv_id",
"]",
"=",
"{",
"}",
"self",
".",
"_conversation_intents",
"[",
"conv_id",
"]",
"[",
"intent_type",
"]",
"=",
"data",
"try",
":",
"self",
".",
"_conversation_list",
".",
"on_event",
".",
"remove_observer",
"(",
"self",
".",
"_async_handle_conversation_event",
")",
"except",
"ValueError",
":",
"pass",
"self",
".",
"_conversation_list",
".",
"on_event",
".",
"add_observer",
"(",
"self",
".",
"_async_handle_conversation_event",
")"
] | [
80,
4
] | [
113,
9
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.async_resolve_conversations | (self, _) | Resolve the list of default and error suppressed conversations. | Resolve the list of default and error suppressed conversations. | def async_resolve_conversations(self, _):
"""Resolve the list of default and error suppressed conversations."""
self._default_conv_ids = []
self._error_suppressed_conv_ids = []
for conversation in self._default_convs:
conv_id = self._resolve_conversation_id(conversation)
if conv_id is not None:
self._default_conv_ids.append(conv_id)
for conversation in self._error_suppressed_convs:
conv_id = self._resolve_conversation_id(conversation)
if conv_id is not None:
self._error_suppressed_conv_ids.append(conv_id)
dispatcher.async_dispatcher_send(
self.hass, EVENT_HANGOUTS_CONVERSATIONS_RESOLVED
) | [
"def",
"async_resolve_conversations",
"(",
"self",
",",
"_",
")",
":",
"self",
".",
"_default_conv_ids",
"=",
"[",
"]",
"self",
".",
"_error_suppressed_conv_ids",
"=",
"[",
"]",
"for",
"conversation",
"in",
"self",
".",
"_default_convs",
":",
"conv_id",
"=",
"self",
".",
"_resolve_conversation_id",
"(",
"conversation",
")",
"if",
"conv_id",
"is",
"not",
"None",
":",
"self",
".",
"_default_conv_ids",
".",
"append",
"(",
"conv_id",
")",
"for",
"conversation",
"in",
"self",
".",
"_error_suppressed_convs",
":",
"conv_id",
"=",
"self",
".",
"_resolve_conversation_id",
"(",
"conversation",
")",
"if",
"conv_id",
"is",
"not",
"None",
":",
"self",
".",
"_error_suppressed_conv_ids",
".",
"append",
"(",
"conv_id",
")",
"dispatcher",
".",
"async_dispatcher_send",
"(",
"self",
".",
"hass",
",",
"EVENT_HANGOUTS_CONVERSATIONS_RESOLVED",
")"
] | [
116,
4
] | [
132,
9
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot._async_handle_conversation_message | (self, conv_id, user_id, event) | Handle a message sent to a conversation. | Handle a message sent to a conversation. | async def _async_handle_conversation_message(self, conv_id, user_id, event):
"""Handle a message sent to a conversation."""
user = self._user_list.get_user(user_id)
if user.is_self:
return
message = event.text
_LOGGER.debug("Handling message '%s' from %s", message, user.full_name)
intents = self._conversation_intents.get(conv_id)
if intents is not None:
is_error = False
try:
intent_result = await self._async_process(intents, message, conv_id)
except (intent.UnknownIntent, intent.IntentHandleError) as err:
is_error = True
intent_result = intent.IntentResponse()
intent_result.async_set_speech(str(err))
if intent_result is None:
is_error = True
intent_result = intent.IntentResponse()
intent_result.async_set_speech("Sorry, I didn't understand that")
message = (
intent_result.as_dict().get("speech", {}).get("plain", {}).get("speech")
)
if (message is not None) and not (
is_error and conv_id in self._error_suppressed_conv_ids
):
await self._async_send_message(
[{"text": message, "parse_str": True}],
[{CONF_CONVERSATION_ID: conv_id}],
None,
) | [
"async",
"def",
"_async_handle_conversation_message",
"(",
"self",
",",
"conv_id",
",",
"user_id",
",",
"event",
")",
":",
"user",
"=",
"self",
".",
"_user_list",
".",
"get_user",
"(",
"user_id",
")",
"if",
"user",
".",
"is_self",
":",
"return",
"message",
"=",
"event",
".",
"text",
"_LOGGER",
".",
"debug",
"(",
"\"Handling message '%s' from %s\"",
",",
"message",
",",
"user",
".",
"full_name",
")",
"intents",
"=",
"self",
".",
"_conversation_intents",
".",
"get",
"(",
"conv_id",
")",
"if",
"intents",
"is",
"not",
"None",
":",
"is_error",
"=",
"False",
"try",
":",
"intent_result",
"=",
"await",
"self",
".",
"_async_process",
"(",
"intents",
",",
"message",
",",
"conv_id",
")",
"except",
"(",
"intent",
".",
"UnknownIntent",
",",
"intent",
".",
"IntentHandleError",
")",
"as",
"err",
":",
"is_error",
"=",
"True",
"intent_result",
"=",
"intent",
".",
"IntentResponse",
"(",
")",
"intent_result",
".",
"async_set_speech",
"(",
"str",
"(",
"err",
")",
")",
"if",
"intent_result",
"is",
"None",
":",
"is_error",
"=",
"True",
"intent_result",
"=",
"intent",
".",
"IntentResponse",
"(",
")",
"intent_result",
".",
"async_set_speech",
"(",
"\"Sorry, I didn't understand that\"",
")",
"message",
"=",
"(",
"intent_result",
".",
"as_dict",
"(",
")",
".",
"get",
"(",
"\"speech\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"plain\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"speech\"",
")",
")",
"if",
"(",
"message",
"is",
"not",
"None",
")",
"and",
"not",
"(",
"is_error",
"and",
"conv_id",
"in",
"self",
".",
"_error_suppressed_conv_ids",
")",
":",
"await",
"self",
".",
"_async_send_message",
"(",
"[",
"{",
"\"text\"",
":",
"message",
",",
"\"parse_str\"",
":",
"True",
"}",
"]",
",",
"[",
"{",
"CONF_CONVERSATION_ID",
":",
"conv_id",
"}",
"]",
",",
"None",
",",
")"
] | [
144,
4
] | [
179,
17
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot._async_process | (self, intents, text, conv_id) | Detect a matching intent. | Detect a matching intent. | async def _async_process(self, intents, text, conv_id):
"""Detect a matching intent."""
for intent_type, data in intents.items():
for matcher in data.get(CONF_MATCHERS, []):
match = matcher.match(text)
if not match:
continue
if intent_type == INTENT_HELP:
return await self.hass.helpers.intent.async_handle(
DOMAIN, intent_type, {"conv_id": {"value": conv_id}}, text
)
return await self.hass.helpers.intent.async_handle(
DOMAIN,
intent_type,
{key: {"value": value} for key, value in match.groupdict().items()},
text,
) | [
"async",
"def",
"_async_process",
"(",
"self",
",",
"intents",
",",
"text",
",",
"conv_id",
")",
":",
"for",
"intent_type",
",",
"data",
"in",
"intents",
".",
"items",
"(",
")",
":",
"for",
"matcher",
"in",
"data",
".",
"get",
"(",
"CONF_MATCHERS",
",",
"[",
"]",
")",
":",
"match",
"=",
"matcher",
".",
"match",
"(",
"text",
")",
"if",
"not",
"match",
":",
"continue",
"if",
"intent_type",
"==",
"INTENT_HELP",
":",
"return",
"await",
"self",
".",
"hass",
".",
"helpers",
".",
"intent",
".",
"async_handle",
"(",
"DOMAIN",
",",
"intent_type",
",",
"{",
"\"conv_id\"",
":",
"{",
"\"value\"",
":",
"conv_id",
"}",
"}",
",",
"text",
")",
"return",
"await",
"self",
".",
"hass",
".",
"helpers",
".",
"intent",
".",
"async_handle",
"(",
"DOMAIN",
",",
"intent_type",
",",
"{",
"key",
":",
"{",
"\"value\"",
":",
"value",
"}",
"for",
"key",
",",
"value",
"in",
"match",
".",
"groupdict",
"(",
")",
".",
"items",
"(",
")",
"}",
",",
"text",
",",
")"
] | [
181,
4
] | [
199,
17
] | python | en | ['en', 'lb', 'en'] | True |
HangoutsBot.async_connect | (self) | Login to the Google Hangouts. | Login to the Google Hangouts. | async def async_connect(self):
"""Login to the Google Hangouts."""
session = await self.hass.async_add_executor_job(
get_auth,
HangoutsCredentials(None, None, None),
HangoutsRefreshToken(self._refresh_token),
)
self._client = Client(session)
self._client.on_connect.add_observer(self._on_connect)
self._client.on_disconnect.add_observer(self._on_disconnect)
self.hass.loop.create_task(self._client.connect()) | [
"async",
"def",
"async_connect",
"(",
"self",
")",
":",
"session",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"get_auth",
",",
"HangoutsCredentials",
"(",
"None",
",",
"None",
",",
"None",
")",
",",
"HangoutsRefreshToken",
"(",
"self",
".",
"_refresh_token",
")",
",",
")",
"self",
".",
"_client",
"=",
"Client",
"(",
"session",
")",
"self",
".",
"_client",
".",
"on_connect",
".",
"add_observer",
"(",
"self",
".",
"_on_connect",
")",
"self",
".",
"_client",
".",
"on_disconnect",
".",
"add_observer",
"(",
"self",
".",
"_on_disconnect",
")",
"self",
".",
"hass",
".",
"loop",
".",
"create_task",
"(",
"self",
".",
"_client",
".",
"connect",
"(",
")",
")"
] | [
201,
4
] | [
213,
58
] | python | en | ['en', 'zh-Latn', 'en'] | True |
HangoutsBot._on_disconnect | (self) | Handle disconnecting. | Handle disconnecting. | async def _on_disconnect(self):
"""Handle disconnecting."""
if self._connected:
_LOGGER.debug("Connection lost! Reconnect...")
await self.async_connect()
else:
dispatcher.async_dispatcher_send(self.hass, EVENT_HANGOUTS_DISCONNECTED) | [
"async",
"def",
"_on_disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connected",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Connection lost! Reconnect...\"",
")",
"await",
"self",
".",
"async_connect",
"(",
")",
"else",
":",
"dispatcher",
".",
"async_dispatcher_send",
"(",
"self",
".",
"hass",
",",
"EVENT_HANGOUTS_DISCONNECTED",
")"
] | [
220,
4
] | [
226,
84
] | python | en | ['it', 'en', 'en'] | False |
HangoutsBot.async_disconnect | (self) | Disconnect the client if it is connected. | Disconnect the client if it is connected. | async def async_disconnect(self):
"""Disconnect the client if it is connected."""
if self._connected:
self._connected = False
await self._client.disconnect() | [
"async",
"def",
"async_disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connected",
":",
"self",
".",
"_connected",
"=",
"False",
"await",
"self",
".",
"_client",
".",
"disconnect",
"(",
")"
] | [
228,
4
] | [
232,
43
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.async_handle_hass_stop | (self, _) | Run once when Home Assistant stops. | Run once when Home Assistant stops. | async def async_handle_hass_stop(self, _):
"""Run once when Home Assistant stops."""
await self.async_disconnect() | [
"async",
"def",
"async_handle_hass_stop",
"(",
"self",
",",
"_",
")",
":",
"await",
"self",
".",
"async_disconnect",
"(",
")"
] | [
234,
4
] | [
236,
37
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.async_handle_send_message | (self, service) | Handle the send_message service. | Handle the send_message service. | async def async_handle_send_message(self, service):
"""Handle the send_message service."""
await self._async_send_message(
service.data[ATTR_MESSAGE],
service.data[ATTR_TARGET],
service.data.get(ATTR_DATA, {}),
) | [
"async",
"def",
"async_handle_send_message",
"(",
"self",
",",
"service",
")",
":",
"await",
"self",
".",
"_async_send_message",
"(",
"service",
".",
"data",
"[",
"ATTR_MESSAGE",
"]",
",",
"service",
".",
"data",
"[",
"ATTR_TARGET",
"]",
",",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_DATA",
",",
"{",
"}",
")",
",",
")"
] | [
330,
4
] | [
336,
9
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.async_handle_update_users_and_conversations | (self, _=None) | Handle the update_users_and_conversations service. | Handle the update_users_and_conversations service. | async def async_handle_update_users_and_conversations(self, _=None):
"""Handle the update_users_and_conversations service."""
await self._async_list_conversations() | [
"async",
"def",
"async_handle_update_users_and_conversations",
"(",
"self",
",",
"_",
"=",
"None",
")",
":",
"await",
"self",
".",
"_async_list_conversations",
"(",
")"
] | [
338,
4
] | [
340,
46
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.async_handle_reconnect | (self, _=None) | Handle the reconnect service. | Handle the reconnect service. | async def async_handle_reconnect(self, _=None):
"""Handle the reconnect service."""
await self.async_disconnect()
await self.async_connect() | [
"async",
"def",
"async_handle_reconnect",
"(",
"self",
",",
"_",
"=",
"None",
")",
":",
"await",
"self",
".",
"async_disconnect",
"(",
")",
"await",
"self",
".",
"async_connect",
"(",
")"
] | [
342,
4
] | [
345,
34
] | python | en | ['en', 'en', 'en'] | True |
HangoutsBot.get_intents | (self, conv_id) | Return the intents for a specific conversation. | Return the intents for a specific conversation. | def get_intents(self, conv_id):
"""Return the intents for a specific conversation."""
return self._conversation_intents.get(conv_id) | [
"def",
"get_intents",
"(",
"self",
",",
"conv_id",
")",
":",
"return",
"self",
".",
"_conversation_intents",
".",
"get",
"(",
"conv_id",
")"
] | [
347,
4
] | [
349,
54
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the Speedtestdotnet sensors. | Set up the Speedtestdotnet sensors. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Speedtestdotnet sensors."""
speedtest_coordinator = hass.data[DOMAIN]
entities = []
for sensor_type in SENSOR_TYPES:
entities.append(SpeedtestSensor(speedtest_coordinator, sensor_type))
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"speedtest_coordinator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"entities",
"=",
"[",
"]",
"for",
"sensor_type",
"in",
"SENSOR_TYPES",
":",
"entities",
".",
"append",
"(",
"SpeedtestSensor",
"(",
"speedtest_coordinator",
",",
"sensor_type",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
20,
0
] | [
29,
32
] | python | en | ['en', 'lv', 'en'] | True |
SpeedtestSensor.__init__ | (self, coordinator, sensor_type) | Initialize the sensor. | Initialize the sensor. | def __init__(self, coordinator, sensor_type):
"""Initialize the sensor."""
super().__init__(coordinator)
self._name = SENSOR_TYPES[sensor_type][0]
self.type = sensor_type
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
",",
"sensor_type",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
")",
"self",
".",
"_name",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"0",
"]",
"self",
".",
"type",
"=",
"sensor_type",
"self",
".",
"_unit_of_measurement",
"=",
"SENSOR_TYPES",
"[",
"self",
".",
"type",
"]",
"[",
"1",
"]",
"self",
".",
"_state",
"=",
"None"
] | [
35,
4
] | [
41,
26
] | python | en | ['en', 'en', 'en'] | True |
SpeedtestSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"{DEFAULT_NAME} {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{DEFAULT_NAME} {self._name}\""
] | [
44,
4
] | [
46,
45
] | python | en | ['en', 'mi', 'en'] | True |
SpeedtestSensor.unique_id | (self) | Return sensor unique_id. | Return sensor unique_id. | def unique_id(self):
"""Return sensor unique_id."""
return self.type | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"type"
] | [
49,
4
] | [
51,
24
] | python | ca | ['fr', 'ca', 'en'] | False |
SpeedtestSensor.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
54,
4
] | [
56,
26
] | python | en | ['en', 'en', 'en'] | True |
SpeedtestSensor.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
59,
4
] | [
61,
40
] | python | en | ['en', 'en', 'en'] | True |
SpeedtestSensor.icon | (self) | Return icon. | Return icon. | def icon(self):
"""Return icon."""
return ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
64,
4
] | [
66,
19
] | python | en | ['en', 'la', 'en'] | False |
SpeedtestSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
if not self.coordinator.data:
return None
attributes = {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_SERVER_NAME: self.coordinator.data["server"]["name"],
ATTR_SERVER_COUNTRY: self.coordinator.data["server"]["country"],
ATTR_SERVER_ID: self.coordinator.data["server"]["id"],
}
if self.type == "download":
attributes[ATTR_BYTES_RECEIVED] = self.coordinator.data["bytes_received"]
if self.type == "upload":
attributes[ATTR_BYTES_SENT] = self.coordinator.data["bytes_sent"]
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"coordinator",
".",
"data",
":",
"return",
"None",
"attributes",
"=",
"{",
"ATTR_ATTRIBUTION",
":",
"ATTRIBUTION",
",",
"ATTR_SERVER_NAME",
":",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"server\"",
"]",
"[",
"\"name\"",
"]",
",",
"ATTR_SERVER_COUNTRY",
":",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"server\"",
"]",
"[",
"\"country\"",
"]",
",",
"ATTR_SERVER_ID",
":",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"server\"",
"]",
"[",
"\"id\"",
"]",
",",
"}",
"if",
"self",
".",
"type",
"==",
"\"download\"",
":",
"attributes",
"[",
"ATTR_BYTES_RECEIVED",
"]",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"bytes_received\"",
"]",
"if",
"self",
".",
"type",
"==",
"\"upload\"",
":",
"attributes",
"[",
"ATTR_BYTES_SENT",
"]",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"bytes_sent\"",
"]",
"return",
"attributes"
] | [
69,
4
] | [
85,
25
] | python | en | ['en', 'en', 'en'] | True |
SpeedtestSensor.async_added_to_hass | (self) | Handle entity which will be added. | Handle entity which will be added. | async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state
@callback
def update():
"""Update state."""
self._update_state()
self.async_write_ha_state()
self.async_on_remove(self.coordinator.async_add_listener(update))
self._update_state() | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"state",
"=",
"await",
"self",
".",
"async_get_last_state",
"(",
")",
"if",
"state",
":",
"self",
".",
"_state",
"=",
"state",
".",
"state",
"@",
"callback",
"def",
"update",
"(",
")",
":",
"\"\"\"Update state.\"\"\"",
"self",
".",
"_update_state",
"(",
")",
"self",
".",
"async_write_ha_state",
"(",
")",
"self",
".",
"async_on_remove",
"(",
"self",
".",
"coordinator",
".",
"async_add_listener",
"(",
"update",
")",
")",
"self",
".",
"_update_state",
"(",
")"
] | [
87,
4
] | [
101,
28
] | python | en | ['en', 'en', 'en'] | True |
SpeedtestSensor._update_state | (self) | Update sensors state. | Update sensors state. | def _update_state(self):
"""Update sensors state."""
if self.coordinator.data:
if self.type == "ping":
self._state = self.coordinator.data["ping"]
elif self.type == "download":
self._state = round(self.coordinator.data["download"] / 10 ** 6, 2)
elif self.type == "upload":
self._state = round(self.coordinator.data["upload"] / 10 ** 6, 2) | [
"def",
"_update_state",
"(",
"self",
")",
":",
"if",
"self",
".",
"coordinator",
".",
"data",
":",
"if",
"self",
".",
"type",
"==",
"\"ping\"",
":",
"self",
".",
"_state",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"ping\"",
"]",
"elif",
"self",
".",
"type",
"==",
"\"download\"",
":",
"self",
".",
"_state",
"=",
"round",
"(",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"download\"",
"]",
"/",
"10",
"**",
"6",
",",
"2",
")",
"elif",
"self",
".",
"type",
"==",
"\"upload\"",
":",
"self",
".",
"_state",
"=",
"round",
"(",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"upload\"",
"]",
"/",
"10",
"**",
"6",
",",
"2",
")"
] | [
103,
4
] | [
111,
81
] | python | en | ['en', 'co', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Last.fm sensor platform. | Set up the Last.fm sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Last.fm sensor platform."""
api_key = config[CONF_API_KEY]
users = config.get(CONF_USERS)
lastfm_api = lastfm.LastFMNetwork(api_key=api_key)
entities = []
for username in users:
try:
lastfm_api.get_user(username).get_image()
entities.append(LastfmSensor(username, lastfm_api))
except WSError as error:
_LOGGER.error(error)
return
add_entities(entities, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"api_key",
"=",
"config",
"[",
"CONF_API_KEY",
"]",
"users",
"=",
"config",
".",
"get",
"(",
"CONF_USERS",
")",
"lastfm_api",
"=",
"lastfm",
".",
"LastFMNetwork",
"(",
"api_key",
"=",
"api_key",
")",
"entities",
"=",
"[",
"]",
"for",
"username",
"in",
"users",
":",
"try",
":",
"lastfm_api",
".",
"get_user",
"(",
"username",
")",
".",
"get_image",
"(",
")",
"entities",
".",
"append",
"(",
"LastfmSensor",
"(",
"username",
",",
"lastfm_api",
")",
")",
"except",
"WSError",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"error",
")",
"return",
"add_entities",
"(",
"entities",
",",
"True",
")"
] | [
35,
0
] | [
51,
32
] | python | en | ['en', 'da', 'en'] | True |
LastfmSensor.__init__ | (self, user, lastfm_api) | Initialize the sensor. | Initialize the sensor. | def __init__(self, user, lastfm_api):
"""Initialize the sensor."""
self._unique_id = hashlib.sha256(user.encode("utf-8")).hexdigest()
self._user = lastfm_api.get_user(user)
self._name = user
self._lastfm = lastfm_api
self._state = "Not Scrobbling"
self._playcount = None
self._lastplayed = None
self._topplayed = None
self._cover = None | [
"def",
"__init__",
"(",
"self",
",",
"user",
",",
"lastfm_api",
")",
":",
"self",
".",
"_unique_id",
"=",
"hashlib",
".",
"sha256",
"(",
"user",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
"self",
".",
"_user",
"=",
"lastfm_api",
".",
"get_user",
"(",
"user",
")",
"self",
".",
"_name",
"=",
"user",
"self",
".",
"_lastfm",
"=",
"lastfm_api",
"self",
".",
"_state",
"=",
"\"Not Scrobbling\"",
"self",
".",
"_playcount",
"=",
"None",
"self",
".",
"_lastplayed",
"=",
"None",
"self",
".",
"_topplayed",
"=",
"None",
"self",
".",
"_cover",
"=",
"None"
] | [
57,
4
] | [
67,
26
] | python | en | ['en', 'en', 'en'] | True |
LastfmSensor.unique_id | (self) | Return the unique ID of the sensor. | Return the unique ID of the sensor. | def unique_id(self):
"""Return the unique ID of the sensor."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
70,
4
] | [
72,
30
] | python | en | ['en', 'la', 'en'] | True |
LastfmSensor.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"
] | [
75,
4
] | [
77,
25
] | python | en | ['en', 'mi', 'en'] | True |
LastfmSensor.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"
] | [
80,
4
] | [
82,
26
] | python | en | ['en', 'en', 'en'] | True |
LastfmSensor.update | (self) | Update device state. | Update device state. | def update(self):
"""Update device state."""
self._cover = self._user.get_image()
self._playcount = self._user.get_playcount()
recent_tracks = self._user.get_recent_tracks(limit=2)
if recent_tracks:
last = recent_tracks[0]
self._lastplayed = f"{last.track.artist} - {last.track.title}"
top_tracks = self._user.get_top_tracks(limit=1)
if top_tracks:
top = top_tracks[0]
toptitle = re.search("', '(.+?)',", str(top))
topartist = re.search("'(.+?)',", str(top))
self._topplayed = f"{topartist.group(1)} - {toptitle.group(1)}"
now_playing = self._user.get_now_playing()
if now_playing is None:
self._state = STATE_NOT_SCROBBLING
return
self._state = f"{now_playing.artist} - {now_playing.title}" | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_cover",
"=",
"self",
".",
"_user",
".",
"get_image",
"(",
")",
"self",
".",
"_playcount",
"=",
"self",
".",
"_user",
".",
"get_playcount",
"(",
")",
"recent_tracks",
"=",
"self",
".",
"_user",
".",
"get_recent_tracks",
"(",
"limit",
"=",
"2",
")",
"if",
"recent_tracks",
":",
"last",
"=",
"recent_tracks",
"[",
"0",
"]",
"self",
".",
"_lastplayed",
"=",
"f\"{last.track.artist} - {last.track.title}\"",
"top_tracks",
"=",
"self",
".",
"_user",
".",
"get_top_tracks",
"(",
"limit",
"=",
"1",
")",
"if",
"top_tracks",
":",
"top",
"=",
"top_tracks",
"[",
"0",
"]",
"toptitle",
"=",
"re",
".",
"search",
"(",
"\"', '(.+?)',\"",
",",
"str",
"(",
"top",
")",
")",
"topartist",
"=",
"re",
".",
"search",
"(",
"\"'(.+?)',\"",
",",
"str",
"(",
"top",
")",
")",
"self",
".",
"_topplayed",
"=",
"f\"{topartist.group(1)} - {toptitle.group(1)}\"",
"now_playing",
"=",
"self",
".",
"_user",
".",
"get_now_playing",
"(",
")",
"if",
"now_playing",
"is",
"None",
":",
"self",
".",
"_state",
"=",
"STATE_NOT_SCROBBLING",
"return",
"self",
".",
"_state",
"=",
"f\"{now_playing.artist} - {now_playing.title}\""
] | [
84,
4
] | [
106,
67
] | python | en | ['fr', 'en', 'en'] | True |
LastfmSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
ATTR_LAST_PLAYED: self._lastplayed,
ATTR_PLAY_COUNT: self._playcount,
ATTR_TOP_PLAYED: self._topplayed,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"ATTR_ATTRIBUTION",
":",
"ATTRIBUTION",
",",
"ATTR_LAST_PLAYED",
":",
"self",
".",
"_lastplayed",
",",
"ATTR_PLAY_COUNT",
":",
"self",
".",
"_playcount",
",",
"ATTR_TOP_PLAYED",
":",
"self",
".",
"_topplayed",
",",
"}"
] | [
109,
4
] | [
116,
9
] | python | en | ['en', 'en', 'en'] | True |
LastfmSensor.entity_picture | (self) | Avatar of the user. | Avatar of the user. | def entity_picture(self):
"""Avatar of the user."""
return self._cover | [
"def",
"entity_picture",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cover"
] | [
119,
4
] | [
121,
26
] | python | en | ['en', 'en', 'en'] | True |
LastfmSensor.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 ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
124,
4
] | [
126,
19
] | python | en | ['en', 'en', 'en'] | True |
async_get_media_source | (hass: HomeAssistantType) | Set up Xbox media source. | Set up Xbox media source. | async def async_get_media_source(hass: HomeAssistantType):
"""Set up Xbox media source."""
entry = hass.config_entries.async_entries(DOMAIN)[0]
client = hass.data[DOMAIN][entry.entry_id]["client"]
return XboxSource(hass, client) | [
"async",
"def",
"async_get_media_source",
"(",
"hass",
":",
"HomeAssistantType",
")",
":",
"entry",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
"[",
"0",
"]",
"client",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"[",
"\"client\"",
"]",
"return",
"XboxSource",
"(",
"hass",
",",
"client",
")"
] | [
43,
0
] | [
47,
35
] | python | en | ['en', 'sr', 'en'] | True |
async_parse_identifier | (
item: MediaSourceItem,
) | Parse identifier. | Parse identifier. | def async_parse_identifier(
item: MediaSourceItem,
) -> Tuple[str, str, str]:
"""Parse identifier."""
identifier = item.identifier or ""
start = ["", "", ""]
items = identifier.lstrip("/").split("~~", 2)
return tuple(items + start[len(items) :]) | [
"def",
"async_parse_identifier",
"(",
"item",
":",
"MediaSourceItem",
",",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
":",
"identifier",
"=",
"item",
".",
"identifier",
"or",
"\"\"",
"start",
"=",
"[",
"\"\"",
",",
"\"\"",
",",
"\"\"",
"]",
"items",
"=",
"identifier",
".",
"lstrip",
"(",
"\"/\"",
")",
".",
"split",
"(",
"\"~~\"",
",",
"2",
")",
"return",
"tuple",
"(",
"items",
"+",
"start",
"[",
"len",
"(",
"items",
")",
":",
"]",
")"
] | [
51,
0
] | [
58,
45
] | python | de | ['en', 'de', 'hi'] | False |
_build_game_item | (item: InstalledPackage, images: List[Image]) | Build individual game. | Build individual game. | def _build_game_item(item: InstalledPackage, images: List[Image]):
"""Build individual game."""
thumbnail = ""
image = _find_media_image(images.get(item.one_store_product_id, []))
if image is not None:
thumbnail = image.uri
if thumbnail[0] == "/":
thumbnail = f"https:{thumbnail}"
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{item.title_id}#{item.name}#{thumbnail}",
media_class=MEDIA_CLASS_GAME,
media_content_type="",
title=item.name,
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_DIRECTORY,
thumbnail=thumbnail,
) | [
"def",
"_build_game_item",
"(",
"item",
":",
"InstalledPackage",
",",
"images",
":",
"List",
"[",
"Image",
"]",
")",
":",
"thumbnail",
"=",
"\"\"",
"image",
"=",
"_find_media_image",
"(",
"images",
".",
"get",
"(",
"item",
".",
"one_store_product_id",
",",
"[",
"]",
")",
")",
"if",
"image",
"is",
"not",
"None",
":",
"thumbnail",
"=",
"image",
".",
"uri",
"if",
"thumbnail",
"[",
"0",
"]",
"==",
"\"/\"",
":",
"thumbnail",
"=",
"f\"https:{thumbnail}\"",
"return",
"BrowseMediaSource",
"(",
"domain",
"=",
"DOMAIN",
",",
"identifier",
"=",
"f\"{item.title_id}#{item.name}#{thumbnail}\"",
",",
"media_class",
"=",
"MEDIA_CLASS_GAME",
",",
"media_content_type",
"=",
"\"\"",
",",
"title",
"=",
"item",
".",
"name",
",",
"can_play",
"=",
"False",
",",
"can_expand",
"=",
"True",
",",
"children_media_class",
"=",
"MEDIA_CLASS_DIRECTORY",
",",
"thumbnail",
"=",
"thumbnail",
",",
")"
] | [
209,
0
] | [
228,
5
] | python | en | ['en', 'id', 'en'] | True |
_build_categories | (title) | Build base categories for Xbox media. | Build base categories for Xbox media. | def _build_categories(title):
"""Build base categories for Xbox media."""
_, name, thumbnail = title.split("#", 2)
base = BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}",
media_class=MEDIA_CLASS_GAME,
media_content_type="",
title=name,
can_play=False,
can_expand=True,
children=[],
children_media_class=MEDIA_CLASS_DIRECTORY,
thumbnail=thumbnail,
)
owners = ["my", "community"]
kinds = ["gameclips", "screenshots"]
for owner in owners:
for kind in kinds:
base.children.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{owner}#{kind}",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_MAP[kind],
)
)
return base | [
"def",
"_build_categories",
"(",
"title",
")",
":",
"_",
",",
"name",
",",
"thumbnail",
"=",
"title",
".",
"split",
"(",
"\"#\"",
",",
"2",
")",
"base",
"=",
"BrowseMediaSource",
"(",
"domain",
"=",
"DOMAIN",
",",
"identifier",
"=",
"f\"{title}\"",
",",
"media_class",
"=",
"MEDIA_CLASS_GAME",
",",
"media_content_type",
"=",
"\"\"",
",",
"title",
"=",
"name",
",",
"can_play",
"=",
"False",
",",
"can_expand",
"=",
"True",
",",
"children",
"=",
"[",
"]",
",",
"children_media_class",
"=",
"MEDIA_CLASS_DIRECTORY",
",",
"thumbnail",
"=",
"thumbnail",
",",
")",
"owners",
"=",
"[",
"\"my\"",
",",
"\"community\"",
"]",
"kinds",
"=",
"[",
"\"gameclips\"",
",",
"\"screenshots\"",
"]",
"for",
"owner",
"in",
"owners",
":",
"for",
"kind",
"in",
"kinds",
":",
"base",
".",
"children",
".",
"append",
"(",
"BrowseMediaSource",
"(",
"domain",
"=",
"DOMAIN",
",",
"identifier",
"=",
"f\"{title}~~{owner}#{kind}\"",
",",
"media_class",
"=",
"MEDIA_CLASS_DIRECTORY",
",",
"media_content_type",
"=",
"\"\"",
",",
"title",
"=",
"f\"{owner.title()} {kind.title()}\"",
",",
"can_play",
"=",
"False",
",",
"can_expand",
"=",
"True",
",",
"children_media_class",
"=",
"MEDIA_CLASS_MAP",
"[",
"kind",
"]",
",",
")",
")",
"return",
"base"
] | [
231,
0
] | [
264,
15
] | python | en | ['en', 'en', 'en'] | True |
_build_media_item | (title: str, category: str, item: XboxMediaItem) | Build individual media item. | Build individual media item. | def _build_media_item(title: str, category: str, item: XboxMediaItem):
"""Build individual media item."""
_, kind = category.split("#", 1)
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}~~{item.uri}",
media_class=item.media_class,
media_content_type=MIME_TYPE_MAP[kind],
title=item.caption,
can_play=True,
can_expand=False,
thumbnail=item.thumbnail,
) | [
"def",
"_build_media_item",
"(",
"title",
":",
"str",
",",
"category",
":",
"str",
",",
"item",
":",
"XboxMediaItem",
")",
":",
"_",
",",
"kind",
"=",
"category",
".",
"split",
"(",
"\"#\"",
",",
"1",
")",
"return",
"BrowseMediaSource",
"(",
"domain",
"=",
"DOMAIN",
",",
"identifier",
"=",
"f\"{title}~~{category}~~{item.uri}\"",
",",
"media_class",
"=",
"item",
".",
"media_class",
",",
"media_content_type",
"=",
"MIME_TYPE_MAP",
"[",
"kind",
"]",
",",
"title",
"=",
"item",
".",
"caption",
",",
"can_play",
"=",
"True",
",",
"can_expand",
"=",
"False",
",",
"thumbnail",
"=",
"item",
".",
"thumbnail",
",",
")"
] | [
267,
0
] | [
279,
5
] | python | en | ['en', 'la', 'en'] | True |
XboxSource.__init__ | (self, hass: HomeAssistantType, client: XboxLiveClient) | Initialize Xbox source. | Initialize Xbox source. | def __init__(self, hass: HomeAssistantType, client: XboxLiveClient):
"""Initialize Xbox source."""
super().__init__(DOMAIN)
self.hass: HomeAssistantType = hass
self.client: XboxLiveClient = client | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistantType",
",",
"client",
":",
"XboxLiveClient",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"DOMAIN",
")",
"self",
".",
"hass",
":",
"HomeAssistantType",
"=",
"hass",
"self",
".",
"client",
":",
"XboxLiveClient",
"=",
"client"
] | [
76,
4
] | [
81,
44
] | python | en | ['fr', 'pl', 'en'] | False |
XboxSource.async_resolve_media | (self, item: MediaSourceItem) | Resolve media to a url. | Resolve media to a url. | async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve media to a url."""
_, category, url = async_parse_identifier(item)
_, kind = category.split("#", 1)
return PlayMedia(url, MIME_TYPE_MAP[kind]) | [
"async",
"def",
"async_resolve_media",
"(",
"self",
",",
"item",
":",
"MediaSourceItem",
")",
"->",
"PlayMedia",
":",
"_",
",",
"category",
",",
"url",
"=",
"async_parse_identifier",
"(",
"item",
")",
"_",
",",
"kind",
"=",
"category",
".",
"split",
"(",
"\"#\"",
",",
"1",
")",
"return",
"PlayMedia",
"(",
"url",
",",
"MIME_TYPE_MAP",
"[",
"kind",
"]",
")"
] | [
83,
4
] | [
87,
50
] | python | en | ['en', 'en', 'en'] | True |
XboxSource.async_browse_media | (
self, item: MediaSourceItem, media_types: Tuple[str] = MEDIA_MIME_TYPES
) | Return media. | Return media. | async def async_browse_media(
self, item: MediaSourceItem, media_types: Tuple[str] = MEDIA_MIME_TYPES
) -> BrowseMediaSource:
"""Return media."""
title, category, _ = async_parse_identifier(item)
if not title:
return await self._build_game_library()
if not category:
return _build_categories(title)
return await self._build_media_items(title, category) | [
"async",
"def",
"async_browse_media",
"(",
"self",
",",
"item",
":",
"MediaSourceItem",
",",
"media_types",
":",
"Tuple",
"[",
"str",
"]",
"=",
"MEDIA_MIME_TYPES",
")",
"->",
"BrowseMediaSource",
":",
"title",
",",
"category",
",",
"_",
"=",
"async_parse_identifier",
"(",
"item",
")",
"if",
"not",
"title",
":",
"return",
"await",
"self",
".",
"_build_game_library",
"(",
")",
"if",
"not",
"category",
":",
"return",
"_build_categories",
"(",
"title",
")",
"return",
"await",
"self",
".",
"_build_media_items",
"(",
"title",
",",
"category",
")"
] | [
89,
4
] | [
101,
61
] | python | en | ['en', 'no', 'en'] | False |
XboxSource._build_game_library | (self) | Display installed games across all consoles. | Display installed games across all consoles. | async def _build_game_library(self):
"""Display installed games across all consoles."""
apps = await self.client.smartglass.get_installed_apps()
games = {
game.one_store_product_id: game
for game in apps.result
if game.is_game and game.title_id
}
app_details = await self.client.catalog.get_products(
games.keys(),
FieldsTemplate.BROWSE,
)
images = {
prod.product_id: prod.localized_properties[0].images
for prod in app_details.products
}
return BrowseMediaSource(
domain=DOMAIN,
identifier="",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title="Xbox Game Media",
can_play=False,
can_expand=True,
children=[_build_game_item(game, images) for game in games.values()],
children_media_class=MEDIA_CLASS_GAME,
) | [
"async",
"def",
"_build_game_library",
"(",
"self",
")",
":",
"apps",
"=",
"await",
"self",
".",
"client",
".",
"smartglass",
".",
"get_installed_apps",
"(",
")",
"games",
"=",
"{",
"game",
".",
"one_store_product_id",
":",
"game",
"for",
"game",
"in",
"apps",
".",
"result",
"if",
"game",
".",
"is_game",
"and",
"game",
".",
"title_id",
"}",
"app_details",
"=",
"await",
"self",
".",
"client",
".",
"catalog",
".",
"get_products",
"(",
"games",
".",
"keys",
"(",
")",
",",
"FieldsTemplate",
".",
"BROWSE",
",",
")",
"images",
"=",
"{",
"prod",
".",
"product_id",
":",
"prod",
".",
"localized_properties",
"[",
"0",
"]",
".",
"images",
"for",
"prod",
"in",
"app_details",
".",
"products",
"}",
"return",
"BrowseMediaSource",
"(",
"domain",
"=",
"DOMAIN",
",",
"identifier",
"=",
"\"\"",
",",
"media_class",
"=",
"MEDIA_CLASS_DIRECTORY",
",",
"media_content_type",
"=",
"\"\"",
",",
"title",
"=",
"\"Xbox Game Media\"",
",",
"can_play",
"=",
"False",
",",
"can_expand",
"=",
"True",
",",
"children",
"=",
"[",
"_build_game_item",
"(",
"game",
",",
"images",
")",
"for",
"game",
"in",
"games",
".",
"values",
"(",
")",
"]",
",",
"children_media_class",
"=",
"MEDIA_CLASS_GAME",
",",
")"
] | [
103,
4
] | [
132,
9
] | python | en | ['en', 'en', 'en'] | True |
XboxSource._build_media_items | (self, title, category) | Fetch requested gameclip/screenshot media. | Fetch requested gameclip/screenshot media. | async def _build_media_items(self, title, category):
"""Fetch requested gameclip/screenshot media."""
title_id, _, thumbnail = title.split("#", 2)
owner, kind = category.split("#", 1)
items: List[XboxMediaItem] = []
try:
if kind == "gameclips":
if owner == "my":
response: GameclipsResponse = (
await self.client.gameclips.get_recent_clips_by_xuid(
self.client.xuid, title_id
)
)
elif owner == "community":
response: GameclipsResponse = await self.client.gameclips.get_recent_community_clips_by_title_id(
title_id
)
else:
return None
items = [
XboxMediaItem(
item.user_caption
or dt_util.as_local(
dt_util.parse_datetime(item.date_recorded)
).strftime("%b. %d, %Y %I:%M %p"),
item.thumbnails[0].uri,
item.game_clip_uris[0].uri,
MEDIA_CLASS_VIDEO,
)
for item in response.game_clips
]
elif kind == "screenshots":
if owner == "my":
response: ScreenshotResponse = (
await self.client.screenshots.get_recent_screenshots_by_xuid(
self.client.xuid, title_id
)
)
elif owner == "community":
response: ScreenshotResponse = await self.client.screenshots.get_recent_community_screenshots_by_title_id(
title_id
)
else:
return None
items = [
XboxMediaItem(
item.user_caption
or dt_util.as_local(item.date_taken).strftime(
"%b. %d, %Y %I:%M%p"
),
item.thumbnails[0].uri,
item.screenshot_uris[0].uri,
MEDIA_CLASS_IMAGE,
)
for item in response.screenshots
]
except ValidationError:
# Unexpected API response
pass
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children=[_build_media_item(title, category, item) for item in items],
children_media_class=MEDIA_CLASS_MAP[kind],
thumbnail=thumbnail,
) | [
"async",
"def",
"_build_media_items",
"(",
"self",
",",
"title",
",",
"category",
")",
":",
"title_id",
",",
"_",
",",
"thumbnail",
"=",
"title",
".",
"split",
"(",
"\"#\"",
",",
"2",
")",
"owner",
",",
"kind",
"=",
"category",
".",
"split",
"(",
"\"#\"",
",",
"1",
")",
"items",
":",
"List",
"[",
"XboxMediaItem",
"]",
"=",
"[",
"]",
"try",
":",
"if",
"kind",
"==",
"\"gameclips\"",
":",
"if",
"owner",
"==",
"\"my\"",
":",
"response",
":",
"GameclipsResponse",
"=",
"(",
"await",
"self",
".",
"client",
".",
"gameclips",
".",
"get_recent_clips_by_xuid",
"(",
"self",
".",
"client",
".",
"xuid",
",",
"title_id",
")",
")",
"elif",
"owner",
"==",
"\"community\"",
":",
"response",
":",
"GameclipsResponse",
"=",
"await",
"self",
".",
"client",
".",
"gameclips",
".",
"get_recent_community_clips_by_title_id",
"(",
"title_id",
")",
"else",
":",
"return",
"None",
"items",
"=",
"[",
"XboxMediaItem",
"(",
"item",
".",
"user_caption",
"or",
"dt_util",
".",
"as_local",
"(",
"dt_util",
".",
"parse_datetime",
"(",
"item",
".",
"date_recorded",
")",
")",
".",
"strftime",
"(",
"\"%b. %d, %Y %I:%M %p\"",
")",
",",
"item",
".",
"thumbnails",
"[",
"0",
"]",
".",
"uri",
",",
"item",
".",
"game_clip_uris",
"[",
"0",
"]",
".",
"uri",
",",
"MEDIA_CLASS_VIDEO",
",",
")",
"for",
"item",
"in",
"response",
".",
"game_clips",
"]",
"elif",
"kind",
"==",
"\"screenshots\"",
":",
"if",
"owner",
"==",
"\"my\"",
":",
"response",
":",
"ScreenshotResponse",
"=",
"(",
"await",
"self",
".",
"client",
".",
"screenshots",
".",
"get_recent_screenshots_by_xuid",
"(",
"self",
".",
"client",
".",
"xuid",
",",
"title_id",
")",
")",
"elif",
"owner",
"==",
"\"community\"",
":",
"response",
":",
"ScreenshotResponse",
"=",
"await",
"self",
".",
"client",
".",
"screenshots",
".",
"get_recent_community_screenshots_by_title_id",
"(",
"title_id",
")",
"else",
":",
"return",
"None",
"items",
"=",
"[",
"XboxMediaItem",
"(",
"item",
".",
"user_caption",
"or",
"dt_util",
".",
"as_local",
"(",
"item",
".",
"date_taken",
")",
".",
"strftime",
"(",
"\"%b. %d, %Y %I:%M%p\"",
")",
",",
"item",
".",
"thumbnails",
"[",
"0",
"]",
".",
"uri",
",",
"item",
".",
"screenshot_uris",
"[",
"0",
"]",
".",
"uri",
",",
"MEDIA_CLASS_IMAGE",
",",
")",
"for",
"item",
"in",
"response",
".",
"screenshots",
"]",
"except",
"ValidationError",
":",
"# Unexpected API response",
"pass",
"return",
"BrowseMediaSource",
"(",
"domain",
"=",
"DOMAIN",
",",
"identifier",
"=",
"f\"{title}~~{category}\"",
",",
"media_class",
"=",
"MEDIA_CLASS_DIRECTORY",
",",
"media_content_type",
"=",
"\"\"",
",",
"title",
"=",
"f\"{owner.title()} {kind.title()}\"",
",",
"can_play",
"=",
"False",
",",
"can_expand",
"=",
"True",
",",
"children",
"=",
"[",
"_build_media_item",
"(",
"title",
",",
"category",
",",
"item",
")",
"for",
"item",
"in",
"items",
"]",
",",
"children_media_class",
"=",
"MEDIA_CLASS_MAP",
"[",
"kind",
"]",
",",
"thumbnail",
"=",
"thumbnail",
",",
")"
] | [
134,
4
] | [
206,
9
] | python | en | ['en', 'co', 'en'] | True |
conv2d | (x_input, w_matrix) | conv2d returns a 2d convolution layer with full stride. | conv2d returns a 2d convolution layer with full stride. | def conv2d(x_input, w_matrix):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | [
"def",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
")",
":",
"return",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"'SAME'",
")"
] | [
124,
0
] | [
126,
80
] | python | en | ['en', 'en', 'en'] | True |
max_pool | (x_input, pool_size) | max_pool downsamples a feature map by 2X. | max_pool downsamples a feature map by 2X. | def max_pool(x_input, pool_size):
"""max_pool downsamples a feature map by 2X."""
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | [
"def",
"max_pool",
"(",
"x_input",
",",
"pool_size",
")",
":",
"return",
"tf",
".",
"nn",
".",
"max_pool",
"(",
"x_input",
",",
"ksize",
"=",
"[",
"1",
",",
"pool_size",
",",
"pool_size",
",",
"1",
"]",
",",
"strides",
"=",
"[",
"1",
",",
"pool_size",
",",
"pool_size",
",",
"1",
"]",
",",
"padding",
"=",
"'SAME'",
")"
] | [
129,
0
] | [
132,
79
] | python | en | ['en', 'en', 'en'] | True |
weight_variable | (shape) | weight_variable generates a weight variable of a given shape. | weight_variable generates a weight variable of a given shape. | def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial) | [
"def",
"weight_variable",
"(",
"shape",
")",
":",
"initial",
"=",
"tf",
".",
"truncated_normal",
"(",
"shape",
",",
"stddev",
"=",
"0.1",
")",
"return",
"tf",
".",
"Variable",
"(",
"initial",
")"
] | [
135,
0
] | [
138,
31
] | python | en | ['en', 'en', 'en'] | True |
bias_variable | (shape) | bias_variable generates a bias variable of a given shape. | bias_variable generates a bias variable of a given shape. | def bias_variable(shape):
"""bias_variable generates a bias variable of a given shape."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial) | [
"def",
"bias_variable",
"(",
"shape",
")",
":",
"initial",
"=",
"tf",
".",
"constant",
"(",
"0.1",
",",
"shape",
"=",
"shape",
")",
"return",
"tf",
".",
"Variable",
"(",
"initial",
")"
] | [
141,
0
] | [
144,
31
] | python | en | ['en', 'en', 'en'] | True |
download_mnist_retry | (data_dir, max_num_retries=20) | Try to download mnist dataset and avoid errors | Try to download mnist dataset and avoid errors | def download_mnist_retry(data_dir, max_num_retries=20):
"""Try to download mnist dataset and avoid errors"""
for _ in range(max_num_retries):
try:
return input_data.read_data_sets(data_dir, one_hot=True)
except tf.errors.AlreadyExistsError:
time.sleep(1)
raise Exception("Failed to download MNIST.") | [
"def",
"download_mnist_retry",
"(",
"data_dir",
",",
"max_num_retries",
"=",
"20",
")",
":",
"for",
"_",
"in",
"range",
"(",
"max_num_retries",
")",
":",
"try",
":",
"return",
"input_data",
".",
"read_data_sets",
"(",
"data_dir",
",",
"one_hot",
"=",
"True",
")",
"except",
"tf",
".",
"errors",
".",
"AlreadyExistsError",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"raise",
"Exception",
"(",
"\"Failed to download MNIST.\"",
")"
] | [
146,
0
] | [
153,
48
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.