sh1k4ku commited on
Commit
e92d3f2
Β·
verified Β·
1 Parent(s): a89f518

Upload index.html with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.html +184 -100
index.html CHANGED
@@ -96,6 +96,7 @@
96
  }
97
  #output .err { color: var(--err); }
98
  #output .ok { color: var(--ok); }
 
99
  #output .meta { color: var(--muted); }
100
  #output img { max-width: 100%; background: #fff; border-radius: 4px; margin: 8px 0; }
101
  </style>
@@ -155,45 +156,53 @@ print([fib(i) for i in range(10)])
155
  # import micropip; await micropip.install("matplotlib")
156
  `;
157
 
158
- // ===== Problems: each has a hidden .dat (its blackbox) + a test starter =====
159
  const PROBLEMS = {
160
  Q1: {
161
  data: "q1.dat",
162
- testTemplate: `# Q1 -- functions: grade(score), clamp(x, lo, hi), fizzbuzz(n)
163
- # The module "blackbox" is hidden. Write tests to verify its behaviour.
164
- import blackbox
165
-
166
- # expect(actual, expected, label): records one case; keeps going on failure
167
- expect(blackbox.grade(85), "HD", "85 should be HD")
168
- expect(blackbox.grade(84), "DN", "boundary 84")
169
- expect(blackbox.grade(50), "PS", "pass lower bound 50")
170
- expect(blackbox.grade(49), "FL", "49 should fail")
171
-
172
- expect(blackbox.fizzbuzz(15), "FizzBuzz", "15")
173
- expect(blackbox.fizzbuzz(7), "7", "7")
174
-
175
- expect(blackbox.clamp(12, 0, 10), 10, "above upper bound")
176
- expect(blackbox.clamp(-3, 0, 10), 0, "below lower bound")
177
-
178
- # See which functions blackbox exposes:
179
- print("callable:", [n for n in dir(blackbox) if not n.startswith('_')])
 
180
  `,
181
  },
182
  Q2: {
183
  data: "q2.dat",
184
- testTemplate: `# Q2 -- functions: is_palindrome(s), count_vowels(s), reverse_words(s)
185
- # The module "blackbox" is hidden. Write tests to verify its behaviour.
186
- import blackbox
187
-
188
- expect(blackbox.is_palindrome("Race car"), True, "ignores case & spaces")
189
- expect(blackbox.is_palindrome("hello"), False, "not a palindrome")
190
-
191
- expect(blackbox.count_vowels("Education"), 5, "count vowels")
192
- expect(blackbox.count_vowels("xyz"), 0, "no vowels")
193
-
194
- expect(blackbox.reverse_words("the quick fox"), "fox quick the", "reverse word order")
195
-
196
- print("callable:", [n for n in dir(blackbox) if not n.startswith('_')])
 
 
 
 
 
 
 
197
  `,
198
  },
199
  };
@@ -275,76 +284,139 @@ problemSel.onchange = async () => {
275
 
276
  applyMode();
277
 
278
- // ===== Test-framework prelude that runs inside Python =====
279
- // Reset on every run; expect() writes PASS to stdout, FAIL to stderr (rendered red).
280
- const PRELUDE = `
281
- import sys as _sys
282
- __bb_pass = 0
283
- __bb_fail = 0
284
- def expect(got, want, label=""):
285
- global __bb_pass, __bb_fail
286
- ok = got == want
287
- if ok:
288
- __bb_pass += 1
289
- print(f"[PASS] {label}".rstrip())
290
- else:
291
- __bb_fail += 1
292
- print(f"[FAIL] {label} got={got!r} want={want!r}".rstrip(), file=_sys.stderr)
293
- return ok
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  `;
295
 
296
  // ===== Load Pyodide + the hidden implementation =====
297
  let pyodide;
298
 
299
- // Fetch problem <key>'s hidden source, (re)import it as module "blackbox",
300
- // then erase its runtime traces so students can't read the implementation.
301
  async function loadProblem(key) {
302
  if (!pyodide) return; // not ready yet; startup will load the current prob
303
  const b64 = (await (await fetch(PROBLEMS[key].data)).text()).trim();
304
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
305
  const src = new TextDecoder("utf-8").decode(bytes);
306
- pyodide.FS.writeFile("blackbox.py", src);
307
- pyodide.runPython(`
308
- import os, sys, linecache
309
- if '.' not in sys.path:
310
- sys.path.insert(0, '.')
311
- sys.modules.pop('blackbox', None) # drop any previously loaded problem
312
- import blackbox
313
- for _a in ('__file__', '__loader__', '__spec__', '__cached__'):
314
- if hasattr(blackbox, _a):
315
- try: delattr(blackbox, _a)
316
- except Exception: pass
317
- try: os.remove('blackbox.py')
318
- except Exception: pass
319
- linecache.cache.clear()
320
- `);
321
- const funcs = pyodide.runPython(
322
- "[n for n in dir(__import__('blackbox')) if not n.startswith('_')]"
323
- ).toJs();
324
- modinfo.textContent = key + ": " + funcs.length + " function" + (funcs.length === 1 ? "" : "s");
325
  }
326
 
327
  (async () => {
328
  try {
329
  pyodide = await loadPyodide({
330
- // In test mode stdout carries PASS lines (green); in run mode it's normal output.
331
- stdout: (s) => append(s + "\n", mode === "test" ? "ok" : null),
332
  stderr: (s) => append(s + "\n", "err"),
333
  });
334
 
335
- // Install the source-hiding guard ONCE (applies to any module named "blackbox").
 
336
  pyodide.runPython(`
