~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/worksheet/utils.py

  • Committer: William Grant
  • Date: 2010-02-25 07:34:50 UTC
  • Revision ID: grantw@unimelb.edu.au-20100225073450-zcl8ev5hlyhbszeu
Activate the Storm C extensions if possible. Moar speed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
This module provides functions for tutorial and worksheet computations.
24
24
"""
25
25
 
 
26
import os.path
 
27
 
26
28
from storm.locals import And, Asc, Desc, Store
27
29
import genshi
28
30
 
29
31
import ivle.database
30
32
from ivle.database import ExerciseAttempt, ExerciseSave, Worksheet, \
31
 
                          WorksheetExercise, Exercise
 
33
                          WorksheetExercise, Exercise, User
 
34
import ivle.webapp.tutorial.test
32
35
 
33
 
__all__ = ['get_exercise_status', 'get_exercise_stored_text',
34
 
           'get_exercise_attempts', 'get_exercise_attempt',
 
36
__all__ = ['ExerciseNotFound', 'get_exercise_status',
 
37
           'get_exercise_statistics',
 
38
           'get_exercise_stored_text', 'get_exercise_attempts',
 
39
           'get_exercise_attempt', 'test_exercise_submission',
35
40
          ]
36
41
 
37
 
def get_exercise_status(store, user, worksheet_exercise):
 
42
class ExerciseNotFound(Exception):
 
43
    pass
 
44
 
 
45
def get_exercise_status(store, user, worksheet_exercise, as_of=None):
38
46
    """Given a storm.store, User and Exercise, returns information about
39
47
    the user's performance on that problem.
 
48
    @param store: A storm.store
 
49
    @param user: A User.
 
50
    @param worksheet_exercise: An Exercise.
 
51
    @param as_of: Optional datetime. If supplied, gets the status as of as_of.
40
52
    Returns a tuple of:
41
53
        - A boolean, whether they have successfully passed this exercise.
42
54
        - An int, the number of attempts they have made up to and
48
60
    is_relevant = ((ExerciseAttempt.user_id == user.id) &
49
61
            (ExerciseAttempt.ws_ex_id == worksheet_exercise.id) &
50
62
            (ExerciseAttempt.active == True))
 
63
    if as_of is not None:
 
64
        is_relevant &= ExerciseAttempt.date <= as_of
51
65
 
52
66
    # Get the first successful active attempt, or None if no success yet.
53
67
    # (For this user, for this exercise).
69
83
 
70
84
    return first_success is not None, num_attempts
71
85
 
 
86
def get_exercise_statistics(store, worksheet_exercise):
 
87
    """Return statistics about an exercise (with respect to a given
 
88
    worksheet).
 
89
    (number of students completed, number of students attempted)."""
 
90
    # Count the set of Users whose ID matches an attempt in this worksheet
 
91
    num_completed = store.find(User, User.id == ExerciseAttempt.user_id,
 
92
        ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
 
93
        ExerciseAttempt.complete == True).config(distinct=True).count()
 
94
    num_attempted = store.find(User, User.id == ExerciseAttempt.user_id,
 
95
        ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
 
96
        ).config(distinct=True).count()
 
97
    return num_completed, num_attempted
 
98
 
72
99
def get_exercise_stored_text(store, user, worksheet_exercise):
73
100
    """Given a storm.store, User and WorksheetExercise, returns an
74
101
    ivle.database.ExerciseSave object for the last saved/submitted attempt for
162
189
    saved.date = date
163
190
    saved.text = text
164
191
 
165
 
def calculate_score(store, user, worksheet):
 
192
def calculate_score(store, user, worksheet, as_of=None):
166
193
    """
167
194
    Given a storm.store, User, Exercise and Worksheet, calculates a score for
168
195
    the user on the given worksheet.
 
196
    @param store: A storm.store
 
197
    @param user: A User.
 
198
    @param worksheet: A Worksheet.
 
199
    @param as_of: Optional datetime. If supplied, gets the score as of as_of.
169
200
    Returns a 4-tuple of ints, consisting of:
170
201
    (No. mandatory exercises completed,
171
202
     Total no. mandatory exercises,
183
214
        worksheet = worksheet_exercise.worksheet
184
215
        optional = worksheet_exercise.optional
185
216
 
186
 
        done, _ = get_exercise_status(store, user, worksheet_exercise)
 
217
        done, _ = get_exercise_status(store, user, worksheet_exercise, as_of)
187
218
        # done is a bool, whether this student has completed that problem
188
219
        if optional:
189
220
            opt_total += 1
194
225
 
195
226
    return mand_done, mand_total, opt_done, opt_total
196
227
 
 
228
def calculate_mark(mand_done, mand_total):
 
229
    """Calculate a subject mark, given the result of all worksheets.
 
230
    @param mand_done: The total number of mandatory exercises completed by
 
231
        some student, across all worksheets.
 
232
    @param mand_total: The total number of mandatory exercises across all
 
233
        worksheets in the offering.
 
234
    @return: (percent, mark, mark_total)
 
235
        percent: The percentage of exercises the student has completed, as an
 
236
            integer between 0 and 100 inclusive.
 
237
        mark: The mark the student has received, based on the percentage.
 
238
        mark_total: The total number of marks available (currently hard-coded
 
239
            as 5).
 
240
    """
 
241
    # We want to display a students mark out of 5. However, they are
 
242
    # allowed to skip 1 in 5 questions and still get 'full marks'.
 
243
    # Hence we divide by 16, essentially making 16 percent worth
 
244
    # 1 star, and 80 or above worth 5.
 
245
    if mand_total > 0:
 
246
        percent_int = (100 * mand_done) // mand_total
 
247
    else:
 
248
        # Avoid Div0, just give everyone 0 marks if there are none available
 
249
        percent_int = 0
 
250
    # percent / 16, rounded down, with a maximum mark of 5
 
251
    max_mark = 5
 
252
    mark = min(percent_int // 16, max_mark)
 
253
    return (percent_int, mark, max_mark)
 
254
 
197
255
def update_exerciselist(worksheet):
198
256
    """Runs through the worksheetstream, generating the appropriate
199
257
    WorksheetExercises, and de-activating the old ones."""
200
258
    exercises = []
201
259
    # Turns the worksheet into an xml stream, and then finds all the 
202
260
    # exercise nodes in the stream.
203
 
    worksheetdata = genshi.XML(worksheet.data)
 
261
    worksheetdata = genshi.XML(worksheet.data_xhtml)
204
262
    for kind, data, pos in worksheetdata:
205
263
        if kind is genshi.core.START:
206
264
            # Data is a tuple of tag name and a list of name->value tuples
231
289
                Exercise.id == exerciseid
232
290
            ).one()
233
291
            if exercise is None:
234
 
                raise NotFound()
 
292
                raise ExerciseNotFound(exerciseid)
235
293
            worksheet_exercise = WorksheetExercise()
236
294
            worksheet_exercise.worksheet_id = worksheet.id
237
295
            worksheet_exercise.exercise_id = exercise.id
240
298
        worksheet_exercise.seq_no = ex_num
241
299
        worksheet_exercise.optional = optional
242
300
 
 
301
 
 
302
def test_exercise_submission(config, user, exercise, code):
 
303
    """Test the given code against an exercise.
 
304
 
 
305
    The code is run in a console process as the provided user.
 
306
    """
 
307
    # Start a console to run the tests on
 
308
    jail_path = os.path.join(config['paths']['jails']['mounts'],
 
309
                             user.login)
 
310
    working_dir = os.path.join("/home", user.login)
 
311
    cons = ivle.console.Console(config, user.unixid, jail_path,
 
312
                                working_dir)
 
313
 
 
314
    # Parse the file into a exercise object using the test suite
 
315
    exercise_obj = ivle.webapp.tutorial.test.parse_exercise_file(
 
316
        exercise, cons)
 
317
 
 
318
    # Run the test cases. Get the result back as a JSONable object.
 
319
    # Return it.
 
320
    test_results = exercise_obj.run_tests(code)
 
321
 
 
322
    # Close the console
 
323
    cons.close()
 
324
 
 
325
    return test_results
 
326
 
 
327
 
 
328
class FakeWorksheetForMarks:
 
329
    """This class represents a worksheet and a particular students progress
 
330
    through it.
 
331
    
 
332
    Do not confuse this with a worksheet in the database. This worksheet
 
333
    has extra information for use in the output, such as marks."""
 
334
    def __init__(self, id, name, assessable, published):
 
335
        self.id = id
 
336
        self.name = name
 
337
        self.assessable = assessable
 
338
        self.published = published
 
339
        self.complete_class = ''
 
340
        self.optional_message = ''
 
341
        self.total = 0
 
342
        self.mand_done = 0
 
343
    def __repr__(self):
 
344
        return ("Worksheet(id=%s, name=%s, assessable=%s)"
 
345
                % (repr(self.id), repr(self.name), repr(self.assessable)))
 
346
 
 
347
 
 
348
# XXX: This really shouldn't be needed.
 
349
def create_list_of_fake_worksheets_and_stats(config, store, user, offering):
 
350
    """Take an offering's real worksheets, converting them into stats.
 
351
 
 
352
    The worksheet listing views expect special fake worksheet objects
 
353
    that contain counts of exercises, whether they've been completed,
 
354
    that sort of thing. A fake worksheet object is used to contain
 
355
    these values, because nobody has managed to refactor the need out
 
356
    yet.
 
357
    """
 
358
    new_worksheets = []
 
359
    problems_done = 0
 
360
    problems_total = 0
 
361
 
 
362
    # Offering.worksheets is ordered by the worksheets seq_no
 
363
    worksheets = offering.worksheets
 
364
 
 
365
    # Unless we can edit worksheets, hide unpublished ones.
 
366
    if 'edit_worksheets' not in offering.get_permissions(user, config):
 
367
        worksheets = worksheets.find(published=True)
 
368
 
 
369
    for worksheet in worksheets:
 
370
        new_worksheet = FakeWorksheetForMarks(
 
371
            worksheet.identifier, worksheet.name, worksheet.assessable,
 
372
            worksheet.published)
 
373
        if new_worksheet.assessable:
 
374
            # Calculate the user's score for this worksheet
 
375
            mand_done, mand_total, opt_done, opt_total = (
 
376
                ivle.worksheet.utils.calculate_score(store, user, worksheet))
 
377
            if opt_total > 0:
 
378
                optional_message = " (excluding optional exercises)"
 
379
            else:
 
380
                optional_message = ""
 
381
            if mand_done >= mand_total:
 
382
                new_worksheet.complete_class = "complete"
 
383
            elif mand_done > 0:
 
384
                new_worksheet.complete_class = "semicomplete"
 
385
            else:
 
386
                new_worksheet.complete_class = "incomplete"
 
387
            problems_done += mand_done
 
388
            problems_total += mand_total
 
389
            new_worksheet.mand_done = mand_done
 
390
            new_worksheet.total = mand_total
 
391
            new_worksheet.optional_message = optional_message
 
392
        new_worksheets.append(new_worksheet)
 
393
 
 
394
    return new_worksheets, problems_total, problems_done