desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Lists all accessible dashboards.'
@require_permission('list_dashboards') def get(self):
results = models.Dashboard.all(self.current_org, self.current_user.group_ids, self.current_user.id) return [q.to_dict() for q in results]
'Creates a new dashboard. :<json string name: Dashboard name Responds with a :ref:`dashboard <dashboard-response-label>`.'
@require_permission('create_dashboard') def post(self):
dashboard_properties = request.get_json(force=True) dashboard = models.Dashboard(name=dashboard_properties['name'], org=self.current_org, user=self.current_user, is_draft=True, layout='[]') models.db.session.add(dashboard) models.db.session.commit() return dashboard.to_dict()
'Retrieves a dashboard. :qparam string slug: Slug of dashboard to retrieve. .. _dashboard-response-label: :>json number id: Dashboard ID :>json string name: :>json string slug: :>json number user_id: ID of the dashboard creator :>json string created_at: ISO format timestamp for dashboard creation :>json string updated_at: ISO format timestamp for last dashboard modification :>json number version: Revision number of dashboard :>json boolean dashboard_filters_enabled: Whether filters are enabled or not :>json boolean is_archived: Whether this dashboard has been removed from the index or not :>json boolean is_draft: Whether this dashboard is a draft or not. :>json array layout: Array of arrays containing widget IDs, corresponding to the rows and columns the widgets are displayed in :>json array widgets: Array of arrays containing :ref:`widget <widget-response-label>` data .. _widget-response-label: Widget structure: :>json number widget.id: Widget ID :>json number widget.width: Widget size :>json object widget.options: Widget options :>json number widget.dashboard_id: ID of dashboard containing this widget :>json string widget.text: Widget contents, if this is a text-box widget :>json object widget.visualization: Widget contents, if this is a visualization widget :>json string widget.created_at: ISO format timestamp for widget creation :>json string widget.updated_at: ISO format timestamp for last widget modification'
@require_permission('list_dashboards') def get(self, dashboard_slug=None):
dashboard = get_object_or_404(models.Dashboard.get_by_slug_and_org, dashboard_slug, self.current_org) response = dashboard.to_dict(with_widgets=True, user=self.current_user) api_key = models.ApiKey.get_by_object(dashboard) if api_key: response['public_url'] = url_for('redash.public_dashboard', token=api_key.api_key, org_slug=self.current_org.slug, _external=True) response['api_key'] = api_key.api_key response['can_edit'] = can_modify(dashboard, self.current_user) return response
'Modifies a dashboard. :qparam string slug: Slug of dashboard to retrieve. Responds with the updated :ref:`dashboard <dashboard-response-label>`. :status 200: success :status 409: Version conflict -- dashboard modified since last read'
@require_permission('edit_dashboard') def post(self, dashboard_slug):
dashboard_properties = request.get_json(force=True) dashboard = models.Dashboard.get_by_id_and_org(dashboard_slug, self.current_org) require_object_modify_permission(dashboard, self.current_user) updates = project(dashboard_properties, ('name', 'layout', 'version', 'is_draft', 'dashboard_filters_enabled')) if (('version' in updates) and (updates['version'] != dashboard.version)): abort(409) updates['changed_by'] = self.current_user self.update_model(dashboard, updates) models.db.session.add(dashboard) try: models.db.session.commit() except StaleDataError: abort(409) result = dashboard.to_dict(with_widgets=True, user=self.current_user) return result
'Archives a dashboard. :qparam string slug: Slug of dashboard to retrieve. Responds with the archived :ref:`dashboard <dashboard-response-label>`.'
@require_permission('edit_dashboard') def delete(self, dashboard_slug):
dashboard = models.Dashboard.get_by_slug_and_org(dashboard_slug, self.current_org) dashboard.is_archived = True dashboard.record_changes(changed_by=self.current_user) models.db.session.add(dashboard) d = dashboard.to_dict(with_widgets=True, user=self.current_user) models.db.session.commit() return d
'Retrieve a public dashboard. :param token: An API key for a public dashboard. :>json array widgets: An array of arrays of :ref:`public widgets <public-widget-label>`, corresponding to the rows and columns the widgets are displayed in'
def get(self, token):
if (not isinstance(self.current_user, models.ApiUser)): api_key = get_object_or_404(models.ApiKey.get_by_api_key, token) dashboard = api_key.object else: dashboard = self.current_user.object return serializers.public_dashboard(dashboard)
'Allow anonymous access to a dashboard. :param dashboard_id: The numeric ID of the dashboard to share. :>json string public_url: The URL for anonymous access to the dashboard. :>json api_key: The API key to use when accessing it.'
def post(self, dashboard_id):
dashboard = models.Dashboard.get_by_id_and_org(dashboard_id, self.current_org) require_admin_or_owner(dashboard.user_id) api_key = models.ApiKey.create_for_object(dashboard, self.current_user) models.db.session.flush() models.db.session.commit() public_url = url_for('redash.public_dashboard', token=api_key.api_key, org_slug=self.current_org.slug, _external=True) self.record_event({'action': 'activate_api_key', 'object_id': dashboard.id, 'object_type': 'dashboard'}) return {'public_url': public_url, 'api_key': api_key.api_key}
'Disable anonymous access to a dashboard. :param dashboard_id: The numeric ID of the dashboard to unshare.'
def delete(self, dashboard_id):
dashboard = models.Dashboard.get_by_id_and_org(dashboard_id, self.current_org) require_admin_or_owner(dashboard.user_id) api_key = models.ApiKey.get_by_object(dashboard) if api_key: api_key.active = False models.db.session.add(api_key) models.db.session.commit() self.record_event({'action': 'deactivate_api_key', 'object_id': dashboard.id, 'object_type': 'dashboard'})
'Convert plain dictionaries to MutableDict.'
@classmethod def coerce(cls, key, value):
if (not isinstance(value, MutableDict)): if isinstance(value, dict): return MutableDict(value) return Mutable.coerce(key, value) else: return value
'Detect dictionary set events and emit change events.'
def __setitem__(self, key, value):
dict.__setitem__(self, key, value) self.changed()
'Detect dictionary del events and emit change events.'
def __delitem__(self, key):
dict.__delitem__(self, key) self.changed()
'importing all attributes at once is done like so: from another_local_module import * The import wildcard cannot be used from within classes or functions.'
def test_importing_all_module_attributes_at_once(self):
goose = Goose() hamster = Hamster() self.assertEqual(__, goose.name) self.assertEqual(__, hamster.name)
'Examine results of: from local_module_with_all_defined import *'
def test_a_module_can_limit_wildcard_imports(self):
goat = Goat() self.assertEqual(__, goat.name) lizard = _Velociraptor() self.assertEqual(__, lizard.name) try: duck = SecretDuck() except NameError as ex: self.assertMatch(__, ex[0])
'Before we can understand this type of decorator we need to consider the partial.'
def test_partial_that_wrappers_no_args(self):
max = functools.partial(self.maximum) self.assertEqual(__, max(7, 23)) self.assertEqual(__, max(10, (-10)))
'Idler'
@documenter('Does nothing') def idler(self, num):
pass
'Lesson 1 Matching Literal String'
def test_matching_literal_text(self):
string = ('Hello, my name is Felix and these koans are based ' + "on Ben's book: Regular Expressions in 10 minutes.") m = re.search(__, string) self.assertTrue((m and m.group(0) and (m.group(0) == 'Felix')), 'I want my name')
'Lesson 1 -- How many matches? The default behaviour of most regular expression engines is to return just the first match. In python you have the following options: match() --> Determine if the RE matches at the beginning of the string. search() --> Scan through a string, looking for any location where this RE matches. findall() --> Find all substrings where the RE matches, and return them as a list. finditer() --> Find all substrings where the RE matches, and return them as an iterator.'
def test_matching_literal_text_how_many(self):
string = (('Hello, my name is Felix and these koans are based ' + "on Ben's book: Regular Expressions in 10 minutes. ") + 'Repeat My name is Felix') m = re.match('Felix', string) self.assertEqual(m, __)
'Lesson 1 -- Matching Literal String non case sensitivity. Most regex implementations also support matches that are not case sensitive. In python you can use re.IGNORECASE, in Javascript you can specify the optional i flag. In Ben\'s book you can see more languages.'
def test_matching_literal_text_not_case_sensitivity(self):
string = ('Hello, my name is Felix or felix and this koan ' + "is based on Ben's book: Regular Expressions in 10 minutes.") self.assertEqual(re.findall('felix', string), __) self.assertEqual(re.findall('felix', string, re.IGNORECASE), __)
'Lesson 1: Matching any character `.` matches any character: alphabetic characters, digits, and punctuation.'
def test_matching_any_character(self):
string = ((((('pecks.xlx\n' + 'orders1.xls\n') + 'apec1.xls\n') + 'na1.xls\n') + 'na2.xls\n') + 'sa1.xls') change_this_search_string = 'a..xlx' self.assertEquals(len(re.findall(change_this_search_string, string)), 3)
'Lesson 2 -- Matching sets of characters A set of characters is defined using the metacharacters `[` and `]`. Everything between them is part of the set, and any single one of the set members will match.'
def test_matching_set_character(self):
string = (((((((('sales.xlx\n' + 'sales1.xls\n') + 'orders3.xls\n') + 'apac1.xls\n') + 'sales2.xls\n') + 'na1.xls\n') + 'na2.xls\n') + 'sa1.xls\n') + 'ca1.xls') change_this_search_string = '[nsc]a[2-9].xls' self.assertEquals(len(re.findall(change_this_search_string, string)), 3)
'Lesson 2 -- Using character set ranges Occasionally, you\'ll have a list of characters that you don\'t want to match. Character sets can be negated using the ^ metacharacter.'
def test_anything_but_matching(self):
string = ((((((((((('sales.xlx\n' + 'sales1.xls\n') + 'orders3.xls\n') + 'apac1.xls\n') + 'sales2.xls\n') + 'sales3.xls\n') + 'europe2.xls\n') + 'sam.xls\n') + 'na1.xls\n') + 'na2.xls\n') + 'sa1.xls\n') + 'ca1.xls') change_this_search_string = '[^nc]am' self.assertEquals(re.findall(change_this_search_string, string), ['sam.xls'])
'You'
def test_pass_does_nothing_at_all(self):
'shall' 'not' pass self.assertEqual(____, ('Still got to this line' != None))
'A string placed at the beginning of a function is used for documentation'
def method_with_documentation(self):
return 'ok'
'Attributes names that start with a double underscore get mangled when an instance is created.'
def test_double_underscore_attribute_prefixes_cause_name_mangling(self):
rover = self.Dog() try: password = rover.__password() except Exception as ex: self.assertEqual(__, ex.__class__.__name__) self.assertEqual(__, rover._Dog__password())
'We shall contemplate truth by testing reality, via asserts.'
def test_assert_truth(self):
self.assertTrue(False)
'Enlightenment may be more easily achieved with appropriate messages.'
def test_assert_with_message(self):
self.assertTrue(False, 'This should be True -- Please fix this')
'Sometimes we will ask you to fill in the values'
def test_fill_in_values(self):
self.assertEqual(__, (1 + 1))
'To understand reality, we must compare our expectations against reality.'
def test_assert_equality(self):
expected_value = __ actual_value = (1 + 1) self.assertTrue((expected_value == actual_value))
'Some ways of asserting equality are better than others.'
def test_a_better_way_of_asserting_equality(self):
expected_value = __ actual_value = (1 + 1) self.assertEqual(expected_value, actual_value)
'Understand what lies within.'
def test_that_unittest_asserts_work_the_same_way_as_python_asserts(self):
assert False
'What is in a class name?'
def test_that_sometimes_we_need_to_know_the_class_type(self):
self.assertEqual(__, 'navel'.__class__)
'Unlike NULL in a lot of languages'
def test_none_is_an_object(self):
self.assertEqual(__, isinstance(None, object))
'There is only one None'
def test_none_is_universal(self):
self.assertEqual(__, (None is None))
'What is the Exception that is thrown when you call a method that does not exist? Hint: launch python command console and try the code in the block below. Don\'t worry about what \'try\' and \'except\' do, we\'ll talk about this later'
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
try: None.some_method_none_does_not_know_about() except Exception as ex: self.assertEqual(__, ex.__class__) self.assertMatch(__, ex.args[0])
'None is distinct from other things which are False.'
def test_none_is_distinct(self):
self.assertEqual(____, (None is not 0)) self.assertEqual(____, (None is not False))
'True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()'
def should_wrap(self):
return (self.convert or self.strip or self.autoreset)
'Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.'
def write_and_convert(self, text):
cursor = 0 for match in self.ANSI_RE.finditer(text): (start, end) = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
'Throw an exception if the regular expresson pattern is matched'
def assertMatch(self, pattern, string, msg=None):
m = re.search(pattern, string) if ((not m) or (not m.group(0))): raise self.failureException, (msg or '{0!r} does not match {1!r}'.format(pattern, string))
'Throw an exception if the regular expresson pattern is not matched'
def assertNoMatch(self, pattern, string, msg=None):
m = re.search(pattern, string) if (m and m.group(0)): raise self.failureException, (msg or '{0!r} matches {1!r}'.format(pattern, string))
'Run the koans tests with a custom runner output.'
def walk_the_path(self, args=None):
if (args and (len(args) >= 2)): args.pop(0) test_names = [('koans.' + test_name) for test_name in args] self.tests = unittest.TestLoader().loadTestsFromNames(test_names) self.tests(self.lesson) self.lesson.learn() return self.lesson
'importing all attributes at once is done like so: from .another_local_module import * The import wildcard cannot be used from within classes or functions.'
def test_importing_all_module_attributes_at_once(self):
goose = Goose() hamster = Hamster() self.assertEqual(__, goose.name) self.assertEqual(__, hamster.name)
'Examine results of: from .local_module_with_all_defined import *'
def test_a_module_can_limit_wildcard_imports(self):
goat = Goat() self.assertEqual(__, goat.name) lizard = _Velociraptor() self.assertEqual(__, lizard.name) with self.assertRaises(___): duck = SecretDuck()
'Before we can understand this type of decorator we need to consider the partial.'
def test_partial_that_wrappers_no_args(self):
max = functools.partial(self.maximum) self.assertEqual(__, max(7, 23)) self.assertEqual(__, max(10, (-10)))
'Idler'
@documenter('Does nothing') def idler(self, num):
pass
'Lesson 1 Matching Literal String'
def test_matching_literal_text(self):
string = "Hello, my name is Felix and this koans are based on the Ben's book: Regular Expressions in 10 minutes." m = re.search(__, string) self.assertTrue((m and m.group(0) and (m.group(0) == 'Felix')), 'I want my name')
'Lesson 1 How many matches? The default behaviour of most regular expression engines is to return just the first match. In python you have the next options: match() --> Determine if the RE matches at the beginning of the string. search() --> Scan through a string, looking for any location where this RE matches. findall() --> Find all substrings where the RE matches, and returns them as a list. finditer() --> Find all substrings where the RE matches, and returns them as an iterator.'
def test_matching_literal_text_how_many(self):
string = "Hello, my name is Felix and this koans are based on the Ben's book: Regular Expressions in 10 minutes. Repeat My name is Felix" m = re.match('Felix', string) self.assertEqual(m, __)
'Lesson 1 Matching Literal String non case sensitivity. Most regex implementations also support matches that are not case sensitive. In python you can use re.IGNORECASE, in Javascript you can specify the optional i flag. In Ben\'s book you can see more languages.'
def test_matching_literal_text_not_case_sensitivity(self):
string = "Hello, my name is Felix or felix and this koans is based on the Ben's book: Regular Expressions in 10 minutes." self.assertEqual(re.findall('felix', string), __) self.assertEqual(re.findall('felix', string, re.IGNORECASE), __)
'Lesson 1 Matching any character . matches any character, alphabetic characters, digits and .'
def test_matching_any_character(self):
string = ((((('pecks.xlx\n' + 'orders1.xls\n') + 'apec1.xls\n') + 'na1.xls\n') + 'na2.xls\n') + 'sa1.xls') change_this_search_string = 'a..xlx' self.assertEquals(len(re.findall(change_this_search_string, string)), 3)
'Lesson 2 Matching sets of characters A set of characters is defined using the metacharacters [ and ]. Everything between them is part of the set and any one of the set members must match (but not all).'
def test_matching_set_character(self):
string = (((((((('sales.xlx\n' + 'sales1.xls\n') + 'orders3.xls\n') + 'apac1.xls\n') + 'sales2.xls\n') + 'na1.xls\n') + 'na2.xls\n') + 'sa1.xls\n') + 'ca1.xls') change_this_search_string = '[nsc]a[2-9].xls' self.assertEquals(len(re.findall(change_this_search_string, string)), 3)
'Lesson 2 Using character set ranges Occasionally, you\'ll want a list of characters that you don\'t want to match. Character sets can be negated using the ^ metacharacter.'
def test_anything_but_matching(self):
string = ((((((((((('sales.xlx\n' + 'sales1.xls\n') + 'orders3.xls\n') + 'apac1.xls\n') + 'sales2.xls\n') + 'sales3.xls\n') + 'europe2.xls\n') + 'sam.xls\n') + 'na1.xls\n') + 'na2.xls\n') + 'sa1.xls\n') + 'ca1.xls') change_this_search_string = '[^nc]am' self.assertEquals(re.findall(change_this_search_string, string), ['sam.xls'])
'You'
def test_pass_does_nothing_at_all(self):
'shall' 'not' pass self.assertEqual(____, ('Still got to this line' != None))
'A string placed at the beginning of a function is used for documentation'
def method_with_documentation(self):
return 'ok'
'We shall contemplate truth by testing reality, via asserts.'
def test_assert_truth(self):
self.assertTrue(False)
'Enlightenment may be more easily achieved with appropriate messages.'
def test_assert_with_message(self):
self.assertTrue(False, 'This should be True -- Please fix this')
'Sometimes we will ask you to fill in the values'
def test_fill_in_values(self):
self.assertEqual(__, (1 + 1))
'To understand reality, we must compare our expectations against reality.'
def test_assert_equality(self):
expected_value = __ actual_value = (1 + 1) self.assertTrue((expected_value == actual_value))
'Some ways of asserting equality are better than others.'
def test_a_better_way_of_asserting_equality(self):
expected_value = __ actual_value = (1 + 1) self.assertEqual(expected_value, actual_value)
'Understand what lies within.'
def test_that_unittest_asserts_work_the_same_way_as_python_asserts(self):
assert False
'What is in a class name?'
def test_that_sometimes_we_need_to_know_the_class_type(self):
self.assertEqual(__, 'navel'.__class__)
'Unlike NULL in a lot of languages'
def test_none_is_an_object(self):
self.assertEqual(__, isinstance(None, object))
'There is only one None'
def test_none_is_universal(self):
self.assertEqual(____, (None is None))
'What is the Exception that is thrown when you call a method that does not exist? Hint: launch python command console and try the code in the block below. Don\'t worry about what \'try\' and \'except\' do, we\'ll talk about this later'
def test_what_exception_do_you_get_when_calling_nonexistent_methods(self):
try: None.some_method_none_does_not_know_about() except Exception as ex: ex2 = ex self.assertEqual(__, ex2.__class__) self.assertRegex(ex2.args[0], __)
'None is distinct from other things which are False.'
def test_none_is_distinct(self):
self.assertEqual(__, (None is not 0)) self.assertEqual(__, (None is not False))
'True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()'
def should_wrap(self):
return (self.convert or self.strip or self.autoreset)
'Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.'
def write_and_convert(self, text):
cursor = 0 for match in self.ANSI_RE.finditer(text): (start, end) = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
'Run the koans tests with a custom runner output.'
def walk_the_path(self, args=None):
if (args and (len(args) >= 2)): self.tests = unittest.TestLoader().loadTestsFromName(('koans.' + args[1])) self.tests(self.lesson) self.lesson.learn() return self.lesson
'Sacrifices some of the safeguards of sqlite3 for speed Users are not likely to run this command in a production environment. They are even less likely to run it in production while using sqlite3.'
def make_database_faster(self):
if (u'sqlite3' in connection.settings_dict[u'ENGINE']): cursor = connection.cursor() cursor.execute(u'PRAGMA temp_store = MEMORY;') cursor.execute(u'PRAGMA synchronous = OFF;')
'Adds the selected product variant and quantity to the cart'
def save(self):
product_variant = self.get_variant(self.cleaned_data) return self.cart.add(variant=product_variant, quantity=self.cleaned_data[u'quantity'])
'Replaces the selected product\'s quantity in cart'
def save(self):
product_variant = self.get_variant(self.cleaned_data) return self.cart.add(product_variant, self.cleaned_data[u'quantity'], replace=True)
'Print a progress meter while iterating over an iterable. Use it as part of a ``for`` loop:: for item in self.print_iter_progress(big_long_list): self.do_expensive_computation(item) A ``.`` character is printed for every value in the iterable, a space every 10 items, and a new line every 50 items.'
def print_iter_progress(self, iterable):
for (i, value) in enumerate(iterable, start=1): (yield value) self.stdout.write(u'.', ending=u'') if ((i % 40) == 0): self.print_newline() self.stdout.write((u' ' * 35), ending=u'') elif ((i % 10) == 0): self.stdout.write(u' ', ending=u'') self.stdout.flush()
'Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded will be a list, not a queryset. Iterating over the chunks is done in a transaction so that the order and count of items in the queryset remains stable.'
@transaction.atomic def queryset_chunks(self, qs, chunk_size=1000):
i = 0 while True: items = list(qs[(i * chunk_size):][:chunk_size]) if (not items): break (yield items) i += 1
'If the indexed model uses multi table inheritance, override this method to return the instance in its most specific class so it reindexes properly.'
def get_indexed_instance(self):
return self
'This method runs either prefetch_related or select_related on the queryset to improve indexing speed of the relation. It decides which method to call based on the number of related objects: - single (eg ForeignKey, OneToOne), it runs select_related - multiple (eg ManyToMany, reverse ForeignKey) it runs prefetch_related'
def select_on_queryset(self, queryset):
try: field = self.get_field(queryset.model) except FieldDoesNotExist: return queryset if isinstance(field, RelatedField): if (field.many_to_one or field.one_to_one): queryset = queryset.select_related(self.field_name) elif (field.one_to_many or field.many_to_many): queryset = queryset.prefetch_related(self.field_name) elif isinstance(field, ForeignObjectRel): if isinstance(field, OneToOneRel): queryset = queryset.select_related(self.field_name) else: queryset = queryset.prefetch_related(self.field_name) return queryset
'Execute search'
def _do_search(self):
raise NotImplementedError
'Applies all fillters and prefetches and constructs SearchQuery and SearchResult objects.'
def search(self, query_string, model_or_queryset, fields=None, filters=None, prefetch_related=None, operator=None, order_by_relevance=True):
if isinstance(model_or_queryset, QuerySet): model = model_or_queryset.model queryset = model_or_queryset else: model = model_or_queryset queryset = model_or_queryset.objects.all() if (query_string == u''): return [] if fields: allowed_fields = {field.field_name for field in model.get_searchable_search_fields()} for field_name in fields: if (field_name not in allowed_fields): raise FieldError(((((((u'Cannot search with field "' + field_name) + u'". Please add index.SearchField(\'') + field_name) + u"') to ") + model.__name__) + u'.search_fields.')) if filters: queryset = queryset.filter(**filters) if prefetch_related: for prefetch in prefetch_related: queryset = queryset.prefetch_related(prefetch) if (operator is not None): operator = operator.lower() if (operator not in [u'or', u'and']): raise ValueError(u"operator must be either 'or' or 'and'") search_query = self.query_class(queryset, query_string, fields=fields, operator=operator, order_by_relevance=order_by_relevance) return self.results_class(self, search_query)
'Multi-model search. Parameters that affect model or database structure are skipped and not used in dashboard query implementation.'
def search(self, query_string, model_or_queryset=None, fields=None, filters=None, prefetch_related=None, operator=None, order_by_relevance=True, queryset_map=None):
search_query = self.query_class(query_string=query_string, fields=fields, operator=operator, order_by_relevance=order_by_relevance, queryset_map=queryset_map) return self.results_class(self, search_query)
'Returns the content type as a string for the model. For example: "wagtailcore.Page" "myapp.MyModel"'
def get_content_type(self):
return ((self.model._meta.app_label + u'.') + self.model.__name__)
'Returns all the content type strings that apply to this model. This includes the models\' content type and all concrete ancestor models that inherit from Indexed. For example: ["myapp.MyPageModel", "wagtailcore.Page"] ["myapp.MyModel"]'
def get_all_content_types(self):
content_types = [self.get_content_type()] ancestor = self.get_parent() while ancestor: content_types.append(ancestor.get_content_type()) ancestor = ancestor.get_parent() return content_types
'If this index object represents an alias (which appear the same in the Elasticsearch API), this method can be used to fetch the list of indices the alias points to. Use the is_alias method if you need to find out if this an alias. This returns an empty list if called on an index.'
def aliased_indices(self):
return [self.backend.index_class(self.backend, index_name) for index_name in self.es.indices.get_alias(name=self.name).keys()]
'Creates a new alias to this index. If the alias already exists it will be repointed to this index.'
def put_alias(self, name):
self.es.indices.put_alias(name=name, index=self.name)
'Restores a previously serialized checkout session. `storage_data` is the value previously returned by `Checkout.for_storage()`.'
@classmethod def from_storage(cls, storage_data, cart, user, tracking_code):
checkout = cls(cart, user, tracking_code) checkout.storage = storage_data try: version = checkout.storage[u'version'] except (TypeError, KeyError): version = None if (version != cls.VERSION): checkout.storage = {u'version': cls.VERSION} return checkout
'Serializes a checkout session to allow persistence. The session can later be restored using `Checkout.from_storage()`.'
def for_storage(self):
return self.storage
'Return tuple with Consumer Key and Consumer Secret for current service provider. Must return (key, secret), order *must* be respected.'
def get_key_and_secret(self):
authorization_key = get_authorization_key_for_backend(self.DB_NAME) if authorization_key: return authorization_key.key_and_secret()
'Creates a User with the given username, email and password'
def create_user(self, email, password=None, is_staff=False, is_active=True, username=u'', **extra_fields):
email = UserManager.normalize_email(email) user = self.model(email=email, is_active=is_active, is_staff=is_staff, **extra_fields) if password: user.set_password(password) user.save() return user
'Run command.'
def run(self):
info = {} info['platform'] = sublime.platform() info['version'] = sublime.version() info['arch'] = sublime.arch() info['bh_version'] = __version__ info['pc_install'] = is_installed_by_package_control() try: import mdpopups info['mdpopups_version'] = format_version(mdpopups, 'version', call=True) except Exception: info['mdpopups_version'] = 'Version could not be acquired!' try: import markdown info['markdown_version'] = format_version(markdown, 'version') except Exception: info['markdown_version'] = 'Version could not be acquired!' try: import jinja2 info['jinja_version'] = format_version(jinja2, '__version__') except Exception: info['jinja_version'] = 'Version could not be acquired!' try: import pygments info['pygments_version'] = format_version(pygments, '__version__') except Exception: info['pygments_version'] = 'Version could not be acquired!' msg = textwrap.dedent((' - Sublime Text: %(version)s\n - Platform: %(platform)s\n - Arch: %(arch)s\n - Theme: %(bh_version)s\n - Install via PC: %(pc_install)s\n - Dependencies:\n * mdpopups: %(mdpopups_version)s\n * markdown: %(markdown_version)s\n * pygments: %(pygments_version)s\n * jinja2: %(jinja_version)s\n ' % info)) view = sublime.active_window().active_view() def copy_and_hide(msg): sublime.set_clipboard(msg) view.hide_popup() view.show_popup((((msg.replace('\n', '<br>') + '<br><a href="') + msg) + '">Copy</a>'), on_navigate=copy_and_hide, max_height=340)
'Open the repository in a browser tab.'
def run(self):
webbrowser.open_new_tab('https://github.com/equinusocio/material-theme')
'Open the issues page in a browser tab'
def run(self):
webbrowser.open_new_tab('https://github.com/equinusocio/material-theme/issues')
'Test case for https://github.com/aio-libs/aiohttp/issues/2084'
def test_cookie_not_expired_when_added_after_removal(self):
timestamps = [533588.993, 533588.993, 533588.993, 533588.993, 533589.093, 533589.093] loop = mock.Mock() loop.time.side_effect = itertools.chain(timestamps, itertools.cycle([timestamps[(-1)]])) jar = CookieJar(unsafe=True, loop=loop) jar.update_cookies(SimpleCookie('foo=""; Max-Age=0')) jar.update_cookies(SimpleCookie('foo="bar"')) assert (len(jar) == 1)
'real_value, coded_value = value_decode(STRING) Called prior to setting a cookie\'s value from the network representation. The VALUE is the value read from HTTP header. Override this function to modify the behavior of cookies.'
def value_decode(self, val):
return (val, val)
'real_value, coded_value = value_encode(VALUE) Called prior to setting a cookie\'s value from the dictionary representation. The VALUE is the value being assigned. Override this function to modify the behavior of cookies.'
def value_encode(self, val):
strval = str(val) return (strval, strval)
'Private method for setting a cookie\'s value'
def __set(self, key, real_value, coded_value):
M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M)
'Dictionary style assignment.'
def __setitem__(self, key, value):
if isinstance(value, Morsel): dict.__setitem__(self, key, value) else: (rval, cval) = self.value_encode(value) self.__set(key, rval, cval)
'Return a string suitable for HTTP.'
def output(self, attrs=None, header='Set-Cookie:', sep='\r\n'):
result = [] items = sorted(self.items()) for (key, value) in items: result.append(value.output(attrs, header)) return sep.join(result)
'Return a string suitable for JavaScript.'
def js_output(self, attrs=None):
result = [] items = sorted(self.items()) for (key, value) in items: result.append(value.js_output(attrs)) return _nulljoin(result)
'Load cookies from a string (presumably HTTP_COOKIE) or from a dictionary. Loading cookies from a dictionary \'d\' is equivalent to calling: map(Cookie.__setitem__, d.keys(), d.values())'
def load(self, rawdata):
if isinstance(rawdata, str): self.__parse_string(rawdata) else: for (key, value) in rawdata.items(): self[key] = value return
'This internal function is important to test separately because if it doesn\'t parse a line properly, false equality can result.'
def it_parses_a_line_to_help_compare(self, parse_fixture):
(line, expected_front, expected_attrs) = parse_fixture[:3] (expected_close, expected_text) = parse_fixture[3:] (front, attrs, close, text) = XmlString._parse_line(line) assert (front == expected_front) assert (attrs == expected_attrs) assert (close == expected_close) assert (text == expected_text)
'Return a <w:tbl> element for snippet at *idx* in \'tbl-cells\' snippet file.'
def _snippet_tbl(self, idx):
return parse_xml(snippet_seq(u'tbl-cells')[idx])
'Intercept attribute access to generalize "with_{xmlattr_name}()" methods.'
def __getattr__(self, name):
if (name in self._xmlattr_method_map): def with_xmlattr(value): xmlattr_name = self._xmlattr_method_map[name] self._set_xmlattr(xmlattr_name, value) return self return with_xmlattr else: tmpl = u"'%s' object has no attribute '%s'" raise AttributeError((tmpl % (self.__class__.__name__, name)))
'Reset this builder back to initial state so it can be reused within a single test.'
def clear(self):
BaseBuilder.__init__(self) return self
'Element parsed from XML generated by builder in current state'
@property def element(self):
elm = parse_xml(self.xml()) return elm