Exemple #1
0
def student_index(request):
    ## logger.debug("student_index(%s)" % request)
    logger.debug("student_index(%s)" % request)
    sp, res = getSpByRequest(request, 'login')
    if not sp and res:
        return res
    teacher = sp.teacher
    logger.debug("sp=%s; teacher=%s" % (sp, teacher))
    curtime = datetime.now()
    warningtime = curtime + timedelta(days=1)
    ## HACK: widen delta by 1 month
    curtime = datetime.now() - timedelta(days=30)
    warningtime = datetime.now() + timedelta(days=30)
    try:
        #        assignments = Assignment.objects.filter(students=sp,
        #                                                deadline__lt=warningtime,
        #                                                deadline__gt=curtime)
        #        logger.debug("assignments=%s; deadline__gt=%s deadline__lt=%s" % (assignments, curtime, warningtime))
        ## HACK: ignore the deadline
        assignments = Assignment.objects.filter(students=sp)
        logger.debug("assignments=%s" % assignments)
    except:
        pass
    else:
        deadlinewarning = "".join(
            str for str in _getdeadlinewarning(sp, assignments))
        if deadlinewarning:
            warninghead = "<h6 class='assignment-dueto-dialog'>Teacher %s:</h6> " % teacher.user.username
            msg = warninghead + deadlinewarning
            messages.add_message(request, messages.SUCCESS, msg)
    return render_to_response('student_index.html',
                              context_instance=RequestContext(request))
Exemple #2
0
def student_papersummarize(request):
    student, res = getSpByRequest(request, 'login')
    if not student and res:
        return res
    paperid = request.GET.get('paperid')
    passed = request.GET.get('passed')
    try:
        paper = Paper.objects.get(id=paperid)
        questionseq = pickle.loads(str(paper.questionseq))
    except:
        return HttpResponse("paper does not exist")
    if paper and questionseq:
        question_set = Question.objects.filter(id__in=questionseq)
        stuanswer_set = getStuanswers(question_set, student)
        if passed == '0':
            mark = _reinitanswer(stuanswer_set)
            messages.add_message(
                request, messages.INFO,
                "You failed in this paper, please don\'t be panic, you can take it again"
            )
        else:
            mark = sum(ans.mark for ans in stuanswer_set)
    else:
        mark = 0
    return render_to_response('student_assignmentsummarize.html', {
        'paper': paper,
        'mark': mark
    },
                              context_instance=RequestContext(request))
Exemple #3
0
def student_getanswerrecords(request):
    student, res = getSpByRequest(request, 'login')
    if not student and res:
        return res
    assignments = student.assignment_set.all()
    paperlist = []
    for assignment in assignments:
        papers = Paper.objects.filter(assignment=assignment)
        for paper in papers:
            question_set = paper.question_set.all()
            papermark = 0
            for question in question_set:
                try:
                    stuanswer = StudentAnswer.objects.filter(
                        question=question, student=student).latest('timestamp')
                except:
                    logger.debug("stuanswer not found")
                    break
                logger.debug(stuanswer)
                papermark = papermark + stuanswer.mark
            paperlist.append([assignment, paper, papermark])
    response = render_to_response('student_allhistoryanswers.json',
                                  {'paperlist': paperlist},
                                  context_instance=RequestContext(request))
    response['Content-Type'] = 'text/plain; charset=utf-8'
    response['Cache-Control'] = 'no-cache'
    return response
Exemple #4
0
def student_getassignedassignments(request):
    # logger.debug("student_getassignedassignments(_)" % repr(request))
    ## print  >> sys.stderr, ("student_getassignedassignments(%s)" % request) # stderr HACK

    try:
        student, res = getSpByRequest(request, None)
        teacher = student.teacher
    except:
        student, res = None, None
    else:
        curtime = datetime.now()
        #        assignments = teacher.assignment_set.filter(deadline__gt=curtime,
        #                                                    students=student)
        ## HACK: no date filter
        assignments = teacher.assignment_set.filter(students=student)
        logger.debug("Assignments = %s" % assignments)
        ## HACK: use stderr
        ## print  >> sys.stderr, ("Assignments = %s" % assignments)
        assignment_list = _getassignmentjson(assignments, teacher, student)
        response = render_to_response('student_allassignedassignments.json',
                                      {'assignment_list': assignment_list},
                                      context_instance=RequestContext(request))
    response['Content-Type'] = 'text/plain; charset=utf-8'
    response['Cache-Control'] = 'no-cache'
    return response
Exemple #5
0
def student_getcustompapers(request):
    student, res = getSpByRequest(request, None)
    papers = Paper.objects.filter(owner=student.user, ptype='Review')
    response = render_to_response('student_allcustompapers.json',
                                  {'paperlist': papers},
                                  context_instance=RequestContext(request))
    response['Content-Type'] = 'text/plain; charset=utf-8'
    response['Cache-Control'] = 'no-cache'
    return response
Exemple #6
0
def paper_getquestions(request):
    try:
        if request.method == "POST":
            ztreejson = []
            qnum = 0
            paperid = request.POST['paperid']
            try:
                view = request.POST['view']
            except:
                view = 0
            print view,"view"
            teacher, res = getTpByRequest(request, None)
            student = None
            if not teacher:
                student, res = getSpByRequest(request, None)
                teacher = student.teacher
            logger.info("paper_getquestions,paperid:%s,teacher:%s" % (paperid, teacher))
            def inital_ztree():
                print 1111111111111111111
                #itempools = Itempool.objects.filter(teacher=teacher)
                itempools = Itempool.objects.filter(accessible=teacher)
                ztreejson = __builduncheckeditempooltree(itempools, view, student)
                return ztreejson
            print paperid
            if paperid and paperid != '-1':
                try:
                    paper = Paper.objects.get(id=int(paperid))
                    print 'paper.questionseq = ', paper.questionseq
                    questionseq = pickle.loads(str(paper.questionseq))
                except:
                    paper = None
                    questionseq = []
                print 'paper @@= ', paper
                print 'questionseq @@@= ', questionseq
                if paper and questionseq:
                    ztreejson, qnum, checkeditempools = __buildcheckeditempooltree(questionseq, view, student)
                    try:
                        #totalitempool = Itempool.objects.filter(teacher=teacher)
                        totalitempool = Itempool.objects.filter(accessible=teacher)
                        itempools = list(set(totalitempool) - set(checkeditempools))
                    except:
                        itempools = []
                    else:
                        ztreejson += __builduncheckeditempooltree(itempools, view, student)
                else:
                    ztreejson = inital_ztree()
            else:
                ztreejson = inital_ztree()
            response = render_to_response('paper_allquestions.json',
                                          {'questiontree': ztreejson,
                                           'inum': len(ztreejson), 'qnum': qnum},
                                          context_instance=RequestContext(request))
            response['Content-Type'] = 'text/plain; charset=utf-8'
            response['Cache-Control'] = 'no-cache'
            return response
    except:
        traceback.print_exc()
Exemple #7
0
def student_submitpaper(request):
    student, res = getSpByRequest(request, None)
    response_data = {'state': 'failure'}
    try:
        paperid = request.POST.get('paperid')
        p = Paper.objects.get(id=int(paperid))
        questionseq = pickle.loads(str(p.questionseq))
    except Exception, e:
        logger.error(e)
        return HttpResponse('paper not found')
Exemple #8
0
def student_takeassignment(request):
    print "this is assignment"
    student, res = getSpByRequest(request, None)
    paperid = request.GET.get("paperid")
    retake = request.GET.get("retake")

    print retake, "retake"
    try:
        paper = Paper.objects.get(id=paperid)
        questionseq = pickle.loads(str(paper.questionseq))
    except:
        paper = None
        questionseq = []
    if paper and questionseq:
        try:
            assignment = paper.assignment
        except:
            assignment = None
        try:
            question_set = Question.objects.filter(id__in=questionseq)
            stuanswer_set = getStuanswers(question_set, student)
            qnameseq = list(
                Question.objects.get(id=qid).qname for qid in questionseq)
        except Exception, e:
            logger.error(e)
            stuanswer_set = []
            qnameseq = []
        #custom paper student can retake
        if retake:
            _reinitanswer(stuanswer_set)
            stuanswer_set = []
        if stuanswer_set:
            teacher_assignment_retake = retake_option(stuanswer_set)
            anscount = sum(1 for stuanswer in stuanswer_set if stuanswer.taked)
            if not teacher_assignment_retake and anscount == paper.total and paper.ptype != 'Review':
                return redirect('student_index')
            else:
                logger.debug(stuanswer_set)
                duration = stuanswer_set[0].timeleft
                logger.debug(duration)
                if duration != -1:
                    __getInstallTimer(request, duration)
                else:
                    duration = __initstuanswer(paper, question_set, student)
                    __getInstallTimer(request, duration)
        else:
            duration = __initstuanswer(paper, question_set, student)
            __getInstallTimer(request, duration)
        if assignment:
            ## HACK: disable the deadline check
            #            if assignment.deadline < datetime.now() + timedelta(seconds=duration):
            #                return HttpResponse("Test time %s is due, you haven\'t enough time: %s"
            #                                    % (assignment.deadline, timedelta(seconds=duration)))
            pass
Exemple #9
0
def assignment_getall(request):
    teacher, res = getTpByRequest(request, None)
    if not teacher:
        student, res = getSpByRequest(request, None)
        teacher = student.teacher
    logger.info("assignment getall:%s" % teacher)
    try:
        assignments = Assignment.objects.filter(teacher=teacher)
    except Exception, e:
        logger.error(e)
        assignments = []
Exemple #10
0
def student_custompaper(request):
    student, res = getSpByRequest(request, 'login')
    #add custompaper
    if request.method == "POST":
        form = CustomPaperForm(request.POST, owner=request.user)
        if form.is_valid():
            paperid = int(form.cleaned_data['paperid'])
            papername = form.cleaned_data['papername']
            duration = form.cleaned_data['duration']
            if paperid != -1:
                paper = Paper.objects.get(id=paperid)
                paper.papername = papername
                paper.ptype = 'Review'
                paper.owner = student.user
                paper.duration = duration
                paper.passpoint = 0
            else:
                paper = Paper.objects.create(papername=papername,
                                             duration=duration,
                                             passpoint=0,
                                             ptype="Review",
                                             owner=request.user)
            questionlist = form.cleaned_data['questionlist']
            paper.questionseq = pickle.dumps([q.id for q in questionlist])
            paper.total = len(questionlist)
            logger.debug("questionlist:%s" % questionlist)
            __updatequestioninpaper(questionlist, paper)
            paper.save()
            return redirect("/student/takeassignment?paperid=" + str(paper.id))
    else:
        #show add custompaper view
        paperid = request.GET.get('paperid')
        if paperid:
            try:
                p = Paper.objects.get(id=paperid)
            except:
                logger.debug("paper not found:%s" % paperid)
                pass
            logger.debug("paper:%s" % p)
            logger.debug(type(request.user))
            form = CustomPaperForm(initial={
                'paperid': p.id,
                'papername': p.papername,
                'duration': p.duration
            },
                                   owner=request.user)
        else:
            form = CustomPaperForm(owner=request.user)
    return render_to_response('student_custompaper.html', {'form': form},
                              context_instance=RequestContext(request))
Exemple #11
0
def paper_getall(request):
    logger.debug("paper_getall(_): method=%s" % request.method)
    if request.method == 'POST':
        logger.debug("request.POST: %s" % request.POST)
        pids = request.POST.get('pids')
        student, res = getSpByRequest(request, None)
        takedpaperlist = list()
        if pids and not student:
            takedpaperlist = __teachermarkreport(pids)
        elif student:
            takedpaperlist = __studentmarkreport(student)
        logger.info("takedpaperlist: %s" % takedpaperlist)
        response = render_to_response('paper_mark.json', {'takedpaperlist': takedpaperlist},
                                      context_instance=RequestContext(request))
    else:
        logger.debug("request.GET: %s" % request.GET)
        forwhat = request.GET.get('forwhat')
        report_type = request.GET.get('report_type')
        if forwhat == 'teacher_report':
            """
               teacher_report default datatable
            """
            try:
                papers = Paper.objects.filter(owner=request.user)
            except:
                papers = []

            if not report_type == "closeness_report":
                response = render_to_response('paper_report.json',
                                              {'papers': papers},
                                              context_instance=RequestContext(request))
            else:
                response = render_to_response('paper_report_closeness.json',
                                              {'papers': papers},
                                              context_instance=RequestContext(request))

        else:
            """
                teacher get all paper ztree
            """
            try:
                papers = Paper.objects.filter(owner=request.user)
            except:
                papers = []
            response = render_to_response('paper_all.json', {'papers': papers},
                                          context_instance=RequestContext(request))
    response['Content-Type'] = 'text/plain; charset=utf-8'
    response['Cache-Control'] = 'no-cache'
    logger.debug("response=%s" % response)
    return response
Exemple #12
0
def student_getassignedassignments(request):
    try:
        student, res = getSpByRequest(request, None)
        teacher = student.teacher
    except:
        student, res = None, None
    else:
        curtime = datetime.now()
        assignments = teacher.assignment_set.filter(deadline__gt=curtime,
                                                    students=student)
        assignment_list = _getassignmentjson(assignments, teacher, student)
        response = render_to_response('student_allassignedassignments.json',
                                      {'assignment_list': assignment_list},
                                      context_instance=RequestContext(request))
    response['Content-Type'] = 'text/plain; charset=utf-8'
    response['Cache-Control'] = 'no-cache'
    return response
Exemple #13
0
def student_answersave(request):
    response_data = {'state': 'failure'}
    try:
        student, res = getSpByRequest(request, 'login')
        if not student and res:
            return res
        qid = request.POST.get('questionid')
        answer_html = request.POST.get('answer_html')
        question = Question.objects.get(id=qid)
        stuanswer = StudentAnswer.objects.filter(
            question=question, student=student).latest('timestamp')

        if stuanswer != None:
            stuanswer.html_answer = answer_html
            stuanswer.save()
            response_data = {'state': 'successful'}
    except Exception, e:
        logger.debug('Error in Answer Save: %s' % e)
Exemple #14
0
def report_question(request):
    questionid = request.GET.get('questionid')
    student, res = getSpByRequest(request, None)
    logger.info(student)
    try:
        question = Question.objects.get(id=questionid)
        studentanswer = StudentAnswer.objects.get(student=student,
                                                  question=question)
        mark = studentanswer.mark
    except:
        return HttpResponse('cant find the specified answer')
    p = re.compile('\'(.*?)\'')
    pointmarklist = []
    try:
        pointmarklist = p.findall(studentanswer.pointmarklist)
    except:
        logger.info("can\'t find pointmark for studentanswer %s" %
                    question.qname)
    pointlist = []
    if pointmarklist:
        for point in pointmarklist:
            pl = 'P' + point
            pointlist.append(pl)
    #p = re.compile('\[\'(.*?)\'')
    omittedpoint = []
    try:
        omittedpoint = p.findall(studentanswer.omitted)
    except:
        logger.info("can\'t find omittedpoint for studentanswer %s" %
                    question.qname)
    omittedlist = []
    if omittedpoint:
        for o in omittedpoint:
            ol = 'P' + o
            omittedlist.append(ol)
    return render_to_response('report_question.html', {
        'qid': question.id,
        'mark': mark,
        'pointmarklist': pointlist,
        'omittedlist': omittedlist
    },
                              context_instance=RequestContext(request))
Exemple #15
0
def student_index(request):
    sp, res = getSpByRequest(request, 'login')
    if not sp and res:
        return res
    teacher = sp.teacher
    curtime = datetime.now()
    warningtime = curtime + timedelta(days=1)
    try:
        assignments = Assignment.objects.filter(students=sp,
                                                deadline__lt=warningtime,
                                                deadline__gt=curtime)
    except:
        pass
    else:
        deadlinewarning = "".join(
            str for str in _getdeadlinewarning(sp, assignments))
        if deadlinewarning:
            warninghead = "<h6 class='assignment-dueto-dialog'>Teacher %s:</h6> " % teacher.user.username
            msg = warninghead + deadlinewarning
            messages.add_message(request, messages.SUCCESS, msg)
    return render_to_response('student_index.html',
                              context_instance=RequestContext(request))
Exemple #16
0
def student_checktime(request):
    student, res = getSpByRequest(request, None)
    startkey = "%s_%s" % (settings.EXAM_TIMEOUT_PREFIX, "start")
    totalkey = "%s_%s" % (settings.EXAM_TIMEOUT_PREFIX, "total")
    starttime = request.session[startkey]
    totaltime = request.session[totalkey]
    curtime = datetime.now()
    paperid = request.POST.get('paperid')
    saverequest = request.POST.get('save')
    if saverequest:
        try:
            p = Paper.objects.get(id=paperid)
            question_set = Question.objects.filter(
                paper=p, infocompleted=Question.ALLCOMPLETED)
            stuanswer_set = getStuanswers(question_set, student)
            logger.debug("stuanswer len: %s" % len(stuanswer_set))
            for stuanswer in stuanswer_set:
                timeleft = stuanswer.timeleft
                stuanswer.timeleft = timeleft - (curtime - starttime).seconds
                stuanswer.save()
        except Exception, e:
            logger.error("%s:can\'t save timeleft" % e)
        response_data = {'timeout': 'false'}
Exemple #17
0
def assignment_add(request):
    teacher, res = getTpByRequest(request, None)
    if request.method == "POST":
        form = AssignmentDetailForm(request.POST, teacher=teacher)
        if form.is_valid():
            if not teacher:
                student, res = getSpByRequest(request, None)
                teacher = student.teacher
            logger.info("assignment add:%s" % teacher)
            assignmentid = int(form.cleaned_data['assignmentid'])
            if assignmentid != -1:
                assignment = Assignment.objects.get(id=assignmentid)
                assignment.teacher = teacher
            else:
                assignment = Assignment.objects.create(
                    assignmentname=form.cleaned_data['assignmentname'],
                    teacher=teacher)

            logger.info("assignment:%s" % assignment)
            assignment.date_created = form.cleaned_data['testdate']
            assignment.deadline = form.cleaned_data['deadline']
            assignment.description = form.cleaned_data['description']
            studentlist = form.cleaned_data['students']
            __updatestuinassignment(assignment, studentlist)
            paperlist = form.cleaned_data['papers']
            __updatepaperinassignment(assignment, paperlist)
            assignment.save()
            messages.add_message(request, messages.SUCCESS,
                                 "One Assignment Added")
            return redirect("/assignment/add?assignmentid=" +
                            str(assignment.id))
        else:
            logger.info("form invalid")
            messages.add_message(request, messages.SUCCESS,
                                 "You missed some values")
    else:
        assignmentid = request.GET.get('assignmentid')
        form = AssignmentDetailForm(teacher=teacher)
        if assignmentid:
            try:
                assignment = Assignment.objects.get(id=assignmentid)
            except:
                form = AssignmentDetailForm(teacher=teacher)
                logger.info("assignment not found:%s" % assignmentid)
            else:
                logger.info("paper:%s" % Assignment)
                papers = Paper.objects.filter(assignment=assignment)
                form = AssignmentDetailForm(teacher=teacher,
                                            initial={
                                                'assignmentid':
                                                assignment.id,
                                                'papername':
                                                assignment.assignmentname,
                                                'testdate':
                                                assignment.date_created,
                                                'deadline':
                                                assignment.deadline,
                                                'description':
                                                assignment.description.replace(
                                                    '</br>', '\n'),
                                                'papers':
                                                papers
                                            })
    return render_to_response('assignment_detail.html', {'form': form},
                              context_instance=RequestContext(request))
Exemple #18
0
def student_submitanswer(request):
    logger.debug("in student_submitanswer()")
    print("in student_submitanswer()")

    alternative = False
    alternative_accepted = False
    response_data = {'state': 'failure'}
    proceed_further = False
    student, res = getSpByRequest(request, 'login')
    proceed_further = False
    if not student and res:
        return res
    try:
        qid = request.POST.get('questionid')
        question = Question.objects.get(id=qid)
        stdanswer = question.stdanswer

        # get the alternative standard answer for the answer
        if question.alt_stdanswer:
            alt_stdanswer = question.alt_stdanswer
            alternative = True
        else:
            alt_stdanswer = None
    except (Exception) as e:
        print e
        logger.error("question %s not exists" % qid)
        print("question %s does not exists" % qid)
        return HttpResponse(simplejson.dumps(response_data),
                            mimetype="application/json")

    try:
        answer_html = request.POST.get('answer_html')
        logger.info('this is the answer: %s ' % answer_html)
        try:
            answer_html = answer_html.decode("utf8").encode('ascii', 'ignore')
        except:
            try:
                answer_html = answer_html.encode('ascii', 'ignore')
            except:
                pass
        anstext = stripHTMLStrings(strip_tags(answer_html))
        try:
            anstext = anstext.decode("utf8").encode('ascii', 'ignore')
        except:
            try:
                anstext = anstext.encode('ascii', 'ignore')
            except:
                import traceback
                traceback.print_exc()
        stuanswer = StudentAnswer.objects.filter(
            question=question, student=student).latest('timestamp')
        stuanswer.html_answer = answer_html
        stuanswer.save()
        print "----------------------------------------------------------------------"
        print anstext

        # stuanswer.html_answer = answer_html
        # stuanswer.txt_answer = anstext
        # stuanswer.save()
        print "answer saveddddddddddddddddddd      done"
    except Exception as e:
        import traceback
        print 111111111111111111111111111111, traceback.format_exc()
        traceback.format_exc()
        logger.error("cant find stuanswer for question %s" % question)
        logger.error(str(traceback.format_exc()))
        return HttpResponse(simplejson.dumps(response_data),
                            mimetype="application/json")

    try:
        thumbnail_ids = [
            int(i) for i in request.POST['stuthumbnail_ids'].split(',') if i
        ]
        print 'thumbnail_ids@@@@@@@@@ = ', thumbnail_ids
    except:
        import traceback
        traceback.format_exc()
        thumbnail_ids = []
        logger.debug("no img for question %s" % question)
        pass
        #stdanswer algorithm to mark stuanswer
    if not stdanswer or not stuanswer:
        return HttpResponse(simplejson.dumps(response_data),
                            mimetype="application/json")
    else:
        textfdist = _loadlist(stdanswer.textfdist)
        slist = _loadlist(stdanswer.sentencelist)
        pointlist = _loadlist(stdanswer.pointlist)
        rulelist = _loadlist(stdanswer.rulelist)

        print textfdist
        print slist
        print pointlist
        print rulelist

        # for alternate answers
        if alternative and alt_stdanswer:
            alt_textfdist = _loadlist(alt_stdanswer.textfdist)
            alt_slist = _loadlist(alt_stdanswer.sentencelist)
            alt_pointlist = _loadlist(alt_stdanswer.pointlist)
            alt_rulelist = _loadlist(alt_stdanswer.rulelist)
        else:
            alt_textfdist = None
            alt_slist = None
            alt_pointlist = None
            alt_rulelist = None

        print alt_textfdist
        print alt_slist
        print alt_pointlist
        print alt_rulelist
    # TODO: add better handling so that progress bar doesn't get stuck when algorithm code has an exception
    try:
        ans = Answer()
        # initialize for alternative answer
        if alternative:
            alt_ans = Answer()
        else:
            alt_ans = None

        if USE_STUDENT_TEXT_DIST:
            ans_textfdist = get_text_distribution(anstext)
            if ans_textfdist:
                textfdist = ans_textfdist
                # save the same to alt_textfdist
                if alternative:
                    alt_textfdist = ans_textfdist
                else:
                    alt_textfdist = None
            if not textfdist:
                textfdist = nltk.FreqDist(['test'])
            # for alternate answer
            if not alt_textfdist:
                alt_textfdist = nltk.FreqDist(['test'])
        print ans.Analysis(anstext, textfdist, slist, pointlist, rulelist)
        mark, marklist, omitted, closeness_stats = ans.Analysis(
            anstext, textfdist, slist, pointlist, rulelist)
        if alternative:
            # calculate the same with alternate standard answer
            alt_mark, alt_marklist, alt_omitted, alt_closeness_stats = alt_ans.Analysis(
                anstext, alt_textfdist, alt_slist, alt_pointlist, alt_rulelist)
        else:
            alt_mark = alt_marklist = alt_omitted = alt_closeness_stats = None

        try:
            stucanvaslist = Canvas.objects.filter(question=question,
                                                  stuanswer=stuanswer)
            canvasmark = sum(stucanvas.mark for stucanvas in stucanvaslist)
            print 'canvasmark = ', canvasmark
        except Exception, e:
            import traceback
            traceback.format_exc()
            logger.error(e)
            canvasmark = 0
        # save mark result

        print '\n##############################################' * 2
        print 'thumbnail_ids = ', thumbnail_ids
        imgmark, stuansimages = __getimgmark(thumbnail_ids, question)
        print 'imgmark = ', imgmark
        # print 'stuansimages = ', stuansimages
        print '\n##############################################' * 2

        if not mark or not marklist:
            mark = 0
            marklist = list()
        if not omitted:
            omitted = list()

        if not alt_mark or not alt_marklist:
            alt_mark = 0
            alt_marklist = list()
        if not alt_omitted:
            alt_omitted = list()

        # Include optional listing with results from external grammar checker and optional closeness summarization
        grammar_issues = ans.critique_results[
            'report'] if ans.critique_results else ""
        closeness = ans.closeness if ans.closeness else 0.0

        # Alernative answer
        if alternative:
            alt_grammar_issues = alt_ans.critique_results[
                'report'] if alt_ans.critique_results else ""
            alt_closeness = alt_ans.closeness if alt_ans.closeness else 0.0

        # Apply min closeness band threshold for mark
        if (question.min_closeness_band > 0):
            band = int(closeness * NUM_CLOSENESS_BANDS - 0.001)
            if (band < question.min_closeness_band):
                logger.info(
                    "Zeroing mark (%s) as closeness band (%s) less then min (%s)"
                    % (mark, band, question.min_closeness_band))
                mark = 0

            if not mark and alternative:
                print "inside alternative marking analysis"
                band = int(alt_closeness * NUM_CLOSENESS_BANDS - 0.001)
                if (band < question.min_closeness_band):
                    alt_mark = 0

        if (stuanswer.mark <= mark + imgmark + canvasmark) or (stuanswer.mark
                                                               <= alt_mark):
            proceed_further = True
            stuanswer.html_answer = answer_html
            stuanswer.txt_answer = anstext
            stuanswer.save()

        print 'mark = ', mark, '\n'
        print 'marklist = ', marklist, '\n'
        print 'omitted = ', omitted, '\n'
        print 'closeness_stats = ', closeness_stats, '\n'

        print 'alt_mark = ', alt_mark, '\n'
        print 'alt_marklist = ', alt_marklist, '\n'
        print 'alt_omitted = ', alt_omitted, '\n'
        print 'alt_closeness_stats = ', alt_closeness_stats, '\n'
Exemple #19
0
def student_submitanswer(request):
    response_data = {'state': 'failure'}
    student, res = getSpByRequest(request, 'login')
    if not student and res:
        return res
    try:
        qid = request.POST.get('questionid')
        question = Question.objects.get(id=qid)
        stdanswer = question.stdanswer
    except:
        logger.error("question %s not exists" % qid)
        return HttpResponse(simplejson.dumps(response_data),
                            mimetype="application/json")

    try:
        answer_html = request.POST.get('answer_html')
        anstext = stripHTMLStrings(strip_tags(answer_html))
        try:
            answer_html = answer_html.decode("utf8").encode('ascii', 'ignore')
        except:
            try:
                answer_html = answer_html.encode('ascii', 'ignore')
            except:
                pass
        anstext = stripHTMLStrings(strip_tags(answer_html))
        try:
            anstext = anstext.decode("utf8").encode('ascii', 'ignore')
        except:
            try:
                anstext = anstext.encode('ascii', 'ignore')
            except:
                import traceback
                traceback.print_exc()

        stuanswer = StudentAnswer.objects.filter(
            question=question, student=student).latest('timestamp')
        stuanswer.html_answer = answer_html
        stuanswer.txt_answer = anstext
        stuanswer.save()
    except:
        logger.error("cant find stuanswer for question %s" % question)
        return HttpResponse(simplejson.dumps(response_data),
                            mimetype="application/json")

    try:
        thumbnail_ids = list(
            int(i) for i in request.POST['stuthumbnail_ids'].split(','))
    except:
        thumbnail_ids = []
        logger.debug("no img for question %s" % question)
        #stdanswer algorithm to mark stuanswer
    if not stdanswer or not stuanswer:
        return HttpResponse(simplejson.dumps(response_data),
                            mimetype="application/json")
    else:
        textfdist = _loadlist(stdanswer.textfdist)
        slist = _loadlist(stdanswer.sentencelist)
        pointlist = _loadlist(stdanswer.pointlist)
        rulelist = _loadlist(stdanswer.rulelist)

    try:
        ans = Answer()
        mark, marklist, omitted = ans.Analysis(anstext, textfdist, slist,
                                               pointlist, rulelist)
    except Exception, e:
        marklist = []
        omitted = []
        logger.error(e)