Example #1
0
    def parse(self, string):
        re_index  = r'\**\s*(?:[A-Ea-e]\.|\(?[A-Ea-e]\))'
        re_body   = r'.+'
        re_option = r'({index}\s+{body})'.format(index=re_index, body=re_body)
        self._tokenize(string)

        # spin thru the input chunks two at a time, the first being the
        # stem, presumably, and the second being the option group
        for st_index in range(0, len(self._tokens), 2):
            op_index = st_index +1
            if op_index < len(self._tokens):
                question = Question()

                stem = re.search(r'[0-9]+(?:\.|\s).+$', self._tokens[st_index], re.DOTALL)
                #~ stem = re.search(r"\n*((?:[0-9]*\.*\s*).+)$", self._tokens[st_index], re.DOTALL)
                #~ stem = re.search(r"(?:[0-9]+\s+(?:.|\n)+$)+?|(?:\n*.+$)", self._tokens[st_index])
                question.stem = stem.group().strip() if stem else self._tokens[st_index] 

                options = [o.strip() for o in re.split(re_option, self._tokens[op_index]) if o.strip()]
                for option in options:
                    question.options.append(option)

                self._questions.append(question)

        return self
Example #2
0
    def parse(self, string):
        question = Question()
        option = False

        self._tokenize(string)
        for token in self._tokens:
            o = re.match(r"^\s*[a-zA-Z][.)] ", token)
            if o and o.group():
                option = True
                try:
                    assert question is not None
                    question.options.append(token)
                except AssertionError:
                    pass
                continue

            if option:
                self._questions.append(question)
                question = Question()
                question.stem = ''
                option = False

            try:
                assert question is not None
                question.stem += token + '\n'
            except AssertionError:
                pass

        if question and len(question.options) > 0:
            self._questions.append(question)

        return self
Example #3
0
def loadSurvey(filename):
    from question import Question
    from answer import Answer
    survey = None
    f = open(filename, "r")
    if f is not None:
        s = ""
        b = f.read(512)
        while len(b):
            s += b
            b = f.read(512)
        f.close()
        sd = jsonpickle.decode(s)
        survey = Survey()
        survey.name = sd['name']
        survey.questions = {}
        for qd in sd['questions'].values():
            question = Question()
            question.id = qd['id']
            question.name = qd['name']
            question.answers = {}
            for ad in qd['answers'].values():
                answer = Answer()
                answer.id = ad['id']
                answer.value = ad['value']
                answer.selected = ad['selected']
                answer.editable = ad['editable']
                question.answers[answer.id] = answer
            survey.questions[question.id] = question
    return survey
Example #4
0
 def test_creation(self):
     q = {'name': 'q1', 'text': 'Random question one, choose a.', 'answers': 
             [{'value': 'a', 'text': 'a'}, {'value': 'b', 'text': 'b'}, 
              {'value': 'c', 'text': 'c'},{'value': 'd', 'text': 'd'}]
         }
     question = Question(q)
     assert question.name == q['name'] and question.text == q['text'] and question.answers == q['answers']
     question.save()
Example #5
0
 def test_blank_name(self):
     question = Question()
     question.text = 'Blank test question'
     question.answers = []
     try:
         question.save()
     except KeyError, e:
         print 'Adding blank question failed: %s' % e
Example #6
0
def get_question(question_id):
    if Question.is_null() == False: 
    	rows = Question.query(Question.serial_no==question_id).fetch()
        if len(rows) == 1:
            return dict(total= Question.count(), detail = rows[0])
        else:
            return empty_question()
    else:
        return empty_question()
Example #7
0
    def parse(self, string):
        self._tokenize(string)
        if not self._tokens: return self

        question = Question()
        question.stem = self._tokens[0]
        question.options = self._tokens[1:] if len(self._tokens) > 1 else []

        self._questions.append(question)

        return self
