_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q26100
ESEDBParser.ParseFileObject
train
def ParseFileObject(self, parser_mediator, file_object): """Parses an ESE database file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. """ ese...
python
{ "resource": "" }
q26101
ChromeExtensionActivityPlugin.ParseActivityLogUncompressedRow
train
def ParseActivityLogUncompressedRow( self, parser_mediator, query, row, **unused_kwargs): """Parses an activity log row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the...
python
{ "resource": "" }
q26102
Sqlite3DatabaseFile.Close
train
def Close(self): """Closes the database file. Raises: RuntimeError: if the database is not opened. """ if not self._connection: raise RuntimeError('Cannot close database not opened.') # We need to run commit or not all
python
{ "resource": "" }
q26103
Sqlite3DatabaseFile.GetValues
train
def GetValues(self, table_names, column_names, condition): """Retrieves values from a table. Args: table_names (list[str]): table names. column_names (list[str]): column names. condition (str): query condition such as "log_source == 'Application Error'". Yields: sqlite3.r...
python
{ "resource": "" }
q26104
Sqlite3DatabaseFile.Open
train
def Open(self, filename, read_only=False): """Opens the database file. Args: filename (str): filename of the database. read_only (Optional[bool]): True if the database should be opened in read-only mode. Since sqlite3 does not support a real read-only mode we fake it by only per...
python
{ "resource": "" }
q26105
WinevtResourcesSqlite3DatabaseReader._GetEventLogProviderKey
train
def _GetEventLogProviderKey(self, log_source): """Retrieves the Event Log provider key. Args: log_source (str): Event Log source. Returns: str: Event Log provider key or None if not available. Raises: RuntimeError: if more than one value is found in the database. """ table_n...
python
{ "resource": "" }
q26106
WinevtResourcesSqlite3DatabaseReader._GetMessage
train
def _GetMessage(self, message_file_key, lcid, message_identifier): """Retrieves a specific message from a specific message table. Args: message_file_key (int): message file key. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str:...
python
{ "resource": "" }
q26107
WinevtResourcesSqlite3DatabaseReader._GetMessageFileKeys
train
def _GetMessageFileKeys(self, event_log_provider_key): """Retrieves the message file keys. Args: event_log_provider_key (int): Event Log provider key. Yields: int: message file key. """ table_names = ['message_file_per_event_log_provider'] column_names = ['message_file_key'] co...
python
{ "resource": "" }
q26108
WinevtResourcesSqlite3DatabaseReader._ReformatMessageString
train
def _ReformatMessageString(self, message_string): """Reformats the message string. Args: message_string (str): message string. Returns: str: message string in Python format() (PEP 3101) style. """ def _PlaceHolderSpecifierReplacer(match_object): """Replaces message string place h...
python
{ "resource": "" }
q26109
WinevtResourcesSqlite3DatabaseReader.GetMessage
train
def GetMessage(self, log_source, lcid, message_identifier): """Retrieves a specific message for a specific Event Log source. Args: log_source (str): Event Log source. lcid (int): language code identifier (LCID). message_identifier (int): message identifier. Returns: str: message st...
python
{ "resource": "" }
q26110
WinevtResourcesSqlite3DatabaseReader.GetMetadataAttribute
train
def GetMetadataAttribute(self, attribute_name): """Retrieves the metadata attribute. Args: attribute_name (str): name of the metadata attribute. Returns: str: the metadata attribute or None. Raises: RuntimeError: if more than one value is found in the database. """ table_nam...
python
{ "resource": "" }
q26111
WinevtResourcesSqlite3DatabaseReader.Open
train
def Open(self, filename): """Opens the database reader object. Args: filename (str): filename of the database. Returns: bool: True if successful. Raises: RuntimeError: if the version or string format of the database is not supported. """ if not super(Wine...
python
{ "resource": "" }
q26112
AnalysisReport.CopyToDict
train
def CopyToDict(self): """Copies the attribute container to a dictionary. Returns: dict[str, object]: attribute values per name. """ dictionary = {} for attribute_name, attribute_value in
python
{ "resource": "" }
q26113
AnalysisReport.GetString
train
def GetString(self): """Retrieves a string representation of the report. Returns: str: string representation of the report. """ string_list = [] string_list.append('Report generated from: {0:s}'.format(self.plugin_name)) time_compiled = getattr(self, 'time_compiled', 0) if time_compi...
python
{ "resource": "" }
q26114
BasePlugin.Process
train
def Process(self, parser_mediator, **kwargs): """Evaluates if this is the correct plugin and processes data accordingly. The purpose of the process function is to evaluate if this particular plugin is the correct one for the particular data structure at hand. This function accepts one value to use for ...
python
{ "resource": "" }
q26115
ConfigureLogging
train
def ConfigureLogging( debug_output=False, filename=None, mode='w', quiet_mode=False): """Configures the logging root logger. Args: debug_output (Optional[bool]): True if the logging should include debug output. filename (Optional[str]): log filename. mode (Optional[str]): log file access mo...
python
{ "resource": "" }
q26116
CompressedFileHandler._open
train
def _open(self): """Opens the compressed log file. Returns file: file-like object of the resulting stream. """ # The gzip module supports directly setting encoding as of Python 3.3. # pylint: disable=unexpected-keyword-arg if
python
{ "resource": "" }
q26117
Broker.shutdown
train
def shutdown(self): """ Stop broker instance. Closes all connected session, stop listening on network socket and free resources. """ try: self._sessions = dict() self._subscriptions = dict() self._retained_messages = dict() ...
python
{ "resource": "" }
q26118
MQTTClient.disconnect
train
def disconnect(self): """ Disconnect from the connected broker. This method sends a `DISCONNECT <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718090>`_ message and closes the network socket. This method is a *coroutine*. """ if ...
python
{ "resource": "" }
q26119
MQTTClient.reconnect
train
def reconnect(self, cleansession=None): """ Reconnect a previously connected broker. Reconnection tries to establish a network connection and send a `CONNECT <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028>`_ message. Retries interval and at...
python
{ "resource": "" }
q26120
MQTTClient.ping
train
def ping(self): """ Ping the broker. Send a MQTT `PINGREQ <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718081>`_ message for response. This method is a *coroutine*. """ if self.session.transitions.is_connected():
python
{ "resource": "" }
q26121
MQTTClient.publish
train
def publish(self, topic, message, qos=None, retain=None, ack_timeout=None): """ Publish a message to the broker. Send a MQTT `PUBLISH <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037>`_ message and wait for acknowledgment depending on Quality Of Service ...
python
{ "resource": "" }
q26122
MQTTClient.unsubscribe
train
def unsubscribe(self, topics): """ Unsubscribe from some topics. Send a MQTT `UNSUBSCRIBE <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718072>`_ message and wait for broker `UNSUBACK <http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc39...
python
{ "resource": "" }
q26123
MQTTClient.deliver_message
train
def deliver_message(self, timeout=None): """ Deliver next received message. Deliver next message received from the broker. If no message is available, this methods waits until next message arrives or ``timeout`` occurs. This method is a *coroutine*. :param time...
python
{ "resource": "" }
q26124
PluginManager.fire_event
train
def fire_event(self, event_name, wait=False, *args, **kwargs): """ Fire an event to plugins. PluginManager schedule @asyncio.coroutinecalls for each plugin on method called "on_" + event_name For example, on_connect will be called on event 'connect' Method calls are schedule in t...
python
{ "resource": "" }
q26125
BrokerSysPlugin._clear_stats
train
def _clear_stats(self): """ Initializes broker statistics data structures """ for stat in (STAT_BYTES_RECEIVED, STAT_BYTES_SENT, STAT_MSG_RECEIVED, STAT_MSG_SENT, STAT_CLIENTS_MAXIMUM, ...
python
{ "resource": "" }
q26126
WebSocketsWriter.drain
train
def drain(self): """ Let the write buffer of the underlying transport a chance to be flushed. """ data = self._stream.getvalue() if len(data):
python
{ "resource": "" }
q26127
search
train
def search(query, results=10, suggestion=False): ''' Do a Wikipedia search for `query`. Keyword arguments: * results - the maxmimum number of results returned * suggestion - if True, return results and suggestion (if any) in a tuple ''' search_params = { 'list': 'search', 'srprop': '', 'srl...
python
{ "resource": "" }
q26128
suggest
train
def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch']
python
{ "resource": "" }
q26129
random
train
def random(pages=1): ''' Get a list of random Wikipedia article titles. .. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. Keyword arguments: * pages - the number of random pages returned (max
python
{ "resource": "" }
q26130
_wiki_request
train
def _wiki_request(params): ''' Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. ''' global RATE_LIMIT_LAST_CALL global USER_AGENT params['format'] = 'json' if not 'action' in params: params['action'] = 'query' headers = { 'Use...
python
{ "resource": "" }
q26131
WikipediaPage.html
train
def html(self): ''' Get full page HTML. .. warning:: This can get pretty slow on long pages. ''' if not getattr(self, '_html', False): query_params = { 'prop': 'revisions', 'rvprop': 'content', 'rvlimit': 1, 'rvparse': '',
python
{ "resource": "" }
q26132
WikipediaPage.content
train
def content(self): ''' Plain text content of the page, excluding images, tables, and other data. ''' if not getattr(self, '_content', False): query_params = { 'prop': 'extracts|revisions', 'explaintext': '', 'rvprop': 'ids' } if not getattr(self, 'title', None)...
python
{ "resource": "" }
q26133
WikipediaPage.images
train
def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max',
python
{ "resource": "" }
q26134
WikipediaPage.references
train
def references(self): ''' List of URLs of external links on a page. May include external links within page that aren't technically cited anywhere. ''' if not getattr(self, '_references', False): def add_protocol(url): return url if url.startswith('http') else 'http:' + url self...
python
{ "resource": "" }
q26135
WikipediaPage.links
train
def links(self): ''' List of titles of Wikipedia page links on a page. .. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. ''' if not getattr(self, '_links', False): self._links = [ link['title']
python
{ "resource": "" }
q26136
WikipediaPage.categories
train
def categories(self): ''' List of categories of a page. ''' if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title']
python
{ "resource": "" }
q26137
WikipediaPage.sections
train
def sections(self): ''' List of section titles from the table of contents on the page. ''' if not getattr(self, '_sections', False): query_params = { 'action': 'parse', 'prop': 'sections', } query_params.update(self.__title_query_param)
python
{ "resource": "" }
q26138
WikipediaPage.section
train
def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that ha...
python
{ "resource": "" }
q26139
List.update
train
def update(self, render, force = False): """ Draw GUI that list active session """ if not force and not self._needUpdate: return self._needUpdate = False i = 0 drawArea = QtGui.QImage(self._width, self._height, render.getImageFormat()) ...
python
{ "resource": "" }
q26140
RDPRenderer.drawImage
train
def drawImage(self, image): """ Render of widget """ padding = image.width() % 4 for i in range(0, image.height()): tmp = image.copy(0, i, image.width() + padding, 1) #in RDP image or bottom top encoded ptr =
python
{ "resource": "" }
q26141
RFB.expectWithHeader
train
def expectWithHeader(self, expectedHeaderLen, callbackBody): """ 2nd level of waiting event read expectedHeaderLen that contain body size @param expectedHeaderLen: contains the number of bytes, which body length needs to be encoded
python
{ "resource": "" }
q26142
RFB.expectedBody
train
def expectedBody(self, data): """ Read header and wait header value to call next state @param data: Stream that length are to header length (1|2|4 bytes) set next state to callBack body when length read from header are received """ bodyLen = None if data.l...
python
{ "resource": "" }
q26143
RFB.readProtocolVersion
train
def readProtocolVersion(self, data): """ Read protocol version @param data: Stream may contain protocol version string (ProtocolVersion) """ data.readType(self._version)
python
{ "resource": "" }
q26144
RFB.recvSecurityList
train
def recvSecurityList(self, data): """ Read security list packet send from server to client @param data: Stream that contains well formed packet """ securityList = [] while data.dataLen() > 0: securityElement = UInt8() data.readType(securityElement)...
python
{ "resource": "" }
q26145
RFB.recvSecurityResult
train
def recvSecurityResult(self, data): """ Read security result packet Use by server to inform connection status of client @param data: Stream that contain well formed packet """ result = UInt32Be() data.readType(result) if result == UInt32Be(1): ...
python
{ "resource": "" }
q26146
RFB.recvServerInit
train
def recvServerInit(self, data): """ Read server init packet @param data: Stream that contains well formed packet """
python
{ "resource": "" }
q26147
dt_to_filetime
train
def dt_to_filetime(dt): """Converts a datetime to Microsoft filetime format. If the object is time zone-naive, it is forced to UTC before conversion. >>> "%.0f" % dt_to_filetime(datetime(2009, 7, 25, 23, 0)) '128930364000000000' >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc)) ...
python
{ "resource": "" }
q26148
filetime_to_dt
train
def filetime_to_dt(ft): """Converts a Microsoft filetime number to a Python datetime. The new datetime object is time zone-naive but is equivalent to tzinfo=utc. >>> filetime_to_dt(116444736000000000) datetime.datetime(1970, 1, 1, 0, 0) >>> filetime_to_dt(128930364000000000) datetime.datetime(...
python
{ "resource": "" }
q26149
des.__des_crypt
train
def __des_crypt(self, block, crypt_type): """Crypt the block of data through DES bit-manipulation""" block = self.__permutate(des.__ip, block) self.L = block[:32] self.R = block[32:] # Encryption starts from Kn[1] through to Kn[16] if crypt_type == des.ENCRYPT: ...
python
{ "resource": "" }
q26150
check_arg_compatibility
train
def check_arg_compatibility(args: argparse.Namespace): """ Check if some arguments are incompatible with each other. :param args: Arguments as returned by argparse. """ if args.lhuc is not None: # Actually this check is a bit too strict check_condition(args.encoder != C.CONVOLUTION...
python
{ "resource": "" }
q26151
check_resume
train
def check_resume(args: argparse.Namespace, output_folder: str) -> bool: """ Check if we should resume a broken training run. :param args: Arguments as returned by argparse. :param output_folder: Main output folder for the model. :return: Flag signaling if we are resuming training and the directory ...
python
{ "resource": "" }
q26152
use_shared_vocab
train
def use_shared_vocab(args: argparse.Namespace) -> bool: """ True if arguments entail a shared source and target vocabulary. :param: args: Arguments as returned by argparse. """ weight_tying = args.weight_tying weight_tying_type = args.weight_tying_type shared_vocab = args.shared_vocab d...
python
{ "resource": "" }
q26153
check_encoder_decoder_args
train
def check_encoder_decoder_args(args) -> None: """ Check possible encoder-decoder argument conflicts. :param args: Arguments as returned by argparse. """ encoder_embed_dropout, decoder_embed_dropout = args.embed_dropout encoder_rnn_dropout_inputs, decoder_rnn_dropout_inputs = args.rnn_dropout_in...
python
{ "resource": "" }
q26154
create_training_model
train
def create_training_model(config: model.ModelConfig, context: List[mx.Context], output_dir: str, train_iter: data_io.BaseParallelSampleIter, args: argparse.Namespace) -> training.TrainingModel: """ Create a t...
python
{ "resource": "" }
q26155
create_optimizer_config
train
def create_optimizer_config(args: argparse.Namespace, source_vocab_sizes: List[int], extra_initializers: List[Tuple[str, mx.initializer.Initializer]] = None) -> OptimizerConfig: """ Returns an OptimizerConfig. :param args: Arguments as returned by argparse. :param source_voc...
python
{ "resource": "" }
q26156
Config.freeze
train
def freeze(self): """ Freezes this Config object, disallowing modification or addition of any parameters. """ if getattr(self, '_frozen'):
python
{ "resource": "" }
q26157
Config.__del_frozen
train
def __del_frozen(self): """ Removes _frozen attribute from this instance and all its child configurations.
python
{ "resource": "" }
q26158
Config.__add_frozen
train
def __add_frozen(self): """ Adds _frozen attribute to this instance and all its child configurations.
python
{ "resource": "" }
q26159
Config.load
train
def load(fname: str) -> 'Config': """ Returns a Config object loaded from a file. The loaded object is not frozen. :param fname: Name of file to load the Config from. :return: Configuration. """
python
{ "resource": "" }
q26160
nearest_k
train
def nearest_k(similarity_matrix: mx.nd.NDArray, query_word_id: int, k: int, gamma: float = 1.0) -> Iterable[Tuple[int, float]]: """ Returns values and indices of k items with largest similarity. :param similarity_matrix: Similarity matrix. :param query_word_id:...
python
{ "resource": "" }
q26161
main
train
def main(): """ Command-line tool to inspect model embeddings. """ setup_main_logger(file_logging=False) params = argparse.ArgumentParser(description='Shows nearest neighbours of input tokens in the embedding space.') params.add_argument('--model', '-m', required=True, he...
python
{ "resource": "" }
q26162
_get_word_ngrams
train
def _get_word_ngrams(n, sentences): """Calculates word n-grams for multiple sentences. """ assert len(sentences) > 0 assert
python
{ "resource": "" }
q26163
rouge
train
def rouge(hypotheses, references): """Calculates average rouge scores for a list of hypotheses and references""" # Filter out hyps that are of 0 length # hyps_and_refs = zip(hypotheses, references) # hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0] # hypotheses, references = zip(*hyp...
python
{ "resource": "" }
q26164
rouge_1
train
def rouge_1(hypotheses, references): """ Calculate ROUGE-1 F1, precision, recall scores """ rouge_1 = [ rouge_n([hyp], [ref], 1) for hyp, ref in zip(hypotheses,
python
{ "resource": "" }
q26165
rouge_2
train
def rouge_2(hypotheses, references): """ Calculate ROUGE-2 F1, precision, recall scores """ rouge_2 = [ rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses,
python
{ "resource": "" }
q26166
rouge_l
train
def rouge_l(hypotheses, references): """ Calculate ROUGE-L F1, precision, recall scores """ rouge_l = [ rouge_l_sentence_level([hyp], [ref])
python
{ "resource": "" }
q26167
RawListTextDatasetLoader.load
train
def load(self, source_list: Iterable[List[str]], target_sentences: Iterable[List[Any]], num_samples_per_bucket: List[int]) -> 'ParallelDataSet': """ Creates a parallel dataset base on source list of strings and target sentences. Returns a `sockeye.data_io.P...
python
{ "resource": "" }
q26168
get_bank_sizes
train
def get_bank_sizes(num_constraints: int, beam_size: int, candidate_counts: List[int]) -> List[int]: """ Evenly distributes the beam across the banks, where each bank is a portion of the beam devoted to hypotheses having met the same number of constraints, 0..num_constra...
python
{ "resource": "" }
q26169
AvoidTrie.add_phrase
train
def add_phrase(self, phrase: List[int]) -> None: """ Recursively adds a phrase to this trie node. :param phrase: A list of word IDs to add to this trie node.
python
{ "resource": "" }
q26170
AvoidState.consume
train
def consume(self, word_id: int) -> 'AvoidState': """ Consumes a word, and updates the state based on it. Returns new objects on a state change. The next state for a word can be tricky. Here are the cases: (1) If the word is found in our set of outgoing child arcs, we take that transitio...
python
{ "resource": "" }
q26171
AvoidState.avoid
train
def avoid(self) -> Set[int]: """ Returns a set of word IDs that should be avoided. This includes the set of final states from the root node, which are single tokens that must never be generated.
python
{ "resource": "" }
q26172
AvoidBatch.consume
train
def consume(self, word_ids: mx.nd.NDArray) -> None: """ Consumes a word for each trie, updating respective states. :param word_ids: The set of word IDs. """ word_ids = word_ids.asnumpy().tolist() for i, word_id in enumerate(word_ids): if self.global_avoid_sta...
python
{ "resource": "" }
q26173
ConstrainedHypothesis.allowed
train
def allowed(self) -> Set[int]: """ Returns the set of constrained words that could follow this one. For unfinished phrasal constraints, it is the next word in the phrase. In other cases, it is the list of all unmet constraints. If all constraints are met, an empty set is returned...
python
{ "resource": "" }
q26174
SockeyeModel.load_config
train
def load_config(fname: str) -> ModelConfig: """ Loads model configuration. :param fname: Path to load model configuration from.
python
{ "resource": "" }
q26175
SockeyeModel.load_params_from_file
train
def load_params_from_file(self, fname: str): """ Loads and sets model parameters from file. :param fname: Path to load parameters from. """ utils.check_condition(os.path.exists(fname), "No model parameter file found under %s. " ...
python
{ "resource": "" }
q26176
SockeyeModel._get_embed_weights
train
def _get_embed_weights(self, prefix: str) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, mx.sym.Symbol]: """ Returns embedding parameters for source and target. When source and target embeddings are shared, they are created here and passed in to each side, instead of being created in the Embeddi...
python
{ "resource": "" }
q26177
models_max_input_output_length
train
def models_max_input_output_length(models: List[InferenceModel], num_stds: int, forced_max_input_len: Optional[int] = None, forced_max_output_len: Optional[int] = None) -> Tuple[int, Callable]: """ Returns a...
python
{ "resource": "" }
q26178
get_max_input_output_length
train
def get_max_input_output_length(supported_max_seq_len_source: Optional[int], supported_max_seq_len_target: Optional[int], training_max_seq_len_source: Optional[int], length_ratio_mean: float, ...
python
{ "resource": "" }
q26179
make_input_from_plain_string
train
def make_input_from_plain_string(sentence_id: SentenceId, string: str) -> TranslatorInput: """ Returns a TranslatorInput object from a plain string. :param sentence_id: Sentence id. :param string: An input
python
{ "resource": "" }
q26180
make_input_from_factored_string
train
def make_input_from_factored_string(sentence_id: SentenceId, factored_string: str, translator: 'Translator', delimiter: str = C.DEFAULT_FACTOR_DELIMITER) -> TranslatorInput: """ Returns a TranslatorInput ...
python
{ "resource": "" }
q26181
make_input_from_multiple_strings
train
def make_input_from_multiple_strings(sentence_id: SentenceId, strings: List[str]) -> TranslatorInput: """ Returns a TranslatorInput object from multiple strings, where the first element corresponds to the surface tokens and the remaining elements to additional factors. All strings must parse into token sequ...
python
{ "resource": "" }
q26182
empty_translation
train
def empty_translation(add_nbest: bool = False) -> Translation: """ Return an empty translation. :param add_nbest: Include (empty) nbest_translations in the translation object. """ return Translation(target_ids=[], attention_matrix=np.asarray([[0]]),
python
{ "resource": "" }
q26183
_concat_nbest_translations
train
def _concat_nbest_translations(translations: List[Translation], stop_ids: Set[int], length_penalty: LengthPenalty, brevity_penalty: Optional[BrevityPenalty] = None) -> Translation: """ Combines nbest translations through concatenation. :param tr...
python
{ "resource": "" }
q26184
_reduce_nbest_translations
train
def _reduce_nbest_translations(nbest_translations_list: List[Translation]) -> Translation: """ Combines Translation objects that are nbest translations of the same sentence. :param nbest_translations_list: A list of Translation objects, all of them translations of the same source sentence. :ret...
python
{ "resource": "" }
q26185
_expand_nbest_translation
train
def _expand_nbest_translation(translation: Translation) -> List[Translation]: """ Expand nbest translations in a single Translation object to one Translation object per nbest translation. :param translation: A Translation object. :return: A list of Translation objects. """ nbest_list = ...
python
{ "resource": "" }
q26186
_concat_translations
train
def _concat_translations(translations: List[Translation], stop_ids: Set[int], length_penalty: LengthPenalty, brevity_penalty: Optional[BrevityPenalty] = None) -> Translation: """ Combines translations through concatenation. :param t...
python
{ "resource": "" }
q26187
InferenceModel.initialize
train
def initialize(self, max_batch_size: int, max_input_length: int, get_max_output_length_function: Callable): """ Delayed construction of modules to ensure multiple Inference models can agree on computing a common maximum output length. :param max_batch_size: Maximum batch size. :...
python
{ "resource": "" }
q26188
InferenceModel._get_encoder_module
train
def _get_encoder_module(self) -> Tuple[mx.mod.BucketingModule, int]: """ Returns a BucketingModule for the encoder. Given a source sequence, it returns the initial decoder states of the model. The bucket key for this module is the length of the source sequence. :return: Tuple of...
python
{ "resource": "" }
q26189
InferenceModel._get_decoder_data_shapes
train
def _get_decoder_data_shapes(self, bucket_key: Tuple[int, int], batch_beam_size: int) -> List[mx.io.DataDesc]: """ Returns data shapes of the decoder module. :param bucket_key: Tuple of (maximum input length, maximum target length). :param batch_beam_size: Batch size * beam size. ...
python
{ "resource": "" }
q26190
InferenceModel.run_encoder
train
def run_encoder(self, source: mx.nd.NDArray, source_max_length: int) -> Tuple['ModelState', mx.nd.NDArray]: """ Runs forward pass of the encoder. Encodes source given source length and bucket key. Returns encoder representation of the source, sourc...
python
{ "resource": "" }
q26191
ModelState.sort_state
train
def sort_state(self, best_hyp_indices: mx.nd.NDArray): """ Sorts states according to k-best order from last step in beam search. """
python
{ "resource": "" }
q26192
Translator._log_linear_interpolation
train
def _log_linear_interpolation(predictions): """ Returns averaged and re-normalized log probabilities """ log_probs =
python
{ "resource": "" }
q26193
Translator._make_result
train
def _make_result(self, trans_input: TranslatorInput, translation: Translation) -> TranslatorOutput: """ Returns a translator result from generated target-side word ids, attention matrices and scores. Strips stop ids from translation string. :par...
python
{ "resource": "" }
q26194
Translator._translate_nd
train
def _translate_nd(self, source: mx.nd.NDArray, source_length: int, restrict_lexicon: Optional[lexicon.TopKLexicon], raw_constraints: List[Optional[constrained.RawConstraintList]], raw_avoid_list: List[Optional[...
python
{ "resource": "" }
q26195
Translator._encode
train
def _encode(self, sources: mx.nd.NDArray, source_length: int) -> Tuple[List[ModelState], mx.nd.NDArray]: """ Returns a ModelState for each model representing the state of the model after encoding the source. :param sources: Source ids. Shape: (batch_size, bucket_key, num_factors). :para...
python
{ "resource": "" }
q26196
Translator._get_best_word_indices_for_kth_hypotheses
train
def _get_best_word_indices_for_kth_hypotheses(ks: np.ndarray, all_hyp_indices: np.ndarray) -> np.ndarray: """ Traverses the matrix of best hypotheses indices collected during beam search in reversed order by using the kth hypotheses index as a backpointer. Returns an array containing the...
python
{ "resource": "" }
q26197
Translator._print_beam
train
def _print_beam(self, sequences: mx.nd.NDArray, accumulated_scores: mx.nd.NDArray, finished: mx.nd.NDArray, inactive: mx.nd.NDArray, constraints: List[Optional[constrained.ConstrainedHypothesis]], tim...
python
{ "resource": "" }
q26198
TopK.hybrid_forward
train
def hybrid_forward(self, F, scores, offset): """ Get the lowest k elements per sentence from a `scores` matrix. :param scores: Vocabulary scores for the next beam step. (batch_size * beam_size, target_vocabulary_size) :param offset: Array to add to the hypothesis indices for offsetting ...
python
{ "resource": "" }
q26199
SampleK.hybrid_forward
train
def hybrid_forward(self, F, scores, target_dists, finished, best_hyp_indices): """ Choose an extension of each hypothesis from its softmax distribution. :param scores: Vocabulary scores for the next beam step. (batch_size * beam_size, target_vocabulary_size) :param target_dists: The non...
python
{ "resource": "" }