neulab/docprompting-conala huggingface dataset:
TransactionTestCase.available_apps  
 Warning This attribute is a private API. It may be changed or removed without a deprecation period in the future, for instance to accommodate changes in application loading. It’s used to optimize Django’s own test suite, which contains hundreds of models but no relations between models in different applications.  By default, available_apps is set to None. After each test, Django calls flush to reset the database state. This empties all tables and emits the post_migrate signal, which recreates one content type and four permissions for each model. This operation gets expensive proportionally to the number of models. Setting available_apps to a list of applications instructs Django to behave as if only the models from these applications were available. The behavior of TransactionTestCase changes as follows:  
post_migrate is fired before each test to create the content types and permissions for each model in available apps, in case they’re missing. After each test, Django empties only tables corresponding to models in available apps. However, at the database level, truncation may cascade to related models in unavailable apps. Furthermore post_migrate isn’t fired; it will be fired by the next TransactionTestCase, after the correct set of applications is selected.  Since the database isn’t fully flushed, if a test creates instances of models not included in available_apps, they will leak and they may cause unrelated tests to fail. Be careful with tests that use sessions; the default session engine stores them in the database. Since post_migrate isn’t emitted after flushing the database, its state after a TransactionTestCase isn’t the same as after a TestCase: it’s missing the rows created by listeners to post_migrate. Considering the order in which tests are executed, this isn’t an issue, provided either all TransactionTestCase in a given test suite declare available_apps, or none of them. available_apps is mandatory in Django’s own test suite.
TransactionTestCase.reset_sequences  
Setting reset_sequences = True on a TransactionTestCase will make sure sequences are always reset before the test run: class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
    reset_sequences = True

    def test_animal_pk(self):
        lion = Animal.objects.create(name="lion", sound="roar")
        # lion.pk is guaranteed to always be 1
        self.assertEqual(lion.pk, 1)
 Unless you are explicitly testing primary keys sequence numbers, it is recommended that you do not hard code primary key values in tests. Using reset_sequences = True will slow down the test, since the primary key reset is a relatively expensive database operation.
setup_databases(verbosity, interactive, *, time_keeper=None, keepdb=False, debug_sql=False, parallel=0, aliases=None, serialized_aliases=None, **kwargs)  
Creates the test databases. Returns a data structure that provides enough detail to undo the changes that have been made. This data will be provided to the teardown_databases() function at the conclusion of testing. The aliases argument determines which DATABASES aliases test databases should be set up for. If it’s not provided, it defaults to all of DATABASES aliases. The serialized_aliases argument determines what subset of aliases test databases should have their state serialized to allow usage of the serialized_rollback feature. If it’s not provided, it defaults to aliases.  Changed in Django 3.2: The time_keeper kwarg was added, and all kwargs were made keyword-only.   Changed in Django 4.0: The serialized_aliases kwarg was added.
setup_test_environment(debug=None)  
Performs global pre-test setup, such as installing instrumentation for the template rendering system and setting up the dummy email outbox. If debug isn’t None, the DEBUG setting is updated to its value.
teardown_databases(old_config, parallel=0, keepdb=False)  
Destroys the test databases, restoring pre-test conditions. old_config is a data structure defining the changes in the database configuration that need to be reversed. It’s the return value of the setup_databases() method.
teardown_test_environment()  
Performs global post-test teardown, such as removing instrumentation from the template system and restoring normal email services.
include(module, namespace=None)  
include(pattern_list)  
include((pattern_list, app_namespace), namespace=None)  
A function that takes a full Python import path to another URLconf module that should be “included” in this place. Optionally, the application namespace and instance namespace where the entries will be included into can also be specified. Usually, the application namespace should be specified by the included module. If an application namespace is set, the namespace argument can be used to set a different instance namespace. include() also accepts as an argument either an iterable that returns URL patterns or a 2-tuple containing such iterable plus the names of the application namespaces.    
Parameters:

 
module – URLconf module (or module name) 
namespace (str) – Instance namespace for the URL entries being included 
pattern_list – Iterable of path() and/or re_path() instances. 
app_namespace (str) – Application namespace for the URL entries being included
class ResolverMatch  
 
func  
The view function that would be used to serve the URL 
  
args  
The arguments that would be passed to the view function, as parsed from the URL. 
  
kwargs  
The keyword arguments that would be passed to the view function, as parsed from the URL. 
  
