# Path: harnas/checker/forms.py
# class SubmitForm(forms.Form):
#     solution = forms.FileField(label="Upload your solution")
#     task = forms.ModelChoiceField(queryset=None, empty_label=None)
# 
#     def __init__(self, *args, **kwargs):
#         contest = kwargs.pop('contest')
#         super(SubmitForm, self).__init__(*args, **kwargs)
#         self.fields['task'].queryset = Task.objects.filter(contest=contest)
# 
#     def clean(self):
#         solution = self.cleaned_data['solution']
#         max_solution_size = self.cleaned_data['task'].max_solution_size
#         if solution._size > max_solution_size:
#             error_message = 'You cannot upload files larger than %(max_size)s.'
#             max_size = filesizeformat(max_solution_size)
#             raise forms.ValidationError(_(error_message),
#                                         params={'max_size': max_size},
#                                         code='too_large_solution')
# 
# Path: harnas/contest/forms.py
# class TaskForm(forms.ModelForm):
#     class Meta:
#         model = Task
#         fields = ['name', 'short_name', 'description', 'test_environment',
#                   'max_solution_size']
# 
# class UploadFileForm(forms.Form):
#     file = BootstrapFileField()
# 
#     def __init__(self, *args, **kwargs):
#         super(UploadFileForm, self).__init__(*args, **kwargs)
#         self.helper = FormHelper()
#         self.helper.form_method = 'post'
#         self.helper.form_id = 'uploadFileForm'
#         self.helper.form_class = 'form-inline'
#         self.helper.field_template = 'bootstrap3/layout/inline_field.html'
#         self.helper.layout = Layout(
#             'file',
#             Submit('submit', 'Upload', css_class='btn btn-sm')
#         )
# 
# class TestCaseForm(forms.ModelForm):
#     in_file = BootstrapFileField()
#     out_file = BootstrapFileField()
# 
#     class Meta:
#         model = TestCase
#         fields = ['name', 'max_memory', 'max_duration']
# 
# Path: harnas/contest/helpers.py
# def save_task(task):
#     try:
#         with transaction.atomic():
#             task.save()
#         return True
#     except Exception as e:
#         print('Error while saving task: %s' % e)
#         return False
# 
# Path: harnas/contest/models.py
# class Task(models.Model):
#     name = models.CharField(max_length=250)
#     short_name = models.CharField(max_length=3)
#     description = models.TextField()
#     test_environment = models.ForeignKey('checker.TestEnvironment')
#     author = models.ForeignKey(User)
#     parent = models.ForeignKey('self', null=True, default=None)
#     contest = models.ForeignKey(Contest, null=True, default=None)
#     max_solution_size = models.PositiveIntegerField()
# 
#     # Default timestamps values for task. Can be overridden individually in
#     # groups. See GroupsTaskDetails.
#     open = models.DateTimeField(null=True, default=None)
#     deadline = models.DateTimeField(null=True, default=None)
#     close = models.DateTimeField(null=True, default=None)
# 
#     class Meta:
#         permissions = (
#             ('view_task', 'Can view task'),
#             ('submit_solution', 'Can submit solution'),
#             ('edit_task', 'Can edit task'))
# 
#     def __str__(self):
#         return self.name
# 
#     @property
#     def display_name(self):
#         if self.contest is not None and self.contest.name.strip() != "":
#             return "%s (%s)" % (self.name, self.contest.name)
#         else:
#             return self.name


import os
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views.decorators.http import (require_http_methods, require_safe,
                                          require_POST)
from guardian.shortcuts import assign_perm, get_objects_for_user
from harnas.checker.forms import SubmitForm
from harnas.contest.forms import TaskForm, UploadFileForm, TestCaseForm
from harnas.contest.helpers import save_task
from harnas.contest.models import Task
    def invalidate_task_cache(task):
        cache_key = make_template_fragment_key('task_description', [task.pk])
        cache.delete(cache_key)

    return handle_task_form(request, form_post, task,
                            success_action=invalidate_task_cache)


def handle_task_form(request, form_post, task, success_action):
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=False)
            if not task.author_id:
                task.author_id = request.user.pk
            if save_task(task):
                success_action(task)
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    'Task %s saved successfully.' % task)
                return HttpResponseRedirect(
                    reverse('task_details', args=[task.pk]))
            else:
                messages.add_message(
                    request,
                    messages.ERROR,
                    'Unable to save this task. '
                    'Please report this accident to administrator.')
    else:

# Path: harnas/checker/forms.py
# class SubmitForm(forms.Form):
#     solution = forms.FileField(label="Upload your solution")
#     task = forms.ModelChoiceField(queryset=None, empty_label=None)
# 
#     def __init__(self, *args, **kwargs):
#         contest = kwargs.pop('contest')
#         super(SubmitForm, self).__init__(*args, **kwargs)
#         self.fields['task'].queryset = Task.objects.filter(contest=contest)
# 
#     def clean(self):
#         solution = self.cleaned_data['solution']
#         max_solution_size = self.cleaned_data['task'].max_solution_size
#         if solution._size > max_solution_size:
#             error_message = 'You cannot upload files larger than %(max_size)s.'
#             max_size = filesizeformat(max_solution_size)
#             raise forms.ValidationError(_(error_message),
#                                         params={'max_size': max_size},
#                                         code='too_large_solution')
# 
# Path: harnas/contest/forms.py
# class TaskForm(forms.ModelForm):
#     class Meta:
#         model = Task
#         fields = ['name', 'short_name', 'description', 'test_environment',
#                   'max_solution_size']
# 
# class UploadFileForm(forms.Form):
#     file = BootstrapFileField()
# 
#     def __init__(self, *args, **kwargs):
#         super(UploadFileForm, self).__init__(*args, **kwargs)
#         self.helper = FormHelper()
#         self.helper.form_method = 'post'
#         self.helper.form_id = 'uploadFileForm'
#         self.helper.form_class = 'form-inline'
#         self.helper.field_template = 'bootstrap3/layout/inline_field.html'
#         self.helper.layout = Layout(
#             'file',
#             Submit('submit', 'Upload', css_class='btn btn-sm')
#         )
# 
# class TestCaseForm(forms.ModelForm):
#     in_file = BootstrapFileField()
#     out_file = BootstrapFileField()
# 
#     class Meta:
#         model = TestCase
#         fields = ['name', 'max_memory', 'max_duration']
# 
# Path: harnas/contest/helpers.py
# def save_task(task):
#     try:
#         with transaction.atomic():
#             task.save()
#         return True
#     except Exception as e:
#         print('Error while saving task: %s' % e)
#         return False
# 
# Path: harnas/contest/models.py
# class Task(models.Model):
#     name = models.CharField(max_length=250)
#     short_name = models.CharField(max_length=3)
#     description = models.TextField()
#     test_environment = models.ForeignKey('checker.TestEnvironment')
#     author = models.ForeignKey(User)
#     parent = models.ForeignKey('self', null=True, default=None)
#     contest = models.ForeignKey(Contest, null=True, default=None)
#     max_solution_size = models.PositiveIntegerField()
# 
#     # Default timestamps values for task. Can be overridden individually in
#     # groups. See GroupsTaskDetails.
#     open = models.DateTimeField(null=True, default=None)
#     deadline = models.DateTimeField(null=True, default=None)
#     close = models.DateTimeField(null=True, default=None)
# 
#     class Meta:
#         permissions = (
#             ('view_task', 'Can view task'),
#             ('submit_solution', 'Can submit solution'),
#             ('edit_task', 'Can edit task'))
# 
#     def __str__(self):
#         return self.name
# 
#     @property
#     def display_name(self):
#         if self.contest is not None and self.contest.name.strip() != "":
#             return "%s (%s)" % (self.name, self.contest.name)
#         else:
#             return self.name


# Path: harnas/contest/views/task.py
import os
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.core.exceptions import PermissionDenied
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views.decorators.http import (require_http_methods, require_safe,
                                          require_POST)
from guardian.shortcuts import assign_perm, get_objects_for_user
from harnas.checker.forms import SubmitForm
from harnas.contest.forms import TaskForm, UploadFileForm, TestCaseForm
from harnas.contest.helpers import save_task
from harnas.contest.models import Task

    def invalidate_task_cache(task):
        cache_key = make_template_fragment_key('task_description', [task.pk])
        cache.delete(cache_key)

    return handle_task_form(request, form_post, task,
                            success_action=invalidate_task_cache)


def handle_task_form(request, form_post, task, success_action):
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save(commit=False)
            if not task.author_id:
                task.author_id = request.user.pk
            if save_task(task):
                success_action(task)
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    'Task %s saved successfully.' % task)
                return HttpResponseRedirect(
                    reverse('task_details', args=[task.pk]))
            else:
                messages.add_message(
                    request,
                    messages.ERROR,
                    'Unable to save this task. '
                    'Please report this accident to administrator.')
    else:

        form = TaskForm(instance=task)