output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
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...
Write a Python 3 script to return the data of the placeholder fields.
You are a Python code architect, reviewing and designing scalable and efficient code
Return all allowed plugins for the current model.
Can you tell what is the following Python 3 function doing def get_all_allowed_plugins(self): # 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 ...
As a Python code composer, you craft elegant and concise scripts.
Create a new MarkupItem model that saves itself in a single language.
Can you generate the documentation for the following Python 3 function def _create_markup_model(fixed_language): title = backend.LANGUAGE_NAMES.get(fixed_language) or fixed_language objects = MarkupLanguageManager(fixed_language) def save(self, *args, **kwargs): self.language = fixed_language ...
You are a Python code generator, capable of creating scripts from specifications.
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...
Create a Python 3 function to return a PlaceholderFormField instance for this database Field.
As a Python code composer, you craft elegant and concise scripts.
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...
Create a Python 3 function to get the set of plugins that this field may display.
You are a Python code analyst, evaluating scripts for potential improvements.
Internal method used to return the value of the object instance.
Can you tell what is the following Python 3 function doing def value_from_object(self, obj): try: # not using self.attname, access the descriptor instead. placeholder = getattr(obj, self.name) except Placeholder.DoesNotExist: return None # Still allow ModelForm / ad...
As a Python code composer, you craft elegant and concise scripts.
Return True if the contentitem can be cached output.
Explain what the following Python 3 code does def can_use_cached_output(self, contentitem): return contentitem.plugin.search_output and not contentitem.plugin.search_fields \ and super(SearchRenderingPipe, self).can_use_cached_output(contentitem)
As a Python code analyst, you investigate and solve complex coding mysteries
Render the item - but render as search text instead.
Given the following Python 3 function, write the documentation def render_item(self, contentitem): 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 pl...
You are a Python code generator, capable of creating scripts from specifications.
Dynamically generate genuine django inlines for all registered content item types.
Given the following Python 3 function, write the documentation def get_content_item_inlines(plugins=None, base=BaseContentItemInline): COPY_FIELDS = ( 'form', 'raw_id_fields', 'filter_vertical', 'filter_horizontal', 'radio_fields', 'prepopulated_fields', 'formfield_overrides', 'readonly_fields', ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the list of OEmbed providers.
Can you generate the documentation for the following Python 3 function def get_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:...
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a Python 3 function for building the provider list from the app settings.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 function that can fetch the OEmbed object from the registry and return the response as dictionary.
As a python code expert, you are capable of creating scripts from specifications.
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: ...
Can you create a Python 3 function that returns all plugins grouped by category.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a tuple of plugin model choices suitable for a select field.
Explain what the following Python 3 code does def plugin_categories_to_choices(categories): choices = [] for category, items in categories.items(): if items: plugin_tuples = tuple((plugin.type_name, plugin.verbose_name) for plugin in items) if category: choices.ap...
As a Python code analyst, you investigate and solve complex coding mysteries
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 ...
Write a Python 3 function that can add a new Media object to a new Media object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a dummy Request instance populated with cms specific attributes.
How would you explain what the following Python 3 function does def get_dummy_request(language=None): 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=h...
You are a Python code generator, capable of creating scripts from specifications.
Returns the language code that should be used to render the content item.
Explain what the following Python 3 code does def get_render_language(contentitem): 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 o...
As a python code expert, you are capable of creating scripts from specifications.
This function is used to optimize the logging level of a logger.
Given the following Python 3 function, write the documentation 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 = logger.isEnabledFor(log_level) if not is_level_logged: s...
As a Python code analyst, you investigate and solve complex coding mysteries
Extract the search fields from the model.
Can you generate a brief explanation for the following Python 3 code def get_search_field_values(contentitem): plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not c...
You are a Python code architect, reviewing and designing scalable and efficient code
Return the metadata about a layout
Make a summary of the following Python 3 code 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_CHOICES) if template_name not in templates: json...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you code a function in Python 3 to apply soft hyphenation to the text.
As a python code expert, you are capable of creating scripts from specifications.
Get the cached output for a placeholder.
Can you tell what is the following Python 3 function doing 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) cache_key = get_placeholder_cache_key_for_pare...
As a Python code composer, you craft elegant and concise scripts.
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...
Can you implement a function in Python 3 that renders a placeholder and returns the rendered HTML output.
You are a Python code generator, capable of creating scripts from specifications.
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. ...
How would you implement a function in Python 3 that renders a list of items as HTML string.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a function in Python 3 to render a placeholder object to search text.
You are a Python code architect, reviewing and designing scalable and efficient code
Render the placeholder field.
Make a summary of the following Python 3 code def render(self, name, value, attrs=None, renderer=None): other_instance_languages = None if value and value != "-DUMMY-": if get_parent_language_code(self.parent_object): # Parent is a multilingual object, provide information ...
You are a Python code generator, capable of creating scripts from specifications.
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() ...
Can you create a Python 3 function that gets the set of plugins that this widget should display.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you code a function in Python 3 to return a redirect response for the exception.
As a Python code composer, you craft elegant and concise scripts.
Render the text using the template filters provided by Django.
How would you explain what the following Python 3 function does def render_text(text, language=None): # 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( ...
You are a Python code generator, capable of creating scripts from specifications.
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)
Write a Python 3 script for reading the derived table data for all objects tracked as remaining.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a Python 3 function for returning the output in the correct ordering.
As a python code expert, you are capable of creating scripts from specifications.
Render the items in the given placeholder.
Can you generate the documentation for the following Python 3 function def render_items(self, placeholder, items, parent_object=None, template_name=None, cachable=None): # Unless it was done before, disable polymorphic effects. is_queryset = False if hasattr(items, "non_polymorphic"): ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you implement a function in Python 3 that fetches all items from the cache and store them in the result.
As a Python code composer, you craft elegant and concise scripts.
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
Implement a function in Python 3 to tell whether the code should try reading cached output for the given contentitem.
You are a Python code analyst, evaluating scripts for potential improvements.
Render a list of items that didn t exist in the cache yet.
Can you generate the documentation for the following Python 3 function 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) exc...
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you write a function in Python 3 where it renders the individual item.
You are a Python code generator, capable of creating scripts from specifications.
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: ...
How would you implement a function in Python 3 that combines all rendered items with a template.
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function for collecting all HTML from the rendered items in the correct ordering.
You are a Python code analyst, evaluating scripts for potential improvements.
Render a single placeholder.
Can you tell what is the following Python 3 function doing def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): placeholder_name = get_placeholder_debug_name(placeholder) logger.debug("Rendering placeholder ...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function that can register a plugin with the CMS.
As a python code expert, you are capable of creating scripts from specifications.
Return the plugins which are supported in the given placeholder name.
How would you explain what the following Python 3 function does 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 = slot_config.get('plugins') if not plugins...
As a Python code composer, you craft elegant and concise scripts.
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...
Create a Python 3 function for returning a list of plugins by name or class name.
You are a Python code generator, capable of creating scripts from specifications.
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()]
Create a Python 3 function for returning all model classes which are exposed by plugins.
As a Python code composer, you craft elegant and concise scripts.
Returns the corresponding plugin for a given model class.
Given the following Python 3 function, write the documentation 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 between model instance ...
You are a Python code analyst, evaluating scripts for potential improvements.
Internal function to import all plugin packages.
Can you generate a brief explanation for the following Python 3 code 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() if...
As a Python code translator, you convert algorithms and pseudocode into 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...
Write a Python 3 script for applying all filters for a given HTML snippet.
You are a Python code generator, capable of creating scripts from specifications.
Apply pre filters to the HTML source code.
Given the following Python 3 function, write the documentation 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) return html
As a Python code composer, you craft elegant and concise scripts.
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...
Implement a function in Python 3 to apply post processing functions to the given HTML.
As a Python code composer, you craft elegant and concise scripts.
Clean the plugin output cache of a rendered plugin.
Explain what the following Python 3 code does def clear_commentarea_cache(comment): parent = comment.content_object for instance in CommentsAreaItem.objects.parent(parent): instance.clear_cache()
You are a Python code architect, reviewing and designing scalable and efficient code
Filter to the given site only give content relevant for that site.
Given the following Python 3 function, write the documentation 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 sites: ...
As a Python code composer, you craft elegant and concise scripts.
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
How would you implement a function in Python 3 that returns a single site instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the list of PlaceholderData objects found in a template.
Given the following Python 3 function, write the documentation def get_template_placeholder_data(template): # Find the instances. nodes = get_node_instances(template, PagePlaceholderNode) # Avoid duplicates, wrap in a class. names = set() result = [] for pageplaceholdernode in nodes: da...
As a python code expert, you are capable of creating scripts from specifications.
Inspect a single model.
Here you have a function in Python 3, explain what it does 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, (PluginUrlField, models.URLField))) file_fields = sorted(f for f in model._meta.fields if ...
As a python code expert, you are capable of creating scripts from specifications.
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') ...
How would you implement a function in Python 3 that takes all <img src =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. srcset =.. src...
You are a Python code generator, capable of creating scripts from specifications.
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
Implement a function in Python 3 to extract the set of images from a source set.
You are a Python code generator, capable of creating scripts from specifications.
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 # ...
Write a Python 3 function for deleting the translation from the ContentItems.
As a Python code translator, you convert algorithms and pseudocode into 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...
Create a Python 3 function to take an HTML fragment and processes it using html5lib to ensure that the HTML is well - formed.
As a Python code translator, you convert algorithms and pseudocode into 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() ...
Create a Python 3 function to return the contents as a dictionary for client - side export.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a Python 3 function for forwarding the MarkupItem model to the correct proxy model that implements the given language.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a FormSet subclass with initial data for the current object.
Can you generate the documentation for the following Python 3 function 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': p.slot, 'title': p.t...
As a python code expert, you are capable of creating scripts from specifications.
Create the inlines for the admin including the placeholder and contentitem inlines.
Can you tell what is the following Python 3 function doing def get_inline_instances(self, request, *args, **kwargs): inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] inlinetypes = self.get_extra_inlines() for Inline...
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 function for returning the placeholder data as dictionary.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns method or function arguments.
Make a summary of the following Python 3 code def get_args(method_or_func): 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
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator that will decorate a view function with this decorator that will check the request for a valid JWT and put it into the application context.
Can you generate a brief explanation for the following Python 3 code def jwt_optional(fn): @wraps(fn) def wrapper(*args, **kwargs): try: jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data except (NoAuthorizationError, InvalidHeaderError): pass ...
You are a Python code architect, reviewing and designing scalable and efficient code
Decodes a JWT encoded string into a base64 - encoded token.
Can you generate the documentation for the following Python 3 function def decode_jwt(encoded_token): secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token, secret, algorithms=[algorithm], audience=audience)
As a Python code analyst, you investigate and solve complex coding mysteries
Register this extension with the flask app
Given the following Python 3 function, write the documentation 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['flask-jwt-simple'] = self # Set all the def...
You are a Python code architect, reviewing and designing scalable and efficient code
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) ...
Write a Python 3 function for setting the error handler callbacks used by this extension.
You are a Python code architect, reviewing and designing scalable and efficient code
Sets the default configuration options used by this extension.
Explain what the following Python 3 code does 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('JWT_HEADER_TYPE', 'Bearer') # How long an a token created wit...
As a Python code analyst, you investigate and solve complex coding mysteries
Get all releases of economic data.
Make a summary of the following Python 3 code def releases(release_id=None, **kwargs): if not 'id' in kwargs and release_id is not None: kwargs['release_id'] = release_id return Fred().release(**kwargs) return Fred().releases(**kwargs)
As a Python code composer, you craft elegant and concise scripts.
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: ...
How would you implement a function in Python 3 that gets an economic data series.
As a Python code composer, you craft elegant and concise scripts.
Get a source of economic data.
Can you tell what is the following Python 3 function doing def source(source_id=None, **kwargs): 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('re...
As a Python code analyst, you investigate and solve complex coding mysteries
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)
Create a Python 3 function for getting the sources of economic data.
You are a Python code analyst, evaluating scripts for potential improvements.
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
Write a Python 3 function that can create the URL path with the Fred endpoint and given arguments.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you implement a function in Python 3 that performs a GET request againt the Fred API endpoint.
You are a Python code analyst, evaluating scripts for potential improvements.
Format GET request s parameters from keywords.
Given the following Python 3 function, write the documentation def _get_keywords(self, location, keywords): if 'xml' in keywords: keywords.pop('xml') self.xml = True else: keywords['file_type'] = 'json' if 'id' in keywords: if location != 'series':...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a dictionary that is used with the add_item call of the custom feed generator.
Can you generate a brief explanation for the following Python 3 code 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_image.file.url ...
As a python code expert, you are capable of creating scripts from specifications.
This is a sample view that can be used to provide custom handlers for undefined menu items on a per - item basis.
Here you have a function in Python 3, explain what it does 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 Http404
You are a Python code generator, capable of creating scripts from specifications.
Refresh all the cached menu item HREFs in the database.
How would you explain what the following Python 3 function does def refresh_hrefs(self, request): 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, ...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Can you create a Python 3 function that removes all MenuItems from Cache.
As a Python code composer, you craft elegant and concise scripts.
Rebuilds the tree and clears the cache.
Can you generate the documentation for the following Python 3 function 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)
You are a Python code analyst, evaluating scripts for potential improvements.
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()
Create a Python 3 function to rebuild the tree after saving items related to parent.
As a python code expert, you are capable of creating scripts from specifications.
Calculate the dispersion between actual points and their assigned centroids
Given the following Python 3 function, write the documentation def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float: disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labels)])) # type: float return disp
As a Python code composer, you craft elegant and concise scripts.
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...
How would you implement a function in Python 3 that calculates the gap value of the given data n_refs and n_clusters and return the resutling gap value and n_clusters.
You are a Python code analyst, evaluating scripts for potential improvements.
Process gap stat using pure rust
Given the following Python 3 function, write the documentation def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): from gap_statistic.rust import gapstat for label, gap_value in gapstat.optimal_k(X, list(cluster_array)): yield (gap_value,...
You are a Python code generator, capable of creating scripts from specifications.
Process calling of. calculate_gap method using joblib.
Given the following Python 3 function, write the documentation def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): if Parallel is None: raise EnvironmentError('joblib is not installed; cannot use joblib as the parallel backend!') with ...
As a python code expert, you are capable of creating scripts from specifications.
Process calling of. calculate_gap method using the multiprocessing library.
Here you have a function in Python 3, explain what it does def _process_with_multiprocessing(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): with ProcessPoolExecutor(max_workers=self.n_jobs) as executor: jobs = [executor.submit(self._calculate_gap, X, n_refs, n_cl...
You are a Python code analyst, evaluating scripts for potential improvements.
Process calling of. calculate_gap method using no parallel backend ; simple for loop
Make a summary of the following Python 3 code def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters) for n_clusters in cluster_array]: ...
You are a Python code generator, capable of creating scripts from specifications.
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()
Create a Python 3 function for getting the last migration batch.
You are a Python code generator, capable of creating scripts from specifications.
Compile an insert SQL statement for the given values.
Can you tell what is the following Python 3 function doing 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 o...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the ALTER TABLE SQL statement for the table diff.
How would you explain what the following Python 3 function does def get_alter_table_sql(self, diff): sql = [] for column_diff in diff.changed_columns.values(): if self.is_unchanged_binary_column(column_diff): continue old_column_name = column_diff.old_column_nam...
You are a Python code analyst, evaluating scripts for potential improvements.
Compile a date based where clause
Can you tell what is the following Python 3 function doing def _date_based_where(self, type, query, where): value = str(where['value']).zfill(2) value = self.parameter(value) return 'strftime(\'%s\', %s) %s %s'\ % (type, self.wrap(where['column']), where['operat...
You are a Python code analyst, evaluating scripts for potential improvements.
Compile a select query into SQL
Can you tell what is the following Python 3 function doing def compile_select(self, query): sql = super(MySqlQueryGrammar, self).compile_select(query) if query.unions: sql = '(%s) %s' % (sql, self._compile_unions(query)) return sql
As a Python code translator, you convert algorithms and pseudocode into 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...
Write a Python 3 function for compiling the lock into SQL
As a python code expert, you are capable of creating scripts from specifications.
Compile an update statement into SQL
Can you generate the documentation for the following Python 3 function def compile_update(self, query, values): sql = super(MySqlQueryGrammar, self).compile_update(query, values) if query.orders: sql += ' %s' % self._compile_orders(query, query.orders) if query.limit_: ...
As a Python code composer, you craft elegant and concise scripts.
Collapse the collection items into a single element
Can you tell what is the following Python 3 function doing def collapse(self): results = [] if isinstance(self._items, dict): items = self._items.values() for values in items: if isinstance(values, Collection): values = values.all() results ...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 function that can determine if an element is in the collection.
As a Python code analyst, you investigate and solve complex coding mysteries
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)
Write a Python 3 script to get a list with the values of a given key.
As a Python code composer, you craft elegant and concise scripts.
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...
Can you implement a function in Python 3 that runs a map over each of the items in the collection.
You are a Python code analyst, evaluating scripts for potential improvements.
Return only unique items from the collection list.
Here you have a function in Python 3, explain what it does 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(x))])
You are a Python code analyst, evaluating scripts for potential improvements.
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
Create a Python 3 function to load a set of relationships onto the collection.
As a python code expert, you are capable of creating scripts from specifications.