url_name  
The name of the URL pattern that matches the URL. 
  
route  
The route of the matching URL pattern. For example, if path('users/<id>/', ...) is the matching pattern, route will contain 'users/<id>/'. 
  
tried  
 New in Django 3.2.  The list of URL patterns tried before the URL either matched one or exhausted available patterns. 
  
app_name  
The application namespace for the URL pattern that matches the URL. 
  
app_names  
The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the app_name is 'foo:bar', then app_names will be ['foo', 'bar']. 
  
namespace  
The instance namespace for the URL pattern that matches the URL. 
  
namespaces  
The list of individual namespace components in the full instance namespace for the URL pattern that matches the URL. i.e., if the namespace is foo:bar, then namespaces will be ['foo', 'bar']. 
  
view_name  
The name of the view that matches the URL, including the namespace if there is one.
app_names  
The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the app_name is 'foo:bar', then app_names will be ['foo', 'bar'].
kwargs  
The keyword arguments that would be passed to the view function, as parsed from the URL.
namespaces  
The list of individual namespace components in the full instance namespace for the URL pattern that matches the URL. i.e., if the namespace is foo:bar, then namespaces will be ['foo', 'bar'].
route  
The route of the matching URL pattern. For example, if path('users/<id>/', ...) is the matching pattern, route will contain 'users/<id>/'.
tried  
 New in Django 3.2.  The list of URL patterns tried before the URL either matched one or exhausted available patterns.
view_name  
The name of the view that matches the URL, including the namespace if there is one.
reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
add_never_cache_headers(response)  
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.
get_cache_key(request, key_prefix=None, method='GET', cache=None)  
Returns a cache key based on the request path. It can be used in the request phase because it pulls the list of headers to take into account from the global path registry and uses those to build a cache key to check against. If there is no headerlist stored, the page needs to be rebuilt, so this function returns None.
get_max_age(response)  
Returns the max-age from the response Cache-Control header as an integer (or None if it wasn’t found or wasn’t an integer).
learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None)  
Learns what headers to take into account for some request path from the response object. It stores those headers in a global path registry so that later access to that path will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key.
patch_cache_control(response, **kwargs)  
This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows:  All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. If the value of a parameter is True (exactly True, not just a true value), only the parameter name is added to the header. All other parameters are added with their value, after applying str() to it.
patch_response_headers(response, cache_timeout=None)  
Adds some useful headers to the given HttpResponse object:  Expires Cache-Control  Each header is only added if it isn’t already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default.
patch_vary_headers(response, newheaders)  
Adds (or updates) the Vary header in the given HttpResponse object. newheaders is a list of header names that should be in Vary. If headers contains an asterisk, then Vary header will consist of a single asterisk '*', according to RFC 7231#section-7.1.4. Otherwise, existing headers in Vary aren’t removed.
parse_datetime(value)  
Parses a string and returns a datetime.datetime. UTC offsets are supported; if value describes one, the result’s tzinfo attribute is a datetime.timezone instance.
parse_duration(value)  
Parses a string and returns a datetime.timedelta. Expects data in the format "DD HH:MM:SS.uuuuuu", "DD HH:MM:SS,uuuuuu", or as specified by ISO 8601 (e.g. P4DT1H15M20S which is equivalent to 4 1:15:20) or PostgreSQL’s day-time interval format (e.g. 3 days 04:05:06).
parse_time(value)  
Parses a string and returns a datetime.time. UTC offsets aren’t supported; if value describes one, the result is None.
async_only_middleware(middleware) [source]
 
Marks a middleware as asynchronous-only. Django will wrap it in an asynchronous event loop when it is called from the WSGI request path.
decorator_from_middleware(middleware_class) [source]
 
Given a middleware class, returns a view decorator. This lets you use middleware functionality on a per-view basis. The middleware is created with no params passed. It assumes middleware that’s compatible with the old style of Django 1.9 and earlier (having methods like process_request(), process_exception(), and process_response()).
decorator_from_middleware_with_args(middleware_class) [source]
 
Like decorator_from_middleware, but returns a function that accepts the arguments to be passed to the middleware_class. For example, the cache_page() decorator is created from the CacheMiddleware like this: cache_page = decorator_from_middleware_with_args(CacheMiddleware)

@cache_page(3600)
def my_view(request):
    pass