337
  import inspect
338
  _orig_getsource = inspect.getsource
339
  def _guard_getsource(obj, *a, **k):
340
- if getattr(obj, '__module__', None) == 'blackbox':
341
- raise OSError("source code is not available for blackbox")
 
342
  return _orig_getsource(obj, *a, **k)
343
  inspect.getsource = _guard_getsource
344
  inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
345
  `);
346
 
347
- await loadProblem(prob); // load the currently selected problem
 
348
 
349
  statusEl.textContent = "βœ“ Ready";
350
  statusEl.className = "status ready";
@@ -363,49 +435,61 @@ async function run() {
363
  output.innerHTML = "";
364
  summary.style.display = "none";
365
 
 
366
  try {
367
  if (mode === "test") {
368
- // Reset the test framework (same global namespace so student code sees expect)
369
- await pyodide.runPythonAsync(PRELUDE);
370
- await pyodide.runPythonAsync(editor.getValue()); // top-level await supported
371
- renderMatplotlib();
372
- showSummary();
 
373
  } else {
374
- // Plain run: just execute and show output, no test harness/summary
375
- const result = await pyodide.runPythonAsync(editor.getValue());
376
  renderMatplotlib();
377
  if (result !== undefined && result !== null) append(String(result) + "\n", "meta");
378
  }
379
  } catch (e) {
380
- // assert / syntax / runtime error: show cleaned traceback, then current stats
381
  append("\nExecution stopped:\n" + cleanError(e.message || String(e)) + "\n", "err");
382
- if (mode === "test") showSummary(true);
383
  } finally {
384
  runBtn.disabled = false;
385
  }
386
  }
387
  runBtn.onclick = run;
388
 
389
- function showSummary(aborted) {
390
- let p = 0, f = 0;
391
- try {
392
- p = pyodide.runPython("__bb_pass");
393
- f = pyodide.runPython("__bb_fail");
394
- } catch (_) {}
395
- if (p === 0 && f === 0 && !aborted) {
396
  summary.style.display = "none";
 
397
  return;
398
  }
399
- summary.style.display = "block";
400
- if (f === 0 && !aborted) {
401
- summary.className = "pass";
402
- summary.textContent = `βœ“ All passed: ${p}/${p}`;
403
- } else {
404
- summary.className = "fail";
405
- const total = p + f;
406
- summary.textContent =
407
- `βœ— Passed ${p}/${total}, failed ${f}` + (aborted ? " (execution interrupted)" : "");
 
 
 
 
 
 
 
408
  }
 
 
 
 
 
 
 
409
  }
410
 
411
  // Strip internal file paths from tracebacks to avoid leakage/noise
 
96
  }
97
  #output .err { color: var(--err); }
98
  #output .ok { color: var(--ok); }
99
+ #output .warn { color: #f9e2af; }
100
  #output .meta { color: var(--muted); }
101
  #output img { max-width: 100%; background: #fff; border-radius: 4px; margin: 8px 0; }
102
  </style>
 
156
  # import micropip; await micropip.install("matplotlib")
157
  `;
158
 
159
+ // ===== Problems: each has a hidden .dat (5-bug blackbox + oracle) + a test starter =====
160
  const PROBLEMS = {
161
  Q1: {
162
  data: "q1.dat",
163
+ public: "allocate",
164
+ sig: "allocate(students, rooms, capacity, mode)",
165
+ testTemplate: `# Q1 - UNSW Room Allocator (Boundary Value Testing)
166
+ # The hidden program blackbox.allocate(students, rooms, capacity, mode) has 5 bugs.
167
+ # A bug is CAUGHT when the program's output differs from the SPEC's expected output.
168
+ #
169
+ # Spec: students 1..300, rooms 1..10, capacity 5..50, mode in {Lecture, Tutorial, Exam}
170
+ # usable_per_room = capacity (Lecture/Tutorial) or capacity // 2 (Exam)
171
+ # total = rooms * usable_per_room
172
+ # SEATED if students <= total else OVERFLOW ; out-of-range/wrong-type -> INVALID
173
+ #
174
+ # Write a list named TESTS, one case per line, in the order:
175
+ # ((students, rooms, capacity, mode), "expected-from-spec")
176
+ TESTS = [
177
+ ((1, 1, 5, "Lecture"), "SEATED"),
178
+ ((301, 5, 25, "Lecture"), "INVALID"),
179
+ ((0, 1, 5, "Lecture"), "INVALID"),
180
+ # add your own boundary-value cases...
181
+ ]
182
  `,
183
  },
184
  Q2: {
185
  data: "q2.dat",
186
+ public: "approve",
187
+ sig: "approve(role, fte, weekly_hours, period)",
188
+ testTemplate: `# Q2 - UNSW Casual Workload Approval (Equivalence Class Testing)
189
+ # The hidden program blackbox.approve(role, fte, weekly_hours, period) has 5 bugs.
190
+ # A bug is CAUGHT when the program's output differs from the SPEC's expected output.
191
+ #
192
+ # Spec: role in {Tutor, Demonstrator, Marker, Coordinator}, 0 < fte <= 1.0,
193
+ # weekly_hours 1..60, period in {Teaching, Break}
194
+ # base = {Tutor:13, Demonstrator:16, Marker:9, Coordinator:21}; cap = floor(fte*base)
195
+ # Break: hours <= cap -> APPROVED else DENIED
196
+ # Teaching: hours <= cap -> APPROVED; cap < hours <= 2*cap -> REQUIRES_APPROVAL; else DENIED
197
+ # out-of-range / wrong type -> ERROR
198
+ #
199
+ # Write a list named TESTS, one case per line, in the order:
200
+ # ((role, fte, weekly_hours, period), "expected-from-spec")
201
+ TESTS = [
202
+ (("Tutor", 1.0, 5, "Teaching"), "APPROVED"),
203
+ (("Lecturer", 0.5, 10, "Teaching"), "ERROR"),
204
+ # add your own equivalence-class cases...
205
+ ]
206
  `,
207
  },
208
  };
 
284
 
285
  applyMode();
286
 
