Example #1
0
    def load_from_db(self, filename, id):
        result = db_select(
            filename, """SELECT ID, START, END, COURSE, SEMESTER, STATE
										FROM SURVEYS
										WHERE ID = """ + str(id))[0]
        if not result:
            return None

        self._id = result[0]
        self._start = result[1]
        self._end = result[2]
        self._course = find_course(result[3], result[4])
        self._course.survey = self
        self._questions = []
        qids = [
            x[0] for x in db_select(
                filename,
                """SELECT QUESTIONID FROM INCLUDE WHERE SURVEYID = """ +
                str(id) + " ORDER BY POSITION")
        ]
        for qid in qids:
            newQuestion = Question()
            newQuestion.load_from_db(filename, qid)
            self._questions.append(newQuestion)

        return self
Example #2
0
def createQuestions():
    global numRes                                                                               # numRes stores the number of reponses for this current question being created
    restore = []                                                                                # restore is a list that is used to carry information between page reloads so that a user does not have to retype entries into the input fields after requesting a new response box etc.
    if request.method == "POST":                                                                    
        if (request.form["bt"] == "back"):                                  
            numRes = 1
            return redirect(url_for("landing"))
        if (request.form["bt"] == "add_response"):                                              # If the user requests to add a response, then reload this page with numRes += 1
            restore.append(request.form["question"])                                            # Current input is also saved for when page is reloaded 
            for i in range(0, numRes):
                restore.append(request.form[str(i)])                                                
            numRes += 1
        if (request.form["bt"] == "submit_question"):                                           # If the user requests to submit the questions, then append responses list with the entry in the request form. Do this for the number of responses that this question has.
            if (request.form["question"] != ""):
                responses = []
                for i in range(0, numRes):
                    if (request.form[str(i)] != ""):
                        responses.append(request.form[str(i)])
                newQuestion = Question(1, request.form["question"], responses)                  # Create a new question object and construct with given input
                server.qaaCSV.append(newQuestion.getCSVRow())                                   # Tell the qaaCSV object to write this new question into the relevent csv file
                numRes = 1                                                                      # Reset the number of responses on this page to 1
                flash("Your question was successfully added")                                   # Flash the user a message that this request was successful
                return redirect(url_for("landing"))                                             # After the question is added - the user is redirected to the landing page
            else: 
                flash("Question box must have text")
    return render_template("createQuestions.html", num = numRes, restore = restore, is_authenticated = server.user_authenticated)    
def read_all_questions():
    question_list = []
    for questionID in [
            i[0]
            for i in db_select(QUESTIONS_FILENAME, "SELECT ID FROM QUESTIONS")
    ]:
        question = Question()
        question.load_from_db(QUESTIONS_FILENAME, questionID)
        question_list.append(question)
    return question_list
Example #4
0
    def test_survey_correct_ordered_questions(self):
        survey = Survey()

        data = {
            'course':
            'COMP1531',
            'semester':
            '17s2',
            'start':
            '2017-10-25',
            'end':
            '2017-10-26',
            'surveyData':
            json.dumps([{
                'questionNum': -1,
                'questionText': 'Example text',
                'multi': 'false',
                'options': ['yes', 'no'],
                'text': 'false',
                'mandatory': 'true'
            }, {
                'questionNum': -1,
                'questionText': 'Example text 2',
                'multi': 'false',
                'options': ['yes', 'no'],
                'text': 'false',
                'mandatory': 'true'
            }])
        }

        survey.load_from_dict(data)

        question1Dict = {
            'questionNum': -1,
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'true'
        }

        question2Dict = {
            'questionNum': -1,
            'questionText': 'Example text 2',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'true'
        }

        question1 = Question()
        question1.load_from_dict(question1Dict)

        question2 = Question()
        question2.load_from_dict(question2Dict)

        self.assertEqual(survey.questions[0].matches(question1), True)
        self.assertEqual(survey.questions[1].matches(question2), True)
Example #5
0
    def load_from_dict(self, data):
        self._course = find_course(data['course'], data['semester'])
        self._course.survey = self

        startData = data['start'].split('-')
        self._start = datetime.date(int(startData[0]), int(startData[1]),
                                    int(startData[2]))
        endData = data['end'].split('-')
        self._end = datetime.date(int(endData[0]), int(endData[1]),
                                  int(endData[2]))

        self._questions = []
        for question in json.loads(data['surveyData']):
            newQuestion = Question()
            newQuestion.load_from_dict(question)
            self._questions.append(newQuestion)
Example #6
0
    def test_create_mandatory_question(self):
        question = Question()

        data = {
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'true'
        }

        question.load_from_dict(data)

        write_id = question.write_to_db(DATABASE_FILENAME)

        question = None

        question = Question()
        question.load_from_db(DATABASE_FILENAME, write_id)

        self.assertEqual(question.get_mandatory(), True)
