Esempio n. 1
0
async def qstart(ctx, *args):
    global QUIZ
    await ctx.message.delete()

    if not QUIZ and len(args) == 3:
        name, song_count, diff_or_name = args
    else:
        return

    try:
        song_count = int(song_count)
    except Exception:
        await ctx.message.delete()
        return

    try:
        difficulty = int(diff_or_name)
        QUIZ = quiz.Quiz(name, song_count, difficulty, ctx.channel)

    except Exception:
        QUIZ = quiz.Quiz(name, song_count, 1, ctx.channel)
        QUIZ.profile = diff_or_name

    msg = info_embed(f'Starting quiz: {QUIZ}', f"""
        {QUIZ.songs_left} rounds left. 
        """)

    await QUIZ.channel.send(embed=msg)
    await QUIZ.send_to_all(embed=msg)
Esempio n. 2
0
def append_daily_data(snqtree_path,
                      raffle_week_name,
                      raffle_day_name,
                      quiz_length=2,
                      random=False):
    stdtab_path = snqtree_path + "/stdtab"
    snq_dir = snqtree_path + "/questions"
    raffle_dir = snqtree_path + "/raffle"
    raffle_week_path = raffle_dir + "/" + raffle_week_name

    std_list = filehandler.read_student_table(snqtree_path)
    question_list = filehandler.read_questions(snq_dir)

    filehandler.init_raffle_week(snqtree_path, raffle_week_name)
    for student in std_list:
        student.give_quiz(quiz.Quiz(question_list, quiz_length))
        print(student.name)
        print(
            "-----------------------------------------------------------------"
        )
        student.student_quiz.run_quiz(random)
        num_raffle_tickets = student.student_quiz.grade_quiz()
        filehandler.write_daily_data(snqtree_path, raffle_week_name,
                                     raffle_day_name, student)
        for i in range(num_raffle_tickets):
            filehandler.add_to_raffle(snqtree_path, raffle_week_name,
                                      student.name)
    def __init__(self, email, password, thread_fbid, config):
        self.stats = stats
        self.config = config
        self.commands = config[consts.COMMANDS]

        self.stats = stats.Stats(STATS_FILE)

        fbchat.Client.__init__(self, email, password, thread_fbid, True, None)
        threads = self.getThreadList(0)
        for item in threads:
            if item.thread_fbid == thread_fbid:
                thread = item

        # Extracts ids from participants and gets full data
        users = []
        for user_id in thread.participants:
            if user_id.startswith("fbid:"):
                users.append(user_id[5:])
        self.full_users = self.getUserInfo(users)

        self.annoy_list = self.stats.vals["annoy_list"]
        self.onseen_list = self.stats.vals["onseen_list"]

        self.mquiz = quiz.Quiz(config["quiz_file"], self.stats)
        self.__quiz_question_count = 0
        self.__quiz_timeout_set = False
        self.__quiz_timer = None
Esempio n. 4
0
def get_quiz(quiz_id):
    global quizs
    q = quizs.get(quiz_id, None)
    if q is None:
        q = quiz.Quiz(quiz_id)
        quizs[quiz_id] = q
    return q
Esempio n. 5
0
def quiz_start(msg_sender):
    if fake_bot.register_activity(msg_sender.puid,'quiz'):
        #msg_sender.send("开始答题")
        msg_sender.send("start")
        quiz.Quiz(fake_bot, msg_sender)
    else:
        #msg_sender.send("当前有其他活动进行中")
        msg_sender.send("...")
Esempio n. 6
0
 def command_start(self, bot, update):
     chat_id = update.message.chat_id
     if chat_id not in self.SESSIONS.keys():
         self.messenger = interfaces.TelegramMessenger(bot, self.logger)
         self.SESSIONS[chat_id] = session.Session(chat_id,
                                                  self.config_instance,
                                                  self.logger)
         self.SESSIONS[chat_id].set_messenger(self.messenger)
         self.SESSIONS[chat_id].quiz = quiz.Quiz(self.SESSIONS[chat_id])
Esempio n. 7
0
def select_quiz(author, action_items, command):
    """
    Allows user to select quiz from numbered list.

    :param author: user selecting quiz.
    :param action_items: the dict of action items.
    :param command: the user's parameter input for number selection.
    :return:
    """
    action = action_items.get(author)

    if isinstance(action, quiz.SelectQuiz):
        file_no = command[1:]

        try:
            file_no = int(file_no)
        except ValueError:
            file_no = ""

        if isinstance(file_no, int):
            files = message.get_files()

            if file_no <= len(files):
                try:
                    action_items[author] = quiz.Quiz(files[file_no - 1])
                    reply = "We are ready to go, @everyone, use `?join` to add yourself to the quiz!\n" \
                            "When we're ready to go, the quiz-master can use `?start` :call_me:"
                # Where the file is invalid.
                except Exception:
                    reply = "Sorry, that quiz file is not valid :worried:\nTry another quiz using `?[number]`."

            else:
                reply = "Please select a file number within the range displayed."

        else:
            reply = "Please select a quiz from the list using its number :upside_down:"

    else:
        reply = None

    return reply