Example #8
0
 def test_duplicate(self):
     q = {'name': 'q2', 'text': 'Random question one, choose a.', 'answers': 
             [{'value': 'a', 'text': 'a'}, {'value': 'b', 'text': 'b'}, 
              {'value': 'c', 'text': 'c'},{'value': 'd', 'text': 'd'}]
         }
     question = Question(q)
     assert question.name == q['name'] and question.text == q['text'] and question.answers == q['answers']
     question.save()
     try:
         question.save()
     except KeyError, e:
         print 'Trying to save duplicate: %s' % e
	def test_illegal_keys(self):
		self.assertFalse(Question.iskey("")[0], "Empty string")
		self.assertFalse(Question.iskey("   ")[0], "Whitespace only")
		self.assertFalse(Question.iskey("  key")[0], "Leading whitespace")
		self.assertFalse(Question.iskey("end\t")[0], "Traling tabulation")
		self.assertFalse(Question.iskey("*$/\\")[0], "Non-alphanumeric characters")
		self.assertFalse(Question.iskey("end")[0], "Reserved keyword")
		self.assertFalse(Question.iskey("photoVisible")[0], "Reserved keyword")
		self.assertFalse(Question.iskey(32768)[0], "Not a string")
		self.assertFalse(Question.iskey("\n")[0], "Illegal escape character")
Example #10
0
def questions():
    form = NewQuestionForm(request.form)
    if request.method == 'POST' and form.validate():
        question = Question(form.category.data, form.question.data,
                            form.option_a.data, form.option_b.data,
                            form.option_c.data, form.option_d.data,
                            form.answer.data)
        question.save()
        flash('Question successfully created!', 'positive')
        return render_template('question_created.html', question=question, amount=Question.size())
    elif request.method == 'POST' and not form.validate():
        flash('Oops, your submitted question appears to be invalid.', 'negative')
        return render_template('question_new.html', form=form, amount=Question.size())
    else:
        return render_template('invalid_request.html')
Example #11
0
def accept_input():
  content = request.args.get('content', '')
  number = request.args.get('from', '')
  # check for malicious URLs
  if url_check(content):
    print "This number is a spammer: %(number)s" % {"number": number}
    return
  if number == '447860033028':
    #no infinite loop 4 u
    return
  question = Question(content,number)
  question.ask()

  # debug statements below
  print("%(content)s from %(number)s." % {"content": question.message, "number": question.number})
  return "%(content)s from %(number)s." % {"content": question.message, "number": question.number} 
Example #12
0
    def ask(self, question, answer_type = str, **configs):
        self.question = Question(question, answer_type)
        self.answer = ""
        for key, value in configs.iteritems():
            self.question.__dict__[key] = value

        if self.question.gather:
            return self.gather()

        self.say(self.question.question)
        # retry until the correct answer
        while True:
            try:
                self.answer = self.question.answer_or_default(self.get_response())
                self.answer = self.question.change_case(self.answer)
                self.__class__(self.input, self.output)
                self.question.update()
                if not self.question.valid_answer(self.answer):
                    self.explain_error("not_valid")
                    raise QuestionError()
                self.answer = self.question.convert(self.answer)
            except QuestionError:
                pass
            else:
                self.question = None
                break
        return self.answer
	def test_valid_keys(self):
		self.assertTrue(Question.iskey("A")[0], "Single-character")
		self.assertTrue(Question.iskey("thisIsALongKey")[0], "Multi-character")
		self.assertTrue(Question.iskey("--")[0], "Hyphens")
		self.assertTrue(Question.iskey("--key")[0], "Leading hyphens")
		self.assertTrue(Question.iskey("_")[0], "Underscores")
		self.assertTrue(Question.iskey("__key")[0], "Leading underscores")
		self.assertTrue(Question.iskey("_now-y0u_4re-pushing-1t")[0], "Mixed characters")
		self.assertTrue(Question.iskey("_end")[0], "Not a reserved keyword")
Example #14
0
 def test_should_return_html_for_single_line_answer_question(self):
     actual = Question.single_line_answer("question")
     expected = '''\
         <div id="1">
             question <input type="text" id=1></input>
         </div>
     '''
     self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