def write_question(form):
    question = Question()
    question.load_from_dict(form)
    if int(form['saved_id']) != -1:
        return question.update_db(QUESTIONS_FILENAME, int(form['saved_id']))
    else:
        return question.write_to_db(QUESTIONS_FILENAME)
Example #8
0
    def test_values_read_from_dictionary(self):

        question = Question()

        data = {
            'questionNum': 20,
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'true'
        }

        question.load_from_dict(data)

        self.assertEqual(question.get_id(), 20)
        self.assertEqual(question.get_question_text(), 'Example text')
        self.assertEqual(question.get_type(), 'single')
        self.assertEqual(question.get_mandatory(), True)
        self.assertEqual(question.get_options()[0], 'yes')
Example #9
0
    def test_add_option(self):

        question = Question()

        data = {
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'false'
        }

        question.load_from_dict(data)

        self.assertEqual(question.get_options().count('maybe'), 0)
        question.add_option(Option(id=-1, text='maybe'))
        self.assertEqual(question.get_options().count('maybe'), 1)
Example #10
0
    def test_turn_invisible(self):

        question = Question()

        data = {
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'false'
        }

        question.load_from_dict(data)

        self.assertEqual(question.get_visible(),
                         True)  #A new question will always be visible
        question.turn_invisible()
        self.assertEqual(question.get_visible(), False)
Example #11
0
    def test_visibility_toggle(self):
        question = Question()

        data = {
            'questionNum': 20,
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'true'
        }

        question.load_from_dict(data)

        self.assertEqual(question.get_visible(),
                         True)  #Any question loaded from dictionary is visible
        question.turn_invisible()
        self.assertEqual(question.get_visible(), False)
Example #12
0
def survey(key):
    valid = True                                                                                    # 'valid' boolean is used to check whether <key> in the web address is valid
    s = []                                                                                          # 's' will contain the information about the survey to be completed
    row = server.surveyCSV.readKeyedRow(key)                                                        # Read in from csv the row that contains the given <key>
    if row == []:                                                                                   # If row is empty then no csv row had the given <key>. Hence invalid key
        valid = False
    if valid:                                                                                       # If the key was valid then create the appropriate survey object
        s = Survey(row[1], row[2], row[3], row[4], row[5], row[6])                                  

    allQaa = []                                                                                     # Load all the questions from pool. TODO Later only load required questions.
    for r in server.qaaCSV.readRow():                                                               # Questions have to be loaded since they are needed to complete the survey.
        q = Question(1, r[0], r[1:])
        allQaa.append(q)   

    if (request.method == "POST"):                                                                  # At the moment empty responses can be submitted. TODO.
        responses = []
        for i in range(0, s.getNumQuestions()):
            responses.append(request.form[str(i)]) #only store solutions
        surveyResponse = CSV("csv/surveyResponse_"+str(row[0])+".csv")
        surveyResponse.append(responses)                              # Also write the responses into the csv file
        flash("Your response has been recorded")
    return render_template("survey.html", currentSurvey = s, questions = allQaa, valid = valid)
Example #13
0
    def write_to_db(self, filename):
        existing_questions = []
        for qid in [
                x[0] for x in db_select(filename, "SELECT ID FROM QUESTIONS")
        ]:
            question = Question()
            question.load_from_db(filename, qid)
            existing_questions.append(question)

        survey_ids = [
            i[0] for i in db_select(filename, "SELECT ID FROM SURVEYS")
        ]
        if survey_ids == []:
            max_survey_id = 0
        else:
            max_survey_id = max(survey_ids)
        db_execute(
            filename,
            """INSERT INTO SURVEYS (ID, START, END, COURSE, SEMESTER, STATE) 
								VALUES ("{0}", "{1}", "{2}", "{3}", "{4}", "{5}")
								""".format(str(max_survey_id + 1), str(self._start), str(self._end),
                   self._course.name, self._course.semester, str(self._state)))

        i = 1
        for question in self._questions:
            exists = False
            for existing_question in existing_questions:
                if not exists and question.matches(existing_question):
                    db_execute(
                        filename,
                        """INSERT INTO INCLUDE (SURVEYID, QUESTIONID, POSITION)
											VALUES ("{0}", "{1}", "{2}")""".format(
                            str(max_survey_id + 1),
                            str(existing_question.get_id()), i + 1))
                    exists = True
            if not exists:
                write_id = question.write_to_db(filename)
                db_execute(
                    filename,
                    """INSERT INTO INCLUDE (SURVEYID, QUESTIONID, POSITION)
										VALUES ("{0}", "{1}", "{2}")""".format(str(max_survey_id + 1),
                                                 str(write_id), i + 1))
            i += 1

        return max_survey_id + 1
