<commit_before>from collections import Counter
import datetime
from dateutil import parser as dateutil_parser
import itertools
import json
import math
import pytz
import requests

from django.conf import settings
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt

from braces.views import LoginRequiredMixin
from extra_views import ModelFormSetView
from rest_framework import permissions, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes

from periods import forms as period_forms, models as period_models, serializers


DATE_FORMAT = "%Y-%m-%d"


class FlowEventViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.FlowEventSerializer
    filter_class = serializers.FlowEventFilter

    def get_queryset(self):
        return period_models.FlowEvent.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class StatisticsViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.StatisticsSerializer

    def get_queryset(self):
        return period_models.Statistics.objects.filter(user=self.request.user)

    def list(self, request, *args, **kwargs):
        # Only return a single statistics object, for the authenticated user
        min_timestamp = request.query_params.get('min_timestamp')
        try:
            min_timestamp = datetime.datetime.strptime(min_timestamp, DATE_FORMAT)
            min_timestamp = pytz.timezone(request.user.timezone.zone).localize(min_timestamp)
        except TypeError:
            min_timestamp = period_models.today()
        queryset = self.filter_queryset(self.get_queryset())
        instance = queryset[0]
        instance.set_start_date_and_day(min_timestamp)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


@csrf_exempt
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def api_authenticate(request):
    user = None
    data = None
    status_code = 400
    error = None

    try:
        data = json.loads(request.body.decode())
    except ValueError:
        error = "Could not parse body as JSON"

    if not error:
        try:
            email = data['email']
            password = data['password']
            user = auth.authenticate(username=email, password=password)
            if not user:
                status_code = 401
                error = "Invalid credentials"
        except KeyError as e:
            error = "Missing required field '%s'" % e.args[0]

    if user:
        return JsonResponse({'token': user.auth_token.key})

    return JsonResponse({'error': error}, status=status_code)


@api_view(['GET'])
def aeris(request):
    moon_phase_url = '%s/sunmoon/moonphases' % settings.AERIS_URL
    from_date = request.GET.get('min_timestamp')
    to_date = request.GET.get('max_timestamp')
    params = {
        'client_id': settings.AERIS_CLIENT_ID,
        'client_secret': settings.AERIS_CLIENT_SECRET,
        'limit': 8,
        'from': from_date,
        'to': to_date,
    }
    result = requests.get(moon_phase_url, params)
    return JsonResponse(result.json())


@login_required
def period_form(request, period_id=None):
    # e.g. /period_form/?timestamp=2015-08-19T08:31:24-07:00
    user_timezone = pytz.timezone(request.user.timezone.zone)
    try:
        flow_event = period_models.FlowEvent.objects.get(pk=int(period_id))
        flow_event.timestamp = flow_event.timestamp.astimezone(user_timezone)
    except (TypeError, period_models.FlowEvent.DoesNotExist):
        timestamp = request.GET.get('timestamp')
        try:
            timestamp = dateutil_parser.parse(timestamp)
        except AttributeError:
            timestamp = period_models.today().astimezone(user_timezone)
        flow_event = period_models.FlowEvent(timestamp=timestamp)
        if timestamp:
            yesterday = timestamp - datetime.timedelta(days=1)
            yesterday_start = yesterday.replace(hour=0, minute=0, second=0)
            yesterday_events = period_models.FlowEvent.objects.filter(
                timestamp__gte=yesterday_start, timestamp__lte=timestamp)
            if not yesterday_events.count():
                flow_event.first_day = True
    flow_event.timestamp = flow_event.timestamp.replace(tzinfo=pytz.utc)
    form = period_forms.PeriodForm(instance=flow_event)
    data = {
        'form': form,
    }
    return render_to_response('periods/period_form.html', data,
                              context_instance=RequestContext(request))


class FlowEventFormSetView(LoginRequiredMixin, ModelFormSetView):
    model = period_models.FlowEvent
    exclude = ['user']

    def get_queryset(self):
        queryset = self.model.objects.filter(user=self.request.user).order_by('-timestamp')
        return queryset


@login_required
def calendar(request):
    data = {
        'periods_url': reverse('periods-list'),
        'statistics_url': reverse('statistics-list'),
        'period_form_url': reverse('period_form'),
        'aeris_url': reverse('aeris'),
    }

    return render_to_response('periods/calendar.html', data,
                              context_instance=RequestContext(request))


@login_required
def cycle_length_frequency(request):
    cycle_lengths = request.user.get_cycle_lengths()
    data = {}
    if cycle_lengths:
        cycle_counter = Counter(cycle_lengths)<commit_msg>Added blank forms to period edit view<commit_after>from collections import Counter
import datetime
from dateutil import parser as dateutil_parser
import itertools
import json
import math
import pytz
import requests