Example #15
0
 def test_should_return_html_for_multi_line_answer_question(self):
     actual = Question.multi_line_answer("question")
     expected = '''\
         <div id="1">
             question <textarea rows=10 cols=30 id=1></textarea>
         </div>
     '''
     self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
Example #16
0
 def test_should_return_html_for_multi_choice_answer_question(self):
     actual = Question.multi_choice("question", "a1", "a2")
     expected = '''\
         <div id="1">
             question <input type=checkbox id="1_1">a1</input><input type=checkbox name="1_2">a2</input>
         </div>
     '''
     self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
Example #17
0
 def test_should_return_html_for_single_choice_question(self):
     actual = Question.single_choice("question", "a1", "a2")
     expected = '''\
         <div id="1">
             question <input type=radio name="1">a1</input><input type=radio name="1">a2</input>
         </div>
     '''
     self.assertEquals(HTMLReader(expected).to_s(), HTMLReader(actual).to_s())
Example #18
0
 def onQuestion(self, msg):
     """
     Gets called when a new question is received.
     The received question is then displayed in the GUI.
     """
     self._answerLocked = False
     self.activeQuestion = Question.fromMsg(msg)
     self.ui.updateQuestion(self.activeQuestion)
Example #19
0
def question(id):
    form = AnswerForm(request.form)
    question = Question.find(id)

    if not question:
        return random_question()

    if request.method == 'GET' or (request.method == 'POST' and not form.validate()):
        return render_template('question.html', question=question, form=form, amount=Question.size())
    elif request.method == 'POST' and form.validate():
        if request.form['answer'] == question.answer:
            flash('Correct!', 'positive')
            return random_question()
        else:
            flash('Wrong Answer!', 'negative')
            return render_template('question.html', question=question, form=form, amount=Question.size())
    else:
        return render_template('invalid_request.html')
Example #20
0
    def parse(self, string):
        super(QuestParser, self).parse(string)
        regex = self._format(r"({i}{w}{body})({a}{w}{body})({b}{w}{body})({c}{w}{body})({d}{w}{body})?({e}{w}{ebody})?{lb}")

        self._tokenize(string)
        for token in [t.strip() for t in self._tokens if t]:
            question = Question()
            match = re.search(regex, token, re.DOTALL | re.IGNORECASE)
            if match:
                question.stem = match.group(1).strip()
                question.options.append(match.group(2).strip())
                question.options.append(match.group(3).strip())
                question.options.append(match.group(4).strip())
                if match.group(5): question.options.append(match.group(5).strip())
                if match.group(6): question.options.append(match.group(6).strip())
                self._questions.append(question)

        return self
 def __call__(self, qid):
     self.question = Question(qid)
     self.qid = int(qid)
     self.qtext = self.question.text
     #self.answer = self.question.answer
     #self.category = self.question.category
     #self.sentences = self.question.get_sentences()
     #self.tokens = self.question.tokenize()
     self.features = defaultdict(dict)