287
+ // ===== Grading harness that runs inside Python (defined once at startup) =====
288
+ // __bb_install: load a problem's hidden module, expose ONLY its public function as
289
+ // "blackbox", and stash the oracle + bug definitions privately in __BB.
290
+ // __bb_run: run the student's TESTS list, identify which bug each case catches,
291
+ // and report it with the source line number + reason.
292
+ const HARNESS = `
293
+ import sys, types, linecache, ast, json
294
+
295
+ def __bb_install(public_name, source):
296
+ ns = {}
297
+ exec(compile(source, "blackbox_impl", "exec"), ns)
298
+ combined = ns["blackbox"] # the 5-bug program students test
299
+ ref = ns["reference"] # the correct spec oracle (kept hidden)
300
+ bugs = ns["BUGS"] # name -> (single_bug_fn, marks) (hidden)
301
+ reasons = ns.get("REASONS", {})
302
+ # scrub the answer key out of the namespace reachable via __globals__
303
+ for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"):
304
+ ns.pop(k, None)
305
+ linecache.cache.clear()
306
+ pub = types.ModuleType("blackbox")
307
+ setattr(pub, public_name, combined)
308
+ sys.modules["blackbox"] = pub
309
+ globals()["__BB"] = {"fn": combined, "ref": ref, "bugs": bugs,
310
+ "reasons": reasons, "pub": public_name}
311
+
312
+ def __s(v):
313
+ return v if isinstance(v, str) else repr(v)
314
+
315
+ def __bb_run(source):
316
+ g = globals()
317
+ info = g.get("__BB")
318
+ TESTS = g.get("TESTS", None)
319
+ # map each TESTS element to its source line number (one case per line)
320
+ linenos = {}
321
+ try:
322
+ tree = ast.parse(source)
323
+ for node in ast.walk(tree):
324
+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets):
325
+ if isinstance(node.value, (ast.List, ast.Tuple)):
326
+ for i, el in enumerate(node.value.elts):
327
+ linenos[i] = el.lineno
328
+ except Exception:
329
+ pass
330
+ if not isinstance(TESTS, (list, tuple)):
331
+ return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."})
332
+ fn = info["fn"]; ref = info["ref"]; BUGS = info["bugs"]; REASONS = info["reasons"]
333
+ caught = {}
334
+ rows = []
335
+ for i, case in enumerate(TESTS):
336
+ line = linenos.get(i)
337
+ try:
338
+ args, expected = case
339
+ args = tuple(args)
340
+ except Exception:
341
+ rows.append({"line": line, "status": "malformed", "raw": repr(case)})
342
+ continue
343
+ try:
344
+ actual = fn(*args)
345
+ except Exception as e:
346
+ rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)})
347
+ continue
348
+ spec = ref(*args)
349
+ bug = None
350
+ for name in BUGS:
351
+ try:
352
+ if BUGS[name][0](*args) != spec:
353
+ bug = name; break
354
+ except Exception:
355
+ pass
356
+ argstr = repr(args)
357
+ valid_expected = (expected == spec)
358
+ if actual != expected:
359
+ if not valid_expected:
360
+ rows.append({"line": line, "status": "invalid", "argstr": argstr,
361
+ "expected": __s(expected), "spec": __s(spec)})
362
+ else:
363
+ if bug is None:
364
+ bug = "(unknown)"
365
+ first = bug not in caught
366
+ if first:
367
+ caught[bug] = line
368
+ rows.append({"line": line, "status": "bug" if first else "dup",
369
+ "bug": bug, "reason": REASONS.get(bug, "output differs from the spec"),
370
+ "argstr": argstr, "actual": __s(actual), "expected": __s(expected)})
371
+ else:
372
+ if not valid_expected:
373
+ rows.append({"line": line, "status": "invalid", "argstr": argstr,
374
+ "expected": __s(expected), "spec": __s(spec)})
375
+ else:
376
+ rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": __s(actual)})
377
+ return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()),
378
+ "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(TESTS)})
379
  `;
380
 
381
  // ===== Load Pyodide + the hidden implementation =====
382
  let pyodide;
383
 
384
+ // Fetch problem <key>'s hidden source and install it: only its public function is
385
+ // exposed as "blackbox"; the oracle + bug definitions stay private in __BB.
386
  async function loadProblem(key) {
387
  if (!pyodide) return; // not ready yet; startup will load the current prob
388
  const b64 = (await (await fetch(PROBLEMS[key].data)).text()).trim();
389
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
390
  const src = new TextDecoder("utf-8").decode(bytes);
391
+ pyodide.globals.set("__bb_src", src);
392
+ pyodide.runPython(`__bb_install(${JSON.stringify(PROBLEMS[key].public)}, __bb_src)`);
393
+ pyodide.runPython("del globals()['__bb_src']");
394
+ modinfo.textContent = key + " Β· " + PROBLEMS[key].sig;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  }
396
 
