def test_enum_field(self): registry = EnumRegistry() field = EnumField(registry) registry.register('OK', 'OK') registry.register('OK', 'Should be ignored (duplicate)') registry.register('ERR', 'Error') self.assertEqual(sorted(list(field.choices)), [('ERR', 'Error'), ('OK', 'OK')]) with self.assertRaises(ValidationError): field.validate('FOO', None)
class TestEnumField(TestCase): def setUp(self): self.registry = EnumRegistry() self.registry.register('OK', 'OK') self.registry.register('OK', 'Should be ignored (duplicate)') self.registry.register('ERR', 'Error') def test_basic_usage(self): field = EnumField(self.registry) self.assertEqual(sorted(list(field.choices)), [('ERR', 'Error'), ('OK', 'OK')]) with self.assertRaises(ValidationError): field.validate('FOO', None) def test_serialization(self): """Test if choices aren't serialized by migration.""" first_field = EnumField(self.registry) first_serialized = first_field.deconstruct() self.registry.register('MAYBE', "You tell me if it's wrong or not") second_field = EnumField(self.registry) second_serialized = second_field.deconstruct() self.assertEqual(first_serialized, second_serialized)
from django.dispatch import receiver from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumField, EnumRegistry from oioioi.contests.fields import ScoreField from oioioi.contests.models import (Contest, ProblemInstance, Submission, SubmissionReport, submission_kinds, submission_report_kinds, submission_statuses) from oioioi.filetracker.fields import FileField from oioioi.problems.models import Problem, make_problem_filename from oioioi.programs.problem_instance_utils import get_language_by_extension execuction_mode_options = EnumRegistry() execuction_mode_options.register('AUTO', _("Auto")) execuction_mode_options.register('cpu', _("Real CPU")) execuction_mode_options.register('sio2jail', _("SIO2Jail")) class ProgramsConfig(models.Model): contest = models.OneToOneField(Contest, related_name='programs_config', on_delete=models.CASCADE) execuction_mode = EnumField( execuction_mode_options, default='AUTO', verbose_name=_("execution mode"), help_text=_("If set to Auto, the execution mode is determined " "according to the type of the contest."))
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from oioioi.contests.models import Submission from oioioi.base.fields import EnumRegistry, EnumField submission_states = EnumRegistry() submission_states.register('QUEUED', _("Queued")) submission_states.register('PROGRESS', _("In progress")) submission_states.register('PROGRESS-RESUMED', _("In progress (resumed)")) submission_states.register('CANCELLED', _("Cancelled")) submission_states.register('WAITING', _("Waiting")) class QueuedSubmit(models.Model): submission = models.ForeignKey(Submission) state = EnumField(submission_states, default='QUEUED') creation_date = models.DateTimeField(default=timezone.now) celery_task_id = models.CharField(max_length=50, unique=True, null=True, blank=True) creation_date.short_description = _("Creation date") class Meta(object): verbose_name = _("Queued submission") verbose_name_plural = _("Queued submissions") ordering = ['pk']
import json from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumField, EnumRegistry from oioioi.contests.models import Submission job_states = EnumRegistry() job_states.register('QUEUED', _("Queued")) job_states.register('PROGRESS', _("In progress")) job_states.register('CANCELLED', _("Cancelled")) job_states.register('WAITING', _("Waiting")) class QueuedJob(models.Model): job_id = models.CharField(max_length=50, primary_key=True) state = EnumField(job_states, default='QUEUED') creation_date = models.DateTimeField(default=timezone.now) # Optional information about queued jobs. submission = models.ForeignKey(Submission, null=True, on_delete=models.CASCADE) celery_task_id = models.CharField(max_length=50, unique=True, null=True, blank=True) class Meta(object): verbose_name = _("Queued job") verbose_name_plural = _("Queued jobs") ordering = ['pk']
raise ValidationError( _("Results cannot appear later than " "public results.")) @receiver(pre_save, sender=Round) def _generate_round_id(sender, instance, raw, **kwargs): """Automatically generate a round name if not provided.""" if not raw and not instance.name: num_other_rounds = (Round.objects.filter( contest=instance.contest).exclude(pk=instance.pk).count()) instance.name = _("Round %d") % (num_other_rounds + 1, ) statements_visibility_options = EnumRegistry() statements_visibility_options.register('YES', _("Visible")) statements_visibility_options.register('NO', _("Not visible")) statements_visibility_options.register('AUTO', _("Auto")) class ProblemStatementConfig(models.Model): contest = models.OneToOneField('contests.Contest', on_delete=models.CASCADE) visible = EnumField( statements_visibility_options, default='AUTO', verbose_name=_("statements visibility"), help_text=_("If set to Auto, the visibility is determined " "according to the type of the contest."), )
from oioioi.statistics.plotfunctions import ( points_histogram_contest, points_histogram_problem, points_to_source_length_problem, submissions_histogram_contest, test_scores, ) from oioioi.statistics.plottypes import ( BarPercentStaticHighchartsPlot, ColumnStaticHighchartsPlot, PointsToSourceLengthProblemPlot, TablePlot, ) statistics_categories = EnumRegistry() statistics_categories.register('CONTEST', (_("Contest"), 'c')) statistics_categories.register('PROBLEM', (_("Problem"), 'p')) statistics_plot_kinds = EnumRegistry() statistics_plot_kinds.register( 'POINTS_HISTOGRAM_CONTEST', (points_histogram_contest, ColumnStaticHighchartsPlot())) statistics_plot_kinds.register( 'SUBMISSIONS_HISTOGRAM_CONTEST', ( submissions_histogram_contest, ColumnStaticHighchartsPlot(), ), ) statistics_plot_kinds.register( 'POINTS_HISTOGRAM_PROBLEM',
from django.db import models, transaction from django.utils.translation import ugettext_lazy as _ from django.dispatch import receiver from django.db.models.signals import post_save from oioioi.base.fields import EnumRegistry, EnumField from oioioi.problems.models import Problem, make_problem_filename from oioioi.filetracker.fields import FileField from oioioi.contests.models import Submission, SubmissionReport, \ submission_statuses, submission_report_kinds, ProblemInstance from oioioi.contests.fields import ScoreField import os.path test_kinds = EnumRegistry() test_kinds.register('NORMAL', _("Normal test")) test_kinds.register('EXAMPLE', _("Example test")) class Test(models.Model): problem = models.ForeignKey(Problem) name = models.CharField(max_length=30, verbose_name=_("name")) input_file = FileField(upload_to=make_problem_filename, verbose_name=_("input"), null=True, blank=True) output_file = FileField(upload_to=make_problem_filename, verbose_name=_("output/hint"), null=True, blank=True) kind = EnumField(test_kinds, verbose_name=_("kind")) group = models.CharField(max_length=30, verbose_name=_("group")) time_limit = models.IntegerField(verbose_name=_("time limit (ms)"), null=True, blank=True) memory_limit = models.IntegerField(verbose_name=_("memory limit (kB)"), null=True, blank=True) max_score = models.IntegerField(verbose_name=_("score"),
from oioioi.base.fields import EnumRegistry from oioioi.contests.controllers import ContestController from oioioi.contests.utils import visible_problem_instances, rounds_times, \ is_contest_admin, is_contest_observer from oioioi.contests.models import ProblemInstance from oioioi.programs.controllers import ProgrammingContestController from oioioi.statistics.plottypes import TablePlot, \ ColumnStaticHighchartsPlot, PointsToSourceLengthProblemPlot, \ BarPercentStaticHighchartsPlot from oioioi.statistics.plotfunctions import points_histogram_contest, \ submissions_histogram_contest, points_histogram_problem, \ points_to_source_length_problem, test_scores from oioioi.statistics.models import StatisticsConfig statistics_categories = EnumRegistry() statistics_categories.register('CONTEST', (_("Contest"), 'c')) statistics_categories.register('PROBLEM', (_("Problem"), 'p')) statistics_plot_kinds = EnumRegistry() statistics_plot_kinds.register('POINTS_HISTOGRAM_CONTEST', (points_histogram_contest, ColumnStaticHighchartsPlot())) statistics_plot_kinds.register('SUBMISSIONS_HISTOGRAM_CONTEST', (submissions_histogram_contest, ColumnStaticHighchartsPlot(),)) statistics_plot_kinds.register('POINTS_HISTOGRAM_PROBLEM', (points_histogram_problem, ColumnStaticHighchartsPlot())) statistics_plot_kinds.register('POINTS_TABLE_PROBLEM', (points_histogram_problem, TablePlot())) statistics_plot_kinds.register('POINTS_TO_SOURCE_LENGTH_PROBLEM', (points_to_source_length_problem, PointsToSourceLengthProblemPlot())) statistics_plot_kinds.register('TEST_SCORES_TABLE_PROBLEM', (test_scores, BarPercentStaticHighchartsPlot()))
from django.utils.translation import ugettext_lazy as _ from oioioi.contests.controllers import ContestController from oioioi.programs.controllers import ProgrammingContestController from oioioi.base.fields import EnumRegistry from oioioi.contests.utils import visible_problem_instances, rounds_times from oioioi.statistics.plottypes import HistogramPlot, TablePlot, ScatterPlot from oioioi.statistics.plotfunctions import points_histogram_contest, \ submissions_histogram_contest, points_histogram_problem, \ points_to_source_length_problem from oioioi.contests.utils import is_contest_admin, is_contest_observer statistics_categories = EnumRegistry() statistics_categories.register('CONTEST', (_("Contest"), 'c')) statistics_categories.register('PROBLEM', (_("Problem"), 'p')) statistics_plot_kinds = EnumRegistry() statistics_plot_kinds.register('POINTS_HISTOGRAM_CONTEST', (points_histogram_contest, HistogramPlot())) statistics_plot_kinds.register('SUBMISSIONS_HISTOGRAM_CONTEST', ( submissions_histogram_contest, HistogramPlot(), )) statistics_plot_kinds.register('POINTS_HISTOGRAM_PROBLEM', (points_histogram_problem, HistogramPlot())) statistics_plot_kinds.register('POINTS_TABLE_PROBLEM', (points_histogram_problem, TablePlot())) statistics_plot_kinds.register( 'POINTS_TO_SOURCE_LENGTH_PROBLEM', (points_to_source_length_problem, ScatterPlot()))
# the custom registration form (in contests like OI and PA) terms_accepted = models.BooleanField(_("terms accepted"), default=False) def erase_data(self): self.address = 'Account deleted' self.postal_code = '00-000' self.city = 'Account deleted' self.job = 'OTH' self.job_name = 'Account deleted' self.t_shirt_size = 'S' self.newsletter = False self.terms_accepted = False self.save() division_registry = EnumRegistry() division_registry.register('A', _("Division A")) division_registry.register('B', _("Division B")) division_registry.register('NONE', _("None")) class PAProblemInstanceData(models.Model): problem_instance = models.OneToOneField(ProblemInstance, primary_key=True, on_delete=models.CASCADE) division = EnumField(division_registry, verbose_name=_("Division")) class Meta(object): verbose_name = _("Division") verbose_name_plural = _("Divisions")
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from oioioi.contests.models import Submission from oioioi.base.fields import EnumRegistry, EnumField submission_states = EnumRegistry() submission_states.register('QUEUED', _("Queued")) submission_states.register('PROGRESS', _("In progress")) submission_states.register('CANCELLED', _("Cancelled")) class QueuedSubmit(models.Model): submission = models.ForeignKey(Submission) state = EnumField(submission_states, default='QUEUED') creation_date = models.DateTimeField(default=timezone.now) celery_task_id = models.CharField(max_length=50, unique=True, null=True, blank=True) creation_date.short_description = _("Creation date") class Meta(object): verbose_name = _("Queued Submit") ordering = ['pk']
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumRegistry, EnumField from oioioi.contests.models import Contest participant_statuses = EnumRegistry() participant_statuses.register('ACTIVE', _("Active")) participant_statuses.register('BANNED', _("Banned")) class Participant(models.Model): contest = models.ForeignKey(Contest) user = models.ForeignKey(User) status = EnumField(participant_statuses, default='ACTIVE') @property def registration_model(self): rcontroller = self.contest.controller.registration_controller() model_class = rcontroller.get_model_class() try: return model_class.objects.get(participant=self) except model_class.DoesNotExist: raise ObjectDoesNotExist class Meta: unique_together = ('contest', 'user') def __unicode__(self):
team = models.ForeignKey(Team, related_name='members') class Meta(object): unique_together = ("user", "team") def validate_unique(self, *args, **kwargs): super(TeamMembership, self).validate_unique(*args, **kwargs) if TeamMembership.objects.filter(user=self.user, team__contest=self.team.contest) \ .exclude(team=self.team).exists(): raise ValidationError( {'user': {"The user is already in another team"}}) teams_list_visibility_options = EnumRegistry() teams_list_visibility_options.register('PUBLIC', _("Visible for all")) teams_list_visibility_options.register('YES', _("Visible only for registered users")) teams_list_visibility_options.register('NO', _("Not visible")) class TeamsConfig(models.Model): contest = models.OneToOneField(Contest) enabled = models.BooleanField(default=False) max_team_size = models.IntegerField(default=3, validators=[MinValueValidator(1)]) modify_begin_date = models.DateTimeField( verbose_name=_("team modification begin date"), blank=True, null=True) modify_end_date = models.DateTimeField( verbose_name=_("team modification end date"), blank=True, null=True) teams_list_visible = EnumField(teams_list_visibility_options, default='NO',
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from oioioi.contests.models import Submission from oioioi.base.fields import EnumRegistry, EnumField submission_states = EnumRegistry() submission_states.register('QUEUED', _("Queued")) submission_states.register('PROGRESS', _("In progress")) submission_states.register('PROGRESS-RESUMED', _("In progress (resumed)")) submission_states.register('CANCELLED', _("Cancelled")) submission_states.register('WAITING', _("Waiting")) class QueuedSubmit(models.Model): submission = models.ForeignKey(Submission) state = EnumField(submission_states, default='QUEUED') creation_date = models.DateTimeField(default=timezone.now) celery_task_id = models.CharField(max_length=50, unique=True, null=True, blank=True) creation_date.short_description = _("Creation date") class Meta(object): verbose_name = _("Queued Submit") ordering = ['pk']
def __unicode__(self): return '%s / %s' % (self.problem.name, self.filename) def _make_package_filename(instance, filename): if instance.contest: contest_name = instance.contest.id else: contest_name = 'no_contest' return 'package/%s/%s' % (contest_name, get_valid_filename(os.path.basename(filename))) package_statuses = EnumRegistry() package_statuses.register('?', pgettext_lazy("Pending", "Pending problem package")) package_statuses.register('OK', _("Uploaded")) package_statuses.register('ERR', _("Error")) TRACEBACK_STACK_LIMIT = 100 class ProblemPackage(models.Model): """Represents a file with data necessary for creating a :class:`~oioioi.problems.models.Problem` instance. """ package_file = FileField(upload_to=_make_package_filename, verbose_name=_("package")) contest = models.ForeignKey('contests.Contest', null=True, blank=True,
from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumRegistry, EnumField from oioioi.base.utils.deps import check_django_app_dependencies from oioioi.base.utils.validators import validate_db_string_id from oioioi.contests.models import Contest from oioioi.participants.fields import \ OneToOneBothHandsCascadingParticipantField check_django_app_dependencies(__name__, ['oioioi.contestexcl']) participant_statuses = EnumRegistry() participant_statuses.register('ACTIVE', _("Active")) participant_statuses.register('BANNED', _("Banned")) participant_statuses.register('DELETED', _("Account deleted")) class Participant(models.Model): contest = models.ForeignKey(Contest) user = models.ForeignKey(User) status = EnumField(participant_statuses, default='ACTIVE') anonymous = models.BooleanField(default=False) @property def registration_model(self): rcontroller = self.contest.controller.registration_controller() model_class = rcontroller.get_model_class()
from django.core.urlresolvers import reverse from django.core.validators import MaxLengthValidator from django.db import models from django.db.models import Q from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from django.utils.text import Truncator from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumField, EnumRegistry from oioioi.base.utils.validators import validate_whitespaces from oioioi.contests.models import Contest, ProblemInstance, Round message_kinds = EnumRegistry() message_kinds.register('QUESTION', _("Question")) message_kinds.register('PRIVATE', _("Private message")) message_kinds.register('PUBLIC', _("Public message")) logger = logging.getLogger('oioioi') class Message(models.Model): contest = models.ForeignKey(Contest, null=True, blank=True, on_delete=models.CASCADE) round = models.ForeignKey(Round, null=True, blank=True, on_delete=models.CASCADE) problem_instance = models.ForeignKey(ProblemInstance, null=True, blank=True, on_delete=models.CASCADE) top_reference = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
pg = PrizeGiving.objects.select_for_update().get(pk=pg_pk) except PrizeGiving.DoesNotExist: return logger.info(prefix + "PG object with given id doesn't exist") if pg.version != version: return logger.info(prefix + "version doesn't match -- %s / %s", version, pg.version) on_success = lambda: logger.info(prefix + "success") on_failure = lambda: logger.info(prefix + "prizes assignment not found") pg._distribute(on_success, on_failure) prizegiving_states = EnumRegistry() prizegiving_states.register('NOT_SCHEDULED', _("NOT SCHEDULED")) prizegiving_states.register('SCHEDULED', _("SCHEDULED")) prizegiving_states.register('FAILURE', _("FAILURE")) prizegiving_states.register('SUCCESS', _("SUCCESS")) def _make_report_filename(instance, filename): return 'prizes/reports/%s/%s/' % ( instance.contest.id, get_valid_filename(os.path.basename(filename))) class PrizeGiving(models.Model): """Represents an event of distributing prizes to users. Such an event needs some proper preparation. First of all, we decide on a date when it's going to happen.
super(TeamMembership, self).validate_unique(*args, **kwargs) query = TeamMembership.objects.filter(user=self.user, team__contest=self.team.contest) # Excluding unsaved object excludes everything see: # https://code.djangoproject.com/ticket/25467 if self.team.pk is not None: query = query.exclude(team=self.team) if query.exists(): raise ValidationError( {'user': {"The user is already in another team"}}) teams_list_visibility_options = EnumRegistry() teams_list_visibility_options.register('PUBLIC', _("Visible for all")) teams_list_visibility_options.register('YES', _("Visible only for registered users")) teams_list_visibility_options.register('NO', _("Not visible")) class TeamsConfig(models.Model): contest = models.OneToOneField(Contest, on_delete=models.CASCADE) enabled = models.BooleanField(default=False) max_team_size = models.IntegerField(default=3, validators=[MinValueValidator(1)]) modify_begin_date = models.DateTimeField( verbose_name=_("team modification begin date"), blank=True, null=True) modify_end_date = models.DateTimeField( verbose_name=_("team modification end date"), blank=True, null=True) teams_list_visible = EnumField(
"date, you should enter a results date too.")) if self.results_date > self.public_results_date: raise ValidationError(_("Results cannot appear later than " "public results.")) @receiver(pre_save, sender=Round) def _generate_round_id(sender, instance, raw, **kwargs): """Automatically generate a round name if not provided.""" if not raw and not instance.name: num_other_rounds = Round.objects.filter(contest=instance.contest) \ .exclude(pk=instance.pk).count() instance.name = _("Round %d") % (num_other_rounds + 1,) statements_visibility_options = EnumRegistry() statements_visibility_options.register('YES', _("Visible")) statements_visibility_options.register('NO', _("Not visible")) statements_visibility_options.register('AUTO', _("Auto")) class ProblemStatementConfig(models.Model): contest = models.OneToOneField('contests.Contest', on_delete=models.CASCADE) visible = EnumField(statements_visibility_options, default='AUTO', verbose_name=_("statements visibility"), help_text=_("If set to Auto, the visibility is determined " "according to the type of the contest.")) class Meta(object): verbose_name = _("problem statement config") verbose_name_plural = _("problem statement configs")
verbose_name_plural = _("attachments") def __unicode__(self): return '%s / %s' % (self.problem.name, self.filename) def _make_package_filename(instance, filename): if instance.contest: contest_name = instance.contest.id else: contest_name = 'no_contest' return 'package/%s/%s' % (contest_name, get_valid_filename(os.path.basename(filename))) package_statuses = EnumRegistry() package_statuses.register('?', pgettext_lazy("Pending", "Pending problem package")) package_statuses.register('OK', _("Uploaded")) package_statuses.register('ERR', _("Error")) TRACEBACK_STACK_LIMIT = 100 class ProblemPackage(models.Model): """Represents a file with data necessary for creating a :class:`~oioioi.problems.models.Problem` instance. """ package_file = FileField(upload_to=_make_package_filename, verbose_name=_("package")) contest = models.ForeignKey('contests.Contest', null=True, blank=True, verbose_name=_("contest")) problem = models.ForeignKey(Problem, verbose_name=_("problem"), null=True,
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumRegistry, EnumField from oioioi.contests.models import Contest participant_statuses = EnumRegistry() participant_statuses.register("ACTIVE", _("Active")) participant_statuses.register("BANNED", _("Banned")) class Participant(models.Model): contest = models.ForeignKey(Contest) user = models.ForeignKey(User) status = EnumField(participant_statuses, default="ACTIVE") @property def registration_model(self): rcontroller = self.contest.controller.registration_controller() model_class = rcontroller.get_model_class() try: return model_class.objects.get(participant=self) except model_class.DoesNotExist: raise ObjectDoesNotExist class Meta: unique_together = ("contest", "user") def __unicode__(self):
try: pg = PrizeGiving.objects.select_for_update().get(pk=pg_pk) except PrizeGiving.DoesNotExist: return logger.info(prefix + "PG object with given id doesn't exist") if pg.version != version: return logger.info(prefix + "version doesn't match -- %s / %s", version, pg.version) on_success = lambda: logger.info(prefix + "success") on_failure = lambda: logger.info(prefix + "prizes assignment not found") pg._distribute(on_success, on_failure) prizegiving_states = EnumRegistry() prizegiving_states.register("NOT_SCHEDULED", _("NOT SCHEDULED")) prizegiving_states.register("SCHEDULED", _("SCHEDULED")) prizegiving_states.register("FAILURE", _("FAILURE")) prizegiving_states.register("SUCCESS", _("SUCCESS")) def _make_report_filename(instance, filename): return "prizes/reports/%s/%s/" % (instance.contest.id, get_valid_filename(os.path.basename(filename))) class PrizeGiving(models.Model): """Represents an event of distributing prizes to users. Such an event needs some proper preparation. First of all, we decide on a date when it's going to happen. Secondly, we decide on a list of Prizes to be distributed.
import json from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumField, EnumRegistry from oioioi.contests.models import Submission job_states = EnumRegistry() job_states.register('QUEUED', _("Queued")) job_states.register('PROGRESS', _("In progress")) job_states.register('CANCELLED', _("Cancelled")) job_states.register('WAITING', _("Waiting")) class QueuedJob(models.Model): job_id = models.CharField(max_length=50, primary_key=True) state = EnumField(job_states, default='QUEUED') creation_date = models.DateTimeField(default=timezone.now) # Optional information about queued jobs. submission = models.ForeignKey(Submission, null=True, on_delete=models.CASCADE) celery_task_id = models.CharField(max_length=50, unique=True, null=True, blank=True) class Meta(object):
from django.db import models, transaction from django.utils.translation import ugettext_lazy as _ from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from oioioi.base.fields import EnumRegistry, EnumField from oioioi.problems.models import Problem, make_problem_filename from oioioi.filetracker.fields import FileField from oioioi.contests.models import Submission, SubmissionReport, \ submission_statuses, submission_report_kinds, ProblemInstance, \ submission_kinds from oioioi.contests.fields import ScoreField import os.path test_kinds = EnumRegistry() test_kinds.register('NORMAL', _("Normal test")) test_kinds.register('EXAMPLE', _("Example test")) def validate_time_limit(value): if value is None or value <= 0: raise ValidationError(_("Time limit must be a positive number.")) def validate_memory_limit(value): if value is None or value <= 0: raise ValidationError(_("Memory limit must be a positive number.")) if value > settings.MAX_MEMORY_LIMIT_FOR_TEST: raise ValidationError( _("Memory limit mustn't be greater than %dKiB." % settings.MAX_MEMORY_LIMIT_FOR_TEST))
from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumField, EnumRegistry from oioioi.base.utils.deps import check_django_app_dependencies from oioioi.base.utils.validators import validate_db_string_id from oioioi.contests.models import Contest from oioioi.participants.fields import \ OneToOneBothHandsCascadingParticipantField check_django_app_dependencies(__name__, ['oioioi.contestexcl']) participant_statuses = EnumRegistry() participant_statuses.register('ACTIVE', _("Active")) participant_statuses.register('BANNED', _("Banned")) participant_statuses.register('DELETED', _("Account deleted")) class Participant(models.Model): contest = models.ForeignKey(Contest) user = models.ForeignKey(User) status = EnumField(participant_statuses, default='ACTIVE') anonymous = models.BooleanField(default=False) @property def registration_model(self): rcontroller = self.contest.controller.registration_controller() model_class = rcontroller.get_model_class()
if not raw and not instance.short_name and instance.problem_id: short_names = ProblemInstance.objects.filter(contest=instance.contest)\ .values_list('short_name', flat=True) problem_short_name = instance.problem.short_name if problem_short_name not in short_names: instance.short_name = problem_short_name else: for i in itertools.count(1): candidate = problem_short_name + str(i) if candidate not in short_names: instance.short_name = candidate break submission_kinds = EnumRegistry() submission_kinds.register('NORMAL', _("Normal")) submission_kinds.register('IGNORED', _("Ignored")) submission_statuses = EnumRegistry() submission_statuses.register('?', _("Pending")) submission_statuses.register('OK', _("OK")) submission_statuses.register('ERR', _("Error")) class Submission(models.Model): problem_instance = models.ForeignKey(ProblemInstance, verbose_name=_("problem")) user = models.ForeignKey(User, blank=True, null=True, verbose_name=_("user")) date = models.DateTimeField(default=datetime.datetime.now, blank=True, verbose_name=_("date")) kind = EnumField(submission_kinds, default='NORMAL',
from django.conf import settings from django.core.validators import MaxLengthValidator from django.utils import timezone from django.utils.text import Truncator from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db.models.signals import post_save from oioioi.contests.models import Contest, Round, ProblemInstance from oioioi.base.fields import EnumRegistry, EnumField from oioioi.base.utils.validators import validate_whitespaces from oioioi.questions.utils import send_email_about_new_question message_kinds = EnumRegistry() message_kinds.register('QUESTION', _("Question")) message_kinds.register('PRIVATE', _("Private message")) message_kinds.register('PUBLIC', _("Public message")) logger = logging.getLogger('oioioi') class Message(models.Model): contest = models.ForeignKey(Contest, null=True, blank=True) round = models.ForeignKey(Round, null=True, blank=True) problem_instance = models.ForeignKey(ProblemInstance, null=True, blank=True) top_reference = models.ForeignKey('self', null=True, blank=True) author = models.ForeignKey(User) kind = EnumField(message_kinds, default='QUESTION', verbose_name=_("kind"))
from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from oioioi.base.fields import EnumField, EnumRegistry from oioioi.contests.fields import ScoreField from oioioi.contests.models import (Contest, ProblemInstance, Submission, SubmissionReport, submission_kinds, submission_report_kinds, submission_statuses) from oioioi.filetracker.fields import FileField from oioioi.problems.models import Problem, make_problem_filename from oioioi.programs.problem_instance_utils import get_language_by_extension execuction_mode_options = EnumRegistry() execuction_mode_options.register('AUTO', _("Auto")) execuction_mode_options.register('cpu', _("Real CPU")) execuction_mode_options.register('vcpu', _("OITimeTool")) execuction_mode_options.register('sio2jail', _("SIO2Jail")) class ProgramsConfig(models.Model): contest = models.OneToOneField(Contest, related_name='programs_config', on_delete=models.CASCADE) execuction_mode = EnumField(execuction_mode_options, default='AUTO', verbose_name=_("execution mode"), help_text=_("If set to Auto, the execution mode is determined " "according to the type of the contest.")) class Meta(object):
short_names = ProblemInstance.objects.filter(contest=instance.contest)\ .values_list('short_name', flat=True) # SlugField and validate_slug accepts uppercase letters, while we don't problem_short_name = instance.problem.short_name.lower() if problem_short_name not in short_names: instance.short_name = problem_short_name else: for i in itertools.count(1): candidate = problem_short_name + str(i) if candidate not in short_names: instance.short_name = candidate break submission_kinds = EnumRegistry() submission_kinds.register('NORMAL', _("Normal")) submission_kinds.register('IGNORED', _("Ignored")) submission_kinds.register('SUSPECTED', _("Suspected")) submission_statuses = EnumRegistry() submission_statuses.register('?', _("Pending")) submission_statuses.register('OK', _("OK")) submission_statuses.register('ERR', _("Error")) class Submission(models.Model): problem_instance = models.ForeignKey(ProblemInstance, verbose_name=_("problem")) user = models.ForeignKey(User, blank=True, null=True,
if not raw and not instance.short_name and instance.problem_id: short_names = ProblemInstance.objects.filter(contest=instance.contest)\ .values_list('short_name', flat=True) # SlugField and validate_slug accepts uppercase letters, while we don't problem_short_name = instance.problem.short_name.lower() if problem_short_name not in short_names: instance.short_name = problem_short_name else: for i in itertools.count(1): candidate = problem_short_name + str(i) if candidate not in short_names: instance.short_name = candidate break submission_kinds = EnumRegistry() submission_kinds.register('NORMAL', _("Normal")) submission_kinds.register('IGNORED', _("Ignored")) submission_kinds.register('SUSPECTED', _("Suspected")) submission_statuses = EnumRegistry() submission_statuses.register('?', _("Pending")) submission_statuses.register('OK', _("OK")) submission_statuses.register('ERR', _("Error")) class Submission(models.Model): problem_instance = models.ForeignKey(ProblemInstance, verbose_name=_("problem")) user = models.ForeignKey(User, blank=True, null=True, verbose_name=_("user")) date = models.DateTimeField(default=timezone.now, blank=True,
pg = PrizeGiving.objects.select_for_update().get(pk=pg_pk) except PrizeGiving.DoesNotExist: return logger.info(prefix + "PG object with given id doesn't exist") if pg.version != version: return logger.info(prefix + "version doesn't match -- %s / %s", version, pg.version) on_success = lambda: logger.info(prefix + "success") on_failure = lambda: logger.info(prefix + "prizes assignment not found") pg._distribute(on_success, on_failure) prizegiving_states = EnumRegistry() prizegiving_states.register('NOT_SCHEDULED', _("NOT SCHEDULED")) prizegiving_states.register('SCHEDULED', _("SCHEDULED")) prizegiving_states.register('FAILURE', _("FAILURE")) prizegiving_states.register('SUCCESS', _("SUCCESS")) def _make_report_filename(instance, filename): return 'prizes/reports/%s/%s/' % (instance.contest.id, get_valid_filename(os.path.basename(filename))) class PrizeGiving(models.Model): """Represents an event of distributing prizes to users. Such an event needs some proper preparation. First of all, we decide on a date when it's going to happen.
if not raw and not instance.short_name and instance.problem_id: short_names = ProblemInstance.objects.filter(contest=instance.contest)\ .values_list('short_name', flat=True) problem_short_name = instance.problem.short_name if problem_short_name not in short_names: instance.short_name = problem_short_name else: for i in itertools.count(1): candidate = problem_short_name + str(i) if candidate not in short_names: instance.short_name = candidate break submission_kinds = EnumRegistry() submission_kinds.register('NORMAL', _("Normal")) submission_kinds.register('IGNORED', _("Ignored")) submission_statuses = EnumRegistry() submission_statuses.register('?', _("Pending")) submission_statuses.register('OK', _("OK")) submission_statuses.register('ERR', _("Error")) class Submission(models.Model): problem_instance = models.ForeignKey(ProblemInstance, verbose_name=_("problem")) user = models.ForeignKey(User, blank=True, null=True, verbose_name=_("user")) date = models.DateTimeField(default=timezone.now, blank=True, verbose_name=_("date")) kind = EnumField(submission_kinds, default='NORMAL',
"the technical arrangements. I fully understand them and " "accept them unconditionally."), default=False) def erase_data(self): self.address = 'Account deleted' self.postal_code = '00-000' self.city = 'Account deleted' self.job = 'OTH' self.job_name = 'Account deleted' self.t_shirt_size = 'S' self.newsletter = False self.terms_accepted = False self.save() division_registry = EnumRegistry() division_registry.register('A', _("Division A")) division_registry.register('B', _("Division B")) division_registry.register('NONE', _("None")) class PAProblemInstanceData(models.Model): problem_instance = models.OneToOneField(ProblemInstance, primary_key=True) division = EnumField(division_registry, verbose_name=_("Division")) class Meta(object): verbose_name = _("Division") verbose_name_plural = _("Divisions")
from django.db import models from django.core.exceptions import ValidationError from django.core.validators import MaxLengthValidator from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from oioioi.contests.models import Contest, ProblemInstance from oioioi.problems.models import Problem from oioioi.base.fields import EnumRegistry, EnumField message_kinds = EnumRegistry() message_kinds.register("QUESTION", _("Question")) message_kinds.register("PRIVATE", _("Private message")) message_kinds.register("PUBLIC", _("Public message")) class Message(models.Model): contest = models.ForeignKey(Contest, null=True, blank=True) problem_instance = models.ForeignKey(ProblemInstance, null=True, blank=True) problem = models.ForeignKey(Problem, null=True, blank=True) top_reference = models.ForeignKey("self", null=True, blank=True) author = models.ForeignKey(User) kind = EnumField(message_kinds, default="QUESTION") topic = models.CharField(max_length=255, validators=[MaxLengthValidator(255)]) content = models.TextField() date = models.DateTimeField(auto_now_add=True, editable=False) def can_have_replies(self): return self.kind == "QUESTION" def save(self): if self.top_reference: