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
setup_web_public_test
(self, num_web_public_message: int = 1)
Send N+2 messages, N in a web-public stream, then one in a non web-public stream and then a private message.
Send N+2 messages, N in a web-public stream, then one in a non web-public stream and then a private message.
def setup_web_public_test(self, num_web_public_message: int = 1) -> None: """ Send N+2 messages, N in a web-public stream, then one in a non web-public stream and then a private message. """ user_profile = self.example_user("iago") self.login("iago") web_public_st...
[ "def", "setup_web_public_test", "(", "self", ",", "num_web_public_message", ":", "int", "=", "1", ")", "->", "None", ":", "user_profile", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "self", ".", "login", "(", "\"iago\"", ")", "web_public_stream", ...
[ 1558, 4 ]
[ 1580, 21 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_web_public
(self)
An unauthenticated call to GET /json/messages with valid parameters including `streams:web-public` narrow returns list of messages in the `web-public` streams.
An unauthenticated call to GET /json/messages with valid parameters including `streams:web-public` narrow returns list of messages in the `web-public` streams.
def test_get_messages_with_web_public(self) -> None: """ An unauthenticated call to GET /json/messages with valid parameters including `streams:web-public` narrow returns list of messages in the `web-public` streams. """ self.setup_web_public_test(num_web_public_message=8...
[ "def", "test_get_messages_with_web_public", "(", "self", ")", "->", "None", ":", "self", ".", "setup_web_public_test", "(", "num_web_public_message", "=", "8", ")", "post_params", "=", "{", "\"anchor\"", ":", "\"first_unread\"", ",", "\"num_before\"", ":", "5", ",...
[ 1612, 4 ]
[ 1631, 62 ]
python
en
['en', 'error', 'th']
False
test_client_avatar
(self)
The client_gravatar flag determines whether we send avatar_url.
The client_gravatar flag determines whether we send avatar_url.
def test_client_avatar(self) -> None: """ The client_gravatar flag determines whether we send avatar_url. """ hamlet = self.example_user("hamlet") self.login_user(hamlet) do_set_realm_property( hamlet.realm, "email_address_visibility", ...
[ "def", "test_client_avatar", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "self", ".", "login_user", "(", "hamlet", ")", "do_set_realm_property", "(", "hamlet", ".", "realm", ",", "\"email_address_vis...
[ 1633, 4 ]
[ 1666, 60 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_pm_with
(self)
A request for old messages with a narrow by pm-with only returns conversations with that user.
A request for old messages with a narrow by pm-with only returns conversations with that user.
def test_get_messages_with_narrow_pm_with(self) -> None: """ A request for old messages with a narrow by pm-with only returns conversations with that user. """ me = self.example_user("hamlet") def dr_emails(dr: DisplayRecipientT) -> str: assert isinstance(dr,...
[ "def", "test_get_messages_with_narrow_pm_with", "(", "self", ")", "->", "None", ":", "me", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "def", "dr_emails", "(", "dr", ":", "DisplayRecipientT", ")", "->", "str", ":", "assert", "isinstance", "(", ...
[ 1668, 4 ]
[ 1720, 81 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_group_pm_with
(self)
A request for old messages with a narrow by group-pm-with only returns group-private conversations with that user.
A request for old messages with a narrow by group-pm-with only returns group-private conversations with that user.
def test_get_messages_with_narrow_group_pm_with(self) -> None: """ A request for old messages with a narrow by group-pm-with only returns group-private conversations with that user. """ me = self.example_user("hamlet") iago = self.example_user("iago") cordelia = ...
[ "def", "test_get_messages_with_narrow_group_pm_with", "(", "self", ")", "->", "None", ":", "me", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "iago", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "cordelia", "=", "self", ".", "example_us...
[ 1734, 4 ]
[ 1788, 73 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_stream
(self)
A request for old messages with a narrow by stream only returns messages for that stream.
A request for old messages with a narrow by stream only returns messages for that stream.
def test_get_messages_with_narrow_stream(self) -> None: """ A request for old messages with a narrow by stream only returns messages for that stream. """ self.login("hamlet") # We need to subscribe to a stream and then send a message to # it to ensure that we actu...
[ "def", "test_get_messages_with_narrow_stream", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "# We need to subscribe to a stream and then send a message to", "# it to ensure that we actually have a stream message in this", "# narrow view.", "sel...
[ 1862, 4 ]
[ 1886, 78 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_stream_mit_unicode_regex
(self)
A request for old messages for a user in the mit.edu relam with Unicode stream name should be correctly escaped in the database query.
A request for old messages for a user in the mit.edu relam with Unicode stream name should be correctly escaped in the database query.
def test_get_messages_with_narrow_stream_mit_unicode_regex(self) -> None: """ A request for old messages for a user in the mit.edu relam with Unicode stream name should be correctly escaped in the database query. """ user = self.mit_user("starnine") self.login_user(user) ...
[ "def", "test_get_messages_with_narrow_stream_mit_unicode_regex", "(", "self", ")", "->", "None", ":", "user", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "self", ".", "login_user", "(", "user", ")", "# We need to susbcribe to a stream and then send a message t...
[ 1899, 4 ]
[ 1931, 64 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_topic_mit_unicode_regex
(self)
A request for old messages for a user in the mit.edu realm with Unicode topic name should be correctly escaped in the database query.
A request for old messages for a user in the mit.edu realm with Unicode topic name should be correctly escaped in the database query.
def test_get_messages_with_narrow_topic_mit_unicode_regex(self) -> None: """ A request for old messages for a user in the mit.edu realm with Unicode topic name should be correctly escaped in the database query. """ mit_user_profile = self.mit_user("starnine") self.login_u...
[ "def", "test_get_messages_with_narrow_topic_mit_unicode_regex", "(", "self", ")", "->", "None", ":", "mit_user_profile", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "self", ".", "login_user", "(", "mit_user_profile", ")", "# We need to susbcribe to a stream an...
[ 1933, 4 ]
[ 1961, 64 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_topic_mit_personal
(self)
We handle .d grouping for MIT realm personal messages correctly.
We handle .d grouping for MIT realm personal messages correctly.
def test_get_messages_with_narrow_topic_mit_personal(self) -> None: """ We handle .d grouping for MIT realm personal messages correctly. """ mit_user_profile = self.mit_user("starnine") # We need to susbcribe to a stream and then send a message to # it to ensure that we ...
[ "def", "test_get_messages_with_narrow_topic_mit_personal", "(", "self", ")", "->", "None", ":", "mit_user_profile", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "# We need to susbcribe to a stream and then send a message to", "# it to ensure that we actually have a strea...
[ 1963, 4 ]
[ 1995, 64 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_narrow_sender
(self)
A request for old messages with a narrow by sender only returns messages sent by that person.
A request for old messages with a narrow by sender only returns messages sent by that person.
def test_get_messages_with_narrow_sender(self) -> None: """ A request for old messages with a narrow by sender only returns messages sent by that person. """ self.login("hamlet") hamlet = self.example_user("hamlet") othello = self.example_user("othello") ...
[ "def", "test_get_messages_with_narrow_sender", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "othello", "=", "self", ".", "example_user", "(", "\"othello\"...
[ 1997, 4 ]
[ 2021, 66 ]
python
en
['en', 'error', 'th']
False
test_get_messages_with_search_not_subscribed
(self)
Verify support for searching a stream you're not subscribed to
Verify support for searching a stream you're not subscribed to
def test_get_messages_with_search_not_subscribed(self) -> None: """Verify support for searching a stream you're not subscribed to""" self.subscribe(self.example_user("hamlet"), "newstream") self.send_stream_message( sender=self.example_user("hamlet"), stream_name="newstre...
[ "def", "test_get_messages_with_search_not_subscribed", "(", "self", ")", "->", "None", ":", "self", ".", "subscribe", "(", "self", ".", "example_user", "(", "\"hamlet\"", ")", ",", "\"newstream\"", ")", "self", ".", "send_stream_message", "(", "sender", "=", "se...
[ 2246, 4 ]
[ 2275, 9 ]
python
en
['en', 'en', 'en']
True
test_get_messages_with_only_searching_anchor
(self)
Test that specifying an anchor but 0 for num_before and num_after returns at most 1 message.
Test that specifying an anchor but 0 for num_before and num_after returns at most 1 message.
def test_get_messages_with_only_searching_anchor(self) -> None: """ Test that specifying an anchor but 0 for num_before and num_after returns at most 1 message. """ self.login("cordelia") cordelia = self.example_user("cordelia") anchor = self.send_stream_message...
[ "def", "test_get_messages_with_only_searching_anchor", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"cordelia\"", ")", "cordelia", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "anchor", "=", "self", ".", "send_stream_message", ...
[ 2467, 4 ]
[ 2493, 49 ]
python
en
['en', 'error', 'th']
False
Is
(param)
param: [remaining_capacity1, remaining_capacity2, remaining_capacity3, ...] [(jobs_running1, capacity1), (jobs_running2, capacity2), (jobs_running3, capacity3), ...]
param: [remaining_capacity1, remaining_capacity2, remaining_capacity3, ...] [(jobs_running1, capacity1), (jobs_running2, capacity2), (jobs_running3, capacity3), ...]
def Is(param): """ param: [remaining_capacity1, remaining_capacity2, remaining_capacity3, ...] [(jobs_running1, capacity1), (jobs_running2, capacity2), (jobs_running3, capacity3), ...] """ instances = [] if isinstance(param[0], tuple): for (jobs_running, capacity) in param: ...
[ "def", "Is", "(", "param", ")", ":", "instances", "=", "[", "]", "if", "isinstance", "(", "param", "[", "0", "]", ",", "tuple", ")", ":", "for", "(", "jobs_running", ",", "capacity", ")", "in", "param", ":", "inst", "=", "Mock", "(", ")", "inst",...
[ 25, 0 ]
[ 46, 20 ]
python
en
['en', 'error', 'th']
False
get_roc_score
(edges_pos, edges_neg, embeddings, adj_sparse)
from https://github.com/tkipf/gae
from https://github.com/tkipf/gae
def get_roc_score(edges_pos, edges_neg, embeddings, adj_sparse): "from https://github.com/tkipf/gae" score_matrix = np.dot(embeddings, embeddings.T) def sigmoid(x): return 1 / (1 + np.exp(-x)) # Store positive edge predictions, actual values preds_pos = [] pos = [] for...
[ "def", "get_roc_score", "(", "edges_pos", ",", "edges_neg", ",", "embeddings", ",", "adj_sparse", ")", ":", "score_matrix", "=", "np", ".", "dot", "(", "embeddings", ",", "embeddings", ".", "T", ")", "def", "sigmoid", "(", "x", ")", ":", "return", "1", ...
[ 15, 0 ]
[ 45, 30 ]
python
en
['en', 'no', 'sw']
False
ObjectIndexer.as_vector
(self, texts, for_autocomplete=False)
Converts an array of strings into a SearchVector that can be indexed.
Converts an array of strings into a SearchVector that can be indexed.
def as_vector(self, texts, for_autocomplete=False): """ Converts an array of strings into a SearchVector that can be indexed. """ texts = [(text.strip(), weight) for text, weight in texts] texts = [(text, weight) for text, weight in texts if text] if not texts: ...
[ "def", "as_vector", "(", "self", ",", "texts", ",", "for_autocomplete", "=", "False", ")", ":", "texts", "=", "[", "(", "text", ".", "strip", "(", ")", ",", "weight", ")", "for", "text", ",", "weight", "in", "texts", "]", "texts", "=", "[", "(", ...
[ 81, 4 ]
[ 96, 10 ]
python
en
['en', 'error', 'th']
False
ObjectIndexer.id
(self)
Returns the value to use as the ID of the record in the index
Returns the value to use as the ID of the record in the index
def id(self): """ Returns the value to use as the ID of the record in the index """ return force_str(self.obj.pk)
[ "def", "id", "(", "self", ")", ":", "return", "force_str", "(", "self", ".", "obj", ".", "pk", ")" ]
[ 99, 4 ]
[ 103, 37 ]
python
en
['en', 'error', 'th']
False
ObjectIndexer.title
(self)
Returns all values to index as "title". This is the value of all SearchFields that have the field_name 'title'
Returns all values to index as "title". This is the value of all SearchFields that have the field_name 'title'
def title(self): """ Returns all values to index as "title". This is the value of all SearchFields that have the field_name 'title' """ texts = [] for field in self.search_fields: for current_field, boost, value in self.prepare_field(self.obj, field): ...
[ "def", "title", "(", "self", ")", ":", "texts", "=", "[", "]", "for", "field", "in", "self", ".", "search_fields", ":", "for", "current_field", ",", "boost", ",", "value", "in", "self", ".", "prepare_field", "(", "self", ".", "obj", ",", "field", ")"...
[ 106, 4 ]
[ 116, 36 ]
python
en
['en', 'error', 'th']
False
ObjectIndexer.body
(self)
Returns all values to index as "body". This is the value of all SearchFields excluding the title
Returns all values to index as "body". This is the value of all SearchFields excluding the title
def body(self): """ Returns all values to index as "body". This is the value of all SearchFields excluding the title """ texts = [] for field in self.search_fields: for current_field, boost, value in self.prepare_field(self.obj, field): if isinstance(c...
[ "def", "body", "(", "self", ")", ":", "texts", "=", "[", "]", "for", "field", "in", "self", ".", "search_fields", ":", "for", "current_field", ",", "boost", ",", "value", "in", "self", ".", "prepare_field", "(", "self", ".", "obj", ",", "field", ")",...
[ 119, 4 ]
[ 129, 36 ]
python
en
['en', 'error', 'th']
False
ObjectIndexer.autocomplete
(self)
Returns all values to index as "autocomplete". This is the value of all AutocompleteFields
Returns all values to index as "autocomplete". This is the value of all AutocompleteFields
def autocomplete(self): """ Returns all values to index as "autocomplete". This is the value of all AutocompleteFields """ texts = [] for field in self.search_fields: for current_field, boost, value in self.prepare_field(self.obj, field): if isinstance...
[ "def", "autocomplete", "(", "self", ")", ":", "texts", "=", "[", "]", "for", "field", "in", "self", ".", "search_fields", ":", "for", "current_field", ",", "boost", ",", "value", "in", "self", ".", "prepare_field", "(", "self", ".", "obj", ",", "field"...
[ 132, 4 ]
[ 142, 59 ]
python
en
['en', 'error', 'th']
False
Index._refresh_title_norms
(self, full=False)
Refreshes the value of the title_norm field. This needs to be set to 'lavg/ld' where: - lavg is the average length of titles in all documents (also in terms) - ld is the length of the title field in this document (in terms)
Refreshes the value of the title_norm field.
def _refresh_title_norms(self, full=False): """ Refreshes the value of the title_norm field. This needs to be set to 'lavg/ld' where: - lavg is the average length of titles in all documents (also in terms) - ld is the length of the title field in this document (in terms) ...
[ "def", "_refresh_title_norms", "(", "self", ",", "full", "=", "False", ")", ":", "lavg", "=", "self", ".", "entries", ".", "annotate", "(", "title_length", "=", "Length", "(", "'title'", ")", ")", ".", "filter", "(", "title_length__gt", "=", "0", ")", ...
[ 167, 4 ]
[ 190, 125 ]
python
en
['en', 'error', 'th']
False
monthly_commits
(repo_dir, commits)
A generator to downsample commits to be the first one per month.
A generator to downsample commits to be the first one per month.
def monthly_commits(repo_dir, commits): '''A generator to downsample commits to be the first one per month.''' last_year = 0 last_month = 0 for commit in commits: dt = dateparser.parse(get_commit_date(repo_dir, commit)) if dt.year > last_year: last_month = 0 last_...
[ "def", "monthly_commits", "(", "repo_dir", ",", "commits", ")", ":", "last_year", "=", "0", "last_month", "=", "0", "for", "commit", "in", "commits", ":", "dt", "=", "dateparser", ".", "parse", "(", "get_commit_date", "(", "repo_dir", ",", "commit", ")", ...
[ 76, 0 ]
[ 87, 24 ]
python
en
['en', 'en', 'en']
True
get_task_form_class
(task_model, for_edit=False)
Generates a form class for the given task model. If the form is to edit an existing task, set for_edit to True. This applies the readonly restrictions on fields defined in admin_form_readonly_on_edit_fields.
Generates a form class for the given task model.
def get_task_form_class(task_model, for_edit=False): """ Generates a form class for the given task model. If the form is to edit an existing task, set for_edit to True. This applies the readonly restrictions on fields defined in admin_form_readonly_on_edit_fields. """ fields = task_model.admin_...
[ "def", "get_task_form_class", "(", "task_model", ",", "for_edit", "=", "False", ")", ":", "fields", "=", "task_model", ".", "admin_form_fields", "form_class", "=", "forms", ".", "modelform_factory", "(", "task_model", ",", "form", "=", "BaseTaskForm", ",", "fiel...
[ 152, 0 ]
[ 180, 21 ]
python
en
['en', 'error', 'th']
False
get_workflow_edit_handler
()
Returns an edit handler which provides the "name" and "tasks" fields for workflow.
Returns an edit handler which provides the "name" and "tasks" fields for workflow.
def get_workflow_edit_handler(): """ Returns an edit handler which provides the "name" and "tasks" fields for workflow. """ # Note. It's a bit of a hack that we use edit handlers here. Ideally, it should be # made easier to reuse the inline panel templates for any formset. # Since this form is i...
[ "def", "get_workflow_edit_handler", "(", ")", ":", "# Note. It's a bit of a hack that we use edit handlers here. Ideally, it should be", "# made easier to reuse the inline panel templates for any formset.", "# Since this form is internal, we're OK with this for now. We might want to revisit", "# thi...
[ 183, 0 ]
[ 199, 47 ]
python
en
['en', 'error', 'th']
False
TaskChooserSearchForm.is_searching
(self)
Returns True if the user typed a search query
Returns True if the user typed a search query
def is_searching(self): """ Returns True if the user typed a search query """ return self.is_valid() and bool(self.cleaned_data.get('q'))
[ "def", "is_searching", "(", "self", ")", ":", "return", "self", ".", "is_valid", "(", ")", "and", "bool", "(", "self", ".", "cleaned_data", ".", "get", "(", "'q'", ")", ")" ]
[ 45, 4 ]
[ 49, 67 ]
python
en
['en', 'error', 'th']
False
TaskChooserSearchForm.task_model
(self)
Returns the selected task model. This looks for the task model in the following order: 1) If there's only one task model option, return it 2) If a task model has been selected, return it 3) Return the generic Task model
Returns the selected task model.
def task_model(self): """ Returns the selected task model. This looks for the task model in the following order: 1) If there's only one task model option, return it 2) If a task model has been selected, return it 3) Return the generic Task model """ mo...
[ "def", "task_model", "(", "self", ")", ":", "models", "=", "list", "(", "self", ".", "task_type_choices", ".", "values", "(", ")", ")", "if", "len", "(", "models", ")", "==", "1", ":", "return", "models", "[", "0", "]", "elif", "self", ".", "is_val...
[ 52, 4 ]
[ 70, 19 ]
python
en
['en', 'error', 'th']
False
BaseWorkflowPagesFormSet.clean
(self)
Checks that no two forms refer to the same page object
Checks that no two forms refer to the same page object
def clean(self): """Checks that no two forms refer to the same page object""" if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return pages = [ form.cleaned_data['page'] for form in self.forms ...
[ "def", "clean", "(", "self", ")", ":", "if", "any", "(", "self", ".", "errors", ")", ":", "# Don't bother validating the formset unless each form is valid on its own", "return", "pages", "=", "[", "form", ".", "cleaned_data", "[", "'page'", "]", "for", "form", "...
[ 125, 4 ]
[ 140, 110 ]
python
en
['en', 'en', 'en']
True
AccessMixin.get_login_url
(self)
Override this method to override the login_url attribute.
Override this method to override the login_url attribute.
def get_login_url(self): """ Override this method to override the login_url attribute. """ login_url = self.login_url or settings.LOGIN_URL if not login_url: raise ImproperlyConfigured( '{0} is missing the login_url attribute. Define {0}.login_url, set...
[ "def", "get_login_url", "(", "self", ")", ":", "login_url", "=", "self", ".", "login_url", "or", "settings", ".", "LOGIN_URL", "if", "not", "login_url", ":", "raise", "ImproperlyConfigured", "(", "'{0} is missing the login_url attribute. Define {0}.login_url, settings.LOG...
[ 18, 4 ]
[ 28, 36 ]
python
en
['en', 'error', 'th']
False
AccessMixin.get_permission_denied_message
(self)
Override this method to override the permission_denied_message attribute.
Override this method to override the permission_denied_message attribute.
def get_permission_denied_message(self): """ Override this method to override the permission_denied_message attribute. """ return self.permission_denied_message
[ "def", "get_permission_denied_message", "(", "self", ")", ":", "return", "self", ".", "permission_denied_message" ]
[ 30, 4 ]
[ 34, 45 ]
python
en
['en', 'error', 'th']
False
AccessMixin.get_redirect_field_name
(self)
Override this method to override the redirect_field_name attribute.
Override this method to override the redirect_field_name attribute.
def get_redirect_field_name(self): """ Override this method to override the redirect_field_name attribute. """ return self.redirect_field_name
[ "def", "get_redirect_field_name", "(", "self", ")", ":", "return", "self", ".", "redirect_field_name" ]
[ 36, 4 ]
[ 40, 39 ]
python
en
['en', 'error', 'th']
False
PermissionRequiredMixin.get_permission_required
(self)
Override this method to override the permission_required attribute. Must return an iterable.
Override this method to override the permission_required attribute. Must return an iterable.
def get_permission_required(self): """ Override this method to override the permission_required attribute. Must return an iterable. """ if self.permission_required is None: raise ImproperlyConfigured( '{0} is missing the permission_required attribute. ...
[ "def", "get_permission_required", "(", "self", ")", ":", "if", "self", ".", "permission_required", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "'{0} is missing the permission_required attribute. Define {0}.permission_required, or override '", "'{0}.get_permission_requi...
[ 65, 4 ]
[ 79, 20 ]
python
en
['en', 'error', 'th']
False
PermissionRequiredMixin.has_permission
(self)
Override this method to customize the way permissions are checked.
Override this method to customize the way permissions are checked.
def has_permission(self): """ Override this method to customize the way permissions are checked. """ perms = self.get_permission_required() return self.request.user.has_perms(perms)
[ "def", "has_permission", "(", "self", ")", ":", "perms", "=", "self", ".", "get_permission_required", "(", ")", "return", "self", ".", "request", ".", "user", ".", "has_perms", "(", "perms", ")" ]
[ 81, 4 ]
[ 86, 49 ]
python
en
['en', 'error', 'th']
False
UserPassesTestMixin.get_test_func
(self)
Override this method to use a different test_func method.
Override this method to use a different test_func method.
def get_test_func(self): """ Override this method to use a different test_func method. """ return self.test_func
[ "def", "get_test_func", "(", "self", ")", ":", "return", "self", ".", "test_func" ]
[ 105, 4 ]
[ 109, 29 ]
python
en
['en', 'error', 'th']
False
_running_under_venv
()
Checks if sys.base_prefix and sys.prefix match. This handles PEP 405 compliant virtual environments.
Checks if sys.base_prefix and sys.prefix match.
def _running_under_venv(): # type: () -> bool """Checks if sys.base_prefix and sys.prefix match. This handles PEP 405 compliant virtual environments. """ return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
[ "def", "_running_under_venv", "(", ")", ":", "# type: () -> bool", "return", "sys", ".", "prefix", "!=", "getattr", "(", "sys", ",", "\"base_prefix\"", ",", "sys", ".", "prefix", ")" ]
[ 20, 0 ]
[ 26, 64 ]
python
en
['en', 'ht', 'en']
True
_running_under_regular_virtualenv
()
Checks if sys.real_prefix is set. This handles virtual environments created with pypa's virtualenv.
Checks if sys.real_prefix is set.
def _running_under_regular_virtualenv(): # type: () -> bool """Checks if sys.real_prefix is set. This handles virtual environments created with pypa's virtualenv. """ # pypa/virtualenv case return hasattr(sys, 'real_prefix')
[ "def", "_running_under_regular_virtualenv", "(", ")", ":", "# type: () -> bool", "# pypa/virtualenv case", "return", "hasattr", "(", "sys", ",", "'real_prefix'", ")" ]
[ 29, 0 ]
[ 36, 38 ]
python
en
['en', 'en', 'en']
True
running_under_virtualenv
()
Return True if we're running inside a virtualenv, False otherwise.
Return True if we're running inside a virtualenv, False otherwise.
def running_under_virtualenv(): # type: () -> bool """Return True if we're running inside a virtualenv, False otherwise. """ return _running_under_venv() or _running_under_regular_virtualenv()
[ "def", "running_under_virtualenv", "(", ")", ":", "# type: () -> bool", "return", "_running_under_venv", "(", ")", "or", "_running_under_regular_virtualenv", "(", ")" ]
[ 39, 0 ]
[ 43, 71 ]
python
en
['en', 'en', 'en']
True
_get_pyvenv_cfg_lines
()
Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines Returns None, if it could not read/access the file.
Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
def _get_pyvenv_cfg_lines(): # type: () -> Optional[List[str]] """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines Returns None, if it could not read/access the file. """ pyvenv_cfg_file = os.path.join(sys.prefix, 'pyvenv.cfg') try: # Although PEP 405 does not spe...
[ "def", "_get_pyvenv_cfg_lines", "(", ")", ":", "# type: () -> Optional[List[str]]", "pyvenv_cfg_file", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "'pyvenv.cfg'", ")", "try", ":", "# Although PEP 405 does not specify, the built-in venv module alwa...
[ 46, 0 ]
[ 59, 19 ]
python
en
['en', 'en', 'en']
True
_no_global_under_venv
()
Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion PEP 405 specifies that when system site-packages are not supposed to be visible from a virtual environment, `pyvenv.cfg` must contain the following line: include-system-site-packages = false Additionally, log a warning if acce...
Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
def _no_global_under_venv(): # type: () -> bool """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion PEP 405 specifies that when system site-packages are not supposed to be visible from a virtual environment, `pyvenv.cfg` must contain the following line: include-system-sit...
[ "def", "_no_global_under_venv", "(", ")", ":", "# type: () -> bool", "cfg_lines", "=", "_get_pyvenv_cfg_lines", "(", ")", "if", "cfg_lines", "is", "None", ":", "# We're not in a \"sane\" venv, so assume there is no system", "# site-packages access (since that's PEP 405's default st...
[ 62, 0 ]
[ 89, 16 ]
python
en
['en', 'en', 'en']
True
_no_global_under_regular_virtualenv
()
Check if "no-global-site-packages.txt" exists beside site.py This mirrors logic in pypa/virtualenv for determining whether system site-packages are visible in the virtual environment.
Check if "no-global-site-packages.txt" exists beside site.py
def _no_global_under_regular_virtualenv(): # type: () -> bool """Check if "no-global-site-packages.txt" exists beside site.py This mirrors logic in pypa/virtualenv for determining whether system site-packages are visible in the virtual environment. """ site_mod_dir = os.path.dirname(os.path.abs...
[ "def", "_no_global_under_regular_virtualenv", "(", ")", ":", "# type: () -> bool", "site_mod_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "site", ".", "__file__", ")", ")", "no_global_site_packages_file", "=", "os", ...
[ 92, 0 ]
[ 103, 55 ]
python
en
['en', 'en', 'en']
True
virtualenv_no_global
()
Returns a boolean, whether running in venv with no system site-packages.
Returns a boolean, whether running in venv with no system site-packages.
def virtualenv_no_global(): # type: () -> bool """Returns a boolean, whether running in venv with no system site-packages. """ # PEP 405 compliance needs to be checked first since virtualenv >=20 would # return True for both checks, but is only able to use the PEP 405 config. if _running_under_v...
[ "def", "virtualenv_no_global", "(", ")", ":", "# type: () -> bool", "# PEP 405 compliance needs to be checked first since virtualenv >=20 would", "# return True for both checks, but is only able to use the PEP 405 config.", "if", "_running_under_venv", "(", ")", ":", "return", "_no_globa...
[ 106, 0 ]
[ 118, 16 ]
python
en
['en', 'en', 'en']
True
get_free_port
()
Get free port.
Get free port.
def get_free_port() -> int: """Get free port.""" sock = socket.socket() sock.bind(('localhost', 0)) port = sock.getsockname()[1] sock.close() del sock gc.collect() return port
[ "def", "get_free_port", "(", ")", "->", "int", ":", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "bind", "(", "(", "'localhost'", ",", "0", ")", ")", "port", "=", "sock", ".", "getsockname", "(", ")", "[", "1", "]", "sock", ".", ...
[ 21, 0 ]
[ 29, 15 ]
python
en
['en', 'ko', 'en']
True
merge_dict
(dict1: Optional[Dict], dict2: Optional[Dict])
Merge two dictionaries into new one.
Merge two dictionaries into new one.
def merge_dict(dict1: Optional[Dict], dict2: Optional[Dict]) -> Dict: """Merge two dictionaries into new one.""" new_dict = {} if dict1: new_dict.update(dict1) if dict2: new_dict.update(dict2) return new_dict
[ "def", "merge_dict", "(", "dict1", ":", "Optional", "[", "Dict", "]", ",", "dict2", ":", "Optional", "[", "Dict", "]", ")", "->", "Dict", ":", "new_dict", "=", "{", "}", "if", "dict1", ":", "new_dict", ".", "update", "(", "dict1", ")", "if", "dict2...
[ 32, 0 ]
[ 39, 19 ]
python
en
['it', 'en', 'en']
True
GeometryField.to_python
(self, value)
Transforms the value to a Geometry object.
Transforms the value to a Geometry object.
def to_python(self, value): """ Transforms the value to a Geometry object. """ if value in self.empty_values: return None if not isinstance(value, GEOSGeometry): try: value = GEOSGeometry(value) except (GEOSException, ValueErro...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "not", "isinstance", "(", "value", ",", "GEOSGeometry", ")", ":", "try", ":", "value", "=", "GEOSGeometry", "(", "va...
[ 34, 4 ]
[ 54, 20 ]
python
en
['en', 'error', 'th']
False
GeometryField.clean
(self, value)
Validates that the input value can be converted to a Geometry object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry.
Validates that the input value can be converted to a Geometry object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry.
def clean(self, value): """ Validates that the input value can be converted to a Geometry object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry. """ geom = super(GeometryField, self).clean(value) if geom is None...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "geom", "=", "super", "(", "GeometryField", ",", "self", ")", ".", "clean", "(", "value", ")", "if", "geom", "is", "None", ":", "return", "geom", "# Ensuring that the geometry is of the correct type (indicat...
[ 56, 4 ]
[ 79, 19 ]
python
en
['en', 'error', 'th']
False
GeometryField.has_changed
(self, initial, data)
Compare geographic value of data with its initial value.
Compare geographic value of data with its initial value.
def has_changed(self, initial, data): """ Compare geographic value of data with its initial value. """ try: data = self.to_python(data) initial = self.to_python(initial) except forms.ValidationError: return True # Only do a geographic comparison if b...
[ "def", "has_changed", "(", "self", ",", "initial", ",", "data", ")", ":", "try", ":", "data", "=", "self", ".", "to_python", "(", "data", ")", "initial", "=", "self", ".", "to_python", "(", "initial", ")", "except", "forms", ".", "ValidationError", ":"...
[ 81, 4 ]
[ 99, 46 ]
python
en
['en', 'en', 'en']
True
GeoModelAdmin.media
(self)
Injects OpenLayers JavaScript into the admin.
Injects OpenLayers JavaScript into the admin.
def media(self): "Injects OpenLayers JavaScript into the admin." media = super(GeoModelAdmin, self).media media.add_js([self.openlayers_url]) media.add_js(self.extra_js) return media
[ "def", "media", "(", "self", ")", ":", "media", "=", "super", "(", "GeoModelAdmin", ",", "self", ")", ".", "media", "media", ".", "add_js", "(", "[", "self", ".", "openlayers_url", "]", ")", "media", ".", "add_js", "(", "self", ".", "extra_js", ")", ...
[ 46, 4 ]
[ 51, 20 ]
python
en
['en', 'en', 'en']
True
GeoModelAdmin.formfield_for_dbfield
(self, db_field, request, **kwargs)
Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing).
Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing).
def formfield_for_dbfield(self, db_field, request, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ if isinstance(db_field, models.GeometryField) and db_fiel...
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "db_field", ",", "models", ".", "GeometryField", ")", "and", "db_field", ".", "dim", "<", "3", ":", "# Setting the wid...
[ 53, 4 ]
[ 64, 96 ]
python
en
['en', 'error', 'th']
False
GeoModelAdmin.get_map_widget
(self, db_field)
Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.
Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.
def get_map_widget(self, db_field): """ Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class. """ is_collection = db_field.geom_type in ('MULTIPOINT', 'MULTILINESTRING', '...
[ "def", "get_map_widget", "(", "self", ",", "db_field", ")", ":", "is_collection", "=", "db_field", ".", "geom_type", "in", "(", "'MULTIPOINT'", ",", "'MULTILINESTRING'", ",", "'MULTIPOLYGON'", ",", "'GEOMETRYCOLLECTION'", ")", "if", "is_collection", ":", "if", "...
[ 66, 4 ]
[ 124, 20 ]
python
en
['en', 'error', 'th']
False
interactive_debug
(sig: int, frame: FrameType)
Interrupt running process, and provide a python prompt for interactive debugging.
Interrupt running process, and provide a python prompt for interactive debugging.
def interactive_debug(sig: int, frame: FrameType) -> None: """Interrupt running process, and provide a python prompt for interactive debugging.""" d = {"_frame": frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) message = "Si...
[ "def", "interactive_debug", "(", "sig", ":", "int", ",", "frame", ":", "FrameType", ")", "->", "None", ":", "d", "=", "{", "\"_frame\"", ":", "frame", "}", "# Allow access to frame object.", "d", ".", "update", "(", "frame", ".", "f_globals", ")", "# Unles...
[ 22, 0 ]
[ 32, 23 ]
python
en
['en', 'en', 'en']
True
maybe_tracemalloc_listen
()
If tracemalloc tracing enabled, listen for requests to dump a snapshot. To trigger once this is listening: echo | socat -u stdin unix-sendto:/tmp/tracemalloc.$pid To enable in the Zulip web server: edit /etc/zulip/uwsgi.ini , and add e.g. ` PYTHONTRACEMALLOC=5` to the `env=` line. This function ...
If tracemalloc tracing enabled, listen for requests to dump a snapshot.
def maybe_tracemalloc_listen() -> None: """If tracemalloc tracing enabled, listen for requests to dump a snapshot. To trigger once this is listening: echo | socat -u stdin unix-sendto:/tmp/tracemalloc.$pid To enable in the Zulip web server: edit /etc/zulip/uwsgi.ini , and add e.g. ` PYTHONTRACEM...
[ "def", "maybe_tracemalloc_listen", "(", ")", "->", "None", ":", "if", "os", ".", "environ", ".", "get", "(", "\"PYTHONTRACEMALLOC\"", ")", ":", "# If the server was started with `tracemalloc` tracing on, then", "# listen for a signal to dump `tracemalloc` snapshots.", "tracemal...
[ 93, 0 ]
[ 112, 28 ]
python
en
['en', 'en', 'en']
True
_sample_sub_epoch
( start_of_epoch_weight: uint128, end_of_epoch_weight: uint128, weight_to_check: List[uint128], )
weight_to_check: List[uint128] is expected to be sorted
weight_to_check: List[uint128] is expected to be sorted
def _sample_sub_epoch( start_of_epoch_weight: uint128, end_of_epoch_weight: uint128, weight_to_check: List[uint128], ) -> bool: """ weight_to_check: List[uint128] is expected to be sorted """ if weight_to_check is None: return True if weight_to_check[-1] < start_of_epoch_weight: ...
[ "def", "_sample_sub_epoch", "(", "start_of_epoch_weight", ":", "uint128", ",", "end_of_epoch_weight", ":", "uint128", ",", "weight_to_check", ":", "List", "[", "uint128", "]", ",", ")", "->", "bool", ":", "if", "weight_to_check", "is", "None", ":", "return", "...
[ 661, 0 ]
[ 686, 17 ]
python
en
['en', 'error', 'th']
False
WeightProofHandler._create_proof_of_weight
(self, tip: bytes32)
Creates a weight proof object
Creates a weight proof object
async def _create_proof_of_weight(self, tip: bytes32) -> Optional[WeightProof]: """ Creates a weight proof object """ assert self.blockchain is not None sub_epoch_segments: List[SubEpochChallengeSegment] = [] tip_rec = self.blockchain.try_block_record(tip) if tip_...
[ "async", "def", "_create_proof_of_weight", "(", "self", ",", "tip", ":", "bytes32", ")", "->", "Optional", "[", "WeightProof", "]", ":", "assert", "self", ".", "blockchain", "is", "not", "None", "sub_epoch_segments", ":", "List", "[", "SubEpochChallengeSegment",...
[ 93, 4 ]
[ 152, 76 ]
python
en
['en', 'error', 'th']
False
WeightProofHandler.create_sub_epoch_segments
(self)
Creates a weight proof object
Creates a weight proof object
async def create_sub_epoch_segments(self): log.debug("check segments in db") """ Creates a weight proof object """ assert self.blockchain is not None peak_height = self.blockchain.get_peak_height() if peak_height is None: log.error("no peak yet") ...
[ "async", "def", "create_sub_epoch_segments", "(", "self", ")", ":", "log", ".", "debug", "(", "\"check segments in db\"", ")", "assert", "self", ".", "blockchain", "is", "not", "None", "peak_height", "=", "self", ".", "blockchain", ".", "get_peak_height", "(", ...
[ 224, 4 ]
[ 256, 19 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.extract_api_suffix_url
(self, url: str)
Function that extracts the URL after `/api/v1` or `/json` and also returns the query data in the URL, if there is any.
Function that extracts the URL after `/api/v1` or `/json` and also returns the query data in the URL, if there is any.
def extract_api_suffix_url(self, url: str) -> Tuple[str, Dict[str, Any]]: """ Function that extracts the URL after `/api/v1` or `/json` and also returns the query data in the URL, if there is any. """ url_split = url.split("?") data: Dict[str, Any] = {} if len(url...
[ "def", "extract_api_suffix_url", "(", "self", ",", "url", ":", "str", ")", "->", "Tuple", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "url_split", "=", "url", ".", "split", "(", "\"?\"", ")", "data", ":", "Dict", "[", "str", "...
[ 218, 4 ]
[ 229, 26 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.validate_api_response_openapi
( self, url: str, method: str, result: HttpResponse, data: Union[str, bytes, Dict[str, Any]], http_headers: Dict[str, Any], intentionally_undocumented: bool = False, )
Validates all API responses received by this test against Zulip's API documentation, declared in zerver/openapi/zulip.yaml. This powerful test lets us use Zulip's extensive test coverage of corner cases in the API to ensure that we've properly documented those corner cases.
Validates all API responses received by this test against Zulip's API documentation, declared in zerver/openapi/zulip.yaml. This powerful test lets us use Zulip's extensive test coverage of corner cases in the API to ensure that we've properly documented those corner cases.
def validate_api_response_openapi( self, url: str, method: str, result: HttpResponse, data: Union[str, bytes, Dict[str, Any]], http_headers: Dict[str, Any], intentionally_undocumented: bool = False, ) -> None: """ Validates all API responses re...
[ "def", "validate_api_response_openapi", "(", "self", ",", "url", ":", "str", ",", "method", ":", "str", ",", "result", ":", "HttpResponse", ",", "data", ":", "Union", "[", "str", ",", "bytes", ",", "Dict", "[", "str", ",", "Any", "]", "]", ",", "http...
[ 231, 4 ]
[ 273, 13 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.client_patch
( self, url: str, info: Dict[str, Any] = {}, intentionally_undocumented: bool = False, **kwargs: Any, )
We need to urlencode, since Django's function won't do it for us.
We need to urlencode, since Django's function won't do it for us.
def client_patch( self, url: str, info: Dict[str, Any] = {}, intentionally_undocumented: bool = False, **kwargs: Any, ) -> HttpResponse: """ We need to urlencode, since Django's function won't do it for us. """ encoded = urllib.parse.urlencode(...
[ "def", "client_patch", "(", "self", ",", "url", ":", "str", ",", "info", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", ",", "intentionally_undocumented", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Any", ",", ")", "->", "...
[ 276, 4 ]
[ 298, 21 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.client_patch_multipart
( self, url: str, info: Dict[str, Any] = {}, **kwargs: Any )
Use this for patch requests that have file uploads or that need some sort of multi-part content. In the future Django's test client may become a bit more flexible, so we can hopefully eliminate this. (When you post with the Django test client, it deals with MULTIPART_CONTENT ...
Use this for patch requests that have file uploads or that need some sort of multi-part content. In the future Django's test client may become a bit more flexible, so we can hopefully eliminate this. (When you post with the Django test client, it deals with MULTIPART_CONTENT ...
def client_patch_multipart( self, url: str, info: Dict[str, Any] = {}, **kwargs: Any ) -> HttpResponse: """ Use this for patch requests that have file uploads or that need some sort of multi-part content. In the future Django's test client may become a bit more flexible, ...
[ "def", "client_patch_multipart", "(", "self", ",", "url", ":", "str", ",", "info", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "HttpResponse", ":", "encoded", "=", "encode_multipart", "(", ...
[ 301, 4 ]
[ 317, 21 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.client_post_request
(self, url: str, req: Any)
We simulate hitting an endpoint here, although we actually resolve the URL manually and hit the view directly. We have this helper method to allow our instrumentation to work for /notify_tornado and future similar methods that require doing funny things to a request obj...
We simulate hitting an endpoint here, although we actually resolve the URL manually and hit the view directly. We have this helper method to allow our instrumentation to work for /notify_tornado and future similar methods that require doing funny things to a request obj...
def client_post_request(self, url: str, req: Any) -> HttpResponse: """ We simulate hitting an endpoint here, although we actually resolve the URL manually and hit the view directly. We have this helper method to allow our instrumentation to work for /notify_tornado and f...
[ "def", "client_post_request", "(", "self", ",", "url", ":", "str", ",", "req", ":", "Any", ")", "->", "HttpResponse", ":", "match", "=", "resolve", "(", "url", ")", "return", "match", ".", "func", "(", "req", ")" ]
[ 366, 4 ]
[ 377, 30 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase._get_page_params
(self, result: HttpResponse)
Helper for parsing page_params after fetching the web app's home view.
Helper for parsing page_params after fetching the web app's home view.
def _get_page_params(self, result: HttpResponse) -> Dict[str, Any]: """Helper for parsing page_params after fetching the web app's home view.""" doc = lxml.html.document_fromstring(result.content) [div] = doc.xpath("//div[@id='page-params']") page_params_json = div.get("data-params") ...
[ "def", "_get_page_params", "(", "self", ",", "result", ":", "HttpResponse", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "doc", "=", "lxml", ".", "html", ".", "document_fromstring", "(", "result", ".", "content", ")", "[", "div", "]", "=", "d...
[ 499, 4 ]
[ 505, 26 ]
python
en
['en', 'en', 'en']
True
ZulipTestCase.check_rendered_logged_in_app
(self, result: HttpResponse)
Verifies that a visit of / was a 200 that rendered page_params and not for a (logged-out) spectator.
Verifies that a visit of / was a 200 that rendered page_params and not for a (logged-out) spectator.
def check_rendered_logged_in_app(self, result: HttpResponse) -> None: """Verifies that a visit of / was a 200 that rendered page_params and not for a (logged-out) spectator.""" self.assertEqual(result.status_code, 200) page_params = self._get_page_params(result) # It is important...
[ "def", "check_rendered_logged_in_app", "(", "self", ",", "result", ":", "HttpResponse", ")", "->", "None", ":", "self", ".", "assertEqual", "(", "result", ".", "status_code", ",", "200", ")", "page_params", "=", "self", ".", "_get_page_params", "(", "result", ...
[ 507, 4 ]
[ 515, 60 ]
python
en
['en', 'en', 'en']
True
ZulipTestCase.check_rendered_spectator
(self, result: HttpResponse)
Verifies that a visit of / was a 200 that rendered page_params for a (logged-out) spectator.
Verifies that a visit of / was a 200 that rendered page_params for a (logged-out) spectator.
def check_rendered_spectator(self, result: HttpResponse) -> None: """Verifies that a visit of / was a 200 that rendered page_params for a (logged-out) spectator.""" self.assertEqual(result.status_code, 200) page_params = self._get_page_params(result) # It is important to check `i...
[ "def", "check_rendered_spectator", "(", "self", ",", "result", ":", "HttpResponse", ")", "->", "None", ":", "self", ".", "assertEqual", "(", "result", ".", "status_code", ",", "200", ")", "page_params", "=", "self", ".", "_get_page_params", "(", "result", ")...
[ 517, 4 ]
[ 524, 59 ]
python
en
['en', 'en', 'en']
True
ZulipTestCase.login
(self, name: str)
Use this for really simple tests where you just need to be logged in as some user, but don't need the actual user object for anything else. Try to use 'hamlet' for non-admins and 'iago' for admins: self.login('hamlet') Try to use 'cordelia' or 'othello' as "other"...
Use this for really simple tests where you just need to be logged in as some user, but don't need the actual user object for anything else. Try to use 'hamlet' for non-admins and 'iago' for admins:
def login(self, name: str) -> None: """ Use this for really simple tests where you just need to be logged in as some user, but don't need the actual user object for anything else. Try to use 'hamlet' for non-admins and 'iago' for admins: self.login('hamlet') ...
[ "def", "login", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "assert", "\"@\"", "not", "in", "name", ",", "\"use login_by_email for email logins\"", "user", "=", "self", ".", "example_user", "(", "name", ")", "self", ".", "login_user", "("...
[ 537, 4 ]
[ 550, 29 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.login_2fa
(self, user_profile: UserProfile)
We need this function to call request.session.save(). do_two_factor_login doesn't save session; in normal request-response cycle this doesn't matter because middleware will save the session when it finds it dirty; however,in tests we will have to do that explicitly.
We need this function to call request.session.save(). do_two_factor_login doesn't save session; in normal request-response cycle this doesn't matter because middleware will save the session when it finds it dirty; however,in tests we will have to do that explicitly.
def login_2fa(self, user_profile: UserProfile) -> None: """ We need this function to call request.session.save(). do_two_factor_login doesn't save session; in normal request-response cycle this doesn't matter because middleware will save the session when it finds it dirty; howeve...
[ "def", "login_2fa", "(", "self", ",", "user_profile", ":", "UserProfile", ")", "->", "None", ":", "request", "=", "HttpRequest", "(", ")", "request", ".", "session", "=", "self", ".", "client", ".", "session", "request", ".", "user", "=", "user_profile", ...
[ 585, 4 ]
[ 597, 30 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.submit_reg_form_for_user
( self, email: str, password: str, realm_name: str = "Zulip Test", realm_subdomain: str = "zuliptest", from_confirmation: str = "", full_name: Optional[str] = None, timezone: str = "", realm_in_root_domain: Optional[str] = None, default_str...
Stage two of the two-step registration process. If things are working correctly the account should be fully registered after this call. You can pass the HTTP_HOST variable for subdomains via kwargs.
Stage two of the two-step registration process.
def submit_reg_form_for_user( self, email: str, password: str, realm_name: str = "Zulip Test", realm_subdomain: str = "zuliptest", from_confirmation: str = "", full_name: Optional[str] = None, timezone: str = "", realm_in_root_domain: Optional[str]...
[ "def", "submit_reg_form_for_user", "(", "self", ",", "email", ":", "str", ",", "password", ":", "str", ",", "realm_name", ":", "str", "=", "\"Zulip Test\"", ",", "realm_subdomain", ":", "str", "=", "\"zuliptest\"", ",", "from_confirmation", ":", "str", "=", ...
[ 606, 4 ]
[ 645, 73 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.encode_uuid
(self, uuid: str)
identifier: Can be an email or a remote server uuid.
identifier: Can be an email or a remote server uuid.
def encode_uuid(self, uuid: str) -> str: """ identifier: Can be an email or a remote server uuid. """ if uuid in self.API_KEYS: api_key = self.API_KEYS[uuid] else: api_key = get_remote_server_by_uuid(uuid).api_key self.API_KEYS[uuid] = api_key ...
[ "def", "encode_uuid", "(", "self", ",", "uuid", ":", "str", ")", "->", "str", ":", "if", "uuid", "in", "self", ".", "API_KEYS", ":", "api_key", "=", "self", ".", "API_KEYS", "[", "uuid", "]", "else", ":", "api_key", "=", "get_remote_server_by_uuid", "(...
[ 678, 4 ]
[ 688, 53 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.encode_credentials
(self, identifier: str, api_key: str)
identifier: Can be an email or a remote server uuid.
identifier: Can be an email or a remote server uuid.
def encode_credentials(self, identifier: str, api_key: str) -> str: """ identifier: Can be an email or a remote server uuid. """ credentials = f"{identifier}:{api_key}" return "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
[ "def", "encode_credentials", "(", "self", ",", "identifier", ":", "str", ",", "api_key", ":", "str", ")", "->", "str", ":", "credentials", "=", "f\"{identifier}:{api_key}\"", "return", "\"Basic \"", "+", "base64", ".", "b64encode", "(", "credentials", ".", "en...
[ 703, 4 ]
[ 708, 87 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.get_streams
(self, user_profile: UserProfile)
Helper function to get the stream names for a user
Helper function to get the stream names for a user
def get_streams(self, user_profile: UserProfile) -> List[str]: """ Helper function to get the stream names for a user """ subs = get_stream_subscriptions_for_user(user_profile).filter( active=True, ) return [check_string("recipient", get_display_recipient(sub....
[ "def", "get_streams", "(", "self", ",", "user_profile", ":", "UserProfile", ")", "->", "List", "[", "str", "]", ":", "subs", "=", "get_stream_subscriptions_for_user", "(", "user_profile", ")", ".", "filter", "(", "active", "=", "True", ",", ")", "return", ...
[ 738, 4 ]
[ 745, 96 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.assert_json_success
(self, result: HttpResponse)
Successful POSTs return a 200 and JSON of the form {"result": "success", "msg": ""}.
Successful POSTs return a 200 and JSON of the form {"result": "success", "msg": ""}.
def assert_json_success(self, result: HttpResponse) -> Dict[str, Any]: """ Successful POSTs return a 200 and JSON of the form {"result": "success", "msg": ""}. """ try: json = orjson.loads(result.content) except orjson.JSONDecodeError: # nocoverage ...
[ "def", "assert_json_success", "(", "self", ",", "result", ":", "HttpResponse", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "json", "=", "orjson", ".", "loads", "(", "result", ".", "content", ")", "except", "orjson", ".", "JSONDecod...
[ 846, 4 ]
[ 861, 19 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.assert_json_error
(self, result: HttpResponse, msg: str, status_code: int = 400)
Invalid POSTs return an error status code and JSON of the form {"result": "error", "msg": "reason"}.
Invalid POSTs return an error status code and JSON of the form {"result": "error", "msg": "reason"}.
def assert_json_error(self, result: HttpResponse, msg: str, status_code: int = 400) -> None: """ Invalid POSTs return an error status code and JSON of the form {"result": "error", "msg": "reason"}. """ self.assertEqual(self.get_json_error(result, status_code=status_code), msg)
[ "def", "assert_json_error", "(", "self", ",", "result", ":", "HttpResponse", ",", "msg", ":", "str", ",", "status_code", ":", "int", "=", "400", ")", "->", "None", ":", "self", ".", "assertEqual", "(", "self", ".", "get_json_error", "(", "result", ",", ...
[ 872, 4 ]
[ 877, 83 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.assert_logged_in_user_id
(self, user_id: Optional[int])
Verifies the user currently logged in for the test client has the provided user_id. Pass None to verify no user is logged in.
Verifies the user currently logged in for the test client has the provided user_id. Pass None to verify no user is logged in.
def assert_logged_in_user_id(self, user_id: Optional[int]) -> None: """ Verifies the user currently logged in for the test client has the provided user_id. Pass None to verify no user is logged in. """ self.assertEqual(get_session_dict_user(self.client.session), user_id)
[ "def", "assert_logged_in_user_id", "(", "self", ",", "user_id", ":", "Optional", "[", "int", "]", ")", "->", "None", ":", "self", ".", "assertEqual", "(", "get_session_dict_user", "(", "self", ".", "client", ".", "session", ")", ",", "user_id", ")" ]
[ 908, 4 ]
[ 913, 77 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.send_webhook_payload
( self, user_profile: UserProfile, url: str, payload: Union[str, Dict[str, Any]], **post_params: Any, )
Send a webhook payload to the server, and verify that the post is successful. This is a pretty low-level function. For most use cases see the helpers that call this function, which do additional checks. Occasionally tests will call this directly, for unique si...
Send a webhook payload to the server, and verify that the post is successful.
def send_webhook_payload( self, user_profile: UserProfile, url: str, payload: Union[str, Dict[str, Any]], **post_params: Any, ) -> Message: """ Send a webhook payload to the server, and verify that the post is successful. This is a pretty low-...
[ "def", "send_webhook_payload", "(", "self", ",", "user_profile", ":", "UserProfile", ",", "url", ":", "str", ",", "payload", ":", "Union", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ",", "*", "*", "post_params", ":", "Any", ",", ")", ...
[ 1028, 4 ]
[ 1078, 18 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.simulated_markdown_failure
(self)
This raises a failure inside of the try/except block of markdown.__init__.do_convert.
This raises a failure inside of the try/except block of markdown.__init__.do_convert.
def simulated_markdown_failure(self) -> Iterator[None]: """ This raises a failure inside of the try/except block of markdown.__init__.do_convert. """ with self.settings(ERROR_BOT=None), mock.patch( "zerver.lib.markdown.timeout", side_effect=subprocess.CalledProcessErr...
[ "def", "simulated_markdown_failure", "(", "self", ")", "->", "Iterator", "[", "None", "]", ":", "with", "self", ".", "settings", "(", "ERROR_BOT", "=", "None", ")", ",", "mock", ".", "patch", "(", "\"zerver.lib.markdown.timeout\"", ",", "side_effect", "=", "...
[ 1087, 4 ]
[ 1095, 17 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.init_default_ldap_database
(self)
Takes care of the mock_ldap setup, loads a directory from zerver/tests/fixtures/ldap/directory.json with various entries to be used by tests. If a test wants to specify its own directory, it can just replace self.mock_ldap.directory with its own content, but in most cases it sho...
Takes care of the mock_ldap setup, loads a directory from zerver/tests/fixtures/ldap/directory.json with various entries to be used by tests. If a test wants to specify its own directory, it can just replace self.mock_ldap.directory with its own content, but in most cases it sho...
def init_default_ldap_database(self) -> None: """ Takes care of the mock_ldap setup, loads a directory from zerver/tests/fixtures/ldap/directory.json with various entries to be used by tests. If a test wants to specify its own directory, it can just replace self.mock_ldap...
[ "def", "init_default_ldap_database", "(", "self", ")", "->", "None", ":", "directory", "=", "orjson", ".", "loads", "(", "self", ".", "fixture_data", "(", "\"directory.json\"", ",", "type", "=", "\"ldap\"", ")", ")", "for", "dn", ",", "attrs", "in", "direc...
[ 1128, 4 ]
[ 1158, 58 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.change_ldap_user_attr
( self, username: str, attr_name: str, attr_value: Union[str, bytes], binary: bool = False )
Method for changing the value of an attribute of a user entry in the mock directory. Use option binary=True if you want binary data to be loaded into the attribute from a file specified at attr_value. This changes the attribute only for the specific test function that calls this method,...
Method for changing the value of an attribute of a user entry in the mock directory. Use option binary=True if you want binary data to be loaded into the attribute from a file specified at attr_value. This changes the attribute only for the specific test function that calls this method,...
def change_ldap_user_attr( self, username: str, attr_name: str, attr_value: Union[str, bytes], binary: bool = False ) -> None: """ Method for changing the value of an attribute of a user entry in the mock directory. Use option binary=True if you want binary data to be loaded ...
[ "def", "change_ldap_user_attr", "(", "self", ",", "username", ":", "str", ",", "attr_name", ":", "str", ",", "attr_value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "binary", ":", "bool", "=", "False", ")", "->", "None", ":", "dn", "=", "f\"u...
[ 1160, 4 ]
[ 1178, 56 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.remove_ldap_user_attr
(self, username: str, attr_name: str)
Method for removing the value of an attribute of a user entry in the mock directory. This changes the attribute only for the specific test function that calls this method, and is isolated from other tests.
Method for removing the value of an attribute of a user entry in the mock directory. This changes the attribute only for the specific test function that calls this method, and is isolated from other tests.
def remove_ldap_user_attr(self, username: str, attr_name: str) -> None: """ Method for removing the value of an attribute of a user entry in the mock directory. This changes the attribute only for the specific test function that calls this method, and is isolated from other tests. ...
[ "def", "remove_ldap_user_attr", "(", "self", ",", "username", ":", "str", ",", "attr_name", ":", "str", ")", "->", "None", ":", "dn", "=", "f\"uid={username},ou=users,dc=zulip,dc=com\"", "self", ".", "mock_ldap", ".", "directory", "[", "dn", "]", ".", "pop", ...
[ 1180, 4 ]
[ 1187, 57 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.ldap_username
(self, username: str)
Maps Zulip username to the name of the corresponding LDAP user in our test directory at zerver/tests/fixtures/ldap/directory.json, if the LDAP user exists.
Maps Zulip username to the name of the corresponding LDAP user in our test directory at zerver/tests/fixtures/ldap/directory.json, if the LDAP user exists.
def ldap_username(self, username: str) -> str: """ Maps Zulip username to the name of the corresponding LDAP user in our test directory at zerver/tests/fixtures/ldap/directory.json, if the LDAP user exists. """ return self.example_user_ldap_username_map[username]
[ "def", "ldap_username", "(", "self", ",", "username", ":", "str", ")", "->", "str", ":", "return", "self", ".", "example_user_ldap_username_map", "[", "username", "]" ]
[ 1189, 4 ]
[ 1195, 60 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.email_display_from
(self, email_message: EmailMessage)
Returns the email address that will show in email clients as the "From" field.
Returns the email address that will show in email clients as the "From" field.
def email_display_from(self, email_message: EmailMessage) -> str: """ Returns the email address that will show in email clients as the "From" field. """ # The extra_headers field may contain a "From" which is used # for display in email clients, and appears in the RFC822 ...
[ "def", "email_display_from", "(", "self", ",", "email_message", ":", "EmailMessage", ")", "->", "str", ":", "# The extra_headers field may contain a \"From\" which is used", "# for display in email clients, and appears in the RFC822", "# header as `From`. The `.from_email` accessor is t...
[ 1200, 4 ]
[ 1210, 80 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.email_envelope_from
(self, email_message: EmailMessage)
Returns the email address that will be used if the email bounces.
Returns the email address that will be used if the email bounces.
def email_envelope_from(self, email_message: EmailMessage) -> str: """ Returns the email address that will be used if the email bounces. """ # See email_display_from, above. return email_message.from_email
[ "def", "email_envelope_from", "(", "self", ",", "email_message", ":", "EmailMessage", ")", "->", "str", ":", "# See email_display_from, above.", "return", "email_message", ".", "from_email" ]
[ 1212, 4 ]
[ 1217, 39 ]
python
en
['en', 'error', 'th']
False
ZulipTestCase.get_maybe_enqueue_notifications_parameters
(self, **kwargs: Any)
Returns a dictionary with the passed parameters, after filling up the missing data with default values, for testing what was passed to the `maybe_enqueue_notifications` method.
Returns a dictionary with the passed parameters, after filling up the missing data with default values, for testing what was passed to the `maybe_enqueue_notifications` method.
def get_maybe_enqueue_notifications_parameters(self, **kwargs: Any) -> Dict[str, Any]: """ Returns a dictionary with the passed parameters, after filling up the missing data with default values, for testing what was passed to the `maybe_enqueue_notifications` method. """ ...
[ "def", "get_maybe_enqueue_notifications_parameters", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "parameters", ":", "Dict", "[", "str", ",", "Any", "]", "=", "dict", "(", "private_message", "=", ...
[ 1324, 4 ]
[ 1343, 39 ]
python
en
['en', 'error', 'th']
False
WebhookTestCase.check_webhook
( self, fixture_name: str, expected_topic: str, expected_message: str, content_type: Optional[str] = "application/json", **kwargs: Any, )
check_webhook is the main way to test "normal" webhooks that work by receiving a payload from a third party and then writing some message to a Zulip stream. We use `fixture_name` to find the payload data in of our test fixtures. Then we verify that a message gets sent to a str...
check_webhook is the main way to test "normal" webhooks that work by receiving a payload from a third party and then writing some message to a Zulip stream.
def check_webhook( self, fixture_name: str, expected_topic: str, expected_message: str, content_type: Optional[str] = "application/json", **kwargs: Any, ) -> None: """ check_webhook is the main way to test "normal" webhooks that work by receivi...
[ "def", "check_webhook", "(", "self", ",", "fixture_name", ":", "str", ",", "expected_topic", ":", "str", ",", "expected_message", ":", "str", ",", "content_type", ":", "Optional", "[", "str", "]", "=", "\"application/json\"", ",", "*", "*", "kwargs", ":", ...
[ 1372, 4 ]
[ 1421, 9 ]
python
en
['en', 'error', 'th']
False
WebhookTestCase.send_and_test_private_message
( self, fixture_name: str, expected_message: str, content_type: str = "application/json", **kwargs: Any, )
For the rare cases that you are testing a webhook that sends private messages, use this function. Most webhooks send to streams, and you will want to look at check_webhook.
For the rare cases that you are testing a webhook that sends private messages, use this function.
def send_and_test_private_message( self, fixture_name: str, expected_message: str, content_type: str = "application/json", **kwargs: Any, ) -> Message: """ For the rare cases that you are testing a webhook that sends private messages, use this function...
[ "def", "send_and_test_private_message", "(", "self", ",", "fixture_name", ":", "str", ",", "expected_message", ":", "str", ",", "content_type", ":", "str", "=", "\"application/json\"", ",", "*", "*", "kwargs", ":", "Any", ",", ")", "->", "Message", ":", "pay...
[ 1434, 4 ]
[ 1466, 18 ]
python
en
['en', 'error', 'th']
False
WebhookTestCase.get_payload
(self, fixture_name: str)
Generally webhooks that override this should return dicts.
Generally webhooks that override this should return dicts.
def get_payload(self, fixture_name: str) -> Union[str, Dict[str, str]]: """ Generally webhooks that override this should return dicts.""" return self.get_body(fixture_name)
[ "def", "get_payload", "(", "self", ",", "fixture_name", ":", "str", ")", "->", "Union", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "return", "self", ".", "get_body", "(", "fixture_name", ")" ]
[ 1490, 4 ]
[ 1493, 42 ]
python
en
['en', 'error', 'th']
False
simple_cycle_1
(node_generator)
r''' 0 /\ / \ . . 1---.2 . | | | -----| . 3
r''' 0 /\ / \ . . 1---.2 . | | | -----| . 3
def simple_cycle_1(node_generator): g = SimpleDAG() nodes = [node_generator() for i in range(4)] for n in nodes: g.add_node(n) r''' 0 /\ / \ . . 1---.2 . | | | -----| . 3 ''' ...
[ "def", "simple_cycle_1", "(", "node_generator", ")", ":", "g", "=", "SimpleDAG", "(", ")", "nodes", "=", "[", "node_generator", "(", ")", "for", "i", "in", "range", "(", "4", ")", "]", "for", "n", "in", "nodes", ":", "g", ".", "add_node", "(", "n",...
[ 14, 0 ]
[ 37, 21 ]
python
cy
['en', 'cy', 'hi']
False
TestDataSet.test_create
(self)
Create a new dataset, and retrieve it
Create a new dataset, and retrieve it
def test_create(self): """Create a new dataset, and retrieve it""" dataset1 = DataSet(data={'description': 'dataset 1'}) # The name for the following dataset will be ignored, and set # to the name of the dataset with dsid = dsid dataset2 = DataSet(id=dataset1.id) # update...
[ "def", "test_create", "(", "self", ")", ":", "dataset1", "=", "DataSet", "(", "data", "=", "{", "'description'", ":", "'dataset 1'", "}", ")", "# The name for the following dataset will be ignored, and set", "# to the name of the dataset with dsid = dsid", "dataset2", "=", ...
[ 26, 4 ]
[ 41, 50 ]
python
en
['en', 'en', 'en']
True
TestDataSet.test_update
(self)
Update all or individual dataset columns
Update all or individual dataset columns
def test_update(self): """Update all or individual dataset columns""" dataset1 = DataSet(data={'description': 'dataset 1'}, ) self.assertEqual(dataset1.description, "dataset 1") dataset1.update(rerun=5, description="new dataset") self.database.cursor.execute( "SELECT ...
[ "def", "test_update", "(", "self", ")", ":", "dataset1", "=", "DataSet", "(", "data", "=", "{", "'description'", ":", "'dataset 1'", "}", ",", ")", "self", ".", "assertEqual", "(", "dataset1", ".", "description", ",", "\"dataset 1\"", ")", "dataset1", ".",...
[ 44, 4 ]
[ 59, 9 ]
python
en
['en', 'en', 'en']
True
TestImage.test_update
(self)
Check that ORM-updates work for the Image class.
Check that ORM-updates work for the Image class.
def test_update(self): """ Check that ORM-updates work for the Image class. """ dataset1 = DataSet(data={'description': 'dataset with changing images'}, database=self.database) image_data = db_subs.example_dbima...
[ "def", "test_update", "(", "self", ")", ":", "dataset1", "=", "DataSet", "(", "data", "=", "{", "'description'", ":", "'dataset with changing images'", "}", ",", "database", "=", "self", ".", "database", ")", "image_data", "=", "db_subs", ".", "example_dbimage...
[ 120, 4 ]
[ 176, 52 ]
python
en
['en', 'error', 'th']
False
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get("generator_flags", {}) if generator_flags.get("adjust_static_libraries", False): global generator_wants_static_library_dependencies_adjusted ...
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "\"generator_flags\"", ",", "{", "}", ")", "if", "generator_flags", ".", "get", "(", "\"adjust_static_libraries\"", ",", "False", ")", ":", "global"...
[ 70, 0 ]
[ 76, 67 ]
python
en
['en', 'en', 'en']
True
GetAllIncludeDirectories
( target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path, )
Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options.
Calculate the set of include directories to be used.
def GetAllIncludeDirectories( target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path, ): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include dire...
[ "def", "GetAllIncludeDirectories", "(", "target_list", ",", "target_dicts", ",", "shared_intermediate_dirs", ",", "config_name", ",", "params", ",", "compiler_path", ",", ")", ":", "gyp_includes_set", "=", "set", "(", ")", "compiler_includes_list", "=", "[", "]", ...
[ 79, 0 ]
[ 177, 28 ]
python
en
['en', 'en', 'en']
True
GetCompilerPath
(target_list, data, options)
Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable.
Determine a command that can be used to invoke the compiler.
def GetCompilerPath(target_list, data, options): """Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variab...
[ "def", "GetCompilerPath", "(", "target_list", ",", "data", ",", "options", ")", ":", "# First, see if the compiler is configured in make's settings.", "build_file", ",", "_", ",", "_", "=", "gyp", ".", "common", ".", "ParseQualifiedTarget", "(", "target_list", "[", ...
[ 180, 0 ]
[ 201, 16 ]
python
en
['en', 'en', 'en']
True
GetAllDefines
(target_list, target_dicts, data, config_name, params, compiler_path)
Calculate the defines for a project. Returns: A dict that includes explicit defines declared in gyp files along with all of the default defines that the compiler uses.
Calculate the defines for a project.
def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explicit defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared in the gyp f...
[ "def", "GetAllDefines", "(", "target_list", ",", "target_dicts", ",", "data", ",", "config_name", ",", "params", ",", "compiler_path", ")", ":", "# Get defines declared in the gyp files.", "all_defines", "=", "{", "}", "flavor", "=", "gyp", ".", "common", ".", "...
[ 204, 0 ]
[ 262, 22 ]
python
en
['en', 'en', 'en']
True
WriteIncludePaths
(out, eclipse_langs, include_dirs)
Write the includes section of a CDT settings export file.
Write the includes section of a CDT settings export file.
def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write( ' <section name="org.eclipse.cdt.internal.ui.wizards.' 'settingswizards.IncludePaths">\n' ) out.write(' <language name="holder for library settings"></...
[ "def", "WriteIncludePaths", "(", "out", ",", "eclipse_langs", ",", "include_dirs", ")", ":", "out", ".", "write", "(", "' <section name=\"org.eclipse.cdt.internal.ui.wizards.'", "'settingswizards.IncludePaths\">\\n'", ")", "out", ".", "write", "(", "' <language name=\"h...
[ 265, 0 ]
[ 281, 31 ]
python
en
['en', 'en', 'en']
True
WriteMacros
(out, eclipse_langs, defines)
Write the macros section of a CDT settings export file.
Write the macros section of a CDT settings export file.
def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write( ' <section name="org.eclipse.cdt.internal.ui.wizards.' 'settingswizards.Macros">\n' ) out.write(' <language name="holder for library settings"></language>\n') f...
[ "def", "WriteMacros", "(", "out", ",", "eclipse_langs", ",", "defines", ")", ":", "out", ".", "write", "(", "' <section name=\"org.eclipse.cdt.internal.ui.wizards.'", "'settingswizards.Macros\">\\n'", ")", "out", ".", "write", "(", "' <language name=\"holder for library...
[ 284, 0 ]
[ 300, 31 ]
python
en
['en', 'en', 'en']
True
GenerateClasspathFile
( target_list, target_dicts, toplevel_dir, toplevel_build, out_name )
Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.
Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.
def GenerateClasspathFile( target_list, target_dicts, toplevel_dir, toplevel_build, out_name ): """Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.""" gyp.common.EnsureDirEx...
[ "def", "GenerateClasspathFile", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ",", "toplevel_build", ",", "out_name", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "out_name", ")", "result", "=", "ET", ".", "Element", "(", "\"cla...
[ 379, 0 ]
[ 411, 42 ]
python
en
['en', 'en', 'en']
True
GetJavaJars
(target_list, target_dicts, toplevel_dir)
Generates a sequence of all .jars used as inputs.
Generates a sequence of all .jars used as inputs.
def GetJavaJars(target_list, target_dicts, toplevel_dir): """Generates a sequence of all .jars used as inputs.""" for target_name in target_list: target = target_dicts[target_name] for action in target.get("actions", []): for input_ in action["inputs"]: if os.path.spl...
[ "def", "GetJavaJars", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ":", "for", "target_name", "in", "target_list", ":", "target", "=", "target_dicts", "[", "target_name", "]", "for", "action", "in", "target", ".", "get", "(", "\"actions\"...
[ 414, 0 ]
[ 424, 80 ]
python
en
['en', 'en', 'en']
True
GetJavaSourceDirs
(target_list, target_dicts, toplevel_dir)
Generates a sequence of all likely java package root directories.
Generates a sequence of all likely java package root directories.
def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): """Generates a sequence of all likely java package root directories.""" for target_name in target_list: target = target_dicts[target_name] for action in target.get("actions", []): for input_ in action["inputs"]: ...
[ "def", "GetJavaSourceDirs", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ":", "for", "target_name", "in", "target_list", ":", "target", "=", "target_dicts", "[", "target_name", "]", "for", "action", "in", "target", ".", "get", "(", "\"act...
[ 427, 0 ]
[ 452, 43 ]
python
en
['en', 'en', 'en']
True
GenerateOutput
(target_list, target_dicts, data, params)
Generate an XML settings file that can be imported into a CDT project.
Generate an XML settings file that can be imported into a CDT project.
def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params["options"].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get("generator_flags", {...
[ "def", "GenerateOutput", "(", "target_list", ",", "target_dicts", ",", "data", ",", "params", ")", ":", "if", "params", "[", "\"options\"", "]", ".", "generator_output", ":", "raise", "NotImplementedError", "(", "\"--generator_output not implemented for eclipse\"", ")...
[ 455, 0 ]
[ 469, 13 ]
python
en
['en', 'en', 'en']
True
XViewMiddleware.process_view
(self, request, view_func, view_args, view_kwargs)
If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, quickly return with an x-header indicating the view function. This is used by the documentation module to lookup the view function for an arbitrary page.
If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, quickly return with an x-header indicating the view function. This is used by the documentation module to lookup the view function for an arbitrary page.
def process_view(self, request, view_func, view_args, view_kwargs): """ If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, quickly return with an x-header indicating the view function. This is used by the documentation module to ...
[ "def", "process_view", "(", "self", ",", "request", ",", "view_func", ",", "view_args", ",", "view_kwargs", ")", ":", "assert", "hasattr", "(", "request", ",", "'user'", ")", ",", "(", "\"The XView middleware requires authentication middleware to be \"", "\"installed....
[ 9, 4 ]
[ 27, 27 ]
python
en
['en', 'error', 'th']
False
delete_test_database
(database)
Use with caution! NB. Not the same as a freshly initialised database. All the sequence counters are offset.
Use with caution!
def delete_test_database(database): """ Use with caution! NB. Not the same as a freshly initialised database. All the sequence counters are offset. """ if database.database.lower().find("test") != 0: raise ValueError("You tried to delete a database not prefixed with 'test'.\n" ...
[ "def", "delete_test_database", "(", "database", ")", ":", "if", "database", ".", "database", ".", "lower", "(", ")", ".", "find", "(", "\"test\"", ")", "!=", "0", ":", "raise", "ValueError", "(", "\"You tried to delete a database not prefixed with 'test'.\\n\"", "...
[ 29, 0 ]
[ 65, 13 ]
python
en
['en', 'error', 'th']
False
example_dbimage_data_dict
(**kwargs)
Defines the canonical default image-data for unit-testing the database. By defining this in one place we make it simple to make changes. A subset of the default values may be overridden by passing the keys as keyword-args. Note that while RA, Dec and extraction radius are arbitrary, they shou...
Defines the canonical default image-data for unit-testing the database.
def example_dbimage_data_dict(**kwargs): """ Defines the canonical default image-data for unit-testing the database. By defining this in one place we make it simple to make changes. A subset of the default values may be overridden by passing the keys as keyword-args. Note that while RA, Dec an...
[ "def", "example_dbimage_data_dict", "(", "*", "*", "kwargs", ")", ":", "starttime", "=", "datetime", ".", "datetime", "(", "2012", ",", "1", ",", "1", ")", "# Happy new year", "init_im_params", "=", "{", "'tau_time'", ":", "300", ",", "'freq_eff'", ":", "1...
[ 68, 0 ]
[ 106, 25 ]
python
en
['en', 'error', 'th']
False
generate_timespaced_dbimages_data
(n_images, timedelta_between_images=datetime.timedelta(days=1), **kwargs)
Generate a list of image data dictionaries. The image-data dicts are identical except for having the taustart_ts advanced by a fixed timedelta for each entry. These can be used to create known entries in the image table, for unit-testing. A subset of the image-data defaults may be overridden...
Generate a list of image data dictionaries.
def generate_timespaced_dbimages_data(n_images, timedelta_between_images=datetime.timedelta(days=1), **kwargs): """ Generate a list of image data dictionaries. The image-data dicts are identical except for having the taustart_ts advanced by a fixed ...
[ "def", "generate_timespaced_dbimages_data", "(", "n_images", ",", "timedelta_between_images", "=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", ",", "*", "*", "kwargs", ")", ":", "init_im_params", "=", "example_dbimage_data_dict", "(", "*", "*", "kw...
[ 109, 0 ]
[ 130, 20 ]
python
en
['en', 'error', 'th']
False
example_extractedsource_tuple
(ra=123.123, dec=10.5, # Arbitrarily picked defaults ra_fit_err=5. / 3600, dec_fit_err=6. / 3600, peak=15e-3, peak_err=5e-4, flux=15e-3, flux_err=5e-4, sigma=15., ...
Generates an example 'fake extraction' for unit testing. Note that while RA and Dec are arbitrary, they should (usually) be close to the RA and Dec of any fake images used, since the association routines reject sources outside of designated extraction regions.
Generates an example 'fake extraction' for unit testing.
def example_extractedsource_tuple(ra=123.123, dec=10.5, # Arbitrarily picked defaults ra_fit_err=5. / 3600, dec_fit_err=6. / 3600, peak=15e-3, peak_err=5e-4, flux=15e-3, flux_err=5e-4, ...
[ "def", "example_extractedsource_tuple", "(", "ra", "=", "123.123", ",", "dec", "=", "10.5", ",", "# Arbitrarily picked defaults", "ra_fit_err", "=", "5.", "/", "3600", ",", "dec_fit_err", "=", "6.", "/", "3600", ",", "peak", "=", "15e-3", ",", "peak_err", "=...
[ 133, 0 ]
[ 162, 5 ]
python
en
['en', 'en', 'en']
True