<commit_before>"View definitions."
import zipfile
import os
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Count, Q
from django.http import HttpResponse, JsonResponse, Http404, HttpResponseBadRequest
from django.views.generic.detail import DetailView
from django.contrib.gis.geos import Polygon
from busstops.models import Region, StopPoint, AdminArea, Locality, District, Operator, Service
from timetables import timetable


DIR = os.path.dirname(__file__)


def index(request):
    "The home page with a list of regions"
    context = {
        'regions': Region.objects.all()
    }
    return render(request, 'index.html', context)


def cookies(request):
    "Cookie policy"
    return render(request, 'cookies.html')


def data(request):
    "Data sources"
    return render(request, 'data.html')


def hugemap(request):
    "The biggish JavaScript map"
    return render(request, 'map.html')


def stops(request):
    """
    JSON endpoint accessed by the JavaScript map,
    listing the active StopPoints within a rectangle,
    in standard GeoJSON format
    """

    try:
        bounding_box = Polygon.from_bbox(
            [request.GET[key] for key in ('xmin', 'ymin', 'xmax', 'ymax')]
        )
    except:
        return HttpResponseBadRequest()

    results = StopPoint.objects.filter(
        latlong__within=bounding_box, active=True
    )

    data = {
        'type': 'FeatureCollection',
        'features': []
    }
    for stop in results:
        data['features'].append(
            {
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': [stop.latlong.x, stop.latlong.y]
                },
                'properties': {
                    'name': str(stop),
                    'url': stop.get_absolute_url()
                    }
                }
            )
    return JsonResponse(data)


def search(request):
    """
    A list of up to 10 localities
    whose names all contain the `request.GET['q']` string
    """
    data = []
    query = request.GET.get('q')
    if query:
        query = query.strip()
        for locality in Locality.objects.filter(name__icontains=query)[:12]:
            data.append({
                'name': locality.get_qualified_name(),
                'url':  locality.get_absolute_url()
            })
    return JsonResponse(data, safe=False)


class RegionDetailView(DetailView):
    "A single region and the administrative areas in it"<commit_msg>Use a slightly less dumb locality search query (can now search for 'King's Lynn' by typing a non-curly apostrope)<commit_after>"View definitions."
import zipfile
import os
import re
import operator
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Q
from django.http import HttpResponse, JsonResponse, Http404, HttpResponseBadRequest
from django.views.generic.detail import DetailView
from django.contrib.gis.geos import Polygon
from busstops.models import Region, StopPoint, AdminArea, Locality, District, Operator, Service
from timetables import timetable


DIR = os.path.dirname(__file__)


def index(request):
    "The home page with a list of regions"
    context = {
        'regions': Region.objects.all()
    }
    return render(request, 'index.html', context)


def cookies(request):
    "Cookie policy"
    return render(request, 'cookies.html')


def data(request):
    "Data sources"
    return render(request, 'data.html')


def hugemap(request):
    "The biggish JavaScript map"
    return render(request, 'map.html')


def stops(request):
    """
    JSON endpoint accessed by the JavaScript map,
    listing the active StopPoints within a rectangle,
    in standard GeoJSON format
    """

    try:
        bounding_box = Polygon.from_bbox(
            [request.GET[key] for key in ('xmin', 'ymin', 'xmax', 'ymax')]
        )
    except:
        return HttpResponseBadRequest()

    results = StopPoint.objects.filter(
        latlong__within=bounding_box, active=True
    )

    return JsonResponse({
        'type': 'FeatureCollection',
        'features': [{
            'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': [stop.latlong.x, stop.latlong.y]
            },
            'properties': {
                'name': str(stop),
                'url': stop.get_absolute_url()
            }
        } for stop in results]
    })


def search(request):
    """
    A list of up to 10 localities
    whose names all contain the `request.GET['q']` string
    """
    data = []
    term = request.GET.get('q')
    if term:
        parts = re.split('[^\w]', term)
        query = reduce(operator.and_, (Locality.objects.filter(name__icontains=part) for part in parts))

        data = [{
            'name': locality.get_qualified_name(),
            'url':  locality.get_absolute_url()
        } for locality in query[:12]]

    return JsonResponse(data, safe=False)


class RegionDetailView(DetailView):
    "A single region and the administrative areas in it"
{'fraction_non_alphanumeric': 0.10786034718158767, 'fraction_numerical': 0.0039009167154281255, 'mean_word_length': 2.536551724137931, '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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1952502', 'n_tokens_mistral': 1506, 'n_tokens_neox': 1429, 'n_words': 418}