repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
django-fluent/django-fluent-contents
fluent_contents/rendering/utils.py
get_render_language
def get_render_language(contentitem): """ Tell which language should be used to render the content item. """ plugin = contentitem.plugin if plugin.render_ignore_item_language \ or (plugin.cache_output and plugin.cache_output_per_language): # Render the template in the current language. ...
python
def get_render_language(contentitem): """ Tell which language should be used to render the content item. """ plugin = contentitem.plugin if plugin.render_ignore_item_language \ or (plugin.cache_output and plugin.cache_output_per_language): # Render the template in the current language. ...
[ "def", "get_render_language", "(", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "if", "plugin", ".", "render_ignore_item_language", "or", "(", "plugin", ".", "cache_output", "and", "plugin", ".", "cache_output_per_language", ")", ":", "# R...
Tell which language should be used to render the content item.
[ "Tell", "which", "language", "should", "be", "used", "to", "render", "the", "content", "item", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/utils.py#L74-L92
train
django-fluent/django-fluent-contents
fluent_contents/rendering/utils.py
optimize_logger_level
def optimize_logger_level(logger, log_level): """ At runtime, when logging is not active, replace the .debug() call with a no-op. """ function_name = _log_functions[log_level] if getattr(logger, function_name) is _dummy_log: return False is_level_logged = logger.isEnabledFor(log_lev...
python
def optimize_logger_level(logger, log_level): """ At runtime, when logging is not active, replace the .debug() call with a no-op. """ function_name = _log_functions[log_level] if getattr(logger, function_name) is _dummy_log: return False is_level_logged = logger.isEnabledFor(log_lev...
[ "def", "optimize_logger_level", "(", "logger", ",", "log_level", ")", ":", "function_name", "=", "_log_functions", "[", "log_level", "]", "if", "getattr", "(", "logger", ",", "function_name", ")", "is", "_dummy_log", ":", "return", "False", "is_level_logged", "=...
At runtime, when logging is not active, replace the .debug() call with a no-op.
[ "At", "runtime", "when", "logging", "is", "not", "active", "replace", "the", ".", "debug", "()", "call", "with", "a", "no", "-", "op", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/utils.py#L159-L172
train
django-fluent/django-fluent-contents
fluent_contents/utils/search.py
get_search_field_values
def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking...
python
def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking...
[ "def", "get_search_field_values", "(", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "values", "=", "[", "]", "for", "field_name", "in", "plugin", ".", "search_fields", ":", "value", "=", "getattr", "(", "contentitem", ",", "field_name"...
Extract the search fields from the model.
[ "Extract", "the", "search", "fields", "from", "the", "model", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/search.py#L9-L25
train
django-fluent/django-fluent-contents
example/simplecms/admin.py
PageAdmin.get_urls
def get_urls(self): """ Introduce more urls """ urls = super(PageAdmin, self).get_urls() my_urls = [ url(r'^get_layout/$', self.admin_site.admin_view(self.get_layout_view)) ] return my_urls + urls
python
def get_urls(self): """ Introduce more urls """ urls = super(PageAdmin, self).get_urls() my_urls = [ url(r'^get_layout/$', self.admin_site.admin_view(self.get_layout_view)) ] return my_urls + urls
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", "PageAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "my_urls", "=", "[", "url", "(", "r'^get_layout/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "...
Introduce more urls
[ "Introduce", "more", "urls" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/example/simplecms/admin.py#L53-L61
train
django-fluent/django-fluent-contents
example/simplecms/admin.py
PageAdmin.get_layout_view
def get_layout_view(self, request): """ Return the metadata about a layout """ template_name = request.GET['name'] # Check if template is allowed, avoid parsing random templates templates = dict(appconfig.SIMPLECMS_TEMPLATE_CHOICES) if template_name not in templa...
python
def get_layout_view(self, request): """ Return the metadata about a layout """ template_name = request.GET['name'] # Check if template is allowed, avoid parsing random templates templates = dict(appconfig.SIMPLECMS_TEMPLATE_CHOICES) if template_name not in templa...
[ "def", "get_layout_view", "(", "self", ",", "request", ")", ":", "template_name", "=", "request", ".", "GET", "[", "'name'", "]", "# Check if template is allowed, avoid parsing random templates", "templates", "=", "dict", "(", "appconfig", ".", "SIMPLECMS_TEMPLATE_CHOIC...
Return the metadata about a layout
[ "Return", "the", "metadata", "about", "a", "layout" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/example/simplecms/admin.py#L63-L85
train
django-fluent/django-fluent-contents
fluent_contents/plugins/text/filters/softhyphen.py
softhyphen_filter
def softhyphen_filter(textitem, html): """ Apply soft hyphenation to the text, which inserts ``­`` markers. """ language = textitem.language_code # Make sure the Django language code gets converted to what django-softhypen 1.0.2 needs. if language == 'en': language = 'en-us' eli...
python
def softhyphen_filter(textitem, html): """ Apply soft hyphenation to the text, which inserts ``­`` markers. """ language = textitem.language_code # Make sure the Django language code gets converted to what django-softhypen 1.0.2 needs. if language == 'en': language = 'en-us' eli...
[ "def", "softhyphen_filter", "(", "textitem", ",", "html", ")", ":", "language", "=", "textitem", ".", "language_code", "# Make sure the Django language code gets converted to what django-softhypen 1.0.2 needs.", "if", "language", "==", "'en'", ":", "language", "=", "'en-us'...
Apply soft hyphenation to the text, which inserts ``­`` markers.
[ "Apply", "soft", "hyphenation", "to", "the", "text", "which", "inserts", "&shy", ";", "markers", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/text/filters/softhyphen.py#L10-L22
train
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
get_cached_placeholder_output
def get_cached_placeholder_output(parent_object, placeholder_name): """ Return cached output for a placeholder, if available. This avoids fetching the Placeholder object. """ if not PlaceholderRenderingPipe.may_cache_placeholders(): return None language_code = get_parent_language_code(p...
python
def get_cached_placeholder_output(parent_object, placeholder_name): """ Return cached output for a placeholder, if available. This avoids fetching the Placeholder object. """ if not PlaceholderRenderingPipe.may_cache_placeholders(): return None language_code = get_parent_language_code(p...
[ "def", "get_cached_placeholder_output", "(", "parent_object", ",", "placeholder_name", ")", ":", "if", "not", "PlaceholderRenderingPipe", ".", "may_cache_placeholders", "(", ")", ":", "return", "None", "language_code", "=", "get_parent_language_code", "(", "parent_object"...
Return cached output for a placeholder, if available. This avoids fetching the Placeholder object.
[ "Return", "cached", "output", "for", "a", "placeholder", "if", "available", ".", "This", "avoids", "fetching", "the", "Placeholder", "object", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L14-L24
train
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
render_placeholder
def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object. Returns a :class:`~fluent_contents.models.ContentItemOutput` object which contains th...
python
def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object. Returns a :class:`~fluent_contents.models.ContentItemOutput` object which contains th...
[ "def", "render_placeholder", "(", "request", ",", "placeholder", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ",", "limit_parent_language", "=", "True", ",", "fallback_language", "=", "None", ")", ":", "ou...
Render a :class:`~fluent_contents.models.Placeholder` object. Returns a :class:`~fluent_contents.models.ContentItemOutput` object which contains the HTML output and :class:`~django.forms.Media` object. This function also caches the complete output of the placeholder when all individual items are cachea...
[ "Render", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "Placeholder", "object", ".", "Returns", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "ContentItemOutput", "object", "which", "contains", "the", "HTML", "output", "and...
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L27-L65
train
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
render_content_items
def render_content_items(request, items, template_name=None, cachable=None): """ Render a list of :class:`~fluent_contents.models.ContentItem` objects as HTML string. This is a variation of the :func:`render_placeholder` function. Note that the items are not filtered in any way by parent or language. ...
python
def render_content_items(request, items, template_name=None, cachable=None): """ Render a list of :class:`~fluent_contents.models.ContentItem` objects as HTML string. This is a variation of the :func:`render_placeholder` function. Note that the items are not filtered in any way by parent or language. ...
[ "def", "render_content_items", "(", "request", ",", "items", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ")", ":", "if", "not", "items", ":", "output", "=", "ContentItemOutput", "(", "mark_safe", "(", "u\"<!-- no items to render -->\"", ")",...
Render a list of :class:`~fluent_contents.models.ContentItem` objects as HTML string. This is a variation of the :func:`render_placeholder` function. Note that the items are not filtered in any way by parent or language. The items are rendered as-is. :param request: The current request object. :ty...
[ "Render", "a", "list", "of", ":", "class", ":", "~fluent_contents", ".", "models", ".", "ContentItem", "objects", "as", "HTML", "string", ".", "This", "is", "a", "variation", "of", "the", ":", "func", ":", "render_placeholder", "function", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L68-L103
train
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
render_placeholder_search_text
def render_placeholder_search_text(placeholder, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object to search text. This text can be used by an indexer (e.g. haystack) to produce content search for a parent object. :param placeholder: The placeholder object. :t...
python
def render_placeholder_search_text(placeholder, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object to search text. This text can be used by an indexer (e.g. haystack) to produce content search for a parent object. :param placeholder: The placeholder object. :t...
[ "def", "render_placeholder_search_text", "(", "placeholder", ",", "fallback_language", "=", "None", ")", ":", "parent_object", "=", "placeholder", ".", "parent", "# this is a cached lookup thanks to PlaceholderFieldDescriptor", "language", "=", "get_parent_language_code", "(", ...
Render a :class:`~fluent_contents.models.Placeholder` object to search text. This text can be used by an indexer (e.g. haystack) to produce content search for a parent object. :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param fallback_lan...
[ "Render", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "Placeholder", "object", "to", "search", "text", ".", "This", "text", "can", "be", "used", "by", "an", "indexer", "(", "e", ".", "g", ".", "haystack", ")", "to", "produce", "cont...
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L106-L125
train
django-fluent/django-fluent-contents
fluent_contents/forms/widgets.py
PlaceholderFieldWidget.render
def render(self, name, value, attrs=None, renderer=None): """ Render the placeholder field. """ other_instance_languages = None if value and value != "-DUMMY-": if get_parent_language_code(self.parent_object): # Parent is a multilingual object, provide...
python
def render(self, name, value, attrs=None, renderer=None): """ Render the placeholder field. """ other_instance_languages = None if value and value != "-DUMMY-": if get_parent_language_code(self.parent_object): # Parent is a multilingual object, provide...
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "renderer", "=", "None", ")", ":", "other_instance_languages", "=", "None", "if", "value", "and", "value", "!=", "\"-DUMMY-\"", ":", "if", "get_parent_language_code", ...
Render the placeholder field.
[ "Render", "the", "placeholder", "field", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/forms/widgets.py#L46-L64
train
django-fluent/django-fluent-contents
fluent_contents/forms/widgets.py
PlaceholderFieldWidget.plugins
def plugins(self): """ Get the set of plugins that this widget should display. """ from fluent_contents import extensions # Avoid circular reference because __init__.py imports subfolders too if self._plugins is None: return extensions.plugin_pool.get_plugins() ...
python
def plugins(self): """ Get the set of plugins that this widget should display. """ from fluent_contents import extensions # Avoid circular reference because __init__.py imports subfolders too if self._plugins is None: return extensions.plugin_pool.get_plugins() ...
[ "def", "plugins", "(", "self", ")", ":", "from", "fluent_contents", "import", "extensions", "# Avoid circular reference because __init__.py imports subfolders too", "if", "self", ".", "_plugins", "is", "None", ":", "return", "extensions", ".", "plugin_pool", ".", "get_p...
Get the set of plugins that this widget should display.
[ "Get", "the", "set", "of", "plugins", "that", "this", "widget", "should", "display", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/forms/widgets.py#L67-L75
train
django-fluent/django-fluent-contents
fluent_contents/middleware.py
_new_render
def _new_render(response): """ Decorator for the TemplateResponse.render() function """ orig_render = response.__class__.render # No arguments, is used as bound method. def _inner_render(): try: return orig_render(response) except HttpRedirectRequest as e: ...
python
def _new_render(response): """ Decorator for the TemplateResponse.render() function """ orig_render = response.__class__.render # No arguments, is used as bound method. def _inner_render(): try: return orig_render(response) except HttpRedirectRequest as e: ...
[ "def", "_new_render", "(", "response", ")", ":", "orig_render", "=", "response", ".", "__class__", ".", "render", "# No arguments, is used as bound method.", "def", "_inner_render", "(", ")", ":", "try", ":", "return", "orig_render", "(", "response", ")", "except"...
Decorator for the TemplateResponse.render() function
[ "Decorator", "for", "the", "TemplateResponse", ".", "render", "()", "function" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/middleware.py#L43-L56
train
django-fluent/django-fluent-contents
fluent_contents/middleware.py
HttpRedirectRequestMiddleware.process_exception
def process_exception(self, request, exception): """ Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest` """ if isinstance(exception, HttpRedirectRequest): return HttpResponseRedirect(exception.url, status=exception.status) else...
python
def process_exception(self, request, exception): """ Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest` """ if isinstance(exception, HttpRedirectRequest): return HttpResponseRedirect(exception.url, status=exception.status) else...
[ "def", "process_exception", "(", "self", ",", "request", ",", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "HttpRedirectRequest", ")", ":", "return", "HttpResponseRedirect", "(", "exception", ".", "url", ",", "status", "=", "exception", "....
Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest`
[ "Return", "a", "redirect", "response", "for", "the", ":", "class", ":", "~fluent_contents", ".", "extensions", ".", "HttpRedirectRequest" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/middleware.py#L23-L30
train
django-fluent/django-fluent-contents
fluent_contents/plugins/markup/backend.py
render_text
def render_text(text, language=None): """ Render the text, reuses the template filters provided by Django. """ # Get the filter text_filter = SUPPORTED_LANGUAGES.get(language, None) if not text_filter: raise ImproperlyConfigured("markup filter does not exist: {0}. Valid options are: {1}"...
python
def render_text(text, language=None): """ Render the text, reuses the template filters provided by Django. """ # Get the filter text_filter = SUPPORTED_LANGUAGES.get(language, None) if not text_filter: raise ImproperlyConfigured("markup filter does not exist: {0}. Valid options are: {1}"...
[ "def", "render_text", "(", "text", ",", "language", "=", "None", ")", ":", "# Get the filter", "text_filter", "=", "SUPPORTED_LANGUAGES", ".", "get", "(", "language", ",", "None", ")", "if", "not", "text_filter", ":", "raise", "ImproperlyConfigured", "(", "\"m...
Render the text, reuses the template filters provided by Django.
[ "Render", "the", "text", "reuses", "the", "template", "filters", "provided", "by", "Django", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/markup/backend.py#L61-L73
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
ResultTracker.fetch_remaining_instances
def fetch_remaining_instances(self): """Read the derived table data for all objects tracked as remaining (=not found in the cache).""" if self.remaining_items: self.remaining_items = ContentItem.objects.get_real_instances(self.remaining_items)
python
def fetch_remaining_instances(self): """Read the derived table data for all objects tracked as remaining (=not found in the cache).""" if self.remaining_items: self.remaining_items = ContentItem.objects.get_real_instances(self.remaining_items)
[ "def", "fetch_remaining_instances", "(", "self", ")", ":", "if", "self", ".", "remaining_items", ":", "self", ".", "remaining_items", "=", "ContentItem", ".", "objects", ".", "get_real_instances", "(", "self", ".", "remaining_items", ")" ]
Read the derived table data for all objects tracked as remaining (=not found in the cache).
[ "Read", "the", "derived", "table", "data", "for", "all", "objects", "tracked", "as", "remaining", "(", "=", "not", "found", "in", "the", "cache", ")", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L98-L101
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
ResultTracker.get_output
def get_output(self, include_exceptions=False): """ Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]] """ # Order all rendered items in the correct sequence. # Don't assume the derived tables are in perfect shape, hence the dict + KeyError han...
python
def get_output(self, include_exceptions=False): """ Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]] """ # Order all rendered items in the correct sequence. # Don't assume the derived tables are in perfect shape, hence the dict + KeyError han...
[ "def", "get_output", "(", "self", ",", "include_exceptions", "=", "False", ")", ":", "# Order all rendered items in the correct sequence.", "# Don't assume the derived tables are in perfect shape, hence the dict + KeyError handling.", "# The derived tables could be truncated/reset or store_o...
Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]]
[ "Return", "the", "output", "in", "the", "correct", "ordering", ".", ":", "rtype", ":", "list", "[", "Tuple", "[", "contentitem", "O", "]]" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L110-L137
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.render_items
def render_items(self, placeholder, items, parent_object=None, template_name=None, cachable=None): """ The main rendering sequence. """ # Unless it was done before, disable polymorphic effects. is_queryset = False if hasattr(items, "non_polymorphic"): is_query...
python
def render_items(self, placeholder, items, parent_object=None, template_name=None, cachable=None): """ The main rendering sequence. """ # Unless it was done before, disable polymorphic effects. is_queryset = False if hasattr(items, "non_polymorphic"): is_query...
[ "def", "render_items", "(", "self", ",", "placeholder", ",", "items", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ")", ":", "# Unless it was done before, disable polymorphic effects.", "is_queryset", "=", "Fals...
The main rendering sequence.
[ "The", "main", "rendering", "sequence", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L167-L210
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe._fetch_cached_output
def _fetch_cached_output(self, items, result): """ First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database. """ if not appsettings.FLU...
python
def _fetch_cached_output(self, items, result): """ First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database. """ if not appsettings.FLU...
[ "def", "_fetch_cached_output", "(", "self", ",", "items", ",", "result", ")", ":", "if", "not", "appsettings", ".", "FLUENT_CONTENTS_CACHE_OUTPUT", "or", "not", "self", ".", "use_cached_output", ":", "result", ".", "add_remaining_list", "(", "items", ")", "retur...
First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database.
[ "First", "try", "to", "fetch", "all", "items", "from", "the", "cache", ".", "The", "items", "are", "non", "-", "polymorphic", "so", "only", "point", "to", "their", "base", "class", ".", "If", "these", "are", "found", "there", "is", "no", "need", "to", ...
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L212-L256
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.can_use_cached_output
def can_use_cached_output(self, contentitem): """ Tell whether the code should try reading cached output """ plugin = contentitem.plugin return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk
python
def can_use_cached_output(self, contentitem): """ Tell whether the code should try reading cached output """ plugin = contentitem.plugin return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk
[ "def", "can_use_cached_output", "(", "self", ",", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "return", "appsettings", ".", "FLUENT_CONTENTS_CACHE_OUTPUT", "and", "plugin", ".", "cache_output", "and", "contentitem", ".", "pk" ]
Tell whether the code should try reading cached output
[ "Tell", "whether", "the", "code", "should", "try", "reading", "cached", "output" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L258-L263
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe._render_uncached_items
def _render_uncached_items(self, items, result): """ Render a list of items, that didn't exist in the cache yet. """ for contentitem in items: # Render the item. # Allow derived classes to skip it. try: output = self.render_item(content...
python
def _render_uncached_items(self, items, result): """ Render a list of items, that didn't exist in the cache yet. """ for contentitem in items: # Render the item. # Allow derived classes to skip it. try: output = self.render_item(content...
[ "def", "_render_uncached_items", "(", "self", ",", "items", ",", "result", ")", ":", "for", "contentitem", "in", "items", ":", "# Render the item.", "# Allow derived classes to skip it.", "try", ":", "output", "=", "self", ".", "render_item", "(", "contentitem", "...
Render a list of items, that didn't exist in the cache yet.
[ "Render", "a", "list", "of", "items", "that", "didn", "t", "exist", "in", "the", "cache", "yet", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L265-L287
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.render_item
def render_item(self, contentitem): """ Render the individual item. May raise :class:`SkipItem` to ignore an item. """ render_language = get_render_language(contentitem) with smart_override(render_language): # Plugin output is likely HTML, but it should be pla...
python
def render_item(self, contentitem): """ Render the individual item. May raise :class:`SkipItem` to ignore an item. """ render_language = get_render_language(contentitem) with smart_override(render_language): # Plugin output is likely HTML, but it should be pla...
[ "def", "render_item", "(", "self", ",", "contentitem", ")", ":", "render_language", "=", "get_render_language", "(", "contentitem", ")", "with", "smart_override", "(", "render_language", ")", ":", "# Plugin output is likely HTML, but it should be placed in mark_safe() to rais...
Render the individual item. May raise :class:`SkipItem` to ignore an item.
[ "Render", "the", "individual", "item", ".", "May", "raise", ":", "class", ":", "SkipItem", "to", "ignore", "an", "item", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L289-L298
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.merge_output
def merge_output(self, result, items, template_name): """ Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code. """ html_output, media = self.get_html_output(result, items) if not template_name: ...
python
def merge_output(self, result, items, template_name): """ Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code. """ html_output, media = self.get_html_output(result, items) if not template_name: ...
[ "def", "merge_output", "(", "self", ",", "result", ",", "items", ",", "template_name", ")", ":", "html_output", ",", "media", "=", "self", ".", "get_html_output", "(", "result", ",", "items", ")", "if", "not", "template_name", ":", "merged_html", "=", "mar...
Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code.
[ "Combine", "all", "rendered", "items", ".", "Allow", "rendering", "the", "items", "with", "a", "template", "to", "inserting", "separators", "or", "nice", "start", "/", "end", "code", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L337-L356
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.get_html_output
def get_html_output(self, result, items): """ Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example. """ html_output = [] merged_media = Media() fo...
python
def get_html_output(self, result, items): """ Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example. """ html_output = [] merged_media = Media() fo...
[ "def", "get_html_output", "(", "self", ",", "result", ",", "items", ")", ":", "html_output", "=", "[", "]", "merged_media", "=", "Media", "(", ")", "for", "contentitem", ",", "output", "in", "result", ".", "get_output", "(", "include_exceptions", "=", "Tru...
Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example.
[ "Collect", "all", "HTML", "from", "the", "rendered", "items", "in", "the", "correct", "ordering", ".", "The", "media", "is", "also", "collected", "in", "the", "same", "ordering", "in", "case", "it", "s", "handled", "by", "django", "-", "compressor", "for",...
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L358-L381
train
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
PlaceholderRenderingPipe.render_placeholder
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end. """ ...
python
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end. """ ...
[ "def", "render_placeholder", "(", "self", ",", "placeholder", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ",", "limit_parent_language", "=", "True", ",", "fallback_language", "=", "None", ")", ":", "place...
The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end.
[ "The", "main", "rendering", "sequence", "for", "placeholders", ".", "This", "will", "do", "all", "the", "magic", "for", "caching", "and", "call", ":", "func", ":", "render_items", "in", "the", "end", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L389-L436
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.register
def register(self, plugin): """ Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`ContentPlugin` The plugin will be instantiated once, just like Django does this with :class:`~django.contrib.admin.ModelA...
python
def register(self, plugin): """ Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`ContentPlugin` The plugin will be instantiated once, just like Django does this with :class:`~django.contrib.admin.ModelA...
[ "def", "register", "(", "self", ",", "plugin", ")", ":", "# Duck-Typing does not suffice here, avoid hard to debug problems by upfront checks.", "assert", "issubclass", "(", "plugin", ",", "ContentPlugin", ")", ",", "\"The plugin must inherit from `ContentPlugin`\"", "assert", ...
Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`ContentPlugin` The plugin will be instantiated once, just like Django does this with :class:`~django.contrib.admin.ModelAdmin` classes. If a plugin is already re...
[ "Make", "a", "plugin", "known", "to", "the", "CMS", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L62-L104
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_allowed_plugins
def get_allowed_plugins(self, placeholder_slot): """ Return the plugins which are supported in the given placeholder name. """ # See if there is a limit imposed. slot_config = appsettings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(placeholder_slot) or {} plugins = slot_config...
python
def get_allowed_plugins(self, placeholder_slot): """ Return the plugins which are supported in the given placeholder name. """ # See if there is a limit imposed. slot_config = appsettings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(placeholder_slot) or {} plugins = slot_config...
[ "def", "get_allowed_plugins", "(", "self", ",", "placeholder_slot", ")", ":", "# See if there is a limit imposed.", "slot_config", "=", "appsettings", ".", "FLUENT_CONTENTS_PLACEHOLDER_CONFIG", ".", "get", "(", "placeholder_slot", ")", "or", "{", "}", "plugins", "=", ...
Return the plugins which are supported in the given placeholder name.
[ "Return", "the", "plugins", "which", "are", "supported", "in", "the", "given", "placeholder", "name", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L113-L126
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_plugins_by_name
def get_plugins_by_name(self, *names): """ Return a list of plugins by plugin class, or name. """ self._import_plugins() plugin_instances = [] for name in names: if isinstance(name, six.string_types): try: plugin_instances.a...
python
def get_plugins_by_name(self, *names): """ Return a list of plugins by plugin class, or name. """ self._import_plugins() plugin_instances = [] for name in names: if isinstance(name, six.string_types): try: plugin_instances.a...
[ "def", "get_plugins_by_name", "(", "self", ",", "*", "names", ")", ":", "self", ".", "_import_plugins", "(", ")", "plugin_instances", "=", "[", "]", "for", "name", "in", "names", ":", "if", "isinstance", "(", "name", ",", "six", ".", "string_types", ")",...
Return a list of plugins by plugin class, or name.
[ "Return", "a", "list", "of", "plugins", "by", "plugin", "class", "or", "name", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L128-L145
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_model_classes
def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.model for plugin in self.plugins.values()]
python
def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.model for plugin in self.plugins.values()]
[ "def", "get_model_classes", "(", "self", ")", ":", "self", ".", "_import_plugins", "(", ")", "return", "[", "plugin", ".", "model", "for", "plugin", "in", "self", ".", "plugins", ".", "values", "(", ")", "]" ]
Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins.
[ "Return", "all", ":", "class", ":", "~fluent_contents", ".", "models", ".", "ContentItem", "model", "classes", "which", "are", "exposed", "by", "plugins", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L147-L152
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_plugin_by_model
def get_plugin_by_model(self, model_class): """ Return the corresponding plugin for a given model. You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly. This is the low-level function that supports that feature. """ ...
python
def get_plugin_by_model(self, model_class): """ Return the corresponding plugin for a given model. You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly. This is the low-level function that supports that feature. """ ...
[ "def", "get_plugin_by_model", "(", "self", ",", "model_class", ")", ":", "self", ".", "_import_plugins", "(", ")", "# could happen during rendering that no plugin scan happened yet.", "assert", "issubclass", "(", "model_class", ",", "ContentItem", ")", "# avoid confusion be...
Return the corresponding plugin for a given model. You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly. This is the low-level function that supports that feature.
[ "Return", "the", "corresponding", "plugin", "for", "a", "given", "model", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L154-L168
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool._import_plugins
def _import_plugins(self): """ Internal function, ensure all plugin packages are imported. """ if self.detected: return # In some cases, plugin scanning may start during a request. # Make sure there is only one thread scanning for plugins. self.scanLo...
python
def _import_plugins(self): """ Internal function, ensure all plugin packages are imported. """ if self.detected: return # In some cases, plugin scanning may start during a request. # Make sure there is only one thread scanning for plugins. self.scanLo...
[ "def", "_import_plugins", "(", "self", ")", ":", "if", "self", ".", "detected", ":", "return", "# In some cases, plugin scanning may start during a request.", "# Make sure there is only one thread scanning for plugins.", "self", ".", "scanLock", ".", "acquire", "(", ")", "i...
Internal function, ensure all plugin packages are imported.
[ "Internal", "function", "ensure", "all", "plugin", "packages", "are", "imported", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L190-L207
train
django-fluent/django-fluent-contents
fluent_contents/utils/filters.py
apply_filters
def apply_filters(instance, html, field_name): """ Run all filters for a given HTML snippet. Returns the results of the pre-filter and post-filter as tuple. This function can be called from the :meth:`~django.db.models.Model.full_clean` method in the model. That function is called when the form val...
python
def apply_filters(instance, html, field_name): """ Run all filters for a given HTML snippet. Returns the results of the pre-filter and post-filter as tuple. This function can be called from the :meth:`~django.db.models.Model.full_clean` method in the model. That function is called when the form val...
[ "def", "apply_filters", "(", "instance", ",", "html", ",", "field_name", ")", ":", "try", ":", "html", "=", "apply_pre_filters", "(", "instance", ",", "html", ")", "# Perform post processing. This does not effect the original 'html'", "html_final", "=", "apply_post_filt...
Run all filters for a given HTML snippet. Returns the results of the pre-filter and post-filter as tuple. This function can be called from the :meth:`~django.db.models.Model.full_clean` method in the model. That function is called when the form values are assigned. For example: .. code-block:: pyt...
[ "Run", "all", "filters", "for", "a", "given", "HTML", "snippet", ".", "Returns", "the", "results", "of", "the", "pre", "-", "filter", "and", "post", "-", "filter", "as", "tuple", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/filters.py#L11-L43
train
django-fluent/django-fluent-contents
fluent_contents/utils/filters.py
apply_pre_filters
def apply_pre_filters(instance, html): """ Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ # Allow pre processing. Typical use-case is HTML syntax correction. for post_fu...
python
def apply_pre_filters(instance, html): """ Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ # Allow pre processing. Typical use-case is HTML syntax correction. for post_fu...
[ "def", "apply_pre_filters", "(", "instance", ",", "html", ")", ":", "# Allow pre processing. Typical use-case is HTML syntax correction.", "for", "post_func", "in", "appsettings", ".", "PRE_FILTER_FUNCTIONS", ":", "html", "=", "post_func", "(", "instance", ",", "html", ...
Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem.
[ "Perform", "optimizations", "in", "the", "HTML", "source", "code", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/filters.py#L46-L57
train
django-fluent/django-fluent-contents
fluent_contents/utils/filters.py
apply_post_filters
def apply_post_filters(instance, html): """ Allow post processing functions to change the text. This change is not saved in the original text. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ for post_func in appsettin...
python
def apply_post_filters(instance, html): """ Allow post processing functions to change the text. This change is not saved in the original text. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ for post_func in appsettin...
[ "def", "apply_post_filters", "(", "instance", ",", "html", ")", ":", "for", "post_func", "in", "appsettings", ".", "POST_FILTER_FUNCTIONS", ":", "html", "=", "post_func", "(", "instance", ",", "html", ")", "return", "html" ]
Allow post processing functions to change the text. This change is not saved in the original text. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem.
[ "Allow", "post", "processing", "functions", "to", "change", "the", "text", ".", "This", "change", "is", "not", "saved", "in", "the", "original", "text", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/filters.py#L60-L71
train
django-fluent/django-fluent-contents
fluent_contents/plugins/commentsarea/models.py
clear_commentarea_cache
def clear_commentarea_cache(comment): """ Clean the plugin output cache of a rendered plugin. """ parent = comment.content_object for instance in CommentsAreaItem.objects.parent(parent): instance.clear_cache()
python
def clear_commentarea_cache(comment): """ Clean the plugin output cache of a rendered plugin. """ parent = comment.content_object for instance in CommentsAreaItem.objects.parent(parent): instance.clear_cache()
[ "def", "clear_commentarea_cache", "(", "comment", ")", ":", "parent", "=", "comment", ".", "content_object", "for", "instance", "in", "CommentsAreaItem", ".", "objects", ".", "parent", "(", "parent", ")", ":", "instance", ".", "clear_cache", "(", ")" ]
Clean the plugin output cache of a rendered plugin.
[ "Clean", "the", "plugin", "output", "cache", "of", "a", "rendered", "plugin", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/commentsarea/models.py#L27-L33
train
django-fluent/django-fluent-contents
fluent_contents/plugins/sharedcontent/managers.py
SharedContentQuerySet.parent_site
def parent_site(self, site): """ Filter to the given site, only give content relevant for that site. """ # Avoid auto filter if site is already set. self._parent_site = site if sharedcontent_appsettings.FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE: # Allow content...
python
def parent_site(self, site): """ Filter to the given site, only give content relevant for that site. """ # Avoid auto filter if site is already set. self._parent_site = site if sharedcontent_appsettings.FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE: # Allow content...
[ "def", "parent_site", "(", "self", ",", "site", ")", ":", "# Avoid auto filter if site is already set.", "self", ".", "_parent_site", "=", "site", "if", "sharedcontent_appsettings", ".", "FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE", ":", "# Allow content to be shared between all s...
Filter to the given site, only give content relevant for that site.
[ "Filter", "to", "the", "given", "site", "only", "give", "content", "relevant", "for", "that", "site", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/sharedcontent/managers.py#L22-L33
train
django-fluent/django-fluent-contents
fluent_contents/plugins/sharedcontent/managers.py
SharedContentQuerySet._single_site
def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if appsettings.FLUENT_CONTENTS_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self
python
def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if appsettings.FLUENT_CONTENTS_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self
[ "def", "_single_site", "(", "self", ")", ":", "if", "appsettings", ".", "FLUENT_CONTENTS_FILTER_SITE_ID", "and", "self", ".", "_parent_site", "is", "None", ":", "return", "self", ".", "parent_site", "(", "settings", ".", "SITE_ID", ")", "else", ":", "return", ...
Make sure the queryset is filtered on a parent site, if that didn't happen already.
[ "Make", "sure", "the", "queryset", "is", "filtered", "on", "a", "parent", "site", "if", "that", "didn", "t", "happen", "already", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/sharedcontent/managers.py#L35-L42
train
django-fluent/django-fluent-contents
fluent_contents/analyzer.py
get_template_placeholder_data
def get_template_placeholder_data(template): """ Return the placeholders found in a template, wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object. This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes in the tem...
python
def get_template_placeholder_data(template): """ Return the placeholders found in a template, wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object. This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes in the tem...
[ "def", "get_template_placeholder_data", "(", "template", ")", ":", "# Find the instances.", "nodes", "=", "get_node_instances", "(", "template", ",", "PagePlaceholderNode", ")", "# Avoid duplicates, wrap in a class.", "names", "=", "set", "(", ")", "result", "=", "[", ...
Return the placeholders found in a template, wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object. This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes in the template, using the :func:`~template_analyzer.djangoanalyzer...
[ "Return", "the", "placeholders", "found", "in", "a", "template", "wrapped", "in", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "containers", ".", "PlaceholderData", "object", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/analyzer.py#L11-L41
train
django-fluent/django-fluent-contents
fluent_contents/management/commands/find_contentitem_urls.py
Command.inspect_model
def inspect_model(self, model): """ Inspect a single model """ # See which interesting fields the model holds. url_fields = sorted(f for f in model._meta.fields if isinstance(f, (PluginUrlField, models.URLField))) file_fields = sorted(f for f in model._meta.fields if isin...
python
def inspect_model(self, model): """ Inspect a single model """ # See which interesting fields the model holds. url_fields = sorted(f for f in model._meta.fields if isinstance(f, (PluginUrlField, models.URLField))) file_fields = sorted(f for f in model._meta.fields if isin...
[ "def", "inspect_model", "(", "self", ",", "model", ")", ":", "# See which interesting fields the model holds.", "url_fields", "=", "sorted", "(", "f", "for", "f", "in", "model", ".", "_meta", ".", "fields", "if", "isinstance", "(", "f", ",", "(", "PluginUrlFie...
Inspect a single model
[ "Inspect", "a", "single", "model" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/management/commands/find_contentitem_urls.py#L61-L113
train
django-fluent/django-fluent-contents
fluent_contents/management/commands/find_contentitem_urls.py
Command.extract_html_urls
def extract_html_urls(self, html): """ Take all ``<img src="..">`` from the HTML """ p = HTMLParser(tree=treebuilders.getTreeBuilder("dom")) dom = p.parse(html) urls = [] for img in dom.getElementsByTagName('img'): src = img.getAttribute('src') ...
python
def extract_html_urls(self, html): """ Take all ``<img src="..">`` from the HTML """ p = HTMLParser(tree=treebuilders.getTreeBuilder("dom")) dom = p.parse(html) urls = [] for img in dom.getElementsByTagName('img'): src = img.getAttribute('src') ...
[ "def", "extract_html_urls", "(", "self", ",", "html", ")", ":", "p", "=", "HTMLParser", "(", "tree", "=", "treebuilders", ".", "getTreeBuilder", "(", "\"dom\"", ")", ")", "dom", "=", "p", ".", "parse", "(", "html", ")", "urls", "=", "[", "]", "for", ...
Take all ``<img src="..">`` from the HTML
[ "Take", "all", "<img", "src", "=", "..", ">", "from", "the", "HTML" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/management/commands/find_contentitem_urls.py#L119-L146
train
django-fluent/django-fluent-contents
fluent_contents/management/commands/find_contentitem_urls.py
Command.extract_srcset
def extract_srcset(self, srcset): """ Handle ``srcset="image.png 1x, image@2x.jpg 2x"`` """ urls = [] for item in srcset.split(','): if item: urls.append(unquote_utf8(item.rsplit(' ', 1)[0])) return urls
python
def extract_srcset(self, srcset): """ Handle ``srcset="image.png 1x, image@2x.jpg 2x"`` """ urls = [] for item in srcset.split(','): if item: urls.append(unquote_utf8(item.rsplit(' ', 1)[0])) return urls
[ "def", "extract_srcset", "(", "self", ",", "srcset", ")", ":", "urls", "=", "[", "]", "for", "item", "in", "srcset", ".", "split", "(", "','", ")", ":", "if", "item", ":", "urls", ".", "append", "(", "unquote_utf8", "(", "item", ".", "rsplit", "(",...
Handle ``srcset="image.png 1x, image@2x.jpg 2x"``
[ "Handle", "srcset", "=", "image", ".", "png", "1x", "image" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/management/commands/find_contentitem_urls.py#L148-L156
train
django-fluent/django-fluent-contents
fluent_contents/models/db.py
on_delete_model_translation
def on_delete_model_translation(instance, **kwargs): """ Make sure ContentItems are deleted when a translation in deleted. """ translation = instance parent_object = translation.master parent_object.set_current_language(translation.language_code) # Also delete any associated plugins # ...
python
def on_delete_model_translation(instance, **kwargs): """ Make sure ContentItems are deleted when a translation in deleted. """ translation = instance parent_object = translation.master parent_object.set_current_language(translation.language_code) # Also delete any associated plugins # ...
[ "def", "on_delete_model_translation", "(", "instance", ",", "*", "*", "kwargs", ")", ":", "translation", "=", "instance", "parent_object", "=", "translation", ".", "master", "parent_object", ".", "set_current_language", "(", "translation", ".", "language_code", ")",...
Make sure ContentItems are deleted when a translation in deleted.
[ "Make", "sure", "ContentItems", "are", "deleted", "when", "a", "translation", "in", "deleted", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/db.py#L426-L438
train
django-fluent/django-fluent-contents
fluent_contents/utils/html.py
clean_html
def clean_html(input, sanitize=False): """ Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed. :param sanitize: Remove unwanted HTML tags and attributes. >>> clean_html("<p>Foo<b>bar</b></p>") u'<p>Foo<b>bar</b></p>' >>> clean_html("<p>Foo<b>bar</b><i...
python
def clean_html(input, sanitize=False): """ Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed. :param sanitize: Remove unwanted HTML tags and attributes. >>> clean_html("<p>Foo<b>bar</b></p>") u'<p>Foo<b>bar</b></p>' >>> clean_html("<p>Foo<b>bar</b><i...
[ "def", "clean_html", "(", "input", ",", "sanitize", "=", "False", ")", ":", "parser_kwargs", "=", "{", "}", "serializer_kwargs", "=", "{", "}", "if", "sanitize", ":", "if", "HTMLSanitizer", "is", "None", ":", "# new syntax as of 0.99999999/1.0b9 (Released on July ...
Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed. :param sanitize: Remove unwanted HTML tags and attributes. >>> clean_html("<p>Foo<b>bar</b></p>") u'<p>Foo<b>bar</b></p>' >>> clean_html("<p>Foo<b>bar</b><i>Ooops!</p>") u'<p>Foo<b>bar</b><i>Ooops!</i></...
[ "Takes", "an", "HTML", "fragment", "and", "processes", "it", "using", "html5lib", "to", "ensure", "that", "the", "HTML", "is", "well", "-", "formed", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/html.py#L20-L48
train
django-fluent/django-fluent-contents
fluent_contents/models/__init__.py
PlaceholderData.as_dict
def as_dict(self): """ Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins`` """ plugins = self.get_allowed_plugins() ...
python
def as_dict(self): """ Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins`` """ plugins = self.get_allowed_plugins() ...
[ "def", "as_dict", "(", "self", ")", ":", "plugins", "=", "self", ".", "get_allowed_plugins", "(", ")", "return", "{", "'slot'", ":", "self", ".", "slot", ",", "'title'", ":", "self", ".", "title", ",", "'role'", ":", "self", ".", "role", ",", "'fallb...
Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins``
[ "Return", "the", "contents", "as", "dictionary", "for", "client", "-", "side", "export", ".", "The", "dictionary", "contains", "the", "fields", ":" ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/__init__.py#L64-L82
train
django-fluent/django-fluent-contents
fluent_contents/plugins/markup/migrations/0002_fix_polymorphic_ctype.py
_forwards
def _forwards(apps, schema_editor): """ Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language. """ # Need to work on the actual models here. from fluent_contents.plugins.markup.models import LANGUAGE_MODEL_CLASSES from fluent_conte...
python
def _forwards(apps, schema_editor): """ Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language. """ # Need to work on the actual models here. from fluent_contents.plugins.markup.models import LANGUAGE_MODEL_CLASSES from fluent_conte...
[ "def", "_forwards", "(", "apps", ",", "schema_editor", ")", ":", "# Need to work on the actual models here.", "from", "fluent_contents", ".", "plugins", ".", "markup", ".", "models", "import", "LANGUAGE_MODEL_CLASSES", "from", "fluent_contents", ".", "plugins", ".", "...
Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language.
[ "Make", "sure", "that", "the", "MarkupItem", "model", "actually", "points", "to", "the", "correct", "proxy", "model", "that", "implements", "the", "given", "language", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/markup/migrations/0002_fix_polymorphic_ctype.py#L8-L26
train
django-fluent/django-fluent-contents
fluent_contents/admin/placeholdereditor.py
PlaceholderEditorInline.get_formset
def get_formset(self, request, obj=None, **kwargs): """ Pre-populate formset with the initial placeholders to display. """ def _placeholder_initial(p): # p.as_dict() returns allowed_plugins too for the client-side API. return { 'slot': p.slot, ...
python
def get_formset(self, request, obj=None, **kwargs): """ Pre-populate formset with the initial placeholders to display. """ def _placeholder_initial(p): # p.as_dict() returns allowed_plugins too for the client-side API. return { 'slot': p.slot, ...
[ "def", "get_formset", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_placeholder_initial", "(", "p", ")", ":", "# p.as_dict() returns allowed_plugins too for the client-side API.", "return", "{", "'slot'", ":", ...
Pre-populate formset with the initial placeholders to display.
[ "Pre", "-", "populate", "formset", "with", "the", "initial", "placeholders", "to", "display", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholdereditor.py#L106-L133
train
django-fluent/django-fluent-contents
fluent_contents/admin/placeholdereditor.py
PlaceholderEditorAdmin.get_inline_instances
def get_inline_instances(self, request, *args, **kwargs): """ Create the inlines for the admin, including the placeholder and contentitem inlines. """ inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] ...
python
def get_inline_instances(self, request, *args, **kwargs): """ Create the inlines for the admin, including the placeholder and contentitem inlines. """ inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] ...
[ "def", "get_inline_instances", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "inlines", "=", "super", "(", "PlaceholderEditorAdmin", ",", "self", ")", ".", "get_inline_instances", "(", "request", ",", "*", "args", ",", ...
Create the inlines for the admin, including the placeholder and contentitem inlines.
[ "Create", "the", "inlines", "for", "the", "admin", "including", "the", "placeholder", "and", "contentitem", "inlines", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholdereditor.py#L188-L200
train
django-fluent/django-fluent-contents
fluent_contents/admin/placeholdereditor.py
PlaceholderEditorAdmin.get_placeholder_data_view
def get_placeholder_data_view(self, request, object_id): """ Return the placeholder data as dictionary. This is used in the client for the "copy" functionality. """ language = 'en' #request.POST['language'] with translation.override(language): # Use generic solution her...
python
def get_placeholder_data_view(self, request, object_id): """ Return the placeholder data as dictionary. This is used in the client for the "copy" functionality. """ language = 'en' #request.POST['language'] with translation.override(language): # Use generic solution her...
[ "def", "get_placeholder_data_view", "(", "self", ",", "request", ",", "object_id", ")", ":", "language", "=", "'en'", "#request.POST['language']", "with", "translation", ".", "override", "(", "language", ")", ":", "# Use generic solution here, don't assume django-parler i...
Return the placeholder data as dictionary. This is used in the client for the "copy" functionality.
[ "Return", "the", "placeholder", "data", "as", "dictionary", ".", "This", "is", "used", "in", "the", "client", "for", "the", "copy", "functionality", "." ]
896f14add58471b98d7aa295b2c9e6abedec9003
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholdereditor.py#L221-L247
train
rmax/scrapy-inline-requests
src/inline_requests/__init__.py
inline_requests
def inline_requests(method_or_func): """A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks def parse(self, response): next_url = response.urjoin('?next') try: ...
python
def inline_requests(method_or_func): """A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks def parse(self, response): next_url = response.urjoin('?next') try: ...
[ "def", "inline_requests", "(", "method_or_func", ")", ":", "args", "=", "get_args", "(", "method_or_func", ")", "if", "not", "args", ":", "raise", "TypeError", "(", "\"Function must accept at least one argument.\"", ")", "# XXX: hardcoded convention of 'self' as first argum...
A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks def parse(self, response): next_url = response.urjoin('?next') try: next_resp = yield Request(next_url) ...
[ "A", "decorator", "to", "use", "coroutine", "-", "like", "spider", "callbacks", "." ]
2cbbb66e6e97260b7e126aa9d8ecde1393a554c9
https://github.com/rmax/scrapy-inline-requests/blob/2cbbb66e6e97260b7e126aa9d8ecde1393a554c9/src/inline_requests/__init__.py#L19-L74
train
rmax/scrapy-inline-requests
src/inline_requests/utils.py
get_args
def get_args(method_or_func): """Returns method or function arguments.""" try: # Python 3.0+ args = list(inspect.signature(method_or_func).parameters.keys()) except AttributeError: # Python 2.7 args = inspect.getargspec(method_or_func).args return args
python
def get_args(method_or_func): """Returns method or function arguments.""" try: # Python 3.0+ args = list(inspect.signature(method_or_func).parameters.keys()) except AttributeError: # Python 2.7 args = inspect.getargspec(method_or_func).args return args
[ "def", "get_args", "(", "method_or_func", ")", ":", "try", ":", "# Python 3.0+", "args", "=", "list", "(", "inspect", ".", "signature", "(", "method_or_func", ")", ".", "parameters", ".", "keys", "(", ")", ")", "except", "AttributeError", ":", "# Python 2.7"...
Returns method or function arguments.
[ "Returns", "method", "or", "function", "arguments", "." ]
2cbbb66e6e97260b7e126aa9d8ecde1393a554c9
https://github.com/rmax/scrapy-inline-requests/blob/2cbbb66e6e97260b7e126aa9d8ecde1393a554c9/src/inline_requests/utils.py#L4-L12
train
rmax/scrapy-inline-requests
src/inline_requests/generator.py
RequestGenerator._unwindGenerator
def _unwindGenerator(self, generator, _prev=None): """Unwind (resume) generator.""" while True: if _prev: ret, _prev = _prev, None else: try: ret = next(generator) except StopIteration: break ...
python
def _unwindGenerator(self, generator, _prev=None): """Unwind (resume) generator.""" while True: if _prev: ret, _prev = _prev, None else: try: ret = next(generator) except StopIteration: break ...
[ "def", "_unwindGenerator", "(", "self", ",", "generator", ",", "_prev", "=", "None", ")", ":", "while", "True", ":", "if", "_prev", ":", "ret", ",", "_prev", "=", "_prev", ",", "None", "else", ":", "try", ":", "ret", "=", "next", "(", "generator", ...
Unwind (resume) generator.
[ "Unwind", "(", "resume", ")", "generator", "." ]
2cbbb66e6e97260b7e126aa9d8ecde1393a554c9
https://github.com/rmax/scrapy-inline-requests/blob/2cbbb66e6e97260b7e126aa9d8ecde1393a554c9/src/inline_requests/generator.py#L44-L71
train
vimalloc/flask-jwt-simple
flask_jwt_simple/view_decorators.py
jwt_required
def jwt_required(fn): """ If you decorate a view with this, it will ensure that the requester has a valid JWT before calling the actual view. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_headers() ctx_stack...
python
def jwt_required(fn): """ If you decorate a view with this, it will ensure that the requester has a valid JWT before calling the actual view. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_headers() ctx_stack...
[ "def", "jwt_required", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "jwt_data", "=", "_decode_jwt_from_headers", "(", ")", "ctx_stack", ".", "top", ".", "jwt", "=", "jwt_dat...
If you decorate a view with this, it will ensure that the requester has a valid JWT before calling the actual view. :param fn: The view function to decorate
[ "If", "you", "decorate", "a", "view", "with", "this", "it", "will", "ensure", "that", "the", "requester", "has", "a", "valid", "JWT", "before", "calling", "the", "actual", "view", "." ]
ed930340cfcff5a6ddc49248d4682e87204dd3be
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/view_decorators.py#L14-L26
train
vimalloc/flask-jwt-simple
flask_jwt_simple/view_decorators.py
jwt_optional
def jwt_optional(fn): """ If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authenticat...
python
def jwt_optional(fn): """ If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authenticat...
[ "def", "jwt_optional", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "jwt_data", "=", "_decode_jwt_from_headers", "(", ")", "ctx_stack", ".", "top", ".", "jwt", ...
If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authentication errors are not affected. F...
[ "If", "you", "decorate", "a", "view", "with", "this", "it", "will", "check", "the", "request", "for", "a", "valid", "JWT", "and", "put", "it", "into", "the", "Flask", "application", "context", "before", "calling", "the", "view", ".", "If", "no", "authori...
ed930340cfcff5a6ddc49248d4682e87204dd3be
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/view_decorators.py#L29-L48
train
vimalloc/flask-jwt-simple
flask_jwt_simple/utils.py
decode_jwt
def decode_jwt(encoded_token): """ Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it. """ secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token...
python
def decode_jwt(encoded_token): """ Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it. """ secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token...
[ "def", "decode_jwt", "(", "encoded_token", ")", ":", "secret", "=", "config", ".", "decode_key", "algorithm", "=", "config", ".", "algorithm", "audience", "=", "config", ".", "audience", "return", "jwt", ".", "decode", "(", "encoded_token", ",", "secret", ",...
Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it.
[ "Returns", "the", "decoded", "token", "from", "an", "encoded", "one", ".", "This", "does", "all", "the", "checks", "to", "insure", "that", "the", "decoded", "token", "is", "valid", "before", "returning", "it", "." ]
ed930340cfcff5a6ddc49248d4682e87204dd3be
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/utils.py#L36-L44
train
vimalloc/flask-jwt-simple
flask_jwt_simple/jwt_manager.py
JWTManager.init_app
def init_app(self, app): """ Register this extension with the flask app :param app: A flask application """ # Save this so we can use it later in the extension if not hasattr(app, 'extensions'): # pragma: no cover app.extensions = {} app.extensions[...
python
def init_app(self, app): """ Register this extension with the flask app :param app: A flask application """ # Save this so we can use it later in the extension if not hasattr(app, 'extensions'): # pragma: no cover app.extensions = {} app.extensions[...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# Save this so we can use it later in the extension", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "# pragma: no cover", "app", ".", "extensions", "=", "{", "}", "app", ".", "extensions...
Register this extension with the flask app :param app: A flask application
[ "Register", "this", "extension", "with", "the", "flask", "app" ]
ed930340cfcff5a6ddc49248d4682e87204dd3be
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/jwt_manager.py#L40-L57
train
vimalloc/flask-jwt-simple
flask_jwt_simple/jwt_manager.py
JWTManager._set_error_handler_callbacks
def _set_error_handler_callbacks(self, app): """ Sets the error handler callbacks used by this extension """ @app.errorhandler(NoAuthorizationError) def handle_no_auth_error(e): return self._unauthorized_callback(str(e)) @app.errorhandler(InvalidHeaderError) ...
python
def _set_error_handler_callbacks(self, app): """ Sets the error handler callbacks used by this extension """ @app.errorhandler(NoAuthorizationError) def handle_no_auth_error(e): return self._unauthorized_callback(str(e)) @app.errorhandler(InvalidHeaderError) ...
[ "def", "_set_error_handler_callbacks", "(", "self", ",", "app", ")", ":", "@", "app", ".", "errorhandler", "(", "NoAuthorizationError", ")", "def", "handle_no_auth_error", "(", "e", ")", ":", "return", "self", ".", "_unauthorized_callback", "(", "str", "(", "e...
Sets the error handler callbacks used by this extension
[ "Sets", "the", "error", "handler", "callbacks", "used", "by", "this", "extension" ]
ed930340cfcff5a6ddc49248d4682e87204dd3be
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/jwt_manager.py#L59-L77
train
vimalloc/flask-jwt-simple
flask_jwt_simple/jwt_manager.py
JWTManager._set_default_configuration_options
def _set_default_configuration_options(app): """ Sets the default configuration options used by this extension """ # Options for JWTs when the TOKEN_LOCATION is headers app.config.setdefault('JWT_HEADER_NAME', 'Authorization') app.config.setdefault('JWT_HEADER_TYPE', 'Bea...
python
def _set_default_configuration_options(app): """ Sets the default configuration options used by this extension """ # Options for JWTs when the TOKEN_LOCATION is headers app.config.setdefault('JWT_HEADER_NAME', 'Authorization') app.config.setdefault('JWT_HEADER_TYPE', 'Bea...
[ "def", "_set_default_configuration_options", "(", "app", ")", ":", "# Options for JWTs when the TOKEN_LOCATION is headers", "app", ".", "config", ".", "setdefault", "(", "'JWT_HEADER_NAME'", ",", "'Authorization'", ")", "app", ".", "config", ".", "setdefault", "(", "'JW...
Sets the default configuration options used by this extension
[ "Sets", "the", "default", "configuration", "options", "used", "by", "this", "extension" ]
ed930340cfcff5a6ddc49248d4682e87204dd3be
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/jwt_manager.py#L80-L109
train
zachwill/fred
fred/api.py
category
def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
python
def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
[ "def", "category", "(", "*", "*", "kwargs", ")", ":", "if", "'series'", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "'series'", ")", "path", "=", "'series'", "else", ":", "path", "=", "None", "return", "Fred", "(", ")", ".", "category", "(", "p...
Get a category.
[ "Get", "a", "category", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L18-L25
train
zachwill/fred
fred/api.py
releases
def releases(release_id=None, **kwargs): """Get all releases of economic data.""" if not 'id' in kwargs and release_id is not None: kwargs['release_id'] = release_id return Fred().release(**kwargs) return Fred().releases(**kwargs)
python
def releases(release_id=None, **kwargs): """Get all releases of economic data.""" if not 'id' in kwargs and release_id is not None: kwargs['release_id'] = release_id return Fred().release(**kwargs) return Fred().releases(**kwargs)
[ "def", "releases", "(", "release_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "'id'", "in", "kwargs", "and", "release_id", "is", "not", "None", ":", "kwargs", "[", "'release_id'", "]", "=", "release_id", "return", "Fred", "(", ")",...
Get all releases of economic data.
[ "Get", "all", "releases", "of", "economic", "data", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L62-L67
train
zachwill/fred
fred/api.py
series
def series(identifier=None, **kwargs): """Get an economic data series.""" if identifier: kwargs['series_id'] = identifier if 'release' in kwargs: kwargs.pop('release') path = 'release' elif 'releases' in kwargs: kwargs.pop('releases') path = 'release' else: ...
python
def series(identifier=None, **kwargs): """Get an economic data series.""" if identifier: kwargs['series_id'] = identifier if 'release' in kwargs: kwargs.pop('release') path = 'release' elif 'releases' in kwargs: kwargs.pop('releases') path = 'release' else: ...
[ "def", "series", "(", "identifier", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "identifier", ":", "kwargs", "[", "'series_id'", "]", "=", "identifier", "if", "'release'", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "'release'", ")", "pat...
Get an economic data series.
[ "Get", "an", "economic", "data", "series", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L79-L91
train
zachwill/fred
fred/api.py
source
def source(source_id=None, **kwargs): """Get a source of economic data.""" if source_id is not None: kwargs['source_id'] = source_id elif 'id' in kwargs: source_id = kwargs.pop('id') kwargs['source_id'] = source_id if 'releases' in kwargs: kwargs.pop('releases') p...
python
def source(source_id=None, **kwargs): """Get a source of economic data.""" if source_id is not None: kwargs['source_id'] = source_id elif 'id' in kwargs: source_id = kwargs.pop('id') kwargs['source_id'] = source_id if 'releases' in kwargs: kwargs.pop('releases') p...
[ "def", "source", "(", "source_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source_id", "is", "not", "None", ":", "kwargs", "[", "'source_id'", "]", "=", "source_id", "elif", "'id'", "in", "kwargs", ":", "source_id", "=", "kwargs", ".", ...
Get a source of economic data.
[ "Get", "a", "source", "of", "economic", "data", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L124-L136
train
zachwill/fred
fred/api.py
sources
def sources(source_id=None, **kwargs): """Get the sources of economic data.""" if source_id or 'id' in kwargs: return source(source_id, **kwargs) return Fred().sources(**kwargs)
python
def sources(source_id=None, **kwargs): """Get the sources of economic data.""" if source_id or 'id' in kwargs: return source(source_id, **kwargs) return Fred().sources(**kwargs)
[ "def", "sources", "(", "source_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source_id", "or", "'id'", "in", "kwargs", ":", "return", "source", "(", "source_id", ",", "*", "*", "kwargs", ")", "return", "Fred", "(", ")", ".", "sources", ...
Get the sources of economic data.
[ "Get", "the", "sources", "of", "economic", "data", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L139-L143
train
zachwill/fred
fred/core.py
Fred._create_path
def _create_path(self, *args): """Create the URL path with the Fred endpoint and given arguments.""" args = filter(None, args) path = self.endpoint + '/'.join(args) return path
python
def _create_path(self, *args): """Create the URL path with the Fred endpoint and given arguments.""" args = filter(None, args) path = self.endpoint + '/'.join(args) return path
[ "def", "_create_path", "(", "self", ",", "*", "args", ")", ":", "args", "=", "filter", "(", "None", ",", "args", ")", "path", "=", "self", ".", "endpoint", "+", "'/'", ".", "join", "(", "args", ")", "return", "path" ]
Create the URL path with the Fred endpoint and given arguments.
[ "Create", "the", "URL", "path", "with", "the", "Fred", "endpoint", "and", "given", "arguments", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L32-L36
train
zachwill/fred
fred/core.py
Fred.get
def get(self, *args, **kwargs): """Perform a GET request againt the Fred API endpoint.""" location = args[0] params = self._get_keywords(location, kwargs) url = self._create_path(*args) request = requests.get(url, params=params) content = request.content self._req...
python
def get(self, *args, **kwargs): """Perform a GET request againt the Fred API endpoint.""" location = args[0] params = self._get_keywords(location, kwargs) url = self._create_path(*args) request = requests.get(url, params=params) content = request.content self._req...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "location", "=", "args", "[", "0", "]", "params", "=", "self", ".", "_get_keywords", "(", "location", ",", "kwargs", ")", "url", "=", "self", ".", "_create_path", "(", ...
Perform a GET request againt the Fred API endpoint.
[ "Perform", "a", "GET", "request", "againt", "the", "Fred", "API", "endpoint", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L38-L46
train
zachwill/fred
fred/core.py
Fred._get_keywords
def _get_keywords(self, location, keywords): """Format GET request's parameters from keywords.""" if 'xml' in keywords: keywords.pop('xml') self.xml = True else: keywords['file_type'] = 'json' if 'id' in keywords: if location != 'series': ...
python
def _get_keywords(self, location, keywords): """Format GET request's parameters from keywords.""" if 'xml' in keywords: keywords.pop('xml') self.xml = True else: keywords['file_type'] = 'json' if 'id' in keywords: if location != 'series': ...
[ "def", "_get_keywords", "(", "self", ",", "location", ",", "keywords", ")", ":", "if", "'xml'", "in", "keywords", ":", "keywords", ".", "pop", "(", "'xml'", ")", "self", ".", "xml", "=", "True", "else", ":", "keywords", "[", "'file_type'", "]", "=", ...
Format GET request's parameters from keywords.
[ "Format", "GET", "request", "s", "parameters", "from", "keywords", "." ]
8fb8975e8b4fd8a550f586027dd75cbc2fe225f0
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L48-L71
train
chrisdev/django-wagtail-feeds
wagtail_feeds/feeds.py
ExtendedFeed.item_extra_kwargs
def item_extra_kwargs(self, item): """ Returns an extra keyword arguments dictionary that is used with the 'add_item' call of the feed generator. Add the fields of the item, to be used by the custom feed generator. """ if use_feed_image: feed_image = item.feed...
python
def item_extra_kwargs(self, item): """ Returns an extra keyword arguments dictionary that is used with the 'add_item' call of the feed generator. Add the fields of the item, to be used by the custom feed generator. """ if use_feed_image: feed_image = item.feed...
[ "def", "item_extra_kwargs", "(", "self", ",", "item", ")", ":", "if", "use_feed_image", ":", "feed_image", "=", "item", ".", "feed_image", "if", "feed_image", ":", "image_complete_url", "=", "urljoin", "(", "self", ".", "get_site_url", "(", ")", ",", "feed_i...
Returns an extra keyword arguments dictionary that is used with the 'add_item' call of the feed generator. Add the fields of the item, to be used by the custom feed generator.
[ "Returns", "an", "extra", "keyword", "arguments", "dictionary", "that", "is", "used", "with", "the", "add_item", "call", "of", "the", "feed", "generator", ".", "Add", "the", "fields", "of", "the", "item", "to", "be", "used", "by", "the", "custom", "feed", ...
df377afa7fc44316d1149183201461de2d8a99ca
https://github.com/chrisdev/django-wagtail-feeds/blob/df377afa7fc44316d1149183201461de2d8a99ca/wagtail_feeds/feeds.py#L231-L270
train
caktus/django-treenav
treenav/views.py
treenav_undefined_url
def treenav_undefined_url(request, item_slug): """ Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis. """ item = get_object_or_404(treenav.MenuItem, slug=item_slug) # noqa # do something with item here and return an HttpResponseRedirect ...
python
def treenav_undefined_url(request, item_slug): """ Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis. """ item = get_object_or_404(treenav.MenuItem, slug=item_slug) # noqa # do something with item here and return an HttpResponseRedirect ...
[ "def", "treenav_undefined_url", "(", "request", ",", "item_slug", ")", ":", "item", "=", "get_object_or_404", "(", "treenav", ".", "MenuItem", ",", "slug", "=", "item_slug", ")", "# noqa", "# do something with item here and return an HttpResponseRedirect", "raise", "Htt...
Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis.
[ "Sample", "view", "demonstrating", "that", "you", "can", "provide", "custom", "handlers", "for", "undefined", "menu", "items", "on", "a", "per", "-", "item", "basis", "." ]
8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/views.py#L7-L14
train
caktus/django-treenav
treenav/signals.py
treenav_save_other_object_handler
def treenav_save_other_object_handler(sender, instance, created, **kwargs): """ This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved. """ # import here so models don't get loaded during app loading from django.contrib.contenttyp...
python
def treenav_save_other_object_handler(sender, instance, created, **kwargs): """ This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved. """ # import here so models don't get loaded during app loading from django.contrib.contenttyp...
[ "def", "treenav_save_other_object_handler", "(", "sender", ",", "instance", ",", "created", ",", "*", "*", "kwargs", ")", ":", "# import here so models don't get loaded during app loading", "from", "django", ".", "contrib", ".", "contenttypes", ".", "models", "import", ...
This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved.
[ "This", "signal", "attempts", "to", "update", "the", "HREF", "of", "any", "menu", "items", "that", "point", "to", "another", "model", "object", "when", "that", "objects", "is", "saved", "." ]
8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/signals.py#L5-L29
train
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.refresh_hrefs
def refresh_hrefs(self, request): """ Refresh all the cached menu item HREFs in the database. """ for item in treenav.MenuItem.objects.all(): item.save() # refreshes the HREF self.message_user(request, _('Menu item HREFs refreshed successfully.')) info = self...
python
def refresh_hrefs(self, request): """ Refresh all the cached menu item HREFs in the database. """ for item in treenav.MenuItem.objects.all(): item.save() # refreshes the HREF self.message_user(request, _('Menu item HREFs refreshed successfully.')) info = self...
[ "def", "refresh_hrefs", "(", "self", ",", "request", ")", ":", "for", "item", "in", "treenav", ".", "MenuItem", ".", "objects", ".", "all", "(", ")", ":", "item", ".", "save", "(", ")", "# refreshes the HREF", "self", ".", "message_user", "(", "request",...
Refresh all the cached menu item HREFs in the database.
[ "Refresh", "all", "the", "cached", "menu", "item", "HREFs", "in", "the", "database", "." ]
8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L82-L91
train
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.clean_cache
def clean_cache(self, request): """ Remove all MenuItems from Cache. """ treenav.delete_cache() self.message_user(request, _('Cache menuitem cache cleaned successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('adm...
python
def clean_cache(self, request): """ Remove all MenuItems from Cache. """ treenav.delete_cache() self.message_user(request, _('Cache menuitem cache cleaned successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('adm...
[ "def", "clean_cache", "(", "self", ",", "request", ")", ":", "treenav", ".", "delete_cache", "(", ")", "self", ".", "message_user", "(", "request", ",", "_", "(", "'Cache menuitem cache cleaned successfully.'", ")", ")", "info", "=", "self", ".", "model", "....
Remove all MenuItems from Cache.
[ "Remove", "all", "MenuItems", "from", "Cache", "." ]
8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L93-L101
train
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.rebuild_tree
def rebuild_tree(self, request): ''' Rebuilds the tree and clears the cache. ''' self.model.objects.rebuild() self.message_user(request, _('Menu Tree Rebuilt.')) return self.clean_cache(request)
python
def rebuild_tree(self, request): ''' Rebuilds the tree and clears the cache. ''' self.model.objects.rebuild() self.message_user(request, _('Menu Tree Rebuilt.')) return self.clean_cache(request)
[ "def", "rebuild_tree", "(", "self", ",", "request", ")", ":", "self", ".", "model", ".", "objects", ".", "rebuild", "(", ")", "self", ".", "message_user", "(", "request", ",", "_", "(", "'Menu Tree Rebuilt.'", ")", ")", "return", "self", ".", "clean_cach...
Rebuilds the tree and clears the cache.
[ "Rebuilds", "the", "tree", "and", "clears", "the", "cache", "." ]
8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L103-L109
train
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.save_related
def save_related(self, request, form, formsets, change): """ Rebuilds the tree after saving items related to parent. """ super(MenuItemAdmin, self).save_related(request, form, formsets, change) self.model.objects.rebuild()
python
def save_related(self, request, form, formsets, change): """ Rebuilds the tree after saving items related to parent. """ super(MenuItemAdmin, self).save_related(request, form, formsets, change) self.model.objects.rebuild()
[ "def", "save_related", "(", "self", ",", "request", ",", "form", ",", "formsets", ",", "change", ")", ":", "super", "(", "MenuItemAdmin", ",", "self", ")", ".", "save_related", "(", "request", ",", "form", ",", "formsets", ",", "change", ")", "self", "...
Rebuilds the tree after saving items related to parent.
[ "Rebuilds", "the", "tree", "after", "saving", "items", "related", "to", "parent", "." ]
8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L111-L116
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._calculate_dispersion
def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float: """ Calculate the dispersion between actual points and their assigned centroids """ disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labe...
python
def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float: """ Calculate the dispersion between actual points and their assigned centroids """ disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labe...
[ "def", "_calculate_dispersion", "(", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "labels", ":", "np", ".", "ndarray", ",", "centroids", ":", "np", ".", "ndarray", ")", "->", "float", ":", "disp", "=", "np", ...
Calculate the dispersion between actual points and their assigned centroids
[ "Calculate", "the", "dispersion", "between", "actual", "points", "and", "their", "assigned", "centroids" ]
146f868febfac37823114e87819df5e8bfc16ac8
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L91-L96
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._calculate_gap
def _calculate_gap(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, n_clusters: int) -> Tuple[float, int]: """ Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters """ # Holder for reference dispersion resu...
python
def _calculate_gap(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, n_clusters: int) -> Tuple[float, int]: """ Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters """ # Holder for reference dispersion resu...
[ "def", "_calculate_gap", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "n_clusters", ":", "int", ")", "->", "Tuple", "[", "float", ",", "int", "]", ":", "# Holder f...
Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters
[ "Calculate", "the", "gap", "value", "of", "the", "given", "data", "n_refs", "and", "number", "of", "clusters", ".", "Return", "the", "resutling", "gap", "value", "and", "n_clusters" ]
146f868febfac37823114e87819df5e8bfc16ac8
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L98-L127
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_with_rust
def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process gap stat using pure rust """ from gap_statistic.rust import gapstat for label, gap_value in gapstat.optimal_k(X, list(cluster_array)): yield (gap_valu...
python
def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process gap stat using pure rust """ from gap_statistic.rust import gapstat for label, gap_value in gapstat.optimal_k(X, list(cluster_array)): yield (gap_valu...
[ "def", "_process_with_rust", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "from", "gap_statistic", ".", "rust", ...
Process gap stat using pure rust
[ "Process", "gap", "stat", "using", "pure", "rust" ]
146f868febfac37823114e87819df5e8bfc16ac8
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L129-L135
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_with_joblib
def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the joblib backend """ if Parallel is None: raise EnvironmentError('joblib is not installed; cannot use joblib as t...
python
def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the joblib backend """ if Parallel is None: raise EnvironmentError('joblib is not installed; cannot use joblib as t...
[ "def", "_process_with_joblib", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "if", "Parallel", "is", "None", ":"...
Process calling of .calculate_gap() method using the joblib backend
[ "Process", "calling", "of", ".", "calculate_gap", "()", "method", "using", "the", "joblib", "backend" ]
146f868febfac37823114e87819df5e8bfc16ac8
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L137-L147
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_with_multiprocessing
def _process_with_multiprocessing(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the multiprocessing library """ with ProcessPoolExecutor(max_workers=self.n_jobs) as executor: jobs = [ex...
python
def _process_with_multiprocessing(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the multiprocessing library """ with ProcessPoolExecutor(max_workers=self.n_jobs) as executor: jobs = [ex...
[ "def", "_process_with_multiprocessing", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "with", "ProcessPoolExecutor", ...
Process calling of .calculate_gap() method using the multiprocessing library
[ "Process", "calling", "of", ".", "calculate_gap", "()", "method", "using", "the", "multiprocessing", "library" ]
146f868febfac37823114e87819df5e8bfc16ac8
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L149-L161
train
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_non_parallel
def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using no parallel backend; simple for loop generator """ for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters) ...
python
def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using no parallel backend; simple for loop generator """ for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters) ...
[ "def", "_process_non_parallel", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "for", "gap_value", ",", "n_clusters...
Process calling of .calculate_gap() method using no parallel backend; simple for loop generator
[ "Process", "calling", "of", ".", "calculate_gap", "()", "method", "using", "no", "parallel", "backend", ";", "simple", "for", "loop", "generator" ]
146f868febfac37823114e87819df5e8bfc16ac8
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L163-L169
train
sdispater/eloquent
eloquent/migrations/database_migration_repository.py
DatabaseMigrationRepository.get_last
def get_last(self): """ Get the last migration batch. :rtype: list """ query = self.table().where('batch', self.get_last_batch_number()) return query.order_by('migration', 'desc').get()
python
def get_last(self): """ Get the last migration batch. :rtype: list """ query = self.table().where('batch', self.get_last_batch_number()) return query.order_by('migration', 'desc').get()
[ "def", "get_last", "(", "self", ")", ":", "query", "=", "self", ".", "table", "(", ")", ".", "where", "(", "'batch'", ",", "self", ".", "get_last_batch_number", "(", ")", ")", "return", "query", ".", "order_by", "(", "'migration'", ",", "'desc'", ")", ...
Get the last migration batch. :rtype: list
[ "Get", "the", "last", "migration", "batch", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/database_migration_repository.py#L25-L33
train
sdispater/eloquent
eloquent/query/grammars/grammar.py
QueryGrammar.compile_insert
def compile_insert(self, query, values): """ Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str ...
python
def compile_insert(self, query, values): """ Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str ...
[ "def", "compile_insert", "(", "self", ",", "query", ",", "values", ")", ":", "# Essentially we will force every insert to be treated as a batch insert which", "# simply makes creating the SQL easier for us since we can utilize the same", "# basic routine regardless of an amount of records gi...
Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str
[ "Compile", "an", "insert", "SQL", "statement" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/grammar.py#L312-L344
train
sdispater/eloquent
eloquent/dbal/platforms/postgres_platform.py
PostgresPlatform.get_alter_table_sql
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ sql = [] for column_diff in diff.changed_columns.values(): if self.is_unch...
python
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ sql = [] for column_diff in diff.changed_columns.values(): if self.is_unch...
[ "def", "get_alter_table_sql", "(", "self", ",", "diff", ")", ":", "sql", "=", "[", "]", "for", "column_diff", "in", "diff", ".", "changed_columns", ".", "values", "(", ")", ":", "if", "self", ".", "is_unchanged_binary_column", "(", "column_diff", ")", ":",...
Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list
[ "Get", "the", "ALTER", "TABLE", "SQL", "statement" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/dbal/platforms/postgres_platform.py#L117-L180
train
sdispater/eloquent
eloquent/query/grammars/sqlite_grammar.py
SQLiteQueryGrammar._date_based_where
def _date_based_where(self, type, query, where): """ Compiled a date where based clause :param type: The date type :type type: str :param query: A QueryBuilder instance :type query: QueryBuilder :param where: The condition :type where: dict :re...
python
def _date_based_where(self, type, query, where): """ Compiled a date where based clause :param type: The date type :type type: str :param query: A QueryBuilder instance :type query: QueryBuilder :param where: The condition :type where: dict :re...
[ "def", "_date_based_where", "(", "self", ",", "type", ",", "query", ",", "where", ")", ":", "value", "=", "str", "(", "where", "[", "'value'", "]", ")", ".", "zfill", "(", "2", ")", "value", "=", "self", ".", "parameter", "(", "value", ")", "return...
Compiled a date where based clause :param type: The date type :type type: str :param query: A QueryBuilder instance :type query: QueryBuilder :param where: The condition :type where: dict :return: The compiled clause :rtype: str
[ "Compiled", "a", "date", "where", "based", "clause" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/sqlite_grammar.py#L114-L135
train
sdispater/eloquent
eloquent/query/grammars/mysql_grammar.py
MySqlQueryGrammar.compile_select
def compile_select(self, query): """ Compile a select query into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str """ sql = super(MySqlQueryGrammar, self).compile_select(query) if query.un...
python
def compile_select(self, query): """ Compile a select query into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str """ sql = super(MySqlQueryGrammar, self).compile_select(query) if query.un...
[ "def", "compile_select", "(", "self", ",", "query", ")", ":", "sql", "=", "super", "(", "MySqlQueryGrammar", ",", "self", ")", ".", "compile_select", "(", "query", ")", "if", "query", ".", "unions", ":", "sql", "=", "'(%s) %s'", "%", "(", "sql", ",", ...
Compile a select query into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str
[ "Compile", "a", "select", "query", "into", "SQL" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/mysql_grammar.py#L23-L38
train
sdispater/eloquent
eloquent/query/grammars/mysql_grammar.py
MySqlQueryGrammar._compile_lock
def _compile_lock(self, query, value): """ Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value :type value: bool or str :return: The compiled lock :rtype: str """ if isin...
python
def _compile_lock(self, query, value): """ Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value :type value: bool or str :return: The compiled lock :rtype: str """ if isin...
[ "def", "_compile_lock", "(", "self", ",", "query", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "return", "value", "if", "value", "is", "True", ":", "return", "'FOR UPDATE'", "elif", "value", "is", "False", ":", ...
Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value :type value: bool or str :return: The compiled lock :rtype: str
[ "Compile", "the", "lock", "into", "SQL" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/mysql_grammar.py#L57-L76
train
sdispater/eloquent
eloquent/query/grammars/mysql_grammar.py
MySqlQueryGrammar.compile_update
def compile_update(self, query, values): """ Compile an update statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The update values :type values: dict :return: The compiled update :rtype: str """ ...
python
def compile_update(self, query, values): """ Compile an update statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The update values :type values: dict :return: The compiled update :rtype: str """ ...
[ "def", "compile_update", "(", "self", ",", "query", ",", "values", ")", ":", "sql", "=", "super", "(", "MySqlQueryGrammar", ",", "self", ")", ".", "compile_update", "(", "query", ",", "values", ")", "if", "query", ".", "orders", ":", "sql", "+=", "' %s...
Compile an update statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The update values :type values: dict :return: The compiled update :rtype: str
[ "Compile", "an", "update", "statement", "into", "SQL" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/grammars/mysql_grammar.py#L78-L99
train
sdispater/eloquent
eloquent/support/collection.py
Collection.collapse
def collapse(self): """ Collapse the collection items into a single element (dict or list) :return: A new Collection instance with collapsed items :rtype: Collection """ results = [] if isinstance(self._items, dict): items = self._items.values() ...
python
def collapse(self): """ Collapse the collection items into a single element (dict or list) :return: A new Collection instance with collapsed items :rtype: Collection """ results = [] if isinstance(self._items, dict): items = self._items.values() ...
[ "def", "collapse", "(", "self", ")", ":", "results", "=", "[", "]", "if", "isinstance", "(", "self", ".", "_items", ",", "dict", ")", ":", "items", "=", "self", ".", "_items", ".", "values", "(", ")", "for", "values", "in", "items", ":", "if", "i...
Collapse the collection items into a single element (dict or list) :return: A new Collection instance with collapsed items :rtype: Collection
[ "Collapse", "the", "collection", "items", "into", "a", "single", "element", "(", "dict", "or", "list", ")" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L50-L68
train
sdispater/eloquent
eloquent/support/collection.py
Collection.contains
def contains(self, key, value=None): """ Determine if an element is in the collection :param key: The element :type key: int or str :param value: The value of the element :type value: mixed :return: Whether the element is in the collection :rtype: bool ...
python
def contains(self, key, value=None): """ Determine if an element is in the collection :param key: The element :type key: int or str :param value: The value of the element :type value: mixed :return: Whether the element is in the collection :rtype: bool ...
[ "def", "contains", "(", "self", ",", "key", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "if", "isinstance", "(", "self", ".", "_items", ",", "list", ")", ":", "return", "key", "in", "self", ".", "_items", "and", ...
Determine if an element is in the collection :param key: The element :type key: int or str :param value: The value of the element :type value: mixed :return: Whether the element is in the collection :rtype: bool
[ "Determine", "if", "an", "element", "is", "in", "the", "collection" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L70-L89
train
sdispater/eloquent
eloquent/support/collection.py
Collection.lists
def lists(self, value, key=None): """ Get a list with the values of a given key :rtype: list """ results = map(lambda x: x[value], self._items) return list(results)
python
def lists(self, value, key=None): """ Get a list with the values of a given key :rtype: list """ results = map(lambda x: x[value], self._items) return list(results)
[ "def", "lists", "(", "self", ",", "value", ",", "key", "=", "None", ")", ":", "results", "=", "map", "(", "lambda", "x", ":", "x", "[", "value", "]", ",", "self", ".", "_items", ")", "return", "list", "(", "results", ")" ]
Get a list with the values of a given key :rtype: list
[ "Get", "a", "list", "with", "the", "values", "of", "a", "given", "key" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L118-L126
train
sdispater/eloquent
eloquent/support/collection.py
Collection.map
def map(self, callback): """ Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection """ if isinstance(self._items, dict): return Collection(list(map(callback, self._items.values()))) re...
python
def map(self, callback): """ Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection """ if isinstance(self._items, dict): return Collection(list(map(callback, self._items.values()))) re...
[ "def", "map", "(", "self", ",", "callback", ")", ":", "if", "isinstance", "(", "self", ".", "_items", ",", "dict", ")", ":", "return", "Collection", "(", "list", "(", "map", "(", "callback", ",", "self", ".", "_items", ".", "values", "(", ")", ")",...
Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection
[ "Run", "a", "map", "over", "each", "of", "the", "item", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L128-L140
train
sdispater/eloquent
eloquent/support/collection.py
Collection.unique
def unique(self): """ Return only unique items from the collection list. :rtype: Collection """ seen = set() seen_add = seen.add return Collection([x for x in self._items if not (x in seen or seen_add(x))])
python
def unique(self): """ Return only unique items from the collection list. :rtype: Collection """ seen = set() seen_add = seen.add return Collection([x for x in self._items if not (x in seen or seen_add(x))])
[ "def", "unique", "(", "self", ")", ":", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "return", "Collection", "(", "[", "x", "for", "x", "in", "self", ".", "_items", "if", "not", "(", "x", "in", "seen", "or", "seen_add", "(",...
Return only unique items from the collection list. :rtype: Collection
[ "Return", "only", "unique", "items", "from", "the", "collection", "list", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/support/collection.py#L142-L151
train
sdispater/eloquent
eloquent/orm/collection.py
Collection.load
def load(self, *relations): """ Load a set of relationships onto the collection. """ if len(self._items) > 0: query = self.first().new_query().with_(*relations) self._items = query.eager_load_relations(self._items) return self
python
def load(self, *relations): """ Load a set of relationships onto the collection. """ if len(self._items) > 0: query = self.first().new_query().with_(*relations) self._items = query.eager_load_relations(self._items) return self
[ "def", "load", "(", "self", ",", "*", "relations", ")", ":", "if", "len", "(", "self", ".", "_items", ")", ">", "0", ":", "query", "=", "self", ".", "first", "(", ")", ".", "new_query", "(", ")", ".", "with_", "(", "*", "relations", ")", "self"...
Load a set of relationships onto the collection.
[ "Load", "a", "set", "of", "relationships", "onto", "the", "collection", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/collection.py#L8-L17
train
sdispater/eloquent
eloquent/schema/grammars/grammar.py
SchemaGrammar.compile_foreign
def compile_foreign(self, blueprint, command, _): """ Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :rtype: str """ table = self.wrap_table(blueprint) ...
python
def compile_foreign(self, blueprint, command, _): """ Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :rtype: str """ table = self.wrap_table(blueprint) ...
[ "def", "compile_foreign", "(", "self", ",", "blueprint", ",", "command", ",", "_", ")", ":", "table", "=", "self", ".", "wrap_table", "(", "blueprint", ")", "on", "=", "self", ".", "wrap_table", "(", "command", ".", "on", ")", "columns", "=", "self", ...
Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :rtype: str
[ "Compile", "a", "foreign", "key", "command", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L73-L105
train
sdispater/eloquent
eloquent/schema/grammars/grammar.py
SchemaGrammar._get_columns
def _get_columns(self, blueprint): """ Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list """ columns = [] for column in blueprint.get_added_columns(): sql = self.wrap(column) + '...
python
def _get_columns(self, blueprint): """ Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list """ columns = [] for column in blueprint.get_added_columns(): sql = self.wrap(column) + '...
[ "def", "_get_columns", "(", "self", ",", "blueprint", ")", ":", "columns", "=", "[", "]", "for", "column", "in", "blueprint", ".", "get_added_columns", "(", ")", ":", "sql", "=", "self", ".", "wrap", "(", "column", ")", "+", "' '", "+", "self", ".", ...
Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list
[ "Get", "the", "blueprint", "s", "columns", "definitions", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L107-L123
train
sdispater/eloquent
eloquent/schema/grammars/grammar.py
SchemaGrammar._add_modifiers
def _add_modifiers(self, sql, blueprint, column): """ Add the column modifiers to the deifinition """ for modifier in self._modifiers: method = '_modify_%s' % modifier if hasattr(self, method): sql += getattr(self, method)(blueprint, column) ...
python
def _add_modifiers(self, sql, blueprint, column): """ Add the column modifiers to the deifinition """ for modifier in self._modifiers: method = '_modify_%s' % modifier if hasattr(self, method): sql += getattr(self, method)(blueprint, column) ...
[ "def", "_add_modifiers", "(", "self", ",", "sql", ",", "blueprint", ",", "column", ")", ":", "for", "modifier", "in", "self", ".", "_modifiers", ":", "method", "=", "'_modify_%s'", "%", "modifier", "if", "hasattr", "(", "self", ",", "method", ")", ":", ...
Add the column modifiers to the deifinition
[ "Add", "the", "column", "modifiers", "to", "the", "deifinition" ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L125-L135
train
sdispater/eloquent
eloquent/orm/relations/belongs_to_many.py
BelongsToMany._clean_pivot_attributes
def _clean_pivot_attributes(self, model): """ Get the pivot attributes from a model. :type model: eloquent.Model """ values = {} delete_keys = [] for key, value in model.get_attributes().items(): if key.find('pivot_') == 0: values[key...
python
def _clean_pivot_attributes(self, model): """ Get the pivot attributes from a model. :type model: eloquent.Model """ values = {} delete_keys = [] for key, value in model.get_attributes().items(): if key.find('pivot_') == 0: values[key...
[ "def", "_clean_pivot_attributes", "(", "self", ",", "model", ")", ":", "values", "=", "{", "}", "delete_keys", "=", "[", "]", "for", "key", ",", "value", "in", "model", ".", "get_attributes", "(", ")", ".", "items", "(", ")", ":", "if", "key", ".", ...
Get the pivot attributes from a model. :type model: eloquent.Model
[ "Get", "the", "pivot", "attributes", "from", "a", "model", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L155-L173
train
sdispater/eloquent
eloquent/orm/relations/belongs_to_many.py
BelongsToMany.get_relation_count_query_for_self_join
def get_relation_count_query_for_self_join(self, query, parent): """ Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder """ query.select(QueryExp...
python
def get_relation_count_query_for_self_join(self, query, parent): """ Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder """ query.select(QueryExp...
[ "def", "get_relation_count_query_for_self_join", "(", "self", ",", "query", ",", "parent", ")", ":", "query", ".", "select", "(", "QueryExpression", "(", "'COUNT(*)'", ")", ")", "table_prefix", "=", "self", ".", "_query", ".", "get_query", "(", ")", ".", "ge...
Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder
[ "Add", "the", "constraints", "for", "a", "relationship", "count", "query", "on", "the", "same", "table", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L202-L220
train
sdispater/eloquent
eloquent/orm/relations/belongs_to_many.py
BelongsToMany._get_select_columns
def _get_select_columns(self, columns=None): """ Set the select clause for the relation query. :param columns: The columns :type columns: list :rtype: list """ if columns == ['*'] or columns is None: columns = ['%s.*' % self._related.get_table()] ...
python
def _get_select_columns(self, columns=None): """ Set the select clause for the relation query. :param columns: The columns :type columns: list :rtype: list """ if columns == ['*'] or columns is None: columns = ['%s.*' % self._related.get_table()] ...
[ "def", "_get_select_columns", "(", "self", ",", "columns", "=", "None", ")", ":", "if", "columns", "==", "[", "'*'", "]", "or", "columns", "is", "None", ":", "columns", "=", "[", "'%s.*'", "%", "self", ".", "_related", ".", "get_table", "(", ")", "]"...
Set the select clause for the relation query. :param columns: The columns :type columns: list :rtype: list
[ "Set", "the", "select", "clause", "for", "the", "relation", "query", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L230-L242
train
sdispater/eloquent
eloquent/orm/relations/belongs_to_many.py
BelongsToMany._get_aliased_pivot_columns
def _get_aliased_pivot_columns(self): """ Get the pivot columns for the relation. :rtype: list """ defaults = [self._foreign_key, self._other_key] columns = [] for column in defaults + self._pivot_columns: value = '%s.%s AS pivot_%s' % (self._table,...
python
def _get_aliased_pivot_columns(self): """ Get the pivot columns for the relation. :rtype: list """ defaults = [self._foreign_key, self._other_key] columns = [] for column in defaults + self._pivot_columns: value = '%s.%s AS pivot_%s' % (self._table,...
[ "def", "_get_aliased_pivot_columns", "(", "self", ")", ":", "defaults", "=", "[", "self", ".", "_foreign_key", ",", "self", ".", "_other_key", "]", "columns", "=", "[", "]", "for", "column", "in", "defaults", "+", "self", ".", "_pivot_columns", ":", "value...
Get the pivot columns for the relation. :rtype: list
[ "Get", "the", "pivot", "columns", "for", "the", "relation", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L244-L259
train
sdispater/eloquent
eloquent/orm/relations/belongs_to_many.py
BelongsToMany._set_join
def _set_join(self, query=None): """ Set the join clause for the relation query. :param query: The query builder :type query: eloquent.orm.Builder :return: self :rtype: BelongsToMany """ if not query: query = self._query base_table =...
python
def _set_join(self, query=None): """ Set the join clause for the relation query. :param query: The query builder :type query: eloquent.orm.Builder :return: self :rtype: BelongsToMany """ if not query: query = self._query base_table =...
[ "def", "_set_join", "(", "self", ",", "query", "=", "None", ")", ":", "if", "not", "query", ":", "query", "=", "self", ".", "_query", "base_table", "=", "self", ".", "_related", ".", "get_table", "(", ")", "key", "=", "'%s.%s'", "%", "(", "base_table...
Set the join clause for the relation query. :param query: The query builder :type query: eloquent.orm.Builder :return: self :rtype: BelongsToMany
[ "Set", "the", "join", "clause", "for", "the", "relation", "query", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L272-L291
train
sdispater/eloquent
eloquent/orm/relations/belongs_to_many.py
BelongsToMany.match
def match(self, models, results, relation): """ Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str """ dictionary = self._build_dictionary(results) for model in models: key = m...
python
def match(self, models, results, relation): """ Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str """ dictionary = self._build_dictionary(results) for model in models: key = m...
[ "def", "match", "(", "self", ",", "models", ",", "results", ",", "relation", ")", ":", "dictionary", "=", "self", ".", "_build_dictionary", "(", "results", ")", "for", "model", "in", "models", ":", "key", "=", "model", ".", "get_key", "(", ")", "if", ...
Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str
[ "Match", "the", "eagerly", "loaded", "results", "to", "their", "parents", "." ]
0638b688d5fd0c1a46b7471dd465eeb4c2f84666
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/belongs_to_many.py#L326-L344
train