Example #14
0
def modifySurvey(written_row):
    global numQues                                                                          # numQues stores the number of questions that are currently required for this survey
    restore = []                                                                            # restore is a list that allows user input to be transferred/saved across page requests

    if (int(written_row) >= server.surveyCSV.numRow() or int(written_row) < 0):             # If index requested (<written_row>) will be out of range, change it
        return redirect(url_for("modifySurvey", written_row = server.surveyCSV.numRow() - 1))

    row = server.surveyCSV.readOneRow(int(written_row))                                     # Read the currently-being-modified survey into a survey object
    s = Survey(row[0], row[1], row[2], row[3], row[4], row[5])                              # Note that questions are reset when a survey is modified          
    allQaa = []                                                                             # Read every question in pool from the csv into question objects. Neccessary as this survey may include any of these questions at the users choice
    for row in server.qaaCSV.readAllRows():
        q = Question(1, row[0], row[1:])
        allQaa.append(q)                                                                          
    
    if (request.method == "POST"):
        if (request.form["bt"] == "back"):
            numQues = 1
            return redirect(url_for("viewSurveys"))
        if (request.form["bt"] == "add_question"):                                          # If the user requests to add another question to the survey, increase numRes and reload
            for i in range(0, numQues):                                                             
                restore.append(int(request.form[str(i)]))                                   # Also current input saved for page reload
            numQues += 1
        if (request.form["bt"] == "submit_survey"):                                         # If the user requests to submit this survey
            s.clearQuestions()                                                              # Clear any current questions that the survey may have had
            for i in range(0, numQues):                                                     # Append the questions from the HTML form inputs onto this survey object
                s.addQuestion(request.form[str(i)])                                                
                restore.append(int(request.form[str(i)])) 
            server.surveyCSV.replaceRow(int(written_row), s.getCSVRow())                    # Replace the row that contained the old version of this survey with the new survey
            flash("Survey was successfully saved")
            numQues = 1                                                                     # Reset the number of questions for this survey to 1 for subsequent surveys
            return redirect(url_for("viewSurveys"))
    else:
        restore = list(s.getQuestions())  
        numQues = len(restore)

    return render_template("modifySurvey.html", currentSurvey = s, qp = allQaa, numQues = numQues, written_row = written_row, restore = restore, is_authenticated = server.user_authenticated)
Example #15
0
from questionClass import Question

question_prompts = [
    'What color are apples? \n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
    'What color are Bananas? \n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
    'What color are strawberries? \n(a) Yellow\n(b) Red\n(c) Blue\n\n'
]

#a list of prompts and answers
questions = [
    Question(question_prompts[0], 'a'),
    Question(question_prompts[1], 'c'),
    Question(question_prompts[2], 'b')
]
'''
run_test will receive a list of prompts&answers.
displays the promtps and check if the user's answers are correct.
track the answers and displays how many questions were correct once finished.
'''


def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
    print('You got ' + str(score) + '/' + str(len(questions)) + ' correct.')


run_test(questions)
def remove_question(id):
    question = Question()
    question.load_from_db(QUESTIONS_FILENAME, id)
    question.turn_invisible()
    question.update_db(QUESTIONS_FILENAME, id)
Example #17
0
    def test_edit_saved_question(self):
        question = Question()

        data = {
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'false'
        }

        question.load_from_dict(data)

        write_id = question.write_to_db(DATABASE_FILENAME)

        question = None

        question = Question()

        data = {
            'questionNum': write_id,
            'questionText': 'Example other text',
            'multi': 'true',
            'options': ['maybe', 'not'],
            'text': 'false',
            'mandatory': 'true'
        }

        question.load_from_dict(data)
        question.update_db(DATABASE_FILENAME, write_id)

        question = None

        question = Question()

        question.load_from_db(DATABASE_FILENAME, write_id)

        self.assertNotEqual(question.get_question_text(), 'Example text')
        self.assertEqual(question.get_question_text(), 'Example other text')
        self.assertNotEqual(question.get_type(), 'single')
        self.assertEqual(question.get_type(), 'multi')
        self.assertNotEqual(question.get_options(), ['yes', 'no'])
        self.assertEqual(question.get_options(), ['maybe', 'not'])
        self.assertNotEqual(question.get_mandatory(), False)
        self.assertEqual(question.get_mandatory(), True)
Example #18
0
    def test_create_text_question_no_options(self):
        question = Question()

        data = {
            'questionText': 'Example text',
            'multi': 'false',
            'options': [],
            'text': 'true',
            'mandatory': 'false'
        }

        question.load_from_dict(data)

        write_id = question.write_to_db(DATABASE_FILENAME)

        question = None

        question = Question()
        question.load_from_db(DATABASE_FILENAME, write_id)

        self.assertEqual(question.get_type(), 'text')
        self.assertEqual(question.get_options(), [])
Example #19
0
    def test_edit_question_type(self):
        question = Question()

        data = {
            'questionText': 'Example text',
            'multi': 'false',
            'options': ['yes', 'no'],
            'text': 'false',
            'mandatory': 'false'
        }

        question.load_from_dict(data)

        self.assertEqual(question.get_type(), 'single')
        question.toggle_multi()
        self.assertEqual(question.get_type(), 'multi')
        question.toggle_multi()
        self.assertEqual(question.get_type(), 'single')