method_decorator(decorator, name='') [source]
 
Converts a function decorator into a method decorator. It can be used to decorate methods or classes; in the latter case, name is the name of the method to be decorated and is required. decorator may also be a list or tuple of functions. They are wrapped in reverse order so that the call order is the order in which the functions appear in the list/tuple. See decorating class based views for example usage.
sync_and_async_middleware(middleware) [source]
 
Marks a middleware as sync and async compatible, this allows to avoid converting requests. You must implement detection of the current request type to use this decorator. See asynchronous middleware documentation for details.
sync_only_middleware(middleware) [source]
 
Marks a middleware as synchronous-only. (The default in Django, but this allows you to future-proof if the default ever changes in a future release.)
escape_uri_path(path) [source]
 
Escapes the unsafe characters from the path portion of a Uniform Resource Identifier (URI).
filepath_to_uri(path) [source]
 
Convert a file system path to a URI portion that is suitable for inclusion in a URL. The path is assumed to be either UTF-8 bytes, string, or a Path. This method will encode certain characters that would normally be recognized as special characters for URIs. Note that this method does not encode the ‘ character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result.
force_bytes(s, encoding='utf-8', strings_only=False, errors='strict') [source]
 
Similar to smart_bytes, except that lazy instances are resolved to bytestrings, rather than kept as lazy objects. If strings_only is True, don’t convert (some) non-string-like objects.
force_str(s, encoding='utf-8', strings_only=False, errors='strict') [source]
 
Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don’t convert (some) non-string-like objects.
iri_to_uri(iri) [source]
 
Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987#section-3.1, slightly simplified since the input is assumed to be a string rather than an arbitrary byte stream. Takes an IRI (string or UTF-8 bytes) and returns a string containing the encoded result.
is_protected_type(obj) [source]
 
Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_str(strings_only=True).
smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict') [source]
 
Returns a bytestring version of arbitrary object s, encoded as specified in encoding. If strings_only is True, don’t convert (some) non-string-like objects.
smart_str(s, encoding='utf-8', strings_only=False, errors='strict') [source]
 
Returns a str object representing arbitrary object s. Treats bytestrings using the encoding codec. If strings_only is True, don’t convert (some) non-string-like objects.
uri_to_iri(uri) [source]
 
Converts a Uniform Resource Identifier into an Internationalized Resource Identifier. This is an algorithm from section 3.2 of RFC 3987#section-3.2. Takes a URI in ASCII bytes and returns a string containing the encoded result.
class Atom1Feed(SyndicationFeed)  
Spec: RFC 4287
get_tag_uri(url, date)  
Creates a TagURI. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
class Rss201rev2Feed(RssFeed)  
Spec: https://cyber.harvard.edu/rss/rss.html
class RssUserland091Feed(RssFeed)  
Spec: http://backend.userland.com/rss091
class SyndicationFeed  
Base class for all syndication feeds. Subclasses should provide write().  
__init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs)  
Initialize the feed with the given dictionary of metadata, which applies to the entire feed. Any extra keyword arguments you pass to __init__ will be stored in self.feed. All parameters should be strings, except categories, which should be a sequence of strings. 
  
add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)  
Adds an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is a list of Enclosure instances. 
  
num_items() 
  
root_attributes()  
Return extra attributes to place on the root (i.e. feed/channel) element. Called from write(). 
  
add_root_elements(handler)  
Add elements in the root (i.e. feed/channel) element. Called from write(). 
  
item_attributes(item)  
Return extra attributes to place on each item (i.e. item/entry) element. 
  
add_item_elements(handler, item)  
Add elements on each item (i.e. item/entry) element. 
  
write(outfile, encoding)  
Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. 
  
writeString(encoding)  
Returns the feed in the given encoding as a string. 
  
latest_post_date()  
Returns the latest pubdate or updateddate for all items in the feed. If no items have either of these attributes this returns the current UTC date/time.
__init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs)  
Initialize the feed with the given dictionary of metadata, which applies to the entire feed. Any extra keyword arguments you pass to __init__ will be stored in self.feed. All parameters should be strings, except categories, which should be a sequence of strings.
add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)  
Adds an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is a list of Enclosure instances.
add_item_elements(handler, item)  
Add elements on each item (i.e. item/entry) element.
add_root_elements(handler)  
Add elements in the root (i.e. feed/channel) element. Called from write().
item_attributes(item)  
Return extra attributes to place on each item (i.e. item/entry) element.
latest_post_date()  
Returns the latest pubdate or updateddate for all items in the feed. If no items have either of these attributes this returns the current UTC date/time.
root_attributes()  
Return extra attributes to place on the root (i.e. feed/channel) element. Called from write().
write(outfile, encoding)  
Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.
class cached_property(func, name=None) [source]
 
The @cached_property decorator caches the result of a method with a single self argument as a property. The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned. Consider a typical case, where a view might need to call a model’s method to perform some computation, before placing the model instance into the context, where the template might invoke the method once more: # the model
class Person(models.Model):

    def friends(self):
        # expensive computation
        ...
        return friends

# in the view:
if person.friends():
    ...
 And in the template you would have: {% for friend in person.friends %}
 Here, friends() will be called twice. Since the instance person in the view and the template are the same, decorating the friends() method with @cached_property can avoid that: from django.utils.functional import cached_property

class Person(models.Model):

    @cached_property
    def friends(self):
        ...
 Note that as the method is now a property, in Python code it will need to be accessed appropriately: # in the view:
if person.friends:
    ...
 The cached value can be treated like an ordinary attribute of the instance: # clear it, requiring re-computation next time it's called
del person.friends # or delattr(person, "friends")

# set a value manually, that will persist on the instance until cleared
person.friends = ["Huckleberry Finn", "Tom Sawyer"]
 Because of the way the descriptor protocol works, using del (or delattr) on a cached_property that hasn’t been accessed raises AttributeError. As well as offering potential performance advantages, @cached_property can ensure that an attribute’s value does not change unexpectedly over the life of an instance. This could occur with a method whose computation is based on datetime.now(), or if a change were saved to the database by some other process in the brief interval between subsequent invocations of a method on the same instance. You can make cached properties of methods. For example, if you had an expensive get_friends() method and wanted to allow calling it without retrieving the cached value, you could write: friends = cached_property(get_friends)
 While person.get_friends() will recompute the friends on each call, the value of the cached property will persist until you delete it as described above: x = person.friends         # calls first time
y = person.get_friends()   # calls again
z = person.friends         # does not call
x is z                     # is True
class classproperty(method=None) [source]
 
Similar to @classmethod, the @classproperty decorator converts the result of a method with a single cls argument into a property that can be accessed directly from the class.
keep_lazy(func, *resultclasses) [source]
 
Django offers many utility functions (particularly in django.utils) that take a string as their first argument and do something to that string. These functions are used by template filters as well as directly in other code. If you write your own similar functions and deal with translations, you’ll face the problem of what to do when the first argument is a lazy translation object. You don’t want to convert it to a string immediately, because you might be using this function outside of a view (and hence the current thread’s locale setting will not be correct). For cases like this, use the django.utils.functional.keep_lazy() decorator. It modifies the function so that if it’s called with a lazy translation as one of its arguments, the function evaluation is delayed until it needs to be converted to a string. For example: from django.utils.functional import keep_lazy, keep_lazy_text

def fancy_utility_function(s, ...):
    # Do some conversion on string 's'
    ...
fancy_utility_function = keep_lazy(str)(fancy_utility_function)

# Or more succinctly:
@keep_lazy(str)
def fancy_utility_function(s, ...):
    ...
 The keep_lazy() decorator takes a number of extra arguments (*args) specifying the type(s) that the original function can return. A common use case is to have functions that return text. For these, you can pass the str type to keep_lazy (or use the keep_lazy_text() decorator described in the next section). Using this decorator means you can write your function and assume that the input is a proper string, then add support for lazy translation objects at the end.
keep_lazy_text(func) [source]
 
A shortcut for keep_lazy(str)(func). If you have a function that returns text and you want to be able to take lazy arguments while delaying their evaluation, you can use this decorator: from django.utils.functional import keep_lazy, keep_lazy_text

# Our previous example was:
@keep_lazy(str)
def fancy_utility_function(s, ...):
    ...

# Which can be rewritten as:
@keep_lazy_text
def fancy_utility_function(s, ...):
    ...
conditional_escape(text)  
Similar to escape(), except that it doesn’t operate on pre-escaped strings, so it will not double escape.
escape(text)  
Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. The input is first coerced to a string and the output has mark_safe() applied.