397
  (async () => {
398
  try {
399
  pyodide = await loadPyodide({
400
+ stdout: (s) => append(s + "\n"),
 
401
  stderr: (s) => append(s + "\n", "err"),
402
  });
403
 
404
+ // Block reading hidden source via inspect (defence-in-depth; getsource also
405
+ // fails naturally because no source file exists on disk).
406
  pyodide.runPython(`
407
  import inspect
408
  _orig_getsource = inspect.getsource
409
  def _guard_getsource(obj, *a, **k):
410
+ mod = getattr(obj, '__module__', None)
411
+ if mod in (None, 'blackbox', 'blackbox_impl'):
412
+ raise OSError("source code is not available")
413
  return _orig_getsource(obj, *a, **k)
414
  inspect.getsource = _guard_getsource
415
  inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
416
  `);
417
 
418
+ pyodide.runPython(HARNESS); // define __bb_install / __bb_run
419
+ await loadProblem(prob); // load the currently selected problem
420
 
421
  statusEl.textContent = "βœ“ Ready";
422
  statusEl.className = "status ready";
 
435
  output.innerHTML = "";
436
  summary.style.display = "none";
437
 
438
+ const code = editor.getValue();
439
  try {
440
  if (mode === "test") {
441
+ // Run the student's code to define TESTS, then grade it against the hidden oracle.
442
+ pyodide.runPython("globals().pop('TESTS', None)");
443
+ pyodide.globals.set("__SRC", code);
444
+ await pyodide.runPythonAsync(code); // defines TESTS (and any prints)
445
+ const rep = JSON.parse(pyodide.runPython("__bb_run(__SRC)"));
446
+ renderReport(rep);
447
  } else {
448
+ // Plain run: just execute and show output, no grading
449
+ const result = await pyodide.runPythonAsync(code);
450
  renderMatplotlib();
451
  if (result !== undefined && result !== null) append(String(result) + "\n", "meta");
452
  }
453
  } catch (e) {
 
454
  append("\nExecution stopped:\n" + cleanError(e.message || String(e)) + "\n", "err");
 
455
  } finally {
456
  runBtn.disabled = false;
457
  }
458
  }
459
  runBtn.onclick = run;
460
 
461
+ // Render the grading report: one line per test case, a "Bug caught at line N" for
462
+ // each newly-detected bug, and a summary of how many distinct bugs were caught.
463
+ function renderReport(rep) {
464
+ if (!rep.ok) {
 
 
 
465
  summary.style.display = "none";
466
+ append((rep.error || "Invalid test setup.") + "\n", "err");
467
  return;
468
  }
469
+ for (const r of rep.rows) {
470
+ const at = r.line ? "line " + r.line : "(unknown line)";
471
+ if (r.status === "bug") {
472
+ append(`βœ“ Bug caught at ${at}: ${r.reason}\n`, "ok");
473
+ append(` input ${r.argstr} β†’ program returned ${r.actual}, spec expects ${r.expected}\n`, "meta");
474
+ } else if (r.status === "dup") {
475
+ append(`Β· ${at}: catches the same bug again (${r.bug})\n`, "meta");
476
+ } else if (r.status === "invalid") {
477
+ append(`⚠ ${at}: expected ${r.expected} does NOT match the spec (spec says ${r.spec}) β€” this test does not count\n`, "warn");
478
+ } else if (r.status === "ok") {
479
+ append(`Β· ${at}: program matches the spec (${r.actual}) β€” no bug here\n`, "meta");
480
+ } else if (r.status === "malformed") {
481
+ append(`βœ— ${at}: malformed test case ${r.raw} β€” expected ((args), expected)\n`, "err");
482
+ } else if (r.status === "error") {
483
+ append(`βœ— ${at}: error calling the program on ${r.argstr}: ${r.msg}\n`, "err");
484
+ }
485
  }
486
+ const all = rep.caughtCount === rep.totalBugs;
487
+ summary.style.display = "block";
488
+ summary.className = all ? "pass" : "";
489
+ summary.style.color = all ? "" : "var(--accent)";
490
+ summary.textContent = all
491
+ ? `🐞 Caught all ${rep.totalBugs}/${rep.totalBugs} bugs`
492
+ : `🐞 Caught ${rep.caughtCount}/${rep.totalBugs} bugs (${rep.totalBugs - rep.caughtCount} still hidden)`;
493
  }
494
 
495
  // Strip internal file paths from tracebacks to avoid leakage/noise