Skip to content

Commit

Permalink
Moves constants to 'settings.py'; DMOJ#993
Browse files Browse the repository at this point in the history
  • Loading branch information
Carson-Tang committed Oct 10, 2019
1 parent 0dd605f commit 7eb13ee
Show file tree
Hide file tree
Showing 32 changed files with 180 additions and 106 deletions.
4 changes: 1 addition & 3 deletions django_ace/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe

ACE_URL = getattr(settings, 'ACE_URL', '//cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ext-split.js')


class AceWidget(forms.Textarea):
def __init__(self, mode=None, theme=None, wordwrap=False, width='100%', height='300px',
Expand All @@ -25,7 +23,7 @@ def __init__(self, mode=None, theme=None, wordwrap=False, width='100%', height='

@property
def media(self):
js = [urljoin(ACE_URL, 'ace.js')] if self.ace_media else []
js = [urljoin(settings.ACE_URL, 'ace.js')] if self.ace_media else []
js.append('django_ace/widget.js')
css = {
'screen': ['django_ace/widget.css'],
Expand Down
87 changes: 87 additions & 0 deletions dmoj/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import tempfile

from django.utils.translation import ugettext_lazy as _
from django_jinja.builtins import DEFAULT_EXTENSIONS
Expand All @@ -31,8 +32,92 @@
SITE_ID = 1
SITE_NAME = 'DMOJ'
SITE_LONG_NAME = 'DMOJ: Modern Online Judge'
SITE_ADMIN_EMAIL = False

'''
1 to use HTTPS if request was made to https://
2 to always use HTTPS for links
0 to always use HTTP for links
'''
DMOJ_SSL = 0

# Refer to dmoj.ca/post/103-point-system-rework
DMOJ_PP_STEP = 0.95
DMOJ_PP_ENTRIES = 100
DMOJ_PP_BONUS_FUNCTION = lambda n: 300 * (1 - 0.997 ** n) # noqa: E731

NODEJS = '/usr/bin/node'
EXIFTOOL = '/usr/bin/exiftool'
ACE_URL = '//cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ext-split.js'
SELECT2_JS_URL = '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'
DEFAULT_SELECT2_CSS = '//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css'

DMOJ_CAMO_URL = None
DMOJ_CAMO_KEY = None
DMOJ_CAMO_HTTPS = False
DMOJ_CAMO_EXCLUDE = ()
DMOJ_PROBLEM_DATA_ROOT = None
DMOJ_RATING_COLORS = False
DMOJ_EMAIL_THROTTLING = (10, 60)
DMOJ_STATS_LANGUAGE_THRESHOLD = 10
DMOJ_SUBMISSIONS_REJUDGE_LIMIT = 10
DMOJ_BLOG_NEW_PROBLEM_COUNT = 7
DMOJ_BLOG_RECENTLY_ATTEMPTED_PROBLEMS_COUNT = 7
DMOJ_TOTP_TOLERANCE_HALF_MINUTES = 1
DMOJ_USER_MAX_ORGANIZATION_COUNT = 3
DMOJ_COMMENT_VOTE_HIDE_THRESHOLD = -5
DMOJ_PDF_PROBLEM_CACHE = ''
DMOJ_PDF_PROBLEM_TEMP_DIR = tempfile.gettempdir()

MARKDOWN_STYLES = {}
MARKDOWN_DEFAULT_STYLE = {}

MATHOID_URL = False
MATHOID_GZIP = False
MATHOID_MML_CACHE = None
MATHOID_CSS_CACHE = 'default'
MATHOID_DEFAULT_TYPE = 'auto'
MATHOID_MML_CACHE_TTL = 86400
MATHOID_CACHE_ROOT = ''
MATHOID_CACHE_URL = False

TEXOID_GZIP = False
TEXOID_META_CACHE = 'default'
TEXOID_META_CACHE_TTL = 86400
DMOJ_NEWSLETTER_ID_ON_REGISTER = None

BAD_MAIL_PROVIDERS = ()
BAD_MAIL_PROVIDER_REGEX = ()
NOFOLLOW_EXCLUDED = set()

TIMEZONE_BG = None
TIMEZONE_MAP = None
TIMEZONE_DETECT_BACKEND = None

TERMS_OF_SERVICE_URL = None
DEFAULT_USER_LANGUAGE = 'PY2'

COMPRESS_ENABLED = not DEBUG

PHANTOMJS = ''
PHANTOMJS_PDF_ZOOM = 0.75
PHANDOMJS_PDF_TIMEOUT = 5.0
PHANTOMJS_PAPER_SIZE = 'Letter'

SLIMERJS = ''
SLIMERJS_PDF_ZOOM = 0.75
SLIMERJS_FIREFOX_PATH = ''
SLIDERJS_PAPER_SIZE = 'Letter'

PUPPETEER_MODULE = '/usr/lib/node_modules/puppeteer'
PUPPETEER_PAPER_SIZE = 'Letter'

PYGMENT_THEME = 'pygment-github.css'
INLINE_JQUERY = True
INLINE_FONTAWESOME = True
JQUERY_JS = '//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'
FONTAWESOME_CSS = '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'
DMOJ_CANONICAL = ''

# Application definition

Expand Down Expand Up @@ -312,6 +397,7 @@

# Bridged configuration
BRIDGED_JUDGE_ADDRESS = [('localhost', 9999)]
BRIDGED_JUDGE_PROXIES = None
BRIDGED_DJANGO_ADDRESS = [('localhost', 9998)]
BRIDGED_DJANGO_CONNECT = None

Expand All @@ -321,6 +407,7 @@
EVENT_DAEMON_GET = 'ws://localhost:9996/'
EVENT_DAEMON_POLL = '/channels/'
EVENT_DAEMON_KEY = None
EVENT_DAEMON_AMQP_EXCHANGE = 'dmoj-events'
EVENT_DAEMON_SUBMISSION_KEY = '6Sdmkx^%pk@GsifDfXcwX*Y7LRF%RGT8vmFpSxFBT$fwS7trc8raWfN#CSfQuKApx&$B#Gh2L7p%W!Ww'

# Internationalization
Expand Down
4 changes: 2 additions & 2 deletions dmoj/throttle_mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@


def new_email():
cache.add('error_email_throttle', 0, getattr(settings, 'DMOJ_EMAIL_THROTTLING', DEFAULT_THROTTLE)[1])
cache.add('error_email_throttle', 0, settings.DMOJ_EMAIL_THROTTLING[1])
return cache.incr('error_email_throttle')


class ThrottledEmailHandler(AdminEmailHandler):
def __init__(self, *args, **kwargs):
super(ThrottledEmailHandler, self).__init__(*args, **kwargs)

self.throttle = getattr(settings, 'DMOJ_EMAIL_THROTTLING', DEFAULT_THROTTLE)[0]
self.throttle = settings.DMOJ_EMAIL_THROTTLING[0]

def emit(self, record):
try:
Expand Down
2 changes: 1 addition & 1 deletion judge/admin/contest.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def rejudge_view(self, request, contest_id, problem_id):

queryset = ContestSubmission.objects.filter(problem_id=problem_id).select_related('submission')
if not request.user.has_perm('judge.rejudge_submission_lot') and \
len(queryset) > getattr(settings, 'DMOJ_SUBMISSIONS_REJUDGE_LIMIT', 10):
len(queryset) > settings.DMOJ_SUBMISSIONS_REJUDGE_LIMIT:
self.message_user(request, ugettext('You do not have the permission to rejudge THAT many submissions.'),
level=messages.ERROR)
return
Expand Down
2 changes: 1 addition & 1 deletion judge/admin/submission.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def judge(self, request, queryset):
return
queryset = queryset.order_by('id')
if not request.user.has_perm('judge.rejudge_submission_lot') and \
queryset.count() > getattr(settings, 'DMOJ_SUBMISSIONS_REJUDGE_LIMIT', 10):
queryset.count() > settings.DMOJ_SUBMISSIONS_REJUDGE_LIMIT:
self.message_user(request, gettext('You do not have the permission to rejudge THAT many submissions.'),
level=messages.ERROR)
return
Expand Down
2 changes: 1 addition & 1 deletion judge/comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,6 @@ def get_context_data(self, **kwargs):
context['is_new_user'] = (not self.request.user.is_staff and
not profile.submission_set.filter(points=F('problem__points')).exists())
context['comment_list'] = queryset
context['vote_hide_threshold'] = getattr(settings, 'DMOJ_COMMENT_VOTE_HIDE_THRESHOLD', -5)
context['vote_hide_threshold'] = settings.DMOJ_COMMENT_VOTE_HIDE_THRESHOLD

return context
2 changes: 1 addition & 1 deletion judge/event_poster.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

__all__ = ['last', 'post']

if not getattr(settings, 'EVENT_DAEMON_USE', False):
if not settings.EVENT_DAEMON_USE:
real = False

def post(channel, message):
Expand Down
2 changes: 1 addition & 1 deletion judge/event_poster_amqp.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class EventPoster(object):
def __init__(self):
self._connect()
self._exchange = getattr(settings, 'EVENT_DAEMON_AMQP_EXCHANGE', 'dmoj-events')
self._exchange = settings.EVENT_DAEMON_AMQP_EXCHANGE

def _connect(self):
self._conn = pika.BlockingConnection(pika.URLParameters(settings.EVENT_DAEMON_AMQP))
Expand Down
18 changes: 6 additions & 12 deletions judge/feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@


class ProblemFeed(Feed):
title = 'Recently Added %s Problems' % getattr(settings, 'SITE_NAME', 'DMOJ')
title = 'Recently Added %s Problems' % settings.SITE_NAME
link = '/'
description = 'The latest problems added on the %s website' % (
getattr(settings, 'SITE_LONG_NAME', getattr(settings, 'SITE_NAME', 'DMOJ'))
)
description = 'The latest problems added on the %s website' % settings.SITE_LONG_NAME

def items(self):
return Problem.objects.filter(is_public=True, is_organization_private=False).order_by('-date', '-id')[:25]
Expand Down Expand Up @@ -42,11 +40,9 @@ class AtomProblemFeed(ProblemFeed):


class CommentFeed(Feed):
title = 'Latest %s Comments' % getattr(settings, 'SITE_NAME', 'DMOJ')
title = 'Latest %s Comments' % settings.SITE_NAME
link = '/'
description = 'The latest comments on the %s website' % (
getattr(settings, 'SITE_LONG_NAME', getattr(settings, 'SITE_NAME', 'DMOJ'))
)
description = 'The latest comments on the %s website' % settings.SITE_LONG_NAME

def items(self):
return Comment.most_recent(AnonymousUser(), 25)
Expand Down Expand Up @@ -74,11 +70,9 @@ class AtomCommentFeed(CommentFeed):


class BlogFeed(Feed):
title = 'Latest %s Blog Posts' % getattr(settings, 'SITE_NAME', 'DMOJ')
title = 'Latest %s Blog Posts' % settings.SITE_NAME
link = '/'
description = 'The latest blog posts from the %s' % (
getattr(settings, 'SITE_LONG_NAME', getattr(settings, 'SITE_NAME', 'DMOJ'))
)
description = 'The latest blog posts from the %s' % settings.SITE_LONG_NAME

def items(self):
return BlogPost.objects.filter(visible=True, publish_on__lte=timezone.now()).order_by('-sticky', '-publish_on')
Expand Down
6 changes: 3 additions & 3 deletions judge/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class Meta:
'ace_theme': Select2Widget(attrs={'style': 'width:200px'}),
}

has_math_config = bool(getattr(settings, 'MATHOID_URL', False))
has_math_config = bool(settings.MATHOID_URL)
if has_math_config:
fields.append('math_engine')
widgets['math_engine'] = Select2Widget(attrs={'style': 'width:200px'})
Expand All @@ -50,7 +50,7 @@ class Meta:

def clean(self):
organizations = self.cleaned_data.get('organizations') or []
max_orgs = getattr(settings, 'DMOJ_USER_MAX_ORGANIZATION_COUNT', 3)
max_orgs = settings.DMOJ_USER_MAX_ORGANIZATION_COUNT

if sum(org.is_open for org in organizations) > max_orgs:
raise ValidationError(
Expand Down Expand Up @@ -125,7 +125,7 @@ def widget_attrs(self, widget):


class TOTPForm(Form):
TOLERANCE = getattr(settings, 'DMOJ_TOTP_TOLERANCE_HALF_MINUTES', 1)
TOLERANCE = settings.DMOJ_TOTP_TOLERANCE_HALF_MINUTES

totp_token = NoAutoCompleteCharField(validators=[
RegexValidator('^[0-9]{6}$', _('Two Factor Authentication tokens must be 6 decimal digits.')),
Expand Down
4 changes: 2 additions & 2 deletions judge/jinja2/markdown/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

logger = logging.getLogger('judge.html')

NOFOLLOW_WHITELIST = getattr(settings, 'NOFOLLOW_EXCLUDED', set())
NOFOLLOW_WHITELIST = settings.NOFOLLOW_EXCLUDED


class CodeSafeInlineGrammar(mistune.InlineGrammar):
Expand Down Expand Up @@ -105,7 +105,7 @@ def header(self, text, level, *args, **kwargs):

@registry.filter
def markdown(value, style, math_engine=None, lazy_load=False):
styles = getattr(settings, 'MARKDOWN_STYLES', {}).get(style, getattr(settings, 'MARKDOWN_DEFAULT_STYLE', {}))
styles = settings.MARKDOWN_STYLES.get(style, settings.MARKDOWN_DEFAULT_STYLE)
escape = styles.get('safe_mode', True)
nofollow = styles.get('nofollow', True)
texoid = TEXOID_ENABLED and styles.get('texoid', False)
Expand Down
2 changes: 1 addition & 1 deletion judge/judgeapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def _post_update_submission(submission, done=False):


def judge_request(packet, reply=True):
sock = socket.create_connection(getattr(settings, 'BRIDGED_DJANGO_CONNECT', None) or
sock = socket.create_connection(settings.BRIDGED_DJANGO_CONNECT or
settings.BRIDGED_DJANGO_ADDRESS[0])

output = json.dumps(packet, separators=(',', ':'))
Expand Down
2 changes: 1 addition & 1 deletion judge/management/commands/runbridged.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def handle(self, *args, **options):
except ImportError:
pass
else:
proxies = getattr(settings, 'BRIDGED_JUDGE_PROXIES', None)
proxies = settings.BRIDGED_JUDGE_PROXIES
if proxies:
judge_handler = judge_handler.with_proxy_set(proxies)

Expand Down
11 changes: 5 additions & 6 deletions judge/models/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class Profile(models.Model):
user = models.OneToOneField(User, verbose_name=_('user associated'), on_delete=models.CASCADE)
about = models.TextField(verbose_name=_('self-description'), null=True, blank=True)
timezone = models.CharField(max_length=50, verbose_name=_('location'), choices=TIMEZONE,
default=getattr(settings, 'DEFAULT_USER_TIME_ZONE', 'America/Toronto'))
default=settings.DEFAULT_USER_TIME_ZONE)
language = models.ForeignKey('Language', verbose_name=_('preferred language'), on_delete=models.CASCADE)
points = models.FloatField(default=0, db_index=True)
performance_points = models.FloatField(default=0, db_index=True)
Expand All @@ -98,7 +98,7 @@ class Profile(models.Model):
current_contest = models.OneToOneField('ContestParticipation', verbose_name=_('current contest'),
null=True, blank=True, related_name='+', on_delete=models.SET_NULL)
math_engine = models.CharField(verbose_name=_('math engine'), choices=MATH_ENGINES_CHOICES, max_length=4,
default=getattr(settings, 'MATHOID_DEFAULT_TYPE', 'auto'),
default=settings.MATHOID_DEFAULT_TYPE,
help_text=_('the rendering engine used to render math'))
is_totp_enabled = models.BooleanField(verbose_name=_('2FA enabled'), default=False,
help_text=_('check to enable TOTP-based two factor authentication'))
Expand All @@ -119,8 +119,7 @@ def organization(self):
def username(self):
return self.user.username

_pp_table = [pow(getattr(settings, 'DMOJ_PP_STEP', 0.95), i)
for i in range(getattr(settings, 'DMOJ_PP_ENTRIES', 100))]
_pp_table = [pow(settings.DMOJ_PP_STEP, i) for i in range(settings.DMOJ_PP_ENTRIES)]

def calculate_points(self, table=_pp_table):
from judge.models import Problem
Expand All @@ -130,7 +129,7 @@ def calculate_points(self, table=_pp_table):
.values_list('max_points', flat=True).filter(max_points__gt=0))
extradata = Problem.objects.filter(submission__user=self, submission__result='AC', is_public=True) \
.values('id').distinct().count()
bonus_function = getattr(settings, 'DMOJ_PP_BONUS_FUNCTION', lambda n: 300 * (1 - 0.997 ** n))
bonus_function = settings.DMOJ_PP_BONUS_FUNCTION
points = sum(data)
problems = len(data)
entries = min(len(data), len(table))
Expand Down Expand Up @@ -164,7 +163,7 @@ def __str__(self):
return self.user.username

@classmethod
def get_user_css_class(cls, display_rank, rating, rating_colors=getattr(settings, 'DMOJ_RATING_COLORS', False)):
def get_user_css_class(cls, display_rank, rating, rating_colors=settings.DMOJ_RATING_COLORS):
if rating_colors:
return 'rating %s %s' % (rating_class(rating) if rating is not None else 'rate-none', display_rank)
return display_rank
Expand Down
Loading

0 comments on commit 7eb13ee

Please sign in to comment.