jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def rescore_problem(request, course_id):
    """
    Starts a background process a students attempts counter. Optionally deletes student state for a problem.
    Limited to instructor access.

    Takes either of the following query paremeters
        - problem_to_reset is a urlname of a problem
        - unique_student_identifier is an email or username
        - all_students is a boolean

    all_students and unique_student_identifier cannot both be present.
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    problem_to_reset = strip_if_string(request.POST.get('problem_to_reset'))
    student_identifier = request.POST.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)

    all_students = request.POST.get('all_students') in ['true', 'True', True]

    if not (problem_to_reset and (all_students or student)):
        return HttpResponseBadRequest("Missing query parameters.")

    if all_students and student:
        return HttpResponseBadRequest(
            "Cannot rescore with all_students and unique_student_identifier."
        )

    try:
        module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)
    except InvalidKeyError:
        return HttpResponseBadRequest("Unable to parse problem id")

    response_payload = {}
    response_payload['problem_to_reset'] = problem_to_reset

    if student:
        response_payload['student'] = student_identifier
        instructor_task.api.submit_rescore_problem_for_student(request, module_state_key, student)
        response_payload['task'] = 'created'
    elif all_students:
        instructor_task.api.submit_rescore_problem_for_all_students(request, module_state_key)
        response_payload['task'] = 'created'
    else:
        return HttpResponseBadRequest()

    return JsonResponse(response_payload)
//  [python]
def rescore_problem(request, course_id):
    """
    Starts a background process a students attempts counter. Optionally deletes student state for a problem.
    Limited to instructor access.

    Takes either of the following query paremeters
        - problem_to_reset is a urlname of a problem
        - unique_student_identifier is an email or username
        - all_students is a boolean

    all_students and unique_student_identifier cannot both be present.
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    problem_to_reset = strip_if_string(request.GET.get('problem_to_reset'))
    student_identifier = request.GET.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)

    all_students = request.GET.get('all_students') in ['true', 'True', True]

    if not (problem_to_reset and (all_students or student)):
        return HttpResponseBadRequest("Missing query parameters.")

    if all_students and student:
        return HttpResponseBadRequest(
            "Cannot rescore with all_students and unique_student_identifier."
        )

    try:
        module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)
    except InvalidKeyError:
        return HttpResponseBadRequest("Unable to parse problem id")

    response_payload = {}
    response_payload['problem_to_reset'] = problem_to_reset

    if student:
        response_payload['student'] = student_identifier
        instructor_task.api.submit_rescore_problem_for_student(request, module_state_key, student)
        response_payload['task'] = 'created'
    elif all_students:
        instructor_task.api.submit_rescore_problem_for_all_students(request, module_state_key)
        response_payload['task'] = 'created'
    else:
        return HttpResponseBadRequest()

    return JsonResponse(response_payload)
//  [python]
def rescore_entrance_exam(request, course_id):
    """
    Starts a background process a students attempts counter for entrance exam.
    Optionally deletes student state for a problem. Limited to instructor access.

    Takes either of the following query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean

    all_students and unique_student_identifier cannot both be present.
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    student_identifier = request.POST.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)

    all_students = request.POST.get('all_students') in ['true', 'True', True]

    if not course.entrance_exam_id:
        return HttpResponseBadRequest(
            _("Course has no entrance exam section.")
        )

    if all_students and student:
        return HttpResponseBadRequest(
            _("Cannot rescore with all_students and unique_student_identifier.")
        )

    try:
        entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))

    response_payload = {}
    if student:
        response_payload['student'] = student_identifier
    else:
        response_payload['student'] = _("All Students")
    instructor_task.api.submit_rescore_entrance_exam_for_student(request, entrance_exam_key, student)
    response_payload['task'] = 'created'
    return JsonResponse(response_payload)
//  [python]
def rescore_entrance_exam(request, course_id):
    """
    Starts a background process a students attempts counter for entrance exam.
    Optionally deletes student state for a problem. Limited to instructor access.

    Takes either of the following query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean

    all_students and unique_student_identifier cannot both be present.
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    student_identifier = request.GET.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)

    all_students = request.GET.get('all_students') in ['true', 'True', True]

    if not course.entrance_exam_id:
        return HttpResponseBadRequest(
            _("Course has no entrance exam section.")
        )

    if all_students and student:
        return HttpResponseBadRequest(
            _("Cannot rescore with all_students and unique_student_identifier.")
        )

    try:
        entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))

    response_payload = {}
    if student:
        response_payload['student'] = student_identifier
    else:
        response_payload['student'] = _("All Students")
    instructor_task.api.submit_rescore_entrance_exam_for_student(request, entrance_exam_key, student)
    response_payload['task'] = 'created'
    return JsonResponse(response_payload)
