Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
LMShuffledIterator.__init__
(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False)
data -- list[LongTensor] -- there is no order among the LongTensors
data -- list[LongTensor] -- there is no order among the LongTensors
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False): """ data -- list[LongTensor] -- there is no order among the LongTensors """ self.data = data self.bsz = bsz self.bptt = bptt self.ext_len = ext_len if ext_len is not None else 0 ...
[ "def", "__init__", "(", "self", ",", "data", ",", "bsz", ",", "bptt", ",", "device", "=", "\"cpu\"", ",", "ext_len", "=", "None", ",", "shuffle", "=", "False", ")", ":", "self", ".", "data", "=", "data", "self", ".", "bsz", "=", "bsz", "self", "....
[ 551, 4 ]
[ 562, 30 ]
python
en
['en', 'error', 'th']
False
TransfoXLCorpus.from_pretrained
(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs)
Instantiate a pre-processed corpus.
Instantiate a pre-processed corpus.
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): """ Instantiate a pre-processed corpus. """ vocab = TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) if pretrained_model_name_or_path in PRETRAINED_CORP...
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "cache_dir", "=", "None", ",", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "vocab", "=", "TransfoXLTokenizer", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",",...
[ 663, 4 ]
[ 704, 21 ]
python
en
['en', 'error', 'th']
False
setup
(hass, config)
Set up the Feedreader component.
Set up the Feedreader component.
def setup(hass, config): """Set up the Feedreader component.""" urls = config.get(DOMAIN)[CONF_URLS] scan_interval = config.get(DOMAIN).get(CONF_SCAN_INTERVAL) max_entries = config.get(DOMAIN).get(CONF_MAX_ENTRIES) data_file = hass.config.path(f"{DOMAIN}.pickle") storage = StoredData(data_file) ...
[ "def", "setup", "(", "hass", ",", "config", ")", ":", "urls", "=", "config", ".", "get", "(", "DOMAIN", ")", "[", "CONF_URLS", "]", "scan_interval", "=", "config", ".", "get", "(", "DOMAIN", ")", ".", "get", "(", "CONF_SCAN_INTERVAL", ")", "max_entries...
[ 42, 0 ]
[ 52, 25 ]
python
en
['en', 'en', 'en']
True
FeedManager.__init__
(self, url, scan_interval, max_entries, hass, storage)
Initialize the FeedManager object, poll as per scan interval.
Initialize the FeedManager object, poll as per scan interval.
def __init__(self, url, scan_interval, max_entries, hass, storage): """Initialize the FeedManager object, poll as per scan interval.""" self._url = url self._scan_interval = scan_interval self._max_entries = max_entries self._feed = None self._hass = hass self._fi...
[ "def", "__init__", "(", "self", ",", "url", ",", "scan_interval", ",", "max_entries", ",", "hass", ",", "storage", ")", ":", "self", ".", "_url", "=", "url", "self", ".", "_scan_interval", "=", "scan_interval", "self", ".", "_max_entries", "=", "max_entrie...
[ 58, 4 ]
[ 73, 40 ]
python
en
['en', 'en', 'en']
True
FeedManager._log_no_entries
(self)
Send no entries log at debug level.
Send no entries log at debug level.
def _log_no_entries(self): """Send no entries log at debug level.""" _LOGGER.debug("No new entries to be published in feed %s", self._url)
[ "def", "_log_no_entries", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"No new entries to be published in feed %s\"", ",", "self", ".", "_url", ")" ]
[ 75, 4 ]
[ 77, 77 ]
python
ca
['ca', 'fil', 'pt']
False
FeedManager._init_regular_updates
(self, hass)
Schedule regular updates at the top of the clock.
Schedule regular updates at the top of the clock.
def _init_regular_updates(self, hass): """Schedule regular updates at the top of the clock.""" track_time_interval(hass, lambda now: self._update(), self._scan_interval)
[ "def", "_init_regular_updates", "(", "self", ",", "hass", ")", ":", "track_time_interval", "(", "hass", ",", "lambda", "now", ":", "self", ".", "_update", "(", ")", ",", "self", ".", "_scan_interval", ")" ]
[ 79, 4 ]
[ 81, 82 ]
python
en
['en', 'en', 'en']
True
FeedManager.last_update_successful
(self)
Return True if the last feed update was successful.
Return True if the last feed update was successful.
def last_update_successful(self): """Return True if the last feed update was successful.""" return self._last_update_successful
[ "def", "last_update_successful", "(", "self", ")", ":", "return", "self", ".", "_last_update_successful" ]
[ 84, 4 ]
[ 86, 43 ]
python
en
['en', 'en', 'en']
True
FeedManager._update
(self)
Update the feed and publish new entries to the event bus.
Update the feed and publish new entries to the event bus.
def _update(self): """Update the feed and publish new entries to the event bus.""" _LOGGER.info("Fetching new data from feed %s", self._url) self._feed = feedparser.parse( self._url, etag=None if not self._feed else self._feed.get("etag"), modified=None if not...
[ "def", "_update", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Fetching new data from feed %s\"", ",", "self", ".", "_url", ")", "self", ".", "_feed", "=", "feedparser", ".", "parse", "(", "self", ".", "_url", ",", "etag", "=", "None", "if", ...
[ 88, 4 ]
[ 129, 63 ]
python
en
['en', 'en', 'en']
True
FeedManager._filter_entries
(self)
Filter the entries provided and return the ones to keep.
Filter the entries provided and return the ones to keep.
def _filter_entries(self): """Filter the entries provided and return the ones to keep.""" if len(self._feed.entries) > self._max_entries: _LOGGER.debug( "Processing only the first %s entries in feed %s", self._max_entries, self._url, ...
[ "def", "_filter_entries", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_feed", ".", "entries", ")", ">", "self", ".", "_max_entries", ":", "_LOGGER", ".", "debug", "(", "\"Processing only the first %s entries in feed %s\"", ",", "self", ".", "_max_en...
[ 131, 4 ]
[ 139, 74 ]
python
en
['en', 'en', 'en']
True
FeedManager._update_and_fire_entry
(self, entry)
Update last_entry_timestamp and fire entry.
Update last_entry_timestamp and fire entry.
def _update_and_fire_entry(self, entry): """Update last_entry_timestamp and fire entry.""" # Check if the entry has a published date. if "published_parsed" in entry and entry.published_parsed: # We are lucky, `published_parsed` data available, let's make use of # it to pu...
[ "def", "_update_and_fire_entry", "(", "self", ",", "entry", ")", ":", "# Check if the entry has a published date.", "if", "\"published_parsed\"", "in", "entry", "and", "entry", ".", "published_parsed", ":", "# We are lucky, `published_parsed` data available, let's make use of", ...
[ 141, 4 ]
[ 155, 52 ]
python
en
['en', 'en', 'en']
True
FeedManager._publish_new_entries
(self)
Publish new entries to the event bus.
Publish new entries to the event bus.
def _publish_new_entries(self): """Publish new entries to the event bus.""" new_entries = False self._last_entry_timestamp = self._storage.get_timestamp(self._feed_id) if self._last_entry_timestamp: self._firstrun = False else: # Set last entry timestamp a...
[ "def", "_publish_new_entries", "(", "self", ")", ":", "new_entries", "=", "False", "self", ".", "_last_entry_timestamp", "=", "self", ".", "_storage", ".", "get_timestamp", "(", "self", ".", "_feed_id", ")", "if", "self", ".", "_last_entry_timestamp", ":", "se...
[ 157, 4 ]
[ 177, 30 ]
python
en
['en', 'en', 'en']
True
StoredData.__init__
(self, data_file)
Initialize pickle data storage.
Initialize pickle data storage.
def __init__(self, data_file): """Initialize pickle data storage.""" self._data_file = data_file self._lock = Lock() self._cache_outdated = True self._data = {} self._fetch_data()
[ "def", "__init__", "(", "self", ",", "data_file", ")", ":", "self", ".", "_data_file", "=", "data_file", "self", ".", "_lock", "=", "Lock", "(", ")", "self", ".", "_cache_outdated", "=", "True", "self", ".", "_data", "=", "{", "}", "self", ".", "_fet...
[ 183, 4 ]
[ 189, 26 ]
python
en
['fr', 'pl', 'en']
False
StoredData._fetch_data
(self)
Fetch data stored into pickle file.
Fetch data stored into pickle file.
def _fetch_data(self): """Fetch data stored into pickle file.""" if self._cache_outdated and exists(self._data_file): try: _LOGGER.debug("Fetching data from file %s", self._data_file) with self._lock, open(self._data_file, "rb") as myfile: ...
[ "def", "_fetch_data", "(", "self", ")", ":", "if", "self", ".", "_cache_outdated", "and", "exists", "(", "self", ".", "_data_file", ")", ":", "try", ":", "_LOGGER", ".", "debug", "(", "\"Fetching data from file %s\"", ",", "self", ".", "_data_file", ")", "...
[ 191, 4 ]
[ 202, 17 ]
python
en
['en', 'en', 'en']
True
StoredData.get_timestamp
(self, feed_id)
Return stored timestamp for given feed id (usually the url).
Return stored timestamp for given feed id (usually the url).
def get_timestamp(self, feed_id): """Return stored timestamp for given feed id (usually the url).""" self._fetch_data() return self._data.get(feed_id)
[ "def", "get_timestamp", "(", "self", ",", "feed_id", ")", ":", "self", ".", "_fetch_data", "(", ")", "return", "self", ".", "_data", ".", "get", "(", "feed_id", ")" ]
[ 204, 4 ]
[ 207, 38 ]
python
en
['en', 'en', 'en']
True
StoredData.put_timestamp
(self, feed_id, timestamp)
Update timestamp for given feed id (usually the url).
Update timestamp for given feed id (usually the url).
def put_timestamp(self, feed_id, timestamp): """Update timestamp for given feed id (usually the url).""" self._fetch_data() with self._lock, open(self._data_file, "wb") as myfile: self._data.update({feed_id: timestamp}) _LOGGER.debug( "Overwriting feed %s ...
[ "def", "put_timestamp", "(", "self", ",", "feed_id", ",", "timestamp", ")", ":", "self", ".", "_fetch_data", "(", ")", "with", "self", ".", "_lock", ",", "open", "(", "self", ".", "_data_file", ",", "\"wb\"", ")", "as", "myfile", ":", "self", ".", "_...
[ 209, 4 ]
[ 223, 35 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Get all devices and setup the switch devices via config entry.
Get all devices and setup the switch devices via config entry.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Get all devices and setup the switch devices via config entry.""" entities = [] for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]: for device in gateway.binary_switch_devices: ...
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "entities", "=", "[", "]", "for", "gateway", "in", "hass", ".", "data", "[", "DOMAIN", "]", "["...
[ 9, 0 ]
[ 29, 32 ]
python
en
['en', 'en', 'en']
True
DevoloSwitch.__init__
(self, homecontrol, device_instance, element_uid)
Initialize an devolo Switch.
Initialize an devolo Switch.
def __init__(self, homecontrol, device_instance, element_uid): """Initialize an devolo Switch.""" super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._binary_switch_property = self._device_instanc...
[ "def", "__init__", "(", "self", ",", "homecontrol", ",", "device_instance", ",", "element_uid", ")", ":", "super", "(", ")", ".", "__init__", "(", "homecontrol", "=", "homecontrol", ",", "device_instance", "=", "device_instance", ",", "element_uid", "=", "elem...
[ 35, 4 ]
[ 52, 36 ]
python
br
['br', 'pl', 'it']
False
DevoloSwitch.is_on
(self)
Return the state.
Return the state.
def is_on(self): """Return the state.""" return self._is_on
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_is_on" ]
[ 55, 4 ]
[ 57, 26 ]
python
en
['en', 'en', 'en']
True
DevoloSwitch.current_power_w
(self)
Return the current consumption.
Return the current consumption.
def current_power_w(self): """Return the current consumption.""" return self._consumption
[ "def", "current_power_w", "(", "self", ")", ":", "return", "self", ".", "_consumption" ]
[ 60, 4 ]
[ 62, 32 ]
python
en
['en', 'la', 'en']
True
DevoloSwitch.turn_on
(self, **kwargs)
Switch on the device.
Switch on the device.
def turn_on(self, **kwargs): """Switch on the device.""" self._is_on = True self._binary_switch_property.set(state=True)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_is_on", "=", "True", "self", ".", "_binary_switch_property", ".", "set", "(", "state", "=", "True", ")" ]
[ 64, 4 ]
[ 67, 52 ]
python
en
['en', 'en', 'en']
True
DevoloSwitch.turn_off
(self, **kwargs)
Switch off the device.
Switch off the device.
def turn_off(self, **kwargs): """Switch off the device.""" self._is_on = False self._binary_switch_property.set(state=False)
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_is_on", "=", "False", "self", ".", "_binary_switch_property", ".", "set", "(", "state", "=", "False", ")" ]
[ 69, 4 ]
[ 72, 53 ]
python
en
['en', 'en', 'en']
True
DevoloSwitch._sync
(self, message)
Update the binary switch state and consumption.
Update the binary switch state and consumption.
def _sync(self, message): """Update the binary switch state and consumption.""" if message[0].startswith("devolo.BinarySwitch"): self._is_on = self._device_instance.binary_switch_property[message[0]].state elif message[0].startswith("devolo.Meter"): self._consumption = se...
[ "def", "_sync", "(", "self", ",", "message", ")", ":", "if", "message", "[", "0", "]", ".", "startswith", "(", "\"devolo.BinarySwitch\"", ")", ":", "self", ".", "_is_on", "=", "self", ".", "_device_instance", ".", "binary_switch_property", "[", "message", ...
[ 74, 4 ]
[ 84, 39 ]
python
en
['en', 'en', 'en']
True
upsample
(x, stride, target_len, separate_cls=True, truncate_seq=False)
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
def upsample(x, stride, target_len, separate_cls=True, truncate_seq=False): """ Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension. """ if stride == 1: return x if separate_cls: cls = x[:, :1] x = x[:, 1:] outp...
[ "def", "upsample", "(", "x", ",", "stride", ",", "target_len", ",", "separate_cls", "=", "True", ",", "truncate_seq", "=", "False", ")", ":", "if", "stride", "==", "1", ":", "return", "x", "if", "separate_cls", ":", "cls", "=", "x", "[", ":", ",", ...
[ 648, 0 ]
[ 665, 17 ]
python
en
['en', 'error', 'th']
False
TFFunnelEmbeddings.call
(self, input_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, 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) assert not (i...
[ "def", "call", "(", "self", ",", "input_ids", "=", "None", ",", "inputs_embeds", "=", "None", ",", "training", "=", "False", ")", ":", "assert", "not", "(", "input_ids", "is", "None", "and", "inputs_embeds", "is", "None", ")", "assert", "not", "(", "in...
[ 99, 4 ]
[ 115, 31 ]
python
en
['en', 'error', 'th']
False
TFFunnelAttentionStructure.init_attention_inputs
(self, inputs_embeds, attention_mask=None, token_type_ids=None, training=False)
Returns the attention inputs associated to the inputs of the model.
Returns the attention inputs associated to the inputs of the model.
def init_attention_inputs(self, inputs_embeds, attention_mask=None, token_type_ids=None, training=False): """ Returns the attention inputs associated to the inputs of the model. """ # inputs_embeds has shape batch_size x seq_len x d_model # attention_mask and token_type_ids have shape batch_size...
[ "def", "init_attention_inputs", "(", "self", ",", "inputs_embeds", ",", "attention_mask", "=", "None", ",", "token_type_ids", "=", "None", ",", "training", "=", "False", ")", ":", "# inputs_embeds has shape batch_size x seq_len x d_model", "# attention_mask and token_type_i...
[ 140, 4 ]
[ 153, 74 ]
python
en
['en', 'en', 'en']
True
TFFunnelAttentionStructure.token_type_ids_to_mat
(self, token_type_ids)
Convert `token_type_ids` to `token_type_mat`.
Convert `token_type_ids` to `token_type_mat`.
def token_type_ids_to_mat(self, token_type_ids): """Convert `token_type_ids` to `token_type_mat`.""" token_type_mat = tf.equal(tf.expand_dims(token_type_ids, -1), tf.expand_dims(token_type_ids, -2)) # Treat <cls> as in the same segment as both A & B cls_ids = tf.equal(token_type_ids, tf....
[ "def", "token_type_ids_to_mat", "(", "self", ",", "token_type_ids", ")", ":", "token_type_mat", "=", "tf", ".", "equal", "(", "tf", ".", "expand_dims", "(", "token_type_ids", ",", "-", "1", ")", ",", "tf", ".", "expand_dims", "(", "token_type_ids", ",", "-...
[ 155, 4 ]
[ 161, 53 ]
python
nl
['en', 'nl', 'nl']
True
TFFunnelAttentionStructure.get_position_embeds
(self, seq_len, training=False)
Create and cache inputs related to relative position encoding. Those are very different depending on whether we are using the factorized or the relative shift attention: For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2, final...
Create and cache inputs related to relative position encoding. Those are very different depending on whether we are using the factorized or the relative shift attention:
def get_position_embeds(self, seq_len, training=False): """ Create and cache inputs related to relative position encoding. Those are very different depending on whether we are using the factorized or the relative shift attention: For the factorized attention, it returns the matrices (ph...
[ "def", "get_position_embeds", "(", "self", ",", "seq_len", ",", "training", "=", "False", ")", ":", "if", "self", ".", "attention_type", "==", "\"factorized\"", ":", "# Notations from the paper, appending A.2.2, final formula.", "# We need to create and return the matrices ph...
[ 163, 4 ]
[ 243, 39 ]
python
en
['en', 'error', 'th']
False
TFFunnelAttentionStructure.stride_pool_pos
(self, pos_id, block_index)
Pool `pos_id` while keeping the cls token separate (if `self.separate_cls=True`).
Pool `pos_id` while keeping the cls token separate (if `self.separate_cls=True`).
def stride_pool_pos(self, pos_id, block_index): """ Pool `pos_id` while keeping the cls token separate (if `self.separate_cls=True`). """ if self.separate_cls: # Under separate <cls>, we treat the <cls> as the first token in # the previous block of the 1st real bl...
[ "def", "stride_pool_pos", "(", "self", ",", "pos_id", ",", "block_index", ")", ":", "if", "self", ".", "separate_cls", ":", "# Under separate <cls>, we treat the <cls> as the first token in", "# the previous block of the 1st real block. Since the 1st real", "# block always has posi...
[ 245, 4 ]
[ 258, 30 ]
python
en
['en', 'error', 'th']
False
TFFunnelAttentionStructure.relative_pos
(self, pos, stride, pooled_pos=None, shift=1)
Build the relative positional vector between `pos` and `pooled_pos`.
Build the relative positional vector between `pos` and `pooled_pos`.
def relative_pos(self, pos, stride, pooled_pos=None, shift=1): """ Build the relative positional vector between `pos` and `pooled_pos`. """ if pooled_pos is None: pooled_pos = pos ref_point = pooled_pos[0] - pos[0] num_remove = shift * shape_list(pooled_pos)[...
[ "def", "relative_pos", "(", "self", ",", "pos", ",", "stride", ",", "pooled_pos", "=", "None", ",", "shift", "=", "1", ")", ":", "if", "pooled_pos", "is", "None", ":", "pooled_pos", "=", "pos", "ref_point", "=", "pooled_pos", "[", "0", "]", "-", "pos...
[ 260, 4 ]
[ 272, 56 ]
python
en
['en', 'error', 'th']
False
TFFunnelAttentionStructure.stride_pool
(self, tensor, axis)
Perform pooling by stride slicing the tensor along the given axis.
Perform pooling by stride slicing the tensor along the given axis.
def stride_pool(self, tensor, axis): """ Perform pooling by stride slicing the tensor along the given axis. """ if tensor is None: return None # Do the stride pool recursively if axis is a list or a tuple of ints. if isinstance(axis, (list, tuple)): ...
[ "def", "stride_pool", "(", "self", ",", "tensor", ",", "axis", ")", ":", "if", "tensor", "is", "None", ":", "return", "None", "# Do the stride pool recursively if axis is a list or a tuple of ints.", "if", "isinstance", "(", "axis", ",", "(", "list", ",", "tuple",...
[ 274, 4 ]
[ 299, 32 ]
python
en
['en', 'error', 'th']
False
TFFunnelAttentionStructure.pool_tensor
(self, tensor, mode="mean", stride=2)
Apply 1D pooling to a tensor of size [B x T (x H)].
Apply 1D pooling to a tensor of size [B x T (x H)].
def pool_tensor(self, tensor, mode="mean", stride=2): """Apply 1D pooling to a tensor of size [B x T (x H)].""" if tensor is None: return None # Do the pool recursively if tensor is a list or tuple of tensors. if isinstance(tensor, (tuple, list)): return type(ten...
[ "def", "pool_tensor", "(", "self", ",", "tensor", ",", "mode", "=", "\"mean\"", ",", "stride", "=", "2", ")", ":", "if", "tensor", "is", "None", ":", "return", "None", "# Do the pool recursively if tensor is a list or tuple of tensors.", "if", "isinstance", "(", ...
[ 301, 4 ]
[ 327, 61 ]
python
en
['en', 'en', 'en']
True
TFFunnelAttentionStructure.pre_attention_pooling
(self, output, attention_inputs)
Pool `output` and the proper parts of `attention_inputs` before the attention layer.
Pool `output` and the proper parts of `attention_inputs` before the attention layer.
def pre_attention_pooling(self, output, attention_inputs): """ Pool `output` and the proper parts of `attention_inputs` before the attention layer. """ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs if self.pool_q_only: if self.attention_type == "factori...
[ "def", "pre_attention_pooling", "(", "self", ",", "output", ",", "attention_inputs", ")", ":", "position_embeds", ",", "token_type_mat", ",", "attention_mask", ",", "cls_mask", "=", "attention_inputs", "if", "self", ".", "pool_q_only", ":", "if", "self", ".", "a...
[ 329, 4 ]
[ 347, 39 ]
python
en
['en', 'en', 'en']
True
TFFunnelAttentionStructure.post_attention_pooling
(self, attention_inputs)
Pool the proper parts of `attention_inputs` after the attention layer.
Pool the proper parts of `attention_inputs` after the attention layer.
def post_attention_pooling(self, attention_inputs): """ Pool the proper parts of `attention_inputs` after the attention layer. """ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs if self.pool_q_only: self.pooling_mult *= 2 if self.attention_ty...
[ "def", "post_attention_pooling", "(", "self", ",", "attention_inputs", ")", ":", "position_embeds", ",", "token_type_mat", ",", "attention_mask", ",", "cls_mask", "=", "attention_inputs", "if", "self", ".", "pool_q_only", ":", "self", ".", "pooling_mult", "*=", "2...
[ 349, 4 ]
[ 360, 31 ]
python
en
['en', 'en', 'en']
True
TFFunnelRelMultiheadAttention.relative_positional_attention
(self, position_embeds, q_head, context_len, cls_mask=None)
Relative attention score for the positional encodings
Relative attention score for the positional encodings
def relative_positional_attention(self, position_embeds, q_head, context_len, cls_mask=None): """ Relative attention score for the positional encodings """ # q_head has shape batch_size x sea_len x n_head x d_head if self.attention_type == "factorized": # Notations from the paper, ap...
[ "def", "relative_positional_attention", "(", "self", ",", "position_embeds", ",", "q_head", ",", "context_len", ",", "cls_mask", "=", "None", ")", ":", "# q_head has shape batch_size x sea_len x n_head x d_head", "if", "self", ".", "attention_type", "==", "\"factorized\""...
[ 425, 4 ]
[ 469, 30 ]
python
en
['en', 'en', 'en']
True
TFFunnelRelMultiheadAttention.relative_token_type_attention
(self, token_type_mat, q_head, cls_mask=None)
Relative attention score for the token_type_ids
Relative attention score for the token_type_ids
def relative_token_type_attention(self, token_type_mat, q_head, cls_mask=None): """ Relative attention score for the token_type_ids """ if token_type_mat is None: return 0 batch_size, seq_len, context_len = shape_list(token_type_mat) # q_head has shape batch_size x seq_len x ...
[ "def", "relative_token_type_attention", "(", "self", ",", "token_type_mat", ",", "q_head", ",", "cls_mask", "=", "None", ")", ":", "if", "token_type_mat", "is", "None", ":", "return", "0", "batch_size", ",", "seq_len", ",", "context_len", "=", "shape_list", "(...
[ 471, 4 ]
[ 496, 30 ]
python
en
['en', 'en', 'en']
True
setup
()
Set up for tests.
Set up for tests.
def setup(): """Set up for tests.""" global TMP_DIR TMP_DIR = mkdtemp()
[ "def", "setup", "(", ")", ":", "global", "TMP_DIR", "TMP_DIR", "=", "mkdtemp", "(", ")" ]
[ 117, 0 ]
[ 120, 23 ]
python
en
['en', 'da', 'en']
True
teardown
()
Clean up after tests.
Clean up after tests.
def teardown(): """Clean up after tests.""" for fname in os.listdir(TMP_DIR): os.remove(os.path.join(TMP_DIR, fname)) os.rmdir(TMP_DIR)
[ "def", "teardown", "(", ")", ":", "for", "fname", "in", "os", ".", "listdir", "(", "TMP_DIR", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "TMP_DIR", ",", "fname", ")", ")", "os", ".", "rmdir", "(", "TMP_DIR", ")" ]
[ 123, 0 ]
[ 127, 21 ]
python
en
['en', 'en', 'en']
True
test_save_and_load
()
Test saving and loading back.
Test saving and loading back.
def test_save_and_load(): """Test saving and loading back.""" yaml = YAML(typ="rt") fname = _path_for("test1") open(fname, "w+").close() util_yaml.save_yaml(fname, yaml.load(TEST_YAML_A)) data = util_yaml.load_yaml(fname, True) assert data == yaml.load(TEST_YAML_A)
[ "def", "test_save_and_load", "(", ")", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"rt\"", ")", "fname", "=", "_path_for", "(", "\"test1\"", ")", "open", "(", "fname", ",", "\"w+\"", ")", ".", "close", "(", ")", "util_yaml", ".", "save_yaml", "(", "...
[ 134, 0 ]
[ 141, 41 ]
python
en
['en', 'en', 'en']
True
test_overwrite_and_reload
()
Test that we can overwrite an existing file and read back.
Test that we can overwrite an existing file and read back.
def test_overwrite_and_reload(): """Test that we can overwrite an existing file and read back.""" yaml = YAML(typ="rt") fname = _path_for("test2") open(fname, "w+").close() util_yaml.save_yaml(fname, yaml.load(TEST_YAML_A)) util_yaml.save_yaml(fname, yaml.load(TEST_YAML_B)) data = util_yaml....
[ "def", "test_overwrite_and_reload", "(", ")", ":", "yaml", "=", "YAML", "(", "typ", "=", "\"rt\"", ")", "fname", "=", "_path_for", "(", "\"test2\"", ")", "open", "(", "fname", ",", "\"w+\"", ")", ".", "close", "(", ")", "util_yaml", ".", "save_yaml", "...
[ 144, 0 ]
[ 152, 41 ]
python
en
['en', 'en', 'en']
True
test_load_bad_data
()
Test error from trying to load unserialisable data.
Test error from trying to load unserialisable data.
def test_load_bad_data(): """Test error from trying to load unserialisable data.""" fname = _path_for("test3") with open(fname, "w") as fh: fh.write(TEST_BAD_YAML) with pytest.raises(HomeAssistantError): util_yaml.load_yaml(fname, True)
[ "def", "test_load_bad_data", "(", ")", ":", "fname", "=", "_path_for", "(", "\"test3\"", ")", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "TEST_BAD_YAML", ")", "with", "pytest", ".", "raises", "(", "HomeAs...
[ 155, 0 ]
[ 161, 40 ]
python
en
['en', 'en', 'en']
True
threshold_log
(count: int, *args, **kwargs)
Log at warn level after WARN_THRESHOLD failures, debug otherwise.
Log at warn level after WARN_THRESHOLD failures, debug otherwise.
def threshold_log(count: int, *args, **kwargs) -> None: """Log at warn level after WARN_THRESHOLD failures, debug otherwise.""" if count >= WARN_THRESHOLD: _LOGGER.warning(*args, **kwargs) else: _LOGGER.debug(*args, **kwargs)
[ "def", "threshold_log", "(", "count", ":", "int", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "count", ">=", "WARN_THRESHOLD", ":", "_LOGGER", ".", "warning", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":",...
[ 44, 0 ]
[ 49, 38 ]
python
en
['en', 'en', 'en']
True
BrData.__init__
(self, hass, coordinates, timeframe, devices)
Initialize the data object.
Initialize the data object.
def __init__(self, hass, coordinates, timeframe, devices): """Initialize the data object.""" self.devices = devices self.data = {} self.hass = hass self.coordinates = coordinates self.timeframe = timeframe
[ "def", "__init__", "(", "self", ",", "hass", ",", "coordinates", ",", "timeframe", ",", "devices", ")", ":", "self", ".", "devices", "=", "devices", "self", ".", "data", "=", "{", "}", "self", ".", "hass", "=", "hass", "self", ".", "coordinates", "="...
[ 59, 4 ]
[ 65, 34 ]
python
en
['en', 'en', 'en']
True
BrData.update_devices
(self)
Update all devices/sensors.
Update all devices/sensors.
async def update_devices(self): """Update all devices/sensors.""" if not self.devices: return # Update all devices for dev in self.devices: dev.data_updated(self.data)
[ "async", "def", "update_devices", "(", "self", ")", ":", "if", "not", "self", ".", "devices", ":", "return", "# Update all devices", "for", "dev", "in", "self", ".", "devices", ":", "dev", ".", "data_updated", "(", "self", ".", "data", ")" ]
[ 67, 4 ]
[ 74, 39 ]
python
en
['sv', 'en', 'en']
True
BrData.schedule_update
(self, minute=1)
Schedule an update after minute minutes.
Schedule an update after minute minutes.
async def schedule_update(self, minute=1): """Schedule an update after minute minutes.""" _LOGGER.debug("Scheduling next update in %s minutes", minute) nxt = dt_util.utcnow() + timedelta(minutes=minute) async_track_point_in_utc_time(self.hass, self.async_update, nxt)
[ "async", "def", "schedule_update", "(", "self", ",", "minute", "=", "1", ")", ":", "_LOGGER", ".", "debug", "(", "\"Scheduling next update in %s minutes\"", ",", "minute", ")", "nxt", "=", "dt_util", ".", "utcnow", "(", ")", "+", "timedelta", "(", "minutes",...
[ 76, 4 ]
[ 80, 72 ]
python
en
['da', 'en', 'en']
True
BrData.get_data
(self, url)
Load data from specified url.
Load data from specified url.
async def get_data(self, url): """Load data from specified url.""" _LOGGER.debug("Calling url: %s...", url) result = {SUCCESS: False, MESSAGE: None} resp = None try: websession = async_get_clientsession(self.hass) with async_timeout.timeout(10): ...
[ "async", "def", "get_data", "(", "self", ",", "url", ")", ":", "_LOGGER", ".", "debug", "(", "\"Calling url: %s...\"", ",", "url", ")", "result", "=", "{", "SUCCESS", ":", "False", ",", "MESSAGE", ":", "None", "}", "resp", "=", "None", "try", ":", "w...
[ 82, 4 ]
[ 105, 36 ]
python
en
['en', 'en', 'en']
True
BrData.async_update
(self, *_)
Update the data from buienradar.
Update the data from buienradar.
async def async_update(self, *_): """Update the data from buienradar.""" content = await self.get_data(JSON_FEED_URL) if content.get(SUCCESS) is not True: # unable to get the data self.load_error_count += 1 threshold_log( self.load_error_count...
[ "async", "def", "async_update", "(", "self", ",", "*", "_", ")", ":", "content", "=", "await", "self", ".", "get_data", "(", "JSON_FEED_URL", ")", "if", "content", ".", "get", "(", "SUCCESS", ")", "is", "not", "True", ":", "# unable to get the data", "se...
[ 107, 4 ]
[ 166, 47 ]
python
en
['en', 'en', 'en']
True
BrData.attribution
(self)
Return the attribution.
Return the attribution.
def attribution(self): """Return the attribution.""" return self.data.get(ATTRIBUTION)
[ "def", "attribution", "(", "self", ")", ":", "return", "self", ".", "data", ".", "get", "(", "ATTRIBUTION", ")" ]
[ 169, 4 ]
[ 171, 41 ]
python
en
['en', 'ja', 'en']
True
BrData.stationname
(self)
Return the name of the selected weatherstation.
Return the name of the selected weatherstation.
def stationname(self): """Return the name of the selected weatherstation.""" return self.data.get(STATIONNAME)
[ "def", "stationname", "(", "self", ")", ":", "return", "self", ".", "data", ".", "get", "(", "STATIONNAME", ")" ]
[ 174, 4 ]
[ 176, 41 ]
python
en
['en', 'en', 'en']
True
BrData.condition
(self)
Return the condition.
Return the condition.
def condition(self): """Return the condition.""" return self.data.get(CONDITION)
[ "def", "condition", "(", "self", ")", ":", "return", "self", ".", "data", ".", "get", "(", "CONDITION", ")" ]
[ 179, 4 ]
[ 181, 39 ]
python
en
['en', 'en', 'en']
True
BrData.temperature
(self)
Return the temperature, or None.
Return the temperature, or None.
def temperature(self): """Return the temperature, or None.""" try: return float(self.data.get(TEMPERATURE)) except (ValueError, TypeError): return None
[ "def", "temperature", "(", "self", ")", ":", "try", ":", "return", "float", "(", "self", ".", "data", ".", "get", "(", "TEMPERATURE", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 184, 4 ]
[ 189, 23 ]
python
en
['en', 'la', 'en']
True
BrData.pressure
(self)
Return the pressure, or None.
Return the pressure, or None.
def pressure(self): """Return the pressure, or None.""" try: return float(self.data.get(PRESSURE)) except (ValueError, TypeError): return None
[ "def", "pressure", "(", "self", ")", ":", "try", ":", "return", "float", "(", "self", ".", "data", ".", "get", "(", "PRESSURE", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 192, 4 ]
[ 197, 23 ]
python
en
['en', 'it', 'en']
True
BrData.humidity
(self)
Return the humidity, or None.
Return the humidity, or None.
def humidity(self): """Return the humidity, or None.""" try: return int(self.data.get(HUMIDITY)) except (ValueError, TypeError): return None
[ "def", "humidity", "(", "self", ")", ":", "try", ":", "return", "int", "(", "self", ".", "data", ".", "get", "(", "HUMIDITY", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 200, 4 ]
[ 205, 23 ]
python
en
['en', 'en', 'en']
True
BrData.visibility
(self)
Return the visibility, or None.
Return the visibility, or None.
def visibility(self): """Return the visibility, or None.""" try: return int(self.data.get(VISIBILITY)) except (ValueError, TypeError): return None
[ "def", "visibility", "(", "self", ")", ":", "try", ":", "return", "int", "(", "self", ".", "data", ".", "get", "(", "VISIBILITY", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 208, 4 ]
[ 213, 23 ]
python
en
['en', 'en', 'en']
True
BrData.wind_speed
(self)
Return the windspeed, or None.
Return the windspeed, or None.
def wind_speed(self): """Return the windspeed, or None.""" try: return float(self.data.get(WINDSPEED)) except (ValueError, TypeError): return None
[ "def", "wind_speed", "(", "self", ")", ":", "try", ":", "return", "float", "(", "self", ".", "data", ".", "get", "(", "WINDSPEED", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 216, 4 ]
[ 221, 23 ]
python
en
['en', 'en', 'en']
True
BrData.wind_bearing
(self)
Return the wind bearing, or None.
Return the wind bearing, or None.
def wind_bearing(self): """Return the wind bearing, or None.""" try: return int(self.data.get(WINDAZIMUTH)) except (ValueError, TypeError): return None
[ "def", "wind_bearing", "(", "self", ")", ":", "try", ":", "return", "int", "(", "self", ".", "data", ".", "get", "(", "WINDAZIMUTH", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 224, 4 ]
[ 229, 23 ]
python
en
['en', 'en', 'en']
True
BrData.forecast
(self)
Return the forecast data.
Return the forecast data.
def forecast(self): """Return the forecast data.""" return self.data.get(FORECAST)
[ "def", "forecast", "(", "self", ")", ":", "return", "self", ".", "data", ".", "get", "(", "FORECAST", ")" ]
[ 232, 4 ]
[ 234, 38 ]
python
en
['en', 'no', 'en']
True
Env.step
(self, action)
Push the environment to next step with action. Args: action (Action): Action(s) from agent. Returns: tuple: a tuple of (metrics, decision event, is_done).
Push the environment to next step with action.
def step(self, action): """Push the environment to next step with action. Args: action (Action): Action(s) from agent. Returns: tuple: a tuple of (metrics, decision event, is_done). """ try: metrics, decision_event, _is_done = self._simulate_...
[ "def", "step", "(", "self", ",", "action", ")", ":", "try", ":", "metrics", ",", "decision_event", ",", "_is_done", "=", "self", ".", "_simulate_generator", ".", "send", "(", "action", ")", "except", "StopIteration", ":", "return", "None", ",", "None", "...
[ 75, 4 ]
[ 89, 48 ]
python
en
['en', 'en', 'en']
True
Env.dump
(self)
Dump environment for restore. NOTE: Not implemented.
Dump environment for restore.
def dump(self): """Dump environment for restore. NOTE: Not implemented. """ return
[ "def", "dump", "(", "self", ")", ":", "return" ]
[ 91, 4 ]
[ 97, 14 ]
python
en
['en', 'no', 'en']
True
Env.reset
(self)
Reset environment.
Reset environment.
def reset(self): """Reset environment.""" self._tick = self._start_tick self._simulate_generator.close() self._simulate_generator = self._simulate() self._event_buffer.reset() if ("enable-dump-snapshot" in self._additional_options) and (self._business_engine._frame is ...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_tick", "=", "self", ".", "_start_tick", "self", ".", "_simulate_generator", ".", "close", "(", ")", "self", ".", "_simulate_generator", "=", "self", ".", "_simulate", "(", ")", "self", ".", "_event_bu...
[ 99, 4 ]
[ 118, 37 ]
python
be
['fr', 'be', 'en']
False
Env.configs
(self)
dict: Configurations of current environment.
dict: Configurations of current environment.
def configs(self) -> dict: """dict: Configurations of current environment.""" return self._business_engine.configs
[ "def", "configs", "(", "self", ")", "->", "dict", ":", "return", "self", ".", "_business_engine", ".", "configs" ]
[ 121, 4 ]
[ 123, 44 ]
python
en
['en', 'en', 'en']
True
Env.summary
(self)
dict: Summary about current simulator, including node details and mappings.
dict: Summary about current simulator, including node details and mappings.
def summary(self) -> dict: """dict: Summary about current simulator, including node details and mappings.""" return { "node_mapping": self._business_engine.get_node_mapping(), "node_detail": self.current_frame.get_node_info(), "event_payload": self._business_engine.ge...
[ "def", "summary", "(", "self", ")", "->", "dict", ":", "return", "{", "\"node_mapping\"", ":", "self", ".", "_business_engine", ".", "get_node_mapping", "(", ")", ",", "\"node_detail\"", ":", "self", ".", "current_frame", ".", "get_node_info", "(", ")", ",",...
[ 126, 4 ]
[ 132, 9 ]
python
en
['en', 'en', 'en']
True
Env.name
(self)
str: Name of current environment.
str: Name of current environment.
def name(self) -> str: """str: Name of current environment.""" return self._name
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_name" ]
[ 135, 4 ]
[ 137, 25 ]
python
en
['en', 'en', 'en']
True
Env.current_frame
(self)
Frame: Frame of current environment.
Frame: Frame of current environment.
def current_frame(self) -> FrameBase: """Frame: Frame of current environment.""" return self._business_engine.frame
[ "def", "current_frame", "(", "self", ")", "->", "FrameBase", ":", "return", "self", ".", "_business_engine", ".", "frame" ]
[ 140, 4 ]
[ 142, 42 ]
python
en
['en', 'en', 'en']
True
Env.tick
(self)
int: Current tick of environment.
int: Current tick of environment.
def tick(self) -> int: """int: Current tick of environment.""" return self._tick
[ "def", "tick", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_tick" ]
[ 145, 4 ]
[ 147, 25 ]
python
en
['en', 'en', 'en']
True
Env.frame_index
(self)
int: Frame index in snapshot list for current tick.
int: Frame index in snapshot list for current tick.
def frame_index(self) -> int: """int: Frame index in snapshot list for current tick.""" return tick_to_frame_index(self._start_tick, self._tick, self._snapshot_resolution)
[ "def", "frame_index", "(", "self", ")", "->", "int", ":", "return", "tick_to_frame_index", "(", "self", ".", "_start_tick", ",", "self", ".", "_tick", ",", "self", ".", "_snapshot_resolution", ")" ]
[ 150, 4 ]
[ 152, 91 ]
python
en
['en', 'en', 'en']
True
Env.snapshot_list
(self)
SnapshotList: A snapshot list containing all the snapshots of frame at each dump point. NOTE: Due to different environment configurations, the resolution of the snapshot may be different.
SnapshotList: A snapshot list containing all the snapshots of frame at each dump point.
def snapshot_list(self) -> SnapshotList: """SnapshotList: A snapshot list containing all the snapshots of frame at each dump point. NOTE: Due to different environment configurations, the resolution of the snapshot may be different. """ return self._business_engine.snapshots
[ "def", "snapshot_list", "(", "self", ")", "->", "SnapshotList", ":", "return", "self", ".", "_business_engine", ".", "snapshots" ]
[ 155, 4 ]
[ 160, 46 ]
python
en
['en', 'en', 'en']
True
Env.agent_idx_list
(self)
List[int]: Agent index list that related to this environment.
List[int]: Agent index list that related to this environment.
def agent_idx_list(self) -> List[int]: """List[int]: Agent index list that related to this environment.""" return self._business_engine.get_agent_idx_list()
[ "def", "agent_idx_list", "(", "self", ")", "->", "List", "[", "int", "]", ":", "return", "self", ".", "_business_engine", ".", "get_agent_idx_list", "(", ")" ]
[ 163, 4 ]
[ 165, 57 ]
python
en
['en', 'en', 'en']
True
Env.set_seed
(self, seed: int)
Set random seed used by simulator. NOTE: This will not set seed for Python random or other packages' seed, such as NumPy. Args: seed (int): Seed to set.
Set random seed used by simulator.
def set_seed(self, seed: int): """Set random seed used by simulator. NOTE: This will not set seed for Python random or other packages' seed, such as NumPy. Args: seed (int): Seed to set. """ if seed is not None: sim_seed(seed)
[ "def", "set_seed", "(", "self", ",", "seed", ":", "int", ")", ":", "if", "seed", "is", "not", "None", ":", "sim_seed", "(", "seed", ")" ]
[ 167, 4 ]
[ 178, 26 ]
python
en
['en', 'et', 'en']
True
Env.metrics
(self)
Some statistics information provided by business engine. Returns: dict: Dictionary of metrics, content and format is determined by business engine.
Some statistics information provided by business engine.
def metrics(self) -> dict: """Some statistics information provided by business engine. Returns: dict: Dictionary of metrics, content and format is determined by business engine. """ return self._business_engine.get_metrics()
[ "def", "metrics", "(", "self", ")", "->", "dict", ":", "return", "self", ".", "_business_engine", ".", "get_metrics", "(", ")" ]
[ 181, 4 ]
[ 188, 50 ]
python
en
['en', 'en', 'en']
True
Env.get_finished_events
(self)
List[Event]: All events finished so far.
List[Event]: All events finished so far.
def get_finished_events(self): """List[Event]: All events finished so far.""" return self._event_buffer.get_finished_events()
[ "def", "get_finished_events", "(", "self", ")", ":", "return", "self", ".", "_event_buffer", ".", "get_finished_events", "(", ")" ]
[ 190, 4 ]
[ 192, 55 ]
python
en
['en', 'en', 'en']
True
Env.get_pending_events
(self, tick)
Pending events at certain tick. Args: tick (int): Specified tick to query.
Pending events at certain tick.
def get_pending_events(self, tick): """Pending events at certain tick. Args: tick (int): Specified tick to query. """ return self._event_buffer.get_pending_events(tick)
[ "def", "get_pending_events", "(", "self", ",", "tick", ")", ":", "return", "self", ".", "_event_buffer", ".", "get_pending_events", "(", "tick", ")" ]
[ 194, 4 ]
[ 200, 58 ]
python
en
['en', 'en', 'en']
True
Env._init_business_engine
(self)
Initialize business engine object. NOTE: 1. For built-in scenarios, they will always under "maro/simulator/scenarios" folder. 2. For external scenarios, the business engine instance is built with the loaded business engine class.
Initialize business engine object.
def _init_business_engine(self): """Initialize business engine object. NOTE: 1. For built-in scenarios, they will always under "maro/simulator/scenarios" folder. 2. For external scenarios, the business engine instance is built with the loaded business engine class. """ m...
[ "def", "_init_business_engine", "(", "self", ")", ":", "max_tick", "=", "self", ".", "_start_tick", "+", "self", ".", "_durations", "if", "self", ".", "_business_engine_cls", "is", "not", "None", ":", "business_class", "=", "self", ".", "_business_engine_cls", ...
[ 202, 4 ]
[ 240, 9 ]
python
en
['en', 'en', 'en']
True
Env._simulate
(self)
This is the generator to wrap each episode process.
This is the generator to wrap each episode process.
def _simulate(self): """This is the generator to wrap each episode process.""" is_end_tick = False self._streamit_episode += 1 streamit.episode(self._streamit_episode) while True: # Ask business engine to do thing for this tick, such as generating and pushing event...
[ "def", "_simulate", "(", "self", ")", ":", "is_end_tick", "=", "False", "self", ".", "_streamit_episode", "+=", "1", "streamit", ".", "episode", "(", "self", ".", "_streamit_episode", ")", "while", "True", ":", "# Ask business engine to do thing for this tick, such ...
[ 242, 4 ]
[ 327, 61 ]
python
en
['en', 'en', 'en']
True
restore_ts
()
Restore default TZ.
Restore default TZ.
def restore_ts(): """Restore default TZ.""" yield dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
[ "def", "restore_ts", "(", ")", ":", "yield", "dt_util", ".", "DEFAULT_TIME_ZONE", "=", "ORIG_TZ" ]
[ 12, 0 ]
[ 15, 39 ]
python
it
['it', 'nl', 'it']
True
test_intervals
(hass)
Test timing intervals of sensors.
Test timing intervals of sensors.
async def test_intervals(hass): """Test timing intervals of sensors.""" device = time_date.TimeDateSensor(hass, "time") now = dt_util.utc_from_timestamp(45.5) with patch("homeassistant.util.dt.utcnow", return_value=now): next_time = device.get_next_interval() assert next_time == dt_util.utc_...
[ "async", "def", "test_intervals", "(", "hass", ")", ":", "device", "=", "time_date", ".", "TimeDateSensor", "(", "hass", ",", "\"time\"", ")", "now", "=", "dt_util", ".", "utc_from_timestamp", "(", "45.5", ")", "with", "patch", "(", "\"homeassistant.util.dt.ut...
[ 19, 0 ]
[ 42, 26 ]
python
en
['en', 'da', 'en']
True
test_states
(hass)
Test states of sensors.
Test states of sensors.
async def test_states(hass): """Test states of sensors.""" now = dt_util.utc_from_timestamp(1495068856) device = time_date.TimeDateSensor(hass, "time") device._update_internal_state(now) assert device.state == "00:54" device = time_date.TimeDateSensor(hass, "date") device._update_internal_s...
[ "async", "def", "test_states", "(", "hass", ")", ":", "now", "=", "dt_util", ".", "utc_from_timestamp", "(", "1495068856", ")", "device", "=", "time_date", ".", "TimeDateSensor", "(", "hass", ",", "\"time\"", ")", "device", ".", "_update_internal_state", "(", ...
[ 45, 0 ]
[ 76, 48 ]
python
en
['en', 'en', 'en']
True
test_states_non_default_timezone
(hass)
Test states of sensors in a timezone other than UTC.
Test states of sensors in a timezone other than UTC.
async def test_states_non_default_timezone(hass): """Test states of sensors in a timezone other than UTC.""" new_tz = dt_util.get_time_zone("America/New_York") assert new_tz is not None dt_util.set_default_time_zone(new_tz) now = dt_util.utc_from_timestamp(1495068856) device = time_date.TimeDat...
[ "async", "def", "test_states_non_default_timezone", "(", "hass", ")", ":", "new_tz", "=", "dt_util", ".", "get_time_zone", "(", "\"America/New_York\"", ")", "assert", "new_tz", "is", "not", "None", "dt_util", ".", "set_default_time_zone", "(", "new_tz", ")", "now"...
[ 79, 0 ]
[ 112, 48 ]
python
en
['en', 'en', 'en']
True
test_timezone_intervals
(hass)
Test date sensor behavior in a timezone besides UTC.
Test date sensor behavior in a timezone besides UTC.
async def test_timezone_intervals(hass): """Test date sensor behavior in a timezone besides UTC.""" new_tz = dt_util.get_time_zone("America/New_York") assert new_tz is not None dt_util.set_default_time_zone(new_tz) device = time_date.TimeDateSensor(hass, "date") now = dt_util.utc_from_timestamp...
[ "async", "def", "test_timezone_intervals", "(", "hass", ")", ":", "new_tz", "=", "dt_util", ".", "get_time_zone", "(", "\"America/New_York\"", ")", "assert", "new_tz", "is", "not", "None", "dt_util", ".", "set_default_time_zone", "(", "new_tz", ")", "device", "=...
[ 116, 0 ]
[ 163, 85 ]
python
en
['en', 'sl', 'en']
True
test_timezone_intervals_empty_parameter
(hass)
Test get_interval() without parameters.
Test get_interval() without parameters.
async def test_timezone_intervals_empty_parameter(hass): """Test get_interval() without parameters.""" new_tz = dt_util.get_time_zone("America/Edmonton") assert new_tz is not None dt_util.set_default_time_zone(new_tz) device = time_date.TimeDateSensor(hass, "date") next_time = device.get_next_in...
[ "async", "def", "test_timezone_intervals_empty_parameter", "(", "hass", ")", ":", "new_tz", "=", "dt_util", ".", "get_time_zone", "(", "\"America/Edmonton\"", ")", "assert", "new_tz", "is", "not", "None", "dt_util", ".", "set_default_time_zone", "(", "new_tz", ")", ...
[ 170, 0 ]
[ 177, 85 ]
python
en
['en', 'en', 'en']
True
test_icons
(hass)
Test attributes of sensors.
Test attributes of sensors.
async def test_icons(hass): """Test attributes of sensors.""" device = time_date.TimeDateSensor(hass, "time") assert device.icon == "mdi:clock" device = time_date.TimeDateSensor(hass, "date") assert device.icon == "mdi:calendar" device = time_date.TimeDateSensor(hass, "date_time") assert dev...
[ "async", "def", "test_icons", "(", "hass", ")", ":", "device", "=", "time_date", ".", "TimeDateSensor", "(", "hass", ",", "\"time\"", ")", "assert", "device", ".", "icon", "==", "\"mdi:clock\"", "device", "=", "time_date", ".", "TimeDateSensor", "(", "hass",...
[ 180, 0 ]
[ 191, 46 ]
python
en
['en', 'en', 'en']
True
generate_ssp_set
(size, subset_size, sumto)
Generate random set of Decimals such that a subset sums to a given value. https://en.wikipedia.org/wiki/Subset_sum_problem
Generate random set of Decimals such that a subset sums to a given value. https://en.wikipedia.org/wiki/Subset_sum_problem
def generate_ssp_set(size, subset_size, sumto): """ Generate random set of Decimals such that a subset sums to a given value. https://en.wikipedia.org/wiki/Subset_sum_problem """ # Generate set with entries uniformly distributed between 0 and 2*average average = sumto / Decimal(size) ssp_se...
[ "def", "generate_ssp_set", "(", "size", ",", "subset_size", ",", "sumto", ")", ":", "# Generate set with entries uniformly distributed between 0 and 2*average", "average", "=", "sumto", "/", "Decimal", "(", "size", ")", "ssp_set", "=", "[", "Decimal", "(", "random", ...
[ 12, 0 ]
[ 33, 28 ]
python
en
['en', 'error', 'th']
False
keygen
()
Generate private and public keys for the "greased", bootstrappable encryption scheme. The main idea here is that we want to minimize computation during decryption because it originally contains an expensive modulus operation (c % p) that is too much for our somewhat homomorphic encryption system to ha...
Generate private and public keys for the "greased", bootstrappable encryption scheme. The main idea here is that we want to minimize computation during decryption because it originally contains an expensive modulus operation (c % p) that is too much for our somewhat homomorphic encryption system to ha...
def keygen(): """ Generate private and public keys for the "greased", bootstrappable encryption scheme. The main idea here is that we want to minimize computation during decryption because it originally contains an expensive modulus operation (c % p) that is too much for our somewhat homomorphic en...
[ "def", "keygen", "(", ")", ":", "# Generate a regular key pair", "p", ",", "pk_z", "=", "asymmetric", ".", "keygen", "(", ")", "# Generate a set of rational numbers such that a hidden subset sums to 1/p", "hint", "=", "(", "Decimal", "(", "1", ")", "/", "Decimal", "...
[ 36, 0 ]
[ 55, 27 ]
python
en
['en', 'error', 'th']
False
encrypt
(pk_z, pk_y, b)
Encrypt a bit b into an array of integers based on the provided public key.
Encrypt a bit b into an array of integers based on the provided public key.
def encrypt(pk_z, pk_y, b): """Encrypt a bit b into an array of integers based on the provided public key.""" # Perform regular asymmetric encryption c = asymmetric.encrypt(pk_z, b) # Post process the cypher text to generate the appropriate 1/p SPP set cy = post_process(c, pk_y) return (c, cy...
[ "def", "encrypt", "(", "pk_z", ",", "pk_y", ",", "b", ")", ":", "# Perform regular asymmetric encryption", "c", "=", "asymmetric", ".", "encrypt", "(", "pk_z", ",", "b", ")", "# Post process the cypher text to generate the appropriate 1/p SPP set", "cy", "=", "post_pr...
[ 58, 0 ]
[ 67, 18 ]
python
en
['en', 'en', 'en']
True
post_process
(c, pk_y)
Post-process the cyphertext with pk_y to simplify computation during decryption. We compute and return the 1/p SSP set for the provided cyphertext before decryption takes place. This is one of the key steps in making our homomorphic encryption scheme bootstrappable.
Post-process the cyphertext with pk_y to simplify computation during decryption. We compute and return the 1/p SSP set for the provided cyphertext before decryption takes place. This is one of the key steps in making our homomorphic encryption scheme bootstrappable.
def post_process(c, pk_y): """ Post-process the cyphertext with pk_y to simplify computation during decryption. We compute and return the 1/p SSP set for the provided cyphertext before decryption takes place. This is one of the key steps in making our homomorphic encryption scheme bootstrappable. ...
[ "def", "post_process", "(", "c", ",", "pk_y", ")", ":", "return", "[", "Decimal", "(", "c", ")", "*", "Decimal", "(", "y", ")", "for", "y", "in", "pk_y", "]" ]
[ 70, 0 ]
[ 77, 50 ]
python
en
['en', 'error', 'th']
False
decrypt
(sk, c, cy)
Decrypt a bit (c, cz) based on sk.
Decrypt a bit (c, cz) based on sk.
def decrypt(sk, c, cy): """Decrypt a bit (c, cz) based on sk.""" # Decode/compute hidden subset sum given secret key x = round(sum([cy[i] if sk[i] > 0 else 0 for i in range(HINT_SIZE)])) lsb_x = x & 1 lsb_c = c & 1 # XOR the least significant bits together return lsb_c ^ lsb_x
[ "def", "decrypt", "(", "sk", ",", "c", ",", "cy", ")", ":", "# Decode/compute hidden subset sum given secret key", "x", "=", "round", "(", "sum", "(", "[", "cy", "[", "i", "]", "if", "sk", "[", "i", "]", ">", "0", "else", "0", "for", "i", "in", "ra...
[ 80, 0 ]
[ 90, 24 ]
python
en
['en', 'cy', 'en']
True
validate_input
(hass: core.HomeAssistant, data)
Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.
Validate the user input allows us to connect.
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(hass) try: api = await async_get_api( data[CONF_USERNAME], data[...
[ "async", "def", "validate_input", "(", "hass", ":", "core", ".", "HomeAssistant", ",", "data", ")", ":", "session", "=", "async_get_clientsession", "(", "hass", ")", "try", ":", "api", "=", "await", "async_get_api", "(", "data", "[", "CONF_USERNAME", "]", ...
[ 18, 0 ]
[ 36, 47 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: await self.async_set_unique_id(user_input[CONF_USERNAME]) self._abort_if_unique_id_configured() try: info = await validate_i...
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "await", "self", ".", "async_set_unique_id", "(", "user_input", "[", "CONF_USERNAME", "]", ")",...
[ 45, 4 ]
[ 59, 9 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.setUp
(self)
Initialize values for this testcase class.
Initialize values for this testcase class.
def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.addCleanup(self.tear_down_cleanup)
[ "def", "setUp", "(", "self", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "addCleanup", "(", "self", ".", "tear_down_cleanup", ")" ]
[ 37, 4 ]
[ 40, 47 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.tear_down_cleanup
(self)
Clean up files and stop Home Assistant.
Clean up files and stop Home Assistant.
def tear_down_cleanup(self): """Clean up files and stop Home Assistant.""" data_file = self.hass.config.path(f"{feedreader.DOMAIN}.pickle") if exists(data_file): remove(data_file) self.hass.stop()
[ "def", "tear_down_cleanup", "(", "self", ")", ":", "data_file", "=", "self", ".", "hass", ".", "config", ".", "path", "(", "f\"{feedreader.DOMAIN}.pickle\"", ")", "if", "exists", "(", "data_file", ")", ":", "remove", "(", "data_file", ")", "self", ".", "ha...
[ 42, 4 ]
[ 47, 24 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_setup_one_feed
(self)
Test the general setup of this component.
Test the general setup of this component.
def test_setup_one_feed(self): """Test the general setup of this component.""" with patch( "homeassistant.components.feedreader.track_time_interval" ) as track_method: assert setup_component(self.hass, feedreader.DOMAIN, VALID_CONFIG_1) track_method.assert_cal...
[ "def", "test_setup_one_feed", "(", "self", ")", ":", "with", "patch", "(", "\"homeassistant.components.feedreader.track_time_interval\"", ")", "as", "track_method", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "feedreader", ".", "DOMAIN", ",", "V...
[ 49, 4 ]
[ 57, 13 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_setup_scan_interval
(self)
Test the setup of this component with scan interval.
Test the setup of this component with scan interval.
def test_setup_scan_interval(self): """Test the setup of this component with scan interval.""" with patch( "homeassistant.components.feedreader.track_time_interval" ) as track_method: assert setup_component(self.hass, feedreader.DOMAIN, VALID_CONFIG_2) track_m...
[ "def", "test_setup_scan_interval", "(", "self", ")", ":", "with", "patch", "(", "\"homeassistant.components.feedreader.track_time_interval\"", ")", "as", "track_method", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "feedreader", ".", "DOMAIN", ",",...
[ 59, 4 ]
[ 67, 13 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_setup_max_entries
(self)
Test the setup of this component with max entries.
Test the setup of this component with max entries.
def test_setup_max_entries(self): """Test the setup of this component with max entries.""" assert setup_component(self.hass, feedreader.DOMAIN, VALID_CONFIG_3)
[ "def", "test_setup_max_entries", "(", "self", ")", ":", "assert", "setup_component", "(", "self", ".", "hass", ",", "feedreader", ".", "DOMAIN", ",", "VALID_CONFIG_3", ")" ]
[ 69, 4 ]
[ 71, 76 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.setup_manager
(self, feed_data, max_entries=DEFAULT_MAX_ENTRIES)
Set up feed manager.
Set up feed manager.
def setup_manager(self, feed_data, max_entries=DEFAULT_MAX_ENTRIES): """Set up feed manager.""" events = [] @callback def record_event(event): """Add recorded event to set.""" events.append(event) self.hass.bus.listen(EVENT_FEEDREADER, record_event) ...
[ "def", "setup_manager", "(", "self", ",", "feed_data", ",", "max_entries", "=", "DEFAULT_MAX_ENTRIES", ")", ":", "events", "=", "[", "]", "@", "callback", "def", "record_event", "(", "event", ")", ":", "\"\"\"Add recorded event to set.\"\"\"", "events", ".", "ap...
[ 73, 4 ]
[ 104, 30 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed
(self)
Test simple feed with valid data.
Test simple feed with valid data.
def test_feed(self): """Test simple feed with valid data.""" feed_data = load_fixture("feedreader.xml") manager, events = self.setup_manager(feed_data) assert len(events) == 1 assert events[0].data.title == "Title 1" assert events[0].data.description == "Description 1" ...
[ "def", "test_feed", "(", "self", ")", ":", "feed_data", "=", "load_fixture", "(", "\"feedreader.xml\"", ")", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ")", "assert", "len", "(", "events", ")", "==", "1", "assert", "even...
[ 106, 4 ]
[ 120, 53 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed_updates
(self)
Test feed updates.
Test feed updates.
def test_feed_updates(self): """Test feed updates.""" # 1. Run feed_data = load_fixture("feedreader.xml") manager, events = self.setup_manager(feed_data) assert len(events) == 1 # 2. Run feed_data2 = load_fixture("feedreader1.xml") # Must patch 'get_timest...
[ "def", "test_feed_updates", "(", "self", ")", ":", "# 1. Run", "feed_data", "=", "load_fixture", "(", "\"feedreader.xml\"", ")", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ")", "assert", "len", "(", "events", ")", "==", "1...
[ 122, 4 ]
[ 145, 36 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed_default_max_length
(self)
Test long feed beyond the default 20 entry limit.
Test long feed beyond the default 20 entry limit.
def test_feed_default_max_length(self): """Test long feed beyond the default 20 entry limit.""" feed_data = load_fixture("feedreader2.xml") manager, events = self.setup_manager(feed_data) assert len(events) == 20
[ "def", "test_feed_default_max_length", "(", "self", ")", ":", "feed_data", "=", "load_fixture", "(", "\"feedreader2.xml\"", ")", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ")", "assert", "len", "(", "events", ")", "==", "20"...
[ 147, 4 ]
[ 151, 32 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed_max_length
(self)
Test long feed beyond a configured 5 entry limit.
Test long feed beyond a configured 5 entry limit.
def test_feed_max_length(self): """Test long feed beyond a configured 5 entry limit.""" feed_data = load_fixture("feedreader2.xml") manager, events = self.setup_manager(feed_data, max_entries=5) assert len(events) == 5
[ "def", "test_feed_max_length", "(", "self", ")", ":", "feed_data", "=", "load_fixture", "(", "\"feedreader2.xml\"", ")", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ",", "max_entries", "=", "5", ")", "assert", "len", "(", "...
[ 153, 4 ]
[ 157, 31 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed_without_publication_date_and_title
(self)
Test simple feed with entry without publication date and title.
Test simple feed with entry without publication date and title.
def test_feed_without_publication_date_and_title(self): """Test simple feed with entry without publication date and title.""" feed_data = load_fixture("feedreader3.xml") manager, events = self.setup_manager(feed_data) assert len(events) == 3
[ "def", "test_feed_without_publication_date_and_title", "(", "self", ")", ":", "feed_data", "=", "load_fixture", "(", "\"feedreader3.xml\"", ")", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ")", "assert", "len", "(", "events", ")"...
[ 159, 4 ]
[ 163, 31 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed_with_unrecognized_publication_date
(self)
Test simple feed with entry with unrecognized publication date.
Test simple feed with entry with unrecognized publication date.
def test_feed_with_unrecognized_publication_date(self): """Test simple feed with entry with unrecognized publication date.""" feed_data = load_fixture("feedreader4.xml") manager, events = self.setup_manager(feed_data) assert len(events) == 1
[ "def", "test_feed_with_unrecognized_publication_date", "(", "self", ")", ":", "feed_data", "=", "load_fixture", "(", "\"feedreader4.xml\"", ")", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ")", "assert", "len", "(", "events", ")"...
[ 165, 4 ]
[ 169, 31 ]
python
en
['en', 'en', 'en']
True
TestFeedreaderComponent.test_feed_invalid_data
(self)
Test feed with invalid data.
Test feed with invalid data.
def test_feed_invalid_data(self): """Test feed with invalid data.""" feed_data = "INVALID DATA" manager, events = self.setup_manager(feed_data) assert len(events) == 0 assert manager.last_update_successful is True
[ "def", "test_feed_invalid_data", "(", "self", ")", ":", "feed_data", "=", "\"INVALID DATA\"", "manager", ",", "events", "=", "self", ".", "setup_manager", "(", "feed_data", ")", "assert", "len", "(", "events", ")", "==", "0", "assert", "manager", ".", "last_...
[ 171, 4 ]
[ 176, 53 ]
python
en
['en', 'en', 'en']
True