Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
purge_cache
(cachevar, limit)
Trim down cache variable to the specified number of newest entries.
Trim down cache variable to the specified number of newest entries.
def purge_cache(cachevar, limit): ''' Trim down cache variable to the specified number of newest entries. ''' oldest = sorted(cachevar, key=lambda k: cachevar[k]['timestamp'])[0:limit + 1] remaining = oldest.pop() now = datetime.utcnow() log('debug', 'purge_cache({0}): age of oldest entry is...
[ "def", "purge_cache", "(", "cachevar", ",", "limit", ")", ":", "oldest", "=", "sorted", "(", "cachevar", ",", "key", "=", "lambda", "k", ":", "cachevar", "[", "k", "]", "[", "'timestamp'", "]", ")", "[", "0", ":", "limit", "+", "1", "]", "remaining...
[ 1204, 0 ]
[ 1218, 29 ]
python
en
['en', 'error', 'th']
False
asn_query
(ip)
http://www.team-cymru.com/IP-ASN-mapping.html
http://www.team-cymru.com/IP-ASN-mapping.html
def asn_query(ip): ''' http://www.team-cymru.com/IP-ASN-mapping.html ''' pi = list(reversed(ip.split('.'))) asn = dns_query('.'.join(pi + ['origin.asn.cymru.com.']), 'txt') if asn is not None: for txt in set([str(x) for x in asn]): log('debug', '{0}: Raw ASN lookup result: {1...
[ "def", "asn_query", "(", "ip", ")", ":", "pi", "=", "list", "(", "reversed", "(", "ip", ".", "split", "(", "'.'", ")", ")", ")", "asn", "=", "dns_query", "(", "'.'", ".", "join", "(", "pi", "+", "[", "'origin.asn.cymru.com.'", "]", ")", ",", "'tx...
[ 1250, 0 ]
[ 1261, 15 ]
python
en
['en', 'error', 'th']
False
get_ns_ips
(domain)
Extract IP addresses of name server(s) for a domain
Extract IP addresses of name server(s) for a domain
def get_ns_ips(domain): """ Extract IP addresses of name server(s) for a domain """ ns_ips = [] nameservers = dns_query(domain, 'ns') if nameservers is not None: for ns in nameservers: this_ns_ips = dns_query(str(ns), 'a') if this_ns_ips is not None: ...
[ "def", "get_ns_ips", "(", "domain", ")", ":", "ns_ips", "=", "[", "]", "nameservers", "=", "dns_query", "(", "domain", ",", "'ns'", ")", "if", "nameservers", "is", "not", "None", ":", "for", "ns", "in", "nameservers", ":", "this_ns_ips", "=", "dns_query"...
[ 1296, 0 ]
[ 1307, 17 ]
python
en
['en', 'error', 'th']
False
ns_is_host
(s, site)
Check if the host name in a link resolves to the same IP address as the IP addresses of all its name servers.
Check if the host name in a link resolves to the same IP address as the IP addresses of all its name servers.
def ns_is_host(s, site): ''' Check if the host name in a link resolves to the same IP address as the IP addresses of all its name servers. ''' for hostname in post_hosts(s, check_tld=True): if metasmoke_cache.is_website_whitelisted(hostname): continue host_ip = dns_query(...
[ "def", "ns_is_host", "(", "s", ",", "site", ")", ":", "for", "hostname", "in", "post_hosts", "(", "s", ",", "check_tld", "=", "True", ")", ":", "if", "metasmoke_cache", ".", "is_website_whitelisted", "(", "hostname", ")", ":", "continue", "host_ip", "=", ...
[ 1311, 0 ]
[ 1326, 20 ]
python
en
['en', 'error', 'th']
False
post_links
(post)
Helper function to extract URLs from a piece of HTML.
Helper function to extract URLs from a piece of HTML.
def post_links(post): """ Helper function to extract URLs from a piece of HTML. """ global LINK_CACHE if post in LINK_CACHE: log('debug', 'Returning cached links for post') return LINK_CACHE[post]['links'] # Fix stupid spammer tricks edited_post = post for p in COMMON_M...
[ "def", "post_links", "(", "post", ")", ":", "global", "LINK_CACHE", "if", "post", "in", "LINK_CACHE", ":", "log", "(", "'debug'", ",", "'Returning cached links for post'", ")", "return", "LINK_CACHE", "[", "post", "]", "[", "'links'", "]", "# Fix stupid spammer ...
[ 1465, 0 ]
[ 1494, 18 ]
python
en
['en', 'error', 'th']
False
post_hosts
(post, check_tld=False)
Return list of hostnames from the post_links() output. With check_tld=True, check if the links have valid TLDs; abandon and return an empty result if too many do not (limit is currently hardcoded at 3 invalid links). Augment LINK_CACHE with parsed hostnames.
Return list of hostnames from the post_links() output.
def post_hosts(post, check_tld=False): ''' Return list of hostnames from the post_links() output. With check_tld=True, check if the links have valid TLDs; abandon and return an empty result if too many do not (limit is currently hardcoded at 3 invalid links). Augment LINK_CACHE with parsed hos...
[ "def", "post_hosts", "(", "post", ",", "check_tld", "=", "False", ")", ":", "global", "LINK_CACHE", "if", "post", "in", "LINK_CACHE", "and", "'hosts'", "in", "LINK_CACHE", "[", "post", "]", ":", "return", "LINK_CACHE", "[", "post", "]", "[", "'hosts'", "...
[ 1497, 0 ]
[ 1540, 18 ]
python
en
['en', 'error', 'th']
False
perform_similarity_checks
(post, name)
Performs 4 tests to determine similarity between links in the post and the user name :param post: Test of the post :param name: Username to compare against :return: Float ratio of similarity
Performs 4 tests to determine similarity between links in the post and the user name :param post: Test of the post :param name: Username to compare against :return: Float ratio of similarity
def perform_similarity_checks(post, name): """ Performs 4 tests to determine similarity between links in the post and the user name :param post: Test of the post :param name: Username to compare against :return: Float ratio of similarity """ max_similarity, similar_links = 0.0, [] # Kee...
[ "def", "perform_similarity_checks", "(", "post", ",", "name", ")", ":", "max_similarity", ",", "similar_links", "=", "0.0", ",", "[", "]", "# Keep checking links until one is deemed \"similar\"", "for", "link", "in", "post_links", "(", "post", ")", ":", "domain", ...
[ 1544, 0 ]
[ 1571, 40 ]
python
en
['en', 'error', 'th']
False
get_domain
(s, full=False)
Extract the domain name; with full=True, keep the TLD tacked on.
Extract the domain name; with full=True, keep the TLD tacked on.
def get_domain(s, full=False): """ Extract the domain name; with full=True, keep the TLD tacked on. """ try: extract = tld.get_tld(s, fix_protocol=True, as_object=True, ) if full: domain = extract.fld else: domain = extract.domain except TldDomainNotFo...
[ "def", "get_domain", "(", "s", ",", "full", "=", "False", ")", ":", "try", ":", "extract", "=", "tld", ".", "get_tld", "(", "s", ",", "fix_protocol", "=", "True", ",", "as_object", "=", "True", ",", ")", "if", "full", ":", "domain", "=", "extract",...
[ 1580, 0 ]
[ 1613, 17 ]
python
en
['en', 'error', 'th']
False
PostFilter.match
(self, post)
See if a post matches this filter
See if a post matches this filter
def match(self, post): """ See if a post matches this filter """ if (post.is_answer and not self.answer) or (not post.is_answer and not self.question): # Wrong post type return False elif self.all_sites == (post.post_site in self.sites): # Post...
[ "def", "match", "(", "self", ",", "post", ")", ":", "if", "(", "post", ".", "is_answer", "and", "not", "self", ".", "answer", ")", "or", "(", "not", "post", ".", "is_answer", "and", "not", "self", ".", "question", ")", ":", "# Wrong post type", "retu...
[ 385, 4 ]
[ 399, 23 ]
python
en
['en', 'error', 'th']
False
Rule.match
(self, post)
Run this rule against a post. Returns a list of 3 tuples for [result_title, result_username, result_body], each in (match, reason, why) format
Run this rule against a post.
def match(self, post): """ Run this rule against a post. Returns a list of 3 tuples for [result_title, result_username, result_body], each in (match, reason, why) format """ if not self.filter.match(post): # Post not matching the filter return [(F...
[ "def", "match", "(", "self", ",", "post", ")", ":", "if", "not", "self", ".", "filter", ".", "match", "(", "post", ")", ":", "# Post not matching the filter", "return", "[", "(", "False", ",", "\"\"", ",", "\"\"", ")", "]", "*", "3", "body_to_check", ...
[ 432, 4 ]
[ 525, 57 ]
python
en
['en', 'error', 'th']
False
TestAPIGunicorn.test_07_get
(self)
Cache non regression
Cache non regression
def test_07_get(self): """ Cache non regression """ r = requests.get("%s/discovery" % ec.api_uri) l = len(json.loads(r.content.decode())) r.close() self.assertEqual(l, len(posts.ALL)) now = time.time() nb = 100 for i in range(nb): ...
[ "def", "test_07_get", "(", "self", ")", ":", "r", "=", "requests", ".", "get", "(", "\"%s/discovery\"", "%", "ec", ".", "api_uri", ")", "l", "=", "len", "(", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", ")", ")", ")", "r", ...
[ 329, 4 ]
[ 346, 43 ]
python
en
['en', 'error', 'th']
False
TestLazyStreamField.test_lazy_load
(self)
Getting a single item should lazily load the StreamField, only accessing the database once the StreamField is accessed
Getting a single item should lazily load the StreamField, only accessing the database once the StreamField is accessed
def test_lazy_load(self): """ Getting a single item should lazily load the StreamField, only accessing the database once the StreamField is accessed """ with self.assertNumQueries(1): # Get the instance. The StreamField should *not* load the image yet inst...
[ "def", "test_lazy_load", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "# Get the instance. The StreamField should *not* load the image yet", "instance", "=", "StreamModel", ".", "objects", ".", "get", "(", "pk", "=", "self", ...
[ 35, 4 ]
[ 55, 50 ]
python
en
['en', 'error', 'th']
False
TestLazyStreamField.test_lazy_load_no_images
(self)
Getting a single item whose StreamField never accesses the database should behave as expected.
Getting a single item whose StreamField never accesses the database should behave as expected.
def test_lazy_load_no_images(self): """ Getting a single item whose StreamField never accesses the database should behave as expected. """ with self.assertNumQueries(1): # Get the instance, nothing else instance = StreamModel.objects.get(pk=self.no_image.p...
[ "def", "test_lazy_load_no_images", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "# Get the instance, nothing else", "instance", "=", "StreamModel", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "no_image", ".",...
[ 80, 4 ]
[ 93, 50 ]
python
en
['en', 'error', 'th']
False
TestLazyStreamField.test_lazy_load_queryset
(self)
Ensure that lazy loading StreamField works when gotten as part of a queryset list
Ensure that lazy loading StreamField works when gotten as part of a queryset list
def test_lazy_load_queryset(self): """ Ensure that lazy loading StreamField works when gotten as part of a queryset list """ with self.assertNumQueries(1): instances = StreamModel.objects.filter( pk__in=[self.with_image.pk, self.no_image.pk]) ...
[ "def", "test_lazy_load_queryset", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "instances", "=", "StreamModel", ".", "objects", ".", "filter", "(", "pk__in", "=", "[", "self", ".", "with_image", ".", "pk", ",", "sel...
[ 95, 4 ]
[ 109, 54 ]
python
en
['en', 'error', 'th']
False
TestLazyStreamField.test_lazy_load_queryset_bulk
(self)
Ensure that lazy loading StreamField works when gotten as part of a queryset list
Ensure that lazy loading StreamField works when gotten as part of a queryset list
def test_lazy_load_queryset_bulk(self): """ Ensure that lazy loading StreamField works when gotten as part of a queryset list """ file_obj = get_test_image_file() image_1 = Image.objects.create(title='Test image 1', file=file_obj) image_3 = Image.objects.create(ti...
[ "def", "test_lazy_load_queryset_bulk", "(", "self", ")", ":", "file_obj", "=", "get_test_image_file", "(", ")", "image_1", "=", "Image", ".", "objects", ".", "create", "(", "title", "=", "'Test image 1'", ",", "file", "=", "file_obj", ")", "image_3", "=", "I...
[ 111, 4 ]
[ 139, 65 ]
python
en
['en', 'error', 'th']
False
TestLazyStreamField.test_lazy_load_get_prep_value
(self)
Saving a lazy StreamField that hasn't had its data accessed should not cause extra database queries by loading and then re-saving block values. Instead the initial JSON stream data should be written back for any blocks that have not been accessed.
Saving a lazy StreamField that hasn't had its data accessed should not cause extra database queries by loading and then re-saving block values. Instead the initial JSON stream data should be written back for any blocks that have not been accessed.
def test_lazy_load_get_prep_value(self): """ Saving a lazy StreamField that hasn't had its data accessed should not cause extra database queries by loading and then re-saving block values. Instead the initial JSON stream data should be written back for any blocks that have not be...
[ "def", "test_lazy_load_get_prep_value", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "instance", "=", "StreamModel", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "with_image", ".", "pk", ")", "# Expect a s...
[ 141, 4 ]
[ 154, 27 ]
python
en
['en', 'error', 'th']
False
TestStreamValueAccess.test_can_read_non_json_content
(self)
StreamField columns should handle non-JSON database content gracefully
StreamField columns should handle non-JSON database content gracefully
def test_can_read_non_json_content(self): """StreamField columns should handle non-JSON database content gracefully""" self.assertIsInstance(self.nonjson_body.body, StreamValue) # the main list-like content of the StreamValue should be blank self.assertFalse(self.nonjson_body.body) ...
[ "def", "test_can_read_non_json_content", "(", "self", ")", ":", "self", ".", "assertIsInstance", "(", "self", ".", "nonjson_body", ".", "body", ",", "StreamValue", ")", "# the main list-like content of the StreamValue should be blank", "self", ".", "assertFalse", "(", "...
[ 188, 4 ]
[ 194, 81 ]
python
en
['en', 'en', 'en']
True
SubprocessedExecutor.get_widget
(self)
Add progress widget to console screen sidebar :rtype: ExecutorWidget
Add progress widget to console screen sidebar
def get_widget(self): """ Add progress widget to console screen sidebar :rtype: ExecutorWidget """ if not self.widget: label = "%s" % self self.widget = ExecutorWidget(self, label) return self.widget
[ "def", "get_widget", "(", "self", ")", ":", "if", "not", "self", ".", "widget", ":", "label", "=", "\"%s\"", "%", "self", "self", ".", "widget", "=", "ExecutorWidget", "(", "self", ",", "label", ")", "return", "self", ".", "widget" ]
[ 166, 4 ]
[ 175, 26 ]
python
en
['en', 'error', 'th']
False
DatabaseSchemaEditor.skip_default
(self, field)
MySQL doesn't accept default values for some data types and implicitly treats these columns as nullable.
MySQL doesn't accept default values for some data types and implicitly treats these columns as nullable.
def skip_default(self, field): """ MySQL doesn't accept default values for some data types and implicitly treats these columns as nullable. """ db_type = field.db_type(self.connection) return ( db_type is not None and db_type.lower() in { ...
[ "def", "skip_default", "(", "self", ",", "field", ")", ":", "db_type", "=", "field", ".", "db_type", "(", "self", ".", "connection", ")", "return", "(", "db_type", "is", "not", "None", "and", "db_type", ".", "lower", "(", ")", "in", "{", "'tinyblob'", ...
[ 31, 4 ]
[ 44, 9 ]
python
en
['en', 'error', 'th']
False
DatabaseSchemaEditor._delete_composed_index
(self, model, fields, *args)
MySQL can remove an implicit FK index on a field when that field is covered by another index like a unique_together. "covered" here means that the more complex index starts like the simpler one. http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757 We check here before r...
MySQL can remove an implicit FK index on a field when that field is covered by another index like a unique_together. "covered" here means that the more complex index starts like the simpler one. http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757 We check here before r...
def _delete_composed_index(self, model, fields, *args): """ MySQL can remove an implicit FK index on a field when that field is covered by another index like a unique_together. "covered" here means that the more complex index starts like the simpler one. http://bugs.mysql.com/bug...
[ "def", "_delete_composed_index", "(", "self", ",", "model", ",", "fields", ",", "*", "args", ")", ":", "first_field", "=", "model", ".", "_meta", ".", "get_field", "(", "fields", "[", "0", "]", ")", "if", "first_field", ".", "get_internal_type", "(", ")"...
[ 73, 4 ]
[ 87, 93 ]
python
en
['en', 'error', 'th']
False
DatabaseSchemaEditor._set_field_new_type_null_status
(self, field, new_type)
Keep the null property of the old field. If it has changed, it will be handled separately.
Keep the null property of the old field. If it has changed, it will be handled separately.
def _set_field_new_type_null_status(self, field, new_type): """ Keep the null property of the old field. If it has changed, it will be handled separately. """ if field.null: new_type += " NULL" else: new_type += " NOT NULL" return new_type
[ "def", "_set_field_new_type_null_status", "(", "self", ",", "field", ",", "new_type", ")", ":", "if", "field", ".", "null", ":", "new_type", "+=", "\" NULL\"", "else", ":", "new_type", "+=", "\" NOT NULL\"", "return", "new_type" ]
[ 89, 4 ]
[ 98, 23 ]
python
en
['en', 'error', 'th']
False
KFAC.__init__
(self, net, eps, sua=False, pi=False, update_freq=1, alpha=1.0, constraint_norm=False)
K-FAC Preconditionner for Linear and Conv2d layers. Computes the K-FAC of the second moment of the gradients. It works for Linear and Conv2d layers and silently skip other layers. Args: net (torch.nn.Module): Network to precondition. eps (float): Tikhonov regularization ...
K-FAC Preconditionner for Linear and Conv2d layers. Computes the K-FAC of the second moment of the gradients. It works for Linear and Conv2d layers and silently skip other layers. Args: net (torch.nn.Module): Network to precondition. eps (float): Tikhonov regularization ...
def __init__(self, net, eps, sua=False, pi=False, update_freq=1, alpha=1.0, constraint_norm=False): """ K-FAC Preconditionner for Linear and Conv2d layers. Computes the K-FAC of the second moment of the gradients. It works for Linear and Conv2d layers and silently skip other lay...
[ "def", "__init__", "(", "self", ",", "net", ",", "eps", ",", "sua", "=", "False", ",", "pi", "=", "False", ",", "update_freq", "=", "1", ",", "alpha", "=", "1.0", ",", "constraint_norm", "=", "False", ")", ":", "self", ".", "eps", "=", "eps", "se...
[ 7, 4 ]
[ 54, 51 ]
python
en
['en', 'en', 'en']
True
KFAC.step
(self, update_stats=True, update_params=True, lam=0.)
Performs one step of preconditioning.
Performs one step of preconditioning.
def step(self, update_stats=True, update_params=True, lam=0.): """Performs one step of preconditioning.""" self.lam = lam fisher_norm = 0. for group in self.param_groups: if len(group['params']) == 2: weight, bias = group['params'] els...
[ "def", "step", "(", "self", ",", "update_stats", "=", "True", ",", "update_params", "=", "True", ",", "lam", "=", "0.", ")", ":", "self", ".", "lam", "=", "lam", "fisher_norm", "=", "0.", "for", "group", "in", "self", ".", "param_groups", ":", "if", ...
[ 56, 4 ]
[ 109, 40 ]
python
en
['en', 'en', 'en']
True
KFAC._save_input
(self, mod, i)
Saves input of layer to compute covariance.
Saves input of layer to compute covariance.
def _save_input(self, mod, i): """Saves input of layer to compute covariance.""" # i = (x, edge_index) if mod.training: self.state[mod]['x'] = i[0] self.mask = i[-1]
[ "def", "_save_input", "(", "self", ",", "mod", ",", "i", ")", ":", "# i = (x, edge_index)", "if", "mod", ".", "training", ":", "self", ".", "state", "[", "mod", "]", "[", "'x'", "]", "=", "i", "[", "0", "]", "self", ".", "mask", "=", "i", "[", ...
[ 111, 4 ]
[ 117, 29 ]
python
en
['en', 'en', 'en']
True
KFAC._save_grad_output
(self, mod, grad_input, grad_output)
Saves grad on output of layer to compute covariance.
Saves grad on output of layer to compute covariance.
def _save_grad_output(self, mod, grad_input, grad_output): """Saves grad on output of layer to compute covariance.""" if mod.training: self.state[mod]['gy'] = grad_output[0] * grad_output[0].size(1) self._cached_edge_index = mod._cached_edge_index
[ "def", "_save_grad_output", "(", "self", ",", "mod", ",", "grad_input", ",", "grad_output", ")", ":", "if", "mod", ".", "training", ":", "self", ".", "state", "[", "mod", "]", "[", "'gy'", "]", "=", "grad_output", "[", "0", "]", "*", "grad_output", "...
[ 119, 4 ]
[ 123, 60 ]
python
en
['en', 'en', 'en']
True
KFAC._precond
(self, weight, bias, group, state)
Applies preconditioning.
Applies preconditioning.
def _precond(self, weight, bias, group, state): """Applies preconditioning.""" ixxt = state['ixxt'] # [d_in x d_in] iggt = state['iggt'] # [d_out x d_out] g = weight.grad.data # [d_in x d_out] s = g.shape g = g.contiguous().view(-1, g.shape[-1]) if b...
[ "def", "_precond", "(", "self", ",", "weight", ",", "bias", ",", "group", ",", "state", ")", ":", "ixxt", "=", "state", "[", "'ixxt'", "]", "# [d_in x d_in]", "iggt", "=", "state", "[", "'iggt'", "]", "# [d_out x d_out]", "g", "=", "weight", ".", "grad...
[ 125, 4 ]
[ 145, 20 ]
python
en
['es', 'en', 'en']
False
KFAC._compute_covs
(self, group, state)
Computes the covariances.
Computes the covariances.
def _compute_covs(self, group, state): """Computes the covariances.""" sub_mod = group['sub_mod'] x = self.state[group['mod']]['x'] # [n x d_in] gy = self.state[group['sub_mod']]['gy'] # [n x d_out] edge_index, edge_weight = self._cached_edge_index # [2, n_edges], [n_edges] ...
[ "def", "_compute_covs", "(", "self", ",", "group", ",", "state", ")", ":", "sub_mod", "=", "group", "[", "'sub_mod'", "]", "x", "=", "self", ".", "state", "[", "group", "[", "'mod'", "]", "]", "[", "'x'", "]", "# [n x d_in]", "gy", "=", "self", "."...
[ 147, 4 ]
[ 184, 53 ]
python
en
['en', 'en', 'en']
True
KFAC._inv_covs
(self, xxt, ggt, num_locations)
Inverses the covariances.
Inverses the covariances.
def _inv_covs(self, xxt, ggt, num_locations): """Inverses the covariances.""" # Computes pi pi = 1.0 if self.pi: tx = torch.trace(xxt) * ggt.shape[0] tg = torch.trace(ggt) * xxt.shape[0] pi = (tx / tg) # Regularizes and inverse eps = se...
[ "def", "_inv_covs", "(", "self", ",", "xxt", ",", "ggt", ",", "num_locations", ")", ":", "# Computes pi", "pi", "=", "1.0", "if", "self", ".", "pi", ":", "tx", "=", "torch", ".", "trace", "(", "xxt", ")", "*", "ggt", ".", "shape", "[", "0", "]", ...
[ 186, 4 ]
[ 201, 25 ]
python
en
['en', 'en', 'en']
True
get_view_description
(view, html=False)
Wrapper around REST framework get_view_description() to continue to support our historical div.
Wrapper around REST framework get_view_description() to continue to support our historical div.
def get_view_description(view, html=False): """Wrapper around REST framework get_view_description() to continue to support our historical div. """ desc = views.get_view_description(view, html=html) if html: desc = '<div class="description">%s</div>' % desc return mark_safe(desc)
[ "def", "get_view_description", "(", "view", ",", "html", "=", "False", ")", ":", "desc", "=", "views", ".", "get_view_description", "(", "view", ",", "html", "=", "html", ")", "if", "html", ":", "desc", "=", "'<div class=\"description\">%s</div>'", "%", "des...
[ 120, 0 ]
[ 128, 26 ]
python
en
['en', 'pt', 'en']
True
APIView.initialize_request
(self, request, *args, **kwargs)
Store the Django REST Framework Request object as an attribute on the normal Django request, store time the request started.
Store the Django REST Framework Request object as an attribute on the normal Django request, store time the request started.
def initialize_request(self, request, *args, **kwargs): """ Store the Django REST Framework Request object as an attribute on the normal Django request, store time the request started. """ self.time_started = time.time() if getattr(settings, 'SQL_DEBUG', False): ...
[ "def", "initialize_request", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "time_started", "=", "time", ".", "time", "(", ")", "if", "getattr", "(", "settings", ",", "'SQL_DEBUG'", ",", "False", ")", "...
[ 145, 4 ]
[ 181, 26 ]
python
en
['en', 'error', 'th']
False
APIView.finalize_response
(self, request, response, *args, **kwargs)
Log warning for 400 requests. Add header with elapsed time.
Log warning for 400 requests. Add header with elapsed time.
def finalize_response(self, request, response, *args, **kwargs): """ Log warning for 400 requests. Add header with elapsed time. """ # # If the URL was rewritten, and we get a 404, we should entirely # replace the view in the request context with an ApiErrorView() ...
[ "def", "finalize_response", "(", "self", ",", "request", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#", "# If the URL was rewritten, and we get a 404, we should entirely", "# replace the view in the request context with an ApiErrorView()", "# Witho...
[ 183, 4 ]
[ 241, 23 ]
python
en
['en', 'error', 'th']
False
RetrieveUpdateAPIView.update_filter
(self, request, *args, **kwargs)
scrub any fields the user cannot/should not put/patch, based on user context. This runs after read-only serialization filtering
scrub any fields the user cannot/should not put/patch, based on user context. This runs after read-only serialization filtering
def update_filter(self, request, *args, **kwargs): '''scrub any fields the user cannot/should not put/patch, based on user context. This runs after read-only serialization filtering''' pass
[ "def", "update_filter", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
[ 788, 4 ]
[ 790, 12 ]
python
en
['en', 'en', 'en']
True
normalize_prefetch_lookups
(lookups, prefix=None)
Helper function that normalize lookups into Prefetch objects.
Helper function that normalize lookups into Prefetch objects.
def normalize_prefetch_lookups(lookups, prefix=None): """ Helper function that normalize lookups into Prefetch objects. """ ret = [] for lookup in lookups: if not isinstance(lookup, Prefetch): lookup = Prefetch(lookup) if prefix: lookup.add_prefix(prefix) ...
[ "def", "normalize_prefetch_lookups", "(", "lookups", ",", "prefix", "=", "None", ")", ":", "ret", "=", "[", "]", "for", "lookup", "in", "lookups", ":", "if", "not", "isinstance", "(", "lookup", ",", "Prefetch", ")", ":", "lookup", "=", "Prefetch", "(", ...
[ 1352, 0 ]
[ 1363, 14 ]
python
en
['en', 'error', 'th']
False
prefetch_related_objects
(model_instances, *related_lookups)
Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given.
Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given.
def prefetch_related_objects(model_instances, *related_lookups): """ Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given. """ if len(model_instances) == 0: return # nothing to do related_lookups = normalize_prefetch_lookups(rela...
[ "def", "prefetch_related_objects", "(", "model_instances", ",", "*", "related_lookups", ")", ":", "if", "len", "(", "model_instances", ")", "==", "0", ":", "return", "# nothing to do", "related_lookups", "=", "normalize_prefetch_lookups", "(", "related_lookups", ")", ...
[ 1366, 0 ]
[ 1486, 39 ]
python
en
['en', 'error', 'th']
False
get_prefetcher
(instance, through_attr, to_attr)
For the attribute 'through_attr' on the given instance, finds an object that has a get_prefetch_queryset(). Returns a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute ...
For the attribute 'through_attr' on the given instance, finds an object that has a get_prefetch_queryset(). Returns a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute ...
def get_prefetcher(instance, through_attr, to_attr): """ For the attribute 'through_attr' on the given instance, finds an object that has a get_prefetch_queryset(). Returns a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationsh...
[ "def", "get_prefetcher", "(", "instance", ",", "through_attr", ",", "to_attr", ")", ":", "prefetcher", "=", "None", "is_fetched", "=", "False", "# For singly related objects, we have to avoid getting the attribute", "# from the object, as this will trigger the query. So we first tr...
[ 1489, 0 ]
[ 1533, 65 ]
python
en
['en', 'error', 'th']
False
prefetch_one_level
(instances, prefetcher, lookup, level)
Helper function for prefetch_related_objects Runs prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. The prefetched objects are returned, along with any additional prefetches that must be done due to prefetch_related lookups found from d...
Helper function for prefetch_related_objects
def prefetch_one_level(instances, prefetcher, lookup, level): """ Helper function for prefetch_related_objects Runs prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. The prefetched objects are returned, along with any additional prefetch...
[ "def", "prefetch_one_level", "(", "instances", ",", "prefetcher", ",", "lookup", ",", "level", ")", ":", "# prefetcher must have a method get_prefetch_queryset() which takes a list", "# of instances, and returns a tuple:", "# (queryset of instances of self.model that are related to passe...
[ 1536, 0 ]
[ 1635, 50 ]
python
en
['en', 'error', 'th']
False
QuerySet.__deepcopy__
(self, memo)
Deep copy of a QuerySet doesn't populate the cache
Deep copy of a QuerySet doesn't populate the cache
def __deepcopy__(self, memo): """ Deep copy of a QuerySet doesn't populate the cache """ obj = self.__class__() for k, v in self.__dict__.items(): if k == '_result_cache': obj.__dict__[k] = None else: obj.__dict__[k] = copy....
[ "def", "__deepcopy__", "(", "self", ",", "memo", ")", ":", "obj", "=", "self", ".", "__class__", "(", ")", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "k", "==", "'_result_cache'", ":", "obj", ".", "__d...
[ 187, 4 ]
[ 197, 18 ]
python
en
['en', 'error', 'th']
False
QuerySet.__iter__
(self)
The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler:execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some col...
The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler:execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some col...
def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler:execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for ...
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "_fetch_all", "(", ")", "return", "iter", "(", "self", ".", "_result_cache", ")" ]
[ 234, 4 ]
[ 250, 39 ]
python
en
['en', 'error', 'th']
False
QuerySet.__getitem__
(self, k)
Retrieves an item or slice from the set of results.
Retrieves an item or slice from the set of results.
def __getitem__(self, k): """ Retrieves an item or slice from the set of results. """ if not isinstance(k, (slice,) + six.integer_types): raise TypeError assert ((not isinstance(k, slice) and (k >= 0)) or (isinstance(k, slice) and (k.start is None or k...
[ "def", "__getitem__", "(", "self", ",", "k", ")", ":", "if", "not", "isinstance", "(", "k", ",", "(", "slice", ",", ")", "+", "six", ".", "integer_types", ")", ":", "raise", "TypeError", "assert", "(", "(", "not", "isinstance", "(", "k", ",", "slic...
[ 259, 4 ]
[ 288, 26 ]
python
en
['en', 'error', 'th']
False
QuerySet.iterator
(self)
An iterator over the results from applying this QuerySet to the database.
An iterator over the results from applying this QuerySet to the database.
def iterator(self): """ An iterator over the results from applying this QuerySet to the database. """ return iter(self._iterable_class(self, chunked_fetch=True))
[ "def", "iterator", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_iterable_class", "(", "self", ",", "chunked_fetch", "=", "True", ")", ")" ]
[ 316, 4 ]
[ 321, 67 ]
python
en
['en', 'error', 'th']
False
QuerySet.aggregate
(self, *args, **kwargs)
Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias.
Returns a dictionary containing the calculations (aggregation) over the current queryset
def aggregate(self, *args, **kwargs): """ Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ if self.query.distinct_fields...
[ "def", "aggregate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "query", ".", "distinct_fields", ":", "raise", "NotImplementedError", "(", "\"aggregate() + distinct(fields) not implemented.\"", ")", "for", "arg", "in", ...
[ 323, 4 ]
[ 349, 60 ]
python
en
['en', 'error', 'th']
False
QuerySet.count
(self)
Performs a SELECT COUNT() and returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid multiple SELECT COUNT(*) calls.
Performs a SELECT COUNT() and returns the number of records as an integer.
def count(self): """ Performs a SELECT COUNT() and returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is ...
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "_result_cache", "is", "not", "None", ":", "return", "len", "(", "self", ".", "_result_cache", ")", "return", "self", ".", "query", ".", "get_count", "(", "using", "=", "self", ".", "db", ")" ...
[ 351, 4 ]
[ 362, 50 ]
python
en
['en', 'error', 'th']
False
QuerySet.get
(self, *args, **kwargs)
Performs the query and returns a single object matching the given keyword arguments.
Performs the query and returns a single object matching the given keyword arguments.
def get(self, *args, **kwargs): """ Performs the query and returns a single object matching the given keyword arguments. """ clone = self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() nu...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "clone", "=", "self", ".", "filter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "self", ".", "query", ".", "can_filter", "(", ")", "and", "not", "self", ...
[ 364, 4 ]
[ 383, 9 ]
python
en
['en', 'error', 'th']
False
QuerySet.create
(self, **kwargs)
Creates a new object with the given kwargs, saving it to the database and returning the created object.
Creates a new object with the given kwargs, saving it to the database and returning the created object.
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "model", "(", "*", "*", "kwargs", ")", "self", ".", "_for_write", "=", "True", "obj", ".", "save", "(", "force_insert", "=", "True", ",", "using", "=", "sel...
[ 385, 4 ]
[ 393, 18 ]
python
en
['en', 'error', 'th']
False
QuerySet.bulk_create
(self, objs, batch_size=None)
Inserts each of the instances into the database. This does *not* call save() on each of the instances, does not send any pre/post save signals, and does not set the primary key attribute if it is an autoincrement field (except if features.can_return_ids_from_bulk_insert=True). M...
Inserts each of the instances into the database. This does *not* call save() on each of the instances, does not send any pre/post save signals, and does not set the primary key attribute if it is an autoincrement field (except if features.can_return_ids_from_bulk_insert=True). M...
def bulk_create(self, objs, batch_size=None): """ Inserts each of the instances into the database. This does *not* call save() on each of the instances, does not send any pre/post save signals, and does not set the primary key attribute if it is an autoincrement field (except if ...
[ "def", "bulk_create", "(", "self", ",", "objs", ",", "batch_size", "=", "None", ")", ":", "# When you bulk insert you don't get the primary keys back (if it's an", "# autoincrement, except if can_return_ids_from_bulk_insert=True), so", "# you can't insert into the child tables which refe...
[ 400, 4 ]
[ 449, 19 ]
python
en
['en', 'error', 'th']
False
QuerySet.get_or_create
(self, defaults=None, **kwargs)
Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created.
Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created.
def get_or_create(self, defaults=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ lookup, params = self._extract_model_p...
[ "def", "get_or_create", "(", "self", ",", "defaults", "=", "None", ",", "*", "*", "kwargs", ")", ":", "lookup", ",", "params", "=", "self", ".", "_extract_model_params", "(", "defaults", ",", "*", "*", "kwargs", ")", "# The get() needs to be targeted at the wr...
[ 451, 4 ]
[ 464, 66 ]
python
en
['en', 'error', 'th']
False
QuerySet.update_or_create
(self, defaults=None, **kwargs)
Looks up an object with the given kwargs, updating one with defaults if it exists, otherwise creates a new one. Returns a tuple (object, created), where created is a boolean specifying whether an object was created.
Looks up an object with the given kwargs, updating one with defaults if it exists, otherwise creates a new one. Returns a tuple (object, created), where created is a boolean specifying whether an object was created.
def update_or_create(self, defaults=None, **kwargs): """ Looks up an object with the given kwargs, updating one with defaults if it exists, otherwise creates a new one. Returns a tuple (object, created), where created is a boolean specifying whether an object was created. ...
[ "def", "update_or_create", "(", "self", ",", "defaults", "=", "None", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "defaults", "or", "{", "}", "lookup", ",", "params", "=", "self", ".", "_extract_model_params", "(", "defaults", ",", "*", "*", "k...
[ 466, 4 ]
[ 486, 25 ]
python
en
['en', 'error', 'th']
False
QuerySet._create_object_from_params
(self, lookup, params)
Tries to create an object using passed params. Used by get_or_create and update_or_create
Tries to create an object using passed params. Used by get_or_create and update_or_create
def _create_object_from_params(self, lookup, params): """ Tries to create an object using passed params. Used by get_or_create and update_or_create """ try: with transaction.atomic(using=self.db): params = {k: v() if callable(v) else v for k, v in para...
[ "def", "_create_object_from_params", "(", "self", ",", "lookup", ",", "params", ")", ":", "try", ":", "with", "transaction", ".", "atomic", "(", "using", "=", "self", ".", "db", ")", ":", "params", "=", "{", "k", ":", "v", "(", ")", "if", "callable",...
[ 488, 4 ]
[ 504, 34 ]
python
en
['en', 'error', 'th']
False
QuerySet._extract_model_params
(self, defaults, **kwargs)
Prepares `lookup` (kwargs that are valid model attributes), `params` (for creating a model instance) based on given kwargs; for use by get_or_create and update_or_create.
Prepares `lookup` (kwargs that are valid model attributes), `params` (for creating a model instance) based on given kwargs; for use by get_or_create and update_or_create.
def _extract_model_params(self, defaults, **kwargs): """ Prepares `lookup` (kwargs that are valid model attributes), `params` (for creating a model instance) based on given kwargs; for use by get_or_create and update_or_create. """ defaults = defaults or {} lookup...
[ "def", "_extract_model_params", "(", "self", ",", "defaults", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "defaults", "or", "{", "}", "lookup", "=", "kwargs", ".", "copy", "(", ")", "for", "f", "in", "self", ".", "model", ".", "_meta", ".", ...
[ 506, 4 ]
[ 532, 29 ]
python
en
['en', 'error', 'th']
False
QuerySet._earliest_or_latest
(self, field_name=None, direction="-")
Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name.
Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name.
def _earliest_or_latest(self, field_name=None, direction="-"): """ Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name. """ order_by = field_name or getattr(self.model._meta, 'get_latest_by') assert bool(order_by), "earl...
[ "def", "_earliest_or_latest", "(", "self", ",", "field_name", "=", "None", ",", "direction", "=", "\"-\"", ")", ":", "order_by", "=", "field_name", "or", "getattr", "(", "self", ".", "model", ".", "_meta", ",", "'get_latest_by'", ")", "assert", "bool", "("...
[ 534, 4 ]
[ 548, 24 ]
python
en
['en', 'error', 'th']
False
QuerySet.first
(self)
Returns the first object of a query, returns None if no match is found.
Returns the first object of a query, returns None if no match is found.
def first(self): """ Returns the first object of a query, returns None if no match is found. """ objects = list((self if self.ordered else self.order_by('pk'))[:1]) if objects: return objects[0] return None
[ "def", "first", "(", "self", ")", ":", "objects", "=", "list", "(", "(", "self", "if", "self", ".", "ordered", "else", "self", ".", "order_by", "(", "'pk'", ")", ")", "[", ":", "1", "]", ")", "if", "objects", ":", "return", "objects", "[", "0", ...
[ 556, 4 ]
[ 563, 19 ]
python
en
['en', 'error', 'th']
False
QuerySet.last
(self)
Returns the last object of a query, returns None if no match is found.
Returns the last object of a query, returns None if no match is found.
def last(self): """ Returns the last object of a query, returns None if no match is found. """ objects = list((self.reverse() if self.ordered else self.order_by('-pk'))[:1]) if objects: return objects[0] return None
[ "def", "last", "(", "self", ")", ":", "objects", "=", "list", "(", "(", "self", ".", "reverse", "(", ")", "if", "self", ".", "ordered", "else", "self", ".", "order_by", "(", "'-pk'", ")", ")", "[", ":", "1", "]", ")", "if", "objects", ":", "ret...
[ 565, 4 ]
[ 572, 19 ]
python
en
['en', 'error', 'th']
False
QuerySet.in_bulk
(self, id_list=None)
Returns a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, the entire QuerySet is evaluated.
Returns a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, the entire QuerySet is evaluated.
def in_bulk(self, id_list=None): """ Returns a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, the entire QuerySet is evaluated. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with in_bulk" ...
[ "def", "in_bulk", "(", "self", ",", "id_list", "=", "None", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot use 'limit' or 'offset' with in_bulk\"", "if", "id_list", "is", "not", "None", ":", "if", "not", "id_list", ":",...
[ 574, 4 ]
[ 587, 53 ]
python
en
['en', 'error', 'th']
False
QuerySet.delete
(self)
Deletes the records in the current QuerySet.
Deletes the records in the current QuerySet.
def delete(self): """ Deletes the records in the current QuerySet. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with delete." if self._fields is not None: raise TypeError("Cannot call delete() after .values() or .values_list()") ...
[ "def", "delete", "(", "self", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot use 'limit' or 'offset' with delete.\"", "if", "self", ".", "_fields", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Cannot call delete(...
[ 589, 4 ]
[ 617, 35 ]
python
en
['en', 'error', 'th']
False
QuerySet._raw_delete
(self, using)
Deletes objects found from the given queryset in single direct SQL query. No signals are sent, and there is no protection for cascades.
Deletes objects found from the given queryset in single direct SQL query. No signals are sent, and there is no protection for cascades.
def _raw_delete(self, using): """ Deletes objects found from the given queryset in single direct SQL query. No signals are sent, and there is no protection for cascades. """ return sql.DeleteQuery(self.model).delete_qs(self, using)
[ "def", "_raw_delete", "(", "self", ",", "using", ")", ":", "return", "sql", ".", "DeleteQuery", "(", "self", ".", "model", ")", ".", "delete_qs", "(", "self", ",", "using", ")" ]
[ 622, 4 ]
[ 627, 65 ]
python
en
['en', 'error', 'th']
False
QuerySet.update
(self, **kwargs)
Updates all elements in the current QuerySet, setting all the given fields to the appropriate values.
Updates all elements in the current QuerySet, setting all the given fields to the appropriate values.
def update(self, **kwargs): """ Updates all elements in the current QuerySet, setting all the given fields to the appropriate values. """ assert self.query.can_filter(), \ "Cannot update a query once a slice has been taken." self._for_write = True quer...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot update a query once a slice has been taken.\"", "self", ".", "_for_write", "=", "True", "query", "=", "self", ".", "q...
[ 630, 4 ]
[ 645, 19 ]
python
en
['en', 'error', 'th']
False
QuerySet._update
(self, values)
A version of update that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level).
A version of update that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level).
def _update(self, values): """ A version of update that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ a...
[ "def", "_update", "(", "self", ",", "values", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot update a query once a slice has been taken.\"", "query", "=", "self", ".", "query", ".", "clone", "(", "sql", ".", "UpdateQuery"...
[ 648, 4 ]
[ 660, 62 ]
python
en
['en', 'error', 'th']
False
QuerySet.dates
(self, field_name, kind, order='ASC')
Returns a list of date objects representing all available dates for the given field_name, scoped to 'kind'.
Returns a list of date objects representing all available dates for the given field_name, scoped to 'kind'.
def dates(self, field_name, kind, order='ASC'): """ Returns a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ assert kind in ("year", "month", "day"), \ "'kind' must be one of 'year', 'month' or 'day'." ass...
[ "def", "dates", "(", "self", ",", "field_name", ",", "kind", ",", "order", "=", "'ASC'", ")", ":", "assert", "kind", "in", "(", "\"year\"", ",", "\"month\"", ",", "\"day\"", ")", ",", "\"'kind' must be one of 'year', 'month' or 'day'.\"", "assert", "order", "i...
[ 719, 4 ]
[ 733, 111 ]
python
en
['en', 'error', 'th']
False
QuerySet.datetimes
(self, field_name, kind, order='ASC', tzinfo=None)
Returns a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'.
Returns a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'.
def datetimes(self, field_name, kind, order='ASC', tzinfo=None): """ Returns a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ assert kind in ("year", "month", "day", "hour", "minute", "second"), \ "'kind' ...
[ "def", "datetimes", "(", "self", ",", "field_name", ",", "kind", ",", "order", "=", "'ASC'", ",", "tzinfo", "=", "None", ")", ":", "assert", "kind", "in", "(", "\"year\"", ",", "\"month\"", ",", "\"day\"", ",", "\"hour\"", ",", "\"minute\"", ",", "\"se...
[ 735, 4 ]
[ 754, 115 ]
python
en
['en', 'error', 'th']
False
QuerySet.none
(self)
Returns an empty QuerySet.
Returns an empty QuerySet.
def none(self): """ Returns an empty QuerySet. """ clone = self._clone() clone.query.set_empty() return clone
[ "def", "none", "(", "self", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", "query", ".", "set_empty", "(", ")", "return", "clone" ]
[ 756, 4 ]
[ 762, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.all
(self)
Returns a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases.
Returns a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases.
def all(self): """ Returns a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._clone()
[ "def", "all", "(", "self", ")", ":", "return", "self", ".", "_clone", "(", ")" ]
[ 768, 4 ]
[ 773, 28 ]
python
en
['en', 'error', 'th']
False
QuerySet.filter
(self, *args, **kwargs)
Returns a new QuerySet instance with the args ANDed to the existing set.
Returns a new QuerySet instance with the args ANDed to the existing set.
def filter(self, *args, **kwargs): """ Returns a new QuerySet instance with the args ANDed to the existing set. """ return self._filter_or_exclude(False, *args, **kwargs)
[ "def", "filter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_filter_or_exclude", "(", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 775, 4 ]
[ 780, 62 ]
python
en
['en', 'error', 'th']
False
QuerySet.exclude
(self, *args, **kwargs)
Returns a new QuerySet instance with NOT (args) ANDed to the existing set.
Returns a new QuerySet instance with NOT (args) ANDed to the existing set.
def exclude(self, *args, **kwargs): """ Returns a new QuerySet instance with NOT (args) ANDed to the existing set. """ return self._filter_or_exclude(True, *args, **kwargs)
[ "def", "exclude", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_filter_or_exclude", "(", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 782, 4 ]
[ 787, 61 ]
python
en
['en', 'error', 'th']
False
QuerySet.complex_filter
(self, filter_obj)
Returns a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object (or anything with an add_to_query() method) or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will...
Returns a new QuerySet instance with filter_obj added to the filters.
def complex_filter(self, filter_obj): """ Returns a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object (or anything with an add_to_query() method) or a dictionary of keyword lookup arguments. This exists to support framework features such a...
[ "def", "complex_filter", "(", "self", ",", "filter_obj", ")", ":", "if", "isinstance", "(", "filter_obj", ",", "Q", ")", "or", "hasattr", "(", "filter_obj", ",", "'add_to_query'", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", "...
[ 801, 4 ]
[ 816, 62 ]
python
en
['en', 'error', 'th']
False
QuerySet.select_for_update
(self, nowait=False, skip_locked=False)
Returns a new QuerySet instance that will select objects with a FOR UPDATE lock.
Returns a new QuerySet instance that will select objects with a FOR UPDATE lock.
def select_for_update(self, nowait=False, skip_locked=False): """ Returns a new QuerySet instance that will select objects with a FOR UPDATE lock. """ if nowait and skip_locked: raise ValueError('The nowait option cannot be used with skip_locked.') obj = self....
[ "def", "select_for_update", "(", "self", ",", "nowait", "=", "False", ",", "skip_locked", "=", "False", ")", ":", "if", "nowait", "and", "skip_locked", ":", "raise", "ValueError", "(", "'The nowait option cannot be used with skip_locked.'", ")", "obj", "=", "self"...
[ 845, 4 ]
[ 857, 18 ]
python
en
['en', 'error', 'th']
False
QuerySet.select_related
(self, *fields)
Returns a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, the list is cleared.
Returns a new QuerySet instance that will select related objects.
def select_related(self, *fields): """ Returns a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, the list is cleared....
[ "def", "select_related", "(", "self", ",", "*", "fields", ")", ":", "if", "self", ".", "_fields", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Cannot call select_related() after .values() or .values_list()\"", ")", "obj", "=", "self", ".", "_clone", "...
[ 859, 4 ]
[ 879, 18 ]
python
en
['en', 'error', 'th']
False
QuerySet.prefetch_related
(self, *lookups)
Returns a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, the list of lookups to prefetch is appended to. If prefetch_related(None) is called, t...
Returns a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated.
def prefetch_related(self, *lookups): """ Returns a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, the list of lookups to prefetch is ap...
[ "def", "prefetch_related", "(", "self", ",", "*", "lookups", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "if", "lookups", "==", "(", "None", ",", ")", ":", "clone", ".", "_prefetch_related_lookups", "=", "(", ")", "else", ":", "clone", "...
[ 881, 4 ]
[ 896, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.annotate
(self, *args, **kwargs)
Return a query set in which the returned objects have been annotated with extra data or aggregations.
Return a query set in which the returned objects have been annotated with extra data or aggregations.
def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with extra data or aggregations. """ annotations = OrderedDict() # To preserve ordering of args for arg in args: # The default_alias property may rai...
[ "def", "annotate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "annotations", "=", "OrderedDict", "(", ")", "# To preserve ordering of args", "for", "arg", "in", "args", ":", "# The default_alias property may raise a TypeError, so we use", "# a...
[ 898, 4 ]
[ 938, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.order_by
(self, *field_names)
Returns a new QuerySet instance with the ordering changed.
Returns a new QuerySet instance with the ordering changed.
def order_by(self, *field_names): """ Returns a new QuerySet instance with the ordering changed. """ assert self.query.can_filter(), \ "Cannot reorder a query once a slice has been taken." obj = self._clone() obj.query.clear_ordering(force_empty=False) ...
[ "def", "order_by", "(", "self", ",", "*", "field_names", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot reorder a query once a slice has been taken.\"", "obj", "=", "self", ".", "_clone", "(", ")", "obj", ".", "query", ...
[ 940, 4 ]
[ 949, 18 ]
python
en
['en', 'error', 'th']
False
QuerySet.distinct
(self, *field_names)
Returns a new QuerySet instance that will select only distinct results.
Returns a new QuerySet instance that will select only distinct results.
def distinct(self, *field_names): """ Returns a new QuerySet instance that will select only distinct results. """ assert self.query.can_filter(), \ "Cannot create distinct fields once a slice has been taken." obj = self._clone() obj.query.add_distinct_fields(*...
[ "def", "distinct", "(", "self", ",", "*", "field_names", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot create distinct fields once a slice has been taken.\"", "obj", "=", "self", ".", "_clone", "(", ")", "obj", ".", "que...
[ 951, 4 ]
[ 959, 18 ]
python
en
['en', 'error', 'th']
False
QuerySet.extra
(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
Adds extra SQL fragments to the query.
Adds extra SQL fragments to the query.
def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None): """ Adds extra SQL fragments to the query. """ assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken" clone = self._clon...
[ "def", "extra", "(", "self", ",", "select", "=", "None", ",", "where", "=", "None", ",", "params", "=", "None", ",", "tables", "=", "None", ",", "order_by", "=", "None", ",", "select_params", "=", "None", ")", ":", "assert", "self", ".", "query", "...
[ 961, 4 ]
[ 970, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.reverse
(self)
Reverses the ordering of the QuerySet.
Reverses the ordering of the QuerySet.
def reverse(self): """ Reverses the ordering of the QuerySet. """ clone = self._clone() clone.query.standard_ordering = not clone.query.standard_ordering return clone
[ "def", "reverse", "(", "self", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", "query", ".", "standard_ordering", "=", "not", "clone", ".", "query", ".", "standard_ordering", "return", "clone" ]
[ 972, 4 ]
[ 978, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.defer
(self, *fields)
Defers the loading of data for certain fields until they are accessed. The set of fields to defer is added to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case all deferrals are removed (None acts as a re...
Defers the loading of data for certain fields until they are accessed. The set of fields to defer is added to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case all deferrals are removed (None acts as a re...
def defer(self, *fields): """ Defers the loading of data for certain fields until they are accessed. The set of fields to defer is added to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case all deferrals a...
[ "def", "defer", "(", "self", ",", "*", "fields", ")", ":", "if", "self", ".", "_fields", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Cannot call defer() after .values() or .values_list()\"", ")", "clone", "=", "self", ".", "_clone", "(", ")", "if...
[ 980, 4 ]
[ 995, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.only
(self, *fields)
Essentially, the opposite of defer. Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated.
Essentially, the opposite of defer. Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated.
def only(self, *fields): """ Essentially, the opposite of defer. Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ if self._fields is not None: raise TypeError("Can...
[ "def", "only", "(", "self", ",", "*", "fields", ")", ":", "if", "self", ".", "_fields", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Cannot call only() after .values() or .values_list()\"", ")", "if", "fields", "==", "(", "None", ",", ")", ":", ...
[ 997, 4 ]
[ 1011, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.using
(self, alias)
Selects which database this QuerySet should execute its query against.
Selects which database this QuerySet should execute its query against.
def using(self, alias): """ Selects which database this QuerySet should execute its query against. """ clone = self._clone() clone._db = alias return clone
[ "def", "using", "(", "self", ",", "alias", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", "_db", "=", "alias", "return", "clone" ]
[ 1013, 4 ]
[ 1019, 20 ]
python
en
['en', 'error', 'th']
False
QuerySet.ordered
(self)
Returns True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model.
Returns True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model.
def ordered(self): """ Returns True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model. """ if self.query.extra_order_by or self.query.order_by: return True elif self.query.default_ordering and self.query.get_meta()....
[ "def", "ordered", "(", "self", ")", ":", "if", "self", ".", "query", ".", "extra_order_by", "or", "self", ".", "query", ".", "order_by", ":", "return", "True", "elif", "self", ".", "query", ".", "default_ordering", "and", "self", ".", "query", ".", "ge...
[ 1026, 4 ]
[ 1036, 24 ]
python
en
['en', 'error', 'th']
False
QuerySet.db
(self)
Return the database that will be used if this query is executed now
Return the database that will be used if this query is executed now
def db(self): "Return the database that will be used if this query is executed now" if self._for_write: return self._db or router.db_for_write(self.model, **self._hints) return self._db or router.db_for_read(self.model, **self._hints)
[ "def", "db", "(", "self", ")", ":", "if", "self", ".", "_for_write", ":", "return", "self", ".", "_db", "or", "router", ".", "db_for_write", "(", "self", ".", "model", ",", "*", "*", "self", ".", "_hints", ")", "return", "self", ".", "_db", "or", ...
[ 1039, 4 ]
[ 1043, 72 ]
python
en
['en', 'en', 'en']
True
QuerySet._insert
(self, objs, fields, return_id=False, raw=False, using=None)
Inserts a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented.
Inserts a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented.
def _insert(self, objs, fields, return_id=False, raw=False, using=None): """ Inserts a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. """ self._for_write = True if using is None: usin...
[ "def", "_insert", "(", "self", ",", "objs", ",", "fields", ",", "return_id", "=", "False", ",", "raw", "=", "False", ",", "using", "=", "None", ")", ":", "self", ".", "_for_write", "=", "True", "if", "using", "is", "None", ":", "using", "=", "self"...
[ 1049, 4 ]
[ 1059, 69 ]
python
en
['en', 'error', 'th']
False
QuerySet._batched_insert
(self, objs, fields, batch_size)
A little helper method for bulk_insert to insert the bulk one batch at a time. Inserts recursively a batch from the front of the bulk and then _batched_insert() the remaining objects again.
A little helper method for bulk_insert to insert the bulk one batch at a time. Inserts recursively a batch from the front of the bulk and then _batched_insert() the remaining objects again.
def _batched_insert(self, objs, fields, batch_size): """ A little helper method for bulk_insert to insert the bulk one batch at a time. Inserts recursively a batch from the front of the bulk and then _batched_insert() the remaining objects again. """ if not objs: ...
[ "def", "_batched_insert", "(", "self", ",", "objs", ",", "fields", ",", "batch_size", ")", ":", "if", "not", "objs", ":", "return", "ops", "=", "connections", "[", "self", ".", "db", "]", ".", "ops", "batch_size", "=", "(", "batch_size", "or", "max", ...
[ 1063, 4 ]
[ 1083, 27 ]
python
en
['en', 'error', 'th']
False
QuerySet._next_is_sticky
(self)
Indicates that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. T...
Indicates that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers.
def _next_is_sticky(self): """ Indicates that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the r...
[ "def", "_next_is_sticky", "(", "self", ")", ":", "self", ".", "_sticky_filter", "=", "True", "return", "self" ]
[ 1105, 4 ]
[ 1117, 19 ]
python
en
['en', 'error', 'th']
False
QuerySet._merge_sanity_check
(self, other)
Checks that we are merging two comparable QuerySet classes.
Checks that we are merging two comparable QuerySet classes.
def _merge_sanity_check(self, other): """ Checks that we are merging two comparable QuerySet classes. """ if self._fields is not None and ( set(self.query.values_select) != set(other.query.values_select) or set(self.query.extra_select) != set(other.query.e...
[ "def", "_merge_sanity_check", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_fields", "is", "not", "None", "and", "(", "set", "(", "self", ".", "query", ".", "values_select", ")", "!=", "set", "(", "other", ".", "query", ".", "values_select"...
[ 1119, 4 ]
[ 1130, 13 ]
python
en
['en', 'error', 'th']
False
QuerySet._merge_known_related_objects
(self, other)
Keep track of all known related objects from either QuerySet instance.
Keep track of all known related objects from either QuerySet instance.
def _merge_known_related_objects(self, other): """ Keep track of all known related objects from either QuerySet instance. """ for field, objects in other._known_related_objects.items(): self._known_related_objects.setdefault(field, {}).update(objects)
[ "def", "_merge_known_related_objects", "(", "self", ",", "other", ")", ":", "for", "field", ",", "objects", "in", "other", ".", "_known_related_objects", ".", "items", "(", ")", ":", "self", ".", "_known_related_objects", ".", "setdefault", "(", "field", ",", ...
[ 1132, 4 ]
[ 1137, 77 ]
python
en
['en', 'error', 'th']
False
QuerySet._add_hints
(self, **hints)
Update hinting information for later use by Routers
Update hinting information for later use by Routers
def _add_hints(self, **hints): """ Update hinting information for later use by Routers """ # If there is any hinting information, add it to what we already know. # If we have a new hint for an existing key, overwrite with the new value. self._hints.update(hints)
[ "def", "_add_hints", "(", "self", ",", "*", "*", "hints", ")", ":", "# If there is any hinting information, add it to what we already know.", "# If we have a new hint for an existing key, overwrite with the new value.", "self", ".", "_hints", ".", "update", "(", "hints", ")" ]
[ 1151, 4 ]
[ 1157, 33 ]
python
en
['en', 'error', 'th']
False
QuerySet._has_filters
(self)
Checks if this QuerySet has any filtering going on. Note that this isn't equivalent for checking if all objects are present in results, for example qs[1:]._has_filters() -> False.
Checks if this QuerySet has any filtering going on. Note that this isn't equivalent for checking if all objects are present in results, for example qs[1:]._has_filters() -> False.
def _has_filters(self): """ Checks if this QuerySet has any filtering going on. Note that this isn't equivalent for checking if all objects are present in results, for example qs[1:]._has_filters() -> False. """ return self.query.has_filters()
[ "def", "_has_filters", "(", "self", ")", ":", "return", "self", ".", "query", ".", "has_filters", "(", ")" ]
[ 1159, 4 ]
[ 1165, 39 ]
python
en
['en', 'error', 'th']
False
RawQuerySet.resolve_model_init_order
(self)
Resolve the init field names and value positions
Resolve the init field names and value positions
def resolve_model_init_order(self): """ Resolve the init field names and value positions """ model_init_fields = [f for f in self.model._meta.fields if f.column in self.columns] annotation_fields = [(column, pos) for pos, column in enumerate(self.columns) ...
[ "def", "resolve_model_init_order", "(", "self", ")", ":", "model_init_fields", "=", "[", "f", "for", "f", "in", "self", ".", "model", ".", "_meta", ".", "fields", "if", "f", ".", "column", "in", "self", ".", "columns", "]", "annotation_fields", "=", "[",...
[ 1198, 4 ]
[ 1207, 68 ]
python
en
['en', 'error', 'th']
False
RawQuerySet.db
(self)
Return the database that will be used if this query is executed now
Return the database that will be used if this query is executed now
def db(self): "Return the database that will be used if this query is executed now" return self._db or router.db_for_read(self.model, **self._hints)
[ "def", "db", "(", "self", ")", ":", "return", "self", ".", "_db", "or", "router", ".", "db_for_read", "(", "self", ".", "model", ",", "*", "*", "self", ".", "_hints", ")" ]
[ 1256, 4 ]
[ 1258, 72 ]
python
en
['en', 'en', 'en']
True
RawQuerySet.using
(self, alias)
Selects which database this Raw QuerySet should execute its query against.
Selects which database this Raw QuerySet should execute its query against.
def using(self, alias): """ Selects which database this Raw QuerySet should execute its query against. """ return RawQuerySet( self.raw_query, model=self.model, query=self.query.clone(using=alias), params=self.params, translations=self.translations, ...
[ "def", "using", "(", "self", ",", "alias", ")", ":", "return", "RawQuerySet", "(", "self", ".", "raw_query", ",", "model", "=", "self", ".", "model", ",", "query", "=", "self", ".", "query", ".", "clone", "(", "using", "=", "alias", ")", ",", "para...
[ 1260, 4 ]
[ 1269, 9 ]
python
en
['en', 'error', 'th']
False
RawQuerySet.columns
(self)
A list of model field names in the order they'll appear in the query results.
A list of model field names in the order they'll appear in the query results.
def columns(self): """ A list of model field names in the order they'll appear in the query results. """ columns = self.query.get_columns() # Adjust any column names which don't match field names for (query_name, model_name) in self.translations.items(): ...
[ "def", "columns", "(", "self", ")", ":", "columns", "=", "self", ".", "query", ".", "get_columns", "(", ")", "# Adjust any column names which don't match field names", "for", "(", "query_name", ",", "model_name", ")", "in", "self", ".", "translations", ".", "ite...
[ 1272, 4 ]
[ 1286, 22 ]
python
en
['en', 'error', 'th']
False
RawQuerySet.model_fields
(self)
A dict mapping column names to model field names.
A dict mapping column names to model field names.
def model_fields(self): """ A dict mapping column names to model field names. """ converter = connections[self.db].introspection.table_name_converter model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() ...
[ "def", "model_fields", "(", "self", ")", ":", "converter", "=", "connections", "[", "self", ".", "db", "]", ".", "introspection", ".", "table_name_converter", "model_fields", "=", "{", "}", "for", "field", "in", "self", ".", "model", ".", "_meta", ".", "...
[ 1289, 4 ]
[ 1298, 27 ]
python
en
['en', 'error', 'th']
False
Tool.__init__
(self, name, attrs=None)
Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None.
Initializes the tool.
def __init__(self, name, attrs=None): """Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None. """ self._attrs = attrs or {} self._attrs["Name"] = name
[ "def", "__init__", "(", "self", ",", "name", ",", "attrs", "=", "None", ")", ":", "self", ".", "_attrs", "=", "attrs", "or", "{", "}", "self", ".", "_attrs", "[", "\"Name\"", "]", "=", "name" ]
[ 14, 4 ]
[ 22, 34 ]
python
en
['en', 'en', 'en']
True
Tool._GetSpecification
(self)
Creates an element for the tool. Returns: A new xml.dom.Element for the tool.
Creates an element for the tool.
def _GetSpecification(self): """Creates an element for the tool. Returns: A new xml.dom.Element for the tool. """ return ["Tool", self._attrs]
[ "def", "_GetSpecification", "(", "self", ")", ":", "return", "[", "\"Tool\"", ",", "self", ".", "_attrs", "]" ]
[ 24, 4 ]
[ 30, 36 ]
python
en
['en', 'en', 'en']
True
Filter.__init__
(self, name, contents=None)
Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained.
Initializes the folder.
def __init__(self, name, contents=None): """Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained. """ self.name = name self.contents = list(contents or [])
[ "def", "__init__", "(", "self", ",", "name", ",", "contents", "=", "None", ")", ":", "self", ".", "name", "=", "name", "self", ".", "contents", "=", "list", "(", "contents", "or", "[", "]", ")" ]
[ 36, 4 ]
[ 44, 44 ]
python
en
['en', 'zu', 'en']
True
Writer.__init__
(self, project_path, version, name, guid=None, platforms=None)
Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, ['Win32']
Initializes the project.
def __init__(self, project_path, version, name, guid=None, platforms=None): """Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of str...
[ "def", "__init__", "(", "self", ",", "project_path", ",", "version", ",", "name", ",", "guid", "=", "None", ",", "platforms", "=", "None", ")", ":", "self", ".", "project_path", "=", "project_path", "self", ".", "version", "=", "version", "self", ".", ...
[ 53, 4 ]
[ 81, 32 ]
python
en
['en', 'en', 'en']
True
Writer.AddToolFile
(self, path)
Adds a tool file to the project. Args: path: Relative path from project to tool file.
Adds a tool file to the project.
def AddToolFile(self, path): """Adds a tool file to the project. Args: path: Relative path from project to tool file. """ self.tool_files_section.append(["ToolFile", {"RelativePath": path}])
[ "def", "AddToolFile", "(", "self", ",", "path", ")", ":", "self", ".", "tool_files_section", ".", "append", "(", "[", "\"ToolFile\"", ",", "{", "\"RelativePath\"", ":", "path", "}", "]", ")" ]
[ 83, 4 ]
[ 89, 76 ]
python
en
['en', 'en', 'en']
True
Writer._GetSpecForConfiguration
(self, config_type, config_name, attrs, tools)
Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns:
Returns the specification for a configuration.
def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): """Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (s...
[ "def", "_GetSpecForConfiguration", "(", "self", ",", "config_type", ",", "config_name", ",", "attrs", ",", "tools", ")", ":", "# Handle defaults", "if", "not", "attrs", ":", "attrs", "=", "{", "}", "if", "not", "tools", ":", "tools", "=", "[", "]", "# Ad...
[ 91, 4 ]
[ 119, 28 ]
python
en
['en', 'en', 'en']
True
Writer.AddConfig
(self, name, attrs=None, tools=None)
Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None.
Adds a configuration to the project.
def AddConfig(self, name, attrs=None, tools=None): """Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ spec = self._GetSpecForConfiguratio...
[ "def", "AddConfig", "(", "self", ",", "name", ",", "attrs", "=", "None", ",", "tools", "=", "None", ")", ":", "spec", "=", "self", ".", "_GetSpecForConfiguration", "(", "\"Configuration\"", ",", "name", ",", "attrs", ",", "tools", ")", "self", ".", "co...
[ 121, 4 ]
[ 130, 48 ]
python
en
['en', 'en', 'en']
True
Writer._AddFilesToNode
(self, parent, files)
Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects.
Adds files and/or filters to the parent node.
def _AddFilesToNode(self, parent, files): """Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects. """ for f in files:...
[ "def", "_AddFilesToNode", "(", "self", ",", "parent", ",", "files", ")", ":", "for", "f", "in", "files", ":", "if", "isinstance", "(", "f", ",", "Filter", ")", ":", "node", "=", "[", "\"Filter\"", ",", "{", "\"Name\"", ":", "f", ".", "name", "}", ...
[ 132, 4 ]
[ 148, 31 ]
python
en
['en', 'en', 'en']
True
Writer.AddFiles
(self, files)
Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this pr...
Adds files to the project.
def AddFiles(self, files): """Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(...
[ "def", "AddFiles", "(", "self", ",", "files", ")", ":", "self", ".", "_AddFilesToNode", "(", "self", ".", "files_section", ",", "files", ")" ]
[ 150, 4 ]
[ 160, 55 ]
python
en
['en', 'en', 'en']
True
Writer.AddFileConfig
(self, path, config, attrs=None, tools=None)
Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any fil...
Adds a configuration to a file.
def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be...
[ "def", "AddFileConfig", "(", "self", ",", "path", ",", "config", ",", "attrs", "=", "None", ",", "tools", "=", "None", ")", ":", "# Find the file node with the right relative path", "parent", "=", "self", ".", "files_dict", ".", "get", "(", "path", ")", "if"...
[ 164, 4 ]
[ 183, 27 ]
python
en
['en', 'en', 'en']
True
Writer.WriteIfChanged
(self)
Writes the project file.
Writes the project file.
def WriteIfChanged(self): """Writes the project file.""" # First create XML content definition content = [ "VisualStudioProject", { "ProjectType": "Visual C++", "Version": self.version.ProjectVersion(), "Name": self.name, ...
[ "def", "WriteIfChanged", "(", "self", ")", ":", "# First create XML content definition", "content", "=", "[", "\"VisualStudioProject\"", ",", "{", "\"ProjectType\"", ":", "\"Visual C++\"", ",", "\"Version\"", ":", "self", ".", "version", ".", "ProjectVersion", "(", ...
[ 185, 4 ]
[ 205, 87 ]
python
en
['en', 'en', 'en']
True