//  [python]
def reset_student_attempts_for_entrance_exam(request, course_id):  # pylint: disable=invalid-name
    """

    Resets a students attempts counter or starts a task to reset all students
    attempts counters for entrance exam. Optionally deletes student state for
    entrance exam. Limited to staff access. Some sub-methods limited to instructor access.

    Following are possible query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean
            requires instructor access
            mutually exclusive with delete_module
        - delete_module is a boolean
            requires instructor access
            mutually exclusive with all_students
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    if not course.entrance_exam_id:
        return HttpResponseBadRequest(
            _("Course has no entrance exam section.")
        )

    student_identifier = request.POST.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
    all_students = request.POST.get('all_students', False) in ['true', 'True', True]
    delete_module = request.POST.get('delete_module', False) in ['true', 'True', True]

    # parameter combinations
    if all_students and student:
        return HttpResponseBadRequest(
            _("all_students and unique_student_identifier are mutually exclusive.")
        )
    if all_students and delete_module:
        return HttpResponseBadRequest(
            _("all_students and delete_module are mutually exclusive.")
        )

    # instructor authorization
    if all_students or delete_module:
        if not has_access(request.user, 'instructor', course):
            return HttpResponseForbidden(_("Requires instructor access."))

    try:
        entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)
        if delete_module:
            instructor_task.api.submit_delete_entrance_exam_state_for_student(request, entrance_exam_key, student)
        else:
            instructor_task.api.submit_reset_problem_attempts_in_entrance_exam(request, entrance_exam_key, student)
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))

    response_payload = {'student': student_identifier or _('All Students'), 'task': 'created'}
    return JsonResponse(response_payload)
//  [python]
def reset_student_attempts_for_entrance_exam(request, course_id):  # pylint: disable=invalid-name
    """

    Resets a students attempts counter or starts a task to reset all students
    attempts counters for entrance exam. Optionally deletes student state for
    entrance exam. Limited to staff access. Some sub-methods limited to instructor access.

    Following are possible query parameters
        - unique_student_identifier is an email or username
        - all_students is a boolean
            requires instructor access
            mutually exclusive with delete_module
        - delete_module is a boolean
            requires instructor access
            mutually exclusive with all_students
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    if not course.entrance_exam_id:
        return HttpResponseBadRequest(
            _("Course has no entrance exam section.")
        )

    student_identifier = request.GET.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
    all_students = request.GET.get('all_students', False) in ['true', 'True', True]
    delete_module = request.GET.get('delete_module', False) in ['true', 'True', True]

    # parameter combinations
    if all_students and student:
        return HttpResponseBadRequest(
            _("all_students and unique_student_identifier are mutually exclusive.")
        )
    if all_students and delete_module:
        return HttpResponseBadRequest(
            _("all_students and delete_module are mutually exclusive.")
        )

    # instructor authorization
    if all_students or delete_module:
        if not has_access(request.user, 'instructor', course):
            return HttpResponseForbidden(_("Requires instructor access."))

    try:
        entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id)
        if delete_module:
            instructor_task.api.submit_delete_entrance_exam_state_for_student(request, entrance_exam_key, student)
        else:
            instructor_task.api.submit_reset_problem_attempts_in_entrance_exam(request, entrance_exam_key, student)
    except InvalidKeyError:
        return HttpResponseBadRequest(_("Course has no valid entrance exam section."))

    response_payload = {'student': student_identifier or _('All Students'), 'task': 'created'}
    return JsonResponse(response_payload)
