-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels.py
1371 lines (1105 loc) · 41.8 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2011- Csaba Hoch
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import logging
import math
import random
import re
import sys
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
version = '1.3.0'
##### Constants #####
# The maximum number of characters used to represent a word
WORD_PREFIX = 40;
# The minimum dimness required for a word to be practiced during "early
# practice". The dimness of 0.75 means that:
#
# actual_interval_len = 0.75 * due_interval
# due_interval2_len = 2 * actual_interval_len = 1.5 * due_interval_len
#
# strength1 = 1 + log_2 due_interval_len
# strength2 = 1 + log_2 due_interval2_len
#
# From these:
#
# strength2 = 1 + log_2 1.5 * due_interval_len
# strength2 = 1 + log_2 1.5 + log_2 due_interval_len
# strength2 = 1 + log_2 due_interval_len + log_2 1.5
# strength2 = strength1 + log_2 1.5
# strength2 = strength1 + 0.5850
#
# General equasion:
#
# log_2 2 * (MIN_DIMNESS_FOR_EARLY_PRACTICE) = strength_increment; i.e.
# MIN_DIMNESS_FOR_EARLY_PRACTICE = (2 ^ strength_increment) / 2
MIN_DIMNESS_FOR_EARLY_PRACTICE = 0.75;
##### Utility functions #####
def unexpected_value(name, value):
msg = 'Unexpected value for variable "%s": %s' % (name, value)
raise EWException(msg)
def remove_trailing_newline(text):
if (len(text) > 1) and (text[-1] == '\n'):
text = text[:-1]
return text
def escape_html(text):
text = re.sub('&', '&', text)
text = re.sub('<', '<', text)
text = re.sub('>', '>', text)
return text
def indent_html(text, add_space_count, skip_first_line=False):
def insert_nbps(matchobject):
"""Returns the same number of " ":s as the number of matched
characters."""
spaces = matchobject.group(1)
space_count = len(spaces)
space_count += add_space_count
return ' ' * space_count
if skip_first_line:
pattern = r'(?<=\n)( *)'
else:
pattern = r'^( *)'
regexp = re.compile(pattern, re.MULTILINE)
text = re.sub(regexp, insert_nbps, text)
return text
def newline_to_br(text, keepend):
if keepend:
return re.sub(r'\n', '<br/>', text)
else:
return '<br/>'.join(text.splitlines())
class NotFound(BaseException):
pass
class TagNotAccepted(BaseException):
pass
def try_match(regexp, s, i):
r = re.compile(regexp)
m = r.match(s, i)
if m:
try:
g = m.group(1)
except IndexError:
g = ''
return m.end(0), g
else:
raise NotFound()
# List of tags from http://www.w3schools.com/tags/ref_byfunc.asp
ALLOWED_TAGS = [
# Basic
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'p',
'br',
'hr',
# Formatting
'abbr',
'b',
'blockquote',
'cite',
'code',
'em',
'i',
'pre',
'q',
'small',
'strong',
'sub',
'sup',
'u',
# Images
'img',
# Links
'a',
# Lists
'ul',
'ol',
'li',
'dl',
'dt',
'dd',
# Style/Sections
'style',
'div',
'span',
# Tables
'table',
'caption',
'th',
'tr',
'td',
'thead',
'tbody',
'tfoot',
'col',
'colgroup',
]
ALLOWED_TAGS_SET = set(ALLOWED_TAGS)
ALLOWED_ATTRIBUTES = [
# Global attributes
# http://www.w3schools.com/tags/ref_standardattributes.asp
'class',
'id',
'lang',
'style',
'title',
# <a>
'href',
'target',
# <img>
'alt',
'height',
'src',
'width',
# <table>
'border',
# <td>
'colspan',
'rowspan',
'headers',
]
ALLOWED_ATTRIBUTES_SET = set(ALLOWED_ATTRIBUTES)
def simple_html_to_html(s, add_br, add_space_count):
i = 0
html_result = []
s = remove_trailing_newline(s)
if s == '':
return ''
first = True
while True:
i, substr = try_match('([^<&]*)', s, i)
text = escape_html(substr)
if add_br:
text = indent_html(text, add_space_count, skip_first_line=not first)
text = newline_to_br(text, keepend=True)
html_result.append(text)
first = False
if i == len(s):
break
if s[i] == '&':
html_result.append('&')
i += 1
continue
# s[i] == '<'
tag_start = i
try:
# Read the opening '<' or '</'
i, _ = try_match(r'<\s*/?', s, i)
# Read the tag name
i, html_tag = try_match(r'\s*([^<>"\'= \t]+)\b', s, i)
if html_tag not in ALLOWED_TAGS_SET:
raise TagNotAccepted()
try:
while True:
i, html_attr = \
try_match(r'\s*([^<>"\'= \t]+)' # src
r'\s*=\s*' # =
r'(?:[^<>"\'= \t]+\b|' # pic
r'"[^"]*"|' # 'pic.jpg'
r'\'[^\']*\')', # "pic.jpg"
s, i)
if html_attr not in ALLOWED_ATTRIBUTES_SET:
raise TagNotAccepted()
except NotFound:
# We didn't find any more attributes
pass
# Read the closing '>' or '/>'
i, _ = try_match(r'\s*/?>', s, i)
except NotFound:
# We didn't find a proper tag
html_result.append('<')
i = tag_start + 1
except TagNotAccepted:
# We tag we found has a name or attribute that is not allowed
html_result.append('<')
i = tag_start + 1
else:
html_result.append(s[tag_start:i])
return ''.join(html_result)
def test_simple_html_to_html():
def test(input, expected_output):
actual_output = simple_html_to_html(input,
add_br=False,
add_space_count=0)
if actual_output != expected_output:
print('Expected and actual output do not match:')
print('Input: ', input)
print('Expected output:', expected_output)
print('Actual output: ', actual_output)
print()
# Edge cases
test('', '')
test('<', '<')
test('>', '>')
test('a<a', 'a<a')
test('<br>', '<br>')
test('< br >', '< br >')
test('<br/>', '<br/>')
test('<unknown>', '<unknown>')
# Ampersand
test('&',
'&')
# Different attribute value formats
test('ab<a href=xy>b</a>',
'ab<a href=xy>b</a>')
test('ab<a href="xy \' z">b</a>',
'ab<a href="xy \' z">b</a>')
test('ab<a href=\'xy " z\'>b</a>',
'ab<a href=\'xy " z\'>b</a>')
# More complex examples
test('<img src=xy title="hello world">',
'<img src=xy title="hello world">')
test('ab<img src=xy title="hello world">b',
'ab<img src=xy title="hello world">b')
test('<img src=xy title="hello world"><img src=xy title="hello world">',
'<img src=xy title="hello world"><img src=xy title="hello world">')
##### Date handling #####
def datetime_to_ts(dt):
# The datetime object is assumed to be in UTC.
return dt.replace(tzinfo=datetime.timezone.utc).timestamp()
def ts_to_datetime(ts):
# The datetime object will be in UTC.
return datetime.datetime.utcfromtimestamp(ts)
def date_to_html(d):
"""Return the date in yyyy-mm-dd format.
But use a non-breaking hyphen ("‑") between mm and dd. If we used only
normal hyphens, a date could be broken in the "Search and operations" page
as 2023-01<br>02. That would not be very readable. Breaking it as
2023-<br>01-02 looks much better.
"""
return '{:04d}-{:02d}‑{:02d}'.format(d.year, d.month, d.day)
def date_to_ord(d):
return d.toordinal()
def ord_to_date(ordinal):
return datetime.date.fromordinal(ordinal)
# General concept:
#
# words at DAY shall be asked
# if user_time(utc) >= DAY_00:00
# where user_time = now_utc + timezone - turning_point
# Example (DAY example in backets):
#
# timezone: UTC+2 (CEST) -> 2:00
# turning_point: 3:00
# words at 2011-01-10 shall be asked
# if user_time + 2:00 - 3:00 >= 2011-01-10_00:00
# if user_time >= 2011-01-10_01:00
def get_user_time(user=None, timezone=None, turning_point=None, now=None):
# set timezone and turning_point
if user is not None:
ewuser = get_ewuser(user)
timezone = ewuser.timezone
turning_point = ewuser.turning_point
elif (timezone is None or turning_point is None):
raise EWException('get_user_time: Either the user or the timezone '
'and the turning_point parameter has to be not None')
# set `now`
if now is None:
now = datetime.datetime.utcnow()
return (now
+ datetime.timedelta(hours=timezone)
- datetime.timedelta(minutes=turning_point))
def is_word_due(word_date, user_time):
word_dt_0 = datetime.datetime(year=word_date.year,
month=word_date.month,
day=word_date.day)
return user_time >= word_dt_0
def get_today(user=None, timezone=None, turning_point=None, now=None):
user_time = get_user_time(user, timezone, turning_point, now)
return datetime.date(user_time.year, user_time.month, user_time.day)
##### Word strengthener/weakener algorithms #####
def get_date_info(strength, due_date):
due_interval = int(round(2 ** (strength - 1)))
if due_interval > 36500: # ~100 years
due_interval = 36500
last_query_date = (due_date - datetime.timedelta(days=due_interval))
return last_query_date, due_interval
def calc_strengthen_double_due(strength, due_date, today):
if strength > 16: # 2**16 = ~179 years
strength = 16
new_due_interval_len = datetime.timedelta(2 ** max(strength, 0))
strength2 = strength + 1
date2 = today + new_due_interval_len
return strength2, date2
def calc_strengthen_double_actual(strength, due_date, today):
#######################################################################
# Number of days before the word
# is asked again (i.e. length of
# the next "due interval")
# ^ x
# | x
# 2 ^ strength1 + . . . . . . . X (dimness = 1 at this point)
# | x.
# | x .
# | x .
# | x .
# | x .
# 0 +---------X-----+----------> Day on which the
# ^ ^ word is practiced
# last_query_date due_date
#
# <----->
# (previous) due_interval = "2 ^ (strength1 - 1)" days
#######################################################################
#######################################################################
# Original strength-calculating function:
#
# New strength of the
# word (strength2)
# ^
# | xxxxxxxxxxxxxxxxxxx
# strength1 + 2 + xxxxxxxxxxxxxxxx
# strength1 + 1 + . . . . Xxxxxxxx
# strength1 + . . Xxxx.
# | xx. .
# | x . .
# 0 +-x---+---+----------------------------------------->
# ^ ^ ^ Day on which the
# last_query_date | due_date word is practiced
# dimness = 0 | dimness = 1
# |
# half-way between last_query_date and due_date
# dimness = 0.5
#
# <------->
# (previous) due_interval = "2 ^ (strength1 - 1)" days
#######################################################################
#######################################################################
# Modified strength-calculating function (strength2 should not be
# smaller than strength1):
#
# New strength of the
# word (strength2)
# ^
# | xxxxxxxxxxxxxxxxxxx
# strength1 + 2 + xxxxxxxxxxxxxxxx
# strength1 + 1 + . . . . Xxxxxxxx
# strength1 + xxxxXxxx.
# | . .
# | . .
# 0 +-+---+---+----------------------------------------->
# ^ ^ Day on which the
# last_query_date due_date word is practiced
#
# <------->
# (previous) due_interval = "2 ^ (strength1 - 1)" days
#######################################################################
#######################################################################
#
# Calculating due_interval2_len:
#
# actual_interval_len = day - last_query_date
# due_interval2_len = 2 * actual_interval_len
#
# Calculating strength2 (original):
#
# due_interval2_len = 2 ^ (strength2 - 1) // log_2 ^ ()
# log_2 due_interval2_len = (strength2 - 1) // () + 1
# 1 + log_2 due_interval2_len = strength2
# strength2 = 1 + log_2 due_interval2_len
#
# Calculating strength2 (modified):
#
# strength2 = max(1 + log_2 due_interval2_len, strength1)
#
#######################################################################
if strength <= 0:
# if the word is new, ask tomorrow
strength2 = strength + 1
date2 = today + datetime.timedelta(days=1)
else:
last_query_date, due_interval_len = \
get_date_info(strength, due_date)
actual_interval_len = (today - last_query_date).days
if due_interval_len <= 0:
# if the word was already strengthened today, don't change
# anything
strength2 = strength
date2 = due_date
else:
# otherwise use the nice equasion
due_interval2_len = 2 * actual_interval_len
strength2 = max(1 + math.log(due_interval2_len, 2), strength)
date2 = today + datetime.timedelta(days=due_interval2_len)
return strength2, date2
def calc_strengthen(strength, due_date, today, strengthener_method):
if strengthener_method == 'double_due':
return calc_strengthen_double_due(strength, due_date, today)
else:
return calc_strengthen_double_actual(strength, due_date, today)
def calc_weaken(strength, today):
strength2 = min(strength, 0)
date2 = today
return strength2, date2
##### Model classes #####
class EWUser(models.Model):
user = models.OneToOneField(User,
primary_key=True,
on_delete=models.CASCADE)
# The language of the user interface
lang = models.CharField(max_length=10, default='en')
# Time difference with UTC in hours (positive value means east from GMT)
timezone = models.IntegerField(default=0)
# How many minutes after midnight should we ask the words of the new day
# (may be negative)
turning_point = models.IntegerField(default=0)
# Word order on practice page
practice_word_order = models.CharField(default='random', max_length=20)
strengthener_method = models.CharField(default='double_actual',
max_length=20)
# Practice page arrangement
practice_arrangement = models.CharField(default='normal', max_length=20)
pgupdown_behavior = models.CharField(default='normal', max_length=20)
quick_labels = models.CharField(default='quick', max_length=255, blank=True)
# Font sizes on the practice page
button_size = models.IntegerField(default=35)
question_size = models.IntegerField(default=20)
answer_size = models.IntegerField(default=20)
explanation_size = models.IntegerField(default=20)
# List of available extra features
extras = models.CharField(default='', max_length=255, blank=True)
# Whether the user wants to receive emails about new ExponWords features
release_emails = models.BooleanField(default=True)
def __unicode__(self):
return self.user.username
def __str__(self):
return self.__unicode__()
def get_turning_point_str(self):
sign = '-' if self.turning_point < 0 else ''
tpa = abs(self.turning_point)
return '%s%02d:%02d' % (sign, tpa / 60, tpa % 60)
def set_turning_point_str(self, s):
s = s.strip()
r = re.match(r'^([+-]?)(\d+):(\d\d)$', s)
if r is None:
raise EWException('Invalid turning point string')
sign, hours, minutes = r.group(1), int(r.group(2)), int(r.group(3))
self.turning_point = ((-1 if sign == '-' else 1) *
(hours * 60 + minutes))
def get_quick_labels(self):
return self.quick_labels.split()
@staticmethod
def get_email_receiver_users():
return [user
for user in
(User.objects.filter(ewuser__release_emails=True).
exclude(email='') |
User.objects.filter(ewuser=None).
exclude(email=''))]
def get_ewuser(user):
try:
return EWUser.objects.get(pk=user)
except EWUser.DoesNotExist as e:
ewuser = EWUser(pk=user.pk)
ewuser.save()
return EWUser.objects.get(pk=user)
class WDict(models.Model):
# WDict = word dictionary (as opposed to the dictionary data type which is
# an "object dictionary")
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255) # the name of the dictionary
lang1 = models.CharField(max_length=255)
lang2 = models.CharField(max_length=255)
deleted = models.BooleanField(default=False)
practice_word_order = models.CharField(default='default', max_length=20)
strengthener_method = models.CharField(default='default', max_length=20)
text_format = models.CharField(default='text', max_length=20)
css = models.TextField(blank=True)
def __unicode__(self):
return self.name
def __str__(self):
return self.__unicode__()
def get_words_to_practice_today(self, word_list_type='normal'):
assert(word_list_type in ('normal', 'early'))
user_time = get_user_time(user=self.user)
today = get_today(self.user)
result = []
for wp in self.wordpair_set.filter(deleted=False):
for direction in (1, 2):
is_due = is_word_due(wp.get_date(direction), user_time)
if word_list_type == 'normal':
is_needed = is_due
else:
is_needed = (is_due or
(wp.get_strength(direction) > 0 and
wp.get_dimness(direction, today) >=
MIN_DIMNESS_FOR_EARLY_PRACTICE))
if is_needed:
result.append((wp, direction))
return result
def sort_words(self, words, order=None, word_list_type='normal'):
# order = 'random' | 'zero_first' |
# ('dimness', dimness_day, dimness_direction)
# dimness_day = 'today' | 'tomorrow'
# dimness_direction = 'dimmer_first' | 'dimmer_last'
# Converting `order` to the format given above
if order is None:
if word_list_type == 'normal':
order = self.get_practice_word_order()
if order in ('dimmer_first', 'dimmer_last'):
order = ('dimness', 'tomorrow', order)
elif word_list_type == 'early':
order = ('dimness', 'today', 'dimmer_first')
else:
unexpected_value('word_list_type', word_list_type)
# Converting `order` to a string and possibly setting up other
# variables
if order in ('random', 'zero_first'):
pass
elif order[0] == 'dimness':
order, dimness_day, dimness_direction = order
else:
unexpected_value('order', order)
random.shuffle(words)
if order == 'random':
pass
elif order in ('zero_first', 'dimness'):
# Separating weak words (which should come first) and strong words
# (which should come last)
weak_words = [] # words with zero or negative strength
strong_words = [] # words with positive strength
for (wp, direction) in words:
if wp.get_strength(direction) > 0:
strong_words.append((wp, direction))
else:
weak_words.append((wp, direction))
# Ordering the strong words by dimness
if order == 'dimness':
# First sort by strength
def strength_key_fun(item):
(wp, direction) = item
return wp.get_strength(direction)
strong_words.sort(key=strength_key_fun)
# Then sort by dimness
if dimness_day == 'today':
dimness_day = get_today(self.user)
elif dimness_day == 'tomorrow':
dimness_day = get_today(self.user) + \
datetime.timedelta(days=1)
else:
unexpected_value('dimness_day', dimness_day)
def dimness_key_fun(item):
(wp, direction) = item
return wp.get_dimness(direction, dimness_day)
reverse = (dimness_direction == 'dimmer_first')
strong_words.sort(key=dimness_key_fun, reverse=reverse)
words[:] = weak_words + strong_words
else:
unexpected_value('order', order)
def get_practice_word_order(self):
if self.practice_word_order == 'default':
return get_ewuser(self.user).practice_word_order
else:
return self.practice_word_order
def get_strengthener_method(self):
if self.strengthener_method == 'default':
return get_ewuser(self.user).strengthener_method
else:
return self.strengthener_method
def get_duplicates(self, wp):
f = WordPair.objects.filter
lang1_same = set(f(wdict=self,
word_in_lang1=wp.word_in_lang1,
deleted=False))
lang1_same.discard(wp)
lang2_same = set(f(wdict=self,
word_in_lang2=wp.word_in_lang2,
deleted=False))
lang2_same.discard(wp)
same_word_pairs = lang1_same & lang2_same
similar_word_pairs = (lang1_same | lang2_same) - same_word_pairs
sorted_same_wps = sorted(same_word_pairs, key=lambda wp: wp.id)[:3]
sorted_similar_wps =sorted(similar_word_pairs, key=lambda wp: wp.id)[:3]
return sorted_same_wps, sorted_similar_wps
def get_css(self):
if self.css == 'text':
return None
else:
# Replace <, otherwise the user could run any code in the browser with
# the following CSS:
#
# </style>
# CODE
# <style>
#
# On the other hand, > cannot be replaced, because then this would not
# work:
# </style>
# .class1 > .class2
# <style>
return re.sub('<', '<', self.css)
class WordPair(models.Model):
# each word pair belongs to a dictionary
wdict = models.ForeignKey(WDict, on_delete=models.CASCADE)
# the word in the first/second language and notes:
word_in_lang1 = models.TextField()
word_in_lang2 = models.TextField()
explanation = models.TextField(blank=True)
# strengths of the word
strength1 = models.FloatField(default=0)
strength2 = models.FloatField(default=0)
# dates of the next practice
date_added = models.DateField()
date1 = models.DateField()
date2 = models.DateField()
# labels
labels = models.CharField(max_length=255, blank=True)
# whether the word pair is deleted or not
deleted = models.BooleanField(default=False)
def save(self):
self.normalize()
return models.Model.save(self)
def normalize(self):
self.word_in_lang1 = self.word_in_lang1.strip()
self.word_in_lang2 = self.word_in_lang2.strip()
self.explanation = self.explanation.rstrip()
self.normalize_labels()
def get_html(self, field):
add_space_count = (4 if field == 'explanation' else 0)
if self.wdict.text_format == 'text':
text = getattr(self, field)
#text = remove_trailing_newline(text)
text = escape_html(text)
text = indent_html(text, add_space_count=add_space_count)
text = newline_to_br(text, keepend=False)
return text
elif self.wdict.text_format == 'html':
return simple_html_to_html(getattr(self, field),
add_br=False,
add_space_count=0)
elif self.wdict.text_format == 'html_ws':
return simple_html_to_html(getattr(self, field),
add_br=True,
add_space_count=add_space_count)
def __unicode__(self):
return ('<%s -- %s>' %
(repr(self.word_in_lang1), repr(self.word_in_lang2)))
def __str__(self):
return self.__unicode__()
def get_strength(self, direction):
if direction == 1:
return self.strength1
else:
return self.strength2
def set_strength(self, direction, value):
if direction == 1:
self.strength1 = value
else:
self.strength2 = value
def get_date(self, direction):
if direction == 1:
return self.date1
else:
return self.date2
def set_date(self, direction, value):
if direction == 1:
self.date1 = value
else:
self.date2 = value
def strengthen(self, direction, dry_run=False, day=None):
if day is None:
day = get_today(self.wdict.user)
method = self.wdict.get_strengthener_method()
date = self.get_date(direction)
strength = self.get_strength(direction)
strength2, date2 = calc_strengthen(strength, date, day, method)
if not dry_run:
self.set_strength(direction, strength2)
self.set_date(direction, date2)
return strength2, date2
def weaken(self, direction, dry_run=False, day=None):
if day is None:
day = get_today(self.wdict.user)
strength = self.get_strength(direction)
strength2, date2 = calc_weaken(strength, day)
if not dry_run:
self.set_strength(direction, strength2)
self.set_date(direction, date2)
return strength2, date2
def get_date_info(self, direction):
due_date = self.get_date(direction)
last_query_date, due_interval = \
get_date_info(self.get_strength(direction), due_date)
return last_query_date, due_date, due_interval
def get_dimness(self, direction, day, silent=False):
# The dimness function does not have a value when strength = 0.
# (Mathematically, it would have the value of 0, but in ExponWords,
# strength = 0 means is a special value meaning that the word
# definitely needs practice, and 0 dimness would mean that it does not
# need a practice.)
#
# The dimness function looks like this when strength > 0:
#
# dimness
# ^ x
# | x
# 1 + . . . . . . . X
# | x.
# | x .
# | x .
# | x .
# | x .
# 0 +---------X-----+----------> day
# ^ ^
# last_query_date due_date
#
# <----->
# due_interval = "2 ^ (strength - 1)" days
strength = self.get_strength(direction)
if silent and strength == 0:
return None
assert(strength > 0)
last_query_date, due_date, due_interval = self.get_date_info(direction)
return float((day - last_query_date).days) / due_interval
@staticmethod
def get_label_set_from_str(s):
return set(s.split())
def get_label_set(self):
return self.get_label_set_from_str(self.labels)
def set_label_set(self, label_set):
self.labels = ' '.join(sorted(label_set))
def normalize_labels(self):
self.set_label_set(self.get_label_set())
def add_labels(self, labels):
self.set_label_set(self.get_label_set() |
self.get_label_set_from_str(labels))
def remove_labels(self, labels):
self.set_label_set(self.get_label_set() -
self.get_label_set_from_str(labels))
def set_labels(self, labels):
self.set_label_set(self.get_label_set_from_str(labels))
@staticmethod
def get_simple_fields():
return ('word_in_lang1',
'word_in_lang2',
'explanation')
@staticmethod
def get_advanced_fields():
return ('labels',
'date_added',
'date1',
'date2',
'strength1',
'strength2')
@staticmethod
# fields_to_be_edited = simple_fields + advanced_fields
def get_fields_to_be_edited():
return ('word_in_lang1',
'word_in_lang2',
'explanation',
'labels',
'date_added',
'date1',
'date2',
'strength1',
'strength2')
@staticmethod
def get_fields_to_search():
return ('word_in_lang1',
'word_in_lang2',
'explanation')
@staticmethod
def prefix(s, max_length):
if len(s) <= max_length: