<commit_before>from datetime import datetime

from django.shortcuts import render
from django.template import RequestContext
from django.http import Http404, HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.decorators import permission_required

from mittab.apps.tab.forms import TeamForm, TeamEntryForm, ScratchForm
from mittab.apps.tab.errors import *
from mittab.apps.tab.models import *
import mittab.libs.tab_logic as tab_logic
from mittab.libs.tab_logic import TabFlags, tot_speaks_deb, tot_ranks_deb, tot_speaks, tot_ranks

def view_teams(request):
    def flags(t):
        result = 0
        if t.checked_in:
            result |= TabFlags.TEAM_CHECKED_IN
        else:
            result |= TabFlags.TEAM_NOT_CHECKED_IN
        return result

    c_teams = [(t.pk, t.name, flags(t), TabFlags.flags_to_symbols(flags(t)))
               for t in Team.objects.all().order_by("name")]
    all_flags = [[TabFlags.TEAM_CHECKED_IN, TabFlags.TEAM_NOT_CHECKED_IN]]
    filters, symbol_text = TabFlags.get_filters_and_symbols(all_flags)
    return render(request, 'list_data.html', 
                             {'item_type':'team',
                              'title': "Viewing All Teams",
                              'item_list': c_teams,
                              'filters': filters,
                              'symbol_text': symbol_text})

def view_team(request, team_id):
    team_id = int(team_id)
    try:
        team = Team.objects.get(pk=team_id)
        stats = []
        stats.append(("Wins", tab_logic.tot_wins(team)))
        stats.append(("Total Speaks", tab_logic.tot_speaks(team)))
        stats.append(("Govs", tab_logic.num_govs(team)))
        stats.append(("Opps", tab_logic.num_opps(team)))
        stats.append(("Avg. Opp Wins", tab_logic.opp_strength(team)))
        stats.append(("Been Pullup", tab_logic.pull_up_count(team)))
        stats.append(("Hit Pullup", tab_logic.hit_pull_up_count(team)))
    except Team.DoesNotExist:
        return render(request, 'error.html', 
                                 {'error_type': "View Team",
                                  'error_name': str(team_id),
                                  'error_info':"No such Team"})
    if request.method == 'POST':
        form = TeamForm(request.POST,instance=team)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return render(request, 'error.html',
                                         {'error_type': "Team",
                                          'error_name': "["+form.cleaned_data['name']+"]",
                                          'error_info':"Team name cannot be validated, most likely a non-existent team"})
            return render(request, 'thanks.html', 
                                     {'data_type': "Team",
                                      'data_name': "["+form.cleaned_data['name']+"]"})
    else:
        form = TeamForm(instance=team)
        links = [('/team/'+str(team_id)+'/scratches/view/','Scratches for {}'.format(team.name), False)]
        for deb in team.debaters.all():
            links.append(('/debater/'+str(deb.id)+'/', "View %s" % deb.name, False))
        return render(request, 'data_entry.html', 
                                 {'title':"Viewing Team: %s"%(team.name),
                                  'form': form,
                                  'links': links,
                                  'team_obj':team,
                                  'team_stats':stats})

    return render(request, 'data_entry.html', 
                             {'form': form})

def enter_team(request):
    if request.method == 'POST':
        form = TeamEntryForm(request.POST)
        if form.is_valid():
            try:
                team = form.save()
            except ValueError:
                return render(request, 'error.html', 
                                         {'error_type': "Team",'error_name': "["+form.cleaned_data['name']+"]",
                                          'error_info':"Team name cannot be validated, most likely a duplicate school"})
            num_forms = form.cleaned_data['number_scratches']
            if num_forms > 0:
                return HttpResponseRedirect('/team/'+str(team.pk)+'/scratches/add/'+str(num_forms))
            else:
                return render(request, 'thanks.html', 
                                         {'data_type': "Team",
                                          'data_name': '[{}]'.format(team.name),
                                          'data_modification': 'CREATED',
                                          'enter_again': True})

    else:
        form = TeamEntryForm()
    return render(request, 'data_entry.html',
                             {'form': form, 'title': "Create Team"})
    