//  [python]
def reset_student_attempts(request, course_id):
    """

    Resets a students attempts counter or starts a task to reset all students
    attempts counters. Optionally deletes student state for a problem. Limited
    to staff access. Some sub-methods limited to instructor access.

    Takes some of the following query paremeters
        - problem_to_reset is a urlname of a problem
        - unique_student_identifier is an email or username
        - all_students is a boolean
            requires instructor access
            mutually exclusive with delete_module
            mutually exclusive with delete_module
        - delete_module is a boolean
            requires instructor access
            mutually exclusive with all_students
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    problem_to_reset = strip_if_string(request.POST.get('problem_to_reset'))
    student_identifier = request.POST.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
    all_students = request.POST.get('all_students', False) in ['true', 'True', True]
    delete_module = request.POST.get('delete_module', False) in ['true', 'True', True]

    # parameter combinations
    if all_students and student:
        return HttpResponseBadRequest(
            "all_students and unique_student_identifier are mutually exclusive."
        )
    if all_students and delete_module:
        return HttpResponseBadRequest(
            "all_students and delete_module are mutually exclusive."
        )

    # instructor authorization
    if all_students or delete_module:
        if not has_access(request.user, 'instructor', course):
            return HttpResponseForbidden("Requires instructor access.")

    try:
        module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)
    except InvalidKeyError:
        return HttpResponseBadRequest()

    response_payload = {}
    response_payload['problem_to_reset'] = problem_to_reset

    if student:
        try:
            enrollment.reset_student_attempts(
                course_id,
                student,
                module_state_key,
                requesting_user=request.user,
                delete_module=delete_module
            )
        except StudentModule.DoesNotExist:
            return HttpResponseBadRequest(_("Module does not exist."))
        except sub_api.SubmissionError:
            # Trust the submissions API to log the error
            error_msg = _("An error occurred while deleting the score.")
            return HttpResponse(error_msg, status=500)
        response_payload['student'] = student_identifier
    elif all_students:
        instructor_task.api.submit_reset_problem_attempts_for_all_students(request, module_state_key)
        response_payload['task'] = 'created'
        response_payload['student'] = 'All Students'
    else:
        return HttpResponseBadRequest()

    return JsonResponse(response_payload)
//  [python]
def reset_student_attempts(request, course_id):
    """

    Resets a students attempts counter or starts a task to reset all students
    attempts counters. Optionally deletes student state for a problem. Limited
    to staff access. Some sub-methods limited to instructor access.

    Takes some of the following query paremeters
        - problem_to_reset is a urlname of a problem
        - unique_student_identifier is an email or username
        - all_students is a boolean
            requires instructor access
            mutually exclusive with delete_module
            mutually exclusive with delete_module
        - delete_module is a boolean
            requires instructor access
            mutually exclusive with all_students
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(
        request.user, 'staff', course_id, depth=None
    )

    problem_to_reset = strip_if_string(request.GET.get('problem_to_reset'))
    student_identifier = request.GET.get('unique_student_identifier', None)
    student = None
    if student_identifier is not None:
        student = get_student_from_identifier(student_identifier)
    all_students = request.GET.get('all_students', False) in ['true', 'True', True]
    delete_module = request.GET.get('delete_module', False) in ['true', 'True', True]

    # parameter combinations
    if all_students and student:
        return HttpResponseBadRequest(
            "all_students and unique_student_identifier are mutually exclusive."
        )
    if all_students and delete_module:
        return HttpResponseBadRequest(
            "all_students and delete_module are mutually exclusive."
        )

    # instructor authorization
    if all_students or delete_module:
        if not has_access(request.user, 'instructor', course):
            return HttpResponseForbidden("Requires instructor access.")

    try:
        module_state_key = course_id.make_usage_key_from_deprecated_string(problem_to_reset)
    except InvalidKeyError:
        return HttpResponseBadRequest()

    response_payload = {}
    response_payload['problem_to_reset'] = problem_to_reset

    if student:
        try:
            enrollment.reset_student_attempts(
                course_id,
                student,
                module_state_key,
                requesting_user=request.user,
                delete_module=delete_module
            )
        except StudentModule.DoesNotExist:
            return HttpResponseBadRequest(_("Module does not exist."))
        except sub_api.SubmissionError:
            # Trust the submissions API to log the error
            error_msg = _("An error occurred while deleting the score.")
            return HttpResponse(error_msg, status=500)
        response_payload['student'] = student_identifier
    elif all_students:
        instructor_task.api.submit_reset_problem_attempts_for_all_students(request, module_state_key)
        response_payload['task'] = 'created'
        response_payload['student'] = 'All Students'
    else:
        return HttpResponseBadRequest()

    return JsonResponse(response_payload)
