_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q26300
activation
train
def activation(data: mx.sym.Symbol, act_type: str) -> mx.sym.Symbol: """ Apply custom or standard activation. Custom activation types include: - Swish-1, also called Sigmoid-Weighted Linear Unit (SiLU): Ramachandran et al. (https://arxiv.org/pdf/1710.05941.pdf), Elfwing et al. (https://a...
python
{ "resource": "" }
q26301
split_heads
train
def split_heads(x: mx.sym.Symbol, depth_per_head: int, heads: int) -> mx.sym.Symbol: """ Returns a symbol with head dimension folded into batch and depth divided by the number of heads. :param x: Symbol of shape (batch, length, depth). :param depth_per_head: Depth per head. :param heads: Number of ...
python
{ "resource": "" }
q26302
dot_attention
train
def dot_attention(queries: mx.sym.Symbol, keys: mx.sym.Symbol, values: mx.sym.Symbol, lengths: Optional[mx.sym.Symbol] = None, dropout: float = 0.0, bias: Optional[mx.sym.Symbol] = None, prefix: Optional[str] = '...
python
{ "resource": "" }
q26303
LengthRatio.average_sources
train
def average_sources(source_encoded: mx.sym.Symbol, source_encoded_length: mx.sym.Symbol) -> mx.nd.NDArray: """ Calculate the average of encoded sources taking into account their lengths. :param source_encoded: Encoder representation for n elements. Shape: (n, source_encoded_length, hidden_size)...
python
{ "resource": "" }
q26304
MultiHeadAttentionBase._attend
train
def _attend(self, queries: mx.sym.Symbol, keys: mx.sym.Symbol, values: mx.sym.Symbol, lengths: Optional[mx.sym.Symbol] = None, bias: Optional[mx.sym.Symbol] = None) -> mx.sym.Symbol: """ Returns context vectors of multi-head...
python
{ "resource": "" }
q26305
rerank
train
def rerank(args: argparse.Namespace): """ Reranks a list of hypotheses according to a sentence-level metric. Writes all output to STDOUT. :param args: Namespace object holding CLI arguments. """ reranker = Reranker(args.metric, args.return_score) with utils.smart_open(args.reference) as re...
python
{ "resource": "" }
q26306
main
train
def main(): """ Commandline interface to rerank nbest lists. """ log.setup_main_logger(console=True, file_logging=False) log.log_sockeye_version(logger) params = argparse.ArgumentParser(description="Rerank nbest lists of translations." " Rerankin...
python
{ "resource": "" }
q26307
Reranker.rerank
train
def rerank(self, hypotheses: Dict[str, Any], reference: str) -> Dict[str, Any]: """ Reranks a set of hypotheses that belong to one single reference translation. Uses stable sorting. :param hypotheses: Nbest translations. :param reference: A single string with the actual referenc...
python
{ "resource": "" }
q26308
Loss.get_loss
train
def get_loss(self, logits: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol: """ Returns loss and softmax output symbols given logits and integer-coded labels. :param logits: Shape: (batch_size * target_seq_len, target_vocab_size).
python
{ "resource": "" }
q26309
CrossEntropyLoss.get_loss
train
def get_loss(self, logits: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol: """ Returns loss symbol given logits and integer-coded labels. :param logits: Shape: (batch_size * target_seq_len, target_vocab_size). :param labels: Shape: (batch_size * target_seq_len,). :return...
python
{ "resource": "" }
q26310
MSELoss.get_loss
train
def get_loss(self, pred: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol: """ Returns MSE loss and output symbol given logits and expected integers as labels. :param pred: Predictions. Shape: (batch_size, 1). :param labels: Targets. Shape: (batch_size,). :return: Loss sym...
python
{ "resource": "" }
q26311
LengthRatioMSEMetric.update_dict
train
def update_dict(self, label: Dict, pred: Dict): """ If label is missing the right name, copy it from the prediction.
python
{ "resource": "" }
q26312
check_version
train
def check_version(version: str): """ Checks given version against code version and determines compatibility. Throws if versions are incompatible. :param version: Given version. """ code_version = parse_version(__version__) given_version = parse_version(version) check_condition(code_vers...
python
{ "resource": "" }
q26313
load_version
train
def load_version(fname: str) -> str: """ Loads version from file. :param fname: Name of file to load version from. :return: Version string. """ if not os.path.exists(fname):
python
{ "resource": "" }
q26314
parse_version
train
def parse_version(version_string: str) -> Tuple[str, str, str]: """ Parse version string into release, major, minor version. :param version_string: Version string. :return: Tuple of strings.
python
{ "resource": "" }
q26315
log_basic_info
train
def log_basic_info(args) -> None: """ Log basic information like version number, arguments, etc. :param args: Arguments as returned by argparse. """ log_sockeye_version(logger)
python
{ "resource": "" }
q26316
save_graph
train
def save_graph(symbol: mx.sym.Symbol, filename: str, hide_weights: bool = True): """ Dumps computation graph visualization to .pdf and .dot file. :param symbol: The symbol representing the computation graph. :param filename: The filename to save the graphic to.
python
{ "resource": "" }
q26317
compute_lengths
train
def compute_lengths(sequence_data: mx.sym.Symbol) -> mx.sym.Symbol: """ Computes sequence lengths of PAD_ID-padded data in sequence_data. :param sequence_data: Input data. Shape: (batch_size, seq_len). :return:
python
{ "resource": "" }
q26318
save_params
train
def save_params(arg_params: Mapping[str, mx.nd.NDArray], fname: str, aux_params: Optional[Mapping[str, mx.nd.NDArray]] = None): """ Saves the parameters to a file. :param arg_params: Mapping from parameter names to the actual parameters. :param fname: The file name to store the paramete...
python
{ "resource": "" }
q26319
load_params
train
def load_params(fname: str) -> Tuple[Dict[str, mx.nd.NDArray], Dict[str, mx.nd.NDArray]]: """ Loads parameters from a file. :param fname: The file containing the parameters. :return: Mapping from parameter names to the actual parameters for both the arg parameters and the aux parameters. """ sa...
python
{ "resource": "" }
q26320
get_tokens
train
def get_tokens(line: str) -> Iterator[str]: """ Yields tokens from input string. :param line: Input string. :return: Iterator over tokens. """
python
{ "resource": "" }
q26321
plot_attention
train
def plot_attention(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], filename: str): """ Uses matplotlib for creating a visualization of the attention matrix. :param attention_matrix: The attention matrix. :param source_tokens: A list of source tokens. :param target_...
python
{ "resource": "" }
q26322
print_attention_text
train
def print_attention_text(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], threshold: float): """ Prints the attention matrix to standard out. :param attention_matrix: The attention matrix. :param source_tokens: A list of source tokens. :para...
python
{ "resource": "" }
q26323
average_arrays
train
def average_arrays(arrays: List[mx.nd.NDArray]) -> mx.nd.NDArray: """ Take a list of arrays of the same shape and take the element wise average. :param arrays: A list of NDArrays with the same shape that will be averaged. :return: The average of the NDArrays in the same context as arrays[0]. """ ...
python
{ "resource": "" }
q26324
query_nvidia_smi
train
def query_nvidia_smi(device_ids: List[int], result_queue: multiprocessing.Queue) -> None: """ Runs nvidia-smi to determine the memory usage. :param device_ids: A list of devices for which the the memory usage will be queried. :param result_queue: The queue to which the result dictionary of device id ma...
python
{ "resource": "" }
q26325
get_gpu_memory_usage
train
def get_gpu_memory_usage(ctx: List[mx.context.Context]) -> Dict[int, Tuple[int, int]]: """ Returns used and total memory for GPUs identified by the given context list. :param ctx: List of MXNet context devices. :return: Dictionary of device id mapping to a tuple of (memory used, memory total). """ ...
python
{ "resource": "" }
q26326
acquire_gpus
train
def acquire_gpus(requested_device_ids: List[int], lock_dir: str = "/tmp", retry_wait_min: int = 10, retry_wait_rand: int = 60, num_gpus_available: Optional[int] = None): """ Acquire a number of GPUs in a transactional way. This method should be used inside a `with` statement. ...
python
{ "resource": "" }
q26327
parse_metrics_line
train
def parse_metrics_line(line_number: int, line: str) -> Dict[str, Any]: """ Parse a line of metrics into a mappings of key and values. :param line_number: Line's number for checking if checkpoints are aligned to it. :param line: A line from the Sockeye metrics file. :return: Dictionary of metric nam...
python
{ "resource": "" }
q26328
read_metrics_file
train
def read_metrics_file(path: str) -> List[Dict[str, Any]]: """ Reads lines metrics file and returns list of mappings of key and values. :param path: File to read metric values from. :return: Dictionary of metric names (e.g. perplexity-train) mapping to a list
python
{ "resource": "" }
q26329
write_metrics_file
train
def write_metrics_file(metrics: List[Dict[str, Any]], path: str): """ Write metrics data to tab-separated file. :param metrics: metrics data. :param path: Path to write to. """ with open(path, 'w') as metrics_out: for checkpoint, metric_dict in enumerate(metrics, 1): metrics...
python
{ "resource": "" }
q26330
grouper
train
def grouper(iterable: Iterable, size: int) -> Iterable: """ Collect data into fixed-length chunks or blocks without discarding underfilled chunks or padding them.
python
{ "resource": "" }
q26331
metric_value_is_better
train
def metric_value_is_better(new: float, old: float, metric: str) -> bool: """ Returns true if new value is strictly better than old for given metric. """
python
{ "resource": "" }
q26332
cleanup_params_files
train
def cleanup_params_files(output_folder: str, max_to_keep: int, checkpoint: int, best_checkpoint: int, keep_first: bool): """ Deletes oldest parameter files from a model folder. :param output_folder: Folder where param files are located. :param max_to_keep: Maximum number of files to keep, negative to k...
python
{ "resource": "" }
q26333
cast_conditionally
train
def cast_conditionally(data: mx.sym.Symbol, dtype: str) -> mx.sym.Symbol: """ Workaround until no-op cast will be fixed in MXNet codebase. Creates cast symbol only if dtype is different from default one, i.e. float32. :param data: Input symbol.
python
{ "resource": "" }
q26334
inflect
train
def inflect(word: str, count: int): """ Minimal inflection module. :param word: The word to inflect. :param count: The count. :return: The word,
python
{ "resource": "" }
q26335
get_coverage
train
def get_coverage(config: CoverageConfig) -> 'Coverage': """ Returns a Coverage instance. :param config: Coverage configuration. :return: Instance of Coverage. """ if config.type == C.COVERAGE_COUNT or config.type == C.COVERAGE_FERTILITY: utils.check_condition(config.num_hidden == 1, "Co...
python
{ "resource": "" }
q26336
mask_coverage
train
def mask_coverage(coverage: mx.sym.Symbol, source_length: mx.sym.Symbol) -> mx.sym.Symbol: """ Masks all coverage scores that are outside the actual sequence. :param coverage: Input coverage vector. Shape: (batch_size, seq_len, coverage_num_hidden). :param source_length: Source length. Shape: (batch_si...
python
{ "resource": "" }
q26337
bin_open
train
def bin_open(fname: str): """ Returns a file descriptor for a plain text or gzipped file, binary read mode for subprocess interaction. :param fname: The filename to open. :return: File descriptor
python
{ "resource": "" }
q26338
check_git
train
def check_git(): """Check if git command is available.""" try: with open(os.devnull, "wb") as devnull: subprocess.check_call(["git", "--version"], stdout=devnull, stderr=devnull)
python
{ "resource": "" }
q26339
checkout_subword_nmt
train
def checkout_subword_nmt(workspace_dir: str): """ Checkout subword-nmt implementation of byte-pair encoding. :param workspace_dir: Workspace third-party directory. """ # Prerequisites check_git() # Check cache dest = os.path.join(workspace_dir, DIR_THIRD_PARTY, SUBWORD_NMT_DEST) if ...
python
{ "resource": "" }
q26340
confirm_checkout
train
def confirm_checkout(dest: str, commit: str) -> bool: """ Confirm that git repository is checked out. :param dest: Local directory for checkout. :param commit: Git commit. :return: True if checkout is usable. """ usable = False if os.path.exists(dest): try: rev = sub...
python
{ "resource": "" }
q26341
call_moses_tokenizer
train
def call_moses_tokenizer(workspace_dir: str, input_fname: str, output_fname: str, lang_code: str, num_threads: int = 4): """ Call Moses tokenizer. :param workspace_dir: Workspace third-party directory where ...
python
{ "resource": "" }
q26342
call_moses_detokenizer
train
def call_moses_detokenizer(workspace_dir: str, input_fname: str, output_fname: str, lang_code: Optional[str] = None): """ Call Moses detokenizer. :param workspace_dir: Workspace third-party directory where Moses tokenizer is checked out. :param input_fname: Path of tokenized i...
python
{ "resource": "" }
q26343
call_learn_bpe
train
def call_learn_bpe(workspace_dir: str, source_fname: str, target_fname: str, model_fname: str, num_ops: int = 32000): """ Call script to learn byte-pair encoding model. :param workspace_dir: Workspace third-party directory where subword-nmt is checked out. :param source_fnam...
python
{ "resource": "" }
q26344
call_apply_bpe
train
def call_apply_bpe(workspace_dir: str, input_fname: str, output_fname: str, model_fname: str): """ Call BPE apply script. :param workspace_dir: Workspace directory where subword-nmt is checked out. :param input_fname: Path of tokenized input file, plain text or gzipped. :param output_fname: Path of...
python
{ "resource": "" }
q26345
merge_bpe
train
def merge_bpe(input_fname: str, output_fname: str): """ Merge byte-pair encoded sub-words. :param input_fname: Path of byte-pair encoded input file, plain text or gzipped. :param output_fname: Path of tokenized output file, plain text. """ with utils.smart_open(input_fna...
python
{ "resource": "" }
q26346
copy_out
train
def copy_out(source: Iterable[bytes], dest: io.BytesIO, use_placeholders: bool = False): """ Copy lines from source to destination. :param source: Source line iterable. :param dest: Destination open file. :param use_placeholders: When true, convert lines containing placeholders to ...
python
{ "resource": "" }
q26347
raw_corpus_bleu
train
def raw_corpus_bleu(hypotheses: Iterable[str], references: Iterable[str], offset: Optional[float] = 0.01) -> float: """ Simple wrapper around sacreBLEU's BLEU without tokenization and smoothing. :param hypotheses: Hypotheses stream. :param references: Reference stream.
python
{ "resource": "" }
q26348
raw_corpus_chrf
train
def raw_corpus_chrf(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around sacreBLEU's chrF implementation, without tokenization. :param hypotheses: Hypotheses stream.
python
{ "resource": "" }
q26349
raw_corpus_rouge1
train
def raw_corpus_rouge1(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around ROUGE-1 implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream.
python
{ "resource": "" }
q26350
raw_corpus_rouge2
train
def raw_corpus_rouge2(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around ROUGE-2 implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream.
python
{ "resource": "" }
q26351
raw_corpus_rougel
train
def raw_corpus_rougel(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around ROUGE-L implementation. :param hypotheses: Hypotheses stream. :param references: Reference stream.
python
{ "resource": "" }
q26352
raw_corpus_length_ratio
train
def raw_corpus_length_ratio(hypotheses: Iterable[str], references: Iterable[str]) -> float: """ Simple wrapper around length ratio implementation. :param hypotheses: Hypotheses stream.
python
{ "resource": "" }
q26353
ImageCaptioner.translate
train
def translate(self, trans_inputs: List[TranslatorInput]) -> List[TranslatorOutput]: """ Batch-translates a list of TranslatorInputs, returns a list of TranslatorOutputs. Splits oversized sentences to sentence chunks of size less than max_input_length. :param trans_inputs: List of Transl...
python
{ "resource": "" }
q26354
ImageCaptioner._get_inference_input
train
def _get_inference_input(self, trans_inputs: List[TranslatorInput]) -> Tuple[mx.nd.NDArray, int, Optional[lexicon.TopKLexicon], ...
python
{ "resource": "" }
q26355
TopKLexicon.save
train
def save(self, path: str): """ Save lexicon in Numpy array format. Lexicon will be specific to Sockeye model.
python
{ "resource": "" }
q26356
TopKLexicon.load
train
def load(self, path: str, k: Optional[int] = None): """ Load lexicon from Numpy array file. The top-k target ids will be sorted by increasing target id. :param path: Path to Numpy array file. :param k: Optionally load less items than stored in path. """ load_time_start =...
python
{ "resource": "" }
q26357
TopKLexicon.get_trg_ids
train
def get_trg_ids(self, src_ids: np.ndarray) -> np.ndarray: """ Lookup possible target ids for input sequence of source ids. :param src_ids: Sequence(s) of source ids (any shape). :return: Possible target ids for source (unique sorted, always includes special symbols). """ ...
python
{ "resource": "" }
q26358
setup_main_logger
train
def setup_main_logger(file_logging=True, console=True, path: Optional[str] = None, level=logging.INFO): """ Configures logging for the main application. :param file_logging: Whether to log to a file. :param console: Whether to log to the console. :param path: Optional path to write logfile to. ...
python
{ "resource": "" }
q26359
identify_raw_files
train
def identify_raw_files(task: Task, test_mode: bool = False) -> List[str]: """ Identify raw files that need to be downloaded for a given task. :param task: Sequence-to-sequence task. :param test_mode: Run in test mode, only downloading test data. :return: List of raw file names. """ raw_file...
python
{ "resource": "" }
q26360
download_extract_raw_files
train
def download_extract_raw_files(names: List[str], cache_dir: str, dest_dir: str): """ Download and extract raw files, making use of a cache directory. - Downloaded files are verified by MD5 sum. - Extraction overwrites existing files. :param names: List of raw file names in RAW_FILES. :param cac...
python
{ "resource": "" }
q26361
md5sum
train
def md5sum(fname: str) -> str: """Compute MD5 sum of file.""" with open(fname, "rb") as inp: md5 =
python
{ "resource": "" }
q26362
populate_parallel_text
train
def populate_parallel_text(extract_dir: str, file_sets: List[Tuple[str, str, str]], dest_prefix: str, keep_separate: bool, head_n: int = 0): """ Create raw parallel train, dev, or test files with a given ...
python
{ "resource": "" }
q26363
copy_parallel_text
train
def copy_parallel_text(file_list: List[str], dest_prefix: str): """ Copy pre-compiled raw parallel files with a given prefix. Perform whitespace character normalization to ensure that only ASCII newlines are considered line breaks. :param file_list: List of file pairs to use. :param dest_prefi...
python
{ "resource": "" }
q26364
renew_step_dir
train
def renew_step_dir(step_dir: str): """Delete step directory if exists and create, reporting actions.""" if os.path.exists(step_dir): logging.info("Remove unfinished step %s", step_dir)
python
{ "resource": "" }
q26365
call_sockeye_train
train
def call_sockeye_train(model: str, bpe_dir: str, model_dir: str, log_fname: str, num_gpus: int, test_mode: bool = False): """ Call sockeye.train with specified arguments on prepared inputs. Will r...
python
{ "resource": "" }
q26366
call_sockeye_average
train
def call_sockeye_average(model_dir: str, log_fname: str): """ Call sockeye.average with reasonable defaults. :param model_dir: Trained model directory. :param log_fname: Location to write log file. """ params_best_fname = os.path.join(model_dir, C.PARAMS_BEST_NAME) params_best_single_fname ...
python
{ "resource": "" }
q26367
call_sockeye_translate
train
def call_sockeye_translate(args: List[str], input_fname: str, output_fname: str, model_dir: str, log_fname: str, use_cpu: bool): """ Call sockeye.translate with specified argume...
python
{ "resource": "" }
q26368
call_sacrebleu
train
def call_sacrebleu(input_fname: str, ref_fname: str, output_fname: str, log_fname: str, tokenized: bool = False): """ Call pip-installed sacrebleu on tokenized or detokenized inputs. :param input_fname: Input translation file. :param ref_fname: Reference translation file. :param output_fname: Outpu...
python
{ "resource": "" }
q26369
print_command
train
def print_command(command: List[str], fname: str): """ Format and print command to file. :param command: Command in args list form. :param fname: File name to write out.
python
{ "resource": "" }
q26370
init_weight
train
def init_weight(weight: np.ndarray, vocab_in: Dict[str, int], vocab_out: Dict[str, int], initializer: mx.initializer.Initializer=mx.init.Constant(value=0.0)) -> mx.nd.NDArray: """ Initialize vocabulary-sized weight by existing values given input and output vocabul...
python
{ "resource": "" }
q26371
load_weight
train
def load_weight(weight_file: str, weight_name: str, weight_file_cache: Dict[str, Dict]) -> mx.nd.NDArray: """ Load wight fron a file or the cache if it was loaded before. :param weight_file: Weight file. :param weight_name: Weight name. :param weight_file_cache: Cach...
python
{ "resource": "" }
q26372
main
train
def main(): """ Commandline interface to initialize Sockeye embedding weights with pretrained word representations. """ setup_main_logger(console=True, file_logging=False) params = argparse.ArgumentParser(description='Quick usage: python3 -m sockeye.init_embedding ' ...
python
{ "resource": "" }
q26373
ScoringModel.run
train
def run(self, batch: mx.io.DataBatch) -> List[mx.nd.NDArray]: """ Runs the forward pass and returns the outputs. :param batch: The batch to run. :return: The grouped symbol (probs and target
python
{ "resource": "" }
q26374
vocab_to_json
train
def vocab_to_json(vocab: Vocab, path: str): """ Saves vocabulary in human-readable json. :param vocab: Vocabulary mapping. :param path: Output file path. """ with open(path, "w", encoding=C.VOCAB_ENCODING) as
python
{ "resource": "" }
q26375
vocab_from_json
train
def vocab_from_json(path: str, encoding: str = C.VOCAB_ENCODING) -> Vocab: """ Saves vocabulary in json format. :param path: Path to json file containing the vocabulary. :param encoding: Vocabulary encoding. :return: The loaded vocabulary. """ with open(path, encoding=encoding) as inp: ...
python
{ "resource": "" }
q26376
save_target_vocab
train
def save_target_vocab(target_vocab: Vocab, folder: str): """ Saves target vocabulary to folder. :param target_vocab: Target vocabulary. :param
python
{ "resource": "" }
q26377
load_source_vocabs
train
def load_source_vocabs(folder: str) -> List[Vocab]: """ Loads source vocabularies from folder. The first element in the list is the primary source vocabulary. Other elements correspond to optional additional source
python
{ "resource": "" }
q26378
load_target_vocab
train
def load_target_vocab(folder: str) -> Vocab: """ Loads target vocabulary from folder. :param folder: Source folder. :return: Target vocabulary
python
{ "resource": "" }
q26379
load_or_create_vocab
train
def load_or_create_vocab(data: str, vocab_path: Optional[str], num_words: int, word_min_count: int, pad_to_multiple_of: Optional[int] = None) -> Vocab: """ If the vocabulary path is defined, the vocabulary is loaded from the path. Otherwise, it is built from the data file. No writin...
python
{ "resource": "" }
q26380
reverse_vocab
train
def reverse_vocab(vocab: Vocab) -> InverseVocab: """ Returns value-to-key mapping from key-to-value-mapping.
python
{ "resource": "" }
q26381
get_ordered_tokens_from_vocab
train
def get_ordered_tokens_from_vocab(vocab: Vocab) -> List[str]: """ Returns the list of tokens in a vocabulary, ordered by increasing vocabulary id. :param vocab: Input vocabulary. :return:
python
{ "resource": "" }
q26382
make_inputs
train
def make_inputs(input_file: Optional[str], translator: inference.Translator, input_is_json: bool, input_factors: Optional[List[str]] = None) -> Generator[inference.TranslatorInput, None, None]: """ Generates TranslatorInput instances from input. If input is None, ...
python
{ "resource": "" }
q26383
read_and_translate
train
def read_and_translate(translator: inference.Translator, output_handler: OutputHandler, chunk_size: Optional[int], input_file: Optional[str] = None, input_factors: Optional[List[str]] = None, input_is_json...
python
{ "resource": "" }
q26384
translate
train
def translate(output_handler: OutputHandler, trans_inputs: List[inference.TranslatorInput], translator: inference.Translator) -> float: """ Translates each line from source_data, calling output handler after translating a batch. :param output_handler: A handler that will be call...
python
{ "resource": "" }
q26385
ConvolutionBlock.step
train
def step(self, data): """ Run convolution over a single position. The data must be exactly as wide as the convolution filters. :param data: Shape: (batch_size, kernel_width, num_hidden). :return: Single result of a convolution. Shape: (batch_size, 1, num_hidden). """ # ...
python
{ "resource": "" }
q26386
benchmark
train
def benchmark(cores, args): """ benchmark is used for Processing per core translation. Each core translates the whole input file. Return after all translations done. :param cores: the number of cores used for translation, each core will launch a thread to translate :param args: input parameters ...
python
{ "resource": "" }
q26387
split_file
train
def split_file(splitNum, fileInput, lines): """ split_file is used to split fileInput into splitNum small pieces file. For example, when splitNum is 56, a 112 lines file will be split into 56 files and each file has 2 lines. :param splitNum: split into splitNum files :param fileInput: file to be sp...
python
{ "resource": "" }
q26388
_indent
train
def _indent(indent=0, quote='', indent_char=' '): """Indent util function, compute new indent_string""" if indent > 0: indent_string = ''.join(( str(quote), (indent_char * (indent - len(quote))) )) else:
python
{ "resource": "" }
q26389
puts
train
def puts(s='', newline=True, stream=STDOUT): """Prints given string to stdout.""" max_width_ctx = _get_max_width_context() if max_width_ctx: cols, separator = max_width_ctx[-1] s = max_width(s, cols, separator) if newline: s = tsplit(s, NEWLINES) s = map(str, s)
python
{ "resource": "" }
q26390
puts_err
train
def puts_err(s='', newline=True, stream=STDERR):
python
{ "resource": "" }
q26391
console_width
train
def console_width(kwargs): """"Determine console_width.""" if sys.platform.startswith('win'): console_width = _find_windows_console_width() else:
python
{ "resource": "" }
q26392
AppDir._create
train
def _create(self): """Creates current AppDir at AppDir.path.""" self._raise_if_none() if not self._exists:
python
{ "resource": "" }
q26393
AppDir.open
train
def open(self, filename, mode='r'): """Returns file object from given filename.""" self._raise_if_none()
python
{ "resource": "" }
q26394
AppDir.append
train
def append(self, filename, content, binary=False): """Appends given content to given filename.""" self._raise_if_none() fn = path_join(self.path, filename) if binary: flags = 'ab'
python
{ "resource": "" }
q26395
AppDir.delete
train
def delete(self, filename=''): """Deletes given file or directory. If no filename is passed, current directory is removed. """ self._raise_if_none() fn = path_join(self.path, filename) try: if isfile(fn): remove(fn) else: ...
python
{ "resource": "" }
q26396
AppDir.read
train
def read(self, filename, binary=False): """Returns contents of given file with AppDir. If file doesn't exist, returns None.""" self._raise_if_none()
python
{ "resource": "" }
q26397
AppDir.sub
train
def sub(self, path): """Returns AppDir instance for given subdirectory name.""" if is_collection(path):
python
{ "resource": "" }
q26398
expand_path
train
def expand_path(path): """Expands directories and globs in given path.""" paths = [] path = os.path.expanduser(path) path = os.path.expandvars(path) if os.path.isdir(path): for (dir, dirs, files) in os.walk(path): for file
python
{ "resource": "" }
q26399
tsplit
train
def tsplit(string, delimiters): """Behaves str.split but supports tuples of delimiters.""" delimiters = tuple(delimiters) if len(delimiters) < 1: return [string,] final_delimiter
python
{ "resource": "" }