@permission_required('tab.team.can_delete', login_url="/403/")                               
def delete_team(request, team_id):
    team_id = int(team_id)
    try :
        team = Team.objects.get(pk=team_id)
        team.delete()
    except Team.DoesNotExist:
        return render(request, 'error.html', 
                                 {'error_type': "Team",
                                 'error_name': str(team_id),
                                 'error_info':"Team does not exist"})
    return render(request, 'thanks.html', 
                             {'data_type': "Team",
                              'data_name': "["+str(team_id)+"]",
                              'data_modification': 'DELETED'})

def add_scratches(request, team_id, number_scratches):
    try:
        team_id,number_scratches = int(team_id),int(number_scratches)
    except ValueError:
        return render(request, 'error.html', 
                                 {'error_type': "Scratch",'error_name': "Data Entry",
                                  'error_info':"I require INTEGERS!"})
    try:
        team = Team.objects.get(pk=team_id)
    except Team.DoesNotExist:
        return render(request, 'error.html', 
                                 {'error_type': "Add Scratches for Team",
                                  'error_name': str(team_id),
                                  'error_info':"No such Team"})
    if request.method == 'POST':
        forms = [ScratchForm(request.POST, prefix=str(i)) for i in range(1,number_scratches+1)]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return render(request, 'thanks.html', 
                                     {'data_type': "Scratches for team",
                                      'data_name': "["+str(team_id)+"]",
                                      'data_modification': "CREATED"})
    else:
        forms = [ScratchForm(prefix=str(i), initial={'team':team_id,'scratch_type':0}) for i in range(1,number_scratches+1)]
    return render(request, 'data_entry_multiple.html', 
                             {'forms': list(zip(forms,[None]*len(forms))),
                              'data_type':'Scratch',
                              'title':"Adding Scratch(es) for %s"%(team.name)})
    
def view_scratches(request, team_id):
    try:
        team_id = int(team_id)
    except ValueError:
        return render(request, 'error.html', 
                                 {'error_type': "Scratch",'error_name': "Delete",
                                  'error_info':"I require INTEGERS!"})
    scratches = Scratch.objects.filter(team=team_id)
    number_scratches = len(scratches)
    team = Team.objects.get(pk=team_id)
    if request.method == 'POST':
        forms = [ScratchForm(request.POST, prefix=str(i),instance=scratches[i-1]) for i in range(1,number_scratches+1)]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return render(request, 'thanks.html', 
                                     {'data_type': "Scratches for team",
                                      'data_name': "["+str(team_id)+"]",
                                      'data_modification': "EDITED"})
    else:
        forms = [ScratchForm(prefix=str(i), instance=scratches[i-1]) for i in range(1,len(scratches)+1)]
    delete_links = ["/team/"+str(team_id)+"/scratches/delete/"+str(scratches[i].id) for i in range(len(scratches))]
    links = [('/team/'+str(team_id)+'/scratches/add/1/','Add Scratch', False)]
    return render(request, 'data_entry_multiple.html', 
                             {'forms': list(zip(forms,delete_links)),
                              'data_type':'Scratch',
                              'links':links,
                              'title':"Viewing Scratch Information for %s"%(team.name)})

@permission_required('tab.tab_settings.can_change', login_url="/403/")
def all_tab_cards(request):
    all_teams = Team.objects.all()
    return render(request, 'all_tab_cards.html',
                              locals())

def pretty_tab_card(request, team_id):
    try:
        team_id = int(team_id)
    except:<commit_msg>Fix bug in links for scratches view<commit_after>from datetime import datetime

from django.shortcuts import render
from django.template import RequestContext
from django.http import Http404, HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.decorators import permission_required