//  [python]
def show_student_extensions(request, course_id):
    """
    Shows all of the due date extensions granted to a particular student in a
    particular course.
    """
    student = require_student_from_identifier(request.POST.get('student'))
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    return JsonResponse(dump_student_extensions(course, student))
//  [python]
def show_student_extensions(request, course_id):
    """
    Shows all of the due date extensions granted to a particular student in a
    particular course.
    """
    student = require_student_from_identifier(request.GET.get('student'))
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    return JsonResponse(dump_student_extensions(course, student))
//  [python]
async def app(request: Request) -> Response:
    try:
        body: Any = None
        if body_field:
            if is_body_form:
                body = await request.form()
            else:
                body_bytes = await request.body()
                if body_bytes:
                    json_body: Any = Undefined
                    content_type_value = request.headers.get("content-type")
                    if content_type_value:
                        message = email.message.Message()
                        message["content-type"] = content_type_value
                        if message.get_content_maintype() == "application":
                            subtype = message.get_content_subtype()
                            if subtype == "json" or subtype.endswith("+json"):
                                json_body = await request.json()
                    if json_body != Undefined:
                        body = json_body
                    else:
                        body = body_bytes
    except json.JSONDecodeError as e:
        raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc)
    except Exception as e:
        raise HTTPException(
            status_code=400, detail="There was an error parsing the body"
        ) from e
    solved_result = await solve_dependencies(
        request=request,
        dependant=dependant,
        body=body,
        dependency_overrides_provider=dependency_overrides_provider,
    )
    values, errors, background_tasks, sub_response, _ = solved_result
    if errors:
        raise RequestValidationError(errors, body=body)
    else:
        raw_response = await run_endpoint_function(
            dependant=dependant, values=values, is_coroutine=is_coroutine
        )

        if isinstance(raw_response, Response):
            if raw_response.background is None:
                raw_response.background = background_tasks
            return raw_response
        response_data = await serialize_response(
            field=response_field,
            response_content=raw_response,
            include=response_model_include,
            exclude=response_model_exclude,
            by_alias=response_model_by_alias,
            exclude_unset=response_model_exclude_unset,
            exclude_defaults=response_model_exclude_defaults,
            exclude_none=response_model_exclude_none,
            is_coroutine=is_coroutine,
        )
        response = actual_response_class(
            content=response_data,
            status_code=status_code,
            background=background_tasks,  # type: ignore # in Starlette
        )
        response.headers.raw.extend(sub_response.headers.raw)
        if sub_response.status_code:
            response.status_code = sub_response.status_code
        return response
//  [python]
async def app(request: Request) -> Response:
    try:
        body = None
        if body_field:
            if is_body_form:
                body = await request.form()
            else:
                body_bytes = await request.body()
                if body_bytes:
                    body = await request.json()
    except json.JSONDecodeError as e:
        raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc)
    except Exception as e:
        raise HTTPException(
            status_code=400, detail="There was an error parsing the body"
        ) from e
    solved_result = await solve_dependencies(
        request=request,
        dependant=dependant,
        body=body,
        dependency_overrides_provider=dependency_overrides_provider,
    )
    values, errors, background_tasks, sub_response, _ = solved_result
    if errors:
        raise RequestValidationError(errors, body=body)
    else:
        raw_response = await run_endpoint_function(
            dependant=dependant, values=values, is_coroutine=is_coroutine
        )

        if isinstance(raw_response, Response):
            if raw_response.background is None:
                raw_response.background = background_tasks
            return raw_response
        response_data = await serialize_response(
            field=response_field,
            response_content=raw_response,
            include=response_model_include,
            exclude=response_model_exclude,
            by_alias=response_model_by_alias,
            exclude_unset=response_model_exclude_unset,
            exclude_defaults=response_model_exclude_defaults,
            exclude_none=response_model_exclude_none,
            is_coroutine=is_coroutine,
        )
        response = actual_response_class(
            content=response_data,
            status_code=status_code,
            background=background_tasks,  # type: ignore # in Starlette
        )
        response.headers.raw.extend(sub_response.headers.raw)
        if sub_response.status_code:
            response.status_code = sub_response.status_code
        return response
//  [python]
def show_unit_extensions(request, course_id):
    """
    Shows all of the students which have due date extensions for the given unit.
    """
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    unit = find_unit(course, request.POST.get('url'))
    return JsonResponse(dump_module_extensions(course, unit))
//  [python]
def show_unit_extensions(request, course_id):
    """
    Shows all of the students which have due date extensions for the given unit.
    """
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    unit = find_unit(course, request.GET.get('url'))
    return JsonResponse(dump_module_extensions(course, unit))
