def create_new_phase(self, phase):
        """
        Creates a new phase with the specified categories.
        It will take all images with the categories and add them to the question
        :param phase: The left and right categories in an object
        :return: A newly created question
        """

        images = Image.query.filter(
            or_(Image.category_id.in_(phase['left_categ']),
                Image.category_id.in_((phase['right_categ'])))).all()

        question = Question(text="", q_type=QuestionType.binary, images=images)
        add_to_db(question)

        for c_left in phase['left_categ']:
            q_to_c = Question_to_category(q_id=question.id,
                                          c_id=c_left,
                                          is_left=True)
            add_to_db(q_to_c)

        for c_right in phase['right_categ']:
            q_to_c = Question_to_category(q_id=question.id,
                                          c_id=c_right,
                                          is_left=False)
            add_to_db(q_to_c)

        return question
Exemplo n.º 2
0
def add_question():
    """
    Function enables user to create a question by first checking if they have
    entered an empty string and returns an error message in that case. If not,
    it creates a question with the information from the json object and adds
    the question to a list of qeustions called 'questions' and returns a
    success message wuth the question that has been created.
    """
    data = request.get_json()

    questionId = len(questions)
    questionId += 1

    details = data.get('details')

    if not details or details.isspace():
        return jsonify({"message":
                        "Sorry, you didn't enter any question!"}), 400
    question = Question(questionId, details)
    questions.append(question)

    return jsonify({
        "id": questionId,
        "question": question.__dict__,
        "message": "Question added successfully!"
    }), 201
Exemplo n.º 3
0
    def create(self, request):
        data = request.data
        print('data >> ', data)

        assignment = Assignment()
        teacher = User.objects.get(username=data['teacher'])
        assignment.teacher = teacher
        assignment.title = data['title']
        assignment.save()

        order = 1
        for q in data['questions']:
            newQ = Question()
            newQ.question = q['title']
            newQ.order = order
            newQ.save()

            for c in q['choices']:
                newC = Choice()
                newC.title = c
                newC.save()
                newQ.choices.add(newC)

            newQ.answer = Choice.objects.get(title=q['answer'])
            newQ.assignment = assignment
            newQ.save()
            order += 1
        return assignment
Exemplo n.º 4
0
def add_question(request, user_id):

    mentee = Mentee.objects.get(id=user_id)
    question = Question()
    question.author = mentee
    question.title = request.data['title']
    question.description = request.data['description']
    question.language = request.data['language']
    question.save()
    return Response(QuestionSerializer(question).data,
                    status=status.HTTP_201_CREATED)
Exemplo n.º 5
0
 def get(self, request, format=None):
     if not 'token' in request.GET:
         return Response(status=status.HTTP_404_NOT_FOUND)
     student = get_student(request.GET['token'])
     quiz = Quiz(subject='fractions')
     quiz.save()
     scores = Score.objects.all().filter(subject='fractions',
                                         student=student)
     avg = 0
     if len(scores) > 2:
         for score in scores:
             avg = avg + score.value
         avg = avg / len(scores)
     if avg <= num_questions / 3.0:
         low_mult = 2
         high_mult = 3
         low_num = 1
         high_num = 3
         high_denom = 6
     elif avg <= (2 * num_questions) / 3.0:
         low_mult = 3
         high_mult = 5
         low_num = 1
         high_num = 4
         high_denom = 8
     else:
         low_mult = 6
         high_mult = 9
         low_num = 1
         high_num = 5
         high_denom = 10
     for i in range(num_questions):
         multiplier = random.randint(low_mult, high_mult)
         numerator = random.randint(low_num, high_num)
         denom = random.randint(numerator + 1, high_denom)
         ans_denom = denom * multiplier
         answer = numerator * multiplier
         text = str(numerator) + ' ' + str(denom) + ' ' + str(ans_denom)
         explanation = 'The correct answer is ' + str(
             answer) + ' because ' + str(numerator) + '/' + str(
                 denom) + ' times ' + str(multiplier) + '/' + str(
                     multiplier) + ' is ' + str(answer) + '/' + str(
                         ans_denom)
         question = Question(text=text,
                             answer=str(answer),
                             explanation=explanation,
                             quiz=quiz)
         question.save()
         quiz.save()
     serializer = QuizSerializer(quiz)
     return Response(serializer.data)
Exemplo n.º 6
0
 def create_question(self, classroom_uuid, content):
     question_uuid = uuid.uuid1()
     school_uuid = self.classroom_helper.get_school_uuid_by_classroom_uuid(
         classroom_uuid)
     Question(uuid=question_uuid,
              classroom_uuid=classroom_uuid,
              school_uuid=school_uuid,
              creator=self.user_id,
              role=self.role,
              anonymous=self.anonymous,
              active=True,
              answer_count=0,
              content=content,
              created_timestamp=self.timestamp_now,
              updated_timestamp=self.timestamp_now).save()
