forked from maxdougherty/snap_autograder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AG_HW3.html
1166 lines (1021 loc) · 50.8 KB
/
AG_HW3.html
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Snap! Build Your Own Blocks. Beta</title>
<link rel="shortcut icon" href="favicon.ico">
<script src="jschannel.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="SnapPLE.js"></script>
<!-- Moved down to the bottom to have var id. -->
<!-- <script type="text/javascript" src="snap.js"></script> -->
<script type="text/javascript" src="morphic.js"></script>
<script type="text/javascript" src="widgets.js"></script>
<script type="text/javascript" src="blocks.js"></script>
<script type="text/javascript" src="threads.js"></script>
<script type="text/javascript" src="objects.js"></script>
<script type="text/javascript" src="gui.js"></script>
<script type="text/javascript" src="paint.js"></script>
<script type="text/javascript" src="lists.js"></script>
<script type="text/javascript" src="byob.js"></script>
<script type="text/javascript" src="xml.js"></script>
<script type="text/javascript" src="store.js"></script>
<script type="text/javascript" src="locale.js"></script>
<script type="text/javascript" src="cloud.js"></script>
<script type="text/javascript" src="sha512.js"></script>
<script type="text/javascript" src="snap-edx-overrides.js"></script>
<link rel="stylesheet" type="text/css" href="AG_status_bar.css" />
<link rel="stylesheet" type="text/css" href="hintstyle.css" />
<script type="text/javascript" src="AG_hint_format.js"></script>
<script type="text/javascript">
// The id is to act as a course identifier.
// NOTE: FOR NOW YOU ALSO HAVE TO ADD THE ID TO THE BOTTOM OF THE PAGE.
var courseID = ""; // e.g. "BJCx"
// Specify a prerequisite task id, should be null if no such requirement.
var preReqTaskID = null;
var preReqID = courseID + preReqTaskID;
// taskID uniquely identifies the task for saving in browser localStorage.
var taskID = "AG_D1_T1";
var id = courseID + taskID;
var isEDX = isEDXurl();
// Add tests to the outputLog. Function is called by runAGTest(id, outputLog)
// var testLog;
function AGTest(outputLog) {
/*Rotate Clockwise*/
multiTestBlock(outputLog, 'rotate %l clockwise',
[[[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],[[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0]], //Input
[[1,0,5,0,5,0,5,0,5,0,5,0,5,0,5,0]],[[1,4,8,5,9,6,9,4,2,5,8,9,6,5,9,0]]],
[[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,4], //Output
[5,5,5,1,0,0,0,0,5,5,5,5,0,0,0,0],[6,2,9,1,5,5,6,4,9,8,9,8,0,9,4,5]],
[-1,-1, -1, -1], //Timeouts
[true,true, true, true]); //Boolean to control if the sprite is tested in a new 'test' Sprite
/*Merge Tile at _, _ on _ up*/
multiTestBlock(outputLog, "merge tile at %n , %n of %l up",
[[3, 1, [2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0]],[2, 1, [2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0]],
[3, 2, [0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0]],[3, 2, [0,4,0,0,0,4,0,0,0,2,0,0,0,0,0,0]]],
[true,false,true,false],
[-1,-1, -1, -1],
[true,true, true, true]);
/*Merge Up _*/
multiTestBlock(outputLog, 'merge up %l',
[[[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],[[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0]],
[[1,0,5,0,5,0,5,0,5,0,5,0,5,0,5,0]],[[1,4,8,5,9,6,9,4,2,5,8,9,6,5,9,0]]],
[[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0],
[1,0,10,0,10,0,10,0,5,0,0,0,0,0,0,0],[1,4,8,5,9,6,9,4,2,10,8,9,6,0,9,0]],
[-1,-1, -1, -1],
[true,true, true, true]);
/*No Moves Left For _*/
multiTestBlock(outputLog, "no moves left for %l ?",
[[[2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],[[1,2,3,4,0,0,0,0,0,0,0,0,0,0,0,0]],
[[2,4,2,4,4,2,4,2,2,4,2,4,4,2,4,2]],[[2,4,2,4,4,2,4,2,8,4,2,4,8,2,4,2]]],
[false,false,true,false],
[-1,-1, -1, -1],
[true,true, true, true]);
return outputLog;
}
/* Removes the previously saved AG_state. Runs the tests in
* AGTest().
* Called by 'click' event on autograder_button.
*/
function runAGTest(snapWorld, taskID, outputLog) {
// Create a new gradingLog if none is specified.
var numAttempts = setNumAttempts(taskID);
outputLog = outputLog || new gradingLog(snapWorld, taskID, numAttempts);
// Populate, run, and evaluate the tests specified in AGTest()
// These tests specified by the Course Designer.
//outputLog.numAttempts += 1;
var test_log = AGTest(outputLog);
if(!test_log.runSnapTests()) {
outputLog.scoreLog();
}
}
/* After loading the XML, check if the current XML is a known
* state, restore the gradingLog if it is.
* @return {gradingLog}
* TODO: Trigger AGStart when a Snap file is loaded.
*/
function AGStart(snapWorld, taskID) {
//Grab HTML divs
var menu_button = document.getElementById("onclick-menu");
var grade_button = document.getElementById("autograding_button");
//Get the current Snap XML string
var ide = snapWorld.children[0];
var curr_xml = ide.serializer.serialize(ide.stage);
//Retrieve previously graded Snap XML strings (if in localStorage).
var c_prev_xml = localStorage.getItem(taskID + "_c_test_state");
var prev_xml = localStorage.getItem(taskID + "_test_state");
var outputLog;
//If the current XML matches the stored correct XML
if (isSameSnapXML(c_prev_xml, curr_xml)) {
//Restore the AG status bar to a graded state
var outputLog = JSON.parse(localStorage.getItem(taskID + "_c_test_log"));
outputLog.snapWorld = snapWorld;
AG_bar_graded(outputLog);
return outputLog;
}
//If the current XML matches the last stored gradingLog
if (isSameSnapXML(prev_xml, curr_xml)) {
//Restore the AG status bar to a graded state
var outputLog = JSON.parse(localStorage.getItem(taskID + "_test_log"));
outputLog.snapWorld = snapWorld;
AG_bar_semigraded(outputLog);
return outputLog;
} else {
//Restore the AG status bar to a graded state
//If no previous state is recognized, return new {gradingLog}.
var numAttempts = setNumAttempts(taskID);
outputLog = new gradingLog(snapWorld, taskID, numAttempts);
AG_bar_ungraded(outputLog);
return outputLog;
}
}
/* Checks to see if the Snap! XML has changed and updates the
* AG status bar. If Snap! is restored to its former state
* the grading log and status bar are also restored.
* @return {gradingLog} outputLog
* Note:
* - Should only be called from a "mouseup" event.
*/
function AGUpdate(snapWorld, taskID) {
//TODO: Are there any optional parameters that may be useful?
//Grabs HTML divs
var menu_button = document.getElementById("onclick-menu");
var grade_button = document.getElementById("autograding_button");
//Get the current Snap XML string
var ide = snapWorld.children[0];
var curr_xml = ide.serializer.serialize(ide.stage);
//Retrieve previously graded Snap XML strings (if in localStorage).
var c_prev_xml = localStorage.getItem(taskID + "_c_test_state");
var prev_xml = localStorage.getItem(taskID + "_test_state");
var last_xml = localStorage.getItem(taskID + "_last_submitted_state");
//Retrieve previous grade logs (if in localStorage). As {String}s
var c_prev_log = localStorage.getItem(taskID + "_c_test_log");
var prev_log = localStorage.getItem(taskID + "_test_log");
if (!prev_xml || !curr_xml) {
console.log(prev_xml);
console.log(curr_xml);
}
//menu bar grays out options that are not available
//(ex. current state is same as best attempt) and restores the button state
grayOutButtons(snapWorld, taskID);
var outputLog;
//If current XML is different from prev_xml
if (c_prev_xml && isSameSnapXML(c_prev_xml, curr_xml)) {
//Restore the AG status bar to a graded state
// TODO: Write a good comment
// TODO: Give gradeLog ability to recover log data and xml string
console.log('AGUpdate: Thinks this is the "correct" XML.');
localStorage.setItem(taskID + "_test_log", c_prev_log);
localStorage.setItem(taskID + "_test_state", curr_xml);
document.getElementById("different-feedback").innerHTML = "";
//Retrieve the correct test log from localStorage
outputLog = JSON.parse(c_prev_log);
outputLog.snapWorld = snapWorld;
AG_bar_graded(outputLog);
if (isEDX) {
parent.document.getElementById('overlay-button').style.display = "none";
}
} else if (prev_xml && isSameSnapXML(prev_xml, curr_xml, true)) {
//Restore the AG status bar to a graded state
console.log('AGUpdate: Thinks this is just the "last" XML.');
//Retrieve the previous test log from localStorage
document.getElementById("different-feedback").innerHTML = "";
outputLog = JSON.parse(prev_log);
outputLog.snapWorld = snapWorld;
AG_bar_semigraded(outputLog);
if (isEDX) {
parent.document.getElementById('overlay-button').style.display = "none";
}
} else {
//Restore the AG status bar to a graded state
var numAttempts = setNumAttempts(taskID);
outputLog = new gradingLog(snapWorld, taskID, numAttempts);
AG_bar_ungraded(outputLog);
document.getElementById("different-feedback").innerHTML = "This feedback does not match what is in the scripting area."
if (isEDX) {
parent.document.getElementById('overlay-button').style.display = "block";
}
}
//populateFeedback(outputLog);
return outputLog;
}
/* Updates the AG_status_bar with respect to the outputLog.
* - Formats CSS for 'autograding_flag' and 'autograding_button'
* If the outputLog is correct, save the Snap XML string into
* localStorage.
* - key = outputLog.taskID + "_c_test_state"
* Note:
* - Should only be called from outputLog.evaluateLog()
*/
function AGFinish(outputLog) {
// Verify correctness
if (outputLog.allCorrect) {
// Save the correct XML string into localStorage
AG_bar_graded(outputLog);
outputLog.saveSnapXML(outputLog.taskID + "_c_test_state");
} else {
// Update AG_status_bar to 'graded, but incorrect state
AG_bar_semigraded(outputLog);
}
//Save the current XML. Log is saved in gradingLog.scoreLog(...)
outputLog.saveSnapXML(outputLog.taskID + "_test_state");
//outputLog.numAttempts += 1;
populateFeedback(outputLog);
grayOutButtons(outputLog.snapWorld, outputLog.taskID);
console.log('Autograder test Results:');
console.log(outputLog);
//parent.document.getElementsByClassName('check-label')[0].click();
}
/*
* Reset state removes all saved logs and XML files, and opens a new
* Snap! file.
*/
function resetState(snapWorld, taskID) {
var numAttempts = JSON.parse(localStorage.getItem(taskID + "_test_log")).numAttempts;
localStorage.removeItem(taskID + "_test_log");
localStorage.removeItem(taskID + "_test_state");
localStorage.removeItem(taskID + "_c_test_log");
localStorage.removeItem(taskID + "_c_test_state");
var ide = snapWorld.children[0];
ide.newProject();
var new_log = AGStart(snapWorld, taskID);
new_log.numAttempts = numAttempts;
//localStorage.setItem(taskID + "_test_log", new_log);
localStorage.setItem(taskID + "_test_state", ide.serializer.serialize(ide.stage));
new_log.saveLog();
//localStorage.setItem(taskID + "_test_log", new_log);
grayOutButtons(snapWorld, taskID);
}
function revertToBestState(snapWorld, taskID) {
var ide = snapWorld.children[0];
var numAttempts = JSON.parse(localStorage.getItem(taskID + "_test_log")).numAttempts;
var c_prev_xml = localStorage.getItem(taskID + "_c_test_state");
var c_prev_log = localStorage.getItem(taskID + "_c_test_log");
localStorage.setItem(taskID + "_test_state", c_prev_xml);
localStorage.setItem(taskID + "_test_log", c_prev_log);
var prev_log = JSON.parse(localStorage.getItem(taskID + "_test_log"));
prev_log.snapWorld = snapWorld;
AG_bar_graded(prev_log);
populateFeedback(prev_log);
prev_log.numAttempts = numAttempts;
ide.openProjectString(c_prev_xml);
grayOutButtons(snapWorld, taskID);
}
function revertToLastState(snapWorld, taskID) {
var ide = snapWorld.children[0];
var prev_xml = localStorage.getItem(taskID + "_test_state");
var prev_log = JSON.parse(localStorage.getItem(taskID + "_test_log"));
prev_log.snapWorld = snapWorld;
if (prev_log['allCorrect']) {
AG_bar_graded(prev_log);
} else {
AG_bar_semigraded(prev_log);
}
populateFeedback(prev_log);
ide.openProjectString(prev_xml);
grayOutButtons(snapWorld, taskID);
}
function revertToLastSubmit(snapWorld, taskID) {
var numAttempts = JSON.parse(localStorage.getItem(taskID + "_test_log")).numAttempts;
var last_xml = localStorage.getItem(taskID + "_last_submitted_state");
var last_log = localStorage.getItem(taskID + "_last_submitted_log");
var ide = snapWorld.children[0];
localStorage.setItem(taskID + "_test_state", last_xml);
localStorage.setItem(taskID + "_test_log", last_log);
var prev_log = JSON.parse(localStorage.getItem(taskID + "_test_log"));
if (prev_log['allCorrect']) {
AG_bar_graded(prev_log);
} else {
AG_bar_semigraded(prev_log);
}
populateFeedback(prev_log);
prev_log.numAttempts = numAttempts;
ide.openProjectString(last_xml);
grayOutButtons(snapWorld, taskID);
}
/*
* Makes AG status bar reflect the ungraded state of the outputLog.
*/
function AG_bar_ungraded(outputLog) {
var button_text = "GRADE";
var button_elem = $('#autograding_button span');
var regex = new RegExp(button_text,"g");
if (button_elem.html().match(regex) !== null) {
return;
}
button_elem.fadeOut('fast', function() {
button_elem.html(button_text);
button_elem.slideDown('fast');
$('#autograding_button').css('background', 'orange');
});
$('#autograding_button .hover_darken').show();
$('#onclick-menu').css('color', 'white');
if (localStorage.getItem(outputLog.taskID + "_test_log")) {
$('#feedback-button').html("View Previous Feedback");
} else {
$('#feedback-button').html("No Feedback Available");
}
document.getElementById("different-feedback").innerHTML = "This feedback does not match what is in the scripting area."
}
/*
* Makes AG status bar reflect the graded state of the outputLog. This
* only occurs when all tests on the outputLog have passed.
*/
function AG_bar_graded(outputLog) {
var button_text = "TESTS PASS";
var button_elem = $('#autograding_button span');
var regex = new RegExp(button_text,"g");
if (button_elem.html().match(regex) !== null) {
return;
}
button_elem.fadeOut('fast', function() {
button_elem.html(button_text);
button_elem.slideDown('fast');
$('#autograding_button').css('background', '#29A629');
});
$('#autograding_button .hover_darken').hide();
$('#onclick-menu').css('color', 'white');
$('#feedback-button').html("Review Feedback");
}
/*
* Makes AG status bar reflect the semi graded state of the outputLog.
* This is called when any test on the outputLog fails.
*/
function AG_bar_semigraded(outputLog) {
var button_text = "❰❰ FEEDBACK";
var button_elem = $('#autograding_button span');
var regex = new RegExp("FEEDBACK","g");
if (button_elem.html().match(regex) !== null) {
return;
}
button_elem.fadeOut('fast', function() {
button_elem.html(button_text);
button_elem.slideDown('fast');
$('#autograding_button').css('background', 'red');
});
$('#autograding_button .hover_darken').show();
$('#onclick-menu').css('color', 'orange');
var num_errors = outputLog.testCount - outputLog.numCorrect;
var plural = "";
if (num_errors > 1) { plural = "s"};
$('#feedback-button').html("View Feedback ("+
num_errors +" Error" + plural + ")");
}
/* Checks if two Snap! XML strings have approximately the same state.
* The positions of scripts are ignored, as well as the order in which
* they were most recently manipulated.
* @param {String} prev_xml
* @param {String} curr_xml
* @return {Boolean} Equivalence of prev_xml and curr_xml, false if
* either are strings are undefined.
* Currently only works for one sprite with scripts
* TODO: Extend to all script groups [DONE]
* TODO: Improve XML scrubbing (Consider the following)
* - If correct solution (scripts) is subset of other [DONE]
* - Optional tags for variables, sprite position
* - Option to restore the highest scoring {gradingLog}
*
* Note: Apparently works with multiple sprites, but produces a malformed
* Snap XML string. Each sprite gets all scripts in sorted order. Needs
* further testing.
*/
function isSameSnapXML(prev_xml, curr_xml, no_subset) {
//replace script coordinates with generic 'x="0" y="0"'
// console.log('isSameSnapXML');
if ((prev_xml === null) || (curr_xml === null)) { return false; }
//Remove script coordinates
// prev_xml = prev_xml.replace(/script x="[\d]*" y="[\d]*"/g, 'script x="0" y="0"');
// curr_xml = curr_xml.replace(/script x="[\d]*" y="[\d]*"/g, 'script x="0" y="0"');
prev_xml = prev_xml.replace(/script x="(.*?)" y="(.*?)"/g, 'script x="0" y="0"');
curr_xml = curr_xml.replace(/script x="(.*?)" y="(.*?)"/g, 'script x="0" y="0"');
//Remove data hashes hashes (to allow coherence b/w reloads).
prev_xml = prev_xml.replace(/data:image(.*?)(?=<)/g, '');
curr_xml = curr_xml.replace(/data:image(.*?)(?=<)/g, '');
//If XML is identical other than images and script positions, short-circuit
if (prev_xml === curr_xml) { return true; }
//split between brackets
prev_xml_scripts = prev_xml.match(/(<script x)(.*?)(<\/script>)/g);
curr_xml_scripts = curr_xml.match(/(<script x)(.*?)(<\/script>)/g);
//split between custom blocks
prev_xml_blocks = prev_xml.match(/(<block-definition s)(.*?)(\/block-definition>)/g);
curr_xml_blocks = curr_xml.match(/(<block-definition s)(.*?)(\/block-definition>)/g);
//sort script tags and convert back to strings
//lol. weird syntax. doesn't sort if curr_xml_scripts === null.
prev_xml_scripts && prev_xml_scripts.sort().join("");
curr_xml_scripts && curr_xml_scripts.sort().join("");
//If the custom block definitions have changed
prev_xml_blocks && prev_xml_blocks.sort().join("");
curr_xml_blocks && curr_xml_blocks.sort().join("");
if(JSON.stringify(prev_xml_blocks) !== JSON.stringify(curr_xml_blocks)) {
return false;
}
//If the previous scripts are a subset of current scripts
if (!no_subset && isArrSubset(curr_xml_scripts, prev_xml_scripts)) {
//Then the solution is still present and in-tact
return true;
}
//replace unsorted scripts with sorted scripts
//TODO: Replace them properly
prev_xml = prev_xml.replace(/(<script x)(.*)(<\/script>)/g,prev_xml_scripts);
curr_xml = curr_xml.replace(/(<script x)(.*)(<\/script>)/g,curr_xml_scripts);
return prev_xml === curr_xml;
}
/*
* Helper Function for isSameSnapXML(...). Used to check if a previous
* solution is a sub-set of the current Snap! scripts.
* @param {Array:Strings} big
* @param {Array:String} small
* @return {Boolean} If 'small' is a sub-set of 'big'
*/
function isArrSubset(big, small) {
if (!big || !small) {
return false;
}
nbig = big.slice();
var index;
for (var elem of small) {
index = nbig.indexOf(elem);
if (nbig.indexOf(elem) >= 0) {
nbig.slice(index, 1);
} else {
return false;
}
}
return true;
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceall(string, find, replace) {
return (string.replace(new RegExp(escapeRegExp(find), 'g'), replace));
}
/*
* Re-format the contents of a the hint string to add HTML tags and
* appropriate CSS. Return the re-formatted string.
*/
function formatFeedback(hint) {
var tags =
[['collapsedivstart', '<input class="toggle-box" id="expander" type="checkbox" ><label for="expander">Details</label><div id="table-wrapper">'],
['collapsedivend', '</div>'],
['linebreak', '<br /></br />'],
['tablestart', '<table class="results">'],
['tableend', '</table>'],
['rowstart', '<tr>'],
['rowend', '</tr>'],
['headstart', '<th class="titles" style="text-align: center;">'],
['headend', '</th>'],
['datastart', '<td class="data" style="text-align: center;">'],
['evenstart', '<td class="evens" style="text-align: center;">'],
['dataend', '</td>'],
['correctstart', '<td class="correctans" style="text-align: center;">'],
['wrongstart', '<td class="incorrectans" style="text-align: center;">'],
['teststart', '<td class="tests" style="text-align: center;">'],
['spanend', '</span>'],
['spanstart', '<span class="message">']];
var taglength = tags.length;
var message = String(hint.innerHTML);
for (var i = 0; i < taglength; i++) {
message = replaceall(message, tags[i][0], tags[i][1]);
}
return message;
}
function toggleMenu() {
var menu_items = document.getElementsByClassName("bubble")[0];
if (menu_items.id === "dropdown-closed") {
menu_items.id = "dropdown-open";
} else {
menu_items.id = "dropdown-closed";
}
}
function openPopup(){
var overlay = document.getElementById('overlay');
overlay.classList.remove("is-hidden");
}
function closePopup(){
var overlay = document.getElementById('overlay');
overlay.classList.add("is-hidden");
}
function openResults(){
var overlay = document.getElementById('ag-output');
overlay.classList.remove("is-hidden");
}
function closeResults(){
var overlay = document.getElementById('ag-output');
overlay.classList.add("is-hidden");
}
function populateFeedback(outputLog) {
var taskID = outputLog.taskID;
var last_log = localStorage.getItem(taskID + "_last_submitted_log");
var prev_log = localStorage.getItem(taskID + "_test_log");
var edx_caution = document.getElementById("edx-submit-different");
var caution = document.getElementById("different-feedback");
var glog = outputLog;
var log = AG_log(glog);
var feedback = log["feedback"];
var title = log["comment"];
// Checks if the grading button has been clicked
if (title === "Please run the Snap Autograder before clicking the 'Submit' button.") {
document.getElementById("table-data").style.display = "none";
document.getElementById("reporter-table-data").style.display = "none";
} else {
document.getElementById("table-data").style.display = "table";
document.getElementById("reporter-table-data").style.display = "table";
}
// Wipes the feedback clean, including if it has been populated before.
caution.innerHTML = "";
edx_caution.innerHTML = "";
document.getElementById("comment").innerHTML = "";
var tableTitles = document.getElementsByClassName("titles");
var tableResults = document.getElementById("table-data");
var repTableResults = document.getElementById("reporter-table-data");
while (tableResults.children.length > 1) {
tableResults.removeChild(tableResults.children[1]);
}
while (repTableResults.children.length > 1) {
repTableResults.removeChild(repTableResults.children[1]);
}
// Warnings for when student's feedback differ from what's on the scripting area/what's been submitted to edX
document.getElementById("comment").innerHTML = title;
if (!last_log) {
edx_caution.innerHTML = "[WARNING: You have not submitted your results to edX yet.]"
}
else if (last_log !== prev_log) {
edx_caution.innerHTML = "[WARNING: These results differ from your last edX submission.]"
}
var nonRepTest = 1;
var repTest = 1;
for (i=1; i<=feedback["testCount"]; i++) {
var test = String(i);
var newRow = document.createElement("tr");
// If test is not a reporter test, only add columns for Test # and Feedback
if (feedback[test]["testClass"] !== "r") {
if (document.getElementsByClassName("non-reporter").length === 0) {
addBasicHeadings();
}
addTableCell(String(nonRepTest), "tests", newRow);
nonRepTest += 1;
}
// If test is a reporter test, add all columns, including input, output, and expected. Makes the background of every other row light gray.
if (feedback[test]["testClass"] === "r") {
if (document.getElementsByClassName("reporter").length === 0) {
addReporterHeadings();
}
addTableCell(String(repTest), "tests", newRow);
var keys = ['blockSpec',"input", "output", "expOut"];
for (key=0; key<keys.length; key++) {
if (repTest % 2 === 0) {
addTableCell(feedback[test][keys[key]], ["data", "evens"], newRow);
} else {
addTableCell(feedback[test][keys[key]], "data", newRow);
}
}
repTest += 1;
}
// If test is correct, make the feedback appropriately colored.
if (feedback[test]["correct"] === true) {
addTableCell(feedback[test]["feedback"], "correctans", newRow);
// addRegradeButton("Regrade", ["data", "hidden"], newRow);
} else {
addTableCell(feedback[test]["feedback"], "incorrectans", newRow);
// addRegradeButton("Regrade", ["data", "regrade", test], newRow);
}
if (feedback[test]["testClass"] === "r") {
document.getElementById("reporter-table-data").appendChild(newRow);
} else {
document.getElementById("table-data").appendChild(newRow);
}
}
console.log(outputLog);
//outputLog.saveLog();
// makes recently created regrade buttons clickable
var regrade_buttons = document.getElementsByClassName("regrade");
for(var i=0; i<regrade_buttons.length; i++) {
regrade_buttons[i].onclick = function() {
var testId = this.classList[2];
regradeOnClick(outputLog, testId);
}
}
}
function addBasicHeadings() {
basicCols = ["Test", "Feedback"];
for (i=0; i<2; i++) {
var header = document.createElement("th");
var text = document.createTextNode(basicCols[i]);
//var lastCol = document.getElementById("reporter-last-column");
var titles = document.getElementById("table-titles");
header.classList.add("titles", "non-reporter");
header.appendChild(text);
titles.appendChild(header);
}
}
function addReporterHeadings() {
var columns = ["Test", "Block", "Input", "Output", "Expected", "Feedback"];
for (i=0; i<columns.length; i++) {
var header = document.createElement("th");
var text = document.createTextNode(columns[i]);
var repTitles = document.getElementById("reporter-table-titles");
header.classList.add("titles", "reporter");
header.appendChild(text);
repTitles.appendChild(header);
}
}
function addTableCell(text, elemClass, row) {
var data = document.createElement("td");
var text = document.createTextNode(stringify_list(text));
data.appendChild(text);
if (Array.isArray(elemClass)) {
DOMTokenList.prototype.add.apply(data.classList, elemClass);
} else {
data.classList.add(elemClass);
}
row.appendChild(data);
}
function stringify_list(lst) {
if (lst instanceof List) {
lst = lst.contents;
}
if (!(lst instanceof Array)) {
if (lst == null) {return ' '};
return String(lst)
} else {
output = '[';
for (elem of lst) {
if (elem instanceof Array) {
output += stringify_list(elem);
} else {
if (elem == null) {elem = ' '}
output += String(elem);
}
output += ',';
}
return output.slice(0,-1) + ']'
}
}
function addRegradeButton(text, elemClass, row) {
var data = document.createElement("td");
var button = document.createElement("p");
var text = document.createTextNode(text);
button.classList.add("regrade-button");
button.appendChild(text);
data.appendChild(button);
if (Array.isArray(elemClass)) {
DOMTokenList.prototype.add.apply(data.classList, elemClass);
} else {
data.classList.add(elemClass);
}
row.appendChild(data);
}
function grayOutButtons(snapWorld, taskID) {
var ide = snapWorld.children[0];
var curr_xml = ide.serializer.serialize(ide.stage);
//Retrieve previously graded Snap XML strings (if in localStorage).
var c_prev_xml = localStorage.getItem(taskID + "_c_test_state");
var prev_xml = localStorage.getItem(taskID + "_test_state");
var last_xml = localStorage.getItem(taskID + "_last_submitted_state");
var last_submit = document.getElementById("last-submit");
if (last_xml === null || isSameSnapXML(last_xml, curr_xml)) {
last_submit.style.color = "#373737";
last_submit.style.pointerEvents = "none";
last_submit.parentNode.id = "disabled-button";
} else {
last_submit.parentNode.id = "enabled-button";
last_submit.style.color = "white";
last_submit.style.pointerEvents = "auto";
}
var revert_button = document.getElementById("revert-button");
if (c_prev_xml === null || isSameSnapXML(c_prev_xml, curr_xml)) {
revert_button.style.color = "#373737";
revert_button.style.pointerEvents = "none";
revert_button.parentNode.id = "disabled-button";
} else {
revert_button.parentNode.id = "enabled-button";
revert_button.style.color = "white";
revert_button.style.pointerEvents = "auto";
}
var undo_button = document.getElementById("undo-button");
if (prev_xml === null || isSameSnapXML(prev_xml, curr_xml)) {
undo_button.style.color = "#373737";
undo_button.style.pointerEvents = "none";
undo_button.parentNode.id = "disabled-button";
} else {
undo_button.parentNode.id = "enabled-button";
undo_button.style.color = "white";
undo_button.style.pointerEvents = "auto";
}
}
function regradeOnClick(outputLog, testId) {
var test = outputLog[testId];
test.graded = false;
test.correct = false;
outputLog.numAttempts += 1;
if (test.testClass === "r") {
outputLog.startSnapTest(parseInt(testId, 10));
// for assertion tests, change feedback accordingly to whether assertion is true or false
} else if (test.testClass === "a") {
if (test.assertion()) {
test.feedback = test.pos_fb;
test.correct = true;
} else {
test.feedback = test.neg_fb;
test.correct = false;
}
test.graded = true;
}
//What about other types of tests?
outputLog.scoreLog();
console.log(outputLog);
}
function setNumAttempts(taskID) {
var prev_log = localStorage.getItem(taskID + "_test_log");
if (prev_log !== null && JSON.parse(prev_log).numAttempts !== undefined) {
return JSON.parse(prev_log).numAttempts;
} else {
return 0;
}
}
function isEDXurl() {
var url = window.location.href;
if (url.indexOf("edx") !== -1) {
return true;
} else {
return false;
}
}
var world;
window.onload = function () {
//check if attempt num for problem exists in local storage:
//AUTOGRADER ADDITION - FEEDBACK FORMATTING
// Checks if problem has been checked and modifies the autograded output if it has been checked
if (parent.document.getElementsByClassName("message").length !== 0) {
var hint = parent.document.getElementsByClassName("message")[0];
hint.innerHTML = formatFeedback(hint);
hint.style.display = "inline";
}
//INITIALIZE UP SNAP
world = new WorldMorph(document.getElementById('world'));
new IDE_Morph().openIn(world);
var ide = world.children[0];
//Reduce Stage Size on initialization
ide.toggleStageSize(true);
//AUTOGRADER ADDITION
//Check if Pre-requisite task has completed
var req_check = parent.document.getElementById("pre_req");
if (preReqTaskID !== null) {
var preReqLog = JSON.parse(localStorage.getItem(preReqID + "_test_log"));
if ((preReqLog === null || !preReqLog.allCorrect) && req_check) {
req_check.innerHTML = "[WARNING: The previous task must be completed before continuing.]"
}
}
//If page has already been loaded, restore previously tested XML
//TODO: Separate this into its own function.
var prev_xml = localStorage.getItem(id + "_test_state");
if (prev_xml !== null) {
ide.openProjectString(prev_xml);
} else if (preReqTaskID !== null) {
if (preReqLog !== null && preReqLog.allCorrect) {
ide.openProjectString(localStorage.getItem(preReqID));
}
}
//AUTOGRADER ADDITION -
//Forced to use setTimeout() to let the world load before... Maybe not.
//Create a gradingLog and initialize the AG status bar (AGSB).
// var testLog = AGStart(world, id);
//Initialize AGSB button.
var grade_button = document.getElementById("autograding_button");
grade_button.style.cursor = "pointer";
//Call the test suite when this element is clicked.
var update_listener = function() {
var outputLog = AGUpdate(world, id);
populateFeedback(outputLog);
};
var button_listener = function(event) {
event.stopPropagation();
console.log('PROPAGATION SHOULD STOP');
var numAttempts = setNumAttempts(id);
outputLog = new gradingLog(world, id, numAttempts);
outputLog.numAttempts += 1;
runAGTest(world, id, outputLog);
if (isEDX) {
parent.document.getElementsByClassName('check-label')[0].click();
}
// var outputLog = AGStart(world, id);
}
grade_button.addEventListener('click', button_listener);
var world_canvas = document.getElementById('world');
world_canvas.addEventListener("mouseup", update_listener);
// grade_button.onclick = function(event) {
// // event.stopPropagation();
// runAGTest(world, id);
// var outputLog = AGStart(world, id);
// //console.log(outputLog);
// //populateFeedback(outputLog);
// }
var reset_button = document.getElementById("reset-button");
var revert_button = document.getElementById("revert-button");
var undo_button = document.getElementById("undo-button");
var last_submit = document.getElementById("last-submit");
//var menu_button = document.getElementById("hamburger-menu");
var menu_button = document.getElementsByClassName("onclick-menu")[0];
//var help_menu = document.getElementById("circle");
var help_overlay = document.getElementById('overlay');
var feedback_button = document.getElementById("feedback-button");
var results_overlay = document.getElementById("ag-output");
var snapWorld = document.getElementById("world");
var regrade_buttons = document.getElementsByClassName("regrade");
//var outside_menu = document.getElementById("outside-menu");
reset_button.onclick = function() { resetState(world, id); toggleMenu(id); };
revert_button.onclick = function() { revertToBestState(world, id); toggleMenu(id); };
last_submit.onclick = function() { revertToLastSubmit(world, id); toggleMenu(id); };
undo_button.onclick = function() { revertToLastState(world, id); toggleMenu(id); };
menu_button.onclick = function() { toggleMenu(id); };
//var overlay_button = parent.document.getElementById('overlay-button');
//overlay_button.onclick = function() { grade_button.click(); }
$(".bubble").click(function(event){
event.stopPropagation();
});
feedback_button.onclick = function() {
openResults();
}
help_overlay.onclick = function(e) {
if (!(document.getElementById('help-popup').contains(e.target))) {
closePopup();
}
}
results_overlay.onclick = function(e) {
if (!(document.getElementById('ag-results').contains(e.target)) && e.target.className.indexOf("regrade") === -1) {
closeResults();
}
}
snapWorld.onclick = function(e) {
if (document.getElementById('dropdown-open') !== null && !(document.getElementById('onclick-menu').contains(e.target))) {
toggleMenu();
}
}
/*outside_menu.onclick = function(e) {
if (document.getElementById('dropdown-open') !== null && !(document.getElementById('onclick-menu').contains(e.target))) {
toggleMenu();
}
}*/
/* Check if the snap xml has changed "significantly".
* Exclude script position and edit history.
*/
document.addEventListener("click", function() {
grayOutButtons(world, id);
});
//TODO: Fix this timeout.
setTimeout(function() {
if (isEDX) {
var overlay_button = parent.document.createElement('button');
var overlay_button_text = parent.document.createTextNode('Grade');
overlay_button.appendChild(overlay_button_text);
overlay_button.id = 'overlay-button';
var button = parent.document.getElementsByName('problem_id')[0];
button.parentNode.insertBefore(overlay_button, button.nextSibling);
var overlay_button = parent.document.getElementById('overlay-button');
//overlay_button.style.display = "block";
overlay_button.onclick = function() {
overlay_button.style.display = "none";
grade_button.click();