neulab/docprompting-conala huggingface dataset:
format_html(format_string, *args, **kwargs)  
This is similar to str.format(), except that it is appropriate for building up HTML fragments. All args and kwargs are passed through conditional_escape() before being passed to str.format(). For the case of building up small HTML fragments, this function is to be preferred over string interpolation using % or str.format() directly, because it applies escaping to all arguments - just like the template system applies escaping by default. So, instead of writing: mark_safe("%s <b>%s</b> %s" % (
    some_html,
    escape(some_text),
    escape(some_other_text),
))
 You should instead use: format_html("{} <b>{}</b> {}",
    mark_safe(some_html),
    some_text,
    some_other_text,
)
 This has the advantage that you don’t need to apply escape() to each argument and risk a bug and an XSS vulnerability if you forget one. Note that although this function uses str.format() to do the interpolation, some of the formatting options provided by str.format() (e.g. number formatting) will not work, since all arguments are passed through conditional_escape() which (ultimately) calls force_str() on the values.
format_html_join(sep, format_string, args_generator)  
A wrapper of format_html(), for the common case of a group of arguments that need to be formatted using the same format string, and then joined using sep. sep is also passed through conditional_escape(). args_generator should be an iterator that returns the sequence of args that will be passed to format_html(). For example: format_html_join(
    '\n', "<li>{} {}</li>",
    ((u.first_name, u.last_name) for u in users)
)
html_safe()  
The __html__() method on a class helps non-Django templates detect classes whose output doesn’t require HTML escaping. This decorator defines the __html__() method on the decorated class by wrapping __str__() in mark_safe(). Ensure the __str__() method does indeed return text that doesn’t require HTML escaping.
strip_tags(value)  
Tries to remove anything that looks like an HTML tag from the string, that is anything contained within <>. Absolutely NO guarantee is provided about the resulting string being HTML safe. So NEVER mark safe the result of a strip_tag call without escaping it first, for example with escape(). For example: strip_tags(value)
 If value is "<b>Joel</b> <button>is</button> a <span>slug</span>" the return value will be "Joel is a slug". If you are looking for a more robust solution, take a look at the bleach Python library.
base36_to_int(s) [source]
 
Converts a base 36 string to an integer.
http_date(epoch_seconds=None) [source]
 
Formats the time to match the RFC 1123#section-5.2.14 date format as specified by HTTP RFC 7231#section-7.1.1.1. Accepts a floating point number expressed in seconds since the epoch in UTC–such as that outputted by time.time(). If set to None, defaults to the current time. Outputs a string in the format Wdy, DD Mon YYYY HH:MM:SS GMT.
int_to_base36(i) [source]
 
Converts a positive integer to a base 36 string.
urlencode(query, doseq=False) [source]
 
A version of Python’s urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values.
urlsafe_base64_decode(s) [source]
 
Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.
urlsafe_base64_encode(s) [source]
 
Encodes a bytestring to a base64 string for use in URLs, stripping any trailing equal signs.
class AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)  
This handler sends an email to the site ADMINS for each log message it receives. If the log record contains a request attribute, the full details of the request will be included in the email. The email subject will include the phrase “internal IP” if the client’s IP address is in the INTERNAL_IPS setting; if not, it will include “EXTERNAL IP”. If the log record contains stack trace information, that stack trace will be included in the email. The include_html argument of AdminEmailHandler is used to control whether the traceback email includes an HTML attachment containing the full content of the debug web page that would have been produced if DEBUG were True. To set this value in your configuration, include it in the handler definition for django.utils.log.AdminEmailHandler, like this: 'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'class': 'django.utils.log.AdminEmailHandler',
        'include_html': True,
    },
},
 Be aware of the security implications of logging when using the AdminEmailHandler. By setting the email_backend argument of AdminEmailHandler, the email backend that is being used by the handler can be overridden, like this: 'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'class': 'django.utils.log.AdminEmailHandler',
        'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
    },
},
 By default, an instance of the email backend specified in EMAIL_BACKEND will be used. The reporter_class argument of AdminEmailHandler allows providing an django.views.debug.ExceptionReporter subclass to customize the traceback text sent in the email body. You provide a string import path to the class you wish to use, like this: 'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'class': 'django.utils.log.AdminEmailHandler',
        'include_html': True,
        'reporter_class': 'somepackage.error_reporter.CustomErrorReporter',
    },
},
  
