/
sell.py
executable file
·1593 lines (1519 loc) · 78.5 KB
/
sell.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
#!/usr/bin/env python3
# pylint: disable=too-many-lines
"""
======= pySELL =================================================================
A Python based Simple E-Learning Language
for the simple creation of interactive courses
LICENSE GPLv3
AUTHOR Andreas Schwenk <mailto:contact@compiler-construction.com>
DOCS Refer to https://github.com/andreas-schwenk/pysell and read the
descriptions at the end of the page
USAGE Only file 'sell.py' is required to compile question files
COMMAND python3 [-J] sell.py PATH
ARGUMENTS -J is optional and generates a JSON output file for debugging
EXAMPLE python3 sell.py examples/ex1.txt
OUTPUT examples/ex1.html, examples/ex1_DEBUG.html
FAQ
Q: Why is this file so long?
A: The intention is to provide pySelL as ONE file, that can easily be
shared and modified.
Q: You could also package and publish pySELL as a package!
A: Sure. Maybe this will happen in the future..
"""
import base64
import datetime
import io
import json
import os
import re
import sys
from typing import Self
class SellError(Exception):
"""exception"""
# pylint: disable-next=too-few-public-methods
class Lexer:
"""Scanner that takes a string input and returns a sequence of tokens;
one at a time."""
def __init__(self, src: str) -> None:
"""sets the source to be scanned"""
# the source code
self.src: str = src
# the current token
self.token: str = ""
# the current input position
self.pos: int = 0
# set the first token to self.token
self.next()
def next(self) -> None:
"""gets the next token"""
# start with a fresh token
self.token = ""
# loop up to the next special character
stop = False
while not stop and self.pos < len(self.src):
# get the next character from the input
ch = self.src[self.pos]
# in case that we get a special character (a.k.a delimiter),
# we stop
if ch in "`^'\"%#*$()[]{}\\,.:;+-*/_!<>\t\n =?|&":
# if the current token is not empty, return it for now and
# keep the delimiter to the next call of next()
if len(self.token) > 0:
return
# a delimiter stops further advancing in the input
stop = True
# keep quotes as a single token. Supported quote types are
# double quotes ("...") and accent grave quotes (`...`)
if ch in '"`':
kind = ch # " or `
self.token += ch
self.pos += 1
# advance to the quotation end
while self.pos < len(self.src):
if self.src[self.pos] == kind:
break
self.token += self.src[self.pos]
self.pos += 1
# add the current character to the token
self.token += ch
self.pos += 1
# # lexer tests
# lex = Lexer('a"x"bc 123 *blub* $`hello, world!`123$')
# while len(lex.token) > 0:
# print(lex.token)
# lex.next()
# exit(0)
# For drawing random variables and to calculate the sample solution, we will
# be executing Python code that is embedded in the quiz descriptions.
# The evaluation of code will populate local variables. Its data types also
# depend on the used libraries.
# The following lists cluster some of these types.
boolean_types = ["<class 'bool'>", "<class 'numpy.bool_'>"]
int_types = [
"<class 'int'>",
"<class 'numpy.int64'>",
"<class 'sympy.core.numbers.Integer'>",
"<class 'sage.rings.integer.Integer'>",
"<class 'sage.rings.finite_rings.integer_mod.IntegerMod_int'>",
]
float_types = ["<class 'float'>"]
# The following list contains all of Pythons basic keywords. These are used
# in syntax highlighting in "*_DEBUG.html" files.
python_kws = [
"and",
"as",
"assert",
"break",
"class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"False",
"finally",
"for",
"from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"None",
"nonlocal",
"not",
"or",
"pass",
"raise",
"return",
"True",
"try",
"while",
"with",
"yield",
]
# The following list of identifiers may be in locals of Python source that
# uses "sympy". These identifiers must be skipped in the JSON output.
skipVariables = [
"acos",
"acosh",
"acoth",
"asin",
"asinh",
"atan",
"atan2",
"atanh",
"ceil",
"ceiling",
"cos",
"cosh",
"cot",
"coth",
"exp",
"floor",
"ln",
"log",
"pi",
"round",
"sin",
"sinc",
"sinh",
"tan",
"transpose",
]
# The following function rangeZ is provided as pseudo-intrinsic
# function in Python scripts, embedded into the question descriptions.
# It is an alternative version for "range", that excludes the zero.
# This is beneficial for drawing random numbers of questions for math classes.
# (the next line disables a warning, about camel-case function names)
# pylint: disable-next=invalid-name
def rangeZ(*a):
"""implements 'range', but excludes the zero"""
r = []
if len(a) == 1:
r = list(range(a[0]))
elif len(a) == 2:
r = list(range(a[0], a[1]))
elif len(a) == 3:
r = list(range(a[0], a[1], a[2]))
if 0 in r:
r.remove(0)
return r
# TODO: add comments starting from here
class TextNode:
"""Tree structure for the question text"""
def __init__(self, type_: str, data: str = "") -> None:
self.type: str = type_
self.data: str = data
self.children: list[TextNode] = []
# pylint: disable-next=too-many-branches,too-many-statements
def parse(self) -> None:
"""parses text recursively"""
if self.type == "root":
self.children = [TextNode(" ", "")]
lines = self.data.split("\n")
self.data = ""
for line in lines:
line = line.strip()
if len(line) == 0:
continue
type_ = line[0] # refer to "types" below
if type_ not in "[(-!":
type_ = " "
if type_ != self.children[-1].type:
self.children.append(TextNode(type_, ""))
self.children[-1].type = type_
self.children[-1].data += line + "\n"
if line.endswith("\\\\"):
# line break
# TODO: this is NOT allowed, if we are within math mode!!
self.children[-1].data = self.children[-1].data[:-3] + "\n"
self.children.append(TextNode(" ", ""))
types = {
" ": "paragraph",
"(": "single-choice",
"[": "multi-choice",
"-": "itemize",
"!": "command",
}
for child in self.children:
child.type = types[child.type]
child.parse()
elif self.type in ("multi-choice", "single-choice"):
options = self.data.strip().split("\n")
self.data = ""
for option in options:
node = TextNode("answer")
self.children.append(node)
text = ""
if self.type == "multi-choice":
text = "]".join(option.split("]")[1:]).strip()
else:
text = ")".join(option.split(")")[1:]).strip()
if option.startswith("[!"):
# conditionally set option
# TODO: check, if variable exists and is of type bool
var_id = option[2:].split("]")[0]
node.children.append(TextNode("var", var_id))
else:
# statically set option
correct = option.startswith("[x]") or option.startswith("(x)")
node.children.append(
TextNode("bool", "true" if correct else "false")
)
node.children.append(TextNode("paragraph", text))
node.children[1].parse()
elif self.type == "itemize":
items = self.data.strip().split("\n")
self.data = ""
for child in items:
node = TextNode("paragraph", child[1:].strip())
self.children.append(node)
node.parse()
elif self.type == "paragraph":
lex = Lexer(self.data.strip())
self.data = ""
self.children.append(self.parse_span(lex))
elif self.type == "command":
if (
".svg" in self.data
or ".png" in self.data
or ".jpg" in self.data
or ".jpeg" in self.data
):
self.parse_image()
else:
# TODO: report error
pass
else:
raise SellError("unimplemented")
def parse_image(self) -> Self:
"""parses an image inclusion"""
img_path = self.data[1:].strip()
img_width = 100 # percentage
if ":" in img_path:
tokens = img_path.split(":")
img_path = tokens[0].strip()
img_width = tokens[1].strip()
self.type = "image"
self.data = img_path
self.children.append(TextNode("width", img_width))
def parse_span(self, lex: Lexer) -> Self:
"""parses a span element"""
# grammar: span = { item };
# item = bold | math | input | string_var | plus_minus | text;
# bold = "*" { item } "*";
# math = "$" { item } "$";
# input = "%" ["!"] var;
# string_var = "&" var;
# plus_minus = "+" "-";
# text = "\\" | otherwise;
span = TextNode("span")
while lex.token != "":
span.children.append(self.parse_item(lex))
return span
# pylint: disable-next=too-many-return-statements
def parse_item(self, lex: Lexer, math_mode=False) -> Self:
"""parses a single item of a span/paragraph"""
if not math_mode and lex.token == "*":
return self.parse_bold_italic(lex)
if lex.token == "$":
return self.parse_math(lex)
if not math_mode and lex.token == "%":
return self.parse_input(lex)
if not math_mode and lex.token == "&":
return self.parse_string_var(lex)
if math_mode and lex.token == "+":
n = TextNode("text", lex.token)
lex.next()
if lex.token == "-":
# "+-" automatically chooses "+" or "-",
# depending on the sign or the following variable.
# For the variable itself, only its absolute value is used.
n.data += lex.token
n.type = "plus_minus"
lex.next()
return n
if not math_mode and lex.token == "\\":
lex.next()
if lex.token == "\\":
lex.next()
return TextNode("text", "<br/>")
n = TextNode("text", lex.token)
lex.next()
return n
def parse_bold_italic(self, lex: Lexer) -> Self:
"""parses bold or italic text"""
node = TextNode("italic")
if lex.token == "*":
lex.next()
if lex.token == "*":
node.type = "bold"
lex.next()
while lex.token not in ("", "*"):
node.children.append(self.parse_item(lex))
if lex.token == "*":
lex.next()
if lex.token == "*":
lex.next()
return node
def parse_math(self, lex: Lexer) -> Self:
"""parses inline math or display style math"""
math = TextNode("math")
if lex.token == "$":
lex.next()
if lex.token == "$":
math.type = "display-math"
lex.next()
while lex.token not in ("", "$"):
math.children.append(self.parse_item(lex, True))
if lex.token == "$":
lex.next()
if math.type == "display-math" and lex.token == "$":
lex.next()
return math
def parse_input(self, lex: Lexer) -> Self:
"""parses an input element field"""
input_ = TextNode("input")
if lex.token == "%":
lex.next()
if lex.token == "!":
input_.type = "input2"
lex.next()
input_.data = lex.token.strip()
lex.next()
return input_
def parse_string_var(self, lex: Lexer) -> Self:
"""parses a string variable"""
sv = TextNode("string_var")
if lex.token == "&":
lex.next()
sv.data = lex.token.strip()
lex.next()
return sv
def optimize(self) -> Self:
"""optimizes the current text node recursively. E.g. multiple pure
text items are concatenated into a single text node."""
children_opt = []
for c in self.children:
opt = c.optimize()
if (
opt.type == "text"
and opt.data.startswith('"') is False
and opt.data.startswith("`") is False
and len(children_opt) > 0
and children_opt[-1].type == "text"
and children_opt[-1].data.startswith('"') is False
and children_opt[-1].data.startswith("`") is False
):
children_opt[-1].data += opt.data
else:
children_opt.append(opt)
self.children = children_opt
return self
def to_dict(self) -> dict:
"""recursively exports the text node instance to a dictionary"""
# t := type, d := data, c := children
return {
"t": self.type,
"d": self.data,
"c": list(map(lambda o: o.to_dict(), self.children)),
}
# pylint: disable-next=too-many-instance-attributes
class Question:
"""Question of the quiz"""
def __init__(self, input_dirname: str, src_line_no: int) -> None:
self.input_dirname: str = input_dirname
self.src_line_no: int = src_line_no
self.title: str = ""
self.python_src: str = ""
self.variables: set[str] = set()
self.instances: list[dict] = []
self.text_src: str = ""
self.text: TextNode = None
self.error: str = ""
self.python_src_tokens: set[str] = set()
def build(self) -> None:
"""builds a question from text and Python sources"""
if len(self.python_src) > 0:
self.analyze_python_code()
instances_str = []
if len(self.error) == 0:
for _ in range(0, 5):
# try to generate instances distinct to prior once
# TODO: give up and keep less than 5, if applicable!
instance = {}
instance_str = ""
for _ in range(0, 10):
self.error = ""
instance = self.run_python_code()
instance_str = str(instance)
if instance_str not in instances_str:
break
instances_str.append(instance_str)
self.instances.append(instance)
# if there is no randomization in the input, then one instance is enough
if "rand" not in self.python_src:
break
if "No module named" in self.error:
print("!!! " + self.error)
self.text = TextNode("root", self.text_src)
self.text.parse()
var_occurrences: set[str] = set()
self.post_process_text(self.text, False, var_occurrences)
self.text.optimize()
# pylint: disable-next=too-many-branches
def post_process_text(
self, node: TextNode, math, var_occurrences: set[str]
) -> None:
"""post processes the textual part. For example, a semantical check
for the existing of referenced variables is applied. Also images
are loaded and stringified."""
for c in node.children:
self.post_process_text(
c,
math or node.type == "math" or node.type == "display-math",
var_occurrences,
)
if node.type == "input":
if node.data.startswith('"'):
# gap question
node.type = "gap"
node.data = node.data.replace('"', "")
elif node.data in self.variables:
var_id = node.data
if var_id in var_occurrences:
self.error += "It is not allowed to refer to a variable "
self.error += "twice or more. Hint: Create a copy of "
self.error += f"variable '{var_id}' in Python and ask for "
self.error += "the new variable name. "
self.error += f"Example code: '{var_id}2 = {var_id}'."
self.error += f"Then ask for '%{var_id}2'."
else:
var_occurrences.add(var_id)
elif node.data not in self.variables:
# ask for numerical/term variable
var_id = node.data
self.error += f"Unknown input variable '{var_id}'. "
elif node.type == "string_var":
var_id = node.data
if var_id not in self.variables:
self.error += f"Unknown string variable '{var_id}'. "
elif node.type == "text":
if (
math
and len(node.data) >= 2
and node.data.startswith('"')
and node.data.endswith('"')
):
node.data = node.data[1:-1]
elif math and (node.data in self.variables):
node.type = "var"
elif (
not math
and len(node.data) >= 2
and node.data.startswith("`")
and node.data.endswith("`")
):
node.type = "code"
node.data = node.data[1:-1]
elif node.type == "image":
# TODO: warning, if file size is (too) large
path = os.path.join(self.input_dirname, node.data)
img_type = os.path.splitext(path)[1][1:]
supported_img_types = ["svg", "png", "jpg", "jpeg"]
if img_type not in supported_img_types:
self.error += f"ERROR: image type '{img_type}' is not supported. "
self.error += f"Use one of {', '.join(supported_img_types)}"
elif os.path.isfile(path) is False:
self.error += "ERROR: cannot find image at path '" + path + '"'
else:
# load image
f = open(path, "rb")
data = f.read()
f.close()
b64 = base64.b64encode(data)
node.children.append(TextNode("data", b64.decode("utf-8")))
def float_to_str(self, v: float) -> str:
"""Converts float to string and cuts '.0' if applicable"""
s = str(v)
if s.endswith(".0"):
return s[:-2]
return s
def analyze_python_code(self) -> None:
"""Get all tokens from Python source code. This is required to filter
out all locals from libraries (refer to method run_python_code).
Since relevant tokens are only those in the left-hand side of an
assignment, we filter out non-assignment statements, as well as
the right-hand side of statements. As a side effect, irrelevant symbols
of packages are also filtered out (e.g. 'mod', is populated to the
locals, when using 'sage.all.power_mod')"""
lines = self.python_src.split("\n")
for line in lines:
if "=" not in line:
continue
lhs = line.split("=")[0]
lex = Lexer(lhs)
while len(lex.token) > 0:
self.python_src_tokens.add(lex.token)
lex.next()
# check for forbidden code
if "matplotlib" in self.python_src and "show(" in self.python_src:
self.error += "Remove the call show(), "
self.error += "since this would result in MANY open windows :-)"
# pylint: disable-next=too-many-locals,too-many-branches,too-many-statements
def run_python_code(self) -> dict:
"""Runs the questions python code and gathers all local variables."""
local_variables = {}
res = {}
src = self.python_src
try:
# pylint: disable-next=exec-used
exec(src, globals(), local_variables)
# pylint: disable-next=broad-exception-caught
except Exception as e:
# print(e)
self.error += str(e) + ". "
return res
for local_id, value in local_variables.items():
if local_id in skipVariables or (local_id not in self.python_src_tokens):
continue
type_str = str(type(value))
if type_str in ("<class 'module'>", "<class 'function'>"):
continue
self.variables.add(local_id)
t = "" # type
v = "" # value
if type_str in boolean_types:
t = "bool"
v = str(value).lower()
elif type_str in int_types:
t = "int"
v = str(value)
elif type_str in float_types:
t = "float"
v = self.float_to_str(value)
elif type_str == "<class 'complex'>":
t = "complex"
# convert "-0" to "0"
real = 0 if value.real == 0 else value.real
imag = 0 if value.imag == 0 else value.imag
v = self.float_to_str(real) + "," + self.float_to_str(imag)
elif type_str == "<class 'list'>":
t = "vector"
v = str(value).replace("[", "").replace("]", "").replace(" ", "")
elif type_str == "<class 'set'>":
t = "set"
v = (
str(value)
.replace("{", "")
.replace("}", "")
.replace(" ", "")
.replace("j", "i")
)
elif type_str == "<class 'sympy.matrices.dense.MutableDenseMatrix'>":
# e.g. 'Matrix([[-1, 0, -2], [-1, 5*sin(x)*cos(x)/7, 2], [-1, 2, 0]])'
t = "matrix"
v = str(value)[7:-1]
elif (
type_str == "<class 'numpy.matrix'>"
or type_str == "<class 'numpy.ndarray'>"
):
# e.g. '[[ -6 -13 -12]\n [-17 -3 -20]\n [-14 -8 -16]\n [ -7 -15 -8]]'
t = "matrix"
v = re.sub(" +", " ", str(value)) # remove double spaces
v = re.sub(r"\[ ", "[", v) # remove space(s) after "["
v = re.sub(r" \]", "]", v) # remove space(s) before "]"
v = v.replace(" ", ",").replace("\n", "")
elif type_str == "<class 'str'>":
t = "string"
v = value
else:
t = "term"
v = str(value).replace("**", "^")
# in case that an ODE is contained in the question
# and only one constant ("C1") is present, then substitute
# "C1" by "C"
if "dsolve" in self.python_src:
if "C2" not in v:
v = v.replace("C1", "C")
# t := type, v := value
v = v.replace("I", "i") # reformat sympy imaginary part
res[local_id] = {"t": t, "v": v}
if len(self.variables) > 50:
self.error += "ERROR: Wrong usage of Python imports. Refer to pySELL docs!"
# TODO: write the docs...
if "matplotlib" in self.python_src and "plt" in local_variables:
plt = local_variables["plt"]
buf = io.BytesIO()
plt.savefig(buf, format="svg", transparent=True)
buf.seek(0)
svg = buf.read()
b64 = base64.b64encode(svg)
res["__svg_image"] = {"t": "svg", "v": b64.decode("utf-8")}
plt.clf()
return res
def to_dict(self) -> dict:
"""recursively exports the question to a dictionary"""
return {
"title": self.title,
"error": self.error,
"is_ode": "dsolve" # contains an Ordinary Differential Equation
in self.python_src,
"variables": list(self.variables),
"instances": self.instances,
"text": self.text.to_dict(),
# the following is only relevant for debugging purposes,
# i.e. only present in _DEBUG.html
"src_line": self.src_line_no,
"text_src_html": self.syntax_highlight_text(self.text_src),
"python_src_html": self.syntax_highlight_python(self.python_src),
"python_src_tokens": list(self.python_src_tokens),
}
# pylint: disable-next=too-many-branches,too-many-statements
def syntax_highlight_text_line(self, src: str) -> str:
"""syntax highlights a single questions text line and returns the
formatted code in HTML format"""
html = ""
math = False
code = False
bold = False
italic = False
n = len(src)
i = 0
while i < n:
ch = src[i]
if ch == " ":
html += " "
elif not math and ch == "%":
html += '<span style="color:green; font-weight: bold;">'
html += ch
if i + 1 < n and src[i + 1] == "!":
html += src[i + 1]
i += 1
html += "</span>"
elif ch == "*" and i + 1 < n and src[i + 1] == "*":
i += 1
bold = not bold
if bold:
html += '<span style="font-weight: bold;">'
html += "**"
else:
html += "**"
html += "</span>"
elif ch == "*":
italic = not italic
if italic:
html += '<span style="font-style: italic;">'
html += "*"
else:
html += "*"
html += "</span>"
elif ch == "$":
display_style = False
if i + 1 < n and src[i + 1] == "$":
display_style = True
i += 1
math = not math
if math:
html += '<span style="color:#FF5733; font-weight: bold;">'
html += ch
if display_style:
html += ch
else:
html += ch
if display_style:
html += ch
html += "</span>"
elif ch == "`":
code = not code
if code:
html += '<span style="color:#33A5FF; font-weight: bold;">'
html += ch
else:
html += ch
html += "</span>"
else:
html += ch
i += 1
if math:
html += "</span>"
if code:
html += "</span>"
if italic:
html += "</span>"
if bold:
html += "</bold>"
return html
def red_colored_span(self, inner_html: str) -> str:
"""embeds HTML code into a red colored span"""
return '<span style="color:#FF5733; font-weight:bold">' + inner_html + "</span>"
def syntax_highlight_text(self, src: str) -> str:
"""syntax highlights a questions text and returns the formatted code in
HTML format"""
html = ""
lines = src.split("\n")
for line in lines:
if len(line.strip()) == 0:
continue
if line.startswith("-"):
html += self.red_colored_span("-")
line = line[1:].replace(" ", " ")
elif line.startswith("["):
l1 = line.split("]")[0] + "]".replace(" ", " ")
html += self.red_colored_span(l1)
line = "]".join(line.split("]")[1:]).replace(" ", " ")
elif line.startswith("("):
l1 = line.split(")")[0] + ")".replace(" ", " ")
html += self.red_colored_span(l1)
line = ")".join(line.split(")")[1:]).replace(" ", " ")
html += self.syntax_highlight_text_line(line)
html += "<br/>"
return html
def syntax_highlight_python(self, src: str) -> str:
"""syntax highlights a questions python code and returns the formatted
code in HTML format"""
lines = src.split("\n")
html = ""
for line in lines:
if len(line.strip()) == 0:
continue
lex = Lexer(line)
while len(lex.token) > 0:
if len(lex.token) > 0 and lex.token[0] >= "0" and lex.token[0] <= "9":
html += '<span style="color:green; font-weight:bold">'
html += lex.token + "</span>"
elif lex.token in python_kws:
html += '<span style="color:#FF5733; font-weight:bold">'
html += lex.token + "</span>"
else:
html += lex.token.replace(" ", " ")
lex.next()
html += "<br/>"
return html
def compile_input_file(input_dirname: str, src: str) -> dict:
"""compiles a SELL input file to JSON"""
lang = "en"
title = ""
author = ""
info = ""
questions = []
question = None
parsing_python = False
lines = src.split("\n")
for line_no, line in enumerate(lines):
line = line.split("#")[0] # remove comments
line_not_stripped = line
line = line.strip()
if len(line) == 0:
continue
if line.startswith("LANG"):
lang = line[4:].strip()
elif line.startswith("TITLE"):
title = line[5:].strip()
elif line.startswith("AUTHOR"):
author = line[6:].strip()
elif line.startswith("INFO"):
info = line[4:].strip()
elif line.startswith("QUESTION"):
question = Question(input_dirname, line_no + 1)
questions.append(question)
question.title = line[8:].strip()
parsing_python = False
elif question is not None:
if line.startswith('"""'):
parsing_python = not parsing_python
else:
if parsing_python:
question.python_src += (
line_not_stripped.replace("\t", " ") + "\n"
)
else:
question.text_src += line + "\n"
for question in questions:
question.build()
return {
"lang": lang,
"title": title,
"author": author,
"date": datetime.datetime.today().strftime("%Y-%m-%d"),
"info": info,
"questions": list(map(lambda o: o.to_dict(), questions)),
}
# the following code is automatically generated and updated by file "build.py"
# @begin(html)
HTML: str = b''
HTML += b'<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <titl'
HTML += b'e>pySELL Quiz</title> <meta name="viewport" content="width=d'
HTML += b'evice-width, initial-scale=1.0" /> <link rel="icon" type="im'
HTML += b'age/x-icon" href="data:image/x-icon;base64,AAABAAEAEBAAAAEAI'
HTML += b'ABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAA'
HTML += b'AAAAACqqqr/PDw8/0VFRf/V1dX////////////09Pb/trbO/3t7q/9wcLH/c'
HTML += b'XG0/3NzqP+iosH/5OTr////////////j4+P/wAAAP8KCgr/x8fH///////k5'
HTML += b'Or/bGym/y4ukP8kJJD/IiKR/yIikv8jI5H/KCiP/1BQnP/Jydz//////5CQk'
HTML += b'P8BAQH/DAwM/8jIyP/7+/v/cHCo/yIij/8lJZP/KSmR/z4+lf9AQJH/Li6Q/'
HTML += b'yUlkv8jI5H/TEya/9/f6P+QkJD/AQEB/wwMDP/Ly8r/ycna/y4ujv8lJZP/N'
HTML += b'DSU/5+fw//j4+v/5+fs/76+0v9LS5f/JSWS/yYmkP+Skrr/kJCQ/wAAAP8MD'
HTML += b'Az/zc3L/5aWvP8iIo//ISGQ/39/sf////7/////////////////n5+7/yMjj'
HTML += b'P8kJJH/bm6p/5CQkP8BAQH/CgoK/6SkpP+Skp//XV2N/1dXi//Hx9X//////'
HTML += b'///////////9fX1/39/rP8kJI7/JCSR/25upP+QkJD/AQEB/wEBAf8ODg7/F'
HTML += b'BQT/xUVE/8hIR//XV1c/8vL0P/IyNv/lZW7/1panP8rK5D/JiaT/ycnjv+bm'
HTML += b'7v/kJCQ/wEBAf8AAAD/AAAA/wAAAP8AAAD/AAAH/wAAK/8aGmv/LCyO/yQkj'
HTML += b'/8jI5L/JSWT/yIikP9dXZ//6enu/5CQkP8BAQH/BQUF/0xMTP9lZWT/Pz9N/'
HTML += b'wUFVP8AAGz/AABu/xYWhf8jI5L/JCSP/zY2k/92dq7/4ODo//////+QkJD/A'
HTML += b'QEB/wwMDP/IyMj//Pz9/2lppf8ZGYf/AgJw/wAAZ/8cHHL/Zmak/5ubv//X1'
HTML += b'+T//v7+////////////kJCQ/wEBAf8MDAz/ycnJ/9/f6f85OZT/IyOR/wcHZ'
HTML += b'P8AAB7/UVFZ//n5+P//////0dHd/7i4yf++vs7/7e3z/5CQkP8AAAD/DAwM/'
HTML += b'87Ozf/Y2OP/MjKQ/x8fjv8EBEr/AAAA/1xcWv//////6ent/0tLlf8kJIn/M'
HTML += b'jKL/8fH2v+QkJD/AQEB/wcHB/98fHv/jo6T/yUlc/8JCXj/AABi/wAAK/9eX'
HTML += b'nj/trbS/2xspv8nJ5H/IyOT/0pKm//m5uz/kJCQ/wEBAf8AAAD/AAAA/wAAA'
HTML += b'P8AACH/AABk/wAAbf8EBHD/IyOM/ykpkv8jI5H/IyOS/ysrjP+kpMP//////'
HTML += b'5GRkf8CAgL/AQEB/wEBAf8BAQH/AgIE/woKK/8ZGWj/IyOG/ycnj/8nJ4//M'
HTML += b'DCS/0xMmf+lpcP/+vr6///////Pz8//kZGR/5CQkP+QkJD/kJCQ/5OTk/+ws'
HTML += b'K//zs7V/8LC2f+goL3/oaG+/8PD2P/n5+z/////////////////AAAAAAAAA'
HTML += b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
HTML += b'AAAAAAAAAAAAAAAAA==" sizes="16x16" /> <link rel="stylesheet"'
HTML += b' href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.'
HTML += b'min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEa'
HTML += b'qSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous" /> '
HTML += b'<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/'
HTML += b'katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1Y'
HTML += b'QqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous'
HTML += b'" ></script> <style> html { font-family: Arial, Helvetica, s'
HTML += b'ans-serif; } body { max-width: 1024px; margin-left: auto; ma'
HTML += b'rgin-right: auto; padding-left: 5px; padding-right: 5px; } h'
HTML += b'1 { text-align: center; font-size: 28pt; word-wrap: break-wo'
HTML += b'rd; } img { width: 100%; display: block; margin-left: auto; '
HTML += b'margin-right: auto; } .author { text-align: center; font-siz'
HTML += b'e: 18pt; } .courseInfo { font-size: 14pt; font-style: italic'
HTML += b'; /*margin-bottom: 24px;*/ text-align: center; } .question {'
HTML += b' position: relative; /* required for feedback overlays */ co'
HTML += b'lor: black; background-color: white; border-style: solid; bo'
HTML += b'rder-radius: 5px; border-width: 3px; border-color: black; pa'
HTML += b'dding: 8px; margin-top: 20px; margin-bottom: 20px; -webkit-b'
HTML += b'ox-shadow: 4px 6px 8px -1px rgba(0, 0, 0, 0.93); box-shadow:'
HTML += b' 4px 6px 8px -1px rgba(0, 0, 0, 0.1); overflow-x: auto; } .q'
HTML += b'uestionFeedback { z-index: 10; display: none; position: abso'
HTML += b'lute; pointer-events: none; left: 10%; top: 33%; width: 80%;'
HTML += b' /*height: 100%;*/ text-align: center; font-size: 24pt; text'
HTML += b'-shadow: 0px 0px 18px rgba(0, 0, 0, 0.33); background-color:'
HTML += b' rgba(255, 255, 255, 1); padding-top: 20px; padding-bottom: '
HTML += b'20px; /*border-style: solid; border-width: 4px; border-color'
HTML += b': rgb(200, 200, 200);*/ border-radius: 16px; -webkit-box-sha'
HTML += b'dow: 0px 0px 18px 5px rgba(0, 0, 0, 0.66); box-shadow: 0px 0'
HTML += b'px 18px 5px rgba(0, 0, 0, 0.66); } .questionTitle { font-siz'
HTML += b'e: 24pt; } .code { font-family: "Courier New", Courier, mono'
HTML += b'space; color: black; background-color: rgb(235, 235, 235); p'
HTML += b'adding: 2px 5px; border-radius: 5px; margin: 1px 2px; } .deb'
HTML += b'ugCode { font-family: "Courier New", Courier, monospace; pad'
HTML += b'ding: 4px; margin-bottom: 5px; background-color: black; colo'
HTML += b'r: white; border-radius: 5px; opacity: 0.85; overflow-x: scr'
HTML += b'oll; } .debugInfo { text-align: end; font-size: 10pt; margin'
HTML += b'-top: 2px; color: rgb(64, 64, 64); } ul { margin-top: 0; mar'
HTML += b'gin-left: 0px; padding-left: 20px; } .inputField { position:'
HTML += b' relative; width: 32px; height: 24px; font-size: 14pt; borde'
HTML += b'r-style: solid; border-color: black; border-radius: 5px; bor'
HTML += b'der-width: 0.2; padding-left: 5px; padding-right: 5px; outli'
HTML += b'ne-color: black; background-color: transparent; margin: 1px;'
HTML += b' } .inputField:focus { outline-color: maroon; } .equationPre'
HTML += b'view { position: absolute; top: 120%; left: 0%; padding-left'
HTML += b': 8px; padding-right: 8px; padding-top: 4px; padding-bottom:'
HTML += b' 4px; background-color: rgb(128, 0, 0); border-radius: 5px; '
HTML += b'font-size: 12pt; color: white; text-align: start; z-index: 2'
HTML += b'0; opacity: 0.95; } .button { padding-left: 8px; padding-rig'
HTML += b'ht: 8px; padding-top: 5px; padding-bottom: 5px; font-size: 1'
HTML += b'2pt; background-color: rgb(0, 150, 0); color: white; border-'
HTML += b'style: none; border-radius: 4px; height: 36px; cursor: point'
HTML += b'er; } .buttonRow { display: flex; align-items: baseline; mar'
HTML += b'gin-top: 12px; } .matrixResizeButton { width: 20px; backgrou'
HTML += b'nd-color: black; color: #fff; text-align: center; border-rad'
HTML += b'ius: 3px; position: absolute; z-index: 1; height: 20px; curs'
HTML += b'or: pointer; margin-bottom: 3px; } a { color: black; text-de'
HTML += b'coration: underline; } </style> </head> <body> <h1 id="title'
HTML += b'"></h1> <div class="author" id="author"></div> <p id="course'
HTML += b'Info1" class="courseInfo"></p> <p id="courseInfo2" class="co'
HTML += b'urseInfo"></p> <h1 id="debug" class="debugCode" style="displ'
HTML += b'ay: none">DEBUG VERSION</h1> <div id="questions"></div> <p s'
HTML += b'tyle="font-size: 8pt; font-style: italic; text-align: center'
HTML += b'"> This quiz was created using <a href="https://github.com/a'
HTML += b'ndreas-schwenk/pysell">pySELL</a>, the <i>Python-based Simpl'
HTML += b'e E-Learning Language</i>, written by Andreas Schwenk, GPLv3'
HTML += b'<br /> last update on <span id="date"></span> </p> <script>l'
HTML += b'et debug = false; let quizSrc = {};var sell=(()=>{var B=Obje'
HTML += b'ct.defineProperty;var re=Object.getOwnPropertyDescriptor;var'
HTML += b' ne=Object.getOwnPropertyNames;var ae=Object.prototype.hasOw'
HTML += b'nProperty;var le=(r,e)=>{for(var t in e)B(r,t,{get:e[t],enum'
HTML += b'erable:!0})},oe=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof'
HTML += b' e=="function")for(let s of ne(e))!ae.call(r,s)&&s!==t&&B(r,'
HTML += b's,{get:()=>e[s],enumerable:!(i=re(e,s))||i.enumerable});retu'
HTML += b'rn r};var he=r=>oe(B({},"__esModule",{value:!0}),r);var de={'
HTML += b'};le(de,{init:()=>pe});function b(r=[]){let e=document.creat'
HTML += b'eElement("div");return e.append(...r),e}function z(r=[]){let'
HTML += b' e=document.createElement("ul");return e.append(...r),e}func'
HTML += b'tion U(r){let e=document.createElement("li");return e.append'
HTML += b'Child(r),e}function R(r){let e=document.createElement("input'