Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
WaterHeaterEntity.state_attributes
(self)
Return the optional state attributes.
Return the optional state attributes.
def state_attributes(self): """Return the optional state attributes.""" data = { ATTR_CURRENT_TEMPERATURE: show_temp( self.hass, self.current_temperature, self.temperature_unit, self.precision, ), ATTR_TEMPERATURE: show_temp( self.hass, self.target_temperature, self.temperature_unit, self.precision, ), ATTR_TARGET_TEMP_HIGH: show_temp( self.hass, self.target_temperature_high, self.temperature_unit, self.precision, ), ATTR_TARGET_TEMP_LOW: show_temp( self.hass, self.target_temperature_low, self.temperature_unit, self.precision, ), } supported_features = self.supported_features if supported_features & SUPPORT_OPERATION_MODE: data[ATTR_OPERATION_MODE] = self.current_operation if supported_features & SUPPORT_AWAY_MODE: is_away = self.is_away_mode_on data[ATTR_AWAY_MODE] = STATE_ON if is_away else STATE_OFF return data
[ "def", "state_attributes", "(", "self", ")", ":", "data", "=", "{", "ATTR_CURRENT_TEMPERATURE", ":", "show_temp", "(", "self", ".", "hass", ",", "self", ".", "current_temperature", ",", "self", ".", "temperature_unit", ",", "self", ".", "precision", ",", ")", ",", "ATTR_TEMPERATURE", ":", "show_temp", "(", "self", ".", "hass", ",", "self", ".", "target_temperature", ",", "self", ".", "temperature_unit", ",", "self", ".", "precision", ",", ")", ",", "ATTR_TARGET_TEMP_HIGH", ":", "show_temp", "(", "self", ".", "hass", ",", "self", ".", "target_temperature_high", ",", "self", ".", "temperature_unit", ",", "self", ".", "precision", ",", ")", ",", "ATTR_TARGET_TEMP_LOW", ":", "show_temp", "(", "self", ".", "hass", ",", "self", ".", "target_temperature_low", ",", "self", ".", "temperature_unit", ",", "self", ".", "precision", ",", ")", ",", "}", "supported_features", "=", "self", ".", "supported_features", "if", "supported_features", "&", "SUPPORT_OPERATION_MODE", ":", "data", "[", "ATTR_OPERATION_MODE", "]", "=", "self", ".", "current_operation", "if", "supported_features", "&", "SUPPORT_AWAY_MODE", ":", "is_away", "=", "self", ".", "is_away_mode_on", "data", "[", "ATTR_AWAY_MODE", "]", "=", "STATE_ON", "if", "is_away", "else", "STATE_OFF", "return", "data" ]
[ 165, 4 ]
[ 203, 19 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.temperature_unit
(self)
Return the unit of measurement used by the platform.
Return the unit of measurement used by the platform.
def temperature_unit(self): """Return the unit of measurement used by the platform.""" raise NotImplementedError
[ "def", "temperature_unit", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 206, 4 ]
[ 208, 33 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.current_operation
(self)
Return current operation ie. eco, electric, performance, ...
Return current operation ie. eco, electric, performance, ...
def current_operation(self): """Return current operation ie. eco, electric, performance, ...""" return None
[ "def", "current_operation", "(", "self", ")", ":", "return", "None" ]
[ 211, 4 ]
[ 213, 19 ]
python
en
['nl', 'en', 'en']
True
WaterHeaterEntity.operation_list
(self)
Return the list of available operation modes.
Return the list of available operation modes.
def operation_list(self): """Return the list of available operation modes.""" return None
[ "def", "operation_list", "(", "self", ")", ":", "return", "None" ]
[ 216, 4 ]
[ 218, 19 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return None
[ "def", "current_temperature", "(", "self", ")", ":", "return", "None" ]
[ 221, 4 ]
[ 223, 19 ]
python
en
['en', 'la', 'en']
True
WaterHeaterEntity.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self): """Return the temperature we try to reach.""" return None
[ "def", "target_temperature", "(", "self", ")", ":", "return", "None" ]
[ 226, 4 ]
[ 228, 19 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.target_temperature_high
(self)
Return the highbound target temperature we try to reach.
Return the highbound target temperature we try to reach.
def target_temperature_high(self): """Return the highbound target temperature we try to reach.""" return None
[ "def", "target_temperature_high", "(", "self", ")", ":", "return", "None" ]
[ 231, 4 ]
[ 233, 19 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.target_temperature_low
(self)
Return the lowbound target temperature we try to reach.
Return the lowbound target temperature we try to reach.
def target_temperature_low(self): """Return the lowbound target temperature we try to reach.""" return None
[ "def", "target_temperature_low", "(", "self", ")", ":", "return", "None" ]
[ 236, 4 ]
[ 238, 19 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.is_away_mode_on
(self)
Return true if away mode is on.
Return true if away mode is on.
def is_away_mode_on(self): """Return true if away mode is on.""" return None
[ "def", "is_away_mode_on", "(", "self", ")", ":", "return", "None" ]
[ 241, 4 ]
[ 243, 19 ]
python
en
['en', 'fy', 'en']
True
WaterHeaterEntity.set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
def set_temperature(self, **kwargs): """Set new target temperature.""" raise NotImplementedError()
[ "def", "set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 245, 4 ]
[ 247, 35 ]
python
en
['en', 'ca', 'en']
True
WaterHeaterEntity.async_set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
async def async_set_temperature(self, **kwargs): """Set new target temperature.""" await self.hass.async_add_executor_job( ft.partial(self.set_temperature, **kwargs) )
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "ft", ".", "partial", "(", "self", ".", "set_temperature", ",", "*", "*", "kwargs", ")", ")" ]
[ 249, 4 ]
[ 253, 9 ]
python
en
['en', 'ca', 'en']
True
WaterHeaterEntity.set_operation_mode
(self, operation_mode)
Set new target operation mode.
Set new target operation mode.
def set_operation_mode(self, operation_mode): """Set new target operation mode.""" raise NotImplementedError()
[ "def", "set_operation_mode", "(", "self", ",", "operation_mode", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 255, 4 ]
[ 257, 35 ]
python
en
['nl', 'en', 'en']
True
WaterHeaterEntity.async_set_operation_mode
(self, operation_mode)
Set new target operation mode.
Set new target operation mode.
async def async_set_operation_mode(self, operation_mode): """Set new target operation mode.""" await self.hass.async_add_executor_job(self.set_operation_mode, operation_mode)
[ "async", "def", "async_set_operation_mode", "(", "self", ",", "operation_mode", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "set_operation_mode", ",", "operation_mode", ")" ]
[ 259, 4 ]
[ 261, 87 ]
python
en
['nl', 'en', 'en']
True
WaterHeaterEntity.turn_away_mode_on
(self)
Turn away mode on.
Turn away mode on.
def turn_away_mode_on(self): """Turn away mode on.""" raise NotImplementedError()
[ "def", "turn_away_mode_on", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 263, 4 ]
[ 265, 35 ]
python
en
['en', 'yo', 'en']
True
WaterHeaterEntity.async_turn_away_mode_on
(self)
Turn away mode on.
Turn away mode on.
async def async_turn_away_mode_on(self): """Turn away mode on.""" await self.hass.async_add_executor_job(self.turn_away_mode_on)
[ "async", "def", "async_turn_away_mode_on", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "turn_away_mode_on", ")" ]
[ 267, 4 ]
[ 269, 70 ]
python
en
['en', 'yo', 'en']
True
WaterHeaterEntity.turn_away_mode_off
(self)
Turn away mode off.
Turn away mode off.
def turn_away_mode_off(self): """Turn away mode off.""" raise NotImplementedError()
[ "def", "turn_away_mode_off", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 271, 4 ]
[ 273, 35 ]
python
en
['en', 'yo', 'en']
True
WaterHeaterEntity.async_turn_away_mode_off
(self)
Turn away mode off.
Turn away mode off.
async def async_turn_away_mode_off(self): """Turn away mode off.""" await self.hass.async_add_executor_job(self.turn_away_mode_off)
[ "async", "def", "async_turn_away_mode_off", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "turn_away_mode_off", ")" ]
[ 275, 4 ]
[ 277, 71 ]
python
en
['en', 'yo', 'en']
True
WaterHeaterEntity.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self): """Return the list of supported features.""" raise NotImplementedError()
[ "def", "supported_features", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 280, 4 ]
[ 282, 35 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.min_temp
(self)
Return the minimum temperature.
Return the minimum temperature.
def min_temp(self): """Return the minimum temperature.""" return convert_temperature( DEFAULT_MIN_TEMP, TEMP_FAHRENHEIT, self.temperature_unit )
[ "def", "min_temp", "(", "self", ")", ":", "return", "convert_temperature", "(", "DEFAULT_MIN_TEMP", ",", "TEMP_FAHRENHEIT", ",", "self", ".", "temperature_unit", ")" ]
[ 285, 4 ]
[ 289, 9 ]
python
en
['en', 'la', 'en']
True
WaterHeaterEntity.max_temp
(self)
Return the maximum temperature.
Return the maximum temperature.
def max_temp(self): """Return the maximum temperature.""" return convert_temperature( DEFAULT_MAX_TEMP, TEMP_FAHRENHEIT, self.temperature_unit )
[ "def", "max_temp", "(", "self", ")", ":", "return", "convert_temperature", "(", "DEFAULT_MAX_TEMP", ",", "TEMP_FAHRENHEIT", ",", "self", ".", "temperature_unit", ")" ]
[ 292, 4 ]
[ 296, 9 ]
python
en
['en', 'la', 'en']
True
WaterHeaterDevice.__init_subclass__
(cls, **kwargs)
Print deprecation warning.
Print deprecation warning.
def __init_subclass__(cls, **kwargs): """Print deprecation warning.""" super().__init_subclass__(**kwargs) _LOGGER.warning( "WaterHeaterDevice is deprecated, modify %s to extend WaterHeaterEntity", cls.__name__, )
[ "def", "__init_subclass__", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init_subclass__", "(", "*", "*", "kwargs", ")", "_LOGGER", ".", "warning", "(", "\"WaterHeaterDevice is deprecated, modify %s to extend WaterHeaterEntity\"", ",", "cls", ".", "__name__", ",", ")" ]
[ 326, 4 ]
[ 332, 9 ]
python
de
['de', 'sv', 'en']
False
SklearnTopicModels.__init__
(self, n_topics=50, estimator='LDA')
n_topics is the desired number of topics To use Latent Semantic Analysis, set estimator to 'LSA', To use Non-Negative Matrix Factorization, set estimator to 'NMF', otherwise, defaults to Latent Dirichlet Allocation ('LDA').
n_topics is the desired number of topics To use Latent Semantic Analysis, set estimator to 'LSA', To use Non-Negative Matrix Factorization, set estimator to 'NMF', otherwise, defaults to Latent Dirichlet Allocation ('LDA').
def __init__(self, n_topics=50, estimator='LDA'): """ n_topics is the desired number of topics To use Latent Semantic Analysis, set estimator to 'LSA', To use Non-Negative Matrix Factorization, set estimator to 'NMF', otherwise, defaults to Latent Dirichlet Allocation ('LDA'). """ self.n_topics = n_topics if estimator == 'LSA': self.estimator = TruncatedSVD(n_components=self.n_topics) elif estimator == 'NMF': self.estimator = NMF(n_components=self.n_topics) else: self.estimator = LatentDirichletAllocation(n_topics=self.n_topics) self.model = Pipeline([ ('norm', TextNormalizer()), ('tfidf', CountVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)), ('model', self.estimator) ])
[ "def", "__init__", "(", "self", ",", "n_topics", "=", "50", ",", "estimator", "=", "'LDA'", ")", ":", "self", ".", "n_topics", "=", "n_topics", "if", "estimator", "==", "'LSA'", ":", "self", ".", "estimator", "=", "TruncatedSVD", "(", "n_components", "=", "self", ".", "n_topics", ")", "elif", "estimator", "==", "'NMF'", ":", "self", ".", "estimator", "=", "NMF", "(", "n_components", "=", "self", ".", "n_topics", ")", "else", ":", "self", ".", "estimator", "=", "LatentDirichletAllocation", "(", "n_topics", "=", "self", ".", "n_topics", ")", "self", ".", "model", "=", "Pipeline", "(", "[", "(", "'norm'", ",", "TextNormalizer", "(", ")", ")", ",", "(", "'tfidf'", ",", "CountVectorizer", "(", "tokenizer", "=", "identity", ",", "preprocessor", "=", "None", ",", "lowercase", "=", "False", ")", ")", ",", "(", "'model'", ",", "self", ".", "estimator", ")", "]", ")" ]
[ 17, 4 ]
[ 38, 10 ]
python
en
['en', 'error', 'th']
False
SklearnTopicModels.get_topics
(self, n=25)
n is the number of top terms to show for each topic
n is the number of top terms to show for each topic
def get_topics(self, n=25): """ n is the number of top terms to show for each topic """ vectorizer = self.model.named_steps['tfidf'] model = self.model.steps[-1][1] names = vectorizer.get_feature_names() topics = dict() for idx, topic in enumerate(model.components_): features = topic.argsort()[:-(n - 1): -1] tokens = [names[i] for i in features] topics[idx] = tokens return topics
[ "def", "get_topics", "(", "self", ",", "n", "=", "25", ")", ":", "vectorizer", "=", "self", ".", "model", ".", "named_steps", "[", "'tfidf'", "]", "model", "=", "self", ".", "model", ".", "steps", "[", "-", "1", "]", "[", "1", "]", "names", "=", "vectorizer", ".", "get_feature_names", "(", ")", "topics", "=", "dict", "(", ")", "for", "idx", ",", "topic", "in", "enumerate", "(", "model", ".", "components_", ")", ":", "features", "=", "topic", ".", "argsort", "(", ")", "[", ":", "-", "(", "n", "-", "1", ")", ":", "-", "1", "]", "tokens", "=", "[", "names", "[", "i", "]", "for", "i", "in", "features", "]", "topics", "[", "idx", "]", "=", "tokens", "return", "topics" ]
[ 47, 4 ]
[ 61, 21 ]
python
en
['en', 'error', 'th']
False
GensimTopicModels.__init__
(self, n_topics=50, estimator='LDA')
n_topics is the desired number of topics To use Latent Semantic Analysis, set estimator to 'LSA' otherwise defaults to Latent Dirichlet Allocation.
n_topics is the desired number of topics
def __init__(self, n_topics=50, estimator='LDA'): """ n_topics is the desired number of topics To use Latent Semantic Analysis, set estimator to 'LSA' otherwise defaults to Latent Dirichlet Allocation. """ self.n_topics = n_topics if estimator == 'LSA': self.estimator = lsimodel.LsiTransformer(num_topics=self.n_topics) else: self.estimator = ldamodel.LdaTransformer(num_topics=self.n_topics) self.model = Pipeline([ ('norm', TextNormalizer()), ('vect', GensimTfidfVectorizer()), ('model', self.estimator) ])
[ "def", "__init__", "(", "self", ",", "n_topics", "=", "50", ",", "estimator", "=", "'LDA'", ")", ":", "self", ".", "n_topics", "=", "n_topics", "if", "estimator", "==", "'LSA'", ":", "self", ".", "estimator", "=", "lsimodel", ".", "LsiTransformer", "(", "num_topics", "=", "self", ".", "n_topics", ")", "else", ":", "self", ".", "estimator", "=", "ldamodel", ".", "LdaTransformer", "(", "num_topics", "=", "self", ".", "n_topics", ")", "self", ".", "model", "=", "Pipeline", "(", "[", "(", "'norm'", ",", "TextNormalizer", "(", ")", ")", ",", "(", "'vect'", ",", "GensimTfidfVectorizer", "(", ")", ")", ",", "(", "'model'", ",", "self", ".", "estimator", ")", "]", ")" ]
[ 66, 4 ]
[ 84, 10 ]
python
en
['en', 'error', 'th']
False
convert_pytorch_checkpoint_to_tf
(model: BertModel, ckpt_dir: str, model_name: str)
Args: model: BertModel Pytorch model instance to be converted ckpt_dir: Tensorflow model directory model_name: model name Currently supported HF models: - Y BertModel - N BertForMaskedLM - N BertForPreTraining - N BertForMultipleChoice - N BertForNextSentencePrediction - N BertForSequenceClassification - N BertForQuestionAnswering
Args: model: BertModel Pytorch model instance to be converted ckpt_dir: Tensorflow model directory model_name: model name
def convert_pytorch_checkpoint_to_tf(model: BertModel, ckpt_dir: str, model_name: str): """ Args: model: BertModel Pytorch model instance to be converted ckpt_dir: Tensorflow model directory model_name: model name Currently supported HF models: - Y BertModel - N BertForMaskedLM - N BertForPreTraining - N BertForMultipleChoice - N BertForNextSentencePrediction - N BertForSequenceClassification - N BertForQuestionAnswering """ tensors_to_transpose = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") var_map = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(ckpt_dir): os.makedirs(ckpt_dir) state_dict = model.state_dict() def to_tf_var_name(name: str): for patt, repl in iter(var_map): name = name.replace(patt, repl) return "bert/{}".format(name) def create_tf_var(tensor: np.ndarray, name: str, session: tf.Session): tf_dtype = tf.dtypes.as_dtype(tensor.dtype) tf_var = tf.get_variable(dtype=tf_dtype, shape=tensor.shape, name=name, initializer=tf.zeros_initializer()) session.run(tf.variables_initializer([tf_var])) session.run(tf_var) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: tf_name = to_tf_var_name(var_name) torch_tensor = state_dict[var_name].numpy() if any([x in var_name for x in tensors_to_transpose]): torch_tensor = torch_tensor.T tf_var = create_tf_var(tensor=torch_tensor, name=tf_name, session=session) tf.keras.backend.set_value(tf_var, torch_tensor) tf_weight = session.run(tf_var) print("Successfully created {}: {}".format(tf_name, np.allclose(tf_weight, torch_tensor))) saver = tf.train.Saver(tf.trainable_variables()) saver.save(session, os.path.join(ckpt_dir, model_name.replace("-", "_") + ".ckpt"))
[ "def", "convert_pytorch_checkpoint_to_tf", "(", "model", ":", "BertModel", ",", "ckpt_dir", ":", "str", ",", "model_name", ":", "str", ")", ":", "tensors_to_transpose", "=", "(", "\"dense.weight\"", ",", "\"attention.self.query\"", ",", "\"attention.self.key\"", ",", "\"attention.self.value\"", ")", "var_map", "=", "(", "(", "\"layer.\"", ",", "\"layer_\"", ")", ",", "(", "\"word_embeddings.weight\"", ",", "\"word_embeddings\"", ")", ",", "(", "\"position_embeddings.weight\"", ",", "\"position_embeddings\"", ")", ",", "(", "\"token_type_embeddings.weight\"", ",", "\"token_type_embeddings\"", ")", ",", "(", "\".\"", ",", "\"/\"", ")", ",", "(", "\"LayerNorm/weight\"", ",", "\"LayerNorm/gamma\"", ")", ",", "(", "\"LayerNorm/bias\"", ",", "\"LayerNorm/beta\"", ")", ",", "(", "\"weight\"", ",", "\"kernel\"", ")", ",", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "ckpt_dir", ")", ":", "os", ".", "makedirs", "(", "ckpt_dir", ")", "state_dict", "=", "model", ".", "state_dict", "(", ")", "def", "to_tf_var_name", "(", "name", ":", "str", ")", ":", "for", "patt", ",", "repl", "in", "iter", "(", "var_map", ")", ":", "name", "=", "name", ".", "replace", "(", "patt", ",", "repl", ")", "return", "\"bert/{}\"", ".", "format", "(", "name", ")", "def", "create_tf_var", "(", "tensor", ":", "np", ".", "ndarray", ",", "name", ":", "str", ",", "session", ":", "tf", ".", "Session", ")", ":", "tf_dtype", "=", "tf", ".", "dtypes", ".", "as_dtype", "(", "tensor", ".", "dtype", ")", "tf_var", "=", "tf", ".", "get_variable", "(", "dtype", "=", "tf_dtype", ",", "shape", "=", "tensor", ".", "shape", ",", "name", "=", "name", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "session", ".", "run", "(", "tf", ".", "variables_initializer", "(", "[", "tf_var", "]", ")", ")", "session", ".", "run", "(", "tf_var", ")", "return", "tf_var", "tf", ".", "reset_default_graph", "(", ")", "with", "tf", ".", "Session", "(", ")", "as", "session", ":", "for", "var_name", "in", "state_dict", ":", "tf_name", "=", "to_tf_var_name", "(", "var_name", ")", "torch_tensor", "=", "state_dict", "[", "var_name", "]", ".", "numpy", "(", ")", "if", "any", "(", "[", "x", "in", "var_name", "for", "x", "in", "tensors_to_transpose", "]", ")", ":", "torch_tensor", "=", "torch_tensor", ".", "T", "tf_var", "=", "create_tf_var", "(", "tensor", "=", "torch_tensor", ",", "name", "=", "tf_name", ",", "session", "=", "session", ")", "tf", ".", "keras", ".", "backend", ".", "set_value", "(", "tf_var", ",", "torch_tensor", ")", "tf_weight", "=", "session", ".", "run", "(", "tf_var", ")", "print", "(", "\"Successfully created {}: {}\"", ".", "format", "(", "tf_name", ",", "np", ".", "allclose", "(", "tf_weight", ",", "torch_tensor", ")", ")", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", "tf", ".", "trainable_variables", "(", ")", ")", "saver", ".", "save", "(", "session", ",", "os", ".", "path", ".", "join", "(", "ckpt_dir", ",", "model_name", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "+", "\".ckpt\"", ")", ")" ]
[ 27, 0 ]
[ 89, 91 ]
python
en
['en', 'error', 'th']
False
TFRobertaEmbeddings.create_position_ids_from_input_ids
(self, input_ids)
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: input_ids: tf.Tensor Returns: tf.Tensor
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`.
def create_position_ids_from_input_ids(self, input_ids): """ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: input_ids: tf.Tensor Returns: tf.Tensor """ mask = tf.cast(tf.math.not_equal(input_ids, self.padding_idx), dtype=input_ids.dtype) incremental_indices = tf.math.cumsum(mask, axis=1) * mask return incremental_indices + self.padding_idx
[ "def", "create_position_ids_from_input_ids", "(", "self", ",", "input_ids", ")", ":", "mask", "=", "tf", ".", "cast", "(", "tf", ".", "math", ".", "not_equal", "(", "input_ids", ",", "self", ".", "padding_idx", ")", ",", "dtype", "=", "input_ids", ".", "dtype", ")", "incremental_indices", "=", "tf", ".", "math", ".", "cumsum", "(", "mask", ",", "axis", "=", "1", ")", "*", "mask", "return", "incremental_indices", "+", "self", ".", "padding_idx" ]
[ 114, 4 ]
[ 126, 53 ]
python
en
['en', 'error', 'th']
False
TFRobertaEmbeddings.call
(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_embeds=None, training=False)
Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor`): output embedding tensor.
Applies embedding based on inputs tensor.
def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_embeds=None, training=False): """ Applies embedding based on inputs tensor. Returns: final_embeddings (:obj:`tf.Tensor`): output embedding tensor. """ assert not (input_ids is None and inputs_embeds is None) if input_ids is not None: inputs_embeds = tf.gather(params=self.weight, indices=input_ids) input_shape = shape_list(inputs_embeds)[:-1] if token_type_ids is None: token_type_ids = tf.fill(dims=input_shape, value=0) if position_ids is None: if input_ids is not None: # Create the position ids from the input token ids. Any padded tokens remain padded. position_ids = self.create_position_ids_from_input_ids(input_ids=input_ids) else: position_ids = tf.expand_dims( tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0 ) position_ids = tf.tile(input=position_ids, multiples=(input_shape[0], 1)) position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids) token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids) final_embeddings = self.embeddings_sum(inputs=[inputs_embeds, position_embeds, token_type_embeds]) final_embeddings = self.LayerNorm(inputs=final_embeddings) final_embeddings = self.dropout(inputs=final_embeddings, training=training) return final_embeddings
[ "def", "call", "(", "self", ",", "input_ids", "=", "None", ",", "position_ids", "=", "None", ",", "token_type_ids", "=", "None", ",", "inputs_embeds", "=", "None", ",", "training", "=", "False", ")", ":", "assert", "not", "(", "input_ids", "is", "None", "and", "inputs_embeds", "is", "None", ")", "if", "input_ids", "is", "not", "None", ":", "inputs_embeds", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "weight", ",", "indices", "=", "input_ids", ")", "input_shape", "=", "shape_list", "(", "inputs_embeds", ")", "[", ":", "-", "1", "]", "if", "token_type_ids", "is", "None", ":", "token_type_ids", "=", "tf", ".", "fill", "(", "dims", "=", "input_shape", ",", "value", "=", "0", ")", "if", "position_ids", "is", "None", ":", "if", "input_ids", "is", "not", "None", ":", "# Create the position ids from the input token ids. Any padded tokens remain padded.", "position_ids", "=", "self", ".", "create_position_ids_from_input_ids", "(", "input_ids", "=", "input_ids", ")", "else", ":", "position_ids", "=", "tf", ".", "expand_dims", "(", "tf", ".", "range", "(", "start", "=", "self", ".", "padding_idx", "+", "1", ",", "limit", "=", "input_shape", "[", "-", "1", "]", "+", "self", ".", "padding_idx", "+", "1", ")", ",", "axis", "=", "0", ")", "position_ids", "=", "tf", ".", "tile", "(", "input", "=", "position_ids", ",", "multiples", "=", "(", "input_shape", "[", "0", "]", ",", "1", ")", ")", "position_embeds", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "position_embeddings", ",", "indices", "=", "position_ids", ")", "token_type_embeds", "=", "tf", ".", "gather", "(", "params", "=", "self", ".", "token_type_embeddings", ",", "indices", "=", "token_type_ids", ")", "final_embeddings", "=", "self", ".", "embeddings_sum", "(", "inputs", "=", "[", "inputs_embeds", ",", "position_embeds", ",", "token_type_embeds", "]", ")", "final_embeddings", "=", "self", ".", "LayerNorm", "(", "inputs", "=", "final_embeddings", ")", "final_embeddings", "=", "self", ".", "dropout", "(", "inputs", "=", "final_embeddings", ",", "training", "=", "training", ")", "return", "final_embeddings" ]
[ 128, 4 ]
[ 161, 31 ]
python
en
['en', 'error', 'th']
False
async_setup_reload_service
(hass)
Create the reload service for the template domain.
Create the reload service for the template domain.
async def async_setup_reload_service(hass): """Create the reload service for the template domain.""" if hass.services.has_service(DOMAIN, SERVICE_RELOAD): return async def _reload_config(call): """Reload the template platform config.""" await async_reload_integration_platforms(hass, DOMAIN, PLATFORMS) hass.bus.async_fire(EVENT_TEMPLATE_RELOADED, context=call.context) hass.helpers.service.async_register_admin_service( DOMAIN, SERVICE_RELOAD, _reload_config )
[ "async", "def", "async_setup_reload_service", "(", "hass", ")", ":", "if", "hass", ".", "services", ".", "has_service", "(", "DOMAIN", ",", "SERVICE_RELOAD", ")", ":", "return", "async", "def", "_reload_config", "(", "call", ")", ":", "\"\"\"Reload the template platform config.\"\"\"", "await", "async_reload_integration_platforms", "(", "hass", ",", "DOMAIN", ",", "PLATFORMS", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_TEMPLATE_RELOADED", ",", "context", "=", "call", ".", "context", ")", "hass", ".", "helpers", ".", "service", ".", "async_register_admin_service", "(", "DOMAIN", ",", "SERVICE_RELOAD", ",", "_reload_config", ")" ]
[ 7, 0 ]
[ 21, 5 ]
python
en
['en', 'en', 'en']
True
T5Tokenizer.get_special_tokens_mask
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False )
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the token list is already formatted with special tokens for the model. Returns: :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method.
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not the token list is already formatted with special tokens for the model. Returns: :obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: if token_ids_1 is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0)) # normal case: some special tokens if token_ids_1 is None: return ([0] * len(token_ids_0)) + [1] return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
[ "def", "get_special_tokens_mask", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ",", "already_has_special_tokens", ":", "bool", "=", "False", ")", "->", "List", "[", "int", "]", ":", "if", "already_has_special_tokens", ":", "if", "token_ids_1", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You should not supply a second sequence if the provided sequence of \"", "\"ids is already formatted with special tokens for the model.\"", ")", "return", "list", "(", "map", "(", "lambda", "x", ":", "1", "if", "x", "in", "[", "self", ".", "sep_token_id", ",", "self", ".", "cls_token_id", "]", "else", "0", ",", "token_ids_0", ")", ")", "# normal case: some special tokens", "if", "token_ids_1", "is", "None", ":", "return", "(", "[", "0", "]", "*", "len", "(", "token_ids_0", ")", ")", "+", "[", "1", "]", "return", "(", "[", "0", "]", "*", "len", "(", "token_ids_0", ")", ")", "+", "[", "1", "]", "+", "(", "[", "0", "]", "*", "len", "(", "token_ids_1", ")", ")", "+", "[", "1", "]" ]
[ 140, 4 ]
[ 168, 78 ]
python
en
['en', 'error', 'th']
False
T5Tokenizer._add_eos_if_not_present
(self, token_ids: List[int])
Do not add eos again if user already added it.
Do not add eos again if user already added it.
def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]: """Do not add eos again if user already added it.""" if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id]
[ "def", "_add_eos_if_not_present", "(", "self", ",", "token_ids", ":", "List", "[", "int", "]", ")", "->", "List", "[", "int", "]", ":", "if", "len", "(", "token_ids", ")", ">", "0", "and", "token_ids", "[", "-", "1", "]", "==", "self", ".", "eos_token_id", ":", "warnings", ".", "warn", "(", "f\"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated eos tokens being added.\"", ")", "return", "token_ids", "else", ":", "return", "token_ids", "+", "[", "self", ".", "eos_token_id", "]" ]
[ 170, 4 ]
[ 178, 50 ]
python
en
['en', 'en', 'en']
True
T5Tokenizer.create_token_type_ids_from_sequences
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make use of token type ids, therefore a list of zeros is returned. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of zeros.
Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make use of token type ids, therefore a list of zeros is returned.
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make use of token type ids, therefore a list of zeros is returned. Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of zeros. """ eos = [self.eos_token_id] if token_ids_1 is None: return len(token_ids_0 + eos) * [0] return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
[ "def", "create_token_type_ids_from_sequences", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "eos", "=", "[", "self", ".", "eos_token_id", "]", "if", "token_ids_1", "is", "None", ":", "return", "len", "(", "token_ids_0", "+", "eos", ")", "*", "[", "0", "]", "return", "len", "(", "token_ids_0", "+", "eos", "+", "token_ids_1", "+", "eos", ")", "*", "[", "0", "]" ]
[ 180, 4 ]
[ 200, 63 ]
python
en
['en', 'error', 'th']
False
T5Tokenizer.build_inputs_with_special_tokens
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A sequence has the following format: - single sequence: ``X </s>`` - pair of sequences: ``A </s> B </s>`` Args: token_ids_0 (:obj:`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A sequence has the following format:
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A sequence has the following format: - single sequence: ``X </s>`` - pair of sequences: ``A </s> B </s>`` Args: token_ids_0 (:obj:`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens. """ token_ids_0 = self._add_eos_if_not_present(token_ids_0) if token_ids_1 is None: return token_ids_0 else: token_ids_1 = self._add_eos_if_not_present(token_ids_1) return token_ids_0 + token_ids_1
[ "def", "build_inputs_with_special_tokens", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "token_ids_0", "=", "self", ".", "_add_eos_if_not_present", "(", "token_ids_0", ")", "if", "token_ids_1", "is", "None", ":", "return", "token_ids_0", "else", ":", "token_ids_1", "=", "self", ".", "_add_eos_if_not_present", "(", "token_ids_1", ")", "return", "token_ids_0", "+", "token_ids_1" ]
[ 202, 4 ]
[ 226, 44 ]
python
en
['en', 'error', 'th']
False
T5Tokenizer._tokenize
(self, text, sample=False)
Take as input a string and return a list of strings (tokens) for words/sub-words
Take as input a string and return a list of strings (tokens) for words/sub-words
def _tokenize(self, text, sample=False): """Take as input a string and return a list of strings (tokens) for words/sub-words""" if not sample: pieces = self.sp_model.EncodeAsPieces(text) else: pieces = self.sp_model.SampleEncodeAsPieces(text, 64, 0.1) return pieces
[ "def", "_tokenize", "(", "self", ",", "text", ",", "sample", "=", "False", ")", ":", "if", "not", "sample", ":", "pieces", "=", "self", ".", "sp_model", ".", "EncodeAsPieces", "(", "text", ")", "else", ":", "pieces", "=", "self", ".", "sp_model", ".", "SampleEncodeAsPieces", "(", "text", ",", "64", ",", "0.1", ")", "return", "pieces" ]
[ 238, 4 ]
[ 244, 21 ]
python
en
['en', 'en', 'en']
True
T5Tokenizer._convert_token_to_id
(self, token)
Converts a token (str) in an id using the vocab.
Converts a token (str) in an id using the vocab.
def _convert_token_to_id(self, token): """ Converts a token (str) in an id using the vocab. """ if token.startswith("<extra_id_"): match = re.match(r"<extra_id_(\d+)>", token) num = int(match.group(1)) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(token)
[ "def", "_convert_token_to_id", "(", "self", ",", "token", ")", ":", "if", "token", ".", "startswith", "(", "\"<extra_id_\"", ")", ":", "match", "=", "re", ".", "match", "(", "r\"<extra_id_(\\d+)>\"", ",", "token", ")", "num", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "return", "self", ".", "vocab_size", "-", "num", "-", "1", "return", "self", ".", "sp_model", ".", "piece_to_id", "(", "token", ")" ]
[ 246, 4 ]
[ 252, 47 ]
python
en
['en', 'en', 'en']
True
T5Tokenizer._convert_id_to_token
(self, index)
Converts an index (integer) in a token (str) using the vocab.
Converts an index (integer) in a token (str) using the vocab.
def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" if index < self.sp_model.get_piece_size(): token = self.sp_model.IdToPiece(index) else: token = "<extra_id_{}>".format(self.vocab_size - 1 - index) return token
[ "def", "_convert_id_to_token", "(", "self", ",", "index", ")", ":", "if", "index", "<", "self", ".", "sp_model", ".", "get_piece_size", "(", ")", ":", "token", "=", "self", ".", "sp_model", ".", "IdToPiece", "(", "index", ")", "else", ":", "token", "=", "\"<extra_id_{}>\"", ".", "format", "(", "self", ".", "vocab_size", "-", "1", "-", "index", ")", "return", "token" ]
[ 254, 4 ]
[ 260, 20 ]
python
en
['en', 'en', 'en']
True
T5Tokenizer.convert_tokens_to_string
(self, tokens)
Converts a sequence of tokens (string) in a single string.
Converts a sequence of tokens (string) in a single string.
def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. """ current_sub_tokens = [] out_string = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode_pieces(current_sub_tokens) + token + " " current_sub_tokens = [] else: current_sub_tokens.append(token) out_string += self.sp_model.decode_pieces(current_sub_tokens) return out_string.strip()
[ "def", "convert_tokens_to_string", "(", "self", ",", "tokens", ")", ":", "current_sub_tokens", "=", "[", "]", "out_string", "=", "\"\"", "for", "token", "in", "tokens", ":", "# make sure that special tokens are not decoded using sentencepiece model", "if", "token", "in", "self", ".", "all_special_tokens", ":", "out_string", "+=", "self", ".", "sp_model", ".", "decode_pieces", "(", "current_sub_tokens", ")", "+", "token", "+", "\" \"", "current_sub_tokens", "=", "[", "]", "else", ":", "current_sub_tokens", ".", "append", "(", "token", ")", "out_string", "+=", "self", ".", "sp_model", ".", "decode_pieces", "(", "current_sub_tokens", ")", "return", "out_string", ".", "strip", "(", ")" ]
[ 262, 4 ]
[ 274, 33 ]
python
en
['en', 'en', 'en']
True
setup_scanner
(hass, config: dict, see, discovery_info=None)
Validate the configuration and return a TrackR scanner.
Validate the configuration and return a TrackR scanner.
def setup_scanner(hass, config: dict, see, discovery_info=None): """Validate the configuration and return a TrackR scanner.""" TrackRDeviceScanner(hass, config, see) return True
[ "def", "setup_scanner", "(", "hass", ",", "config", ":", "dict", ",", "see", ",", "discovery_info", "=", "None", ")", ":", "TrackRDeviceScanner", "(", "hass", ",", "config", ",", "see", ")", "return", "True" ]
[ 19, 0 ]
[ 22, 15 ]
python
en
['en', 'en', 'en']
True
TrackRDeviceScanner.__init__
(self, hass, config: dict, see)
Initialize the TrackR device scanner.
Initialize the TrackR device scanner.
def __init__(self, hass, config: dict, see) -> None: """Initialize the TrackR device scanner.""" self.hass = hass self.api = trackrApiInterface( config.get(CONF_USERNAME), config.get(CONF_PASSWORD) ) self.see = see self.devices = self.api.get_trackrs() self._update_info() track_utc_time_change(self.hass, self._update_info, second=range(0, 60, 30))
[ "def", "__init__", "(", "self", ",", "hass", ",", "config", ":", "dict", ",", "see", ")", "->", "None", ":", "self", ".", "hass", "=", "hass", "self", ".", "api", "=", "trackrApiInterface", "(", "config", ".", "get", "(", "CONF_USERNAME", ")", ",", "config", ".", "get", "(", "CONF_PASSWORD", ")", ")", "self", ".", "see", "=", "see", "self", ".", "devices", "=", "self", ".", "api", ".", "get_trackrs", "(", ")", "self", ".", "_update_info", "(", ")", "track_utc_time_change", "(", "self", ".", "hass", ",", "self", ".", "_update_info", ",", "second", "=", "range", "(", "0", ",", "60", ",", "30", ")", ")" ]
[ 28, 4 ]
[ 39, 84 ]
python
en
['en', 'en', 'en']
True
TrackRDeviceScanner._update_info
(self, now=None)
Update the device info.
Update the device info.
def _update_info(self, now=None) -> None: """Update the device info.""" _LOGGER.debug("Updating devices %s", now) # Update self.devices to collect new devices added # to the users account. self.devices = self.api.get_trackrs() for trackr in self.devices: trackr.update_state() trackr_id = trackr.tracker_id() trackr_device_id = trackr.id() lost = trackr.lost() dev_id = slugify(trackr.name()) if dev_id is None: dev_id = trackr_id location = trackr.last_known_location() lat = location["latitude"] lon = location["longitude"] attrs = { "last_updated": trackr.last_updated(), "last_seen": trackr.last_time_seen(), "trackr_id": trackr_id, "id": trackr_device_id, "lost": lost, "battery_level": trackr.battery_level(), } self.see(dev_id=dev_id, gps=(lat, lon), attributes=attrs)
[ "def", "_update_info", "(", "self", ",", "now", "=", "None", ")", "->", "None", ":", "_LOGGER", ".", "debug", "(", "\"Updating devices %s\"", ",", "now", ")", "# Update self.devices to collect new devices added", "# to the users account.", "self", ".", "devices", "=", "self", ".", "api", ".", "get_trackrs", "(", ")", "for", "trackr", "in", "self", ".", "devices", ":", "trackr", ".", "update_state", "(", ")", "trackr_id", "=", "trackr", ".", "tracker_id", "(", ")", "trackr_device_id", "=", "trackr", ".", "id", "(", ")", "lost", "=", "trackr", ".", "lost", "(", ")", "dev_id", "=", "slugify", "(", "trackr", ".", "name", "(", ")", ")", "if", "dev_id", "is", "None", ":", "dev_id", "=", "trackr_id", "location", "=", "trackr", ".", "last_known_location", "(", ")", "lat", "=", "location", "[", "\"latitude\"", "]", "lon", "=", "location", "[", "\"longitude\"", "]", "attrs", "=", "{", "\"last_updated\"", ":", "trackr", ".", "last_updated", "(", ")", ",", "\"last_seen\"", ":", "trackr", ".", "last_time_seen", "(", ")", ",", "\"trackr_id\"", ":", "trackr_id", ",", "\"id\"", ":", "trackr_device_id", ",", "\"lost\"", ":", "lost", ",", "\"battery_level\"", ":", "trackr", ".", "battery_level", "(", ")", ",", "}", "self", ".", "see", "(", "dev_id", "=", "dev_id", ",", "gps", "=", "(", "lat", ",", "lon", ")", ",", "attributes", "=", "attrs", ")" ]
[ 41, 4 ]
[ 70, 69 ]
python
en
['en', 'en', 'en']
True
async_describe_on_off_states
( hass: HomeAssistantType, registry: GroupIntegrationRegistry )
Describe group on off states.
Describe group on off states.
def async_describe_on_off_states( hass: HomeAssistantType, registry: GroupIntegrationRegistry ) -> None: """Describe group on off states.""" registry.on_off_states({STATE_HOME}, STATE_NOT_HOME)
[ "def", "async_describe_on_off_states", "(", "hass", ":", "HomeAssistantType", ",", "registry", ":", "GroupIntegrationRegistry", ")", "->", "None", ":", "registry", ".", "on_off_states", "(", "{", "STATE_HOME", "}", ",", "STATE_NOT_HOME", ")" ]
[ 10, 0 ]
[ 14, 56 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities )
Set up discovered binary sensors.
Set up discovered binary sensors.
async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up discovered binary sensors.""" devs = [] for dev in hass.data[AQUALINK_DOMAIN][DOMAIN]: devs.append(HassAqualinkBinarySensor(dev)) async_add_entities(devs, True)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "config_entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "devs", "=", "[", "]", "for", "dev", "in", "hass", ".", "data", "[", "AQUALINK_DOMAIN", "]", "[", "DOMAIN", "]", ":", "devs", ".", "append", "(", "HassAqualinkBinarySensor", "(", "dev", ")", ")", "async_add_entities", "(", "devs", ",", "True", ")" ]
[ 15, 0 ]
[ 22, 34 ]
python
en
['en', 'en', 'en']
True
HassAqualinkBinarySensor.name
(self)
Return the name of the binary sensor.
Return the name of the binary sensor.
def name(self) -> str: """Return the name of the binary sensor.""" return self.dev.label
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "dev", ".", "label" ]
[ 29, 4 ]
[ 31, 29 ]
python
en
['en', 'mi', 'en']
True
HassAqualinkBinarySensor.is_on
(self)
Return whether the binary sensor is on or not.
Return whether the binary sensor is on or not.
def is_on(self) -> bool: """Return whether the binary sensor is on or not.""" return self.dev.is_on
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "dev", ".", "is_on" ]
[ 34, 4 ]
[ 36, 29 ]
python
en
['en', 'en', 'en']
True
HassAqualinkBinarySensor.device_class
(self)
Return the class of the binary sensor.
Return the class of the binary sensor.
def device_class(self) -> str: """Return the class of the binary sensor.""" if self.name == "Freeze Protection": return DEVICE_CLASS_COLD return None
[ "def", "device_class", "(", "self", ")", "->", "str", ":", "if", "self", ".", "name", "==", "\"Freeze Protection\"", ":", "return", "DEVICE_CLASS_COLD", "return", "None" ]
[ 39, 4 ]
[ 43, 19 ]
python
en
['en', 'tg', 'en']
True
test_cover
(hass, cover_data, sent_messages, cover_msg)
Test setting up config entry.
Test setting up config entry.
async def test_cover(hass, cover_data, sent_messages, cover_msg): """Test setting up config entry.""" receive_message = await setup_ozw(hass, fixture=cover_data) # Test loaded state = hass.states.get("cover.roller_shutter_3_instance_1_level") assert state is not None assert state.state == "closed" assert state.attributes[ATTR_CURRENT_POSITION] == 0 # Test opening await hass.services.async_call( "cover", "open_cover", {"entity_id": "cover.roller_shutter_3_instance_1_level"}, blocking=True, ) assert len(sent_messages) == 1 msg = sent_messages[0] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 99, "ValueIDKey": 625573905} # Feedback on state cover_msg.decode() cover_msg.payload["Value"] = 99 cover_msg.encode() receive_message(cover_msg) await hass.async_block_till_done() state = hass.states.get("cover.roller_shutter_3_instance_1_level") assert state is not None assert state.state == "open" assert state.attributes[ATTR_CURRENT_POSITION] == 100 # Test closing await hass.services.async_call( "cover", "close_cover", {"entity_id": "cover.roller_shutter_3_instance_1_level"}, blocking=True, ) assert len(sent_messages) == 2 msg = sent_messages[1] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 0, "ValueIDKey": 625573905} # Test setting position await hass.services.async_call( "cover", "set_cover_position", {"entity_id": "cover.roller_shutter_3_instance_1_level", "position": 50}, blocking=True, ) assert len(sent_messages) == 3 msg = sent_messages[2] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 50, "ValueIDKey": 625573905} # Test converting position to zwave range for position > 0 await hass.services.async_call( "cover", "set_cover_position", {"entity_id": "cover.roller_shutter_3_instance_1_level", "position": 100}, blocking=True, ) assert len(sent_messages) == 4 msg = sent_messages[3] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 99, "ValueIDKey": 625573905} # Test converting position to zwave range for position = 0 await hass.services.async_call( "cover", "set_cover_position", {"entity_id": "cover.roller_shutter_3_instance_1_level", "position": 0}, blocking=True, ) assert len(sent_messages) == 5 msg = sent_messages[4] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 0, "ValueIDKey": 625573905}
[ "async", "def", "test_cover", "(", "hass", ",", "cover_data", ",", "sent_messages", ",", "cover_msg", ")", ":", "receive_message", "=", "await", "setup_ozw", "(", "hass", ",", "fixture", "=", "cover_data", ")", "# Test loaded", "state", "=", "hass", ".", "states", ".", "get", "(", "\"cover.roller_shutter_3_instance_1_level\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "==", "\"closed\"", "assert", "state", ".", "attributes", "[", "ATTR_CURRENT_POSITION", "]", "==", "0", "# Test opening", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"open_cover\"", ",", "{", "\"entity_id\"", ":", "\"cover.roller_shutter_3_instance_1_level\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "1", "msg", "=", "sent_messages", "[", "0", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "99", ",", "\"ValueIDKey\"", ":", "625573905", "}", "# Feedback on state", "cover_msg", ".", "decode", "(", ")", "cover_msg", ".", "payload", "[", "\"Value\"", "]", "=", "99", "cover_msg", ".", "encode", "(", ")", "receive_message", "(", "cover_msg", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"cover.roller_shutter_3_instance_1_level\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "==", "\"open\"", "assert", "state", ".", "attributes", "[", "ATTR_CURRENT_POSITION", "]", "==", "100", "# Test closing", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"close_cover\"", ",", "{", "\"entity_id\"", ":", "\"cover.roller_shutter_3_instance_1_level\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "2", "msg", "=", "sent_messages", "[", "1", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "0", ",", "\"ValueIDKey\"", ":", "625573905", "}", "# Test setting position", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"set_cover_position\"", ",", "{", "\"entity_id\"", ":", "\"cover.roller_shutter_3_instance_1_level\"", ",", "\"position\"", ":", "50", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "3", "msg", "=", "sent_messages", "[", "2", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "50", ",", "\"ValueIDKey\"", ":", "625573905", "}", "# Test converting position to zwave range for position > 0", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"set_cover_position\"", ",", "{", "\"entity_id\"", ":", "\"cover.roller_shutter_3_instance_1_level\"", ",", "\"position\"", ":", "100", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "4", "msg", "=", "sent_messages", "[", "3", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "99", ",", "\"ValueIDKey\"", ":", "625573905", "}", "# Test converting position to zwave range for position = 0", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"set_cover_position\"", ",", "{", "\"entity_id\"", ":", "\"cover.roller_shutter_3_instance_1_level\"", ",", "\"position\"", ":", "0", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "5", "msg", "=", "sent_messages", "[", "4", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "0", ",", "\"ValueIDKey\"", ":", "625573905", "}" ]
[ 9, 0 ]
[ 88, 66 ]
python
en
['en', 'en', 'en']
True
test_barrier
(hass, cover_gdo_data, sent_messages, cover_gdo_msg)
Test setting up config entry.
Test setting up config entry.
async def test_barrier(hass, cover_gdo_data, sent_messages, cover_gdo_msg): """Test setting up config entry.""" receive_message = await setup_ozw(hass, fixture=cover_gdo_data) # Test loaded state = hass.states.get("cover.gd00z_4_barrier_state") assert state is not None assert state.state == "closed" # Test opening await hass.services.async_call( "cover", "open_cover", {"entity_id": "cover.gd00z_4_barrier_state"}, blocking=True, ) assert len(sent_messages) == 1 msg = sent_messages[0] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 4, "ValueIDKey": 281475083239444} # Feedback on state cover_gdo_msg.decode() cover_gdo_msg.payload[VALUE_ID][VALUE_SELECTED_ID] = 4 cover_gdo_msg.encode() receive_message(cover_gdo_msg) await hass.async_block_till_done() state = hass.states.get("cover.gd00z_4_barrier_state") assert state is not None assert state.state == "open" # Test closing await hass.services.async_call( "cover", "close_cover", {"entity_id": "cover.gd00z_4_barrier_state"}, blocking=True, ) assert len(sent_messages) == 2 msg = sent_messages[1] assert msg["topic"] == "OpenZWave/1/command/setvalue/" assert msg["payload"] == {"Value": 0, "ValueIDKey": 281475083239444}
[ "async", "def", "test_barrier", "(", "hass", ",", "cover_gdo_data", ",", "sent_messages", ",", "cover_gdo_msg", ")", ":", "receive_message", "=", "await", "setup_ozw", "(", "hass", ",", "fixture", "=", "cover_gdo_data", ")", "# Test loaded", "state", "=", "hass", ".", "states", ".", "get", "(", "\"cover.gd00z_4_barrier_state\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "==", "\"closed\"", "# Test opening", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"open_cover\"", ",", "{", "\"entity_id\"", ":", "\"cover.gd00z_4_barrier_state\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "1", "msg", "=", "sent_messages", "[", "0", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "4", ",", "\"ValueIDKey\"", ":", "281475083239444", "}", "# Feedback on state", "cover_gdo_msg", ".", "decode", "(", ")", "cover_gdo_msg", ".", "payload", "[", "VALUE_ID", "]", "[", "VALUE_SELECTED_ID", "]", "=", "4", "cover_gdo_msg", ".", "encode", "(", ")", "receive_message", "(", "cover_gdo_msg", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"cover.gd00z_4_barrier_state\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "==", "\"open\"", "# Test closing", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"close_cover\"", ",", "{", "\"entity_id\"", ":", "\"cover.gd00z_4_barrier_state\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "sent_messages", ")", "==", "2", "msg", "=", "sent_messages", "[", "1", "]", "assert", "msg", "[", "\"topic\"", "]", "==", "\"OpenZWave/1/command/setvalue/\"", "assert", "msg", "[", "\"payload\"", "]", "==", "{", "\"Value\"", ":", "0", ",", "\"ValueIDKey\"", ":", "281475083239444", "}" ]
[ 91, 0 ]
[ 132, 72 ]
python
en
['en', 'en', 'en']
True
_blink_startup_wrapper
(hass, entry)
Startup wrapper for blink.
Startup wrapper for blink.
def _blink_startup_wrapper(hass, entry): """Startup wrapper for blink.""" blink = Blink() auth_data = deepcopy(dict(entry.data)) blink.auth = Auth(auth_data, no_prompt=True) blink.refresh_rate = entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) if blink.start(): blink.setup_post_verify() elif blink.auth.check_key_required(): _LOGGER.debug("Attempting a reauth flow") _reauth_flow_wrapper(hass, auth_data) return blink
[ "def", "_blink_startup_wrapper", "(", "hass", ",", "entry", ")", ":", "blink", "=", "Blink", "(", ")", "auth_data", "=", "deepcopy", "(", "dict", "(", "entry", ".", "data", ")", ")", "blink", ".", "auth", "=", "Auth", "(", "auth_data", ",", "no_prompt", "=", "True", ")", "blink", ".", "refresh_rate", "=", "entry", ".", "options", ".", "get", "(", "CONF_SCAN_INTERVAL", ",", "DEFAULT_SCAN_INTERVAL", ")", "if", "blink", ".", "start", "(", ")", ":", "blink", ".", "setup_post_verify", "(", ")", "elif", "blink", ".", "auth", ".", "check_key_required", "(", ")", ":", "_LOGGER", ".", "debug", "(", "\"Attempting a reauth flow\"", ")", "_reauth_flow_wrapper", "(", "hass", ",", "auth_data", ")", "return", "blink" ]
[ 31, 0 ]
[ 44, 16 ]
python
da
['nb', 'da', 'en']
False
_reauth_flow_wrapper
(hass, data)
Reauth flow wrapper.
Reauth flow wrapper.
def _reauth_flow_wrapper(hass, data): """Reauth flow wrapper.""" hass.add_job( hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth"}, data=data ) ) persistent_notification.async_create( hass, "Blink configuration migrated to a new version. Please go to the integrations page to re-configure (such as sending a new 2FA key).", "Blink Migration", )
[ "def", "_reauth_flow_wrapper", "(", "hass", ",", "data", ")", ":", "hass", ".", "add_job", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "\"reauth\"", "}", ",", "data", "=", "data", ")", ")", "persistent_notification", ".", "async_create", "(", "hass", ",", "\"Blink configuration migrated to a new version. Please go to the integrations page to re-configure (such as sending a new 2FA key).\"", ",", "\"Blink Migration\"", ",", ")" ]
[ 47, 0 ]
[ 58, 5 ]
python
en
['en', 'fr', 'en']
True
async_setup
(hass, config)
Set up a Blink component.
Set up a Blink component.
async def async_setup(hass, config): """Set up a Blink component.""" hass.data[DOMAIN] = {} return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "return", "True" ]
[ 61, 0 ]
[ 64, 15 ]
python
en
['en', 'da', 'en']
True
async_migrate_entry
(hass, entry)
Handle migration of a previous version config entry.
Handle migration of a previous version config entry.
async def async_migrate_entry(hass, entry): """Handle migration of a previous version config entry.""" data = {**entry.data} if entry.version == 1: data.pop("login_response", None) await hass.async_add_executor_job(_reauth_flow_wrapper, hass, data) return False return True
[ "async", "def", "async_migrate_entry", "(", "hass", ",", "entry", ")", ":", "data", "=", "{", "*", "*", "entry", ".", "data", "}", "if", "entry", ".", "version", "==", "1", ":", "data", ".", "pop", "(", "\"login_response\"", ",", "None", ")", "await", "hass", ".", "async_add_executor_job", "(", "_reauth_flow_wrapper", ",", "hass", ",", "data", ")", "return", "False", "return", "True" ]
[ 67, 0 ]
[ 74, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry)
Set up Blink via config entry.
Set up Blink via config entry.
async def async_setup_entry(hass, entry): """Set up Blink via config entry.""" _async_import_options_from_data_if_missing(hass, entry) hass.data[DOMAIN][entry.entry_id] = await hass.async_add_executor_job( _blink_startup_wrapper, hass, entry ) if not hass.data[DOMAIN][entry.entry_id].available: raise ConfigEntryNotReady for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) def blink_refresh(event_time=None): """Call blink to refresh info.""" hass.data[DOMAIN][entry.entry_id].refresh(force_cache=True) async def async_save_video(call): """Call save video service handler.""" await async_handle_save_video_service(hass, entry, call) def send_pin(call): """Call blink to send new pin.""" pin = call.data[CONF_PIN] hass.data[DOMAIN][entry.entry_id].auth.send_auth_key( hass.data[DOMAIN][entry.entry_id], pin, ) hass.services.async_register(DOMAIN, SERVICE_REFRESH, blink_refresh) hass.services.async_register( DOMAIN, SERVICE_SAVE_VIDEO, async_save_video, schema=SERVICE_SAVE_VIDEO_SCHEMA ) hass.services.async_register( DOMAIN, SERVICE_SEND_PIN, send_pin, schema=SERVICE_SEND_PIN_SCHEMA ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "_async_import_options_from_data_if_missing", "(", "hass", ",", "entry", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "=", "await", "hass", ".", "async_add_executor_job", "(", "_blink_startup_wrapper", ",", "hass", ",", "entry", ")", "if", "not", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", ".", "available", ":", "raise", "ConfigEntryNotReady", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "def", "blink_refresh", "(", "event_time", "=", "None", ")", ":", "\"\"\"Call blink to refresh info.\"\"\"", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", ".", "refresh", "(", "force_cache", "=", "True", ")", "async", "def", "async_save_video", "(", "call", ")", ":", "\"\"\"Call save video service handler.\"\"\"", "await", "async_handle_save_video_service", "(", "hass", ",", "entry", ",", "call", ")", "def", "send_pin", "(", "call", ")", ":", "\"\"\"Call blink to send new pin.\"\"\"", "pin", "=", "call", ".", "data", "[", "CONF_PIN", "]", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", ".", "auth", ".", "send_auth_key", "(", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", ",", "pin", ",", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_REFRESH", ",", "blink_refresh", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_SAVE_VIDEO", ",", "async_save_video", ",", "schema", "=", "SERVICE_SAVE_VIDEO_SCHEMA", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_SEND_PIN", ",", "send_pin", ",", "schema", "=", "SERVICE_SEND_PIN_SCHEMA", ")", "return", "True" ]
[ 77, 0 ]
[ 117, 15 ]
python
en
['en', 'da', 'en']
True
async_unload_entry
(hass, entry)
Unload Blink entry.
Unload Blink entry.
async def async_unload_entry(hass, entry): """Unload Blink entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if not unload_ok: return False hass.data[DOMAIN].pop(entry.entry_id) if len(hass.data[DOMAIN]) != 0: return True hass.services.async_remove(DOMAIN, SERVICE_REFRESH) hass.services.async_remove(DOMAIN, SERVICE_SAVE_VIDEO_SCHEMA) hass.services.async_remove(DOMAIN, SERVICE_SEND_PIN) return True
[ "async", "def", "async_unload_entry", "(", "hass", ",", "entry", ")", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "component", ")", "for", "component", "in", "PLATFORMS", "]", ")", ")", "if", "not", "unload_ok", ":", "return", "False", "hass", ".", "data", "[", "DOMAIN", "]", ".", "pop", "(", "entry", ".", "entry_id", ")", "if", "len", "(", "hass", ".", "data", "[", "DOMAIN", "]", ")", "!=", "0", ":", "return", "True", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "SERVICE_REFRESH", ")", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "SERVICE_SAVE_VIDEO_SCHEMA", ")", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "SERVICE_SEND_PIN", ")", "return", "True" ]
[ 130, 0 ]
[ 153, 15 ]
python
da
['eu', 'da', 'en']
False
async_handle_save_video_service
(hass, entry, call)
Handle save video service calls.
Handle save video service calls.
async def async_handle_save_video_service(hass, entry, call): """Handle save video service calls.""" camera_name = call.data[CONF_NAME] video_path = call.data[CONF_FILENAME] if not hass.config.is_allowed_path(video_path): _LOGGER.error("Can't write %s, no access to path!", video_path) return def _write_video(camera_name, video_path): """Call video write.""" all_cameras = hass.data[DOMAIN][entry.entry_id].cameras if camera_name in all_cameras: all_cameras[camera_name].video_to_file(video_path) try: await hass.async_add_executor_job(_write_video, camera_name, video_path) except OSError as err: _LOGGER.error("Can't write image to file: %s", err)
[ "async", "def", "async_handle_save_video_service", "(", "hass", ",", "entry", ",", "call", ")", ":", "camera_name", "=", "call", ".", "data", "[", "CONF_NAME", "]", "video_path", "=", "call", ".", "data", "[", "CONF_FILENAME", "]", "if", "not", "hass", ".", "config", ".", "is_allowed_path", "(", "video_path", ")", ":", "_LOGGER", ".", "error", "(", "\"Can't write %s, no access to path!\"", ",", "video_path", ")", "return", "def", "_write_video", "(", "camera_name", ",", "video_path", ")", ":", "\"\"\"Call video write.\"\"\"", "all_cameras", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", ".", "cameras", "if", "camera_name", "in", "all_cameras", ":", "all_cameras", "[", "camera_name", "]", ".", "video_to_file", "(", "video_path", ")", "try", ":", "await", "hass", ".", "async_add_executor_job", "(", "_write_video", ",", "camera_name", ",", "video_path", ")", "except", "OSError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Can't write image to file: %s\"", ",", "err", ")" ]
[ 156, 0 ]
[ 173, 59 ]
python
en
['en', 'en', 'en']
True
async_register_built_in_panel
( hass, component_name, sidebar_title=None, sidebar_icon=None, frontend_url_path=None, config=None, require_admin=False, *, update=False, )
Register a built-in panel.
Register a built-in panel.
def async_register_built_in_panel( hass, component_name, sidebar_title=None, sidebar_icon=None, frontend_url_path=None, config=None, require_admin=False, *, update=False, ): """Register a built-in panel.""" panel = Panel( component_name, sidebar_title, sidebar_icon, frontend_url_path, config, require_admin, ) panels = hass.data.setdefault(DATA_PANELS, {}) if not update and panel.frontend_url_path in panels: raise ValueError(f"Overwriting panel {panel.frontend_url_path}") panels[panel.frontend_url_path] = panel hass.bus.async_fire(EVENT_PANELS_UPDATED)
[ "def", "async_register_built_in_panel", "(", "hass", ",", "component_name", ",", "sidebar_title", "=", "None", ",", "sidebar_icon", "=", "None", ",", "frontend_url_path", "=", "None", ",", "config", "=", "None", ",", "require_admin", "=", "False", ",", "*", ",", "update", "=", "False", ",", ")", ":", "panel", "=", "Panel", "(", "component_name", ",", "sidebar_title", ",", "sidebar_icon", ",", "frontend_url_path", ",", "config", ",", "require_admin", ",", ")", "panels", "=", "hass", ".", "data", ".", "setdefault", "(", "DATA_PANELS", ",", "{", "}", ")", "if", "not", "update", "and", "panel", ".", "frontend_url_path", "in", "panels", ":", "raise", "ValueError", "(", "f\"Overwriting panel {panel.frontend_url_path}\"", ")", "panels", "[", "panel", ".", "frontend_url_path", "]", "=", "panel", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_PANELS_UPDATED", ")" ]
[ 171, 0 ]
[ 199, 45 ]
python
en
['en', 'en', 'en']
True
async_remove_panel
(hass, frontend_url_path)
Remove a built-in panel.
Remove a built-in panel.
def async_remove_panel(hass, frontend_url_path): """Remove a built-in panel.""" panel = hass.data.get(DATA_PANELS, {}).pop(frontend_url_path, None) if panel is None: _LOGGER.warning("Removing unknown panel %s", frontend_url_path) hass.bus.async_fire(EVENT_PANELS_UPDATED)
[ "def", "async_remove_panel", "(", "hass", ",", "frontend_url_path", ")", ":", "panel", "=", "hass", ".", "data", ".", "get", "(", "DATA_PANELS", ",", "{", "}", ")", ".", "pop", "(", "frontend_url_path", ",", "None", ")", "if", "panel", "is", "None", ":", "_LOGGER", ".", "warning", "(", "\"Removing unknown panel %s\"", ",", "frontend_url_path", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_PANELS_UPDATED", ")" ]
[ 204, 0 ]
[ 211, 45 ]
python
en
['en', 'en', 'en']
True
add_extra_js_url
(hass, url, es5=False)
Register extra js or module url to load.
Register extra js or module url to load.
def add_extra_js_url(hass, url, es5=False): """Register extra js or module url to load.""" key = DATA_EXTRA_JS_URL_ES5 if es5 else DATA_EXTRA_MODULE_URL url_set = hass.data.get(key) if url_set is None: url_set = hass.data[key] = set() url_set.add(url)
[ "def", "add_extra_js_url", "(", "hass", ",", "url", ",", "es5", "=", "False", ")", ":", "key", "=", "DATA_EXTRA_JS_URL_ES5", "if", "es5", "else", "DATA_EXTRA_MODULE_URL", "url_set", "=", "hass", ".", "data", ".", "get", "(", "key", ")", "if", "url_set", "is", "None", ":", "url_set", "=", "hass", ".", "data", "[", "key", "]", "=", "set", "(", ")", "url_set", ".", "add", "(", "url", ")" ]
[ 214, 0 ]
[ 220, 20 ]
python
en
['en', 'en', 'en']
True
add_manifest_json_key
(key, val)
Add a keyval to the manifest.json.
Add a keyval to the manifest.json.
def add_manifest_json_key(key, val): """Add a keyval to the manifest.json.""" MANIFEST_JSON[key] = val
[ "def", "add_manifest_json_key", "(", "key", ",", "val", ")", ":", "MANIFEST_JSON", "[", "key", "]", "=", "val" ]
[ 223, 0 ]
[ 225, 28 ]
python
en
['en', 'en', 'en']
True
_frontend_root
(dev_repo_path)
Return root path to the frontend files.
Return root path to the frontend files.
def _frontend_root(dev_repo_path): """Return root path to the frontend files.""" if dev_repo_path is not None: return pathlib.Path(dev_repo_path) / "hass_frontend" # Keep import here so that we can import frontend without installing reqs # pylint: disable=import-outside-toplevel import hass_frontend return hass_frontend.where()
[ "def", "_frontend_root", "(", "dev_repo_path", ")", ":", "if", "dev_repo_path", "is", "not", "None", ":", "return", "pathlib", ".", "Path", "(", "dev_repo_path", ")", "/", "\"hass_frontend\"", "# Keep import here so that we can import frontend without installing reqs", "# pylint: disable=import-outside-toplevel", "import", "hass_frontend", "return", "hass_frontend", ".", "where", "(", ")" ]
[ 228, 0 ]
[ 236, 32 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the serving of the frontend.
Set up the serving of the frontend.
async def async_setup(hass, config): """Set up the serving of the frontend.""" await async_setup_frontend_storage(hass) hass.components.websocket_api.async_register_command(websocket_get_panels) hass.components.websocket_api.async_register_command(websocket_get_themes) hass.components.websocket_api.async_register_command(websocket_get_translations) hass.components.websocket_api.async_register_command(websocket_get_version) hass.http.register_view(ManifestJSONView) conf = config.get(DOMAIN, {}) for key in (CONF_EXTRA_HTML_URL, CONF_EXTRA_HTML_URL_ES5, CONF_JS_VERSION): if key in conf: _LOGGER.error( "Please remove %s from your frontend config. It is no longer supported", key, ) repo_path = conf.get(CONF_FRONTEND_REPO) is_dev = repo_path is not None root_path = _frontend_root(repo_path) for path, should_cache in ( ("service_worker.js", False), ("robots.txt", False), ("onboarding.html", True), ("static", True), ("frontend_latest", True), ("frontend_es5", True), ): hass.http.register_static_path(f"/{path}", str(root_path / path), should_cache) hass.http.register_static_path( "/auth/authorize", str(root_path / "authorize.html"), False ) # https://wicg.github.io/change-password-url/ hass.http.register_redirect( "/.well-known/change-password", "/profile", redirect_exc=web.HTTPFound ) local = hass.config.path("www") if os.path.isdir(local): hass.http.register_static_path("/local", local, not is_dev) hass.http.app.router.register_resource(IndexView(repo_path, hass)) async_register_built_in_panel(hass, "profile") # To smooth transition to new urls, add redirects to new urls of dev tools # Added June 27, 2019. Can be removed in 2021. for panel in ("event", "service", "state", "template"): hass.http.register_redirect(f"/dev-{panel}", f"/developer-tools/{panel}") for panel in ("logs", "info", "mqtt"): # Can be removed in 2021. hass.http.register_redirect(f"/dev-{panel}", f"/config/{panel}") # Added June 20 2020. Can be removed in 2022. hass.http.register_redirect(f"/developer-tools/{panel}", f"/config/{panel}") async_register_built_in_panel( hass, "developer-tools", require_admin=True, sidebar_title="developer_tools", sidebar_icon="hass:hammer", ) if DATA_EXTRA_MODULE_URL not in hass.data: hass.data[DATA_EXTRA_MODULE_URL] = set() for url in conf.get(CONF_EXTRA_MODULE_URL, []): add_extra_js_url(hass, url) if DATA_EXTRA_JS_URL_ES5 not in hass.data: hass.data[DATA_EXTRA_JS_URL_ES5] = set() for url in conf.get(CONF_EXTRA_JS_URL_ES5, []): add_extra_js_url(hass, url, True) await _async_setup_themes(hass, conf.get(CONF_THEMES)) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "await", "async_setup_frontend_storage", "(", "hass", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_get_panels", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_get_themes", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_get_translations", ")", "hass", ".", "components", ".", "websocket_api", ".", "async_register_command", "(", "websocket_get_version", ")", "hass", ".", "http", ".", "register_view", "(", "ManifestJSONView", ")", "conf", "=", "config", ".", "get", "(", "DOMAIN", ",", "{", "}", ")", "for", "key", "in", "(", "CONF_EXTRA_HTML_URL", ",", "CONF_EXTRA_HTML_URL_ES5", ",", "CONF_JS_VERSION", ")", ":", "if", "key", "in", "conf", ":", "_LOGGER", ".", "error", "(", "\"Please remove %s from your frontend config. It is no longer supported\"", ",", "key", ",", ")", "repo_path", "=", "conf", ".", "get", "(", "CONF_FRONTEND_REPO", ")", "is_dev", "=", "repo_path", "is", "not", "None", "root_path", "=", "_frontend_root", "(", "repo_path", ")", "for", "path", ",", "should_cache", "in", "(", "(", "\"service_worker.js\"", ",", "False", ")", ",", "(", "\"robots.txt\"", ",", "False", ")", ",", "(", "\"onboarding.html\"", ",", "True", ")", ",", "(", "\"static\"", ",", "True", ")", ",", "(", "\"frontend_latest\"", ",", "True", ")", ",", "(", "\"frontend_es5\"", ",", "True", ")", ",", ")", ":", "hass", ".", "http", ".", "register_static_path", "(", "f\"/{path}\"", ",", "str", "(", "root_path", "/", "path", ")", ",", "should_cache", ")", "hass", ".", "http", ".", "register_static_path", "(", "\"/auth/authorize\"", ",", "str", "(", "root_path", "/", "\"authorize.html\"", ")", ",", "False", ")", "# https://wicg.github.io/change-password-url/", "hass", ".", "http", ".", "register_redirect", "(", "\"/.well-known/change-password\"", ",", "\"/profile\"", ",", "redirect_exc", "=", "web", ".", "HTTPFound", ")", "local", "=", "hass", ".", "config", ".", "path", "(", "\"www\"", ")", "if", "os", ".", "path", ".", "isdir", "(", "local", ")", ":", "hass", ".", "http", ".", "register_static_path", "(", "\"/local\"", ",", "local", ",", "not", "is_dev", ")", "hass", ".", "http", ".", "app", ".", "router", ".", "register_resource", "(", "IndexView", "(", "repo_path", ",", "hass", ")", ")", "async_register_built_in_panel", "(", "hass", ",", "\"profile\"", ")", "# To smooth transition to new urls, add redirects to new urls of dev tools", "# Added June 27, 2019. Can be removed in 2021.", "for", "panel", "in", "(", "\"event\"", ",", "\"service\"", ",", "\"state\"", ",", "\"template\"", ")", ":", "hass", ".", "http", ".", "register_redirect", "(", "f\"/dev-{panel}\"", ",", "f\"/developer-tools/{panel}\"", ")", "for", "panel", "in", "(", "\"logs\"", ",", "\"info\"", ",", "\"mqtt\"", ")", ":", "# Can be removed in 2021.", "hass", ".", "http", ".", "register_redirect", "(", "f\"/dev-{panel}\"", ",", "f\"/config/{panel}\"", ")", "# Added June 20 2020. Can be removed in 2022.", "hass", ".", "http", ".", "register_redirect", "(", "f\"/developer-tools/{panel}\"", ",", "f\"/config/{panel}\"", ")", "async_register_built_in_panel", "(", "hass", ",", "\"developer-tools\"", ",", "require_admin", "=", "True", ",", "sidebar_title", "=", "\"developer_tools\"", ",", "sidebar_icon", "=", "\"hass:hammer\"", ",", ")", "if", "DATA_EXTRA_MODULE_URL", "not", "in", "hass", ".", "data", ":", "hass", ".", "data", "[", "DATA_EXTRA_MODULE_URL", "]", "=", "set", "(", ")", "for", "url", "in", "conf", ".", "get", "(", "CONF_EXTRA_MODULE_URL", ",", "[", "]", ")", ":", "add_extra_js_url", "(", "hass", ",", "url", ")", "if", "DATA_EXTRA_JS_URL_ES5", "not", "in", "hass", ".", "data", ":", "hass", ".", "data", "[", "DATA_EXTRA_JS_URL_ES5", "]", "=", "set", "(", ")", "for", "url", "in", "conf", ".", "get", "(", "CONF_EXTRA_JS_URL_ES5", ",", "[", "]", ")", ":", "add_extra_js_url", "(", "hass", ",", "url", ",", "True", ")", "await", "_async_setup_themes", "(", "hass", ",", "conf", ".", "get", "(", "CONF_THEMES", ")", ")", "return", "True" ]
[ 239, 0 ]
[ 319, 15 ]
python
en
['en', 'en', 'en']
True
_async_setup_themes
(hass, themes)
Set up themes data and services.
Set up themes data and services.
async def _async_setup_themes(hass, themes): """Set up themes data and services.""" hass.data[DATA_THEMES] = themes or {} store = hass.data[DATA_THEMES_STORE] = hass.helpers.storage.Store( THEMES_STORAGE_VERSION, THEMES_STORAGE_KEY ) theme_data = await store.async_load() or {} theme_name = theme_data.get(DATA_DEFAULT_THEME, DEFAULT_THEME) dark_theme_name = theme_data.get(DATA_DEFAULT_DARK_THEME) if theme_name == DEFAULT_THEME or theme_name in hass.data[DATA_THEMES]: hass.data[DATA_DEFAULT_THEME] = theme_name else: hass.data[DATA_DEFAULT_THEME] = DEFAULT_THEME if dark_theme_name == DEFAULT_THEME or dark_theme_name in hass.data[DATA_THEMES]: hass.data[DATA_DEFAULT_DARK_THEME] = dark_theme_name @callback def update_theme_and_fire_event(): """Update theme_color in manifest.""" name = hass.data[DATA_DEFAULT_THEME] themes = hass.data[DATA_THEMES] MANIFEST_JSON["theme_color"] = DEFAULT_THEME_COLOR if name != DEFAULT_THEME: MANIFEST_JSON["theme_color"] = themes[name].get( "app-header-background-color", themes[name].get(PRIMARY_COLOR, DEFAULT_THEME_COLOR), ) hass.bus.async_fire(EVENT_THEMES_UPDATED) @callback def set_theme(call): """Set backend-preferred theme.""" name = call.data[CONF_NAME] mode = call.data.get("mode", "light") if ( name not in (DEFAULT_THEME, VALUE_NO_THEME) and name not in hass.data[DATA_THEMES] ): _LOGGER.warning("Theme %s not found", name) return light_mode = mode == "light" theme_key = DATA_DEFAULT_THEME if light_mode else DATA_DEFAULT_DARK_THEME if name == VALUE_NO_THEME: to_set = DEFAULT_THEME if light_mode else None else: _LOGGER.info("Theme %s set as default %s theme", name, mode) to_set = name hass.data[theme_key] = to_set store.async_delay_save( lambda: { DATA_DEFAULT_THEME: hass.data[DATA_DEFAULT_THEME], DATA_DEFAULT_DARK_THEME: hass.data.get(DATA_DEFAULT_DARK_THEME), }, THEMES_SAVE_DELAY, ) update_theme_and_fire_event() async def reload_themes(_): """Reload themes.""" config = await async_hass_config_yaml(hass) new_themes = config[DOMAIN].get(CONF_THEMES, {}) hass.data[DATA_THEMES] = new_themes if hass.data[DATA_DEFAULT_THEME] not in new_themes: hass.data[DATA_DEFAULT_THEME] = DEFAULT_THEME if ( hass.data.get(DATA_DEFAULT_DARK_THEME) and hass.data.get(DATA_DEFAULT_DARK_THEME) not in new_themes ): hass.data[DATA_DEFAULT_DARK_THEME] = None update_theme_and_fire_event() service.async_register_admin_service( hass, DOMAIN, SERVICE_SET_THEME, set_theme, vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_MODE): vol.Any("dark", "light"), } ), ) service.async_register_admin_service( hass, DOMAIN, SERVICE_RELOAD_THEMES, reload_themes )
[ "async", "def", "_async_setup_themes", "(", "hass", ",", "themes", ")", ":", "hass", ".", "data", "[", "DATA_THEMES", "]", "=", "themes", "or", "{", "}", "store", "=", "hass", ".", "data", "[", "DATA_THEMES_STORE", "]", "=", "hass", ".", "helpers", ".", "storage", ".", "Store", "(", "THEMES_STORAGE_VERSION", ",", "THEMES_STORAGE_KEY", ")", "theme_data", "=", "await", "store", ".", "async_load", "(", ")", "or", "{", "}", "theme_name", "=", "theme_data", ".", "get", "(", "DATA_DEFAULT_THEME", ",", "DEFAULT_THEME", ")", "dark_theme_name", "=", "theme_data", ".", "get", "(", "DATA_DEFAULT_DARK_THEME", ")", "if", "theme_name", "==", "DEFAULT_THEME", "or", "theme_name", "in", "hass", ".", "data", "[", "DATA_THEMES", "]", ":", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", "=", "theme_name", "else", ":", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", "=", "DEFAULT_THEME", "if", "dark_theme_name", "==", "DEFAULT_THEME", "or", "dark_theme_name", "in", "hass", ".", "data", "[", "DATA_THEMES", "]", ":", "hass", ".", "data", "[", "DATA_DEFAULT_DARK_THEME", "]", "=", "dark_theme_name", "@", "callback", "def", "update_theme_and_fire_event", "(", ")", ":", "\"\"\"Update theme_color in manifest.\"\"\"", "name", "=", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", "themes", "=", "hass", ".", "data", "[", "DATA_THEMES", "]", "MANIFEST_JSON", "[", "\"theme_color\"", "]", "=", "DEFAULT_THEME_COLOR", "if", "name", "!=", "DEFAULT_THEME", ":", "MANIFEST_JSON", "[", "\"theme_color\"", "]", "=", "themes", "[", "name", "]", ".", "get", "(", "\"app-header-background-color\"", ",", "themes", "[", "name", "]", ".", "get", "(", "PRIMARY_COLOR", ",", "DEFAULT_THEME_COLOR", ")", ",", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_THEMES_UPDATED", ")", "@", "callback", "def", "set_theme", "(", "call", ")", ":", "\"\"\"Set backend-preferred theme.\"\"\"", "name", "=", "call", ".", "data", "[", "CONF_NAME", "]", "mode", "=", "call", ".", "data", ".", "get", "(", "\"mode\"", ",", "\"light\"", ")", "if", "(", "name", "not", "in", "(", "DEFAULT_THEME", ",", "VALUE_NO_THEME", ")", "and", "name", "not", "in", "hass", ".", "data", "[", "DATA_THEMES", "]", ")", ":", "_LOGGER", ".", "warning", "(", "\"Theme %s not found\"", ",", "name", ")", "return", "light_mode", "=", "mode", "==", "\"light\"", "theme_key", "=", "DATA_DEFAULT_THEME", "if", "light_mode", "else", "DATA_DEFAULT_DARK_THEME", "if", "name", "==", "VALUE_NO_THEME", ":", "to_set", "=", "DEFAULT_THEME", "if", "light_mode", "else", "None", "else", ":", "_LOGGER", ".", "info", "(", "\"Theme %s set as default %s theme\"", ",", "name", ",", "mode", ")", "to_set", "=", "name", "hass", ".", "data", "[", "theme_key", "]", "=", "to_set", "store", ".", "async_delay_save", "(", "lambda", ":", "{", "DATA_DEFAULT_THEME", ":", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", ",", "DATA_DEFAULT_DARK_THEME", ":", "hass", ".", "data", ".", "get", "(", "DATA_DEFAULT_DARK_THEME", ")", ",", "}", ",", "THEMES_SAVE_DELAY", ",", ")", "update_theme_and_fire_event", "(", ")", "async", "def", "reload_themes", "(", "_", ")", ":", "\"\"\"Reload themes.\"\"\"", "config", "=", "await", "async_hass_config_yaml", "(", "hass", ")", "new_themes", "=", "config", "[", "DOMAIN", "]", ".", "get", "(", "CONF_THEMES", ",", "{", "}", ")", "hass", ".", "data", "[", "DATA_THEMES", "]", "=", "new_themes", "if", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", "not", "in", "new_themes", ":", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", "=", "DEFAULT_THEME", "if", "(", "hass", ".", "data", ".", "get", "(", "DATA_DEFAULT_DARK_THEME", ")", "and", "hass", ".", "data", ".", "get", "(", "DATA_DEFAULT_DARK_THEME", ")", "not", "in", "new_themes", ")", ":", "hass", ".", "data", "[", "DATA_DEFAULT_DARK_THEME", "]", "=", "None", "update_theme_and_fire_event", "(", ")", "service", ".", "async_register_admin_service", "(", "hass", ",", "DOMAIN", ",", "SERVICE_SET_THEME", ",", "set_theme", ",", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_NAME", ")", ":", "cv", ".", "string", ",", "vol", ".", "Optional", "(", "CONF_MODE", ")", ":", "vol", ".", "Any", "(", "\"dark\"", ",", "\"light\"", ")", ",", "}", ")", ",", ")", "service", ".", "async_register_admin_service", "(", "hass", ",", "DOMAIN", ",", "SERVICE_RELOAD_THEMES", ",", "reload_themes", ")" ]
[ 322, 0 ]
[ 417, 5 ]
python
en
['en', 'en', 'en']
True
websocket_get_panels
(hass, connection, msg)
Handle get panels command.
Handle get panels command.
def websocket_get_panels(hass, connection, msg): """Handle get panels command.""" user_is_admin = connection.user.is_admin panels = { panel_key: panel.to_response() for panel_key, panel in connection.hass.data[DATA_PANELS].items() if user_is_admin or not panel.require_admin } connection.send_message(websocket_api.result_message(msg["id"], panels))
[ "def", "websocket_get_panels", "(", "hass", ",", "connection", ",", "msg", ")", ":", "user_is_admin", "=", "connection", ".", "user", ".", "is_admin", "panels", "=", "{", "panel_key", ":", "panel", ".", "to_response", "(", ")", "for", "panel_key", ",", "panel", "in", "connection", ".", "hass", ".", "data", "[", "DATA_PANELS", "]", ".", "items", "(", ")", "if", "user_is_admin", "or", "not", "panel", ".", "require_admin", "}", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "panels", ")", ")" ]
[ 537, 0 ]
[ 546, 76 ]
python
en
['nl', 'en', 'en']
True
websocket_get_themes
(hass, connection, msg)
Handle get themes command.
Handle get themes command.
def websocket_get_themes(hass, connection, msg): """Handle get themes command.""" if hass.config.safe_mode: connection.send_message( websocket_api.result_message( msg["id"], { "themes": { "safe_mode": { "primary-color": "#db4437", "accent-color": "#ffca28", } }, "default_theme": "safe_mode", }, ) ) return connection.send_message( websocket_api.result_message( msg["id"], { "themes": hass.data[DATA_THEMES], "default_theme": hass.data[DATA_DEFAULT_THEME], "default_dark_theme": hass.data.get(DATA_DEFAULT_DARK_THEME), }, ) )
[ "def", "websocket_get_themes", "(", "hass", ",", "connection", ",", "msg", ")", ":", "if", "hass", ".", "config", ".", "safe_mode", ":", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"themes\"", ":", "{", "\"safe_mode\"", ":", "{", "\"primary-color\"", ":", "\"#db4437\"", ",", "\"accent-color\"", ":", "\"#ffca28\"", ",", "}", "}", ",", "\"default_theme\"", ":", "\"safe_mode\"", ",", "}", ",", ")", ")", "return", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"themes\"", ":", "hass", ".", "data", "[", "DATA_THEMES", "]", ",", "\"default_theme\"", ":", "hass", ".", "data", "[", "DATA_DEFAULT_THEME", "]", ",", "\"default_dark_theme\"", ":", "hass", ".", "data", ".", "get", "(", "DATA_DEFAULT_DARK_THEME", ")", ",", "}", ",", ")", ")" ]
[ 551, 0 ]
[ 579, 5 ]
python
en
['en', 'en', 'en']
True
websocket_get_translations
(hass, connection, msg)
Handle get translations command.
Handle get translations command.
async def websocket_get_translations(hass, connection, msg): """Handle get translations command.""" resources = await async_get_translations( hass, msg["language"], msg["category"], msg.get("integration"), msg.get("config_flow"), ) connection.send_message( websocket_api.result_message(msg["id"], {"resources": resources}) )
[ "async", "def", "websocket_get_translations", "(", "hass", ",", "connection", ",", "msg", ")", ":", "resources", "=", "await", "async_get_translations", "(", "hass", ",", "msg", "[", "\"language\"", "]", ",", "msg", "[", "\"category\"", "]", ",", "msg", ".", "get", "(", "\"integration\"", ")", ",", "msg", ".", "get", "(", "\"config_flow\"", ")", ",", ")", "connection", ".", "send_message", "(", "websocket_api", ".", "result_message", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"resources\"", ":", "resources", "}", ")", ")" ]
[ 592, 0 ]
[ 603, 5 ]
python
bg
['fr', 'bg', 'en']
False
websocket_get_version
(hass, connection, msg)
Handle get version command.
Handle get version command.
async def websocket_get_version(hass, connection, msg): """Handle get version command.""" integration = await async_get_integration(hass, "frontend") frontend = None for req in integration.requirements: if req.startswith("home-assistant-frontend=="): frontend = req.split("==", 1)[1] if frontend is None: connection.send_error(msg["id"], "unknown_version", "Version not found") else: connection.send_result(msg["id"], {"version": frontend})
[ "async", "def", "websocket_get_version", "(", "hass", ",", "connection", ",", "msg", ")", ":", "integration", "=", "await", "async_get_integration", "(", "hass", ",", "\"frontend\"", ")", "frontend", "=", "None", "for", "req", "in", "integration", ".", "requirements", ":", "if", "req", ".", "startswith", "(", "\"home-assistant-frontend==\"", ")", ":", "frontend", "=", "req", ".", "split", "(", "\"==\"", ",", "1", ")", "[", "1", "]", "if", "frontend", "is", "None", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"unknown_version\"", ",", "\"Version not found\"", ")", "else", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"version\"", ":", "frontend", "}", ")" ]
[ 608, 0 ]
[ 621, 64 ]
python
en
['nl', 'en', 'en']
True
Panel.__init__
( self, component_name, sidebar_title, sidebar_icon, frontend_url_path, config, require_admin, )
Initialize a built-in panel.
Initialize a built-in panel.
def __init__( self, component_name, sidebar_title, sidebar_icon, frontend_url_path, config, require_admin, ): """Initialize a built-in panel.""" self.component_name = component_name self.sidebar_title = sidebar_title self.sidebar_icon = sidebar_icon self.frontend_url_path = frontend_url_path or component_name self.config = config self.require_admin = require_admin
[ "def", "__init__", "(", "self", ",", "component_name", ",", "sidebar_title", ",", "sidebar_icon", ",", "frontend_url_path", ",", "config", ",", "require_admin", ",", ")", ":", "self", ".", "component_name", "=", "component_name", "self", ".", "sidebar_title", "=", "sidebar_title", "self", ".", "sidebar_icon", "=", "sidebar_icon", "self", ".", "frontend_url_path", "=", "frontend_url_path", "or", "component_name", "self", ".", "config", "=", "config", "self", ".", "require_admin", "=", "require_admin" ]
[ 139, 4 ]
[ 154, 42 ]
python
en
['en', 'en', 'en']
True
Panel.to_response
(self)
Panel as dictionary.
Panel as dictionary.
def to_response(self): """Panel as dictionary.""" return { "component_name": self.component_name, "icon": self.sidebar_icon, "title": self.sidebar_title, "config": self.config, "url_path": self.frontend_url_path, "require_admin": self.require_admin, }
[ "def", "to_response", "(", "self", ")", ":", "return", "{", "\"component_name\"", ":", "self", ".", "component_name", ",", "\"icon\"", ":", "self", ".", "sidebar_icon", ",", "\"title\"", ":", "self", ".", "sidebar_title", ",", "\"config\"", ":", "self", ".", "config", ",", "\"url_path\"", ":", "self", ".", "frontend_url_path", ",", "\"require_admin\"", ":", "self", ".", "require_admin", ",", "}" ]
[ 157, 4 ]
[ 166, 9 ]
python
en
['es', 'en', 'en']
True
IndexView.__init__
(self, repo_path, hass)
Initialize the frontend view.
Initialize the frontend view.
def __init__(self, repo_path, hass): """Initialize the frontend view.""" super().__init__(name="frontend:index") self.repo_path = repo_path self.hass = hass self._template_cache = None
[ "def", "__init__", "(", "self", ",", "repo_path", ",", "hass", ")", ":", "super", "(", ")", ".", "__init__", "(", "name", "=", "\"frontend:index\"", ")", "self", ".", "repo_path", "=", "repo_path", "self", ".", "hass", "=", "hass", "self", ".", "_template_cache", "=", "None" ]
[ 423, 4 ]
[ 428, 35 ]
python
en
['en', 'en', 'en']
True
IndexView.canonical
(self)
Return resource's canonical path.
Return resource's canonical path.
def canonical(self) -> str: """Return resource's canonical path.""" return "/"
[ "def", "canonical", "(", "self", ")", "->", "str", ":", "return", "\"/\"" ]
[ 431, 4 ]
[ 433, 18 ]
python
en
['en', 'en', 'en']
True
IndexView._route
(self)
Return the index route.
Return the index route.
def _route(self): """Return the index route.""" return web_urldispatcher.ResourceRoute("GET", self.get, self)
[ "def", "_route", "(", "self", ")", ":", "return", "web_urldispatcher", ".", "ResourceRoute", "(", "\"GET\"", ",", "self", ".", "get", ",", "self", ")" ]
[ 436, 4 ]
[ 438, 69 ]
python
en
['en', 'la', 'en']
True
IndexView.url_for
(self, **kwargs: str)
Construct url for resource with additional params.
Construct url for resource with additional params.
def url_for(self, **kwargs: str) -> URL: """Construct url for resource with additional params.""" return URL("/")
[ "def", "url_for", "(", "self", ",", "*", "*", "kwargs", ":", "str", ")", "->", "URL", ":", "return", "URL", "(", "\"/\"", ")" ]
[ 440, 4 ]
[ 442, 23 ]
python
en
['en', 'en', 'en']
True
IndexView.resolve
( self, request: web.Request )
Resolve resource. Return (UrlMappingMatchInfo, allowed_methods) pair.
Resolve resource.
async def resolve( self, request: web.Request ) -> Tuple[Optional[web_urldispatcher.UrlMappingMatchInfo], Set[str]]: """Resolve resource. Return (UrlMappingMatchInfo, allowed_methods) pair. """ if ( request.path != "/" and request.url.parts[1] not in self.hass.data[DATA_PANELS] ): return None, set() if request.method != hdrs.METH_GET: return None, {"GET"} return web_urldispatcher.UrlMappingMatchInfo({}, self._route), {"GET"}
[ "async", "def", "resolve", "(", "self", ",", "request", ":", "web", ".", "Request", ")", "->", "Tuple", "[", "Optional", "[", "web_urldispatcher", ".", "UrlMappingMatchInfo", "]", ",", "Set", "[", "str", "]", "]", ":", "if", "(", "request", ".", "path", "!=", "\"/\"", "and", "request", ".", "url", ".", "parts", "[", "1", "]", "not", "in", "self", ".", "hass", ".", "data", "[", "DATA_PANELS", "]", ")", ":", "return", "None", ",", "set", "(", ")", "if", "request", ".", "method", "!=", "hdrs", ".", "METH_GET", ":", "return", "None", ",", "{", "\"GET\"", "}", "return", "web_urldispatcher", ".", "UrlMappingMatchInfo", "(", "{", "}", ",", "self", ".", "_route", ")", ",", "{", "\"GET\"", "}" ]
[ 444, 4 ]
[ 460, 78 ]
python
de
['et', 'de', 'en']
False
IndexView.add_prefix
(self, prefix: str)
Add a prefix to processed URLs. Required for subapplications support.
Add a prefix to processed URLs.
def add_prefix(self, prefix: str) -> None: """Add a prefix to processed URLs. Required for subapplications support. """
[ "def", "add_prefix", "(", "self", ",", "prefix", ":", "str", ")", "->", "None", ":" ]
[ 462, 4 ]
[ 466, 11 ]
python
en
['en', 'mt', 'en']
True
IndexView.get_info
(self)
Return a dict with additional info useful for introspection.
Return a dict with additional info useful for introspection.
def get_info(self): """Return a dict with additional info useful for introspection.""" return {"panels": list(self.hass.data[DATA_PANELS])}
[ "def", "get_info", "(", "self", ")", ":", "return", "{", "\"panels\"", ":", "list", "(", "self", ".", "hass", ".", "data", "[", "DATA_PANELS", "]", ")", "}" ]
[ 468, 4 ]
[ 470, 60 ]
python
en
['en', 'en', 'en']
True
IndexView.freeze
(self)
Freeze the resource.
Freeze the resource.
def freeze(self) -> None: """Freeze the resource."""
[ "def", "freeze", "(", "self", ")", "->", "None", ":" ]
[ 472, 4 ]
[ 473, 34 ]
python
en
['en', 'en', 'en']
True
IndexView.raw_match
(self, path: str)
Perform a raw match against path.
Perform a raw match against path.
def raw_match(self, path: str) -> bool: """Perform a raw match against path."""
[ "def", "raw_match", "(", "self", ",", "path", ":", "str", ")", "->", "bool", ":" ]
[ 475, 4 ]
[ 476, 47 ]
python
en
['en', 'en', 'en']
True
IndexView.get_template
(self)
Get template.
Get template.
def get_template(self): """Get template.""" tpl = self._template_cache if tpl is None: with open(str(_frontend_root(self.repo_path) / "index.html")) as file: tpl = jinja2.Template(file.read()) # Cache template if not running from repository if self.repo_path is None: self._template_cache = tpl return tpl
[ "def", "get_template", "(", "self", ")", ":", "tpl", "=", "self", ".", "_template_cache", "if", "tpl", "is", "None", ":", "with", "open", "(", "str", "(", "_frontend_root", "(", "self", ".", "repo_path", ")", "/", "\"index.html\"", ")", ")", "as", "file", ":", "tpl", "=", "jinja2", ".", "Template", "(", "file", ".", "read", "(", ")", ")", "# Cache template if not running from repository", "if", "self", ".", "repo_path", "is", "None", ":", "self", ".", "_template_cache", "=", "tpl", "return", "tpl" ]
[ 478, 4 ]
[ 489, 18 ]
python
en
['en', 'nl', 'en']
False
IndexView.get
(self, request: web.Request)
Serve the index page for panel pages.
Serve the index page for panel pages.
async def get(self, request: web.Request) -> web.Response: """Serve the index page for panel pages.""" hass = request.app["hass"] if not hass.components.onboarding.async_is_onboarded(): return web.Response(status=302, headers={"location": "/onboarding.html"}) template = self._template_cache if template is None: template = await hass.async_add_executor_job(self.get_template) return web.Response( text=template.render( theme_color=MANIFEST_JSON["theme_color"], extra_modules=hass.data[DATA_EXTRA_MODULE_URL], extra_js_es5=hass.data[DATA_EXTRA_JS_URL_ES5], ), content_type="text/html", )
[ "async", "def", "get", "(", "self", ",", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "if", "not", "hass", ".", "components", ".", "onboarding", ".", "async_is_onboarded", "(", ")", ":", "return", "web", ".", "Response", "(", "status", "=", "302", ",", "headers", "=", "{", "\"location\"", ":", "\"/onboarding.html\"", "}", ")", "template", "=", "self", ".", "_template_cache", "if", "template", "is", "None", ":", "template", "=", "await", "hass", ".", "async_add_executor_job", "(", "self", ".", "get_template", ")", "return", "web", ".", "Response", "(", "text", "=", "template", ".", "render", "(", "theme_color", "=", "MANIFEST_JSON", "[", "\"theme_color\"", "]", ",", "extra_modules", "=", "hass", ".", "data", "[", "DATA_EXTRA_MODULE_URL", "]", ",", "extra_js_es5", "=", "hass", ".", "data", "[", "DATA_EXTRA_JS_URL_ES5", "]", ",", ")", ",", "content_type", "=", "\"text/html\"", ",", ")" ]
[ 491, 4 ]
[ 510, 9 ]
python
en
['en', 'en', 'en']
True
IndexView.__len__
(self)
Return length of resource.
Return length of resource.
def __len__(self) -> int: """Return length of resource.""" return 1
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "return", "1" ]
[ 512, 4 ]
[ 514, 16 ]
python
en
['en', 'id', 'en']
True
IndexView.__iter__
(self)
Iterate over routes.
Iterate over routes.
def __iter__(self): """Iterate over routes.""" return iter([self._route])
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "[", "self", ".", "_route", "]", ")" ]
[ 516, 4 ]
[ 518, 34 ]
python
en
['en', 'en', 'en']
True
ManifestJSONView.get
(self, request)
Return the manifest.json.
Return the manifest.json.
def get(self, request): # pylint: disable=no-self-use """Return the manifest.json.""" msg = json.dumps(MANIFEST_JSON, sort_keys=True) return web.Response(text=msg, content_type="application/manifest+json")
[ "def", "get", "(", "self", ",", "request", ")", ":", "# pylint: disable=no-self-use", "msg", "=", "json", ".", "dumps", "(", "MANIFEST_JSON", ",", "sort_keys", "=", "True", ")", "return", "web", ".", "Response", "(", "text", "=", "msg", ",", "content_type", "=", "\"application/manifest+json\"", ")" ]
[ 529, 4 ]
[ 532, 79 ]
python
en
['en', 'is', 'en']
True
async_setup
(hass: HomeAssistant, config: dict)
Set up the JuiceNet component.
Set up the JuiceNet component.
async def async_setup(hass: HomeAssistant, config: dict): """Set up the JuiceNet component.""" conf = config.get(DOMAIN) hass.data.setdefault(DOMAIN, {}) if not conf: return True hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=conf ) ) return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", ":", "conf", "=", "config", ".", "get", "(", "DOMAIN", ")", "hass", ".", "data", ".", "setdefault", "(", "DOMAIN", ",", "{", "}", ")", "if", "not", "conf", ":", "return", "True", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "conf", ")", ")", "return", "True" ]
[ 30, 0 ]
[ 43, 15 ]
python
en
['en', 'fr', 'en']
True
async_setup_entry
(hass: HomeAssistant, entry: ConfigEntry)
Set up JuiceNet from a config entry.
Set up JuiceNet from a config entry.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up JuiceNet from a config entry.""" config = entry.data session = async_get_clientsession(hass) access_token = config[CONF_ACCESS_TOKEN] api = Api(access_token, session) juicenet = JuiceNetApi(api) try: await juicenet.setup() except TokenError as error: _LOGGER.error("JuiceNet Error %s", error) return False except aiohttp.ClientError as error: _LOGGER.error("Could not reach the JuiceNet API %s", error) raise ConfigEntryNotReady from error if not juicenet.devices: _LOGGER.error("No JuiceNet devices found for this account") return False _LOGGER.info("%d JuiceNet device(s) found", len(juicenet.devices)) async def async_update_data(): """Update all device states from the JuiceNet API.""" for device in juicenet.devices: await device.update_state(True) return True coordinator = DataUpdateCoordinator( hass, _LOGGER, name="JuiceNet", update_method=async_update_data, update_interval=timedelta(seconds=30), ) hass.data[DOMAIN][entry.entry_id] = { JUICENET_API: juicenet, JUICENET_COORDINATOR: coordinator, } await coordinator.async_refresh() for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "config", "=", "entry", ".", "data", "session", "=", "async_get_clientsession", "(", "hass", ")", "access_token", "=", "config", "[", "CONF_ACCESS_TOKEN", "]", "api", "=", "Api", "(", "access_token", ",", "session", ")", "juicenet", "=", "JuiceNetApi", "(", "api", ")", "try", ":", "await", "juicenet", ".", "setup", "(", ")", "except", "TokenError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"JuiceNet Error %s\"", ",", "error", ")", "return", "False", "except", "aiohttp", ".", "ClientError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Could not reach the JuiceNet API %s\"", ",", "error", ")", "raise", "ConfigEntryNotReady", "from", "error", "if", "not", "juicenet", ".", "devices", ":", "_LOGGER", ".", "error", "(", "\"No JuiceNet devices found for this account\"", ")", "return", "False", "_LOGGER", ".", "info", "(", "\"%d JuiceNet device(s) found\"", ",", "len", "(", "juicenet", ".", "devices", ")", ")", "async", "def", "async_update_data", "(", ")", ":", "\"\"\"Update all device states from the JuiceNet API.\"\"\"", "for", "device", "in", "juicenet", ".", "devices", ":", "await", "device", ".", "update_state", "(", "True", ")", "return", "True", "coordinator", "=", "DataUpdateCoordinator", "(", "hass", ",", "_LOGGER", ",", "name", "=", "\"JuiceNet\"", ",", "update_method", "=", "async_update_data", ",", "update_interval", "=", "timedelta", "(", "seconds", "=", "30", ")", ",", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "=", "{", "JUICENET_API", ":", "juicenet", ",", "JUICENET_COORDINATOR", ":", "coordinator", ",", "}", "await", "coordinator", ".", "async_refresh", "(", ")", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "return", "True" ]
[ 46, 0 ]
[ 98, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass: HomeAssistant, entry: ConfigEntry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "component", ")", "for", "component", "in", "PLATFORMS", "]", ")", ")", "if", "unload_ok", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "pop", "(", "entry", ".", "entry_id", ")", "return", "unload_ok" ]
[ 101, 0 ]
[ 114, 20 ]
python
en
['en', 'es', 'en']
True
test_is_invalid_auth_code
()
Test for invalid auth.
Test for invalid auth.
async def test_is_invalid_auth_code(): """Test for invalid auth.""" assert util.is_invalid_auth_code(HTTP_UNAUTHORIZED) is True assert util.is_invalid_auth_code(HTTP_FORBIDDEN) is True assert util.is_invalid_auth_code(HTTP_NOT_FOUND) is False
[ "async", "def", "test_is_invalid_auth_code", "(", ")", ":", "assert", "util", ".", "is_invalid_auth_code", "(", "HTTP_UNAUTHORIZED", ")", "is", "True", "assert", "util", ".", "is_invalid_auth_code", "(", "HTTP_FORBIDDEN", ")", "is", "True", "assert", "util", ".", "is_invalid_auth_code", "(", "HTTP_NOT_FOUND", ")", "is", "False" ]
[ 7, 0 ]
[ 12, 61 ]
python
en
['en', 'en', 'en']
True
test_percent_conv
()
Test percentage conversion.
Test percentage conversion.
async def test_percent_conv(): """Test percentage conversion.""" assert util.percent_conv(0.12) == 12.0 assert util.percent_conv(0.123) == 12.3
[ "async", "def", "test_percent_conv", "(", ")", ":", "assert", "util", ".", "percent_conv", "(", "0.12", ")", "==", "12.0", "assert", "util", ".", "percent_conv", "(", "0.123", ")", "==", "12.3" ]
[ 15, 0 ]
[ 19, 43 ]
python
en
['en', 'fr', 'en']
True
async_reload
(hass: HomeAssistantType, integration_name: str)
Register notify services for an integration.
Register notify services for an integration.
async def async_reload(hass: HomeAssistantType, integration_name: str) -> None: """Register notify services for an integration.""" if not _async_integration_has_notify_services(hass, integration_name): return tasks = [ notify_service.async_register_services() for notify_service in hass.data[NOTIFY_SERVICES][integration_name] ] await asyncio.gather(*tasks)
[ "async", "def", "async_reload", "(", "hass", ":", "HomeAssistantType", ",", "integration_name", ":", "str", ")", "->", "None", ":", "if", "not", "_async_integration_has_notify_services", "(", "hass", ",", "integration_name", ")", ":", "return", "tasks", "=", "[", "notify_service", ".", "async_register_services", "(", ")", "for", "notify_service", "in", "hass", ".", "data", "[", "NOTIFY_SERVICES", "]", "[", "integration_name", "]", "]", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")" ]
[ 66, 0 ]
[ 76, 32 ]
python
en
['en', 'en', 'en']
True
async_reset_platform
(hass: HomeAssistantType, integration_name: str)
Unregister notify services for an integration.
Unregister notify services for an integration.
async def async_reset_platform(hass: HomeAssistantType, integration_name: str) -> None: """Unregister notify services for an integration.""" if not _async_integration_has_notify_services(hass, integration_name): return tasks = [ notify_service.async_unregister_services() for notify_service in hass.data[NOTIFY_SERVICES][integration_name] ] await asyncio.gather(*tasks) del hass.data[NOTIFY_SERVICES][integration_name]
[ "async", "def", "async_reset_platform", "(", "hass", ":", "HomeAssistantType", ",", "integration_name", ":", "str", ")", "->", "None", ":", "if", "not", "_async_integration_has_notify_services", "(", "hass", ",", "integration_name", ")", ":", "return", "tasks", "=", "[", "notify_service", ".", "async_unregister_services", "(", ")", "for", "notify_service", "in", "hass", ".", "data", "[", "NOTIFY_SERVICES", "]", "[", "integration_name", "]", "]", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")", "del", "hass", ".", "data", "[", "NOTIFY_SERVICES", "]", "[", "integration_name", "]" ]
[ 80, 0 ]
[ 92, 52 ]
python
en
['en', 'en', 'en']
True
_async_integration_has_notify_services
( hass: HomeAssistantType, integration_name: str )
Determine if an integration has notify services registered.
Determine if an integration has notify services registered.
def _async_integration_has_notify_services( hass: HomeAssistantType, integration_name: str ) -> bool: """Determine if an integration has notify services registered.""" if ( NOTIFY_SERVICES not in hass.data or integration_name not in hass.data[NOTIFY_SERVICES] ): return False return True
[ "def", "_async_integration_has_notify_services", "(", "hass", ":", "HomeAssistantType", ",", "integration_name", ":", "str", ")", "->", "bool", ":", "if", "(", "NOTIFY_SERVICES", "not", "in", "hass", ".", "data", "or", "integration_name", "not", "in", "hass", ".", "data", "[", "NOTIFY_SERVICES", "]", ")", ":", "return", "False", "return", "True" ]
[ 95, 0 ]
[ 105, 15 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the notify services.
Set up the notify services.
async def async_setup(hass, config): """Set up the notify services.""" hass.data.setdefault(NOTIFY_SERVICES, {}) async def persistent_notification(service: ServiceCall) -> None: """Send notification via the built-in persistsent_notify integration.""" payload = {} message = service.data[ATTR_MESSAGE] message.hass = hass payload[ATTR_MESSAGE] = message.async_render(parse_result=False) title = service.data.get(ATTR_TITLE) if title: title.hass = hass payload[ATTR_TITLE] = title.async_render(parse_result=False) await hass.services.async_call( pn.DOMAIN, pn.SERVICE_CREATE, payload, blocking=True ) async def async_setup_platform( integration_name, p_config=None, discovery_info=None ): """Set up a notify platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform( hass, config, DOMAIN, integration_name ) if platform is None: _LOGGER.error("Unknown notification service specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, integration_name) notify_service = None try: if hasattr(platform, "async_get_service"): notify_service = await platform.async_get_service( hass, p_config, discovery_info ) elif hasattr(platform, "get_service"): notify_service = await hass.async_add_executor_job( platform.get_service, hass, p_config, discovery_info ) else: raise HomeAssistantError("Invalid notify platform.") if notify_service is None: # Platforms can decide not to create a service based # on discovery data. if discovery_info is None: _LOGGER.error( "Failed to initialize notification service %s", integration_name ) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", integration_name) return if discovery_info is None: discovery_info = {} conf_name = p_config.get(CONF_NAME) or discovery_info.get(CONF_NAME) target_service_name_prefix = conf_name or integration_name service_name = slugify(conf_name or SERVICE_NOTIFY) await notify_service.async_setup(hass, service_name, target_service_name_prefix) await notify_service.async_register_services() hass.data[NOTIFY_SERVICES].setdefault(integration_name, []).append( notify_service ) hass.config.components.add(f"{DOMAIN}.{integration_name}") return True hass.services.async_register( DOMAIN, SERVICE_PERSISTENT_NOTIFICATION, persistent_notification, schema=PERSISTENT_NOTIFICATION_SERVICE_SCHEMA, ) setup_tasks = [ async_setup_platform(integration_name, p_config) for integration_name, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks) async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "hass", ".", "data", ".", "setdefault", "(", "NOTIFY_SERVICES", ",", "{", "}", ")", "async", "def", "persistent_notification", "(", "service", ":", "ServiceCall", ")", "->", "None", ":", "\"\"\"Send notification via the built-in persistsent_notify integration.\"\"\"", "payload", "=", "{", "}", "message", "=", "service", ".", "data", "[", "ATTR_MESSAGE", "]", "message", ".", "hass", "=", "hass", "payload", "[", "ATTR_MESSAGE", "]", "=", "message", ".", "async_render", "(", "parse_result", "=", "False", ")", "title", "=", "service", ".", "data", ".", "get", "(", "ATTR_TITLE", ")", "if", "title", ":", "title", ".", "hass", "=", "hass", "payload", "[", "ATTR_TITLE", "]", "=", "title", ".", "async_render", "(", "parse_result", "=", "False", ")", "await", "hass", ".", "services", ".", "async_call", "(", "pn", ".", "DOMAIN", ",", "pn", ".", "SERVICE_CREATE", ",", "payload", ",", "blocking", "=", "True", ")", "async", "def", "async_setup_platform", "(", "integration_name", ",", "p_config", "=", "None", ",", "discovery_info", "=", "None", ")", ":", "\"\"\"Set up a notify platform.\"\"\"", "if", "p_config", "is", "None", ":", "p_config", "=", "{", "}", "platform", "=", "await", "async_prepare_setup_platform", "(", "hass", ",", "config", ",", "DOMAIN", ",", "integration_name", ")", "if", "platform", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Unknown notification service specified\"", ")", "return", "_LOGGER", ".", "info", "(", "\"Setting up %s.%s\"", ",", "DOMAIN", ",", "integration_name", ")", "notify_service", "=", "None", "try", ":", "if", "hasattr", "(", "platform", ",", "\"async_get_service\"", ")", ":", "notify_service", "=", "await", "platform", ".", "async_get_service", "(", "hass", ",", "p_config", ",", "discovery_info", ")", "elif", "hasattr", "(", "platform", ",", "\"get_service\"", ")", ":", "notify_service", "=", "await", "hass", ".", "async_add_executor_job", "(", "platform", ".", "get_service", ",", "hass", ",", "p_config", ",", "discovery_info", ")", "else", ":", "raise", "HomeAssistantError", "(", "\"Invalid notify platform.\"", ")", "if", "notify_service", "is", "None", ":", "# Platforms can decide not to create a service based", "# on discovery data.", "if", "discovery_info", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Failed to initialize notification service %s\"", ",", "integration_name", ")", "return", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Error setting up platform %s\"", ",", "integration_name", ")", "return", "if", "discovery_info", "is", "None", ":", "discovery_info", "=", "{", "}", "conf_name", "=", "p_config", ".", "get", "(", "CONF_NAME", ")", "or", "discovery_info", ".", "get", "(", "CONF_NAME", ")", "target_service_name_prefix", "=", "conf_name", "or", "integration_name", "service_name", "=", "slugify", "(", "conf_name", "or", "SERVICE_NOTIFY", ")", "await", "notify_service", ".", "async_setup", "(", "hass", ",", "service_name", ",", "target_service_name_prefix", ")", "await", "notify_service", ".", "async_register_services", "(", ")", "hass", ".", "data", "[", "NOTIFY_SERVICES", "]", ".", "setdefault", "(", "integration_name", ",", "[", "]", ")", ".", "append", "(", "notify_service", ")", "hass", ".", "config", ".", "components", ".", "add", "(", "f\"{DOMAIN}.{integration_name}\"", ")", "return", "True", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_PERSISTENT_NOTIFICATION", ",", "persistent_notification", ",", "schema", "=", "PERSISTENT_NOTIFICATION_SERVICE_SCHEMA", ",", ")", "setup_tasks", "=", "[", "async_setup_platform", "(", "integration_name", ",", "p_config", ")", "for", "integration_name", ",", "p_config", "in", "config_per_platform", "(", "config", ",", "DOMAIN", ")", "]", "if", "setup_tasks", ":", "await", "asyncio", ".", "wait", "(", "setup_tasks", ")", "async", "def", "async_platform_discovered", "(", "platform", ",", "info", ")", ":", "\"\"\"Handle for discovered platform.\"\"\"", "await", "async_setup_platform", "(", "platform", ",", "discovery_info", "=", "info", ")", "discovery", ".", "async_listen_platform", "(", "hass", ",", "DOMAIN", ",", "async_platform_discovered", ")", "return", "True" ]
[ 222, 0 ]
[ 322, 15 ]
python
en
['en', 'en', 'en']
True
BaseNotificationService.send_message
(self, message, **kwargs)
Send a message. kwargs can contain ATTR_TITLE to specify a title.
Send a message.
def send_message(self, message, **kwargs): """Send a message. kwargs can contain ATTR_TITLE to specify a title. """ raise NotImplementedError()
[ "def", "send_message", "(", "self", ",", "message", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 113, 4 ]
[ 118, 35 ]
python
en
['en', 'lb', 'en']
True
BaseNotificationService.async_send_message
(self, message: Any, **kwargs: Any)
Send a message. kwargs can contain ATTR_TITLE to specify a title.
Send a message.
async def async_send_message(self, message: Any, **kwargs: Any) -> None: """Send a message. kwargs can contain ATTR_TITLE to specify a title. """ await self.hass.async_add_executor_job(partial(self.send_message, message, **kwargs))
[ "async", "def", "async_send_message", "(", "self", ",", "message", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "partial", "(", "self", ".", "send_message", ",", "message", ",", "*", "*", "kwargs", ")", ")" ]
[ 120, 4 ]
[ 125, 93 ]
python
en
['en', 'lb', 'en']
True
BaseNotificationService._async_notify_message_service
(self, service: ServiceCall)
Handle sending notification message service calls.
Handle sending notification message service calls.
async def _async_notify_message_service(self, service: ServiceCall) -> None: """Handle sending notification message service calls.""" kwargs = {} message = service.data[ATTR_MESSAGE] title = service.data.get(ATTR_TITLE) if title: title.hass = self.hass kwargs[ATTR_TITLE] = title.async_render(parse_result=False) if self._registered_targets.get(service.service) is not None: kwargs[ATTR_TARGET] = [self._registered_targets[service.service]] elif service.data.get(ATTR_TARGET) is not None: kwargs[ATTR_TARGET] = service.data.get(ATTR_TARGET) message.hass = self.hass kwargs[ATTR_MESSAGE] = message.async_render(parse_result=False) kwargs[ATTR_DATA] = service.data.get(ATTR_DATA) await self.async_send_message(**kwargs)
[ "async", "def", "_async_notify_message_service", "(", "self", ",", "service", ":", "ServiceCall", ")", "->", "None", ":", "kwargs", "=", "{", "}", "message", "=", "service", ".", "data", "[", "ATTR_MESSAGE", "]", "title", "=", "service", ".", "data", ".", "get", "(", "ATTR_TITLE", ")", "if", "title", ":", "title", ".", "hass", "=", "self", ".", "hass", "kwargs", "[", "ATTR_TITLE", "]", "=", "title", ".", "async_render", "(", "parse_result", "=", "False", ")", "if", "self", ".", "_registered_targets", ".", "get", "(", "service", ".", "service", ")", "is", "not", "None", ":", "kwargs", "[", "ATTR_TARGET", "]", "=", "[", "self", ".", "_registered_targets", "[", "service", ".", "service", "]", "]", "elif", "service", ".", "data", ".", "get", "(", "ATTR_TARGET", ")", "is", "not", "None", ":", "kwargs", "[", "ATTR_TARGET", "]", "=", "service", ".", "data", ".", "get", "(", "ATTR_TARGET", ")", "message", ".", "hass", "=", "self", ".", "hass", "kwargs", "[", "ATTR_MESSAGE", "]", "=", "message", ".", "async_render", "(", "parse_result", "=", "False", ")", "kwargs", "[", "ATTR_DATA", "]", "=", "service", ".", "data", ".", "get", "(", "ATTR_DATA", ")", "await", "self", ".", "async_send_message", "(", "*", "*", "kwargs", ")" ]
[ 127, 4 ]
[ 146, 47 ]
python
en
['en', 'nl', 'en']
True
BaseNotificationService.async_setup
( self, hass: HomeAssistantType, service_name: str, target_service_name_prefix: str, )
Store the data for the notify service.
Store the data for the notify service.
async def async_setup( self, hass: HomeAssistantType, service_name: str, target_service_name_prefix: str, ) -> None: """Store the data for the notify service.""" # pylint: disable=attribute-defined-outside-init self.hass = hass self._service_name = service_name self._target_service_name_prefix = target_service_name_prefix self._registered_targets: Dict = {}
[ "async", "def", "async_setup", "(", "self", ",", "hass", ":", "HomeAssistantType", ",", "service_name", ":", "str", ",", "target_service_name_prefix", ":", "str", ",", ")", "->", "None", ":", "# pylint: disable=attribute-defined-outside-init", "self", ".", "hass", "=", "hass", "self", ".", "_service_name", "=", "service_name", "self", ".", "_target_service_name_prefix", "=", "target_service_name_prefix", "self", ".", "_registered_targets", ":", "Dict", "=", "{", "}" ]
[ 148, 4 ]
[ 159, 43 ]
python
en
['en', 'en', 'en']
True
BaseNotificationService.async_register_services
(self)
Create or update the notify services.
Create or update the notify services.
async def async_register_services(self) -> None: """Create or update the notify services.""" assert self.hass if hasattr(self, "targets"): stale_targets = set(self._registered_targets) # pylint: disable=no-member for name, target in self.targets.items(): # type: ignore target_name = slugify(f"{self._target_service_name_prefix}_{name}") if target_name in stale_targets: stale_targets.remove(target_name) if target_name in self._registered_targets: continue self._registered_targets[target_name] = target self.hass.services.async_register( DOMAIN, target_name, self._async_notify_message_service, schema=NOTIFY_SERVICE_SCHEMA, ) for stale_target_name in stale_targets: del self._registered_targets[stale_target_name] self.hass.services.async_remove( DOMAIN, stale_target_name, ) if self.hass.services.has_service(DOMAIN, self._service_name): return self.hass.services.async_register( DOMAIN, self._service_name, self._async_notify_message_service, schema=NOTIFY_SERVICE_SCHEMA, )
[ "async", "def", "async_register_services", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "hass", "if", "hasattr", "(", "self", ",", "\"targets\"", ")", ":", "stale_targets", "=", "set", "(", "self", ".", "_registered_targets", ")", "# pylint: disable=no-member", "for", "name", ",", "target", "in", "self", ".", "targets", ".", "items", "(", ")", ":", "# type: ignore", "target_name", "=", "slugify", "(", "f\"{self._target_service_name_prefix}_{name}\"", ")", "if", "target_name", "in", "stale_targets", ":", "stale_targets", ".", "remove", "(", "target_name", ")", "if", "target_name", "in", "self", ".", "_registered_targets", ":", "continue", "self", ".", "_registered_targets", "[", "target_name", "]", "=", "target", "self", ".", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "target_name", ",", "self", ".", "_async_notify_message_service", ",", "schema", "=", "NOTIFY_SERVICE_SCHEMA", ",", ")", "for", "stale_target_name", "in", "stale_targets", ":", "del", "self", ".", "_registered_targets", "[", "stale_target_name", "]", "self", ".", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "stale_target_name", ",", ")", "if", "self", ".", "hass", ".", "services", ".", "has_service", "(", "DOMAIN", ",", "self", ".", "_service_name", ")", ":", "return", "self", ".", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "self", ".", "_service_name", ",", "self", ".", "_async_notify_message_service", ",", "schema", "=", "NOTIFY_SERVICE_SCHEMA", ",", ")" ]
[ 161, 4 ]
[ 198, 9 ]
python
en
['en', 'en', 'en']
True
BaseNotificationService.async_unregister_services
(self)
Unregister the notify services.
Unregister the notify services.
async def async_unregister_services(self) -> None: """Unregister the notify services.""" assert self.hass if self._registered_targets: remove_targets = set(self._registered_targets) for remove_target_name in remove_targets: del self._registered_targets[remove_target_name] self.hass.services.async_remove( DOMAIN, remove_target_name, ) if not self.hass.services.has_service(DOMAIN, self._service_name): return self.hass.services.async_remove( DOMAIN, self._service_name, )
[ "async", "def", "async_unregister_services", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "hass", "if", "self", ".", "_registered_targets", ":", "remove_targets", "=", "set", "(", "self", ".", "_registered_targets", ")", "for", "remove_target_name", "in", "remove_targets", ":", "del", "self", ".", "_registered_targets", "[", "remove_target_name", "]", "self", ".", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "remove_target_name", ",", ")", "if", "not", "self", ".", "hass", ".", "services", ".", "has_service", "(", "DOMAIN", ",", "self", ".", "_service_name", ")", ":", "return", "self", ".", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "self", ".", "_service_name", ",", ")" ]
[ 200, 4 ]
[ 219, 9 ]
python
en
['en', 'en', 'en']
True
NetAdaptPruner.validate_config
(self, model, config_list)
Parameters ---------- model : torch.nn.Module Model to be pruned config_list : list List on pruning configs
Parameters ---------- model : torch.nn.Module Model to be pruned config_list : list List on pruning configs
def validate_config(self, model, config_list): """ Parameters ---------- model : torch.nn.Module Model to be pruned config_list : list List on pruning configs """ if self._base_algo == 'level': schema = CompressorSchema([{ 'sparsity': And(float, lambda n: 0 < n < 1), Optional('op_types'): [str], Optional('op_names'): [str], }], model, _logger) elif self._base_algo in ['l1', 'l2', 'fpgm']: schema = CompressorSchema([{ 'sparsity': And(float, lambda n: 0 < n < 1), 'op_types': ['Conv2d'], Optional('op_names'): [str] }], model, _logger) schema.validate(config_list)
[ "def", "validate_config", "(", "self", ",", "model", ",", "config_list", ")", ":", "if", "self", ".", "_base_algo", "==", "'level'", ":", "schema", "=", "CompressorSchema", "(", "[", "{", "'sparsity'", ":", "And", "(", "float", ",", "lambda", "n", ":", "0", "<", "n", "<", "1", ")", ",", "Optional", "(", "'op_types'", ")", ":", "[", "str", "]", ",", "Optional", "(", "'op_names'", ")", ":", "[", "str", "]", ",", "}", "]", ",", "model", ",", "_logger", ")", "elif", "self", ".", "_base_algo", "in", "[", "'l1'", ",", "'l2'", ",", "'fpgm'", "]", ":", "schema", "=", "CompressorSchema", "(", "[", "{", "'sparsity'", ":", "And", "(", "float", ",", "lambda", "n", ":", "0", "<", "n", "<", "1", ")", ",", "'op_types'", ":", "[", "'Conv2d'", "]", ",", "Optional", "(", "'op_names'", ")", ":", "[", "str", "]", "}", "]", ",", "model", ",", "_logger", ")", "schema", ".", "validate", "(", "config_list", ")" ]
[ 111, 4 ]
[ 134, 36 ]
python
en
['en', 'error', 'th']
False
NetAdaptPruner._update_config_list
(self, config_list, op_name, sparsity)
update sparsity of op_name in config_list
update sparsity of op_name in config_list
def _update_config_list(self, config_list, op_name, sparsity): ''' update sparsity of op_name in config_list ''' config_list_updated = copy.deepcopy(config_list) for idx, item in enumerate(config_list): if op_name in item['op_names']: config_list_updated[idx]['sparsity'] = sparsity return config_list_updated # if op_name is not in self._config_list_generated, create a new json item if self._base_algo in ['l1', 'l2', 'fpgm']: config_list_updated.append( {'sparsity': sparsity, 'op_types': ['Conv2d'], 'op_names': [op_name]}) elif self._base_algo == 'level': config_list_updated.append( {'sparsity': sparsity, 'op_names': [op_name]}) return config_list_updated
[ "def", "_update_config_list", "(", "self", ",", "config_list", ",", "op_name", ",", "sparsity", ")", ":", "config_list_updated", "=", "copy", ".", "deepcopy", "(", "config_list", ")", "for", "idx", ",", "item", "in", "enumerate", "(", "config_list", ")", ":", "if", "op_name", "in", "item", "[", "'op_names'", "]", ":", "config_list_updated", "[", "idx", "]", "[", "'sparsity'", "]", "=", "sparsity", "return", "config_list_updated", "# if op_name is not in self._config_list_generated, create a new json item", "if", "self", ".", "_base_algo", "in", "[", "'l1'", ",", "'l2'", ",", "'fpgm'", "]", ":", "config_list_updated", ".", "append", "(", "{", "'sparsity'", ":", "sparsity", ",", "'op_types'", ":", "[", "'Conv2d'", "]", ",", "'op_names'", ":", "[", "op_name", "]", "}", ")", "elif", "self", ".", "_base_algo", "==", "'level'", ":", "config_list_updated", ".", "append", "(", "{", "'sparsity'", ":", "sparsity", ",", "'op_names'", ":", "[", "op_name", "]", "}", ")", "return", "config_list_updated" ]
[ 139, 4 ]
[ 158, 34 ]
python
en
['en', 'error', 'th']
False
NetAdaptPruner._get_op_num_weights_remained
(self, op_name, module)
Get the number of weights remained after channel pruning with current sparsity Returns ------- int remained number of weights of the op
Get the number of weights remained after channel pruning with current sparsity
def _get_op_num_weights_remained(self, op_name, module): ''' Get the number of weights remained after channel pruning with current sparsity Returns ------- int remained number of weights of the op ''' # if op is wrapped by the pruner for wrapper in self.get_modules_wrapper(): if wrapper.name == op_name: return wrapper.weight_mask.sum().item() # if op is not wrapped by the pruner return module.weight.data.numel()
[ "def", "_get_op_num_weights_remained", "(", "self", ",", "op_name", ",", "module", ")", ":", "# if op is wrapped by the pruner", "for", "wrapper", "in", "self", ".", "get_modules_wrapper", "(", ")", ":", "if", "wrapper", ".", "name", "==", "op_name", ":", "return", "wrapper", ".", "weight_mask", ".", "sum", "(", ")", ".", "item", "(", ")", "# if op is not wrapped by the pruner", "return", "module", ".", "weight", ".", "data", ".", "numel", "(", ")" ]
[ 160, 4 ]
[ 176, 41 ]
python
en
['en', 'error', 'th']
False
NetAdaptPruner._calc_num_related_weights
(self, op_name)
Calculate total number weights of the op and the next op, applicable only for models without dependencies among ops Parameters ---------- op_name : str Returns ------- int total number of all the realted (current and the next) op weights
Calculate total number weights of the op and the next op, applicable only for models without dependencies among ops
def _calc_num_related_weights(self, op_name): ''' Calculate total number weights of the op and the next op, applicable only for models without dependencies among ops Parameters ---------- op_name : str Returns ------- int total number of all the realted (current and the next) op weights ''' num_weights = 0 flag_found = False previous_name = None previous_module = None for name, module in self._model_to_prune.named_modules(): if not flag_found and name != op_name and type(module).__name__ in ['Conv2d', 'Linear']: previous_name = name previous_module = module if not flag_found and name == op_name: _logger.debug("original module found: %s", name) num_weights = module.weight.data.numel() # consider related pruning in this op caused by previous op's pruning if previous_module: sparsity_previous_op = self._get_op_sparsity(previous_name) if sparsity_previous_op: _logger.debug( "decrease op's weights by %s due to previous op %s's pruning...", sparsity_previous_op, previous_name) num_weights *= (1-sparsity_previous_op) flag_found = True continue if flag_found and type(module).__name__ in ['Conv2d', 'Linear']: _logger.debug("related module found: %s", name) # channel/filter pruning crossing is considered here, so only the num_weights after channel pruning is valuable num_weights += self._get_op_num_weights_remained(name, module) break _logger.debug("num related weights of op %s : %d", op_name, num_weights) return num_weights
[ "def", "_calc_num_related_weights", "(", "self", ",", "op_name", ")", ":", "num_weights", "=", "0", "flag_found", "=", "False", "previous_name", "=", "None", "previous_module", "=", "None", "for", "name", ",", "module", "in", "self", ".", "_model_to_prune", ".", "named_modules", "(", ")", ":", "if", "not", "flag_found", "and", "name", "!=", "op_name", "and", "type", "(", "module", ")", ".", "__name__", "in", "[", "'Conv2d'", ",", "'Linear'", "]", ":", "previous_name", "=", "name", "previous_module", "=", "module", "if", "not", "flag_found", "and", "name", "==", "op_name", ":", "_logger", ".", "debug", "(", "\"original module found: %s\"", ",", "name", ")", "num_weights", "=", "module", ".", "weight", ".", "data", ".", "numel", "(", ")", "# consider related pruning in this op caused by previous op's pruning", "if", "previous_module", ":", "sparsity_previous_op", "=", "self", ".", "_get_op_sparsity", "(", "previous_name", ")", "if", "sparsity_previous_op", ":", "_logger", ".", "debug", "(", "\"decrease op's weights by %s due to previous op %s's pruning...\"", ",", "sparsity_previous_op", ",", "previous_name", ")", "num_weights", "*=", "(", "1", "-", "sparsity_previous_op", ")", "flag_found", "=", "True", "continue", "if", "flag_found", "and", "type", "(", "module", ")", ".", "__name__", "in", "[", "'Conv2d'", ",", "'Linear'", "]", ":", "_logger", ".", "debug", "(", "\"related module found: %s\"", ",", "name", ")", "# channel/filter pruning crossing is considered here, so only the num_weights after channel pruning is valuable", "num_weights", "+=", "self", ".", "_get_op_num_weights_remained", "(", "name", ",", "module", ")", "break", "_logger", ".", "debug", "(", "\"num related weights of op %s : %d\"", ",", "op_name", ",", "num_weights", ")", "return", "num_weights" ]
[ 184, 4 ]
[ 228, 26 ]
python
en
['en', 'error', 'th']
False
NetAdaptPruner.compress
(self)
Compress the model. Returns ------- torch.nn.Module model with specified modules compressed.
Compress the model.
def compress(self): """ Compress the model. Returns ------- torch.nn.Module model with specified modules compressed. """ _logger.info('Starting NetAdapt Compression...') pruning_iteration = 0 current_sparsity = 0 delta_num_weights_per_iteration = \ int(get_total_num_weights(self._model_to_prune, ['Conv2d', 'Linear']) * self._sparsity_per_iteration) # stop condition while current_sparsity < self._sparsity: _logger.info('Pruning iteration: %d', pruning_iteration) # calculate target sparsity of this iteration target_sparsity = current_sparsity + self._sparsity_per_iteration # variable to store the info of the best layer found in this iteration best_op = {} for wrapper in self.get_modules_wrapper(): _logger.debug("op name : %s", wrapper.name) _logger.debug("op weights : %d", wrapper.weight_mask.numel()) _logger.debug("op left weights : %d", wrapper.weight_mask.sum().item()) current_op_sparsity = 1 - wrapper.weight_mask.sum().item() / wrapper.weight_mask.numel() _logger.debug("current op sparsity : %s", current_op_sparsity) # sparsity that this layer needs to prune to satisfy the requirement target_op_sparsity = current_op_sparsity + delta_num_weights_per_iteration / self._calc_num_related_weights(wrapper.name) if target_op_sparsity >= 1: _logger.info('Layer %s has no enough weights (remained) to prune', wrapper.name) continue config_list = self._update_config_list(self._config_list_generated, wrapper.name, target_op_sparsity) _logger.debug("config_list used : %s", config_list) pruner = PRUNER_DICT[self._base_algo](copy.deepcopy(self._model_to_prune), config_list) model_masked = pruner.compress() # Short-term fine tune the pruned model self._short_term_fine_tuner(model_masked) performance = self._evaluator(model_masked) _logger.info("Layer : %s, evaluation result after short-term fine tuning : %s", wrapper.name, performance) if not best_op \ or (self._optimize_mode is OptimizeMode.Maximize and performance > best_op['performance']) \ or (self._optimize_mode is OptimizeMode.Minimize and performance < best_op['performance']): _logger.debug("updating best layer to %s...", wrapper.name) # find weight mask of this layer for w in pruner.get_modules_wrapper(): if w.name == wrapper.name: masks = {'weight_mask': w.weight_mask, 'bias_mask': w.bias_mask} break best_op = { 'op_name': wrapper.name, 'sparsity': target_op_sparsity, 'performance': performance, 'masks': masks } # save model weights pruner.export_model(self._tmp_model_path) if not best_op: # decrease pruning step self._sparsity_per_iteration *= 0.5 _logger.info("No more layers to prune, decrease pruning step to %s", self._sparsity_per_iteration) continue # Pick the best layer to prune, update iterative information # update config_list self._config_list_generated = self._update_config_list( self._config_list_generated, best_op['op_name'], best_op['sparsity']) # update weights parameters self._model_to_prune.load_state_dict(torch.load(self._tmp_model_path)) # update mask of the chosen op for wrapper in self.get_modules_wrapper(): if wrapper.name == best_op['op_name']: for k in best_op['masks']: setattr(wrapper, k, best_op['masks'][k]) break current_sparsity = target_sparsity _logger.info('Pruning iteration %d finished, current sparsity: %s', pruning_iteration, current_sparsity) _logger.info('Layer %s seleted with sparsity %s, performance after pruning & short term fine-tuning : %s', best_op['op_name'], best_op['sparsity'], best_op['performance']) pruning_iteration += 1 self._final_performance = best_op['performance'] # load weights parameters self.load_model_state_dict(torch.load(self._tmp_model_path)) os.remove(self._tmp_model_path) _logger.info('----------Compression finished--------------') _logger.info('config_list generated: %s', self._config_list_generated) _logger.info("Performance after pruning: %s", self._final_performance) _logger.info("Masked sparsity: %.6f", current_sparsity) # save best config found and best performance with open(os.path.join(self._experiment_data_dir, 'search_result.json'), 'w') as jsonfile: json.dump({ 'performance': self._final_performance, 'config_list': json.dumps(self._config_list_generated) }, jsonfile) _logger.info('search history and result saved to foler : %s', self._experiment_data_dir) return self.bound_model
[ "def", "compress", "(", "self", ")", ":", "_logger", ".", "info", "(", "'Starting NetAdapt Compression...'", ")", "pruning_iteration", "=", "0", "current_sparsity", "=", "0", "delta_num_weights_per_iteration", "=", "int", "(", "get_total_num_weights", "(", "self", ".", "_model_to_prune", ",", "[", "'Conv2d'", ",", "'Linear'", "]", ")", "*", "self", ".", "_sparsity_per_iteration", ")", "# stop condition", "while", "current_sparsity", "<", "self", ".", "_sparsity", ":", "_logger", ".", "info", "(", "'Pruning iteration: %d'", ",", "pruning_iteration", ")", "# calculate target sparsity of this iteration", "target_sparsity", "=", "current_sparsity", "+", "self", ".", "_sparsity_per_iteration", "# variable to store the info of the best layer found in this iteration", "best_op", "=", "{", "}", "for", "wrapper", "in", "self", ".", "get_modules_wrapper", "(", ")", ":", "_logger", ".", "debug", "(", "\"op name : %s\"", ",", "wrapper", ".", "name", ")", "_logger", ".", "debug", "(", "\"op weights : %d\"", ",", "wrapper", ".", "weight_mask", ".", "numel", "(", ")", ")", "_logger", ".", "debug", "(", "\"op left weights : %d\"", ",", "wrapper", ".", "weight_mask", ".", "sum", "(", ")", ".", "item", "(", ")", ")", "current_op_sparsity", "=", "1", "-", "wrapper", ".", "weight_mask", ".", "sum", "(", ")", ".", "item", "(", ")", "/", "wrapper", ".", "weight_mask", ".", "numel", "(", ")", "_logger", ".", "debug", "(", "\"current op sparsity : %s\"", ",", "current_op_sparsity", ")", "# sparsity that this layer needs to prune to satisfy the requirement", "target_op_sparsity", "=", "current_op_sparsity", "+", "delta_num_weights_per_iteration", "/", "self", ".", "_calc_num_related_weights", "(", "wrapper", ".", "name", ")", "if", "target_op_sparsity", ">=", "1", ":", "_logger", ".", "info", "(", "'Layer %s has no enough weights (remained) to prune'", ",", "wrapper", ".", "name", ")", "continue", "config_list", "=", "self", ".", "_update_config_list", "(", "self", ".", "_config_list_generated", ",", "wrapper", ".", "name", ",", "target_op_sparsity", ")", "_logger", ".", "debug", "(", "\"config_list used : %s\"", ",", "config_list", ")", "pruner", "=", "PRUNER_DICT", "[", "self", ".", "_base_algo", "]", "(", "copy", ".", "deepcopy", "(", "self", ".", "_model_to_prune", ")", ",", "config_list", ")", "model_masked", "=", "pruner", ".", "compress", "(", ")", "# Short-term fine tune the pruned model", "self", ".", "_short_term_fine_tuner", "(", "model_masked", ")", "performance", "=", "self", ".", "_evaluator", "(", "model_masked", ")", "_logger", ".", "info", "(", "\"Layer : %s, evaluation result after short-term fine tuning : %s\"", ",", "wrapper", ".", "name", ",", "performance", ")", "if", "not", "best_op", "or", "(", "self", ".", "_optimize_mode", "is", "OptimizeMode", ".", "Maximize", "and", "performance", ">", "best_op", "[", "'performance'", "]", ")", "or", "(", "self", ".", "_optimize_mode", "is", "OptimizeMode", ".", "Minimize", "and", "performance", "<", "best_op", "[", "'performance'", "]", ")", ":", "_logger", ".", "debug", "(", "\"updating best layer to %s...\"", ",", "wrapper", ".", "name", ")", "# find weight mask of this layer", "for", "w", "in", "pruner", ".", "get_modules_wrapper", "(", ")", ":", "if", "w", ".", "name", "==", "wrapper", ".", "name", ":", "masks", "=", "{", "'weight_mask'", ":", "w", ".", "weight_mask", ",", "'bias_mask'", ":", "w", ".", "bias_mask", "}", "break", "best_op", "=", "{", "'op_name'", ":", "wrapper", ".", "name", ",", "'sparsity'", ":", "target_op_sparsity", ",", "'performance'", ":", "performance", ",", "'masks'", ":", "masks", "}", "# save model weights", "pruner", ".", "export_model", "(", "self", ".", "_tmp_model_path", ")", "if", "not", "best_op", ":", "# decrease pruning step", "self", ".", "_sparsity_per_iteration", "*=", "0.5", "_logger", ".", "info", "(", "\"No more layers to prune, decrease pruning step to %s\"", ",", "self", ".", "_sparsity_per_iteration", ")", "continue", "# Pick the best layer to prune, update iterative information", "# update config_list", "self", ".", "_config_list_generated", "=", "self", ".", "_update_config_list", "(", "self", ".", "_config_list_generated", ",", "best_op", "[", "'op_name'", "]", ",", "best_op", "[", "'sparsity'", "]", ")", "# update weights parameters", "self", ".", "_model_to_prune", ".", "load_state_dict", "(", "torch", ".", "load", "(", "self", ".", "_tmp_model_path", ")", ")", "# update mask of the chosen op", "for", "wrapper", "in", "self", ".", "get_modules_wrapper", "(", ")", ":", "if", "wrapper", ".", "name", "==", "best_op", "[", "'op_name'", "]", ":", "for", "k", "in", "best_op", "[", "'masks'", "]", ":", "setattr", "(", "wrapper", ",", "k", ",", "best_op", "[", "'masks'", "]", "[", "k", "]", ")", "break", "current_sparsity", "=", "target_sparsity", "_logger", ".", "info", "(", "'Pruning iteration %d finished, current sparsity: %s'", ",", "pruning_iteration", ",", "current_sparsity", ")", "_logger", ".", "info", "(", "'Layer %s seleted with sparsity %s, performance after pruning & short term fine-tuning : %s'", ",", "best_op", "[", "'op_name'", "]", ",", "best_op", "[", "'sparsity'", "]", ",", "best_op", "[", "'performance'", "]", ")", "pruning_iteration", "+=", "1", "self", ".", "_final_performance", "=", "best_op", "[", "'performance'", "]", "# load weights parameters", "self", ".", "load_model_state_dict", "(", "torch", ".", "load", "(", "self", ".", "_tmp_model_path", ")", ")", "os", ".", "remove", "(", "self", ".", "_tmp_model_path", ")", "_logger", ".", "info", "(", "'----------Compression finished--------------'", ")", "_logger", ".", "info", "(", "'config_list generated: %s'", ",", "self", ".", "_config_list_generated", ")", "_logger", ".", "info", "(", "\"Performance after pruning: %s\"", ",", "self", ".", "_final_performance", ")", "_logger", ".", "info", "(", "\"Masked sparsity: %.6f\"", ",", "current_sparsity", ")", "# save best config found and best performance", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'search_result.json'", ")", ",", "'w'", ")", "as", "jsonfile", ":", "json", ".", "dump", "(", "{", "'performance'", ":", "self", ".", "_final_performance", ",", "'config_list'", ":", "json", ".", "dumps", "(", "self", ".", "_config_list_generated", ")", "}", ",", "jsonfile", ")", "_logger", ".", "info", "(", "'search history and result saved to foler : %s'", ",", "self", ".", "_experiment_data_dir", ")", "return", "self", ".", "bound_model" ]
[ 230, 4 ]
[ 350, 31 ]
python
en
['en', 'error', 'th']
False