text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_overview(self): """ Get overview for installation """
response = None try: response = requests.get( urls.overview(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'app...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_smartplug_state(self, device_label, state): """ Turn on or off smartplug Args: device_label (str): Smartplug device label state (boolean): new status, ...
response = None try: response = requests.post( urls.smartplug(self._giid), headers={ 'Content-Type': 'application/json', 'Cookie': 'vid={}'.format(self._vid)}, data=json.dumps([{ "dev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_history(self, filters=(), pagesize=15, offset=0): """ Get recent events Args: filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION', 'TECHNICAL', '...
response = None try: response = requests.get( urls.history(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.format(self._vid)}, params={ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_lock_state(self, code, device_label, state): """ Lock or unlock Args: code (str): Lock code device_label (str): device label of lock state (str): 'loc...
response = None try: response = requests.put( urls.set_lockstate(self._giid, device_label, state), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/json', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_lock_state_transaction(self, transaction_id): """ Get lock state transaction status Args: transaction_id: Transaction ID received from set_lock_state """
response = None try: response = requests.get( urls.get_lockstate_transaction(self._giid, transaction_id), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.format(self._vid)}) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_lock_config(self, device_label): """ Get lock configuration Args: device_label (str): device label of lock """
response = None try: response = requests.get( urls.lockconfig(self._giid, device_label), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.format(self._vid)}) except reques...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_lock_config(self, device_label, volume=None, voice_level=None, auto_lock_enabled=None): """ Set lock configuration Args: device_label (str): device labe...
response = None data = {} if volume: data['volume'] = volume if voice_level: data['voiceLevel'] = voice_level if auto_lock_enabled is not None: data['autoLockEnabled'] = auto_lock_enabled try: response = requests.put( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture_image(self, device_label): """ Capture smartcam image Args: device_label (str): device label of camera """
response = None try: response = requests.post( urls.imagecapture(self._giid, device_label), headers={ 'Content-Type': 'application/json', 'Cookie': 'vid={}'.format(self._vid)}) except requests.exceptions.Request...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_camera_imageseries(self, number_of_imageseries=10, offset=0): """ Get smartcam image series Args: number_of_imageseries (int): number of image series to...
response = None try: response = requests.get( urls.get_imageseries(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.format(self._vid)}, params={ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_image(self, device_label, image_id, file_name): """ Download image taken by a smartcam Args: device_label (str): device label of camera image_id (s...
response = None try: response = requests.get( urls.download_image(self._giid, device_label, image_id), headers={ 'Cookie': 'vid={}'.format(self._vid)}, stream=True) except requests.exceptions.RequestException as ex:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(self): """ Logout and remove vid """
response = None try: response = requests.delete( urls.login(), headers={ 'Cookie': 'vid={}'.format(self._vid)}) except requests.exceptions.RequestException as ex: raise RequestError(ex) _validate_response(respon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_result(overview, *names): """ Print the result of a verisure request """
if names: for name in names: toprint = overview for part in name.split('/'): toprint = toprint[part] print(json.dumps(toprint, indent=4, separators=(',', ': '))) else: print(json.dumps(overview, indent=4, separators=(',', ': ')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def type_id(self): """ Shortcut to retrieving the ContentType id of the model. """
try: return ContentType.objects.get_for_model(self.model, for_concrete_model=False).id except DatabaseError as e: raise DatabaseError("Unable to fetch ContentType object, is a plugin being registered before the initial syncdb? (original error: {0})".format(str(e)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rendering_cache_key(placeholder_name, contentitem): """ Return a cache key for the content item output. .. seealso:: The :func:`ContentItem.clear_cache()...
if not contentitem.pk: return None return "contentitem.@{0}.{1}.{2}".format( placeholder_name, contentitem.plugin.type_name, # always returns the upcasted name. contentitem.pk, # already unique per language_code )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_placeholder_cache_key(placeholder, language_code): """ Return a cache key for an existing placeholder object. This key is used to cache the entire output...
return _get_placeholder_cache_key_for_id( placeholder.parent_type_id, placeholder.parent_id, placeholder.slot, language_code )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code): """ Return a cache key for a placeholder. This key is used to cache the...
parent_type = ContentType.objects.get_for_model(parent_object) return _get_placeholder_cache_key_for_id( parent_type.id, parent_object.pk, placeholder_name, language_code )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_stale_items(self, stale_cts): """ See if there are items that point to a removed model. """
stale_ct_ids = list(stale_cts.keys()) items = (ContentItem.objects .non_polymorphic() # very important, or polymorphic skips them on fetching derived data .filter(polymorphic_ctype__in=stale_ct_ids) .order_by('polymorphic_ctype', 'pk') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_unreferenced_items(self, stale_cts): """ See if there are items that no longer point to an existing parent. """
stale_ct_ids = list(stale_cts.keys()) parent_types = (ContentItem.objects.order_by() .exclude(polymorphic_ctype__in=stale_ct_ids) .values_list('parent_type', flat=True).distinct()) num_unreferenced = 0 for ct_id in parent_types: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_placeholder_arg(arg_name, placeholder): """ Validate and return the Placeholder object that the template variable points to. """
if placeholder is None: raise RuntimeWarning(u"placeholder object is None") elif isinstance(placeholder, Placeholder): return placeholder elif isinstance(placeholder, Manager): manager = placeholder try: parent_object = manager.instance # read RelatedManager cod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_title(self): """ Return the string literal that is used in the template. The title is used in the admin screens. """
try: return extract_literal(self.meta_kwargs['title']) except KeyError: slot = self.get_slot() if slot is not None: return slot.replace('_', ' ').title() return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_literal(templatevar): """ See if a template FilterExpression holds a literal value. :type templatevar: django.template.FilterExpression :rtype: bool|...
# FilterExpression contains another 'var' that either contains a Variable or SafeData object. if hasattr(templatevar, 'var'): templatevar = templatevar.var if isinstance(templatevar, SafeData): # Literal in FilterExpression, can return. return templatevar else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_literal_bool(templatevar): """ See if a template FilterExpression holds a literal boolean value. :type templatevar: django.template.FilterExpression ...
# FilterExpression contains another 'var' that either contains a Variable or SafeData object. if hasattr(templatevar, 'var'): templatevar = templatevar.var if isinstance(templatevar, SafeData): # Literal in FilterExpression, can return. return is_true(templatevar) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_markup_plugin(language, model): """ Create a new MarkupPlugin class that represents the plugin type. """
form = type("{0}MarkupItemForm".format(language.capitalize()), (MarkupItemForm,), { 'default_language': language, }) classname = "{0}MarkupPlugin".format(language.capitalize()) PluginClass = type(classname, (MarkupPluginBase,), { 'model': model, 'form': form, }) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_slot(self, parent_object, slot): """ Return a placeholder by key. """
placeholder = self.parent(parent_object).get(slot=slot) placeholder.parent = parent_object # fill the reverse cache return placeholder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_for_object(self, parent_object, slot, role='m', title=None): """ Create a placeholder with the given parameters """
from .db import Placeholder parent_attrs = get_parent_lookup_kwargs(parent_object) obj = self.create( slot=slot, role=role or Placeholder.MAIN, title=title or slot.title().replace('_', ' '), **parent_attrs ) obj.parent = parent_obj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_for_placeholder(self, placeholder, sort_order=1, language_code=None, **kwargs): """ Create a Content Item with the given parameters If the language_co...
if language_code is None: # Could also use get_language() or appsettings.FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE # thus avoid the risk of performing an extra query here to the parent. # However, this identical behavior to BaseContentItemFormSet, # and the parent ca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.model._meta_placeholder_fields.items(): assert isinstance(field, PlaceholderField) data.append(Placehold...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 for inlines. return [] plugins = [] for name, field in self.model._meta_placeholder_fields.items...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = fixed_language MarkupItem.save(self, *args, **kwargs) class Meta: verbose_name = title verbose_name_pl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 access to the placeholder setattr(cls, name, PlaceholderFieldDescriptor(self.slot)) # Make placeholder fields easy to find # Can't assign this to cl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_plugins_by_name(*self._plugins) except extensions.PluginNotFound as e: ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.DoesNotExist: return None # Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated. return placeho...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 SkipItem if not plugin.search_output: output = ContentItemOutput('', cacheable=False) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_content_item_inlines(plugins=None, base=BaseContentItemInline): """ Dynamically generate genuine django inlines for all registered content item types. Wh...
COPY_FIELDS = ( 'form', 'raw_id_fields', 'filter_vertical', 'filter_horizontal', 'radio_fields', 'prepopulated_fields', 'formfield_overrides', 'readonly_fields', ) if plugins is None: plugins = extensions.plugin_pool.get_plugins() inlines = [] for plugin in plugins: # self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 check whether that already succeeded when the lock is granted. if _provider...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.MICAWBER_EMBEDLY_KEY: params['key'] = appsettings.MICAWBER_EMBEDLY_KEY registry = bootstrap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(url, **params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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().get("/", HTTP_HOST=host) request.session = {} request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE # Ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. # The cache also stores the output under the current language code. # # It would make sense to a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 for just the PluginHtmlField here. if value and isinstance(value, six.string_types): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 templates: jsondata = {'success': False, 'error': 'Template not found'} status = 404...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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' elif '-' not in language: language = "{0}-{0}".format(language) return hyphenate(html, language=language)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cached_placeholder_output(parent_object, placeholder_name): """ Return cached output for a placeholder, if available. This avoids fetching the Placeholde...
if not PlaceholderRenderingPipe.may_cache_placeholders(): return None language_code = get_parent_language_code(parent_object) cache_key = get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code) return cache.get(cache_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 information # for the copy dialog. other_instance_languages = get_parent_active_langua...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() else: return extensions.plugin_pool.get_plugins_by_name(*self._plugins)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}".format( language, ', '.join(list(SUPPORTED_LANGUAGES.keys())) )) # Convert. return text_filt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_queryset = True if not items.polymorphic_disabled and items._result_cache is None: items = items.non_polymorphic() # See if the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 clas...
if not appsettings.FLUENT_CONTENTS_CACHE_OUTPUT or not self.use_cached_output: result.add_remaining_list(items) return for contentitem in items: result.add_ordering(contentitem) output = None try: plugin = contentitem.plugin ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(contentitem) except PluginNotFound as ex: result.store_exception(contentitem, ex) logger.debug("- item ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
html_output = [] merged_media = Media() for contentitem, output in result.get_output(include_exceptions=True): if output is ResultTracker.MISSING: # Likely get_real_instances() didn't return an item for it. # The get_real_instances() didn't return an ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, plugin): """ Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`Cont...
# 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 plugin.model, "The plugin has no model defined" assert issubclass(plugin.model, ContentItem), "The plugin ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.get('plugins') if not plugins: return self.get_plugins() else: try: return self.get_plugins_b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.append(self.plugins[name.lower()]) except KeyError: raise PluginNotFound("No plugin na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_content...
self._import_plugins() # could happen during rendering that no plugin scan happened yet. assert issubclass(model_class, ContentItem) # avoid confusion between model instance and class here! try: name = self._name_for_model[model_class] except KeyError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.scanLock.acquire() if self.detected: return # previous threaded released + completed try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
try: html = apply_pre_filters(instance, html) # Perform post processing. This does not effect the original 'html' html_final = apply_post_filters(instance, html) except ValidationError as e: if hasattr(e, 'error_list'): # The filters can raise a "dump" ValidationErr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_pre_filters(instance, html): """ Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationErr...
# Allow pre processing. Typical use-case is HTML syntax correction. for post_func in appsettings.PRE_FILTER_FUNCTIONS: html = post_func(instance, html) return html
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: fl...
for post_func in appsettings.POST_FILTER_FUNCTIONS: html = post_func(instance, html) return html
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 isinstance(f, (PluginImageField, models.FileField))) html_fields = sorted(f for f ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 # Placeholders are shared between languages, so these are not affected. for item in ContentItem.objects.parent(parent_object, limit_pare...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_contents.plugins.markup.models import MarkupItem from django.contrib.contenttypes.models import ContentType ctype = ContentType.objects.get_for_model(MarkupItem) for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, 'title': p.title, 'role': p.role, } # Note this method is called twice, the second time in get_fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = [] inlinetypes = self.get_extra_inlines() for InlineType in inlinetypes: inline_instance = InlineType(self.model, self.admin_site) extra_inline_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 here, don't assume django-parler is used now. obj = self.get_object(request, object_id) if obj is None: json = {'success': False, 'error': 'Page not found'} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inline_requests(method_or_func): """A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks ...
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 argument for methods if args[0] == 'self': def wrapper(self, response, **kwargs): callback = create_bound_method(method_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
@wraps(fn) def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data return fn(*args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 callin...
@wraps(fn) def wrapper(*args, **kwargs): try: jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data except (NoAuthorizationError, InvalidHeaderError): pass return fn(*args, **kwargs) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 retur...
secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token, secret, algorithms=[algorithm], audience=audience)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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['flask-jwt-simple'] = self # Set all the default configurations for this extension self._set_default_configuration_options(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def category(**kwargs): """Get a category."""
if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: path = None return Fred().series(path, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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') path = 'releases' else: path = None return Fred().source(path, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._request = request return self._output(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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': location = location.rstrip('s') key = '%s_id' % location value = k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if use_feed_image: feed_image = item.feed_image if feed_image: image_complete_url = urljoin( self.get_site_url(), feed_image.file.url ) else: image_complete_url = "" content_field = getattr(item, se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 raise Http404
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 m...
# import here so models don't get loaded during app loading from django.contrib.contenttypes.models import ContentType from .models import MenuItem cache_key = 'django-treenav-menumodels' if sender == MenuItem: cache.delete(cache_key) menu_models = cache.get(cache_key) if not menu_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('admin:%s_%s_changelist' % info, cur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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('admin:%s_%s_changelist' % info, current_app=self.admin_site.name) return redirect(changelis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float: """ Calculate the dispersion between actual poi...
disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labels)])) # type: float return disp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_...
# Holder for reference dispersion results ref_dispersions = np.zeros(n_refs) # type: np.ndarray # For n_references, generate random sample and perform kmeans getting resulting dispersion of each loop for i in range(n_refs): # Create new random reference set ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_value, label)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_insert(self, query, values): """ Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The v...
# 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 given to us to insert. table = self.wrap_table(query.from__) if not isin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 i...
value = str(where['value']).zfill(2) value = self.parameter(value) return 'strftime(\'%s\', %s) %s %s'\ % (type, self.wrap(where['column']), where['operator'], value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_lock(self, query, value): """ Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value...
if isinstance(value, basestring): return value if value is True: return 'FOR UPDATE' elif value is False: return 'LOCK IN SHARE MODE'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile_foreign(self, blueprint, command, _): """ Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: T...
table = self.wrap_table(blueprint) on = self.wrap_table(command.on) columns = self.columnize(command.columns) on_columns = self.columnize(command.references if isinstance(command.references, list) else [command.r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) + ' ' + self._get_type(column) columns.append(self._add_modifiers(sql, blueprint, column)) return columns