Esempio n. 8
0
def handle_answer_submission():
    print(request.get_json())
    j = request.get_json(force=True)
    j['username'] = current_user.get_id()
    TRACE(json.dumps(j, indent=4, ensure_ascii=False))
    s = quizObject.handle_submission(j)
    return ('', 200) if s else ('', 400)


if __name__ == "__main__":
    #    compile_quiz(os.path.join(config.basedir, "example_quiz", "quiz"),
    #            os.path.join(config.basedir, "quiz", "quiz.json"))
    parser = arg.ArgumentParser(description='Serve the GraphVisual website.')
    # Flags go here
    parser.add_argument('--backup')  # TODO KYLE please fill in here
    parser.add_argument(
        '--reset',
        action='store_true',
        help=
        "Whether the server should delete the database upon startup (debug flag)"
    )
    # End flags
    args = parser.parse_args()
    if args.reset:
        shutil.rmtree('db', True)
        compile("../quiz/questions/", "../quiz/graph_quiz.json")
    quizObject = quiz.Quiz()
    login_manager.init_app(app)
    #app.run(host='localhost', port='8080')#, ssl_context='adhoc')
    app.run(host='0.0.0.0', port='8081', ssl_context='adhoc')
Esempio n. 9
0
from flask import Flask, render_template, request
import quiz, imageSourcer

app = Flask(__name__)

mainQuiz = quiz.Quiz(0)

#### WEB STUFF ####


@app.route("/")
def initialise():
    return render_template('signup.html')


@app.route("/loggedin")
def intro():
    return render_template('intro.html')