from django.conf import settings
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt

from braces.views import LoginRequiredMixin
from extra_views import ModelFormSetView
from rest_framework import permissions, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes

from periods import forms as period_forms, models as period_models, serializers


DATE_FORMAT = "%Y-%m-%d"


class FlowEventViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.FlowEventSerializer
    filter_class = serializers.FlowEventFilter

    def get_queryset(self):
        return period_models.FlowEvent.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class StatisticsViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.StatisticsSerializer

    def get_queryset(self):
        return period_models.Statistics.objects.filter(user=self.request.user)

    def list(self, request, *args, **kwargs):
        # Only return a single statistics object, for the authenticated user
        min_timestamp = request.query_params.get('min_timestamp')
        try:
            min_timestamp = datetime.datetime.strptime(min_timestamp, DATE_FORMAT)
            min_timestamp = pytz.timezone(request.user.timezone.zone).localize(min_timestamp)
        except TypeError:
            min_timestamp = period_models.today()
        queryset = self.filter_queryset(self.get_queryset())
        instance = queryset[0]
        instance.set_start_date_and_day(min_timestamp)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


@csrf_exempt
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def api_authenticate(request):
    user = None
    data = None
    status_code = 400
    error = None

    try:
        data = json.loads(request.body.decode())
    except ValueError:
        error = "Could not parse body as JSON"

    if not error:
        try:
            email = data['email']
            password = data['password']
            user = auth.authenticate(username=email, password=password)
            if not user:
                status_code = 401
                error = "Invalid credentials"
        except KeyError as e:
            error = "Missing required field '%s'" % e.args[0]

    if user:
        return JsonResponse({'token': user.auth_token.key})

    return JsonResponse({'error': error}, status=status_code)


@api_view(['GET'])
def aeris(request):
    moon_phase_url = '%s/sunmoon/moonphases' % settings.AERIS_URL
    from_date = request.GET.get('min_timestamp')
    to_date = request.GET.get('max_timestamp')
    params = {
        'client_id': settings.AERIS_CLIENT_ID,
        'client_secret': settings.AERIS_CLIENT_SECRET,
        'limit': 8,
        'from': from_date,
        'to': to_date,
    }
    result = requests.get(moon_phase_url, params)
    return JsonResponse(result.json())


@login_required
def period_form(request, period_id=None):
    # e.g. /period_form/?timestamp=2015-08-19T08:31:24-07:00
    user_timezone = pytz.timezone(request.user.timezone.zone)
    try:
        flow_event = period_models.FlowEvent.objects.get(pk=int(period_id))
        flow_event.timestamp = flow_event.timestamp.astimezone(user_timezone)
    except (TypeError, period_models.FlowEvent.DoesNotExist):
        timestamp = request.GET.get('timestamp')
        try:
            timestamp = dateutil_parser.parse(timestamp)
        except AttributeError:
            timestamp = period_models.today().astimezone(user_timezone)
        flow_event = period_models.FlowEvent(timestamp=timestamp)
        if timestamp:
            yesterday = timestamp - datetime.timedelta(days=1)
            yesterday_start = yesterday.replace(hour=0, minute=0, second=0)
            yesterday_events = period_models.FlowEvent.objects.filter(
                timestamp__gte=yesterday_start, timestamp__lte=timestamp)
            if not yesterday_events.count():
                flow_event.first_day = True
    flow_event.timestamp = flow_event.timestamp.replace(tzinfo=pytz.utc)
    form = period_forms.PeriodForm(instance=flow_event)
    data = {
        'form': form,
    }
    return render_to_response('periods/period_form.html', data,
                              context_instance=RequestContext(request))


class FlowEventFormSetView(LoginRequiredMixin, ModelFormSetView):
    model = period_models.FlowEvent
    exclude = ['user']
    extra = 10

    def get_queryset(self):
        queryset = self.model.objects.filter(user=self.request.user).order_by('timestamp')
        return queryset


@login_required
def calendar(request):
    data = {
        'periods_url': reverse('periods-list'),
        'statistics_url': reverse('statistics-list'),
        'period_form_url': reverse('period_form'),
        'aeris_url': reverse('aeris'),
    }

    return render_to_response('periods/calendar.html', data,
                              context_instance=RequestContext(request))


@login_required
def cycle_length_frequency(request):
    cycle_lengths = request.user.get_cycle_lengths()
    data = {}
    if cycle_lengths:
        cycle_counter = Counter(cycle_lengths)
{'fraction_non_alphanumeric': 0.09090909090909091, 'fraction_numerical': 0.005520096601690529, 'mean_word_length': 3.423884013735216, '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': '1825691', 'n_tokens_mistral': 3373, 'n_tokens_neox': 3299, 'n_words': 677}