<commit_before>"""Select2 view implementation."""

import collections
# import json

from dal.views import BaseQuerySetView, ViewMixin

from django import http
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils.translation import ugettext as _
from django.views.generic.list import View


class Select2ViewMixin(object):
    """View mixin to render a JSON response for Select2."""

    def get_results(self, context):
        """Return data for the 'results' key of the response."""
        return [
            {
                'id': self.get_result_value(result),
                'text': self.get_result_label(result),
                'selected_text': self.get_selected_result_label(result),
            } for result in context['object_list']
        ]

    def get_create_option(self, context, q):
        """Form the correct create_option to append to results."""
        create_option = []
        display_create_option = False
        if self.create_field and q:
            page_obj = context.get('page_obj', None)
            if page_obj is None or page_obj.number == 1:
                display_create_option = True

            # Don't offer to create a new option if a
            # case-insensitive) identical one already exists
            existing_options = (self.get_result_label(result).lower()
                                for result in context['object_list'])
            if q.lower() in existing_options:
                display_create_option = False

        if display_create_option and self.has_add_permission(self.request):
            create_option = [{
                'id': q,
                'text': _('Create "%(new_value)s"') % {'new_value': q},
                'create_id': True,
            }]
        return create_option

    def render_to_response(self, context):
        """Return a JSON response in Select2 format."""
        q = self.request.GET.get('q', None)

        create_option = self.get_create_option(context, q)

        return http.JsonResponse(
            {
                'results': self.get_results(context) + create_option,
                'pagination': {
                    'more': self.has_more(context)
                }
            })


class Select2QuerySetView(Select2ViewMixin, BaseQuerySetView):
    """List options for a Select2 widget."""


class Select2ListView(ViewMixin, View):
    """Autocomplete from a list of items rather than a QuerySet."""

    def get_list(self):
        """Return the list strings from which to autocomplete."""
        return []

    def get(self, request, *args, **kwargs):
        """Return option list json response."""
        results = self.get_list()
        create_option = []
        if self.q:
            results = self.autocomplete_results(results)
            if hasattr(self, 'create'):
                create_option = [{
                    'id': self.q,
                    'text': _('Create "%(new_value)s"') % {'new_value': q},
                    'create_id': True
                }]
        return http.JsonResponse({
            'results': self.results(results) + create_option
        }, content_type='application/json')

    def autocomplete_results(self, results):
        """Return list of strings that match the autocomplete query."""
        return [x for x in results if self.q.lower() in x.lower()]

    def results(self, results):
        """Return the result dictionary."""
        return [dict(id=x, text=x) for x in results]

    def post(self, request):
        """Add an option to the autocomplete list.

        If 'text' is not defined in POST or self.create(text) fails, raises
        bad request. Raises ImproperlyConfigured if self.create if not defined.
        """
        if not hasattr(self, 'create'):
            raise ImproperlyConfigured('Missing "create()"')

        text = request.POST.get('text', None)

        if text is None:
            return http.HttpResponseBadRequest()
<commit_msg>Change q to self.q because q does not exist in that scope<commit_after>"""Select2 view implementation."""

import collections
# import json

from dal.views import BaseQuerySetView, ViewMixin

from django import http
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils.translation import ugettext as _
from django.views.generic.list import View


class Select2ViewMixin(object):
    """View mixin to render a JSON response for Select2."""

    def get_results(self, context):
        """Return data for the 'results' key of the response."""
        return [
            {
                'id': self.get_result_value(result),
                'text': self.get_result_label(result),
                'selected_text': self.get_selected_result_label(result),
            } for result in context['object_list']
        ]

    def get_create_option(self, context, q):
        """Form the correct create_option to append to results."""
        create_option = []
        display_create_option = False
        if self.create_field and q:
            page_obj = context.get('page_obj', None)
            if page_obj is None or page_obj.number == 1:
                display_create_option = True

            # Don't offer to create a new option if a
            # case-insensitive) identical one already exists
            existing_options = (self.get_result_label(result).lower()
                                for result in context['object_list'])
            if q.lower() in existing_options:
                display_create_option = False

        if display_create_option and self.has_add_permission(self.request):
            create_option = [{
                'id': q,
                'text': _('Create "%(new_value)s"') % {'new_value': q},
                'create_id': True,
            }]
        return create_option

    def render_to_response(self, context):
        """Return a JSON response in Select2 format."""
        q = self.request.GET.get('q', None)

        create_option = self.get_create_option(context, q)

        return http.JsonResponse(
            {
                'results': self.get_results(context) + create_option,
                'pagination': {
                    'more': self.has_more(context)
                }
            })


class Select2QuerySetView(Select2ViewMixin, BaseQuerySetView):
    """List options for a Select2 widget."""


class Select2ListView(ViewMixin, View):
    """Autocomplete from a list of items rather than a QuerySet."""

    def get_list(self):
        """Return the list strings from which to autocomplete."""
        return []

    def get(self, request, *args, **kwargs):
        """Return option list json response."""
        results = self.get_list()
        create_option = []
        if self.q:
            results = self.autocomplete_results(results)
            if hasattr(self, 'create'):
                create_option = [{
                    'id': self.q,
                    'text': _('Create "%(new_value)s"') % {'new_value': self.q},
                    'create_id': True
                }]
        return http.JsonResponse({
            'results': self.results(results) + create_option
        }, content_type='application/json')

    def autocomplete_results(self, results):
        """Return list of strings that match the autocomplete query."""
        return [x for x in results if self.q.lower() in x.lower()]

    def results(self, results):
        """Return the result dictionary."""
        return [dict(id=x, text=x) for x in results]

    def post(self, request):
        """Add an option to the autocomplete list.

        If 'text' is not defined in POST or self.create(text) fails, raises
        bad request. Raises ImproperlyConfigured if self.create if not defined.
        """
        if not hasattr(self, 'create'):
            raise ImproperlyConfigured('Missing "create()"')

        text = request.POST.get('text', None)

        if text is None:
            return http.HttpResponseBadRequest()

{'fraction_non_alphanumeric': 0.10337526466558725, 'fraction_numerical': 0.0022418732096151452, 'mean_word_length': 2.1689029202841357, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2850207', 'n_tokens_mistral': 2170, 'n_tokens_neox': 2077, 'n_words': 641}