-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathevaluation.js
More file actions
303 lines (266 loc) · 10.5 KB
/
evaluation.js
File metadata and controls
303 lines (266 loc) · 10.5 KB
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
<<<<<<< HEAD
window.CodeOceanEditorEvaluation = {
=======
const CodeOceanEditorEvaluation = {
>>>>>>> 787f0509 (refactor: Move Sprocket JS files to Webpack)
// A list of non-printable characters that are not allowed in the code output.
// Taken from https://stackoverflow.com/a/69024306
nonPrintableRegEx: /[\u0000-\u0008\u000B\u000C\u000F-\u001F\u007F-\u009F\u2000-\u200F\u2028-\u202F\u205F-\u206F\u3000\uFEFF]/g,
/**
* Scoring-Functions
*/
scoreCode: function (event) {
event.preventDefault();
const cause = $('#assess');
this.newSentryTransaction(cause, async () => {
await this.stopCode(event);
this.clearScoringOutput();
$('#submit').addClass("d-none");
const submission = await this.createSubmission(cause, null).catch((response) => {
this.ajaxError(response);
cause.one('click', this.scoreCode.bind(this));
});
if (!submission) return;
this.showSpinner($('#assess'));
$('#score_div').removeClass('d-none');
await this.socketScoreCode(submission.id);
});
},
handleScoringResponse: function (results) {
this.printScoringResults(results);
var score = _.reduce(results, function (sum, result) {
return sum + result.score * result.weight;
}, 0).toFixed(2);
$('#score').data('score', score);
this.renderScore();
},
printScoringResult: function (result, index) {
if (result === undefined || result === null) {
return;
}
$('#results').show();
let card;
if (result.file_role === 'teacher_defined_linter') {
card = $('#linter-dummies').children().first().clone();
} else {
card = $('#test-dummies').children().first().clone();
}
if (card.isPresent()) {
// the card won't be present if @embed_options[:hide_test_results] == true
this.populateCard(card, result, index);
$('#results ul').first().append(card);
}
},
printScoringResults: function (response) {
response = (Array.isArray(response)) ? response : [response]
const test_results = response.filter(function(x) {
if (x === undefined || x === null) {
return false;
}
switch (x.file_role) {
case 'teacher_defined_test':
return true;
case 'teacher_defined_linter':
return true;
default:
return false;
}
});
$('#results ul').first().html('');
$('.test-count .number').html(test_results.length);
this.clearOutput();
_.each(test_results, function (result, index) {
// based on https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
if (result === Object(result)) {
this.printOutput(result, false, index);
this.printScoringResult(result, index);
}
}.bind(this));
if (_.some(response, function (result) {
return result.status === 'timeout';
})) {
this.showTimeoutMessage();
}
if (_.some(response, function (result) {
return result.status === 'out_of_memory';
})) {
this.showOutOfMemoryMessage();
}
if (_.some(response, function (result) {
return result.status === 'runner_in_use';
})) {
this.showRunnerInUseMessage();
}
if (_.some(response, function (result) {
return result.status === 'container_depleted';
})) {
this.showContainerDepletedMessage();
}
},
renderScore: function () {
var score = parseFloat($('#score').data('score'));
var maximum_score = parseFloat($('#score').data('maximum-score'));
if (score >= 0 && score <= maximum_score && maximum_score > 0) {
var percentage_score = (score / maximum_score * 100).toFixed(0);
$('.score').html(percentage_score + '%');
} else {
$('.score').html(0 + '%');
}
this.renderProgressBar(score, maximum_score);
},
/**
* Testing-Logic
*/
handleTestResponse: function (result) {
this.clearOutput();
this.printOutput(result, false, 0);
this.showStatus(result);
this.showOutputBar();
},
/**
* Stop-Logic
*/
stopCode: async function (event) {
event && event.preventDefault();
if (this.websocket && this.websocket.getReadyState() !== WebSocket.CLOSED) {
const websocketClosedPromise = new Promise((resolve) => {
this.websocket.onClose(() => {
this.killWebsocket();
this.cleanUpUI();
resolve();
});
})
this.websocket.send(JSON.stringify({'cmd': 'client_kill'}));
return websocketClosedPromise;
}
},
killWebsocket: function () {
if (this.websocket != null && this.websocket.getReadyState() !== WebSocket.OPEN) {
return;
}
this.websocket.killWebSocket();
this.websocket.onError(_.noop);
this.running = false;
},
cleanUpUI: function () {
this.hideSpinner();
this.toggleButtonStates();
this.hidePrompt();
},
/**
* Output-Logic
*/
printWebsocketOutput: function (msg) {
if (!msg.data || msg.data === "\r") {
return;
}
var stream = {};
stream[msg.stream] = msg.data;
this.printOutput(stream, true, 0);
},
clearOutput: function () {
$('#output > .output-element').remove();
CodeOceanEditorTurtle.hideCanvas();
},
clearScoringOutput: function () {
$('#results ul').first().html('');
$('.test-count .number').html(0);
$('#score').data('score', 0);
this.renderScore();
this.clearOutput();
},
printOutput: function (output, colorize, index) {
if (output === undefined || output === null || output.stderr === undefined && output.stdout === undefined) {
// Prevent empty element with no text at all
return;
}
const sanitizedStdout = this.sanitizeOutput(output.stdout);
const sanitizedStderr = this.sanitizeOutput(output.stderr);
const element = this.findOrCreateOutputElement(index);
const pre = $('<span>');
if (sanitizedStdout !== '') {
if (colorize) {
pre.addClass('text-success');
}
pre.append(sanitizedStdout)
}
if (sanitizedStderr !== '') {
if (colorize) {
pre.addClass('text-warning');
} else {
pre.append('StdErr: ');
}
pre.append(sanitizedStderr);
}
if (sanitizedStdout === '' && sanitizedStderr === '') {
if (colorize) {
pre.addClass('text-body-secondary');
}
pre.text($('#output').data('message-no-output'))
}
element.append(pre);
},
sanitizeOutput: function (rawContent) {
let sanitizedContent = _.escape(rawContent).replace(this.nonPrintableRegEx, "");
if (rawContent !== undefined && rawContent.trim().startsWith("<img")) {
const doc = new DOMParser().parseFromString(rawContent, "text/html");
// Get the parsed element, it is automatically wrapped in a <html><body> document
const parsedElement = doc.firstChild.lastChild.firstChild;
if (parsedElement.src.startsWith("data:image")) {
const sanitizedImg = document.createElement('img');
sanitizedImg.src = parsedElement.src;
sanitizedContent = sanitizedImg.outerHTML + "\n";
}
}
return sanitizedContent;
},
getDeadlineInformation: function(deadline, translation_key, otherwise) {
if (deadline !== undefined) {
let li = document.createElement("li");
this.submission_deadline = new Date(deadline);
let deadline_text = I18n.l("time.formats.long", this.submission_deadline);
deadline_text += ` (${this.getUTCTime(this.submission_deadline, I18n.locale === 'en')})`;
const bullet_point = I18n.t(`exercises.editor.hints.${translation_key}`,
{ deadline: deadline_text, otherwise: otherwise })
let text = $.parseHTML(bullet_point);
$(li).append(text);
return li;
}
},
getUTCTime: function(d, use_am_pm) {
let hour = d.getUTCHours();
const pm = hour >= 12;
let hour12 = hour % 12;
if (!hour12) {
hour12 += 12;
}
hour = hour.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping: false})
const minute = d.getUTCMinutes().toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping: false})
const second = d.getUTCSeconds().toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping: false})
if (use_am_pm) {
return `${hour12}:${minute}:${second} ${pm ? 'pm' : 'am'} UTC`;
} else {
return `${hour}:${minute}:${second} UTC`;
}
},
initializeDeadlines: function () {
const deadline = $('#deadline');
if (deadline) {
const submission_deadline = deadline.data('submission-deadline');
const late_submission_deadline = deadline.data('late-submission-deadline');
const ul = document.createElement("ul");
if (submission_deadline && late_submission_deadline) {
// i18n-tasks-use t('exercises.editor.hints.submission_deadline')
ul.append(this.getDeadlineInformation(submission_deadline, 'submission_deadline', ''));
// i18n-tasks-use t('exercises.editor.hints.late_submission_deadline')
ul.append(this.getDeadlineInformation(late_submission_deadline, 'late_submission_deadline', ''));
} else {
const otherwise_no_points = I18n.t('exercises.editor.hints.otherwise');
// i18n-tasks-use t('exercises.editor.hints.submission_deadline')
ul.append(this.getDeadlineInformation(submission_deadline, 'submission_deadline', otherwise_no_points));
}
$(ul).insertAfter($(deadline).children()[0]);
}
}
};
export default CodeOceanEditor;