Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def logging_config(logpath=None,
level=logging.DEBUG,
console_level=logging.INFO,
no_console=False):
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
... | [
"\n Config the logging.\n "
] |
Please provide a description of the function:def parse_args():
parser = argparse.ArgumentParser(
description='GloVe with GluonNLP',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Data options
group = parser.add_argument_group('Data arguments')
group.add_argument(
... | [
"Parse command line arguments."
] |
Please provide a description of the function:def get_train_data(args):
counter = dict()
with io.open(args.vocab, 'r', encoding='utf-8') as f:
for line in f:
token, count = line.split('\t')
counter[token] = int(count)
vocab = nlp.Vocab(counter, unknown_token=None, padding... | [
"Helper function to get training data."
] |
Please provide a description of the function:def train(args):
vocab, row, col, counts = get_train_data(args)
model = GloVe(token_to_idx=vocab.token_to_idx, output_dim=args.emsize,
dropout=args.dropout, x_max=args.x_max, alpha=args.alpha,
weight_initializer=mx.init.Unifor... | [
"Training helper."
] |
Please provide a description of the function:def log(args, kwargs):
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
... | [
"Log to a file."
] |
Please provide a description of the function:def hybrid_forward(self, F, row, col, counts):
emb_in = self.source_embedding(row)
emb_out = self.context_embedding(col)
if self._dropout:
emb_in = F.Dropout(emb_in, p=self._dropout)
emb_out = F.Dropout(emb_out, p=se... | [
"Compute embedding of words in batch.\n\n Parameters\n ----------\n row : mxnet.nd.NDArray or mxnet.sym.Symbol\n Array of token indices for source words. Shape (batch_size, ).\n row : mxnet.nd.NDArray or mxnet.sym.Symbol\n Array of token indices for context words. S... |
Please provide a description of the function:def update(self, labels, preds, masks=None):
# pylint: disable=arguments-differ
labels, preds = check_label_shapes(labels, preds, True)
masks = [None] * len(labels) if masks is None else masks
for label, pred_label, mask in zip(label... | [
"Updates the internal evaluation result.\n\n Parameters\n ----------\n labels : list of `NDArray`\n The labels of the data with class indices as values, one per sample.\n preds : list of `NDArray`\n Prediction values for samples. Each prediction value can either be ... |
Please provide a description of the function:def hybrid_forward(self, F, sentence1, sentence2):
feature1 = self.lin_proj(self.word_emb(sentence1))
feature2 = self.lin_proj(self.word_emb(sentence2))
if self.use_intra_attention:
feature1 = F.concat(feature1, self.intra_attenti... | [
"\n Predict the relation of two sentences.\n\n Parameters\n ----------\n sentence1 : NDArray\n Shape (batch_size, length)\n sentence2 : NDArray\n Shape (batch_size, length)\n\n Returns\n -------\n pred : NDArray\n Shape (batch_... |
Please provide a description of the function:def hybrid_forward(self, F, feature_a):
tilde_a = self.intra_attn_emb(feature_a)
e_matrix = F.batch_dot(tilde_a, tilde_a, transpose_b=True)
alpha = F.batch_dot(e_matrix.softmax(), tilde_a)
return alpha | [
"\n Compute intra-sentence attention given embedded words.\n\n Parameters\n ----------\n feature_a : NDArray\n Shape (batch_size, length, hidden_size)\n\n Returns\n -------\n alpha : NDArray\n Shape (batch_size, length, hidden_size)\n "
] |
Please provide a description of the function:def hybrid_forward(self, F, a, b):
# a.shape = [B, L1, H]
# b.shape = [B, L2, H]
# extract features
tilde_a = self.f(a) # shape = [B, L1, H]
tilde_b = self.f(b) # shape = [B, L2, H]
# attention
# e.shape = [B... | [
"\n Forward of Decomposable Attention layer\n "
] |
Please provide a description of the function:def count_tokens(tokens, to_lower=False, counter=None):
r
if to_lower:
tokens = [t.lower() for t in tokens]
if counter is None:
return Counter(tokens)
else:
counter.update(tokens)
return counter | [
"Counts tokens in the specified string.\n\n For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may\n look like::\n\n (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)\n\n\n Parameters\n ----------\n tokens : list of str\n A source... |
Please provide a description of the function:def slice_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0):
if length <= overlap:
raise ValueError('length needs to be larger than overlap')
if pad_last:
pad_len = _slice_pad_length(len(sequence), length, overlap)
... | [
"Slice a flat sequence of tokens into sequences tokens, with each\n inner sequence's length equal to the specified `length`, taking into account the requested\n sequence overlap.\n\n Parameters\n ----------\n sequence : list of object\n A flat list of tokens.\n length : int\n The len... |
Please provide a description of the function:def _slice_pad_length(num_items, length, overlap=0):
if length <= overlap:
raise ValueError('length needs to be larger than overlap')
step = length - overlap
span = num_items - length
residual = span % step
if residual:
return step -... | [
"Calculate the padding length needed for sliced samples in order not to discard data.\n\n Parameters\n ----------\n num_items : int\n Number of items in dataset before collating.\n length : int\n The length of each of the samples.\n overlap : int, default 0\n The extra number of ... |
Please provide a description of the function:def train_valid_split(dataset, valid_ratio=0.05):
if not 0.0 <= valid_ratio <= 1.0:
raise ValueError('valid_ratio should be in [0, 1]')
num_train = len(dataset)
num_valid = np.ceil(num_train * valid_ratio).astype('int')
indices = np.arange(num_t... | [
"Split the dataset into training and validation sets.\n\n Parameters\n ----------\n dataset : list\n A list of training samples.\n valid_ratio : float, default 0.05\n Proportion of training samples to use for validation set\n range: [0, 1]\n\n Returns\n -------\n train : Si... |
Please provide a description of the function:def _load_pretrained_vocab(name, root=os.path.join(get_home_dir(), 'models'), cls=None):
file_name = '{name}-{short_hash}'.format(name=name,
short_hash=short_hash(name))
root = os.path.expanduser(root)
file_path =... | [
"Load the accompanying vocabulary object for pre-trained model.\n\n Parameters\n ----------\n name : str\n Name of the vocabulary, usually the name of the dataset.\n root : str, default '$MXNET_HOME/models'\n Location for keeping the model parameters.\n MXNET_HOME defaults to '~/.mx... |
Please provide a description of the function:def _extract_archive(file, target_dir):
if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tgz'):
archive = tarfile.open(file, 'r')
elif file.endswith('.zip'):
archive = zipfile.ZipFile(file, 'r')
else:
raise Exceptio... | [
"Extract archive file\n\n Parameters\n ----------\n file : str\n Absolute path of the archive file.\n target_dir : str\n Target directory of the archive to be uncompressed\n\n "
] |
Please provide a description of the function:def discard(self, min_freq, unknown_token):
freq = 0
ret = Counter({})
for token, count in self.items():
if count < min_freq:
freq += count
else:
ret[token] = count
ret[unknown_t... | [
"Discards tokens with frequency below min_frequency and represents them\n as `unknown_token`.\n\n Parameters\n ----------\n min_freq: int\n Tokens whose frequency is under min_freq is counted as `unknown_token` in\n the Counter returned.\n unknown_token: str\... |
Please provide a description of the function:def train():
trainer = gluon.Trainer(model.collect_params(), args.optimizer,
{'learning_rate': args.lr, 'beta2': 0.98, 'epsilon': 1e-9})
train_data_loader, val_data_loader, test_data_loader \
= dataprocessor.make_dataloader(d... | [
"Training function."
] |
Please provide a description of the function:def hybrid_forward(self, F, inputs, **kwargs):
# pylint: disable=unused-argument
r
current_input = inputs
for layer in self.hnet:
projected_input = layer(current_input)
linear_transform = current_input
nonli... | [
"\n Forward computation for highway layer\n\n Parameters\n ----------\n inputs: NDArray\n The input tensor is of shape `(..., input_size)`.\n\n Returns\n ----------\n outputs: NDArray\n The output tensor is of the same shape with input tensor `(... |
Please provide a description of the function:def forward(self, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ
bert_output = self.bert(inputs, token_types, valid_length)
output = self.span_classifier(bert_output)
return output | [
"Generate the unnormalized score for the given the input sequences.\n\n Parameters\n ----------\n inputs : NDArray, shape (batch_size, seq_length)\n Input words for the sequences.\n token_types : NDArray, shape (batch_size, seq_length)\n Token types for the sequence... |
Please provide a description of the function:def hybrid_forward(self, F, inputs, states=None, mask=None):
# pylint: disable=arguments-differ
# pylint: disable=unused-argument
states_forward, states_backward = states
if mask is not None:
sequence_length = mask.sum(axi... | [
"Defines the forward computation for cache cell. Arguments can be either\n :py:class:`NDArray` or :py:class:`Symbol`.\n\n Parameters\n ----------\n inputs : NDArray\n The input data layout='TNC'.\n states : Tuple[List[List[NDArray]]]\n The states. including:\... |
Please provide a description of the function:def main(args):
examples = []
with open(args.input, 'r') as fin:
reader = csv.DictReader(fin, delimiter='\t')
for cols in reader:
s1 = read_tokens(cols['sentence1_parse'])
s2 = read_tokens(cols['sentence2_parse'])
... | [
"\n Read tokens from the provided parse tree in the SNLI dataset.\n Illegal examples are removed.\n "
] |
Please provide a description of the function:def _recenter(self):
for split_idx in range(len(self._splits)):
split = self._splits[split_idx]
len_idx = self._split2len_idx[split]
if split == self._splits[-1]:
continue
right_split = self._sp... | [
"\n one iteration of k-means\n "
] |
Please provide a description of the function:def _reindex(self):
self._len2split_idx = {}
last_split = -1
for split_idx, split in enumerate(self._splits):
self._len2split_idx.update(
dict(list(zip(list(range(last_split + 1, split)), [split_idx] * (split - (la... | [
"\n Index every sentence into a cluster\n "
] |
Please provide a description of the function:def get_gnmt_encoder_decoder(cell_type='lstm', attention_cell='scaled_luong', num_layers=2,
num_bi_layers=1, hidden_size=128, dropout=0.0, use_residual=False,
i2h_weight_initializer=None, h2h_weight_initializer=None,
... | [
"Build a pair of GNMT encoder/decoder\n\n Parameters\n ----------\n cell_type : str or type\n attention_cell : str or AttentionCell\n num_layers : int\n num_bi_layers : int\n hidden_size : int\n dropout : float\n use_residual : bool\n i2h_weight_initializer : mx.init.Initializer or Non... |
Please provide a description of the function:def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None):
mem_value, rnn_states = encoder_outputs
batch_size, _, mem_size = mem_value.shape
attention_vec = mx.nd.zeros(shape=(batch_size, mem_size), ctx=mem_value.context)
... | [
"Initialize the state from the encoder outputs.\n\n Parameters\n ----------\n encoder_outputs : list\n encoder_valid_length : NDArray or None\n\n Returns\n -------\n decoder_states : list\n The decoder states, includes:\n\n - rnn_states : NDArra... |
Please provide a description of the function:def decode_seq(self, inputs, states, valid_length=None):
length = inputs.shape[1]
output = []
additional_outputs = []
inputs = _as_list(mx.nd.split(inputs, num_outputs=length, axis=1, squeeze_axis=True))
rnn_states_l = []
... | [
"Decode the decoder inputs. This function is only used for training.\n\n Parameters\n ----------\n inputs : NDArray, Shape (batch_size, length, C_in)\n states : list of NDArrays or None\n Initial states. The list of initial decoder states\n valid_length : NDArray or Non... |
Please provide a description of the function:def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True):
pad = tokenizer.convert_tokens_to_ids(['[PAD]'])[0]
input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
input_mask = [1] * len(input_ids)
segment_ids = lis... | [
"Transform instance to inputs for MLM and NSP."
] |
Please provide a description of the function:def write_to_files_np(features, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
# pylint: disable=unused-argument
next_sentence_labels = []
valid_lengths = []
assert len(output_files) == 1, 'numpy format only sup... | [
"Write to numpy files from `TrainingInstance`s."
] |
Please provide a description of the function:def write_to_files_rec(instances, tokenizer, max_seq_length,
max_predictions_per_seq, output_files):
writers = []
for output_file in output_files:
writers.append(
mx.recordio.MXIndexedRecordIO(
os.path.s... | [
"Create IndexedRecordIO files from `TrainingInstance`s."
] |
Please provide a description of the function:def create_training_instances(x):
(input_files, out, tokenizer, max_seq_length, dupe_factor,
short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng) = x
time_start = time.time()
logging.info('Processing %s', input_files)
all_documents = [[]]
... | [
"Create `TrainingInstance`s from raw text."
] |
Please provide a description of the function:def create_instances_from_document(
all_documents, document_index, max_seq_length, short_seq_prob,
masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
document = all_documents[document_index]
# Account for [CLS], [SEP], [SEP]
max_num... | [
"Creates `TrainingInstance`s for a single document."
] |
Please provide a description of the function:def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
cand_indexes = []
for (i, token) in enumerate(tokens):
if token in ['[CLS]', '[SEP]']:
continue
can... | [
"Creates the predictions for the masked LM objective."
] |
Please provide a description of the function:def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_num_tokens:
break
trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else token... | [
"Truncates a pair of sequences to a maximum sequence length."
] |
Please provide a description of the function:def main():
time_start = time.time()
logging.info('loading vocab file from dataset: %s', args.vocab)
vocab_obj = nlp.data.utils._load_pretrained_vocab(args.vocab)
tokenizer = BERTTokenizer(
vocab=vocab_obj, lower='uncased' in args.vocab)
inp... | [
"Main function."
] |
Please provide a description of the function:def convert_vocab(vocab_file):
original_vocab = load_vocab(vocab_file)
token_to_idx = dict(original_vocab)
num_tokens = len(token_to_idx)
idx_to_token = [None] * len(original_vocab)
for word in original_vocab:
idx = int(original_vocab[word])
... | [
"GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab."
] |
Please provide a description of the function:def read_tf_checkpoint(path):
from tensorflow.python import pywrap_tensorflow
tensors = {}
reader = pywrap_tensorflow.NewCheckpointReader(path)
var_to_shape_map = reader.get_variable_to_shape_map()
for key in sorted(var_to_shape_map):
tensor ... | [
"read tensorflow checkpoint"
] |
Please provide a description of the function:def profile(curr_step, start_step, end_step, profile_name='profile.json',
early_exit=True):
if curr_step == start_step:
mx.nd.waitall()
mx.profiler.set_config(profile_memory=False, profile_symbolic=True,
pro... | [
"profile the program between [start_step, end_step)."
] |
Please provide a description of the function:def load_vocab(vocab_file):
vocab = collections.OrderedDict()
index = 0
with io.open(vocab_file, 'r') as reader:
while True:
token = reader.readline()
if not token:
break
token = token.strip()
... | [
"Loads a vocabulary file into a dictionary."
] |
Please provide a description of the function:def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
r
if mask is not None:
inputs = F.broadcast_mul(inputs, mask.expand_dims(-1))
inputs = F.transpose(inputs, axes=(1, 2, 0))
output = self._convs(in... | [
"\n Forward computation for char_encoder\n\n Parameters\n ----------\n inputs: NDArray\n The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC.\n mask: NDArray\n The mask applied to the input of shape `(seq_len, batch_size)`, the mask will\... |
Please provide a description of the function:def _position_encoding_init(max_length, dim):
position_enc = np.arange(max_length).reshape((-1, 1)) \
/ (np.power(10000, (2. / dim) * np.arange(dim).reshape((1, -1))))
# Apply the cosine to even columns and sin to odds.
position_enc[:, 0::... | [
"Init the sinusoid position encoding table "
] |
Please provide a description of the function:def get_transformer_encoder_decoder(num_layers=2,
num_heads=8, scaled=True,
units=512, hidden_size=2048, dropout=0.0, use_residual=True,
max_src_length=50, max_tgt_len... | [
"Build a pair of Parallel Transformer encoder/decoder\n\n Parameters\n ----------\n num_layers : int\n num_heads : int\n scaled : bool\n units : int\n hidden_size : int\n dropout : float\n use_residual : bool\n max_src_length : int\n max_tgt_length : int\n weight_initializer : mx... |
Please provide a description of the function:def transformer_en_de_512(dataset_name=None, src_vocab=None, tgt_vocab=None, pretrained=False,
ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r
predefined_args = {'num_units': 512,
'hidden_size': 20... | [
"Transformer pretrained model.\n\n Embedding size is 400, and hidden layer size is 1150.\n\n Parameters\n ----------\n dataset_name : str or None, default None\n src_vocab : gluonnlp.Vocab or None, default None\n tgt_vocab : gluonnlp.Vocab or None, default None\n pretrained : bool, default Fals... |
Please provide a description of the function:def _get_activation(self, act):
if isinstance(act, str):
if act.lower() == 'gelu':
return GELU()
else:
return gluon.nn.Activation(act)
assert isinstance(act, gluon.Block)
return act | [
"Get activation block based on the name. "
] |
Please provide a description of the function:def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
outputs = self.ffn_1(inputs)
if self.activation:
outputs = self.activation(outputs)
outputs = self.ffn_2(outputs)
... | [
"Position-wise encoding of the inputs.\n\n Parameters\n ----------\n inputs : Symbol or NDArray\n Input sequence. Shape (batch_size, length, C_in)\n\n Returns\n -------\n outputs : Symbol or NDArray\n Shape (batch_size, length, C_out)\n "
] |
Please provide a description of the function:def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
outputs, attention_weights =\
self.attention_cell(inputs, inputs, inputs, mask)
outputs = self.proj(outputs)
... | [
"Transformer Encoder Attention Cell.\n\n Parameters\n ----------\n inputs : Symbol or NDArray\n Input sequence. Shape (batch_size, length, C_in)\n mask : Symbol or NDArray or None\n Mask for inputs. Shape (batch_size, length, length)\n\n Returns\n ----... |
Please provide a description of the function:def hybrid_forward(self, F, inputs, mem_value, mask=None, mem_mask=None): #pylint: disable=unused-argument
# pylint: disable=arguments-differ
outputs, attention_in_outputs =\
self.attention_cell_in(inputs, inputs, inputs, mask)
... | [
"Transformer Decoder Attention Cell.\n\n Parameters\n ----------\n inputs : Symbol or NDArray\n Input sequence. Shape (batch_size, length, C_in)\n mem_value : Symbol or NDArrays\n Memory value, i.e. output of the encoder. Shape (batch_size, mem_length, C_in)\n ... |
Please provide a description of the function:def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None):
mem_value = encoder_outputs
decoder_states = [mem_value]
mem_length = mem_value.shape[1]
if encoder_valid_length is not None:
dtype = encoder_v... | [
"Initialize the state from the encoder outputs.\n\n Parameters\n ----------\n encoder_outputs : list\n encoder_valid_length : NDArray or None\n\n Returns\n -------\n decoder_states : list\n The decoder states, includes:\n\n - mem_value : NDArray... |
Please provide a description of the function:def decode_seq(self, inputs, states, valid_length=None):
batch_size = inputs.shape[0]
length = inputs.shape[1]
length_array = mx.nd.arange(length, ctx=inputs.context, dtype=inputs.dtype)
mask = mx.nd.broadcast_lesser_equal(
... | [
"Decode the decoder inputs. This function is only used for training.\n\n Parameters\n ----------\n inputs : NDArray, Shape (batch_size, length, C_in)\n states : list of NDArrays or None\n Initial states. The list of decoder states\n valid_length : NDArray or None\n ... |
Please provide a description of the function:def forward_backward(self, x):
(src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x
with mx.autograd.record():
out, _ = self._model(src_seq, tgt_seq[:, :-1],
src_valid_length, tgt_valid_l... | [
"Perform forward and backward computation for a batch of src seq and dst seq"
] |
Please provide a description of the function:def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu-id', type=int, default=0,
help='GPU id (-1 means CPU)')
parser.add_argument('--train-file', default='snli_1.0/snli_1.0_train.txt',
... | [
"\n Parse arguments.\n "
] |
Please provide a description of the function:def train_model(model, train_data_loader, val_data_loader, embedding, ctx, args):
logger.info(vars(args))
# Initialization
model.hybridize()
model.collect_params().initialize(mx.init.Normal(0.01), ctx=ctx)
model.word_emb.weight.set_data(embedding.id... | [
"\n Train model and validate/save every epoch.\n "
] |
Please provide a description of the function:def main(args):
json.dump(vars(args), open(os.path.join(args.output_dir, 'config.json'), 'w'))
if args.gpu_id == -1:
ctx = mx.cpu()
else:
ctx = mx.gpu(args.gpu_id)
mx.random.seed(args.seed, ctx=ctx)
if args.mode == 'train':
... | [
"\n Entry point: train or test.\n "
] |
Please provide a description of the function:def hybrid_forward(self, F, candidates_like, prob, alias):
# pylint: disable=unused-argument
flat_shape = functools.reduce(operator.mul, self._shape)
idx = F.random.uniform(low=0, high=self.N, shape=flat_shape,
... | [
"Draw samples from uniform distribution and return sampled candidates.\n\n Parameters\n ----------\n candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol\n This input specifies the shape of the to be sampled candidates. #\n TODO shape selection is not yet supported. Shape... |
Please provide a description of the function:def add(
self,
sink,
*,
level=_defaults.LOGURU_LEVEL,
format=_defaults.LOGURU_FORMAT,
filter=_defaults.LOGURU_FILTER,
colorize=_defaults.LOGURU_COLORIZE,
serialize=_defaults.LOGURU_SERIALIZE,
backtrace=_... | [
"Add a handler sending log messages to a sink adequately configured.\n\n Parameters\n ----------\n sink : |file-like object|_, |str|, |Path|, |function|_, |Handler| or |class|_\n An object in charge of receiving formatted logging messages and propagating them to an\n appro... |
Please provide a description of the function:def remove(self, handler_id=None):
with self._lock:
handlers = self._handlers.copy()
if handler_id is None:
for handler in handlers.values():
handler.stop()
handlers.clear()
... | [
"Remove a previously added handler and stop sending logs to its sink.\n\n Parameters\n ----------\n handler_id : |int| or ``None``\n The id of the sink to remove, as it was returned by the |add| method. If ``None``, all\n handlers are removed. The pre-configured handler is... |
Please provide a description of the function:def catch(
self,
exception=Exception,
*,
level="ERROR",
reraise=False,
message="An error has been caught in function '{record[function]}', "
"process '{record[process].name}' ({record[process].id}), "
"thread '{... | [
"Return a decorator to automatically log possibly caught error in wrapped function.\n\n This is useful to ensure unexpected exceptions are logged, the entire program can be\n wrapped by this method. This is also very useful to decorate |Thread.run| methods while\n using threads to propagate err... |
Please provide a description of the function:def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0):
r
return Logger(self._extra, exception, record, lazy, ansi, raw, depth) | [
"Parametrize a logging call to slightly change generated log message.\n\n Parameters\n ----------\n exception : |bool|, |tuple| or |Exception|, optional\n If it does not evaluate as ``False``, the passed exception is formatted and added to the\n log message. It could be an... |
Please provide a description of the function:def bind(_self, **kwargs):
return Logger(
{**_self._extra, **kwargs},
_self._exception,
_self._record,
_self._lazy,
_self._ansi,
_self._raw,
_self._depth,
) | [
"Bind attributes to the ``extra`` dict of each logged message record.\n\n This is used to add custom context to each logging call.\n\n Parameters\n ----------\n **kwargs\n Mapping between keys and values that will be added to the ``extra`` dict.\n\n Returns\n ---... |
Please provide a description of the function:def level(self, name, no=None, color=None, icon=None):
if not isinstance(name, str):
raise ValueError(
"Invalid level name, it should be a string, not: '%s'" % type(name).__name__
)
if no is color is icon is N... | [
"Add, update or retrieve a logging level.\n\n Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``\n and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom\n level, you should necessarily use its name, the severity number is ... |
Please provide a description of the function:def configure(self, *, handlers=None, levels=None, extra=None, activation=None):
if handlers is not None:
self.remove()
else:
handlers = []
if levels is not None:
for params in levels:
self... | [
"Configure the core logger.\n\n It should be noted that ``extra`` values set using this function are available across all\n modules, so this is the best way to set overall default values.\n\n Parameters\n ----------\n handlers : |list| of |dict|, optional\n A list of ea... |
Please provide a description of the function:def parse(file, pattern, *, cast={}, chunk=2 ** 16):
if isinstance(file, (str, PathLike)):
should_close = True
fileobj = open(str(file))
elif hasattr(file, "read") and callable(file.read):
should_close = False
... | [
"\n Parse raw logs and extract each entry as a |dict|.\n\n The logging format has to be specified as the regex ``pattern``, it will then be\n used to parse the ``file`` and retrieve each entries based on the named groups present\n in the regex.\n\n Parameters\n ----------\n... |
Please provide a description of the function:def log(_self, _level, _message, *args, **kwargs):
r
logger = _self.opt(
exception=_self._exception,
record=_self._record,
lazy=_self._lazy,
ansi=_self._ansi,
raw=_self._raw,
depth=_self.... | [
"Log ``_message.format(*args, **kwargs)`` with severity ``_level``."
] |
Please provide a description of the function:def start(self, *args, **kwargs):
warnings.warn(
"The 'start()' method is deprecated, please use 'add()' instead", DeprecationWarning
)
return self.add(*args, **kwargs) | [
"Deprecated function to |add| a new handler.\n\n Warnings\n --------\n .. deprecated:: 0.2.2\n ``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less\n confusing name.\n "
] |
Please provide a description of the function:def stop(self, *args, **kwargs):
warnings.warn(
"The 'stop()' method is deprecated, please use 'remove()' instead", DeprecationWarning
)
return self.remove(*args, **kwargs) | [
"Deprecated function to |remove| an existing handler.\n\n Warnings\n --------\n .. deprecated:: 0.2.2\n ``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less\n confusing name.\n "
] |
Please provide a description of the function:def perform_import(val, setting_name):
if val is None:
return None
elif isinstance(val, six.string_types):
return import_from_string(val, setting_name)
elif isinstance(val, (list, tuple)):
return [import_from_string(item, setting_name... | [
"\n If the given setting is a string import notation,\n then perform the necessary import or imports.\n "
] |
Please provide a description of the function:def custom_filterset_factory(model, filterset_base_class=FilterSet, **meta):
meta.update({"model": model})
meta_class = type(str("Meta"), (object,), meta)
filterset = type(
str("%sFilterSet" % model._meta.object_name),
(filterset_base_class, ... | [
" Create a filterset for the given model using the provided meta data\n "
] |
Please provide a description of the function:def filter(self, qs, value):
_id = None
if value is not None:
_, _id = from_global_id(value)
return super(GlobalIDFilter, self).filter(qs, _id) | [
" Convert the filter value to a primary key before filtering "
] |
Please provide a description of the function:def get_filtering_args_from_filterset(filterset_class, type):
from ..forms.converter import convert_form_field
args = {}
for name, filter_field in six.iteritems(filterset_class.base_filters):
field_type = convert_form_field(filter_field.field).Argum... | [
" Inspect a FilterSet and produce the arguments to pass to\n a Graphene Field. These arguments will be available to\n filter against in the GraphQL\n "
] |
Please provide a description of the function:def _make_topics_result(f, futmap):
try:
result = f.result()
for topic, error in result.items():
fut = futmap.get(topic, None)
if fut is None:
raise RuntimeError("Topic {} not found ... | [
"\n Map per-topic results to per-topic futures in futmap.\n The result value of each (successful) future is None.\n "
] |
Please provide a description of the function:def _make_resource_result(f, futmap):
try:
result = f.result()
for resource, configs in result.items():
fut = futmap.get(resource, None)
if fut is None:
raise RuntimeError("Resource ... | [
"\n Map per-resource results to per-resource futures in futmap.\n The result value of each (successful) future is a ConfigResource.\n "
] |
Please provide a description of the function:def _make_futures(futmap_keys, class_check, make_result_fn):
futmap = {}
for key in futmap_keys:
if class_check is not None and not isinstance(key, class_check):
raise ValueError("Expected list of {}".format(type(class_che... | [
"\n Create futures and a futuremap for the keys in futmap_keys,\n and create a request-level future to be bassed to the C API.\n "
] |
Please provide a description of the function:def create_topics(self, new_topics, **kwargs):
f, futmap = AdminClient._make_futures([x.topic for x in new_topics],
None,
AdminClient._make_topics_result)
s... | [
"\n Create new topics in cluster.\n\n The future result() value is None.\n\n :param list(NewTopic) new_topics: New topics to be created.\n :param float operation_timeout: Set broker's operation timeout in seconds,\n controlling how long the CreateTopics request will bloc... |
Please provide a description of the function:def delete_topics(self, topics, **kwargs):
f, futmap = AdminClient._make_futures(topics, None,
AdminClient._make_topics_result)
super(AdminClient, self).delete_topics(topics, f, **kwargs)
retur... | [
"\n Delete topics.\n\n The future result() value is None.\n\n :param list(str) topics: Topics to mark for deletion.\n :param float operation_timeout: Set broker's operation timeout in seconds,\n controlling how long the DeleteTopics request will block\n ... |
Please provide a description of the function:def create_partitions(self, new_partitions, **kwargs):
f, futmap = AdminClient._make_futures([x.topic for x in new_partitions],
None,
AdminClient._make_topics_result... | [
"\n Create additional partitions for the given topics.\n\n The future result() value is None.\n\n :param list(NewPartitions) new_partitions: New partitions to be created.\n :param float operation_timeout: Set broker's operation timeout in seconds,\n controlling how long ... |
Please provide a description of the function:def describe_configs(self, resources, **kwargs):
f, futmap = AdminClient._make_futures(resources, ConfigResource,
AdminClient._make_resource_result)
super(AdminClient, self).describe_configs(resources, ... | [
"\n Get configuration for the specified resources.\n\n The future result() value is a dict(<configname, ConfigEntry>).\n\n :warning: Multiple resources and resource types may be requested,\n but at most one resource of type RESOURCE_BROKER is allowed\n per call... |
Please provide a description of the function:def loads(schema_str):
try:
if sys.version_info[0] < 3:
return schema.parse(schema_str)
else:
return schema.Parse(schema_str)
except schema.SchemaParseException as e:
raise ClientError("Schema parse failed: %s" % (... | [
" Parse a schema given a schema string "
] |
Please provide a description of the function:def produce(self, **kwargs):
# get schemas from kwargs if defined
key_schema = kwargs.pop('key_schema', self._key_schema)
value_schema = kwargs.pop('value_schema', self._value_schema)
topic = kwargs.pop('topic', None)
if not ... | [
"\n Asynchronously sends message to Kafka by encoding with specified or default avro schema.\n\n :param str topic: topic name\n :param object value: An object to serialize\n :param str value_schema: Avro schema for value\n :param object key: An object to serial... |
Please provide a description of the function:def poll(self, timeout=None):
if timeout is None:
timeout = -1
message = super(AvroConsumer, self).poll(timeout)
if message is None:
return None
if not message.error():
try:
if mess... | [
"\n This is an overriden method from confluent_kafka.Consumer class. This handles message\n deserialization using avro schema\n\n :param float timeout: Poll timeout in seconds (default: indefinite)\n :returns: message object with deserialized key and value as dict objects\n :rtype... |
Please provide a description of the function:def encode_record_with_schema(self, topic, schema, record, is_key=False):
serialize_err = KeySerializerError if is_key else ValueSerializerError
subject_suffix = ('-key' if is_key else '-value')
# get the latest schema for the subject
... | [
"\n Given a parsed avro schema, encode a record for the given topic. The\n record is expected to be a dictionary.\n\n The schema is registered with the subject of 'topic-value'\n :param str topic: Topic name\n :param schema schema: Avro Schema\n :param dict record: An obje... |
Please provide a description of the function:def encode_record_with_schema_id(self, schema_id, record, is_key=False):
serialize_err = KeySerializerError if is_key else ValueSerializerError
# use slow avro
if schema_id not in self.id_to_writers:
# get the writer + schema
... | [
"\n Encode a record with a given schema id. The record must\n be a python dictionary.\n :param int schema_id: integer ID\n :param dict record: An object to serialize\n :param bool is_key: If the record is a key\n :returns: decoder function\n :rtype: func\n "
... |
Please provide a description of the function:def decode_message(self, message, is_key=False):
if message is None:
return None
if len(message) <= 5:
raise SerializerError("message is too small to decode")
with ContextStringIO(message) as payload:
ma... | [
"\n Decode a message from kafka that has been encoded for use with\n the schema registry.\n :param str|bytes or None message: message key or value to be decoded\n :returns: Decoded message contents.\n :rtype dict:\n "
] |
Please provide a description of the function:def acked(err, msg):
if err is not None:
print("failed to deliver message: {}".format(err.str()))
else:
print("produced to: {} [{}] @ {}".format(msg.topic(), msg.partition(), msg.offset())) | [
"Delivery report callback called (from flush()) on successful or failed delivery of the message."
] |
Please provide a description of the function:def example_create_topics(a, topics):
new_topics = [NewTopic(topic, num_partitions=3, replication_factor=1) for topic in topics]
# Call create_topics to asynchronously create topics, a dict
# of <topic,future> is returned.
fs = a.create_topics(new_topic... | [
" Create topics "
] |
Please provide a description of the function:def example_delete_topics(a, topics):
# Call delete_topics to asynchronously delete topics, a future is returned.
# By default this operation on the broker returns immediately while
# topics are deleted in the background. But here we give it some time (30s)... | [
" delete topics "
] |
Please provide a description of the function:def example_create_partitions(a, topics):
new_parts = [NewPartitions(topic, int(new_total_count)) for
topic, new_total_count in zip(topics[0::2], topics[1::2])]
# Try switching validate_only to True to only validate the operation
# on the ... | [
" create partitions "
] |
Please provide a description of the function:def example_describe_configs(a, args):
resources = [ConfigResource(restype, resname) for
restype, resname in zip(args[0::2], args[1::2])]
fs = a.describe_configs(resources)
# Wait for operation to finish.
for res, f in fs.items():
... | [
" describe configs "
] |
Please provide a description of the function:def example_alter_configs(a, args):
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
resources.append(resource)
for k, v in [conf.split('=') for conf in ... | [
" Alter configs atomically, replacing non-specified\n configuration properties with their default values.\n "
] |
Please provide a description of the function:def example_delta_alter_configs(a, args):
# Convert supplied config to resources.
# We can reuse the same resources both for describe_configs and
# alter_configs.
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]... | [
"\n The AlterConfigs Kafka API requires all configuration to be passed,\n any left out configuration properties will revert to their default settings.\n\n This example shows how to just modify the supplied configuration entries\n by first reading the configuration from the broker, updating the supplied\... |
Please provide a description of the function:def example_list(a, args):
if len(args) == 0:
what = "all"
else:
what = args[0]
md = a.list_topics(timeout=10)
print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name))
if what in ("all", "... | [
" list topics and cluster metadata "
] |
Please provide a description of the function:def _resolve_plugins(plugins):
import os
from sys import platform
# Location of __init__.py and the embedded library directory
basedir = os.path.dirname(__file__)
if platform in ('win32', 'cygwin'):
paths_sep = ';'
ext = '.dll'
... | [
" Resolve embedded plugins from the wheel's library directory.\n\n For internal module use only.\n\n :param str plugins: The plugin.library.paths value\n "
] |
Please provide a description of the function:def on_delivery(err, msg, obj):
if err is not None:
print('Message {} delivery failed for user {} with error {}'.format(
obj.id, obj.name, err))
else:
print('Message {} successfully produced to {} [{}] at offset {}'.format(
... | [
"\n Handle delivery reports served from producer.poll.\n This callback takes an extra argument, obj.\n This allows the original contents to be included for debugging purposes.\n "
] |
Please provide a description of the function:def produce(topic, conf):
from confluent_kafka.avro import AvroProducer
producer = AvroProducer(conf, default_value_schema=record_schema)
print("Producing user records to topic {}. ^c to exit.".format(topic))
while True:
# Instantiate new User... | [
"\n Produce User records\n "
] |
Please provide a description of the function:def consume(topic, conf):
from confluent_kafka.avro import AvroConsumer
from confluent_kafka.avro.serializer import SerializerError
print("Consuming user records from topic {} with group {}. ^c to exit.".format(topic, conf["group.id"]))
c = AvroConsume... | [
"\n Consume User records\n "
] |
Please provide a description of the function:def register(self, subject, avro_schema):
schemas_to_id = self.subject_to_schema_ids[subject]
schema_id = schemas_to_id.get(avro_schema, None)
if schema_id is not None:
return schema_id
# send it up
url = '/'.join... | [
"\n POST /subjects/(string: subject)/versions\n Register a schema with the registry under the given subject\n and receive a schema id.\n\n avro_schema must be a parsed schema from the python avro library\n\n Multiple instances of the same schema will result in cache misses.\n\n ... |
Please provide a description of the function:def delete_subject(self, subject):
url = '/'.join([self.url, 'subjects', subject])
result, code = self._send_request(url, method="DELETE")
if not (code >= 200 and code <= 299):
raise ClientError('Unable to delete subject: {}'.fo... | [
"\n DELETE /subjects/(string: subject)\n Deletes the specified subject and its associated compatibility level if registered.\n It is recommended to use this API only when a topic needs to be recycled or in development environments.\n :param subject: subject name\n :returns: versio... |
Please provide a description of the function:def get_by_id(self, schema_id):
if schema_id in self.id_to_schema:
return self.id_to_schema[schema_id]
# fetch from the registry
url = '/'.join([self.url, 'schemas', 'ids', str(schema_id)])
result, code = self._send_reque... | [
"\n GET /schemas/ids/{int: id}\n Retrieve a parsed avro schema by id or None if not found\n :param int schema_id: int value\n :returns: Avro schema\n :rtype: schema\n "
] |
Please provide a description of the function:def get_version(self, subject, avro_schema):
schemas_to_version = self.subject_to_schema_versions[subject]
version = schemas_to_version.get(avro_schema, None)
if version is not None:
return version
url = '/'.join([self.ur... | [
"\n POST /subjects/(string: subject)\n\n Get the version of a schema for a given subject.\n\n Returns None if not found.\n :param str subject: subject name\n :param: schema avro_schema: Avro schema\n :returns: version\n :rtype: int\n "
] |
Please provide a description of the function:def update_compatibility(self, level, subject=None):
if level not in VALID_LEVELS:
raise ClientError("Invalid level specified: %s" % (str(level)))
url = '/'.join([self.url, 'config'])
if subject:
url += '/' + subject
... | [
"\n PUT /config/(string: subject)\n\n Update the compatibility level for a subject. Level must be one of:\n\n :param str level: ex: 'NONE','FULL','FORWARD', or 'BACKWARD'\n "
] |
Please provide a description of the function:def get_compatibility(self, subject=None):
url = '/'.join([self.url, 'config'])
if subject:
url = '/'.join([url, subject])
result, code = self._send_request(url)
is_successful_request = code >= 200 and code <= 299
... | [
"\n GET /config\n Get the current compatibility level for a subject. Result will be one of:\n\n :param str subject: subject name\n :raises ClientError: if the request was unsuccessful or an invalid compatibility level was returned\n :returns: one of 'NONE','FULL','FORWARD', or 'B... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.