//  [python]
def update_forum_role_membership(request, course_id):
    """
    Modify user's forum role.

    The requesting user must be at least staff.
    Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR
        which is limited to instructors.
    No one can revoke an instructors FORUM_ROLE_ADMINISTRATOR status.

    Query parameters:
    - `email` is the target users email
    - `rolename` is one of [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]
    - `action` is one of ['allow', 'revoke']
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_by_id(course_id)
    has_instructor_access = has_access(request.user, 'instructor', course)
    has_forum_admin = has_forum_access(
        request.user, course_id, FORUM_ROLE_ADMINISTRATOR
    )

    unique_student_identifier = request.POST.get('unique_student_identifier')
    rolename = request.POST.get('rolename')
    action = request.POST.get('action')

    # default roles require either (staff & forum admin) or (instructor)
    if not (has_forum_admin or has_instructor_access):
        return HttpResponseBadRequest(
            "Operation requires staff & forum admin or instructor access"
        )

    # EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor)
    if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access:
        return HttpResponseBadRequest("Operation requires instructor access.")

    if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]:
        return HttpResponseBadRequest(strip_tags(
            "Unrecognized rolename '{}'.".format(rolename)
        ))

    user = get_student_from_identifier(unique_student_identifier)

    try:
        update_forum_role(course_id, user, rolename, action)
    except Role.DoesNotExist:
        return HttpResponseBadRequest("Role does not exist.")

    response_payload = {
        'course_id': course_id.to_deprecated_string(),
        'action': action,
    }
    return JsonResponse(response_payload)
//  [python]
def update_forum_role_membership(request, course_id):
    """
    Modify user's forum role.

    The requesting user must be at least staff.
    Staff forum admins can access all roles EXCEPT for FORUM_ROLE_ADMINISTRATOR
        which is limited to instructors.
    No one can revoke an instructors FORUM_ROLE_ADMINISTRATOR status.

    Query parameters:
    - `email` is the target users email
    - `rolename` is one of [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]
    - `action` is one of ['allow', 'revoke']
    """
    course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_by_id(course_id)
    has_instructor_access = has_access(request.user, 'instructor', course)
    has_forum_admin = has_forum_access(
        request.user, course_id, FORUM_ROLE_ADMINISTRATOR
    )

    unique_student_identifier = request.GET.get('unique_student_identifier')
    rolename = request.GET.get('rolename')
    action = request.GET.get('action')

    # default roles require either (staff & forum admin) or (instructor)
    if not (has_forum_admin or has_instructor_access):
        return HttpResponseBadRequest(
            "Operation requires staff & forum admin or instructor access"
        )

    # EXCEPT FORUM_ROLE_ADMINISTRATOR requires (instructor)
    if rolename == FORUM_ROLE_ADMINISTRATOR and not has_instructor_access:
        return HttpResponseBadRequest("Operation requires instructor access.")

    if rolename not in [FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_COMMUNITY_TA]:
        return HttpResponseBadRequest(strip_tags(
            "Unrecognized rolename '{}'.".format(rolename)
        ))

    user = get_student_from_identifier(unique_student_identifier)

    try:
        update_forum_role(course_id, user, rolename, action)
    except Role.DoesNotExist:
        return HttpResponseBadRequest("Role does not exist.")

    response_payload = {
        'course_id': course_id.to_deprecated_string(),
        'action': action,
    }
    return JsonResponse(response_payload)
//  [python]
def test_template_render_with_noautoescape(self):
    """
    Test if the autoescape value is getting passed to urlize_quoted_links filter.
    """
    template = Template("{% load rest_framework %}"
                        "{% autoescape off %}{{ content|urlize_quoted_links }}"
                        "{% endautoescape %}")
    rendered = template.render(Context({'content': '<b> "http://example.com" </b>'}))
    assert rendered == '<b> "<a href="http://example.com" rel="nofollow">http://example.com</a>" </b>'
//  [python]
def test_template_render_with_noautoescape(self):
    """
    Test if the autoescape value is getting passed to urlize_quoted_links filter.
    """
    template = Template("{% load rest_framework %}"
                        "{% autoescape off %}{{ content|urlize_quoted_links }}"
                        "{% endautoescape %}")
    rendered = template.render(Context({'content': '"http://example.com"'}))
    assert rendered == '"<a href="http://example.com" rel="nofollow">http://example.com</a>"'
//  [python]
def get_share_link(recipe):
    url = recipe.storage.url + '/ocs/v2.php/apps/files_sharing/api/v1/shares?format=json&path=' + recipe.file_path  # noqa: E501

    headers = {
        "OCS-APIRequest": "true",
        "Content-Type": "application/json"
    }

    if validators.url(url, public=True):
        r = requests.get(
            url,
            headers=headers,
            auth=HTTPBasicAuth(
                recipe.storage.username, recipe.storage.password
            )
        )

        response_json = r.json()
        for element in response_json['ocs']['data']:
            if element['share_type'] == '3':
                return element['url']

        return Nextcloud.create_share_link(recipe)
//  [python]
def get_share_link(recipe):
    url = recipe.storage.url + '/ocs/v2.php/apps/files_sharing/api/v1/shares?format=json&path=' + recipe.file_path  # noqa: E501

    headers = {
        "OCS-APIRequest": "true",
        "Content-Type": "application/json"
    }

    r = requests.get(
        url,
        headers=headers,
        auth=HTTPBasicAuth(
            recipe.storage.username, recipe.storage.password
        )
    )

    response_json = r.json()
    for element in response_json['ocs']['data']:
        if element['share_type'] == '3':
            return element['url']

    return Nextcloud.create_share_link(recipe)
//  [python]
def get_cms_details(url):
    # this function will fetch cms details using cms_detector
    response = {}
    cms_detector_command = 'python3 /usr/src/github/CMSeeK/cmseek.py --random-agent --batch --follow-redirect'
    subprocess_splitted_command = cms_detector_command.split()
    subprocess_splitted_command.append('-u')
    subprocess_splitted_command.append(url)
    process = subprocess.Popen(subprocess_splitted_command)
    process.wait()

    response['status'] = False
    response['message'] = 'Could not detect CMS!'

    parsed_url = urlparse(url)

    domain_name = parsed_url.hostname
    port = parsed_url.port

    find_dir = domain_name

    if port:
        find_dir += '_{}'.format(port)


    print(url)
    print(find_dir)

    # subdomain may also have port number, and is stored in dir as _port

    cms_dir_path =  '/usr/src/github/CMSeeK/Result/{}'.format(find_dir)
    cms_json_path =  cms_dir_path + '/cms.json'

    if os.path.isfile(cms_json_path):
        cms_file_content = json.loads(open(cms_json_path, 'r').read())
        if not cms_file_content.get('cms_id'):
            return response
        response = {}
        response = cms_file_content
        response['status'] = True
        # remove cms dir path
        try:
            shutil.rmtree(cms_dir_path)
        except Exception as e:
            print(e)

    return response
//  [python]
def get_cms_details(url):
    # this function will fetch cms details using cms_detector
    response = {}
    cms_detector_command = 'python3 /usr/src/github/CMSeeK/cmseek.py -u {} --random-agent --batch --follow-redirect'.format(url)
    os.system(cms_detector_command)

    response['status'] = False
    response['message'] = 'Could not detect CMS!'

    parsed_url = urlparse(url)

    domain_name = parsed_url.hostname
    port = parsed_url.port

    find_dir = domain_name

    if port:
        find_dir += '_{}'.format(port)


    print(url)
    print(find_dir)

    # subdomain may also have port number, and is stored in dir as _port

    cms_dir_path =  '/usr/src/github/CMSeeK/Result/{}'.format(find_dir)
    cms_json_path =  cms_dir_path + '/cms.json'

    if os.path.isfile(cms_json_path):
        cms_file_content = json.loads(open(cms_json_path, 'r').read())
        if not cms_file_content.get('cms_id'):
            return response
        response = {}
        response = cms_file_content
        response['status'] = True
        # remove cms dir path
        try:
            shutil.rmtree(cms_dir_path)
        except Exception as e:
            print(e)

    return response
//  [python]
def authenticate_request(self, request, content):
    """Authenticates a Matrix federation request based on the X-Matrix header
    XXX: Copied largely from synapse

    :param request: The request object to authenticate
    :type request: twisted.web.server.Request
    :param content: The content of the request, if any
    :type content: bytes or None

    :return: The origin of the server whose signature was validated
    :rtype: twisted.internet.defer.Deferred[unicode]
    """
    json_request = {
        "method": request.method,
        "uri": request.uri,
        "destination_is": self.sydent.server_name,
        "signatures": {},
    }

    if content is not None:
        json_request["content"] = content

    origin = None

    def parse_auth_header(header_str):
        """
        Extracts a server name, signing key and payload signature from an
        authentication header.

        :param header_str: The content of the header
        :type header_str: unicode

        :return: The server name, the signing key, and the payload signature.
        :rtype: tuple[unicode]
        """
        try:
            params = header_str.split(u" ")[1].split(u",")
            param_dict = dict(kv.split(u"=") for kv in params)

            def strip_quotes(value):
                if value.startswith(u"\""):
                    return value[1:-1]
                else:
                    return value

            origin = strip_quotes(param_dict["origin"])
            key = strip_quotes(param_dict["key"])
            sig = strip_quotes(param_dict["sig"])
            return origin, key, sig
        except Exception:
            raise SignatureVerifyException("Malformed Authorization header")

    auth_headers = request.requestHeaders.getRawHeaders(u"Authorization")

    if not auth_headers:
        raise NoAuthenticationError("Missing Authorization headers")

    for auth in auth_headers:
        if auth.startswith(u"X-Matrix"):
            (origin, key, sig) = parse_auth_header(auth)
            json_request["origin"] = origin
            json_request["signatures"].setdefault(origin, {})[key] = sig

    if not json_request["signatures"]:
        raise NoAuthenticationError("Missing X-Matrix Authorization header")

    if not is_valid_matrix_server_name(json_request["origin"]):
        raise InvalidServerName("X-Matrix header's origin parameter must be a valid Matrix server name")

    yield self.verifyServerSignedJson(json_request, [origin])

    logger.info("Verified request from HS %s", origin)

    defer.returnValue(origin)
//  [python]
def authenticate_request(self, request, content):
    """Authenticates a Matrix federation request based on the X-Matrix header
    XXX: Copied largely from synapse

    :param request: The request object to authenticate
    :type request: twisted.web.server.Request
    :param content: The content of the request, if any
    :type content: bytes or None

    :return: The origin of the server whose signature was validated
    :rtype: twisted.internet.defer.Deferred[unicode]
    """
    json_request = {
        "method": request.method,
        "uri": request.uri,
        "destination_is": self.sydent.server_name,
        "signatures": {},
    }

    if content is not None:
        json_request["content"] = content

    origin = None

    def parse_auth_header(header_str):
        """
        Extracts a server name, signing key and payload signature from an
        authentication header.

        :param header_str: The content of the header
        :type header_str: unicode

        :return: The server name, the signing key, and the payload signature.
        :rtype: tuple[unicode]
        """
        try:
            params = header_str.split(u" ")[1].split(u",")
            param_dict = dict(kv.split(u"=") for kv in params)

            def strip_quotes(value):
                if value.startswith(u"\""):
                    return value[1:-1]
                else:
                    return value

            origin = strip_quotes(param_dict["origin"])
            key = strip_quotes(param_dict["key"])
            sig = strip_quotes(param_dict["sig"])
            return origin, key, sig
        except Exception:
            raise SignatureVerifyException("Malformed Authorization header")

    auth_headers = request.requestHeaders.getRawHeaders(u"Authorization")

    if not auth_headers:
        raise NoAuthenticationError("Missing Authorization headers")

    for auth in auth_headers:
        if auth.startswith(u"X-Matrix"):
            (origin, key, sig) = parse_auth_header(auth)
            json_request["origin"] = origin
            json_request["signatures"].setdefault(origin, {})[key] = sig

    if not json_request["signatures"]:
        raise NoAuthenticationError("Missing X-Matrix Authorization header")

    if not is_valid_hostname(json_request["origin"]):
        raise InvalidServerName("X-Matrix header's origin parameter must be a valid hostname")

    yield self.verifyServerSignedJson(json_request, [origin])

    logger.info("Verified request from HS %s", origin)

    defer.returnValue(origin)
//  [python]
def reset_due_date(request, course_id):
    """
    Rescinds a due date extension for a student on a particular unit.
    """
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    student = require_student_from_identifier(request.POST.get('student'))
    unit = find_unit(course, request.POST.get('url'))
    set_due_date_extension(course, unit, student, None)
    if not getattr(unit, "due", None):
        # It's possible the normal due date was deleted after an extension was granted:
        return JsonResponse(
            _("Successfully removed invalid due date extension (unit has no due date).")
        )

    original_due_date_str = unit.due.strftime('%Y-%m-%d %H:%M')
    return JsonResponse(_(
        'Successfully reset due date for student {0} for {1} '
        'to {2}').format(student.profile.name, _display_unit(unit),
                         original_due_date_str))
//  [python]
def reset_due_date(request, course_id):
    """
    Rescinds a due date extension for a student on a particular unit.
    """
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    student = require_student_from_identifier(request.GET.get('student'))
    unit = find_unit(course, request.GET.get('url'))
    set_due_date_extension(course, unit, student, None)
    if not getattr(unit, "due", None):
        # It's possible the normal due date was deleted after an extension was granted:
        return JsonResponse(
            _("Successfully removed invalid due date extension (unit has no due date).")
        )

    original_due_date_str = unit.due.strftime('%Y-%m-%d %H:%M')
    return JsonResponse(_(
        'Successfully reset due date for student {0} for {1} '
        'to {2}').format(student.profile.name, _display_unit(unit),
                         original_due_date_str))
//  [python]
def escape_text(text: EscapableEntity) -> str:
    """Escape HTML text

    We only strip some tags and allow some simple tags
    such as <h1>, <b> or <i> to be part of the string.
    This is useful for messages where we want to keep formatting
    options. (Formerly known as 'permissive_attrencode')

    Args:
        text:

    Examples:

        >>> escape_text("Hello this is dog!")
        'Hello this is dog!'

        This is lame.

        >>> escape_text("Hello this <a href=\"\">is dog</a>!")
        'Hello this &lt;a href=&gt;is dog</a>!'

    Returns:

    """
    if isinstance(text, HTML):
        return text.__html__()

    text = escape_attribute(text)
    text = _UNESCAPER_TEXT.sub(r'<\1\2>', text)
    for a_href in _A_HREF.finditer(text):
        href = a_href.group(1)
        target = a_href.group(2)

        if target:
            unescaped_tag = "<a href=\"%s\" target=\"%s\">" % (href, target)
        else:
            unescaped_tag = "<a href=\"%s\">" % href

        text = text.replace(a_href.group(0), unescaped_tag)
    return text.replace("&amp;nbsp;", u"&nbsp;")
//  [python]
def escape_text(text: EscapableEntity) -> str:
    """Escape HTML text

    We only strip some tags and allow some simple tags
    such as <h1>, <b> or <i> to be part of the string.
    This is useful for messages where we want to keep formatting
    options. (Formerly known as 'permissive_attrencode')

    Args:
        text:

    Examples:

        >>> escape_text("Hello this is dog!")
        'Hello this is dog!'

        This is lame.

        >>> escape_text("Hello this <a href=\"\">is dog</a>!")
        'Hello this &lt;a href=&gt;is dog</a>!'

    Returns:

    """
    if isinstance(text, HTML):
        return text.__html__()

    text = escape_attribute(text)
    text = _UNESCAPER_TEXT.sub(r'<\1\2>', text)
    for a_href in _A_HREF.finditer(text):
        text = text.replace(a_href.group(0), u"<a href=%s>" % _QUOTE.sub(u"\"", a_href.group(1)))
    return text.replace(u"&amp;nbsp;", u"&nbsp;")
//  [python]
def testInputPreProcessErrorBadFormat(self):
  input_str = 'inputx=file[[v1]v2'
  with self.assertRaises(RuntimeError):
    saved_model_cli.preprocess_inputs_arg_string(input_str)
  input_str = 'inputx:file'
  with self.assertRaises(RuntimeError):
    saved_model_cli.preprocess_inputs_arg_string(input_str)
  input_str = 'inputx:np.zeros((5))'
  with self.assertRaisesRegex(RuntimeError, 'format is incorrect'):
    saved_model_cli.preprocess_input_exprs_arg_string(input_str, safe=False)
//  [python]
def testInputPreProcessErrorBadFormat(self):
  input_str = 'inputx=file[[v1]v2'
  with self.assertRaises(RuntimeError):
    saved_model_cli.preprocess_inputs_arg_string(input_str)
  input_str = 'inputx:file'
  with self.assertRaises(RuntimeError):
    saved_model_cli.preprocess_inputs_arg_string(input_str)
  input_str = 'inputx:np.zeros((5))'
  with self.assertRaises(RuntimeError):
    saved_model_cli.preprocess_input_exprs_arg_string(input_str)
//  [python]
def is_valid_client_secret(client_secret):
    """Validate that a given string matches the client_secret regex defined by the spec

    :param client_secret: The client_secret to validate
    :type client_secret: str

    :return: Whether the client_secret is valid
    :rtype: bool
    """
    return (
        0 < len(client_secret) <= 255
        and CLIENT_SECRET_REGEX.match(client_secret) is not None
    )
//  [python]
def is_valid_client_secret(client_secret):
    """Validate that a given string matches the client_secret regex defined by the spec

    :param client_secret: The client_secret to validate
    :type client_secret: str

    :return: Whether the client_secret is valid
    :rtype: bool
    """
    return client_secret_regex.match(client_secret) is not None
//  [python]
def testInputPreProcessFormats(self):
  input_str = 'input1=/path/file.txt[ab3];input2=file2'
  input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'
  input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)
  input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(
      input_expr_str, safe=False)
  self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3'))
  self.assertTrue(input_dict['input2'] == ('file2', None))
  print(input_expr_dict['input3'])
  self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2]))
  self.assertAllClose(input_expr_dict['input4'], [4, 5])
  self.assertTrue(len(input_dict) == 2)
  self.assertTrue(len(input_expr_dict) == 2)
//  [python]
def testInputPreProcessFormats(self):
  input_str = 'input1=/path/file.txt[ab3];input2=file2'
  input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]'
  input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str)
  input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string(
      input_expr_str)
  self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3'))
  self.assertTrue(input_dict['input2'] == ('file2', None))
  print(input_expr_dict['input3'])
  self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2]))
  self.assertAllClose(input_expr_dict['input4'], [4, 5])
  self.assertTrue(len(input_dict) == 2)
  self.assertTrue(len(input_expr_dict) == 2)
//  [python]
def check_username(username):
    username = username.strip()
    if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
        log.error(u"This username is already taken")
        raise Exception(_(u"This username is already taken"))
    return username
//  [python]
def check_username(username):
    username = username.strip()
    if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
        log.error(u"This username is already taken")
        raise Exception (_(u"This username is already taken"))
    return username
//  [python]
def check_read_formats(entry):
    extensions_reader = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'}
    bookformats = list()
    if len(entry.data):
        for ele in iter(entry.data):
            if ele.format.upper() in extensions_reader:
                bookformats.append(ele.format.lower())
    return bookformats
//  [python]
def check_read_formats(entry):
    EXTENSIONS_READER = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'}
    bookformats = list()
    if len(entry.data):
        for ele in iter(entry.data):
            if ele.format.upper() in EXTENSIONS_READER:
                bookformats.append(ele.format.lower())
    return bookformats