send_mail(subject, message, *args, **kwargs)  
Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.
send_mail(subject, message, *args, **kwargs)  
Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.
class CallbackFilter(callback)  
This filter accepts a callback function (which should accept a single argument, the record to be logged), and calls it for each record that passes through the filter. Handling of that record will not proceed if the callback returns False. For instance, to filter out UnreadablePostError (raised when a user cancels an upload) from the admin emails, you would create a filter function: from django.http import UnreadablePostError

def skip_unreadable_post(record):
    if record.exc_info:
        exc_type, exc_value = record.exc_info[:2]
        if isinstance(exc_value, UnreadablePostError):
            return False
    return True
 and then add it to your logging config: 'filters': {
    'skip_unreadable_posts': {
        '()': 'django.utils.log.CallbackFilter',
        'callback': skip_unreadable_post,
    },
},
'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'filters': ['skip_unreadable_posts'],
        'class': 'django.utils.log.AdminEmailHandler',
    },
},
class RequireDebugFalse  
This filter will only pass on records when settings.DEBUG is False. This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False: 'filters': {
    'require_debug_false': {
        '()': 'django.utils.log.RequireDebugFalse',
    },
},
'handlers': {
    'mail_admins': {
        'level': 'ERROR',
        'filters': ['require_debug_false'],
        'class': 'django.utils.log.AdminEmailHandler',
    },
},
class RequireDebugTrue  
This filter is similar to RequireDebugFalse, except that records are passed only when DEBUG is True.
import_string(dotted_path) [source]
 
Imports a dotted module path and returns the attribute/class designated by the last name in the path. Raises ImportError if the import failed. For example: from django.utils.module_loading import import_string
ValidationError = import_string('django.core.exceptions.ValidationError')
 is equivalent to: from django.core.exceptions import ValidationError
mark_safe(s) [source]
 
Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. Can be called multiple times on a single string. Can also be used as a decorator. For building up fragments of HTML, you should normally be using django.utils.html.format_html() instead. String marked safe will become unsafe again if modified. For example: >>> mystr = '<b>Hello World</b>   '
>>> mystr = mark_safe(mystr)
>>> type(mystr)
<class 'django.utils.safestring.SafeString'>

>>> mystr = mystr.strip()  # removing whitespace
>>> type(mystr)
<type 'str'>
class SafeString [source]
 
A str subclass that has been specifically marked as “safe” (requires no further escaping) for HTML output purposes.
format_lazy(format_string, *args, **kwargs)  
A version of str.format() for when format_string, args, and/or kwargs contain lazy objects. The first argument is the string to be formatted. For example: from django.utils.text import format_lazy
from django.utils.translation import pgettext_lazy

urlpatterns = [
    path(format_lazy('{person}/<int:pk>/', person=pgettext_lazy('URL', 'person')),
         PersonDetailView.as_view()),
]
 This example allows translators to translate part of the URL. If “person” is translated to “persona”, the regular expression will match persona/(?P<pk>\d+)/$, e.g. persona/5/.
slugify(value, allow_unicode=False)  
Converts a string to a URL slug by:  Converting to ASCII if allow_unicode is False (the default). Converting to lowercase. Removing characters that aren’t alphanumerics, underscores, hyphens, or whitespace. Replacing any whitespace or repeated dashes with single dashes. Removing leading and trailing whitespace, dashes, and underscores.  For example: >>> slugify(' Joel is a slug ')
'joel-is-a-slug'
 If you want to allow Unicode characters, pass allow_unicode=True. For example: >>> slugify('你好 World', allow_unicode=True)
'你好-world'
  Changed in Django 3.2: In older versions, leading and trailing dashes and underscores are not removed.
