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 fetch_search_document(self, *, index):
"""Fetch the object's document from a search index by id.""" |
assert self.pk, "Object must have a primary key before being indexed."
client = get_client()
return client.get(index=index, doc_type=self.search_doc_type, id=self.pk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_search_document(self, *, index):
""" Create or replace search document in named index. Checks the local cache to see if the document has changed, and i... |
cache_key = self.search_document_cache_key
new_doc = self.as_search_document(index=index)
cached_doc = cache.get(cache_key)
if new_doc == cached_doc:
logger.debug("Search document for %r is unchanged, ignoring update.", self)
return []
cache.set(cache_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 update_search_document(self, *, index, update_fields):
""" Partial update of a document in named index. Partial updates are invoked via a call to save the do... |
doc = self.as_search_document_update(index=index, update_fields=update_fields)
if not doc:
logger.debug("Ignoring object update as document is empty.")
return
get_client().update(
index=index, doc_type=self.search_doc_type, body={"doc": doc}, id=self.pk
... |
<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_search_document(self, *, index):
"""Delete document from named index.""" |
cache.delete(self.search_document_cache_key)
get_client().delete(index=index, doc_type=self.search_doc_type, id=self.pk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setPluginSetting(name, value, namespace = None):
'''
Sets the value of a plugin setting.
:param name: the name of the setting. It is not the full path, but just the last name of it
:param value: the value to set for the plugin setting
:param namespace: The namespace. If not passed or None, the ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pluginSetting(name, namespace=None, typ=None):
''' Returns the value of a plugin setting. :param name: the name of the setting. It is not the full path, but ... |
if t == BOOL:
return bool
elif t == NUMBER:
return float
else:
return unicode
namespace = namespace or _callerName().split(".")[0]
full_name = namespace + "/" + name
if settings.contains(full_name):
if typ is None:
typ = _type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_index_command(self, index, **options):
"""Delete search index.""" |
if options["interactive"]:
logger.warning("This will permanently delete the index '%s'.", index)
if not self._confirm_action():
logger.warning(
"Aborting deletion of index '%s' at user's request.", index
)
return
... |
<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_index(index):
"""Create an index and apply mapping if appropriate.""" |
logger.info("Creating search index: '%s'", index)
client = get_client()
return client.indices.create(index=index, body=get_index_mapping(index)) |
<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_index(index):
"""Re-index every document in a named index.""" |
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = model.objects.get_search_queryset(index).iterator()
actions = bulk_actio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prune_index(index):
"""Remove all orphaned documents from an index. This function works by scanning the remote index, and in each returned batch of documents... |
logger.info("Pruning missing objects from index '%s'", index)
prunes = []
responses = []
client = get_client()
for model in get_index_models(index):
for hit in scan_index(index, model):
obj = _prune_hit(hit, model)
if obj:
prunes.append(obj)
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prune_hit(hit, model):
""" Check whether a document should be pruned. This method uses the SearchDocumentManagerMixin.in_search_queryset method to determine... |
hit_id = hit["_id"]
hit_index = hit["_index"]
if model.objects.in_search_queryset(hit_id, index=hit_index):
logger.debug(
"%s with id=%s exists in the '%s' index queryset.", model, hit_id, hit_index
)
return None
else:
logger.debug(
"%s with id=%s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scan_index(index, model):
""" Yield all documents of model type in an index. This function calls the elasticsearch.helpers.scan function, and yields all the ... |
# see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-type-query.html
query = {"query": {"type": {"value": model._meta.model_name}}}
client = get_client()
for hit in helpers.scan(client, index=index, query=query):
yield hit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bulk_actions(objects, index, action):
""" Yield bulk api 'actions' from a collection of objects. The output from this method can be fed in to the bulk api he... |
assert (
index != "_all"
), "index arg must be a valid index name. '_all' is a reserved term."
logger.info("Creating bulk '%s' actions for '%s'", action, index)
for obj in objects:
try:
logger.debug("Appending '%s' action for '%r'", action, obj)
yield obj.as_sear... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_config(strict=False):
"""Validate settings.SEARCH_SETTINGS.""" |
for index in settings.get_index_names():
_validate_mapping(index, strict=strict)
for model in settings.get_index_models(index):
_validate_model(model)
if settings.get_setting("update_strategy", "full") not in ["full", "partial"]:
raise ImproperlyConfigured(
"Inva... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_mapping(index, strict=False):
"""Check that an index mapping JSON file exists.""" |
try:
settings.get_index_mapping(index)
except IOError:
if strict:
raise ImproperlyConfigured("Index '%s' has no mapping file." % index)
else:
logger.warning("Index '%s' has no mapping, relying on ES instead.", index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_model(model):
"""Check that a model configured for an index subclasses the required classes.""" |
if not hasattr(model, "as_search_document"):
raise ImproperlyConfigured("'%s' must implement `as_search_document`." % model)
if not hasattr(model.objects, "get_search_queryset"):
raise ImproperlyConfigured(
"'%s.objects must implement `get_search_queryset`." % model
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect_signals():
"""Connect up post_save, post_delete signals for models.""" |
for index in settings.get_index_names():
for model in settings.get_index_models(index):
_connect_model_signals(model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect_model_signals(model):
"""Connect signals for a single model.""" |
dispatch_uid = "%s.post_save" % model._meta.model_name
logger.debug("Connecting search index model post_save signal: %s", dispatch_uid)
signals.post_save.connect(_on_model_save, sender=model, dispatch_uid=dispatch_uid)
dispatch_uid = "%s.post_delete" % model._meta.model_name
logger.debug("Connectin... |
<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_model_save(sender, **kwargs):
"""Update document in search index post_save.""" |
instance = kwargs.pop("instance")
update_fields = kwargs.pop("update_fields")
for index in instance.search_indexes:
try:
_update_search_index(
instance=instance, index=index, update_fields=update_fields
)
except Exception:
logger.exception... |
<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_model_delete(sender, **kwargs):
"""Remove documents from search indexes post_delete.""" |
instance = kwargs.pop("instance")
for index in instance.search_indexes:
try:
_delete_from_search_index(instance=instance, index=index)
except Exception:
logger.exception("Error handling 'on_delete' signal for %s", instance) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _in_search_queryset(*, instance, index) -> bool: """Wrapper around the instance manager method.""" |
try:
return instance.__class__.objects.in_search_queryset(instance.id, index=index)
except Exception:
logger.exception("Error checking object in_search_queryset.")
return False |
<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_from_search_index(*, instance, index):
"""Remove a document from a search index.""" |
pre_delete.send(sender=instance.__class__, instance=instance, index=index)
if settings.auto_sync(instance):
instance.delete_search_document(index=index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ready(self):
"""Validate config and connect signals.""" |
super(ElasticAppConfig, self).ready()
_validate_config(settings.get_setting("strict_validation"))
_connect_signals() |
<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_setting(key, *default):
"""Return specific search setting from Django conf.""" |
if default:
return get_settings().get(key, default[0])
else:
return get_settings()[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 get_index_mapping(index):
"""Return the JSON mapping file for an index. Mappings are stored as JSON files in the mappings subdirectory of this app. They must... |
# app_path = apps.get_app_config('elasticsearch_django').path
mappings_dir = get_setting("mappings_dir")
filename = "%s.json" % index
path = os.path.join(mappings_dir, filename)
with open(path, "r") as f:
return json.load(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 get_model_index_properties(instance, index):
"""Return the list of properties specified for a model in an index.""" |
mapping = get_index_mapping(index)
doc_type = instance._meta.model_name.lower()
return list(mapping["mappings"][doc_type]["properties"].keys()) |
<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_index_models(index):
"""Return list of models configured for a named index. Args: index: string, the name of the index to look up. """ |
models = []
for app_model in get_index_config(index).get("models"):
app, model = app_model.split(".")
models.append(apps.get_model(app, model))
return models |
<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_model_indexes(model):
"""Return list of all indexes in which a model is configured. A model may be configured to appear in multiple indexes. This functio... |
indexes = []
for index in get_index_names():
for app_model in get_index_models(index):
if app_model == model:
indexes.append(index)
return indexes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pprint(data):
""" Returns an indented HTML pretty-print version of JSON. Take the event_payload JSON, indent it, order the keys and then present it as a <cod... |
pretty = json.dumps(data, sort_keys=True, indent=4, separators=(",", ": "))
html = pretty.replace(" ", " ").replace("\n", "<br>")
return mark_safe("<code>%s</code>" % html) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def showMessageDialog(title, text):
'''
Show a dialog containing a given text, with a given title.
The text accepts HTML syntax
'''
dlg = QgsMessageOutput.createMessageOutput()
dlg.setTitle(title)
dlg.setMessage(text, QgsMessageOutput.MessageHtml)
dlg.showMessage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def askForFiles(parent, msg = None, isSave = False, allowMultiple = False, exts = "*"):
'''
Asks for a file or files, opening the corresponding dialog with the last path that was selected
when this same function was invoked from the calling method.
:param parent: The parent window
:param msg: The m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def askForFolder(parent, msg = None):
'''
Asks for a folder, opening the corresponding dialog with the last path that was selected
when this same function was invoked from the calling method
:param parent: The parent window
:param msg: The message to use for the dialog title
'''
msg = msg o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def execute(func, message = None):
'''
Executes a lengthy tasks in a separate thread and displays a waiting dialog if needed.
Sets the cursor to wait cursor while the task is running.
This function does not provide any support for progress indication
:param func: The function to execute.
:par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_search_updates():
""" Context manager used to temporarily disable auto_sync. This is useful when performing bulk updates on objects - when you may no... |
_receivers = signals.post_save.receivers.copy()
signals.post_save.receivers = _strip_on_model_save()
yield
signals.post_save.receivers = _receivers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requestTimedOut(self, reply):
"""Trap the timeout. In Async mode requestTimedOut is called after replyFinished""" |
# adapt http_call_result basing on receiving qgs timer timout signal
self.exception_class = RequestsExceptionTimeout
self.http_call_result.exception = RequestsExceptionTimeout("Timeout error") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sslErrors(self, ssl_errors):
""" Handle SSL errors, logging them if debug is on and ignoring them if disable_ssl_certificate_validation is set. """ |
if ssl_errors:
for v in ssl_errors:
self.msg_log("SSL Error: %s" % v.errorString())
if self.disable_ssl_certificate_validation:
self.reply.ignoreSslErrors() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abort(self):
""" Handle request to cancel HTTP call """ |
if (self.reply and self.reply.isRunning()):
self.on_abort = True
self.reply.abort() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def addLayerNoCrsDialog(layer, loadInLegend=True):
'''
Tries to add a layer from layer object
Same as the addLayer method, but it does not ask for CRS, regardless of current
configuration in QGIS settings
'''
settings = QSettings()
prjSetting = settings.value('/Projections/defaultBehaviour')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def newVectorLayer(filename, fields, geometryType, crs, encoding="utf-8"):
'''
Creates a new vector layer
:param filename: The filename to store the file. The extensions determines the type of file.
If extension is not among the supported ones, a shapefile will be created and the file will
get an 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 layerFromName(name):
'''
Returns the layer from the current project with the passed name
Raises WrongLayerNameException if no layer with that name is found
If several layers with that name exist, only the first one is returned
'''
layers =_layerreg.mapLayers().values()
for layer in layer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def layerFromSource(source):
'''
Returns the layer from the current project with the passed source
Raises WrongLayerSourceException if no layer with that source is found
'''
layers =_layerreg.mapLayers().values()
for layer in layers:
if layer.source() == source:
return layer
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def loadLayer(filename, name = None, provider=None):
'''
Tries to load a layer from the given file
:param filename: the path to the file to load.
:param name: the name to use for adding the layer to the current project.
If not passed or None, it will use the filename basename
'''
name = na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def loadLayerNoCrsDialog(filename, name=None, provider=None):
'''
Tries to load a layer from the given file
Same as the loadLayer method, but it does not ask for CRS, regardless of current
configuration in QGIS settings
'''
settings = QSettings()
prjSetting = settings.value('/Projections/def... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def openParametersDialog(params, title=None):
'''
Opens a dialog to enter parameters.
Parameters are passed as a list of Parameter objects
Returns a dict with param names as keys and param values as values
Returns None if the dialog was cancelled
'''
QApplication.setOverrideCursor(QCursor(Qt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_index_command(self, index, **options):
"""Rebuild search index.""" |
if options["interactive"]:
logger.warning("This will permanently delete the index '%s'.", index)
if not self._confirm_action():
logger.warning(
"Aborting rebuild of index '%s' at user's request.", index
)
return
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle(self, *args, **options):
"""Run do_index_command on each specified index and log the output.""" |
for index in options.pop("indexes"):
data = {}
try:
data = self.do_index_command(index, **options)
except TransportError as ex:
logger.warning("ElasticSearch threw an error: %s", ex)
data = {"index": index, "status": ex.status_... |
<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(self, Name, Subject, HtmlBody=None, TextBody=None, Alias=None):
""" Creates a template. :param Name: Name of template :param Subject: The content to u... |
assert TextBody or HtmlBody, "Provide either email TextBody or HtmlBody or both"
data = {"Name": Name, "Subject": Subject, "HtmlBody": HtmlBody, "TextBody": TextBody, "Alias": Alias}
return self._init_instance(self.call("POST", "/templates", data=data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_config(cls, config, prefix="postmark_", is_uppercase=False):
""" Helper method for instantiating PostmarkClient from dict-like objects. """ |
kwargs = {}
for arg in get_args(cls):
key = prefix + arg
if is_uppercase:
key = key.upper()
else:
key = key.lower()
if key in config:
kwargs[arg] = config[key]
return cls(**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 chunks(container, n):
""" Split a container into n-sized chunks. """ |
for i in range(0, len(container), n):
yield container[i : i + n] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sizes(count, offset=0, max_chunk=500):
""" Helper to iterate over remote data via count & offset pagination. """ |
if count is None:
chunk = max_chunk
while True:
yield chunk, offset
offset += chunk
else:
while count:
chunk = min(count, max_chunk)
count = max(0, count - max_chunk)
yield chunk, offset
offset += chunk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_for_response(self, responses):
""" Constructs appropriate exception from list of responses and raises it. """ |
exception_messages = [self.client.format_exception_message(response) for response in responses]
if len(exception_messages) == 1:
message = exception_messages[0]
else:
message = "[%s]" % ", ".join(exception_messages)
raise PostmarkerException(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_to_csv(value):
""" Converts list to string with comma separated values. For string is no-op. """ |
if isinstance(value, (list, tuple, set)):
value = ",".join(value)
return 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 prepare_attachments(attachment):
""" Converts incoming attachment into dictionary. """ |
if isinstance(attachment, tuple):
result = {"Name": attachment[0], "Content": attachment[1], "ContentType": attachment[2]}
if len(attachment) == 4:
result["ContentID"] = attachment[3]
elif isinstance(attachment, MIMEBase):
payload = attachment.get_payload()
content_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 as_dict(self):
""" Additionally encodes headers. :return: """ |
data = super(BaseEmail, self).as_dict()
data["Headers"] = [{"Name": name, "Value": value} for name, value in data["Headers"].items()]
for field in ("To", "Cc", "Bcc"):
if field in data:
data[field] = list_to_csv(data[field])
data["Attachments"] = [prepare_att... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach_binary(self, content, filename):
""" Attaches given binary data. :param bytes content: Binary data to be attached. :param str filename: :return: None.... |
content_type = guess_content_type(filename)
payload = {"Name": filename, "Content": b64encode(content).decode("utf-8"), "ContentType": content_type}
self.attach(payload) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_mime(cls, message, manager):
""" Instantiates ``Email`` instance from ``MIMEText`` instance. :param message: ``email.mime.text.MIMEText`` instance. :par... |
text, html, attachments = deconstruct_multipart(message)
subject = prepare_header(message["Subject"])
sender = prepare_header(message["From"])
to = prepare_header(message["To"])
cc = prepare_header(message["Cc"])
bcc = prepare_header(message["Bcc"])
reply_to = 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 as_dict(self, **extra):
""" Converts all available emails to dictionaries. :return: List of dictionaries. """ |
return [self._construct_email(email, **extra) for email in self.emails] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_email(self, email, **extra):
""" Converts incoming data to properly structured dictionary. """ |
if isinstance(email, dict):
email = Email(manager=self._manager, **email)
elif isinstance(email, (MIMEText, MIMEMultipart)):
email = Email.from_mime(email, self._manager)
elif not isinstance(email, Email):
raise ValueError
email._update(extra)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, **extra):
""" Sends email batch. :return: Information about sent emails. :rtype: `list` """ |
emails = self.as_dict(**extra)
responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)]
return sum(responses, []) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send( self, message=None, From=None, To=None, Cc=None, Bcc=None, Subject=None, Tag=None, HtmlBody=None, TextBody=None, Metadata=None, ReplyTo=None, Headers=No... |
assert not (message and (From or To)), "You should specify either message or From and To parameters"
assert TrackLinks in ("None", "HtmlAndText", "HtmlOnly", "TextOnly")
if message is None:
message = self.Email(
From=From,
To=To,
Cc=Cc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def activate(self):
""" Activates the bounce instance and updates it with the latest data. :return: Activation status. :rtype: `str` """ |
response = self._manager.activate(self.ID)
self._update(response["Bounce"])
return response["Message"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all( self, count=500, offset=0, type=None, inactive=None, emailFilter=None, tag=None, messageID=None, fromdate=None, todate=None, ):
""" Returns many bounces... |
responses = self.call_many(
"GET",
"/bounces/",
count=count,
offset=offset,
type=type,
inactive=inactive,
emailFilter=emailFilter,
tag=tag,
messageID=messageID,
fromdate=fromdate,
... |
<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_kwargs(self, kwargs, count, offset):
""" Helper to support handy dictionaries merging on all Python versions. """ |
kwargs.update({self.count_key: count, self.offset_key: offset})
return 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 overview(self, tag=None, fromdate=None, todate=None):
""" Gets a brief overview of statistics for all of your outbound email. """ |
return self.call("GET", "/stats/outbound", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spam(self, tag=None, fromdate=None, todate=None):
""" Gets a total count of recipients who have marked your email as spam. """ |
return self.call("GET", "/stats/outbound/spam", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opens(self, tag=None, fromdate=None, todate=None):
""" Gets total counts of recipients who opened your emails. This is only recorded when open tracking is en... |
return self.call("GET", "/stats/outbound/opens", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opens_platforms(self, tag=None, fromdate=None, todate=None):
""" Gets an overview of the platforms used to open your emails. This is only recorded when open ... |
return self.call("GET", "/stats/outbound/opens/platforms", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emailclients(self, tag=None, fromdate=None, todate=None):
""" Gets an overview of the email clients used to open your emails. This is only recorded when open... |
return self.call("GET", "/stats/outbound/opens/emailclients", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readtimes(self, tag=None, fromdate=None, todate=None):
""" Gets the length of time that recipients read emails along with counts for each time. This is only ... |
return self.call("GET", "/stats/outbound/opens/readtimes", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clicks(self, tag=None, fromdate=None, todate=None):
""" Gets total counts of unique links that were clicked. """ |
return self.call("GET", "/stats/outbound/clicks", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def browserfamilies(self, tag=None, fromdate=None, todate=None):
""" Gets an overview of the browsers used to open links in your emails. This is only recorded wh... |
return self.call("GET", "/stats/outbound/clicks/browserfamilies", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clicks_platforms(self, tag=None, fromdate=None, todate=None):
""" Gets an overview of the browser platforms used to open your emails. This is only recorded w... |
return self.call("GET", "/stats/outbound/clicks/platforms", tag=tag, fromdate=fromdate, todate=todate) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def line_rate(self, filename=None):
""" Return the global line rate of the coverage report. If the `filename` file is given, return the line rate of the file. ""... |
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['line-rate']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def branch_rate(self, filename=None):
""" Return the global branch rate of the coverage report. If the `filename` file is given, return the branch rate of the fi... |
if filename is None:
el = self.xml
else:
el = self._get_class_element_by_filename(filename)
return float(el.attrib['branch-rate']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def missed_statements(self, filename):
""" Return a list of uncovered line numbers for each of the missed statements found for the file `filename`. """ |
el = self._get_class_element_by_filename(filename)
lines = el.xpath('./lines/line[@hits=0]')
return [int(l.attrib['number']) for l in lines] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def missed_lines(self, filename):
""" Return a list of extrapolated uncovered line numbers for the file `filename` according to `Cobertura.line_statuses`. """ |
statuses = self.line_statuses(filename)
statuses = extrapolate_coverage(statuses)
return [lno for lno, status in statuses if status is False] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_source(self, filename):
""" Return a list of namedtuple `Line` for each line of code found in the source file with the given `filename`. """ |
lines = []
try:
with self.filesystem.open(filename) as f:
line_statuses = dict(self.line_statuses(filename))
for lineno, source in enumerate(f, start=1):
line_status = line_statuses.get(lineno)
line = Line(lineno, sourc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_misses(self, filename=None):
""" Return the total number of uncovered statements for the file `filename`. If `filename` is not given, return the total ... |
if filename is not None:
return len(self.missed_statements(filename))
total = 0
for filename in self.files():
total += len(self.missed_statements(filename))
return total |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_hits(self, filename=None):
""" Return the total number of covered statements for the file `filename`. If `filename` is not given, return the total numb... |
if filename is not None:
return len(self.hit_statements(filename))
total = 0
for filename in self.files():
total += len(self.hit_statements(filename))
return total |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_statements(self, filename=None):
""" Return the total number of statements for the file `filename`. If `filename` is not given, return the total number... |
if filename is not None:
statements = self._get_lines_by_filename(filename)
return len(statements)
total = 0
for filename in self.files():
statements = self._get_lines_by_filename(filename)
total += len(statements)
return total |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files(self):
""" Return the list of available files in the coverage report. """ |
# maybe replace with a trie at some point? see has_file FIXME
already_seen = set()
filenames = []
for el in self.xml.xpath("//class"):
filename = el.attrib['filename']
if filename in already_seen:
continue
already_seen.add(filename)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def source_lines(self, filename):
""" Return a list for source lines of file `filename`. """ |
with self.filesystem.open(filename) as f:
return f.readlines() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_better_coverage(self):
""" Return `True` if coverage of has improved, `False` otherwise. This does not ensure that all changes have been covered. If this... |
for filename in self.files():
if self.diff_total_misses(filename) > 0:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_all_changes_covered(self):
""" Return `True` if all changes have been covered, `False` otherwise. """ |
for filename in self.files():
for hunk in self.file_source_hunks(filename):
for line in hunk:
if line.reason is None:
continue # line untouched
if line.status is False:
return False # line not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_source(self, filename):
""" Return a list of namedtuple `Line` for each line of code found in the given file `filename`. """ |
if self.cobertura1.has_file(filename) and \
self.cobertura1.filesystem.has_file(filename):
lines1 = self.cobertura1.source_lines(filename)
line_statuses1 = dict(self.cobertura1.line_statuses(
filename))
else:
lines1 = []
li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_source_hunks(self, filename):
""" Like `CoberturaDiff.file_source`, but returns a list of line hunks of the lines that have changed for the given file `... |
lines = self.file_source(filename)
hunks = hunkify_lines(lines)
return hunks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitor(self):
"""Flushes the queue periodically.""" |
while self.monitor_running.is_set():
if time.time() - self.last_flush > self.batch_time:
if not self.queue.empty():
logger.info("Queue Flush: time without flush exceeded")
self.flush_queue()
time.sleep(self.batch_time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_records(self, records, partition_key=None):
"""Add a list of data records to the record queue in the proper format. Convinience method that calls self.pu... |
for record in records:
self.put_record(record, partition_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 put_record(self, data, partition_key=None):
"""Add data to the record queue in the proper format. Parameters data : str Data to send. partition_key: str Hash... |
# Byte encode the data
data = encode_data(data)
# Create a random partition key if not provided
if not partition_key:
partition_key = uuid.uuid4().hex
# Build the record
record = {
'Data': data,
'PartitionKey': partition_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 close(self):
"""Flushes the queue and waits for the executor to finish.""" |
logger.info('Closing producer')
self.flush_queue()
self.monitor_running.clear()
self.pool.shutdown()
logger.info('Producer closed') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush_queue(self):
"""Grab all the current records in the queue and send them.""" |
records = []
while not self.queue.empty() and len(records) < self.batch_size:
records.append(self.queue.get())
if records:
self.send_records(records)
self.last_flush = time.time() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_records(self, records, attempt=0):
"""Send records to the Kinesis stream. Falied records are sent again with an exponential backoff decay. Parameters re... |
# If we already tried more times than we wanted, save to a file
if attempt > self.max_retries:
logger.warning('Writing {} records to file'.format(len(records)))
with open('failed_records.dlq', 'ab') as f:
for r in records:
f.write(r.get('Data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rangify(number_list):
"""Assumes the list is sorted.""" |
if not number_list:
return number_list
ranges = []
range_start = prev_num = number_list[0]
for num in number_list[1:]:
if num != (prev_num + 1):
ranges.append((range_start, prev_num))
range_start = num
prev_num = num
ranges.append((range_start, pre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hunkify_lines(lines, context=3):
""" Return a list of line hunks given a list of lines `lines`. The number of context lines can be control with `context` whi... |
# Find contiguous line changes
ranges = []
range_start = None
for i, line in enumerate(lines):
if line.status is not None:
if range_start is None:
range_start = i
continue
elif range_start is not None:
range_stop = i
ra... |
<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(cobertura_file, format, output, source, source_prefix):
"""show coverage summary of a Cobertura report""" |
cobertura = Cobertura(cobertura_file, source=source)
Reporter = reporters[format]
reporter = Reporter(cobertura)
report = reporter.generate()
if not isinstance(report, bytes):
report = report.encode('utf-8')
isatty = True if output is None else output.isatty()
click.echo(report, 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 diff( cobertura_file1, cobertura_file2, color, format, output, source1, source2, source_prefix1, source_prefix2, source):
"""compare coverage of two Cobertur... |
cobertura1 = Cobertura(
cobertura_file1,
source=source1,
source_prefix=source_prefix1
)
cobertura2 = Cobertura(
cobertura_file2,
source=source2,
source_prefix=source_prefix2
)
Reporter = delta_reporters[format]
reporter_args = [cobertura1, cobert... |
<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(self, filename):
""" Yield a file-like object for file `filename`. This function is a context manager. """ |
filename = self.real_filename(filename)
if not os.path.exists(filename):
raise self.FileNotFound(filename)
with codecs.open(filename, encoding='utf-8') as f:
yield 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 nickmask(prefix: str, kwargs: Dict[str, Any]) -> None: """ store nick, user, host in kwargs if prefix is correct format """ |
if "!" in prefix and "@" in prefix:
# From a user
kwargs["nick"], remainder = prefix.split("!", 1)
kwargs["user"], kwargs["host"] = remainder.split("@", 1)
else:
# From a server, probably the host
kwargs["host"] = prefix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_line(msg: str) -> Tuple[str, str, List[str]]: """ Parse message according to rfc 2812 for routing """ |
match = RE_IRCLINE.match(msg)
if not match:
raise ValueError("Invalid line")
prefix = match.group("prefix") or ""
command = match.group("command")
params = (match.group("params") or "").split()
message = match.group("message") or ""
if message:
params.append(message)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def f(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None) -> str: """ Alias for more readable command construction """ |
if default is not None:
return str(kwargs.get(field, default))
return str(kwargs[field]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.