from mittab.apps.tab.forms import TeamForm, TeamEntryForm, ScratchForm
from mittab.apps.tab.errors import *
from mittab.apps.tab.models import *
import mittab.libs.tab_logic as tab_logic
from mittab.libs.tab_logic import TabFlags, tot_speaks_deb, tot_ranks_deb, tot_speaks, tot_ranks

def view_teams(request):
    def flags(t):
        result = 0
        if t.checked_in:
            result |= TabFlags.TEAM_CHECKED_IN
        else:
            result |= TabFlags.TEAM_NOT_CHECKED_IN
        return result

    c_teams = [(t.pk, t.name, flags(t), TabFlags.flags_to_symbols(flags(t)))
               for t in Team.objects.all().order_by("name")]
    all_flags = [[TabFlags.TEAM_CHECKED_IN, TabFlags.TEAM_NOT_CHECKED_IN]]
    filters, symbol_text = TabFlags.get_filters_and_symbols(all_flags)
    return render(request, 'list_data.html', 
                             {'item_type':'team',
                              'title': "Viewing All Teams",
                              'item_list': c_teams,
                              'filters': filters,
                              'symbol_text': symbol_text})

def view_team(request, team_id):
    team_id = int(team_id)
    try:
        team = Team.objects.get(pk=team_id)
        stats = []
        stats.append(("Wins", tab_logic.tot_wins(team)))
        stats.append(("Total Speaks", tab_logic.tot_speaks(team)))
        stats.append(("Govs", tab_logic.num_govs(team)))
        stats.append(("Opps", tab_logic.num_opps(team)))
        stats.append(("Avg. Opp Wins", tab_logic.opp_strength(team)))
        stats.append(("Been Pullup", tab_logic.pull_up_count(team)))
        stats.append(("Hit Pullup", tab_logic.hit_pull_up_count(team)))
    except Team.DoesNotExist:
        return render(request, 'error.html', 
                                 {'error_type': "View Team",
                                  'error_name': str(team_id),
                                  'error_info':"No such Team"})
    if request.method == 'POST':
        form = TeamForm(request.POST,instance=team)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return render(request, 'error.html',
                                         {'error_type': "Team",
                                          'error_name': "["+form.cleaned_data['name']+"]",
                                          'error_info':"Team name cannot be validated, most likely a non-existent team"})
            return render(request, 'thanks.html', 
                                     {'data_type': "Team",
                                      'data_name': "["+form.cleaned_data['name']+"]"})
    else:
        form = TeamForm(instance=team)
        links = [('/team/'+str(team_id)+'/scratches/view/','Scratches for {}'.format(team.name), False)]
        for deb in team.debaters.all():
            links.append(('/debater/'+str(deb.id)+'/', "View %s" % deb.name, False))
        return render(request, 'data_entry.html', 
                                 {'title':"Viewing Team: %s"%(team.name),
                                  'form': form,
                                  'links': links,
                                  'team_obj':team,
                                  'team_stats':stats})

    return render(request, 'data_entry.html', 
                             {'form': form})

def enter_team(request):
    if request.method == 'POST':
        form = TeamEntryForm(request.POST)
        if form.is_valid():
            try:
                team = form.save()
            except ValueError:
                return render(request, 'error.html', 
                                         {'error_type': "Team",'error_name': "["+form.cleaned_data['name']+"]",
                                          'error_info':"Team name cannot be validated, most likely a duplicate school"})
            num_forms = form.cleaned_data['number_scratches']
            if num_forms > 0:
                return HttpResponseRedirect('/team/'+str(team.pk)+'/scratches/add/'+str(num_forms))
            else:
                return render(request, 'thanks.html', 
                                         {'data_type': "Team",
                                          'data_name': '[{}]'.format(team.name),
                                          'data_modification': 'CREATED',
                                          'enter_again': True})

    else:
        form = TeamEntryForm()
    return render(request, 'data_entry.html',
                             {'form': form, 'title': "Create Team"})
    