Example #22
0
def jsubmit(question_id):

    hs = Historysession.get_current_history_session_by_user_id_quiz_id(current_user.id)
    session_id = hs.hsid

    current_app.logger.debug("jsubmit - " + str(question_id) + ", session_id - " + str(session_id))
    current_app.logger.debug("json in jsubmit - " + str(request.json))
    
    question = Question.get_active_question_by_id(question_id)

    if question:
        if current_user.id == question.user_id:
            schema = {
                    "type" : "object",
                    "properties" : {            
                        "id" : {"type" : "integer", "maxLength" : 8, "optional" : False},
                        "answers" : {"type": "array", "items": { "type" : "object", "properties": {
                                                                  "id" : {"type": "integer", "maxLength": 8, "optional": False},
                                                                  "value" : {"type" : "string", "enum" : ["T", "F", "N"], "optional" : False}
                                                                  }}, "maxItems" : 25, "optional" : True}
                        }
                    }

            v = Draft4Validator(schema)
            errors = sorted(v.iter_errors(request.json), key=lambda e: e.path)
            
            if len(errors) > 0:
                msg = u"Error in json format"
                current_app.logger.warning(msg)
                return jsonify({"status" : "ERROR", "message" : msg})
            else:            
                qid = request.json['id']
                received_answers = request.json['answers']

                correct = True
                for i in range(0, len(received_answers)):
                    item = received_answers[i]
                    aid = item['id']
                    value = item['value']

                    AnswerResult.add_answer_result(session_id, aid, question.revision_id, value)
        
                    correct = correct and (value == question.answers[i].correct)                    
                    
                    current_app.logger.debug("a# = " + str(i) + ", value = " + str(value) + ", answer = " + str(question.answers[i].correct) + ", correct = " + str(correct))

                QuestionResult.add_question_result(session_id, question.qid, question.revision_id, correct)
                db.session.commit()
                
                result = {'jstaus':'OK'}
                return jsonify(result)
        else:
            msg = auth_failure_message + u"submit this question"
            current_app.logger.warning(msg)
            return jsonify({"status" : "ERROR", "message" : msg})
    else:
        return jsonify({"status" : "ERROR"})
Example #23
0
def markdown_questionlist(qlist):
    qlist.formatted_questions = []
    for q in qlist.questions:
        if isinstance(q,Question):
            question = q
        else:
            question = Question.get(q)
        if question:
            question.formatted_text = mymarkdown(question.text)
            qlist.formatted_questions.append(question)
Example #24
0
    def get_default_question_objects():
        """
        Creates a list which is returned, this is to be used as default option in
        the list ```question_objects_list```

        Returns:
            list: A list with default question objects
        """
        question_list = list()
        question1 = Question(0, 'Choose A, B or C', False)
        question1.add_alternative(0, 'A', True)
        question1.add_alternative(1, 'B', False)
        question1.add_alternative(2, 'C', False)
        question_list.append(question1)
        question2 = Question(1, 'Choose D, E or F', False)
        question2.add_alternative(0, 'D', False)
        question2.add_alternative(1, 'E', False)
        question2.add_alternative(2, 'F', True)
        question_list.append(question2)
        return question_list
Example #25
0
def refresh_chapter(chapter):
    chapter.refresh = True
    chapter.put()
    query = Question.all().filter('chapter =', chapter)
    for q in query.run():
        q.refresh = True
        q.put
    query = Chapter.all().ancestor(chapter.key())
    for c in query.run():
        if c  != chapter:
            refresh_chapter(c)
Example #26
0
    def __init__(self):
        # Set up a clock for managing the frame rate.
        self.clock = pygame.time.Clock()

        self.x = -100
        self.vx = 10

        self.paused = False
        self.direction = -1

        self.circle_size = 150

        self.horse_change_semaphore = 3
        self.horse_change = 0

        self.font = pygame.font.SysFont('monospace', 36)
        self.lg_font = pygame.font.SysFont('monospace', 60)
        self.xlg_font = pygame.font.SysFont('monospace', 90)

        self.hurdle_number = 0

        self.points = 0

        self.question = Question()

        self.question_text_label = self.lg_font.render(
            str(self.question),
            1,
            Color.BLACK
        )

        self.question_label = self.font.render(
            'Hurdle #' + str(self.hurdle_number),
            1,
            Color.BLACK
        )

        self.score_label = self.lg_font.render(
            str(self.points),
            1,
            Color.BLACK
        )

        self.buttons = []

        self.songs = [
            self.get_sound_path('william_tell_overture_intro.wav'),
            self.get_sound_path('william_tell_overture_race.wav')
        ]

        self.death_sfx = pygame.mixer.Sound(self.get_sound_path('sad_trombone.wav'))
        self.jump_sfx = pygame.mixer.Sound(self.get_sound_path('success.wav'))
