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

« back to all changes in this revision

Viewing changes to ivle/worksheet.py

  • Committer: William Grant
  • Date: 2009-02-27 05:07:09 UTC
  • Revision ID: grantw@unimelb.edu.au-20090227050709-k16kvhyl50nzjbwm
Subject URLs now contain the short name (eg. info1) rather than the code
(eg. 600151).

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
 
 
28
26
from storm.locals import And, Asc, Desc, Store
29
27
import genshi
30
28
 
31
29
import ivle.database
32
30
from ivle.database import ExerciseAttempt, ExerciseSave, Worksheet, \
33
31
                          WorksheetExercise, Exercise
34
 
import ivle.webapp.tutorial.test
35
32
 
36
 
__all__ = ['ExerciseNotFound', 'get_exercise_status',
37
 
           'get_exercise_stored_text', 'get_exercise_attempts',
38
 
           'get_exercise_attempt', 'test_exercise_submission',
 
33
__all__ = ['get_exercise_status', 'get_exercise_stored_text',
 
34
           'get_exercise_attempts', 'get_exercise_attempt',
39
35
          ]
40
36
 
41
 
class ExerciseNotFound(Exception):
42
 
    pass
43
 
 
44
 
def get_exercise_status(store, user, worksheet_exercise, as_of=None):
 
37
def get_exercise_status(store, user, worksheet_exercise):
45
38
    """Given a storm.store, User and Exercise, returns information about
46
39
    the user's performance on that problem.
47
 
    @param store: A storm.store
48
 
    @param user: A User.
49
 
    @param worksheet_exercise: An Exercise.
50
 
    @param as_of: Optional datetime. If supplied, gets the status as of as_of.
51
40
    Returns a tuple of:
52
41
        - A boolean, whether they have successfully passed this exercise.
53
42
        - An int, the number of attempts they have made up to and
59
48
    is_relevant = ((ExerciseAttempt.user_id == user.id) &
60
49
            (ExerciseAttempt.ws_ex_id == worksheet_exercise.id) &
61
50
            (ExerciseAttempt.active == True))
62
 
    if as_of is not None:
63
 
        is_relevant &= ExerciseAttempt.date <= as_of
64
51
 
65
52
    # Get the first successful active attempt, or None if no success yet.
66
53
    # (For this user, for this exercise).
175
162
    saved.date = date
176
163
    saved.text = text
177
164
 
178
 
def calculate_score(store, user, worksheet, as_of=None):
 
165
def calculate_score(store, user, worksheet):
179
166
    """
180
167
    Given a storm.store, User, Exercise and Worksheet, calculates a score for
181
168
    the user on the given worksheet.
182
 
    @param store: A storm.store
183
 
    @param user: A User.
184
 
    @param worksheet: A Worksheet.
185
 
    @param as_of: Optional datetime. If supplied, gets the score as of as_of.
186
169
    Returns a 4-tuple of ints, consisting of:
187
170
    (No. mandatory exercises completed,
188
171
     Total no. mandatory exercises,
200
183
        worksheet = worksheet_exercise.worksheet
201
184
        optional = worksheet_exercise.optional
202
185
 
203
 
        done, _ = get_exercise_status(store, user, worksheet_exercise, as_of)
 
186
        done, _ = get_exercise_status(store, user, worksheet_exercise)
204
187
        # done is a bool, whether this student has completed that problem
205
188
        if optional:
206
189
            opt_total += 1
211
194
 
212
195
    return mand_done, mand_total, opt_done, opt_total
213
196
 
214
 
def calculate_mark(mand_done, mand_total):
215
 
    """Calculate a subject mark, given the result of all worksheets.
216
 
    @param mand_done: The total number of mandatory exercises completed by
217
 
        some student, across all worksheets.
218
 
    @param mand_total: The total number of mandatory exercises across all
219
 
        worksheets in the offering.
220
 
    @return: (percent, mark, mark_total)
221
 
        percent: The percentage of exercises the student has completed, as an
222
 
            integer between 0 and 100 inclusive.
223
 
        mark: The mark the student has received, based on the percentage.
224
 
        mark_total: The total number of marks available (currently hard-coded
225
 
            as 5).
226
 
    """
227
 
    # We want to display a students mark out of 5. However, they are
228
 
    # allowed to skip 1 in 5 questions and still get 'full marks'.
229
 
    # Hence we divide by 16, essentially making 16 percent worth
230
 
    # 1 star, and 80 or above worth 5.
231
 
    if mand_total > 0:
232
 
        percent_int = (100 * mand_done) // mand_total
233
 
    else:
234
 
        # Avoid Div0, just give everyone 0 marks if there are none available
235
 
        percent_int = 0
236
 
    # percent / 16, rounded down, with a maximum mark of 5
237
 
    max_mark = 5
238
 
    mark = min(percent_int // 16, max_mark)
239
 
    return (percent_int, mark, max_mark)
240
 
 
241
197
def update_exerciselist(worksheet):
242
198
    """Runs through the worksheetstream, generating the appropriate
243
199
    WorksheetExercises, and de-activating the old ones."""
244
200
    exercises = []
245
201
    # Turns the worksheet into an xml stream, and then finds all the 
246
202
    # exercise nodes in the stream.
247
 
    worksheetdata = genshi.XML(worksheet.get_xml())
 
203
    worksheetdata = genshi.XML(worksheet.data)
248
204
    for kind, data, pos in worksheetdata:
249
205
        if kind is genshi.core.START:
250
206
            # Data is a tuple of tag name and a list of name->value tuples
275
231
                Exercise.id == exerciseid
276
232
            ).one()
277
233
            if exercise is None:
278
 
                raise ExerciseNotFound(exerciseid)
 
234
                raise NotFound()
279
235
            worksheet_exercise = WorksheetExercise()
280
236
            worksheet_exercise.worksheet_id = worksheet.id
281
237
            worksheet_exercise.exercise_id = exercise.id
284
240
        worksheet_exercise.seq_no = ex_num
285
241
        worksheet_exercise.optional = optional
286
242
 
287
 
 
288
 
def test_exercise_submission(config, user, exercise, code):
289
 
    """Test the given code against an exercise.
290
 
 
291
 
    The code is run in a console process as the provided user.
292
 
    """
293
 
    # Start a console to run the tests on
294
 
    jail_path = os.path.join(config['paths']['jails']['mounts'],
295
 
                             user.login)
296
 
    working_dir = os.path.join("/home", user.login)
297
 
    cons = ivle.console.Console(config, user.unixid, jail_path,
298
 
                                working_dir)
299
 
 
300
 
    # Parse the file into a exercise object using the test suite
301
 
    exercise_obj = ivle.webapp.tutorial.test.parse_exercise_file(
302
 
        exercise, cons)
303
 
 
304
 
    # Run the test cases. Get the result back as a JSONable object.
305
 
    # Return it.
306
 
    test_results = exercise_obj.run_tests(code)
307
 
 
308
 
    # Close the console
309
 
    cons.close()
310
 
 
311
 
    return test_results
312
 
 
313
 
 
314
 
class FakeWorksheetForMarks:
315
 
    """This class represents a worksheet and a particular students progress
316
 
    through it.
317
 
    
318
 
    Do not confuse this with a worksheet in the database. This worksheet
319
 
    has extra information for use in the output, such as marks."""
320
 
    def __init__(self, id, name, assessable):
321
 
        self.id = id
322
 
        self.name = name
323
 
        self.assessable = assessable
324
 
        self.complete_class = ''
325
 
        self.optional_message = ''
326
 
        self.total = 0
327
 
        self.mand_done = 0
328
 
    def __repr__(self):
329
 
        return ("Worksheet(id=%s, name=%s, assessable=%s)"
330
 
                % (repr(self.id), repr(self.name), repr(self.assessable)))
331
 
 
332
 
 
333
 
# XXX: This really shouldn't be needed.
334
 
def create_list_of_fake_worksheets_and_stats(store, user, offering):
335
 
    """Take an offering's real worksheets, converting them into stats.
336
 
 
337
 
    The worksheet listing views expect special fake worksheet objects
338
 
    that contain counts of exercises, whether they've been completed,
339
 
    that sort of thing. A fake worksheet object is used to contain
340
 
    these values, because nobody has managed to refactor the need out
341
 
    yet.
342
 
    """
343
 
    new_worksheets = []
344
 
    problems_done = 0
345
 
    problems_total = 0
346
 
 
347
 
    # Offering.worksheets is ordered by the worksheets seq_no
348
 
    for worksheet in offering.worksheets:
349
 
        new_worksheet = FakeWorksheetForMarks(
350
 
            worksheet.identifier, worksheet.name, worksheet.assessable)
351
 
        if new_worksheet.assessable:
352
 
            # Calculate the user's score for this worksheet
353
 
            mand_done, mand_total, opt_done, opt_total = (
354
 
                ivle.worksheet.utils.calculate_score(store, user, worksheet))
355
 
            if opt_total > 0:
356
 
                optional_message = " (excluding optional exercises)"
357
 
            else:
358
 
                optional_message = ""
359
 
            if mand_done >= mand_total:
360
 
                new_worksheet.complete_class = "complete"
361
 
            elif mand_done > 0:
362
 
                new_worksheet.complete_class = "semicomplete"
363
 
            else:
364
 
                new_worksheet.complete_class = "incomplete"
365
 
            problems_done += mand_done
366
 
            problems_total += mand_total
367
 
            new_worksheet.mand_done = mand_done
368
 
            new_worksheet.total = mand_total
369
 
            new_worksheet.optional_message = optional_message
370
 
        new_worksheets.append(new_worksheet)
371
 
 
372
 
    return new_worksheets, problems_total, problems_done