text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recenter(self): """ one iteration of k-means """
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._splits[split_idx + 1] # Try shifting the centroid to the left ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reindex(self): """ Index every sentence into a cluster """
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 - (last_split + 1))))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True): """Transform instance to inputs for MLM and NSP."""
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 = list(instance.segment_ids) assert len(input_ids) <= max_seq_length valid_lengths = len(input_ids) masked_lm_positions = list(inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_to_files_np(features, tokenizer, max_seq_length, max_predictions_per_seq, output_files): # pylint: disable=unused-argument """Write to numpy files from...
next_sentence_labels = [] valid_lengths = [] assert len(output_files) == 1, 'numpy format only support single output file' output_file = output_files[0] (input_ids, segment_ids, masked_lm_positions, masked_lm_ids, masked_lm_weights, next_sentence_labels, valid_lengths) = features total_wr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_to_files_rec(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create IndexedRecordIO files from `TrainingInstance`s."""
writers = [] for output_file in output_files: writers.append( mx.recordio.MXIndexedRecordIO( os.path.splitext(output_file)[0] + '.idx', output_file, 'w')) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): features = t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_training_instances(x): """Create `TrainingInstance`s from raw text."""
(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 = [[]] # Input file format: # (1) One sentence per line. These should ideally be a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_tokens = max_seq_length - 3 # We *usually* want to fill up the entire sequence since we are padding # to `max_seq_length` anyways, so short sequences are generally wasted # computation. However, we *sometimes* ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective."""
cand_indexes = [] for (i, token) in enumerate(tokens): if token in ['[CLS]', '[SEP]']: continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length."""
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 tokens_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_vocab(vocab_file): """GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab."""
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]) idx_to_token[idx] = word def swap(token, target_idx, token_to_idx, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_tf_checkpoint(path): """read tensorflow checkpoint"""
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 = reader.get_tensor(key) tensors[key] = tensor return tensors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile(curr_step, start_step, end_step, profile_name='profile.json', early_exit=True): """profile the program between [start_step, end_step)."""
if curr_step == start_step: mx.nd.waitall() mx.profiler.set_config(profile_memory=False, profile_symbolic=True, profile_imperative=True, filename=profile_name, aggregate_stats=True) mx.profiler.set_state('run') elif curr_step...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary."""
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() vocab[token] = index index += 1 return vocab
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ r""" Forward computation for char_encoder Parameters inputs: NDArray The input...
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(inputs) if self._highways: output = self._highways(output) if self._projection: output = self._pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _position_encoding_init(max_length, dim): """Init the sinusoid position encoding table """
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::2] = np.sin(position_enc[:, 0::2]) # dim 2i position_enc[:, 1::2] = np.cos(position_enc[:,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): ...
predefined_args = {'num_units': 512, 'hidden_size': 2048, 'dropout': 0.1, 'epsilon': 0.1, 'num_layers': 6, 'num_heads': 8, 'scaled': True, 'share_embed': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_activation(self, act): """Get activation block based on the name. """
if isinstance(act, str): if act.lower() == 'gelu': return GELU() else: return gluon.nn.Activation(act) assert isinstance(act, gluon.Block) return act
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Position-wise encoding of the inputs. Parameters inp...
outputs = self.ffn_1(inputs) if self.activation: outputs = self.activation(outputs) outputs = self.ffn_2(outputs) if self._dropout: outputs = self.dropout_layer(outputs) if self._use_residual: outputs = outputs + inputs outputs = self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Transformer Encoder Attention Cell. Param...
outputs, attention_weights =\ self.attention_cell(inputs, inputs, inputs, mask) outputs = self.proj(outputs) if self._dropout: outputs = self.dropout_layer(outputs) if self._use_residual: outputs = outputs + inputs outputs = self.layer_norm(ou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybrid_forward(self, F, inputs, mem_value, mask=None, mem_mask=None): #pylint: disable=unused-argument # pylint: disable=arguments-differ """Transformer Deco...
outputs, attention_in_outputs =\ self.attention_cell_in(inputs, inputs, inputs, mask) outputs = self.proj_in(outputs) if self._dropout: outputs = self.dropout_layer(outputs) if self._use_residual: outputs = outputs + inputs outputs = self.laye...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward_backward(self, x): """Perform forward and backward computation for a batch of src seq and dst seq"""
(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_length - 1) smoothed_label = self._label_smoothing(tgt_seq[:, 1:]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hybrid_forward(self, F, candidates_like, prob, alias): # pylint: disable=unused-argument """Draw samples from uniform distribution and return sampled candida...
flat_shape = functools.reduce(operator.mul, self._shape) idx = F.random.uniform(low=0, high=self.N, shape=flat_shape, dtype='float64').floor() prob = F.gather_nd(prob, idx.reshape((1, -1))) alias = F.gather_nd(alias, idx.reshape((1, -1))) where = F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, handler_id=None): """Remove a previously added handler and stop sending logs to its sink. Parameters handler_id : |int| or ``None`` The id of th...
with self._lock: handlers = self._handlers.copy() if handler_id is None: for handler in handlers.values(): handler.stop() handlers.clear() else: try: handler = handlers.pop(handler_id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def catch( self, exception=Exception, *, level="ERROR", reraise=False, message="An error has been caught in function '{record[function]}', " "process '{record[pro...
if callable(exception) and ( not isclass(exception) or not issubclass(exception, BaseException) ): return self.catch()(exception) class Catcher: def __init__(self, as_decorator): self._as_decorator = as_decorator def __enter__(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0): r"""Parametrize a logging call to slightly change generated log messa...
return Logger(self._extra, exception, record, lazy, ansi, raw, depth)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(_self, **kwargs): """Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Param...
return Logger( {**_self._extra, **kwargs}, _self._exception, _self._record, _self._lazy, _self._ansi, _self._raw, _self._depth, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def level(self, name, no=None, color=None, icon=None): """Add, update or retrieve a logging level. Logging levels are defined by their ``name`` to which a severi...
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 None: try: return self._levels[name] except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, *, handlers=None, levels=None, extra=None, activation=None): """Configure the core logger. It should be noted that ``extra`` values set using...
if handlers is not None: self.remove() else: handlers = [] if levels is not None: for params in levels: self.level(**params) if extra is not None: with self._lock: self._extra_class.clear() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(file, pattern, *, cast={}, chunk=2 ** 16): """ Parse raw logs and extract each entry as a |dict|. The logging format has to be specified as the regex `...
if isinstance(file, (str, PathLike)): should_close = True fileobj = open(str(file)) elif hasattr(file, "read") and callable(file.read): should_close = False fileobj = file else: raise ValueError( "Invalid file, it shoul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, *args, **kwargs): """Deprecated function to |add| a new handler. Warnings -------- .. deprecated:: 0.2.2 ``start()`` will be removed in Loguru 1....
warnings.warn( "The 'start()' method is deprecated, please use 'add()' instead", DeprecationWarning ) return self.add(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self, *args, **kwargs): """Deprecated function to |remove| an existing handler. Warnings -------- .. deprecated:: 0.2.2 ``stop()`` will be removed in Lo...
warnings.warn( "The 'stop()' method is deprecated, please use 'remove()' instead", DeprecationWarning ) return self.remove(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_serializer_field(field, is_input=True): """ Converts a django rest frameworks field to a graphql field and marks the field as required if we are crea...
graphql_type = get_graphene_type_from_serializer_field(field) args = [] kwargs = {"description": field.help_text, "required": is_input and field.required} # if it is a tuple or a list it means that we are returning # the graphql type and the child type if isinstance(graphql_type, (list, tupl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_filterset_factory(model, filterset_base_class=FilterSet, **meta): """ Create a filterset for the given model using the provided meta data """
meta.update({"model": model}) meta_class = type(str("Meta"), (object,), meta) filterset = type( str("%sFilterSet" % model._meta.object_name), (filterset_base_class, GrapheneFilterSetMixin), {"Meta": meta_class}, ) return filterset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, qs, value): """ Convert the filter value to a primary key before filtering """
_id = None if value is not None: _, _id = from_global_id(value) return super(GlobalIDFilter, self).filter(qs, _id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_filtering_args_from_filterset(filterset_class, type): """ Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will...
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).Argument() field_type.description = filter_field.label args[name] = field_type return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_futures(futmap_keys, class_check, make_result_fn): """ Create futures and a futuremap for the keys in futmap_keys, and create a request-level future to...
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_check))) futmap[key] = concurrent.futures.Future() if not futmap[key].set_running_or_notify_c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_topics(self, new_topics, **kwargs): """ Create new topics in cluster. The future result() value is None. :param list(NewTopic) new_topics: New topics ...
f, futmap = AdminClient._make_futures([x.topic for x in new_topics], None, AdminClient._make_topics_result) super(AdminClient, self).create_topics(new_topics, f, **kwargs) return futmap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_topics(self, topics, **kwargs): """ Delete topics. The future result() value is None. :param list(str) topics: Topics to mark for deletion. :param flo...
f, futmap = AdminClient._make_futures(topics, None, AdminClient._make_topics_result) super(AdminClient, self).delete_topics(topics, f, **kwargs) return futmap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_partitions(self, new_partitions, **kwargs): """ Create additional partitions for the given topics. The future result() value is None. :param list(NewP...
f, futmap = AdminClient._make_futures([x.topic for x in new_partitions], None, AdminClient._make_topics_result) super(AdminClient, self).create_partitions(new_partitions, f, **kwargs) return futmap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_configs(self, resources, **kwargs): """ Get configuration for the specified resources. The future result() value is a dict(<configname, ConfigEntry>...
f, futmap = AdminClient._make_futures(resources, ConfigResource, AdminClient._make_resource_result) super(AdminClient, self).describe_configs(resources, f, **kwargs) return futmap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loads(schema_str): """ Parse a schema given a schema string """
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" % (str(e)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def produce(self, **kwargs): """ Asynchronously sends message to Kafka by encoding with specified or default avro schema. :param str topic: topic name :param obj...
# 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 topic: raise ClientError("Topic name not specified.") value = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll(self, timeout=None): """ This is an overriden method from confluent_kafka.Consumer class. This handles message deserialization using avro schema :param ...
if timeout is None: timeout = -1 message = super(AvroConsumer, self).poll(timeout) if message is None: return None if not message.error(): try: if message.value() is not None: decoded_value = self._serializer.decod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_record_with_schema(self, topic, schema, record, is_key=False): """ Given a parsed avro schema, encode a record for the given topic. The record is expe...
serialize_err = KeySerializerError if is_key else ValueSerializerError subject_suffix = ('-key' if is_key else '-value') # get the latest schema for the subject subject = topic + subject_suffix # register it schema_id = self.registry_client.register(subject, schema) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_alter_configs(a, args): """ Alter configs atomically, replacing non-specified configuration properties with their default values. """
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 configs.split(',')]: resource.set_config(k, v) fs = a.alter_configs(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_delta_alter_configs(a, args): """ The AlterConfigs Kafka API requires all configuration to be passed, any left out configuration properties will reve...
# 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]): resource = ConfigResource(restype, resname) resources.append(resource) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_list(a, args): """ list topics and cluster metadata """
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", "brokers"): print(" {} brokers:".format(len(md.brokers))) for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_plugins(plugins): """ Resolve embedded plugins from the wheel's library directory. For internal module use only. :param str plugins: The plugin.libr...
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' libdir = basedir elif platform in ('linux', 'linux2'): paths_sep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_delivery(err, msg, obj): """ Handle delivery reports served from producer.poll. This callback takes an extra argument, obj. This allows the original conte...
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( obj.id, msg.topic(), msg.partition(), msg.offset()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def produce(topic, conf): """ Produce User records """
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, populate fields, produce record, execute callbacks. record = User...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(topic, conf): """ Consume User records """
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 = AvroConsumer(conf, reader_value_schema=record_schema) c.subscribe([topic]) wh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, dirpath): """ Download artifact from S3 and store in dirpath directory. If the artifact is already downloaded nothing is done. """
if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0: return print('Downloading %s -> %s' % (self.path, self.lpath)) if dry_run: return self.arts.s3_bucket.download_file(self.path, self.lpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_s3(self): """ Collect and download build-artifacts from S3 based on git reference """
print('Collecting artifacts matching tag/sha %s from S3 bucket %s' % (self.gitref, s3_bucket)) self.s3 = boto3.resource('s3') self.s3_bucket = self.s3.Bucket(s3_bucket) self.s3.meta.client.head_bucket(Bucket=s3_bucket) for key in self.s3_bucket.objects.all(): self.co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_local(self, path): """ Collect artifacts from a local directory possibly previously collected from s3 """
for f in os.listdir(path): lpath = os.path.join(path, f) if not os.path.isfile(lpath): continue Artifact(self, lpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs): ''' Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, fir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def help(module=None, *args): ''' Display help on Ansible standard module. :param module: :return: ''' if not module: raise CommandExecutionError('Please tell me what module you want to have helped with. ' 'Or call "ansible.list" to know what is avail...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ans...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lchown(path, user, group): ''' Chown a file, pass the file the desired user and group without following symlinks. path path to the file or directory user user owner group group owner CLI Example: .. code-block:: bash salt '*' file.chown /etc/pass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versioncha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _sed_esc(string, escape_all=False): ''' Escape single quotes and forward slashes ''' special_chars = "^.[$()|*+?{" string = string.replace("'", "'\"'\"'").replace("/", "\\/") if escape_all is True: for char in special_chars: string = string.replace(char, "\\" + char) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _psed(text, before, after, limit, flags): ''' Does the actual work for file.psed, so that single lines can be passed in ''' atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = ''.join(comps[1:]) c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_flags(flags): ''' Return an integer appropriate for use as a flag for the re module from a list of human-readable strings .. code-block:: python >>> _get_flags(['MULTILINE', 'IGNORECASE']) 10 >>> _get_flags('MULTILINE') 8 >>> _get_flags(2) 2 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _add_flags(flags, new_flags): ''' Combine ``flags`` and ``new_flags`` ''' flags = _get_flags(flags) new_flags = _get_flags(new_flags) return flags | new_flags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _starts_till(src, probe, strip_comments=True): ''' Returns True if src and probe at least matches at the beginning till some point. ''' def _strip_comments(txt): ''' Strip possible comments. Usually comments are one or two symbols at the beginning of the line, separated with ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _regex_to_static(src, regex): ''' Expand regular expression to static match. ''' if not src or not regex: return None try: compiled = re.compile(regex, re.DOTALL) src = [line for line in src if compiled.search(line) or line.count(regex)] except Exception as ex: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _assert_occurrence(probe, target, amount=1): ''' Raise an exception, if there are different amount of specified occurrences in src. ''' occ = len(probe) if occ > amount: msg = 'more than' elif occ < amount: msg = 'less than' elif not occ: msg = 'no' else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _set_line_indent(src, line, indent): ''' Indent the line with the source line. ''' if not indent: return line idt = [] for c in src: if c not in ['\t', ' ']: break idt.append(c) return ''.join(idt) + line.lstrip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _set_line_eol(src, line): ''' Add line ending ''' line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy(src, dst, recurse=False, remove_existing=False): ''' Copy a file or directory from source to dst In order to copy a directory, the recurse flag is required, and will by default overwrite files in the destination with the same path, and retain all other existing files. (similar to cp -r on ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stats(path, hash_type=None, follow_symlinks=True): ''' Return a dict containing the stats for a given file CLI Example: .. code-block:: bash salt '*' file.stats /etc/passwd ''' path = os.path.expanduser(path) ret = {} if not os.path.exists(path): try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remove(path, **kwargs): ''' Remove the named file. If a directory is supplied, it will be recursively deleted. CLI Example: .. code-block:: bash salt '*' file.remove /tmp/foo ''' path = os.path.expanduser(path) if not os.path.isabs(path): raise SaltInvocationError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def restorecon(path, recursive=False): ''' Reset the SELinux context on a given path CLI Example: .. code-block:: bash salt '*' file.restorecon /home/user/.ssh/authorized_keys ''' if recursive: cmd = ['restorecon', '-FR', path] else: cmd = ['restorecon', '-F', pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_selinux_context(path): ''' Get an SELinux context from a given path CLI Example: .. code-block:: bash salt '*' file.get_selinux_context /etc/hosts ''' out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False) try: ret = re.search(r'\w+:\w+:\w+:\w+', out).g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def apply_template_on_contents( contents, template, context, defaults, saltenv): ''' Return the contents after applying the templating engine contents template string template template format context Overrides default context variabl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_managed( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, seuser=None, serole=None, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_managed_changes( name, source, source_hash, source_hash_name, user, group, mode, attrs, template, context, defaults, saltenv, contents=None, skip_verify=False, keep_mode=False, seuse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_diff(file1, file2, saltenv='base', show_filenames=True, show_changes=True, template=False, source_hash_file1=None, source_hash_file2=None): ''' Return unified diff of two files file1 The first file to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mkdir(dir_path, user=None, group=None, mode=None): ''' Ensure that a directory is available. CLI Example: .. code-block:: bash salt '*' file.mkdir /opt/jetty/context ''' dir_path = os.path.expanduser(dir_path) directory = os.path.normpath(dir_pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makedirs_perms(name, user=None, group=None, mode='0755'): ''' Taken and modified from os.makedirs to set user, group and mode for each directory created. CLI Example: .. code-block:: bash salt '*' file.makedirs_perms /opt/code ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_chrdev(name): ''' Check if a file exists and is a character device. CLI Example: .. code-block:: bash salt '*' file.is_chrdev /dev/chr ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_blkdev(name): ''' Check if a file exists and is a block device. CLI Example: .. code-block:: bash salt '*' file.is_blkdev /dev/blk ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_fifo(name): ''' Check if a file exists and is a FIFO. CLI Example: .. code-block:: bash salt '*' file.is_fifo /dev/fifo ''' name = os.path.expanduser(name) stat_structure = None try: stat_structure = os.stat(name) except OSError as exc: if exc.errno ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def grep(path, pattern, *opts): ''' Grep for a string in the specified file .. note:: This function's return value is slated for refinement in future versions of Salt path Path to the file to be searched .. note:: Globbing is supported (i....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def open_files(by_pid=False): ''' Return a list of all physical open files on the system. CLI Examples: .. code-block:: bash salt '*' file.open_files salt '*' file.open_files by_pid=True ''' # First we collect valid PIDs pids = {} procfs = os.listdir('/proc/') for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def move(src, dst): ''' Move a file or directory CLI Example: .. code-block:: bash salt '*' file.move /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('Source path must be ab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def diskusage(path): ''' Recursively calculate disk usage of path and return it in bytes CLI Example: .. code-block:: bash salt '*' file.diskusage /path/to/check ''' total_size = 0 seen = set() if os.path.isfile(path): stat_structure = os.stat(path) ret = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get(key, profile=None): ''' Get a value from sqlite3 ''' if not profile: return None _, cur, table = _connect(profile) q = profile.get('get_query', ('SELECT value FROM {0} WHERE ' 'key=:key'.format(table))) res = cur.execute(q, {'key': key}) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def show(destination, protocol=None, **kwargs): # pylint: disable=unused-argument ''' Displays all details for a certain route learned via a specific protocol. If the protocol is not specified, will return all possible routes. .. note:: This function return the routes from the RIB. I...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def absent(name): ''' Ensure that a network is absent. name Name of the network Usage Example: .. code-block:: yaml network_foo: docker_network.absent ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _remove_network(network): ''' Remove network, including all connected containers ''' ret = {'name': network['Name'], 'changes': {}, 'result': False, 'comment': ''} errors = [] for cid in network['Containers']: try: cinfo = __salt__['docke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _encrypt_private(self, ret, dictkey, target): ''' The server equivalent of ReqChannel.crypted_transfer_decode_dictentry ''' # encrypt with a specific AES key pubfn = os.path.join(self.opts['pki_dir'], 'minions', target...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _update_aes(self): ''' Check to see if a fresh AES key is available and update the components of the worker ''' if salt.master.SMaster.secrets['aes']['secret'].value != self.crypticle.key_string: self.crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def which(exe): ''' Decorator wrapper for salt.utils.path.which ''' def wrapper(function): def wrapped(*args, **kwargs): if salt.utils.path.which(exe) is None: raise CommandNotFoundError( 'The \'{0}\' binary was not found in $PATH.'.format(exe) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def which_bin(exes): ''' Decorator wrapper for salt.utils.path.which_bin ''' def wrapper(function): def wrapped(*args, **kwargs): if salt.utils.path.which_bin(exes) is None: raise CommandNotFoundError( 'None of provided binaries({0}) was not found ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def runner(): ''' Return all inline documentation for runner modules CLI Example: .. code-block:: bash salt-run doc.runner ''' client = salt.runner.RunnerClient(__opts__) ret = client.get_docs() return ret