@app.route("/start")
def renderQuestion(valid):
    (imgSol, imgIndex) = mainQuiz.roverImages[mainQuiz.getIndex()]
    imgRequest = imageSourcer.ImageSourcer("Curiosity", imgSol, "navcam",
                                           imgIndex)
    x = imgRequest()
    link = imgRequest.receiveImages()
    quizData = mainQuiz.currentQuizState()
    return render_template('screenload.html',
                           challenge=quizData[0],
                           optA=quizData[1],
#Author : cF
#Contact : gg.gg/cryptosurge
import discord
import sys

import quiz

client = discord.Client()
quiz = quiz.Quiz(client)


@client.event
async def on_ready():
    print('Logged in as: ' + client.user.name)
    print('User ID: ' + client.user.id)
    print('------')


@client.event
async def on_message(message):
    if message.content.startswith('$$$exitme'):
        await client.send_message(message.channel, 'Leaving server. BYE!')
        await client.close()
        exit()

    elif (message.content.startswith('!stop')
          or message.content.startswith('$stop')):
        await quiz.stop()
    elif (message.content.startswith('$resetscore')):
        await quiz.reset()
    elif (message.content.startswith('$start')
Esempio n. 11
0
def main():
    print_header()
    game = quiz.Quiz()
    game.take_quiz()
Esempio n. 12
0
def main():
    quiz_info = get_quiz_file()
    q = quiz.Quiz(quiz_info[0], quiz_info[1])
    correct = start_quiz(q)
    print("\nYou got %s out of %s correct." %
          (str(correct[0]), str(correct[1])))
Esempio n. 13
0
    def update(self):
        """This method updates all of the database entries, deletes questions that have been removed and adds questions that have been added."""
        import quiz
        # Get the quiz details from the entry boxes.
        title = self.nameString.get().strip()
        subject = self.subjectString.get()
        examBoard = self.examBoardString.get()
        difficulty = self.difficultyString.get()
        tags = self.tagsString.get()
        # Title length check, show an error message if it's too long or too short.
        if (len(title) < 3):
            # If the title is too short, display an error message.
            tkmb.showerror(
                "Title error",
                "Quiz title is too short, it should be at least 3 characters long (currently: "
                + str(len(title)) + ").",
                parent=self.window)
            return
        if (len(title) > 70):
            # If the title is too long, display an error message.
            tkmb.showerror(
                "Title error",
                "Quiz title is too long, it should be at most 70 characters long (currently: "
                + str(len(title)) + ").",
                parent=self.window)
            return
        # Regular expression to check if the title has any invalid characters.
        quizTitleRegex = re.compile('[^a-zA-Z0-9\.\-\? ]')
        # Running the title through the regular expression.
        reducedTitle = quizTitleRegex.sub("", title)
        if (reducedTitle != title):
            # If the title is changed by the regular expression, then it contained invalid characters and so has failed the format check. Show an error message to the user.
            tkmb.showerror(
                "Title error",
                "Quiz title contains invalid characters, it should only contain english letters, numbers, spaces, dashes, question marks, or full stops/periods.",
                parent=self.window)
            return
        # Presence check on difficulty drop-down entry box.
        if (not difficulty):
            # If the difficulty has not been set, show an error message.
            tkmb.showerror("Difficulty error",
                           "No difficulty has been set for this quiz.",
                           parent=self.window)
            return
        # Length check on tag entry.
        if (len(tags) > 150):
            # If the tags entry is too long, show an error message.
            tkmb.showerror(
                "Tags error",
                "Tag list is too long, it should be at most 150 characters long (currently: "
                + str(len(tags)) + ").",
                parent=self.window)
            return
        # Reformatting tags in case the user hasn't entered in the correct format, by removing all whitespace that would be adjacent to a comma.
        tagList = []
        for i in tags.split(","):  # Convert the CSV string to a list
            # For each tag,
            if (i.strip() == ""):
                # If (after removing preceeding and trailing whitespace) there is no tag, skip it.
                continue
            # Else, remove the preceeding and trailing whitespace and turn the tag to lower case, and add it to the tag list.
            tagList.append(i.strip().lower())
        # Re-creating the tags CSV string in case the last one had excess commas or had excess whitespace.
        tags = ",".join(tagList)
        # Validating all the questions.
        questions = []
        for i in self.questions.keys():
            # For each question, get all the entered fields.
            questionText = self.questions[i][0].get()
            correctAnswer = self.questions[i][1].get()
            otherAnswers = []
            answer2 = self.questions[i][2].get()
            answer3 = self.questions[i][3].get()
            answer4 = self.questions[i][4].get()
            # If answers have been entered, add them to the wrong answer list for that question.
            if (answer2):
                otherAnswers.append(answer2)
            if (answer3):
                otherAnswers.append(answer3)
            if (answer4):
                otherAnswers.append(answer4)
            hint = self.questions[i][5].get()
            help = self.questions[i][6].get()
            # Create a question object and check if it is valid.
            q = quiz.Question(-1, questionText, correctAnswer, otherAnswers,
                              -1, hint, help)
            # Check if the question is valid, errorText will be None if there are no errors, else it will be a string.
            errorText = q.validate()
            if (errorText):
                # If it's invalid, show an error, and then return.
                tkmb.showerror("Question error",
                               "Question (\"" + questionText +
                               "\") has error: " + errorText,
                               parent=self.window)
                return
            # If the question passes all the checks, add it to the questions list.
            questions.append(q)
        if (len(questions) < 2):
            # If there are less than 2 questions, show an error, and the return.
            tkmb.showerror("Question error",
                           "Quiz should have at least 2 questions.",
                           parent=self.window)
            return
        # Get the subject and/or exam board ID from the text entry.
        subjectID = None
        examBoardID = None
        # It will only get them if the field has text in it, that isn't "None".
        if (subject):
            # If the subject has been set, look up its ID.
            subjectID = self.parent.inverseSubjectDictionary.get(subject, None)
        if (subjectID != None):
            # Convert it to a float to prevent errors with PyODBC in Python 3.3.
            subjectID = float(subjectID)

        if (examBoard):
            # If the exam board has been set, look up its ID.
            examBoardID = self.parent.inverseExamboardDictionary.get(
                examBoard, None)
        if (examBoardID != None):
            # Convert it to a float to prevent errors with PyODBC in Python 3.3.
            examBoardID = float(examBoardID)

        # Check if any other quizzes have the same title.
        quizzesWithSameTitle = self.parent.database.execute(
            "SELECT * FROM `Quizzes` WHERE `QuizName`=?;", title)
        if (len(quizzesWithSameTitle) > 0
                and quizzesWithSameTitle[0][0] != self.quiz.id):
            # If another quiz exists with the same title that isn't the quiz currently being edited, show an error message.
            tkmb.showerror("Quiz error",
                           "Quiz name is already in use.",
                           parent=self.window)
            return

        # Create the quiz object, so we can generate a hash.
        quizObject = quiz.Quiz(None, None, title, tags,
                               int(subjectID) if subjectID else None,
                               int(examBoardID) if examBoardID else None,
                               difficulty, questions)

        # Update the quiz record.
        self.parent.database.execute(
            "UPDATE `Quizzes` SET QuizName = ?, SubjectID = ?, ExamboardID = ?, AmountOfQuestions = ?, TagList = ?, Difficulty = ?, Hash = ? WHERE QuizID = ?;",
            title, subjectID, examBoardID, float(len(questions)), tags,
            float(difficulty), quizObject.getHash(self.parent),
            float(self.quiz.id))
        # Remove the old questions
        self.parent.database.execute("DELETE FROM `Questions` WHERE QuizID=?;",
                                     float(self.quiz.id))
        # Add the new questions to the database.
        for i in questions:
            i.quizID = self.quiz.id
            i.addToDatabase(self.parent.database)

        # Reload the quiz list on the quiz browser to show the new quiz.
        self.parent.refreshList()
        # Exit the window upon successfully creating the quiz.
        self.window.destroy()
Esempio n. 14
0
def main():
    new_quiz = quiz.Quiz("./questions.txt", "./answers.txt")
    print("You scored %d out of %d points." %
          (ask_questions(new_quiz), len(new_quiz.get_questions())))
Esempio n. 15
0
def main():
    lessonNumber = int(input('Which lesson would you like to work in? '))
    Q = quiz.Quiz(lessonNumber)