<commit_before>from django import forms
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework import serializers, generics, status

from .models import CandidateRating


# Serializers define the API representation.
class RatingSerializer(serializers.ModelSerializer):

    candidate = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(is_staff=False))
    interviewer = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(is_staff=True), required=False)

    class Meta:
        model = CandidateRating
        fields = ('candidate', 'interviewer', 'rating')

    def __init__(self, *args, **kwargs):
        super(RatingSerializer, self).__init__(*args, **kwargs)
        kargs = kwargs.get('data', None)
        if not kargs:
            return


class RatingCreateUpdate(generics.GenericAPIView):
    """
    List all snippets, or create a new snippet.
    """
    permission_classes = (IsAdminUser,)
    queryset = CandidateRating.objects.all()
    serializer_class = RatingSerializer
    allowed_methods = ('POST',)

    def post(self, request, *args, **kwargs):
        # request.data['interviewer'] = request.user
        request_data_cpy = request.data.copy()
        request_data_cpy['interviewer'] = request.user.id
        serializer = RatingSerializer(data=request_data_cpy)
        if serializer.is_valid():
            try:
                # Allow Update only before all interviewers voted?
                cr = CandidateRating.objects.get(interviewer=request.user, candidate__id=request.data['candidate'])
                cr.rating = request.data['rating']
                cr.save()
                return Response(status=status.HTTP_200_OK)
            except CandidateRating.DoesNotExist:
                serializer.save()
                return Response(status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


def get_previous_candidates(request):
    """
    Loads Candidate Ratings
    """
    from django.db.models import Avg

    staff_size = User.objects.filter(is_staff=True).count()
    candidates = User.objects.filter(is_staff=False).order_by('date_joined')[:50]

    candidate_ratings=[]
    for candidate in candidates:
        rating = CandidateRating.objects.filter(candidate=candidate)

        s = { 'candidate': candidate }

        # All interviewers have rated candidate
        if rating.count() == staff_size:

            s['rating'] = rating.aggregate(Avg('rating')).values()[0]
            s['my_rating'] = rating.filter(interviewer=request.user)[0]
        else:
<commit_msg>Corrected update/create fn in rating candidate<commit_after>from django import forms
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework import serializers, generics, status

from .models import CandidateRating


# Serializers define the API representation.
class RatingSerializer(serializers.ModelSerializer):

    candidate = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(is_staff=False))
    interviewer = serializers.PrimaryKeyRelatedField(queryset=User.objects.filter(is_staff=True), required=False)

    class Meta:
        model = CandidateRating
        fields = ('candidate', 'interviewer', 'rating')

    def __init__(self, *args, **kwargs):
        super(RatingSerializer, self).__init__(*args, **kwargs)
        kargs = kwargs.get('data', None)
        if not kargs:
            return


class RatingCreateUpdate(generics.GenericAPIView):
    """
    List all snippets, or create a new snippet.
    """
    permission_classes = (IsAdminUser,)
    queryset = CandidateRating.objects.all()
    serializer_class = RatingSerializer
    allowed_methods = ('POST',)

    def post(self, request, *args, **kwargs):
        request_data_cpy = request.data.copy()
        request_data_cpy['interviewer'] = request.user.id
        serializer = RatingSerializer(data=request_data_cpy)
        if serializer.is_valid():
            serializer.save()
            return Response(status=status.HTTP_201_CREATED)
        else:
            try:
                # Allow Update only before all interviewers voted?
                cr = CandidateRating.objects.get(interviewer=request.user, candidate__id=request.data['candidate'])
                cr.rating = request.data['rating']
                cr.save()
                return Response(status=status.HTTP_200_OK)
            except CandidateRating.DoesNotExist:
                pass
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


def get_previous_candidates(request):
    """
    Loads Candidate Ratings
    """
    from django.db.models import Avg

    staff_size = User.objects.filter(is_staff=True).count()
    candidates = User.objects.filter(is_staff=False).order_by('date_joined')[:50]

    candidate_ratings=[]
    for candidate in candidates:
        rating = CandidateRating.objects.filter(candidate=candidate)

        s = { 'candidate': candidate }

        # All interviewers have rated candidate
        if rating.count() == staff_size:

            s['rating'] = rating.aggregate(Avg('rating')).values()[0]
            s['my_rating'] = rating.filter(interviewer=request.user)[0]
        else:

{'fraction_non_alphanumeric': 0.10075659715814726, 'fraction_numerical': 0.004797933198007013, 'mean_word_length': 3.2244738893219016, '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': '2836228', 'n_tokens_mistral': 1525, 'n_tokens_neox': 1470, 'n_words': 311}