示例#1
0
def teacheradmin_stats_kqs(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    if not 'unit' in request.GET:
        return HttpResponse(status=400)
    unit = get_object_or_404(Unit, id=request.GET['unit'])
    if not unit in course.unit_set.all():
        return HttpResponse(status=400)
    data = []
    activity = get_db().get_collection('activity')
    answers = get_db().get_collection('answers')

    kq_list = unit.knowledgequantum_set.all()
    for kq in kq_list:
        kq_data = {
            'id': kq.id,
            'title': kq.title,
            'viewed': 0
        }

        question = None
        if kq.question_set.count() > 0:
            question = kq.question_set.all()[0]
            kq_data['answered'] = 0

            if getattr(course, "threshold", None) is not None:
                # if the course doesn't support certification, then don't
                # return the 'passed' stat since it doesn't apply
                kq_data['passed'] = 0
                for student in course.students.all():
                    if calculate_kq_mark(kq, student) >= float(course.threshold):
                        kq_data['passed'] += 1

        for student in course.students.all():
            user_activity_list = activity.find_one({'user': student.id}, safe=True)

            if user_activity_list is not None:
                visited_kqs = user_activity_list.get('courses', {}).get(unicode(course.id), {}).get('kqs', [])
                visited_kqs = [int(vkq) for vkq in visited_kqs]

                if kq.id in visited_kqs:
                    kq_data['viewed'] += 1

            if question is not None:
                user_answer_list = answers.find_one({'user': student.id}, safe=True)
                if user_answer_list is not None:
                    answer = user_answer_list.get('questions', {}).get(unicode(question.id))
                    if answer:
                        kq_data['answered'] += 1

        data.append(kq_data)

    return HttpResponse(simplejson.dumps(data),
                        mimetype='application/json')
示例#2
0
def teacheradmin_stats_kqs(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    if not 'unit' in request.GET:
        return HttpResponse(status=400)
    unit = get_object_or_404(Unit, id=request.GET['unit'])
    if not unit in course.unit_set.all():
        return HttpResponse(status=400)
    data = []
    activity = get_db().get_collection('activity')
    answers = get_db().get_collection('answers')

    kq_list = unit.knowledgequantum_set.all()
    for kq in kq_list:
        kq_data = {'id': kq.id, 'title': kq.title, 'viewed': 0}

        question = None
        if kq.question_set.count() > 0:
            question = kq.question_set.all()[0]
            kq_data['answered'] = 0

            if getattr(course, "threshold", None) is not None:
                # if the course doesn't support certification, then don't
                # return the 'passed' stat since it doesn't apply
                kq_data['passed'] = 0
                for student in course.students.all():
                    if calculate_kq_mark(kq, student) >= float(
                            course.threshold):
                        kq_data['passed'] += 1

        for student in course.students.all():
            user_activity_list = activity.find_one({'user': student.id},
                                                   safe=True)

            if user_activity_list is not None:
                visited_kqs = user_activity_list.get('courses', {}).get(
                    unicode(course.id), {}).get('kqs', [])
                visited_kqs = [int(vkq) for vkq in visited_kqs]

                if kq.id in visited_kqs:
                    kq_data['viewed'] += 1

            if question is not None:
                user_answer_list = answers.find_one({'user': student.id},
                                                    safe=True)
                if user_answer_list is not None:
                    answer = user_answer_list.get('questions',
                                                  {}).get(unicode(question.id))
                    if answer:
                        kq_data['answered'] += 1

        data.append(kq_data)

    return HttpResponse(simplejson.dumps(data), mimetype='application/json')
示例#3
0
 def dispatch(self, request_type, request, **kwargs):
     db = get_db()
     self.user_answers = get_user(request, db.get_collection('answers'))
     self.user_activity = get_user(request, db.get_collection('activity'))
     return super(KnowledgeQuantumResource, self).dispatch(request_type,
                                                           request,
                                                           **kwargs)
示例#4
0
 def dispatch(self, request_type, request, **kwargs):
     db = get_db()
     self.user_answers = get_user(request, db.get_collection('answers'))
     self.user_activity = get_user(request, db.get_collection('activity'))
     return super(KnowledgeQuantumResource, self).dispatch(request_type,
                                                           request,
                                                           **kwargs)
示例#5
0
def course_reviews(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)

    is_enrolled = course.students.filter(id=request.user.id).exists()
    if not is_enrolled:
        return HttpResponseForbidden(_('You are not enrolled in this course'))

    assignments = course_get_visible_peer_review_assignments(request.user,
                                                             course)

    collection = get_db().get_collection('peer_review_submissions')
    submissions = collection.find({
        'author': request.user.id,
        'course': course.id,
    }, {'kq': True, '_id': False})
    submissions = [s['kq'] for s in submissions]

    user_submissions = [a.id for a in assignments if a.kq.id in submissions]

    return render_to_response('peerreview/reviews.html', {
        'course': course,
        'assignments': assignments,
        'user_submissions': user_submissions,
        'is_enrolled': is_enrolled,
    }, context_instance=RequestContext(request))
示例#6
0
文件: utils.py 项目: minipunk/moocng
def calculate_kq_mark(kq, user):
    # TODO Optimize per student
    from moocng.courses.models import Question
    try:
        db = get_db()
        question = Question.objects.filter(kq=kq)
        if question:
            answers = db.get_collection('answers')
            user_answer_list = answers.find_one({'user': user.id}, safe=True)
            if user_answer_list is not None:
                answer = user_answer_list.get('questions', {}).get(unicode(question[0].id))
                if answer and question[0].is_correct(answer):
                    return (normalize_kq_weight(kq) * 10.0) / 100
                else:
                    if kq.unit.deadline is not None and kq.unit.deadline > datetime.now(kq.unit.deadline.tzinfo):
                        return 0
        else:
            activity = db.get_collection('activity')
            user_activity_list = activity.find_one({'user': user.id}, safe=True)
            if user_activity_list is not None:
                visited_kqs = user_activity_list.get('courses', {}).get(unicode(kq.unit.course.id), {}).get('kqs', [])
                if unicode(kq.id) in visited_kqs:
                    return (normalize_kq_weight(kq) * 10.0) / 100
                else:
                    if kq.unit.deadline is not None and kq.unit.deadline > datetime.now(kq.unit.deadline.tzinfo):
                        return 0
    except AttributeError:
        pass
    return -1
示例#7
0
def calculate_kq_mark(kq, user):
    from moocng.courses.models import Question
    try:
        db = get_db()
        question = Question.objects.filter(kq=kq)
        if question:
            answers = db.get_collection('answers')
            user_answer_list = answers.find_one({'user': user.id}, safe=True)
            if user_answer_list is not None:
                answer = user_answer_list.get('questions',
                                              {}).get(unicode(question[0].id))
                if answer and question[0].is_correct(answer):
                    return (normalize_kq_weight(kq) * 10.0) / 100
                else:
                    if kq.unit.deadline is not None and kq.unit.deadline > datetime.now(
                            kq.unit.deadline.tzinfo):
                        return 0
        else:
            activity = db.get_collection('activity')
            user_activity_list = activity.find_one({'user': user.id},
                                                   safe=True)
            if user_activity_list is not None:
                visited_kqs = user_activity_list.get('courses', {}).get(
                    unicode(kq.unit.course.id), {}).get('kqs', [])
                if unicode(kq.id) in visited_kqs:
                    return (normalize_kq_weight(kq) * 10.0) / 100
                else:
                    if kq.unit.deadline is not None and kq.unit.deadline > datetime.now(
                            kq.unit.deadline.tzinfo):
                        return 0
    except AttributeError:
        pass
    return -1
示例#8
0
文件: views.py 项目: MCHacker/moocng
def course_reviews(request, course_slug):
    course = get_course_if_user_can_view_or_404(course_slug, request)

    is_enrolled = course.students.filter(id=request.user.id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(reverse('course_overview', args=[course_slug]))

    is_ready, ask_admin = is_course_ready(course)

    if not is_ready:
        return render_to_response('courses/no_content.html', {
            'course': course,
            'is_enrolled': is_enrolled,
            'ask_admin': ask_admin,
        }, context_instance=RequestContext(request))

    assignments = course_get_visible_peer_review_assignments(request.user,
                                                             course)

    collection = get_db().get_collection('peer_review_submissions')
    submissions = collection.find({
        'author': request.user.id,
        'course': course.id,
    }, {'kq': True, '_id': False})
    submissions = [s['kq'] for s in submissions]

    user_submissions = [a.id for a in assignments if a.kq.id in submissions]

    return render_to_response('peerreview/reviews.html', {
        'course': course,
        'assignments': assignments,
        'user_submissions': user_submissions,
        'is_enrolled': is_enrolled,
    }, context_instance=RequestContext(request))
示例#9
0
文件: views.py 项目: minipunk/moocng
def teacheradmin_stats_kqs(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    if not 'unit' in request.GET:
        return HttpResponse(status=400)
    unit = get_object_or_404(Unit, id=request.GET['unit'])
    if not unit in course.unit_set.all():
        return HttpResponse(status=400)
    data = []
    activity = get_db().get_collection('activity')
    answers = get_db().get_collection('answers')

    kq_list = unit.knowledgequantum_set.all()
    for kq in kq_list:
        kq_data = {
            'id': kq.id,
            'title': kq.title,
            'viewed': 0
        }

        question = None
        if kq.question_set.count() > 0:
            question = kq.question_set.all()[0]
            kq_data['answered'] = 0

            # if course.threshold is not None:
            #     # if the course doesn't support certification, then don't
            #     # return the 'passed' stat since it doesn't apply
            #     kq_data['passed'] = 0
            #     for student in course.students.all():
            #         if calculate_kq_mark(kq, student) >= float(course.threshold):
            #             kq_data['passed'] += 1

        kq_data["viewed"] = activity.find({
            "courses.%s.kqs" % course.id: str(kq.id)
        }).count()

        for question in kq.question_set.all():
            kq_data["answered"] = answers.find({
                "questions.%s" % question.id: {
                    "$exists": True
                }
            }).count()

        data.append(kq_data)

    return HttpResponse(simplejson.dumps(data),
                        mimetype='application/json')
示例#10
0
def course_review_assign(request, course_slug, assignment_id):
    course = get_course_if_user_can_view_or_404(course_slug, request)
    assignment = get_object_or_404(PeerReviewAssignment, id=assignment_id)
    user_id = request.user.id

    is_enrolled = course.students.filter(id=user_id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(reverse('course_overview', args=[course_slug]))

    if assignment.kq.unit.course != course:
        messages.error(request, _('The selected peer review assignment is not part of this course.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

    collection = get_db().get_collection('peer_review_submissions')

    submission = collection.find({
        'kq': assignment.kq.id,
        'assigned_to': user_id
    })
    if submission.count() > 0:
        messages.error(request, _('You already have a submission assigned.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

    max_hours_assigned = timedelta(hours=getattr(settings,
                                   "PEER_REVIEW_ASSIGNATION_EXPIRE", 24))

    assignation_expire = datetime.utcnow() - max_hours_assigned

    #Check number of course langs to assign a PeerReview
    is_user_lang_valid = False
    if course.languages.count() > 1:
        for lang in course.languages.all():
            if request.user.get_profile().language == lang.abbr:
                is_user_lang_valid = True
        if is_user_lang_valid:
            submission = _get_peer_review_submission(user_id, assignment.kq.id, assignation_expire, request.user.get_profile().language)
        else:
            submission = _get_peer_review_submission(user_id, assignment.kq.id, assignation_expire)
    else:
        submission = _get_peer_review_submission(user_id, assignment.kq.id, assignation_expire)

    if submission.count() == 0:
        # Deactivate while it is finished
        #if course.languages.count() > 1 and is_user_lang_valid:
        #    return HttpResponseRedirect(reverse('course_reviews_ignorelang', args=[course_slug, assignment.kq.id]))
        messages.error(request, _('There is no submission avaliable for you at this moment. Please, try again later.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))
    else:
        collection.update({
            '_id': submission[0]['_id']
        }, {
            '$set': {
                'assigned_to': user_id,
                'assigned_when': datetime.utcnow()
            }
        })
        return HttpResponseRedirect(reverse('course_review_review', args=[course_slug, assignment_id]))
示例#11
0
def _get_peer_review_submission(user_id, kq_id, assignation_expire, lang=None):
    collection = get_db().get_collection('peer_review_submissions')
    if lang:
        submission = collection.find({
            'kq': kq_id,
            '$or': [
                {
                    'assigned_to': {
                        '$exists': False
                    },
                },
                {
                    'assigned_when': {
                        '$lt': assignation_expire
                    },
                }
            ],
            'author': {
                '$ne': user_id
            },
            'language': lang,
            'reviewers': {
                '$ne': user_id
            }
        }).sort([
            ('reviews', pymongo.ASCENDING),
            ('author_reviews', pymongo.DESCENDING),
        ]).limit(1)
    else:
        submission = collection.find({
            'kq': kq_id,
            '$or': [
                {
                    'assigned_to': {
                        '$exists': False
                    },
                },
                {
                    'assigned_when': {
                        '$lt': assignation_expire
                    },
                }
            ],
            'author': {
                '$ne': user_id
            },
            'reviewers': {
                '$ne': user_id
            }
        }).sort([
            ('reviews', pymongo.ASCENDING),
            ('author_reviews', pymongo.DESCENDING),
        ]).limit(1)

    return submission
示例#12
0
def course_review_upload(request, course_slug):
    if request.method == "POST":
        course = get_object_or_404(Course, slug=course_slug)

        file_to_upload = request.FILES.get('pr_file', None)
        submission_text = request.POST.get('pr-submission', '')

        kq = get_object_or_404(KnowledgeQuantum,
                               id=request.POST.get('kq_id', 0))
        unit = kq.unit

        if (file_to_upload.size /
            (1024 * 1024) >= settings.PEER_REVIEW_FILE_MAX_SIZE):
            messages.error(
                request,
                _('Your file is greater than the max allowed size (%d MB).') %
                settings.PEER_REVIEW_FILE_MAX_SIZE)
            return HttpResponseRedirect(
                reverse('course_classroom', args=[course_slug]) +
                "#unit%d/kq%d/p" % (unit.id, kq.id))

        if (len(submission_text) >= settings.PEER_REVIEW_TEXT_MAX_SIZE):
            messages.error(
                request,
                _('Your text is greater than the max allowed size (%d characters).'
                  ) % settings.PEER_REVIEW_TEXT_MAX_SIZE)
            return HttpResponseRedirect(
                reverse('course_classroom', args=[course_slug]) +
                "#unit%d/kq%d/p" % (unit.id, kq.id))

        s3_upload(request.user.id, kq.id, file_to_upload.name, file_to_upload)
        file_url = s3_url(request.user.id, file_to_upload.name, kq.id)

        submission = {
            "author": request.user.id,
            "author_reviews": 0,
            "text": request.POST.get('pr-submission', ''),
            "file": file_url,
            "created": datetime.now(),
            "reviewers": [],
            "reviews": 0,
            "course": course.id,
            "unit": unit.id,
            "kq": kq.id,
            "assigned_to": None,
        }
        db = get_db()
        submissions = db.get_collection("peer_review_submissions")
        submissions.insert(submission)

        return HttpResponseRedirect(
            reverse('course_classroom', args=[course_slug]) +
            "#unit%d/kq%d/p" % (unit.id, kq.id))
示例#13
0
def teacheradmin_stats_units(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    data = []
    use_old_calculus = False
    if course.slug in settings.COURSES_USING_OLD_TRANSCRIPT:
        use_old_calculus = True
    activity = get_db().get_collection('activity')

    unit_list = course.unit_set.all()
    for unit in unit_list:
        unit_data = {
            'id': unit.id,
            'title': unit.title,
            'started': 0,
            'completed': 0
        }

        if getattr(course, "threshold", None) is not None:
            # if the course doesn't support certification, then don't return
            # the 'passed' stat since it doesn't apply
            unit_data['passed'] = 0
            for student in course.students.all():
                if calculate_unit_mark(unit, student,
                                       use_old_calculus)[0] >= float(
                                           course.threshold):
                    unit_data['passed'] += 1

        kqs = [kq.id for kq in unit.knowledgequantum_set.all()]
        for student in course.students.all():
            user_activity_list = activity.find_one({'user': student.id},
                                                   safe=True)

            if user_activity_list is not None:
                visited_kqs = user_activity_list.get('courses', {}).get(
                    unicode(course.id), {}).get('kqs', [])

                started = 0
                completed = 0
                for kq in visited_kqs:
                    if int(kq) in kqs:
                        started = 1
                        completed += 1

                unit_data['started'] += started
                if len(kqs) == completed:
                    unit_data['completed'] += 1

        data.append(unit_data)

    return HttpResponse(simplejson.dumps(data), mimetype='application/json')
示例#14
0
def course_reviews(request, course_slug, kq_id=None, ignore_langs=False):
    course = get_course_if_user_can_view_or_404(course_slug, request)

    is_enrolled = course.students.filter(id=request.user.id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(reverse('course_overview', args=[course_slug]))

    is_ready, ask_admin, is_outdated = is_course_ready(course)
    is_teacher = is_teacher_test(request.user, course)

    if not is_ready and not is_teacher and not request.user.is_staff and not request.user.is_superuser:
        return render_to_response('courses/no_content.html', {
            'course': course,
            'is_enrolled': is_enrolled,
            'ask_admin': ask_admin,
        }, context_instance=RequestContext(request))

    assignments = course_get_visible_peer_review_assignments(request.user,
                                                             course)

    collection = get_db().get_collection('peer_review_submissions')
    submissions = collection.find({
        'author': request.user.id,
        'course': course.id,
    }, {'kq': True, '_id': False})
    submissions = [s['kq'] for s in submissions]

    user_submissions = [a.id for a in assignments if a.kq.id in submissions]
    tasks = get_tasks_available_for_user(course, request.user)
    group = get_group_by_user_and_course(request.user.id, course.id)

    return render_to_response('peerreview/reviews.html', {
        'course': course,
        'assignments': assignments,
        'user_submissions': user_submissions,
        'kq_id': kq_id,
        'ignore_langs': ignore_langs,
        'is_enrolled': is_enrolled,
        'is_ready': is_ready,
        'is_outdated': is_outdated,
        'can_review': date.today() < course.end_date+timedelta(days=14),
        'task_list': tasks[0],
        'tasks_done': tasks[1],
        'progress': get_course_progress_for_user(course, request.user),
        'passed': has_user_passed_course(request.user, course),
        'group': group,
    }, context_instance=RequestContext(request))
示例#15
0
def teacheradmin_stats_units(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    data = []
    use_old_calculus = False
    if course.slug in settings.COURSES_USING_OLD_TRANSCRIPT:
        use_old_calculus = True
    activity = get_db().get_collection('activity')

    unit_list = course.unit_set.all()
    for unit in unit_list:
        unit_data = {
            'id': unit.id,
            'title': unit.title,
            'started': 0,
            'completed': 0
        }

        if getattr(course, "threshold", None) is not None:
            # if the course doesn't support certification, then don't return
            # the 'passed' stat since it doesn't apply
            unit_data['passed'] = 0
            for student in course.students.all():
                if calculate_unit_mark(unit, student, use_old_calculus)[0] >= float(course.threshold):
                    unit_data['passed'] += 1

        kqs = [kq.id for kq in unit.knowledgequantum_set.all()]
        for student in course.students.all():
            user_activity_list = activity.find_one({'user': student.id}, safe=True)

            if user_activity_list is not None:
                visited_kqs = user_activity_list.get('courses', {}).get(unicode(course.id), {}).get('kqs', [])

                started = 0
                completed = 0
                for kq in visited_kqs:
                    if int(kq) in kqs:
                        started = 1
                        completed += 1

                unit_data['started'] += started
                if len(kqs) == completed:
                    unit_data['completed'] += 1

        data.append(unit_data)

    return HttpResponse(simplejson.dumps(data),
                        mimetype='application/json')
示例#16
0
文件: views.py 项目: minipunk/moocng
def teacheradmin_stats_units(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    data = []
    use_old_calculus = False
    if course.slug in settings.COURSES_USING_OLD_TRANSCRIPT:
        use_old_calculus = True
    activity = get_db().get_collection('activity')

    unit_list = course.unit_set.all()
    for unit in unit_list:
        unit_data = {
            'id': unit.id,
            'title': unit.title,
            'started': 0,
            'completed': 0
        }

        # if course.threshold is not None:
        #     # if the course doesn't support certification, then don't return
        #     # the 'passed' stat since it doesn't apply
        #     unit_data['passed'] = 0
        #     for student in course.students.all():
        #         if calculate_unit_mark(unit, student, use_old_calculus)[0] >= float(course.threshold):
        #             unit_data['passed'] += 1

        kqs = [str(kq.id) for kq in unit.knowledgequantum_set.all()]

        unit_data["completed"] = activity.find({
            "courses.%s" % course.id: {"$exists": True},
            "courses.%s.kqs" % course.id: {
                "$all": kqs
            }
        }).count()

        unit_data["started"] = activity.find({
            "courses.%s" % course.id: {"$exists": True},
            "courses.%s.kqs" % course.id: {
                "$in": kqs
            }
        }).count()

        data.append(unit_data)

    return HttpResponse(simplejson.dumps(data),
                        mimetype='application/json')
示例#17
0
文件: views.py 项目: ntwuxc/moocng
def course_reviews(request, course_slug):
    course = get_course_if_user_can_view_or_404(course_slug, request)

    is_enrolled = course.students.filter(id=request.user.id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(
            reverse('course_overview', args=[course_slug]))

    is_ready, ask_admin = is_course_ready(course)

    if not is_ready:
        return render_to_response('courses/no_content.html', {
            'course': course,
            'is_enrolled': is_enrolled,
            'ask_admin': ask_admin,
        },
                                  context_instance=RequestContext(request))

    assignments = course_get_visible_peer_review_assignments(
        request.user, course)

    collection = get_db().get_collection('peer_review_submissions')
    submissions = collection.find(
        {
            'author': request.user.id,
            'course': course.id,
        }, {
            'kq': True,
            '_id': False
        })
    submissions = [s['kq'] for s in submissions]

    user_submissions = [a.id for a in assignments if a.kq.id in submissions]

    return render_to_response('peerreview/reviews.html', {
        'course': course,
        'assignments': assignments,
        'user_submissions': user_submissions,
        'is_enrolled': is_enrolled,
    },
                              context_instance=RequestContext(request))
示例#18
0
def teacheradmin_stats(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    is_enrolled = course.students.filter(id=request.user.id).exists()
    activity = get_db().get_collection('activity')

    data = {
        'enrolled': course.students.count(),
        'started': 0,
        'completed': 0
    }

    if getattr(course, "threshold", None) is not None:
        # if the course doesn't support certification, then don't return the
        # 'passed' stat since it doesn't apply
        data['passed'] = 0
        for student in course.students.all():
            if calculate_course_mark(course, student)[0] >= float(course.threshold):
                data['passed'] += 1

    units = course.unit_set.all()
    kqs = 0
    for unit in units:
        kqs += unit.knowledgequantum_set.count()

    for student in course.students.all():
        user_activity_list = activity.find_one({'user': student.id}, safe=True)

        if user_activity_list is not None:
            visited_kqs = user_activity_list.get('courses', {}).get(unicode(course.id), {}).get('kqs', [])

            if len(visited_kqs) > 0:
                data['started'] += 1
            if len(visited_kqs) == kqs:
                data['completed'] += 1

    return render_to_response('teacheradmin/stats.html', {
        'course': course,
        'is_enrolled': is_enrolled,
        'initial_data': simplejson.dumps(data),
    }, context_instance=RequestContext(request))
示例#19
0
def teacheradmin_stats(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    is_enrolled = course.students.filter(id=request.user.id).exists()
    activity = get_db().get_collection('activity')

    data = {'enrolled': course.students.count(), 'started': 0, 'completed': 0}

    if getattr(course, "threshold", None) is not None:
        # if the course doesn't support certification, then don't return the
        # 'passed' stat since it doesn't apply
        data['passed'] = 0
        for student in course.students.all():
            if calculate_course_mark(course, student)[0] >= float(
                    course.threshold):
                data['passed'] += 1

    units = course.unit_set.all()
    kqs = 0
    for unit in units:
        kqs += unit.knowledgequantum_set.count()

    for student in course.students.all():
        user_activity_list = activity.find_one({'user': student.id}, safe=True)

        if user_activity_list is not None:
            visited_kqs = user_activity_list.get('courses', {}).get(
                unicode(course.id), {}).get('kqs', [])

            if len(visited_kqs) > 0:
                data['started'] += 1
            if len(visited_kqs) == kqs:
                data['completed'] += 1

    return render_to_response('teacheradmin/stats.html', {
        'course': course,
        'is_enrolled': is_enrolled,
        'initial_data': simplejson.dumps(data),
    },
                              context_instance=RequestContext(request))
示例#20
0
def course_review_upload(request, course_slug):
    if request.method == "POST":
        course = get_object_or_404(Course, slug=course_slug)

        file_to_upload = request.FILES.get('pr_file', None)
        submission_text = request.POST.get('pr-submission', '')

        kq = get_object_or_404(KnowledgeQuantum, id=request.POST.get('kq_id', 0))
        unit = kq.unit

        if (file_to_upload.size / (1024 * 1024) >= settings.PEER_REVIEW_FILE_MAX_SIZE):
            messages.error(request, _('Your file is greater than the max allowed size (%d MB).') % settings.PEER_REVIEW_FILE_MAX_SIZE)
            return HttpResponseRedirect(reverse('course_classroom', args=[course_slug])+"#unit%d/kq%d/p" % (unit.id, kq.id))

        if (len(submission_text) >= settings.PEER_REVIEW_TEXT_MAX_SIZE):
            messages.error(request, _('Your text is greater than the max allowed size (%d characters).') % settings.PEER_REVIEW_TEXT_MAX_SIZE)
            return HttpResponseRedirect(reverse('course_classroom', args=[course_slug])+"#unit%d/kq%d/p" % (unit.id, kq.id))

        s3_upload(request.user.id, kq.id, file_to_upload.name, file_to_upload)
        file_url = s3_url(request.user.id, file_to_upload.name, kq.id)

        submission = {
            "author": request.user.id,
            "author_reviews": 0,
            "text": request.POST.get('pr-submission', ''),
            "file": file_url,
            "created": datetime.now(),
            "reviewers": [],
            "reviews": 0,
            "course": course.id,
            "unit": unit.id,
            "kq": kq.id,
            "assigned_to": None,
        }
        db = get_db()
        submissions = db.get_collection("peer_review_submissions")
        submissions.insert(submission)

        return HttpResponseRedirect(reverse('course_classroom', args=[course_slug])+"#unit%d/kq%d/p" % (unit.id, kq.id))
示例#21
0
文件: views.py 项目: minipunk/moocng
def teacheradmin_stats(request, course_slug):
    course = get_object_or_404(Course, slug=course_slug)
    is_enrolled = course.students.filter(id=request.user.id).exists()
    activity = get_db().get_collection('activity')

    data = {
        'enrolled': course.students.count(),
        'started': 0,
        'completed': 0
    }

    # if course.threshold is not None:
    #     # if the course doesn't support certification, then don't return the
    #     # 'passed' stat since it doesn't apply
    #     data['passed'] = 0
    #     for student in course.students.all():
    #         if calculate_course_mark(course, student)[0] >= float(course.threshold):
    #             data['passed'] += 1

    kqs = [str(kq.id)
           for kq in KnowledgeQuantum.objects.filter(unit__course=course)]

    data["completed"] = activity.find({
        "courses.%s" % course.id: {"$exists": True},
        "courses.%s.kqs" % course.id: {"$all": kqs}
    }).count()
    print data["completed"]

    data["started"] = activity.find({
        "courses.%s" % course.id: {
            "$exists": True
        }
    }).count()

    return render_to_response('teacheradmin/stats.html', {
        'course': course,
        'is_enrolled': is_enrolled,
        'initial_data': simplejson.dumps(data),
    }, context_instance=RequestContext(request))
示例#22
0
 def dispatch(self, request_type, request, **kwargs):
     # We need the request to dehydrate some fields
     collection = get_db().get_collection('answers')
     self.user = get_user(request, collection)
     return super(OptionResource, self).dispatch(request_type, request,
                                                 **kwargs)
示例#23
0
文件: views.py 项目: MCHacker/moocng
def course_review_assign(request, course_slug, assignment_id):
    course = get_course_if_user_can_view_or_404(course_slug, request)
    assignment = get_object_or_404(PeerReviewAssignment, id=assignment_id)
    user_id = request.user.id

    is_enrolled = course.students.filter(id=user_id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(reverse('course_overview', args=[course_slug]))

    if assignment.kq.unit.course != course:
        messages.error(request, _('The selected peer review assignment is not part of this course.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

    collection = get_db().get_collection('peer_review_submissions')

    submission = collection.find({
        'kq': assignment.kq.id,
        'assigned_to': user_id
    })
    if submission.count() > 0:
        messages.error(request, _('You already have a submission assigned.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

    max_hours_assigned = timedelta(hours=getattr(settings,
                                   "PEER_REVIEW_ASSIGNATION_EXPIRE", 24))

    assignation_expire = datetime.utcnow() - max_hours_assigned

    submission = collection.find({
        'kq': assignment.kq.id,
        '$or': [
            {
                'assigned_to': {
                    '$exists': False
                },
            },
            {
                'assigned_when': {
                    '$lt': assignation_expire
                },
            }
        ],
        'author': {
            '$ne': user_id
        },
        'reviewers': {
            '$ne': user_id
        }
    }).sort([
        ('reviews', pymongo.ASCENDING),
        ('author_reviews', pymongo.DESCENDING),
    ]).limit(1)

    if submission.count() == 0:
        messages.error(request, _('There is no submission avaliable for you at this moment. Please, try again later.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))
    else:
        collection.update({
            '_id': submission[0]['_id']
        }, {
            '$set': {
                'assigned_to': user_id,
                'assigned_when': datetime.utcnow()
            }
        })
        return HttpResponseRedirect(reverse('course_review_review', args=[course_slug, assignment_id]))
示例#24
0
def course_review_review(request, course_slug, assignment_id):
    course = get_course_if_user_can_view_or_404(course_slug, request)
    assignment = get_object_or_404(PeerReviewAssignment, id=assignment_id)
    user_id = request.user.id

    is_enrolled = course.students.filter(id=user_id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(reverse('course_overview', args=[course_slug]))

    if assignment.kq.unit.course != course:
        messages.error(request, _('The selected peer review assignment is not part of this course.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

    collection = get_db().get_collection('peer_review_submissions')

    submission = collection.find({
        'kq': assignment.kq.id,
        'assigned_to': user_id
    })

    if submission.count() == 0:
        messages.error(request, _('You don\'t have this submission assigned.'))
        return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

    submission_obj = submission[0]

    submitter = User.objects.get(id=int(submission_obj['author']))

    criteria_initial = [{'evaluation_criterion_id': criterion.id} for criterion in assignment.criteria.all()]
    EvalutionCriteriaResponseFormSet = formset_factory(EvalutionCriteriaResponseForm, extra=0, max_num=len(criteria_initial))

    if request.method == "POST":
        submission_form = ReviewSubmissionForm(request.POST)
        criteria_formset = EvalutionCriteriaResponseFormSet(request.POST, initial=criteria_initial)
        if criteria_formset.is_valid() and submission_form.is_valid():
            criteria_values = [(int(form.cleaned_data['evaluation_criterion_id']), int(form.cleaned_data['value'])) for form in criteria_formset]
            try:
                review = save_review(assignment.kq, request.user, submitter, criteria_values, submission_form.cleaned_data['comments'])

                reviews = get_db().get_collection('peer_review_reviews')
                reviewed_count = reviews.find({
                    'reviewer': user_id,
                    'kq': assignment.kq.id
                }).count()

                review_scores = [int(form.cleaned_data['value']) for form in criteria_formset]
                if len(review_scores) > 0:
                    score = float(sum(review_scores) / len(review_scores)) * 2 / 10
                else:
                    score = 1
                extra = {
                    'geolocation': {
                        'lat': float(request.POST.get("context_geo_lat", "0.0")),
                        'lon': float(request.POST.get("context_geo_lon", "0.0")),
                    },
                    'url': request.build_absolute_uri(),
                    'result': {
                        'score': score,
                        'comment': submission_form.cleaned_data['comments']
                    }
                }
                on_peerreviewreview_created_task.apply_async(
                    args=[review, reviewed_count, extra],
                    queue='stats',
                )

                current_site_name = get_current_site(request).name
                send_mail_to_submission_owner(current_site_name, assignment, review, submitter)
            except IntegrityError:
                messages.error(request, _('Your can\'t submit two times the same review.'))
                return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))

            pending = assignment.minimum_reviewers - reviewed_count
            if pending > 0:
                messages.success(request, _('Your review has been submitted. You have to review at least %d exercises more.') % pending)
            else:
                messages.success(request, _('Your review has been submitted.'))
            return HttpResponseRedirect(reverse('course_reviews', args=[course_slug]))
    else:
        submission_form = ReviewSubmissionForm()
        criteria_formset = EvalutionCriteriaResponseFormSet(initial=criteria_initial)

    max_hours_assigned = timedelta(hours=getattr(settings,
                                   "PEER_REVIEW_ASSIGNATION_EXPIRE", 24))

    assigned_when = submission[0]["assigned_when"]
    assignation_expire = assigned_when + max_hours_assigned

    now = datetime.now(assigned_when.tzinfo)
    is_assignation_expired = now > assignation_expire

    return render_to_response('peerreview/review_review.html', {
        'submission': submission[0],
        'is_assignation_expired': is_assignation_expired,
        'assignation_expire': assignation_expire,
        'submission_form': submission_form,
        'criteria_formset': criteria_formset,
        'course': course,
        'assignment': assignment,
        'is_enrolled': is_enrolled,
    }, context_instance=RequestContext(request))
示例#25
0
 def dispatch(self, request_type, request, **kwargs):
     # We need the request to dehydrate some fields
     collection = get_db().get_collection('answers')
     self.user = get_user(request, collection)
     return super(OptionResource, self).dispatch(request_type, request,
                                                 **kwargs)
示例#26
0
文件: views.py 项目: ntwuxc/moocng
def course_review_review(request, course_slug, assignment_id):
    course = get_course_if_user_can_view_or_404(course_slug, request)
    assignment = get_object_or_404(PeerReviewAssignment, id=assignment_id)
    user_id = request.user.id

    is_enrolled = course.students.filter(id=user_id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(
            reverse('course_overview', args=[course_slug]))

    if assignment.kq.unit.course != course:
        messages.error(
            request,
            _('The selected peer review assignment is not part of this course.'
              ))
        return HttpResponseRedirect(
            reverse('course_reviews', args=[course_slug]))

    collection = get_db().get_collection('peer_review_submissions')

    submission = collection.find({
        'kq': assignment.kq.id,
        'assigned_to': user_id
    })

    if submission.count() == 0:
        messages.error(request, _('You don\'t have this submission assigned.'))
        return HttpResponseRedirect(
            reverse('course_reviews', args=[course_slug]))

    submission_obj = submission[0]

    submitter = User.objects.get(id=int(submission_obj['author']))

    criteria_initial = [{
        'evaluation_criterion_id': criterion.id
    } for criterion in assignment.criteria.all()]
    EvalutionCriteriaResponseFormSet = formset_factory(
        EvalutionCriteriaResponseForm, extra=0, max_num=len(criteria_initial))

    if request.method == "POST":
        submission_form = ReviewSubmissionForm(request.POST)
        criteria_formset = EvalutionCriteriaResponseFormSet(
            request.POST, initial=criteria_initial)
        if criteria_formset.is_valid() and submission_form.is_valid():
            criteria_values = [
                (int(form.cleaned_data['evaluation_criterion_id']),
                 int(form.cleaned_data['value'])) for form in criteria_formset
            ]
            try:
                review = save_review(assignment.kq, request.user, submitter,
                                     criteria_values,
                                     submission_form.cleaned_data['comments'])

                reviews = get_db().get_collection('peer_review_reviews')
                reviewed_count = reviews.find({
                    'reviewer': user_id,
                    'kq': assignment.kq.id
                }).count()
                on_peerreviewreview_created_task.apply_async(
                    args=[review, reviewed_count],
                    queue='stats',
                )

                current_site_name = get_current_site(request).name
                send_mail_to_submission_owner(current_site_name, assignment,
                                              review, submitter)
            except IntegrityError:
                messages.error(
                    request,
                    _('Your can\'t submit two times the same review.'))
                return HttpResponseRedirect(
                    reverse('course_reviews', args=[course_slug]))

            pending = assignment.minimum_reviewers - reviewed_count
            if pending > 0:
                messages.success(
                    request,
                    _('Your review has been submitted. You have to review at least %d exercises more.'
                      ) % pending)
            else:
                messages.success(request, _('Your review has been submitted.'))
            return HttpResponseRedirect(
                reverse('course_reviews', args=[course_slug]))
    else:
        submission_form = ReviewSubmissionForm()
        criteria_formset = EvalutionCriteriaResponseFormSet(
            initial=criteria_initial)

    max_hours_assigned = timedelta(
        hours=getattr(settings, "PEER_REVIEW_ASSIGNATION_EXPIRE", 24))

    assigned_when = submission[0]["assigned_when"]
    assignation_expire = assigned_when + max_hours_assigned

    now = datetime.now(assigned_when.tzinfo)
    is_assignation_expired = now > assignation_expire

    return render_to_response('peerreview/review_review.html', {
        'submission': submission[0],
        'is_assignation_expired': is_assignation_expired,
        'assignation_expire': assignation_expire,
        'submission_form': submission_form,
        'criteria_formset': criteria_formset,
        'course': course,
        'assignment': assignment,
        'is_enrolled': is_enrolled,
    },
                              context_instance=RequestContext(request))
示例#27
0
文件: views.py 项目: ntwuxc/moocng
def course_review_assign(request, course_slug, assignment_id):
    course = get_course_if_user_can_view_or_404(course_slug, request)
    assignment = get_object_or_404(PeerReviewAssignment, id=assignment_id)
    user_id = request.user.id

    is_enrolled = course.students.filter(id=user_id).exists()
    if not is_enrolled:
        messages.error(request, _('You are not enrolled in this course'))
        return HttpResponseRedirect(
            reverse('course_overview', args=[course_slug]))

    if assignment.kq.unit.course != course:
        messages.error(
            request,
            _('The selected peer review assignment is not part of this course.'
              ))
        return HttpResponseRedirect(
            reverse('course_reviews', args=[course_slug]))

    collection = get_db().get_collection('peer_review_submissions')

    submission = collection.find({
        'kq': assignment.kq.id,
        'assigned_to': user_id
    })
    if submission.count() > 0:
        messages.error(request, _('You already have a submission assigned.'))
        return HttpResponseRedirect(
            reverse('course_reviews', args=[course_slug]))

    max_hours_assigned = timedelta(
        hours=getattr(settings, "PEER_REVIEW_ASSIGNATION_EXPIRE", 24))

    assignation_expire = datetime.utcnow() - max_hours_assigned

    submission = collection.find({
        'kq':
        assignment.kq.id,
        '$or': [{
            'assigned_to': {
                '$exists': False
            },
        }, {
            'assigned_when': {
                '$lt': assignation_expire
            },
        }],
        'author': {
            '$ne': user_id
        },
        'reviewers': {
            '$ne': user_id
        }
    }).sort([
        ('reviews', pymongo.ASCENDING),
        ('author_reviews', pymongo.DESCENDING),
    ]).limit(1)

    if submission.count() == 0:
        messages.error(
            request,
            _('There is no submission avaliable for you at this moment. Please, try again later.'
              ))
        return HttpResponseRedirect(
            reverse('course_reviews', args=[course_slug]))
    else:
        collection.update({'_id': submission[0]['_id']}, {
            '$set': {
                'assigned_to': user_id,
                'assigned_when': datetime.utcnow()
            }
        })
        return HttpResponseRedirect(
            reverse('course_review_review', args=[course_slug, assignment_id]))