Exemplo n.º 7
0
def question_create(request):
    """
    Create a one question.

    """
    user = request.user
    question = Question(author=user)
    if request.method == 'POST':

        serializer = QuestionSerializer(question, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
Exemplo n.º 8
0
def save_question(question, answer, detractors):
    operator = get_math_operation(question)
    has_negative_values = check_for_negative_values(answer, *detractors)

    q = Question(text=question, operation_type=operator, has_negative_values=has_negative_values)
    q.save()

    all_answers = []
    a = Answer(text=answer, is_correct_answer=True)
    a.save()
    all_answers.append(a)

    for d in detractors:
        a = Answer(text=d, is_correct_answer=False)
        a.save()
        all_answers.append(a)

    q.answers.add(*all_answers)
Exemplo n.º 9
0
    def post(self):
        request_data = request.get_json()

        user = User.query.first()

        question_schema = QuestionSchema(
            only=["id", "title", "created_at", "updated_at"])
        question_data = question_schema.load_object_into_schema(request_data)
        question_data["questioner"] = user
        question = Question(**question_data)
        question.save()

        return jsonify({
            "data":
            question_schema.dump(question).data,
            "status":
            "success",
            "message":
            SUCCESS_MESSAGES["created"].format("Question")
        })
Exemplo n.º 10
0
    def create(self, validated_data):
        question_tags = validated_data.pop('tags', None)
        question = Question(**validated_data)
        question.author = self.context['request'].user
        question.save()

        for request_tag in question_tags:
            tag_name = request_tag.get('name')
            if not Tag.objects.filter(name=tag_name).exists():
                tag = create_tag(request_tag)
            else:
                tag = Tag.objects.filter(name=tag_name)[0]
            qt = QuestionTag.objects.create(
                question=question,
                tag=tag,
            )
            qt.save()

        question.save()
        return question
Exemplo n.º 11
0
    def post(self, request, room_number):
        request.session.save()
        json = JSONParser().parse(request)
        room = get_or_none(Room, number=room_number)

        if room:
            question = Question(room=room, title=json['title'], balance=0)
            question.save()

            Group('room-%s' % question.room.number).send({
                'text': dumps({
                    'type': 'question',
                    'action': 'create',
                    'data': QuestionSerializer(question).data
                })
            })

            return Response(QuestionSerializer(question).data, status=201)

        else:
            return Response({"error": "no room " + room_number + " found"}, status=404)
Exemplo n.º 12
0
 def get(self, request, format=None):
     if not 'token' in request.GET:
         return Response(status=status.HTTP_404_NOT_FOUND)
     student = get_student(request.GET['token'])
     quiz = Quiz(subject='subtraction')
     quiz.save()
     scores = Score.objects.all().filter(subject='subtraction',
                                         student=student)
     avg = 0
     if len(scores) > 2:
         for score in scores:
             avg = avg + score.value
         avg = avg / len(scores)
     if avg <= num_questions / 3.0:
         low_x = 3
         low_y = 1
         high = 9
     elif avg <= (2 * num_questions) / 3.0:
         low_x = 5
         low_y = 3
         high = 20
     else:
         low_x = 15
         low_y = 11
         high = 99
     for i in range(num_questions):
         x = random.randint(low_x, high)
         y = random.randint(low_y, x - 1)
         answer = x - y
         text = str(x) + ' ' + str(y)
         explanation = str(x) + ' - ' + str(y) + ' is equal to ' + str(
             answer)
         question = Question(text=text,
                             answer=str(answer),
                             explanation=explanation,
                             quiz=quiz)
         question.save()
         quiz.save()
     serializer = QuizSerializer(quiz)
     return Response(serializer.data)
Exemplo n.º 13
0
def PostQuestion(request):
    """!@brief Function which is called when a user adds a question
    @details the function takes a question object as part of the request body, extracts the object and then creates a new entry in the question table. Since the topics is a many-to-many field, the topics need to be added one by one
    @return returns the feed output for the given user
    """
    serializer = QuestionSerializer(data=request.data)
    if serializer.is_valid():
        ques = serializer.validated_data
        user = ques['user']
        question = Question(user=user,
                            username=user.name,
                            userdepartment=user.department,
                            userbio=user.bio,
                            userdegree=user.degree,
                            userspecialization=user.specialization,
                            question=ques['question'],
                            description=ques['description'])
        question.save()
        for topic in ques['topics']:
            question.topics.add(topic)
        return Feed(user.id)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 14
0
async def random_questions(request, random_users: Tuple[List[User], List[Dict]]):
    async def fin():
        async with in_transaction() as connection:
            for question in questions_db:
                await question.delete(using_db=connection)

    faker = Faker()
    questions = []
    questions_db = []

    request.addfinalizer(fin)
    users_db, users = random_users

    async with in_transaction() as connection:
        for user in users_db:
            question_data = QuestionInput(faker.paragraph(), user.id)
            question = Question(**asdict(question_data))
            await question.save(using_db=connection)
            questions_db.append(question)
            questions.append(asdict(question_data))

    yield questions
Exemplo n.º 15
0
 def get(self, request, format=None):
     if not 'token' in request.GET:
         return Response(status=status.HTTP_404_NOT_FOUND)
     student = get_student(request.GET['token'])
     quiz = Quiz(subject='division')
     quiz.save()
     scores = Score.objects.all().filter(subject='division',
                                         student=student)
     avg = 0
     if len(scores) > 2:
         for score in scores:
             avg = avg + score.value
         avg = avg / len(scores)
     if avg <= num_questions / 3.0:
         low = 1
         high = 4
     elif avg <= (2 * num_questions) / 3.0:
         low = 3
         high = 7
     else:
         low = 6
         high = 12
     for i in range(num_questions):
         y = random.randint(low, high)
         answer = random.randint(low, high)
         x = y * answer
         text = str(x) + ' ' + str(y)
         explanation = str(x) + ' divided by ' + str(
             y) + ' is equal to ' + str(answer)
         question = Question(text=text,
                             answer=str(answer),
                             explanation=explanation,
                             quiz=quiz)
         question.save()
         quiz.save()
     serializer = QuizSerializer(quiz)
     return Response(serializer.data)
def question(request):

    if request.method == 'GET':
        name = request.GET.get('name' , request.GET.get('name',None))
        title = request.GET.get('title' , request.GET.get('title',None))
        content = request.GET.get('content' , request.GET.get('content',None))
        replys = request.GET.get('replys' , request.GET.get('replys',None))
        times = request.GET.get('times' , request.GET.get('times',None))
        questions = Question.objects.all()

        if name:
            questions = questions.filter(name=name)

        if title:
            questions = questions.filter(title=title)

        if content:
            questions = question.filter(content=content)

        if replys:
            questions = question.filter(replys=replys)

        serializer = QuestionSerializer(questions, many=True)
        return Response(data=serializer.data, status=status.HTTP_200_OK)

    if request.method == 'POST':
        ques = request.data["params"]
        name = ques["name"]
        title = ques["title"]
        content = ques["content"]
        replys = ques["replys"]
        times = datetime.datetime.now().date() + datetime.timedelta(days=31)

        Question(name = name, title = title, content = content , replys=replys , times=times).save()

        return Response(data=status.HTTP_201_CREATED)
Exemplo n.º 17
0
 def get(self, request, format=None):
     if not 'token' in request.GET:
         return Response(status=status.HTTP_404_NOT_FOUND)
     student = get_student(request.GET['token'])
     quiz = Quiz(subject='geometry')
     quiz.save()
     scores = Score.objects.all().filter(subject='geometry',
                                         student=student)
     avg = 0
     for i in range(num_questions):
         area = random.choice(['Area', 'Perimeter'])
         if len(scores) > 2:
             for score in scores:
                 avg = avg + score.value
             avg = avg / len(scores)
         if avg <= num_questions / 3.0:
             shape = 'Square'
             low = 2
             high = 5
         elif avg <= (2 * num_questions) / 3.0:
             shape = random.choice(['Square', 'Rectangle'])
             low = 3
             high = 9
         else:
             shape = random.choice(['Square', 'Rectangle', 'Triangle'])
             low = 6
             high = 20
         val = ''
         if shape == 'Square':
             x = random.randint(low, high)
             if area == 'Area':
                 answer = x * x
             elif area == 'Perimeter':
                 answer = 4 * x
             val = str(x)
         elif shape == 'Rectangle':
             x = random.randint(low, high)
             y = random.randint(low, high)
             while y == x:
                 y == random.randint(low, high)
             if area == 'Area':
                 answer = x * y
             elif area == 'Perimeter':
                 answer = 2 * (x + y)
             if y > x:
                 val = str(x) + ' ' + str(y)
             else:
                 val = str(y) + ' ' + str(x)
         elif shape == 'Triangle':
             x = random.randint(low, high)
             if x % 2 == 1:
                 if not x == high:
                     x = x + 1
                 else:
                     x = x - 1
             y = random.randint(low, high)
             while y == x:
                 y == random.randint(low, high)
             if area == 'Area':
                 answer = (x * y) / 2
                 if y > x:
                     val = str(x) + ' ' + str(y)
                 else:
                     val = str(y) + ' ' + str(x)
             elif area == 'Perimeter':
                 pythag = random.choice([[3, 4, 5], [5, 12, 13],
                                         [8, 15, 17], [7, 24, 25],
                                         [9, 40, 41], [11, 60, 61],
                                         [12, 35, 37], [16, 63, 65],
                                         [20, 21, 29]])
                 answer = pythag[0] + pythag[1] + pythag[2]
                 val = str(pythag[0]) + ' ' + str(pythag[1]) + ' ' + str(
                     pythag[2])
         text = shape + ' ' + area + ' ' + val
         explanation = 'blank on purpose'
         question = Question(text=text,
                             answer=str(answer),
                             explanation=explanation,
                             quiz=quiz)
         question.save()
         quiz.save()
     serializer = QuizSerializer(quiz)
     return Response(serializer.data)