@permission_required('tab.team.can_delete', login_url="/403/")                               
def delete_team(request, team_id):
    team_id = int(team_id)
    try :
        team = Team.objects.get(pk=team_id)
        team.delete()
    except Team.DoesNotExist:
        return render(request, 'error.html', 
                                 {'error_type': "Team",
                                 'error_name': str(team_id),
                                 'error_info':"Team does not exist"})
    return render(request, 'thanks.html', 
                             {'data_type': "Team",
                              'data_name': "["+str(team_id)+"]",
                              'data_modification': 'DELETED'})

def add_scratches(request, team_id, number_scratches):
    try:
        team_id,number_scratches = int(team_id),int(number_scratches)
    except ValueError:
        return render(request, 'error.html', 
                                 {'error_type': "Scratch",'error_name': "Data Entry",
                                  'error_info':"I require INTEGERS!"})
    try:
        team = Team.objects.get(pk=team_id)
    except Team.DoesNotExist:
        return render(request, 'error.html', 
                                 {'error_type': "Add Scratches for Team",
                                  'error_name': str(team_id),
                                  'error_info':"No such Team"})
    if request.method == 'POST':
        forms = [ScratchForm(request.POST, prefix=str(i)) for i in range(1,number_scratches+1)]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return render(request, 'thanks.html', 
                                     {'data_type': "Scratches for team",
                                      'data_name': "["+str(team_id)+"]",
                                      'data_modification': "CREATED"})
    else:
        forms = [ScratchForm(prefix=str(i), initial={'team':team_id,'scratch_type':0}) for i in range(1,number_scratches+1)]
    return render(request, 'data_entry_multiple.html', 
                             {'forms': list(zip(forms,[None]*len(forms))),
                              'data_type':'Scratch',
                              'title':"Adding Scratch(es) for %s"%(team.name)})
    
def view_scratches(request, team_id):
    try:
        team_id = int(team_id)
    except ValueError:
        return render(request, 'error.html', 
                                 {'error_type': "Scratch",'error_name': "Delete",
                                  'error_info':"I require INTEGERS!"})
    scratches = Scratch.objects.filter(team=team_id)
    number_scratches = len(scratches)
    team = Team.objects.get(pk=team_id)
    if request.method == 'POST':
        forms = [ScratchForm(request.POST, prefix=str(i),instance=scratches[i-1]) for i in range(1,number_scratches+1)]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return render(request, 'thanks.html', 
                                     {'data_type': "Scratches for team",
                                      'data_name': "["+str(team_id)+"]",
                                      'data_modification': "EDITED"})
    else:
        forms = [ScratchForm(prefix=str(i), instance=scratches[i-1]) for i in range(1,len(scratches)+1)]
    delete_links = ["/team/"+str(team_id)+"/scratches/delete/"+str(scratches[i].id) for i in range(len(scratches))]
    links = [('/team/'+str(team_id)+'/scratches/add/1/','Add Scratch')]
    return render(request, 'data_entry_multiple.html', 
                             {'forms': list(zip(forms,delete_links)),
                              'data_type':'Scratch',
                              'links':links,
                              'title':"Viewing Scratch Information for %s"%(team.name)})

@permission_required('tab.tab_settings.can_change', login_url="/403/")
def all_tab_cards(request):
    all_teams = Team.objects.all()
    return render(request, 'all_tab_cards.html',
                              locals())

def pretty_tab_card(request, team_id):
    try:
        team_id = int(team_id)
    except:
{'fraction_non_alphanumeric': 0.1253859069490332, 'fraction_numerical': 0.002491469425337161, 'mean_word_length': 1.698626132709734, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 88, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4486266', 'n_tokens_mistral': 5322, 'n_tokens_neox': 5074, 'n_words': 998}