Example #27
0
    def parse(self, string):
        question = None
        self._tokenize(string)

        for token in self._tokens:
            s = re.match(r"^\s*\d+\.\s", token)
            if s and s.group():
                if question and len(question.options) > 0:
                    self._questions.append(question)
                question = Question()
                question.stem = token
                continue

            if question is not None:
                o = re.match(r"^\s*[\[\(]?[a-zA-Z][.):\]]\s", token)
                if o and o.group():
                    question.options.append(token)

        if question and len(question.options) > 0:
            self._questions.append(question)

        return self
Example #28
0
    def save_question(self, data, suffix=''):
        """
        Adds question to question collection stored in ``QuestionController`` class.
        :param data: JSON object that contains question in a format:
                data = {
                        'id': 1,
                        'text': 'Text',
                        'alternatives': [
                            {
                                'id': '1',
                                'text': 'Text',
                                'isCorrect': 'false'
                            },
                            {
                                'id': '2',
                                'text': 'Text2',
                                'isCorrect': 'false'
                            },
                            ...
                        ],
                        'hasDifficultyLevel': 'false'
                }
        :param suffix:
        :return: JSON object with the size of questions collection and last added question
        """
        try:
            q_id = int(data['id'])
            q_text = data['text']
            if data['hasDifficultyLevel']:
                q_has_diff_lvl = True
            else:
                q_has_diff_lvl = False

            new_question = Question(q_id, q_text, q_has_diff_lvl)

            for i in range(0, len(data['alternatives'])):
                # TODO: Note that the called function in CreatedAnswers throws error
                # TODO: See comment in Question::add_alternative
                if not new_question.add_alternative(i, data['alternatives'][i]['text'], data['alternatives'][i]['isCorrect']):
                    return {'status': 'Not saved', 'message': 'Alternative is not valid'}

            if new_question.is_valid:
                if q_id < 0:
                    new_question.set_question_id(len(self.questions_json_list))
                    self.questions_json_list.append(new_question.to_json())
                else:
                    for i in range(0, len(self.questions_json_list)):
                        if self.questions_json_list[i]['id'] == q_id:
                            del self.questions_json_list[i]
                            self.questions_json_list.insert(i, new_question.to_json())

                num_questions = len(self.questions_json_list)
                question = self.questions_json_list[num_questions - 1]
                return {'status': 'successful', 'numQuestions': num_questions, 'question': question}
            else:
                return{'status': 'unsuccessful', 'message': 'Question data is not valid'}
        except Exception as ex:
            return {'status': 'unsuccessful', 'message': str(ex)}
Example #29
0
    def parse(self, string):
        super(StemsParser, self).parse(string)
        si = r'[0-9]+\.\s+'
        sb = r'.+?[?:.]\n\n'
        o  = r'.+'
        regex = r"({si}{sb})({o})".format(
            si=si, sb=sb, o=o,
            )

        self._tokenize(string)
        for token in self._tokens:
            question = Question()
            match = re.search(regex, token, re.DOTALL)
            if match:
                question.stem = match.group(1).strip()
                for option in match.group(2).split('\n'):
                    if option:
                        question.options.append(option.strip())
                    else:
                        break
                self._questions.append(question)

        return self
Example #30
0
    def create_object_from_json(self):
        """
        Creates a list of Question objects from the JSON dictionary questions_json_list

        Returns:
            list: List containing objects of the class Questions

        """
        question_list = list()
        # loop through all the json questions and add them to the list
        for json_question in self.questions_json_list:
            q_id = json_question['id']
            q_text = json_question['question']
            q_diff_lvl = json_question['has_difficulty_level']
            question = Question(q_id, q_text, q_diff_lvl)
            # loop through all the alternatives for this question and add them
            for alt in json_question['alternatives']:
                a_id = alt['id']
                a_text = alt['text']
                a_is_correct = alt['isCorrect']
                question.add_alternative(a_id, a_text, a_is_correct)
            # add the question object to the list
            question_list.append(question)
        return question_list