Coverage for e2xgrader/preprocessors/unpermutetasks.py: 23%

26 statements  

« prev     ^ index     » next       coverage.py v7.4.2, created at 2024-03-14 13:22 +0100

1from e2xcore.utils.nbgrader_cells import get_tasks, grade_id 

2from nbformat.v4 import new_notebook 

3from nbgrader.preprocessors import NbGraderPreprocessor 

4 

5 

6class UnpermuteTasks(NbGraderPreprocessor): 

7 def unpermute(self, nb): 

8 unpermuted_nb = new_notebook() 

9 # Get original order 

10 original_order = nb.metadata.original_order 

11 # Get indices of tasks 

12 tasks = get_tasks(nb) 

13 

14 cursor = 0 

15 

16 for task in tasks: 

17 # Add all cells between cursor and current task 

18 for idx in range(cursor, task[0]): 

19 unpermuted_nb.cells.append(nb.cells[idx]) 

20 # Get name and cells of next task in the original order 

21 next_task_id = original_order.pop(0) 

22 next_task = [ 

23 task for task in tasks if grade_id(nb.cells[task[0]]) == next_task_id 

24 ][0] 

25 # Add cells of the next task 

26 unpermuted_nb.cells.extend([nb.cells[idx] for idx in next_task]) 

27 # Set the cursor to the idx after the inserted task 

28 cursor = task[-1] + 1 

29 

30 # Add remaining cells at the bottom of the notebook 

31 unpermuted_nb.cells.extend( 

32 [nb.cells[idx] for idx in range(cursor, len(nb.cells))] 

33 ) 

34 

35 return unpermuted_nb 

36 

37 def preprocess(self, nb, resources): 

38 if "original_order" not in nb.metadata: 

39 return nb, resources 

40 

41 perm = nb.metadata.permutation 

42 keys = sorted(range(len(perm)), key=perm.__getitem__) 

43 reorder_cells = [nb.cells[i] for i in keys] 

44 nb.cells = reorder_cells 

45 return nb, resources