Skip to content
base.py 40.6 KiB
Newer Older
# -*- coding: utf-8 -*-

from __future__ import division

__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import six

import django.forms as forms

from course.validation import validate_struct, ValidationError
from course.constants import MAX_EXTRA_CREDIT_FACTOR
from relate.utils import StyledForm, Struct, string_concat
from django.forms import ValidationError as FormValidationError
from django.utils.safestring import mark_safe
from django.utils.functional import lazy
from django.utils.translation import (
from django.utils import translation
from django.conf import settings
    from typing import Text, Optional, Any, Tuple, Dict, Callable, FrozenSet, Union  # noqa
Dong Zhuang's avatar
Dong Zhuang committed
    from django import http  # noqa
    from course.models import (  # noqa
            Course,
            FlowSession
            )
    from course.content import Repo_ish  # noqa

# }}}


mark_safe_lazy = lazy(mark_safe, six.text_type)
class PageContext(object):
    """
    .. attribute:: course
    .. attribute:: repo
    .. attribute:: commit_sha
    .. attribute:: flow_session

        May be None.

    .. attribute:: page_uri

    Note that this is different from :class:`course.utils.FlowPageContext`,
    which is used internally by the flow views.
    """

    def __init__(
            self,
            course,  # type: Course
            repo,  # type: Repo_ish
            commit_sha,  # type: bytes
            flow_session,  # type: FlowSession
            in_sandbox=False,  # type: bool
            page_uri=None,  # type: Optional[str]
            ):
        # type: (...) -> None

        self.course = course
        self.repo = repo
        self.commit_sha = commit_sha
        self.flow_session = flow_session
        self.in_sandbox = in_sandbox
        self.page_uri = page_uri
class PageBehavior(object):
    """
    .. attribute:: show_correctness
    .. attribute:: show_answer
    .. attribute:: may_change_answer
    """

    def __init__(
            self,
            show_correctness,  # type: bool
            show_answer,  # type: bool
            may_change_answer,  # type:bool
            ):
        # type: (...) -> None

        self.show_correctness = show_correctness
        self.show_answer = show_answer
        self.may_change_answer = may_change_answer

    def __bool__(self):
        # This is for compatiblity: page_behavior used to be a bool argument
        # 'answer_is_final'.
        return not self.may_change_answer

    __nonzero__ = __bool__


def markup_to_html(
        page_context,  # type: PageContext
        text,  # type: Text
        use_jinja=True,  # type: bool
        reverse_func=None,  # type: Callable
        ):
    # type: (...) -> Text
    from course.content import markup_to_html as mth

    return mth(
            page_context.course,
            page_context.repo,
            page_context.commit_sha,
            use_jinja=use_jinja,
            reverse_func=reverse_func)

class InvalidFeedbackPointsError(ValueError):
    pass


CORRECTNESS_ATOL = 1e-5


def get_close_value(correctness):
    # type: (Optional[float]) -> (Optional[Union[float, int]])

    if correctness is None:
        return None
    elif abs(correctness - 0) < CORRECTNESS_ATOL:
        return 0
    elif abs(correctness - 1) < CORRECTNESS_ATOL:
        return 1
    elif abs(correctness - MAX_EXTRA_CREDIT_FACTOR) < CORRECTNESS_ATOL:
        return MAX_EXTRA_CREDIT_FACTOR
    else:
        return correctness


def get_auto_feedback(correctness):

    correctness = get_close_value(correctness)

    if correctness is None:
        return six.text_type(_("No information on correctness of answer."))

    error_msg_pattern = _(
        "'correctness' is invalid: expecting "
        "a value within [0, %(max_extra_credit_factor)s] or None, "
        "got %(invalid_value)s.")

    if correctness < -CORRECTNESS_ATOL:
        raise InvalidFeedbackPointsError(
            error_msg_pattern
            % {"max_extra_credit_factor": MAX_EXTRA_CREDIT_FACTOR,
               "invalid_value": correctness})
    elif correctness == 0:
        return six.text_type(_("Your answer is not correct."))
        return six.text_type(_("Your answer is correct."))
    elif correctness > 1:
        if correctness > MAX_EXTRA_CREDIT_FACTOR:
            raise InvalidFeedbackPointsError(
                error_msg_pattern
                % {"max_extra_credit_factor": MAX_EXTRA_CREDIT_FACTOR,
                   "invalid_value": correctness})
        return six.text_type(
                string_concat(
                    _("Your answer is correct and earned bonus points."),
                    " (%.1f %%)")
                % (100*correctness))
    elif correctness > 0.5:
        return six.text_type(
Loading
Loading full blame...