Search is not available for this dataset
text
stringlengths
75
104k
def parent(self, parent_object, limit_parent_language=True): """ Return all content items which are associated with a given parent object. """ lookup = get_parent_lookup_kwargs(parent_object) # Filter the items by default, giving the expected "objects for this parent" items ...
def move_to_placeholder(self, placeholder, sort_order=None): """ .. versionadded: 1.0.2 Move the entire queryset to a new object. Returns a queryset with the newly created objects. """ qs = self.all() # Get clone for item in qs: # Change the item directly in...
def copy_to_placeholder(self, placeholder, sort_order=None): """ .. versionadded: 1.0 Copy the entire queryset to a new object. Returns a queryset with the newly created objects. """ qs = self.all() # Get clone for item in qs: # Change the item directly in t...
def parent(self, parent_object, limit_parent_language=True): """ Return all content items which are associated with a given parent object. """ return self.all().parent(parent_object, limit_parent_language)
def create_for_placeholder(self, placeholder, sort_order=1, language_code=None, **kwargs): """ Create a Content Item with the given parameters If the language_code is not provided, the language code of the parent will be used. This may perform an additional database query, unless ...
def get_placeholder_data(self, request, obj=None): """ Return the data of the placeholder fields. """ # Return all placeholder fields in the model. if not hasattr(self.model, '_meta_placeholder_fields'): return [] data = [] for name, field in self.mod...
def get_all_allowed_plugins(self): """ Return which plugins are allowed by the placeholder fields. """ # Get all allowed plugins of the various placeholders together. if not hasattr(self.model, '_meta_placeholder_fields'): # No placeholder fields in the model, no need...
def _create_markup_model(fixed_language): """ Create a new MarkupItem model that saves itself in a single language. """ title = backend.LANGUAGE_NAMES.get(fixed_language) or fixed_language objects = MarkupLanguageManager(fixed_language) def save(self, *args, **kwargs): self.language = ...
def formfield(self, **kwargs): """ Returns a :class:`PlaceholderFormField` instance for this database Field. """ defaults = { 'label': capfirst(self.verbose_name), 'help_text': self.help_text, 'required': not self.blank, } defaults.upda...
def contribute_to_class(self, cls, name, **kwargs): """ Internal Django method to associate the field with the Model; it assigns the descriptor. """ super(PlaceholderField, self).contribute_to_class(cls, name, **kwargs) # overwrites what instance.<colname> returns; give direct a...
def plugins(self): """ Get the set of plugins that this field may display. """ from fluent_contents import extensions if self._plugins is None: return extensions.plugin_pool.get_plugins() else: try: return extensions.plugin_pool.get...
def value_from_object(self, obj): """ Internal Django method, used to return the placeholder ID when exporting the model instance. """ try: # not using self.attname, access the descriptor instead. placeholder = getattr(obj, self.name) except Placeholder.Do...
def can_use_cached_output(self, contentitem): """ Read the cached output - only when search needs it. """ return contentitem.plugin.search_output and not contentitem.plugin.search_fields \ and super(SearchRenderingPipe, self).can_use_cached_output(contentitem)
def render_item(self, contentitem): """ Render the item - but render as search text instead. """ plugin = contentitem.plugin if not plugin.search_output and not plugin.search_fields: # Only render items when the item was output will be indexed. raise SkipI...
def get_content_item_inlines(plugins=None, base=BaseContentItemInline): """ Dynamically generate genuine django inlines for all registered content item types. When the `plugins` parameter is ``None``, all plugin inlines are returned. """ COPY_FIELDS = ( 'form', 'raw_id_fields', 'filter_verti...
def get_oembed_providers(): """ Get the list of OEmbed providers. """ global _provider_list, _provider_lock if _provider_list is not None: return _provider_list # Allow only one thread to build the list, or make request to embed.ly. _provider_lock.acquire() try: # And ch...
def _build_provider_list(): """ Construct the provider registry, using the app settings. """ registry = None if appsettings.FLUENT_OEMBED_SOURCE == 'basic': registry = bootstrap_basic() elif appsettings.FLUENT_OEMBED_SOURCE == 'embedly': params = {} if appsettings.MICAWBE...
def get_oembed_data(url, max_width=None, max_height=None, **params): """ Fetch the OEmbed object, return the response as dictionary. """ if max_width: params['maxwidth'] = max_width if max_height: params['maxheight'] = max_height registry = get_oembed_providers() return registry.request(ur...
def group_plugins_into_categories(plugins): """ Return all plugins, grouped by category. The structure is a {"Categorynane": [list of plugin classes]} """ if not plugins: return {} plugins = sorted(plugins, key=lambda p: p.verbose_name) categories = {} for plugin in plugins: ...
def plugin_categories_to_choices(categories): """ Return a tuple of plugin model choices, suitable for a select field. Each tuple is a ("TypeName", "Title") value. """ choices = [] for category, items in categories.items(): if items: plugin_tuples = tuple((plugin.type_name, p...
def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, 0): combined = dest + media ...
def get_dummy_request(language=None): """ Returns a Request instance populated with cms specific attributes. """ if settings.ALLOWED_HOSTS and settings.ALLOWED_HOSTS != "*": host = settings.ALLOWED_HOSTS[0] else: host = Site.objects.get_current().domain request = RequestFactory...
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 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 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_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_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 softhyphen_filter(textitem, html): """ Apply soft hyphenation to the text, which inserts ``&shy;`` 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 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 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_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_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(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 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 _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 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 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 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 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 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 _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 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 _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_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 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 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 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 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 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_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_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_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 _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 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_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_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 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 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 _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 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 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 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_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 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 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 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 _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 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_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_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 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 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 _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 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_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 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 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 _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_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 category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
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 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 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 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 _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 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_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 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 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_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 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 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 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 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 _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_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 _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_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_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_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) ...