activate(timezone)  
Sets the current time zone. The timezone argument must be an instance of a tzinfo subclass or a time zone name.
get_fixed_timezone(offset)  
Returns a tzinfo instance that represents a time zone with a fixed offset from UTC. offset is a datetime.timedelta or an integer number of minutes. Use positive values for time zones east of UTC and negative values for west of UTC.
is_aware(value)  
Returns True if value is aware, False if it is naive. This function assumes that value is a datetime.
is_naive(value)  
Returns True if value is naive, False if it is aware. This function assumes that value is a datetime.
localdate(value=None, timezone=None)  
Uses localtime() to convert an aware datetime to a date() in a different time zone, by default the current time zone. When value is omitted, it defaults to now(). This function doesn’t work on naive datetimes.
localtime(value=None, timezone=None)  
Converts an aware datetime to a different time zone, by default the current time zone. When value is omitted, it defaults to now(). This function doesn’t work on naive datetimes; use make_aware() instead.
make_aware(value, timezone=None, is_dst=None)  
Returns an aware datetime that represents the same point in time as value in timezone, value being a naive datetime. If timezone is set to None, it defaults to the current time zone.  Deprecated since version 4.0: When using pytz, the pytz.AmbiguousTimeError exception is raised if you try to make value aware during a DST transition where the same time occurs twice (when reverting from DST). Setting is_dst to True or False will avoid the exception by choosing if the time is pre-transition or post-transition respectively. When using pytz, the pytz.NonExistentTimeError exception is raised if you try to make value aware during a DST transition such that the time never occurred. For example, if the 2:00 hour is skipped during a DST transition, trying to make 2:30 aware in that time zone will raise an exception. To avoid that you can use is_dst to specify how make_aware() should interpret such a nonexistent time. If is_dst=True then the above time would be interpreted as 2:30 DST time (equivalent to 1:30 local time). Conversely, if is_dst=False the time would be interpreted as 2:30 standard time (equivalent to 3:30 local time). The is_dst parameter has no effect when using non-pytz timezone implementations. The is_dst parameter is deprecated and will be removed in Django 5.0.
make_naive(value, timezone=None)  
Returns a naive datetime that represents in timezone the same point in time as value, value being an aware datetime. If timezone is set to None, it defaults to the current time zone.
now()  
Returns a datetime that represents the current point in time. Exactly what’s returned depends on the value of USE_TZ:  If USE_TZ is False, this will be a naive datetime (i.e. a datetime without an associated timezone) that represents the current time in the system’s local timezone. If USE_TZ is True, this will be an aware datetime representing the current time in UTC. Note that now() will always return times in UTC regardless of the value of TIME_ZONE; you can use localtime() to get the time in the current time zone.
override(timezone)  
This is a Python context manager that sets the current time zone on entry with activate(), and restores the previously active time zone on exit. If the timezone argument is None, the current time zone is unset on entry with deactivate() instead. override is also usable as a function decorator.
activate(language)  
Fetches the translation object for a given language and activates it as the current translation object for the current thread.
check_for_language(lang_code)  
Checks whether there is a global language file for the given language code (e.g. ‘fr’, ‘pt_BR’). This is used to decide whether a user-provided language is available.
deactivate()  
Deactivates the currently active translation object so that further _ calls will resolve against the default translation object, again.
deactivate_all()  
Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.
get_language()  
Returns the currently selected language code. Returns None if translations are temporarily deactivated (by deactivate_all() or when None is passed to override()).
get_language_bidi()  
Returns selected language’s BiDi layout:  
False = left-to-right layout 
True = right-to-left layout
get_language_from_request(request, check_path=False)  
Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the function first checks the requested URL for whether its path begins with a language code listed in the LANGUAGES setting.
get_supported_language_variant(lang_code, strict=False)  
Returns lang_code if it’s in the LANGUAGES setting, possibly selecting a more generic variant. For example, 'es' is returned if lang_code is 'es-ar' and 'es' is in LANGUAGES but 'es-ar' isn’t. If strict is False (the default), a country-specific variant may be returned when neither the language code nor its generic variant is found. For example, if only 'es-co' is in LANGUAGES, that’s returned for lang_codes like 'es' and 'es-ar'. Those matches aren’t returned if strict=True. Raises LookupError if nothing is found.
gettext_noop(message)  
Marks strings for translation but doesn’t translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.
ngettext(singular, plural, number)  
Translates singular and plural and returns the appropriate string based on number.
npgettext(context, singular, plural, number)  
Translates singular and plural and returns the appropriate string based on number and the context.
npgettext_lazy(context, singular, plural, number)  
Same as the non-lazy versions above, but using lazy execution. See lazy translations documentation.
override(language, deactivate=False)  
A Python context manager that uses django.utils.translation.activate() to fetch the translation object for a given language, activates it as the translation object for the current thread and reactivates the previous active language on exit. Optionally, it can deactivate the temporary translation on exit with django.utils.translation.deactivate() if the deactivate argument is True. If you pass None as the language argument, a NullTranslations() instance is activated within the context. override is also usable as a function decorator.
pgettext(context, message)  
Translates message given the context and returns it as a string. For more information, see Contextual markers.
pgettext_lazy(context, message)  
Same as the non-lazy versions above, but using lazy execution. See lazy translations documentation.
templatize(src)  
Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
to_locale(language)  
Turns a language name (en-us) into a locale name (en_US).
Validators These validators are available from the django.contrib.postgres.validators module. KeysValidator  
class KeysValidator(keys, strict=False, messages=None)  
Validates that the given keys are contained in the value. If strict is True, then it also checks that there are no other keys present. The messages passed should be a dict containing the keys missing_keys and/or extra_keys.  Note Note that this checks only for the existence of a given key, not that the value of a key is non-empty.  
 Range validators RangeMaxValueValidator  
class RangeMaxValueValidator(limit_value, message=None)  
Validates that the upper bound of the range is not greater than limit_value. 
 RangeMinValueValidator  
class RangeMinValueValidator(limit_value, message=None)  
Validates that the lower bound of the range is not less than the limit_value.
class ExceptionReporter  
 
html_template_path  
 New in Django 3.2.  Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template. 
  
text_template_path  
 New in Django 3.2.  Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template. 
  
get_traceback_data()  
Return a dictionary containing traceback information. This is the main extension point for customizing exception reports, for example: from django.views.debug import ExceptionReporter


class CustomExceptionReporter(ExceptionReporter):
    def get_traceback_data(self):
        data = super().get_traceback_data()
        # ... remove/add something here ...
        return data
 
  
get_traceback_html()  
Return HTML version of exception report. Used for HTML version of debug 500 HTTP error page. 
  
get_traceback_text()  
Return plain text version of exception report. Used for plain text version of debug 500 HTTP error page and email reports.
get_traceback_data()  
Return a dictionary containing traceback information. This is the main extension point for customizing exception reports, for example: from django.views.debug import ExceptionReporter


class CustomExceptionReporter(ExceptionReporter):
    def get_traceback_data(self):
        data = super().get_traceback_data()
        # ... remove/add something here ...
        return data
get_traceback_html()  
Return HTML version of exception report. Used for HTML version of debug 500 HTTP error page.
get_traceback_text()  
Return plain text version of exception report. Used for plain text version of debug 500 HTTP error page and email reports.
html_template_path  
 New in Django 3.2.  Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template.
text_template_path  
 New in Django 3.2.  Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template.
class SafeExceptionReporterFilter  
 
cleansed_substitute  
The string value to replace sensitive value with. By default it replaces the values of sensitive variables with stars (**********). 
  
hidden_settings  
A compiled regular expression object used to match settings and request.META values considered as sensitive. By default equivalent to: import re

re.compile(r'API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE)
 
  
is_active(request)  
Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation. 
  
get_post_parameters(request)  
Returns the filtered dictionary of POST parameters. Sensitive values are replaced with cleansed_substitute. 
  
get_traceback_frame_variables(request, tb_frame)  
Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute.
cleansed_substitute  
The string value to replace sensitive value with. By default it replaces the values of sensitive variables with stars (**********).
get_post_parameters(request)  
Returns the filtered dictionary of POST parameters. Sensitive values are replaced with cleansed_substitute.
get_traceback_frame_variables(request, tb_frame)  
Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute.
hidden_settings  
A compiled regular expression object used to match settings and request.META values considered as sensitive. By default equivalent to: import re

re.compile(r'API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE)
is_active(request)  
Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation.
cache_control(**kwargs)  
This decorator patches the response’s Cache-Control header by adding all of the keyword arguments to it. See patch_cache_control() for the details of the transformation.
never_cache(view_func)  
This decorator adds a Cache-Control: max-age=0, no-cache, no-store,
must-revalidate, private header to a response to indicate that a page should never be cached.
no_append_slash()  
This decorator allows individual views to be excluded from APPEND_SLASH URL normalization.
csrf_exempt(view)  
This decorator marks a view as being exempt from the protection ensured by the middleware. Example: from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')
csrf_protect(view)  
Decorator that provides the protection of CsrfViewMiddleware to a view. Usage: from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect

@csrf_protect
def my_view(request):
    c = {}
    # ...
    return render(request, "a_template.html", c)
 If you are using class-based views, you can refer to Decorating class-based views.
ensure_csrf_cookie(view)  
This decorator forces a view to send the CSRF cookie.
requires_csrf_token(view)  
Normally the csrf_token template tag will not work if CsrfViewMiddleware.process_view or an equivalent like csrf_protect has not run. The view decorator requires_csrf_token can be used to ensure the template tag does work. This decorator works similarly to csrf_protect, but never rejects an incoming request. Example: from django.shortcuts import render
from django.views.decorators.csrf import requires_csrf_token

@requires_csrf_token
def my_view(request):
    c = {}
    # ...
    return render(request, "a_template.html", c)