Пример #1
0
def store_uploaded_file(problem_id, base_path):
    student_upload = input.get_input(problem_id)
    filename = input.get_input("{}:filename".format(problem_id))
    filename_with_path = Path(base_path) / filename

    # Stores a copy of this file inside "student" folder
    with open(filename_with_path, 'w+') as fileUpload:
        fileUpload.write(student_upload.decode('utf-8'))
        fileUpload.close()

    return filename_with_path
Пример #2
0
def checkStack(q,correct):
    stack=getStack(input.get_input(q))
    response = ""
    errors = 0
    grade = 0
    if(stack == correct):
        grade=100
        feedback.set_problem_result("success", q)
        feedback.set_problem_feedback(response, q)
        return grade
    else:
        if not (stack.startswith( correct[0:1] ) ):
            response += "The top-label of your stack is incorrect.\n"

        if not (stack.endswith( correct[-2:] ) ):
            response += "The bottom label of your stack is incorrect.\n"

        clist=correct.split(':')
        slist=stack.split(':')
        if len(slist) > len(clist):
            response += "Your answer contains more labels in its stack than the correct one.\n"
        if len(slist) < len(clist):
            response += "Your answer contains fewer labels in its stack than the correct one.\n"
            
        feedback.set_problem_result("failed", q)
        response += "Your answer to this question is incorrect.\n"
        feedback.set_problem_feedback(response, q)
        return grade
Пример #3
0
 def code_2_string(problem_id):
     student_upload = input.get_input(problem_id)
     # Extract the given code into a single String file with no space, leading stuff, etc...
     # FYI: It is done to simplify the verification as statements in java could be on multiple lines
     return student_upload.strip().replace("\n",
                                           '').replace("\t",
                                                       '').replace(" ", '')
Пример #4
0
def checkNPaths(q, correct):
    path = getPath(input.get_input(q))
    list = path.split(',')
    clist = correct.split(',')
    errors = 0
    grade = 0
    response = ""

    if (len(list) != len(clist)):
        feedback.set_problem_result("failed", q)
        response += "Your answer to this question is incorrect. There are {} paths from this router.\n".format(
            len(clist))
        feedback.set_problem_feedback(response, q)
        return 0

    for l in clist:
        if not (l in list):
            feedback.set_problem_result("failed", q)
            response += "Your answer to this question is incorrect.\n"
            feedback.set_problem_feedback(response, q)
            return 0

    feedback.set_problem_result("success", q)
    feedback.set_problem_feedback(response, "q1")
    return 100
Пример #5
0
def checkSinglePath(q, correct):
    path = getPath(input.get_input(q))
    response = ""
    errors = 0
    grade = 0
    if (path == correct):
        grade = 100
        feedback.set_problem_result("success", q)
        feedback.set_problem_feedback(response, q)
        return grade
    else:
        if not (path.startswith(correct[0:1])):
            response += "Your answer does not start with {}\n".format(
                correct[0:1])

        if not (path.endswith(correct[-2:])):
            response += "Your answer does not end with {}\n".format(
                correct[-2:])
        if (',' in path):
            response += "There is only one path from this router.\n"

        feedback.set_problem_result("failed", q)
        response += "Your answer to this question is incorrect. There is only one path from this router to the destination.\n"
        feedback.set_problem_feedback(response, q)
        return grade
def get_random(i=0, upper=1000):
    """Return a random number.

    :optional param i: The index of the random number of INGInious.
    :optional param upper: The upper bound of the random number. The default is 1000
    """

    return int(input.get_input("@random")[i] * upper)
def get_single_line_answer(problem_id):
    """Return the answer of the student to the question identified by the argument.
    Return "NONE" if the answer was "None", otherwise return a list of string which
    is the answer of the student, split by the coma."""

    answer = input.get_input(problem_id).upper()
    if answer == "NONE":
        return answer
    answer = ''.join(answer.split())  # remove spaces
    return answer.split(",")
Пример #8
0
def contains_prohibited_statement_in_input(prohibited_array, problem_id):
    student_upload = input.get_input(problem_id)
    # Extract the given code into a single String file with no space, leading stuff, etc...
    # FYI: It is done to simplify the verification as statements in java could be on multiple lines
    source_code_as_string = student_upload.strip().replace("\n", '').replace(
        "\t", '').replace(" ", '')

    # if any match , student tried to cheat
    return any(
        prohibited_statment.strip().replace(" ", '') in source_code_as_string
        for prohibited_statment in prohibited_array)
def get_multiple_line_answer(problem_id):
    """Return the answer of the student to the question identified by the argument.
    Return "NONE" if the answer was "None", otherwise return a bidimensional list,
    where the the first list is a split of the answer according to new lines, and
    the second list according to comas. (Example: "1,2,3\n4,4,6" will return 
    [[1, 2, 3], [4, 5, 6]])"""

    answer = input.get_input(problem_id).upper()
    if answer == "NONE":
        return answer
    return [''.join(a.split()).split(",") for a in answer.split("\n")]
Пример #10
0
def initTranslations():
    """ Initialise la fonction _() qui permettra de traduire les chaines de caractère. 

        Crée un fichier contenant le code de langue afin que le code Java puisse le récupérer plus tard
    """
    import gettext
    current_locale = input.get_input("@lang")
    with open("student/lang","w+") as f: # This file will be used by Java to get the correct lang
        f.write(current_locale)
    try: # Try to load translations.
        language = gettext.translation ('run', 'student/Translations/translations_run', [current_locale])
        _ = language.gettext
    except OSError:
        _ = gettext.gettext # This will use String id if an error occurs
    return _
Пример #11
0
def main():
    #####################################
    #   Load feedback task settings     #
    #####################################

    feedback_settings = config.config_file_to_dict(FEEDBACK_REVIEW_PATH)
    print("FEEDBACK SETTINGS LOADED")

    #####################################
    #   Check prohibited statements      #
    #####################################

    feedback.handle_prohibited_statements(feedback_settings)
    print("NO PROHIBITED STATMENT(S) DETECTED")

    #####################################
    #       Apply templates             #
    #####################################

    # we have a folder where we have only these files
    helper.apply_templates(PATH_TEMPLATES)
    print("TEMPLATE(S) APPLIED")

    #####################################
    #   CREATE A CLASSES FOLDER         #
    #####################################

    Path(PATH_CLASSES).mkdir(parents=True, exist_ok=True)
    print("SET UP CLASSES FOLDER FOR COMPILATION")

    #####################################
    #  EXTERNAL LIBRARIES TO USE  ?     #
    #####################################

    libs = helper.libraries(feedback_settings["external_libraries"])

    #####################################
    #   COMPILE ALL CODE IN SRC         #
    #####################################

    # Possible paths where we could keep source code : src, templates and flavour (optional)
    folders_to_compile = [PATH_SRC, PATH_TEMPLATES, PATH_FLAVOUR]

    # For custom structure, for example many packages in folders_to_compile
    # we need a generic way to find all files to compiles
    all_folders_to_compile = [
        item for sublist in [
            helper.find_files_folder_in_path(folder)
            for folder in folders_to_compile
        ] for item in sublist
    ]

    # Files that must be compiled by javac
    files_to_compile = [
        "{}/{}{}".format(folder, "*", FILE_EXTENSION)
        for folder in all_folders_to_compile
    ]

    compile_cmd = helper.generate_java_command_string(files_to_compile, libs,
                                                      "javac")
    print("COMPILING CODE : {}".format(compile_cmd))
    result = helper.run_command(compile_cmd)

    # handle compilation errors
    feedback.compilation_feedback(result)

    #####################################
    #       GENERATE A JAR FILE         #
    #####################################

    # We need a manifest in order to make the created jar runnable
    helper.create_manifest(libs)

    # Create a jar file
    create_jar = helper.generate_jar_file()
    print("GENERATING JAR : {}".format(create_jar))

    # WARNING ; JUST FOR JAVA TO NOT MISUNDERSTAND OUR STRUCTURE, we have to change the CWD in the command
    result = helper.run_command(create_jar, PATH_CLASSES)

    # For debug the jar construction
    # print(result.stdout)

    # handle jar creation errors
    feedback.jar_feedback(result)

    #####################################
    #   RUN  TEST  RUNNER               #
    #####################################

    # invoke runner with classes as arg
    # in the case of code coverage ( Jacoco ) , we need to generate also the report file (exec ) by the JaCoco agent
    coverage_required = True if feedback_settings[
        "feedback_kind"] == "JaCoCo" else False

    run_code = helper.generate_java_command_string(JAR_FILE,
                                                   libs,
                                                   coverage=coverage_required,
                                                   is_jar=True)
    print("RUNNING CODE : {}".format(run_code))
    result = helper.run_command(run_code)

    #####################################
    #   Show and handle results         #
    #####################################
    feedback.result_feedback(result, feedback_settings)

    #####################################
    #   Prepare archive for JPlag       #
    #####################################
    if feedback_settings["plagiarism"]:

        student_name = input.get_input("@username")

        # The files filled by the student are all inside PATH_TEMPLATES
        files_to_be_tested = helper.find_files_in_path(PATH_TEMPLATES)

        # Creates the archive like expected by JPlag
        for student_file in files_to_be_tested:
            command = "archive -a {} -o {}".format(student_file, student_name)
            helper.run_command(command, universal_newlines=True)
Пример #12
0
  
        pre: aucune
        post: renvoie 'True' si la réponse est juste, 'False' sinon
    """
    answer = answer.strip()
    answer = list(answer)
    simp_answer = "("
    for el in answer:
        if el in "-.,1234567890":
            simp_answer += el
    simp_answer += ")"

    return simp_answer == correction


answer = input.get_input(
    "q1")  #Remplacez tous les 'q1' par l'ID du sous-problème
grade = 0
check = is_coordinates(answer)

if check != True:  #Renvoie un feedback personnalisé en fonction des erreurs rencontrées
    feedback.set_problem_result("failed", "q1")  #Ici
    if check == "parenthese":
        feedback.set_problem_feedback(
            "Votre réponse doit contenir des parenthèses pour délimiter le point",
            "q1")  #Ici
    if check == "lettre":
        feedback.set_problem_feedback(
            "Votre réponse ne doit contenir que des chiffres", "q1")  #Ici
    if check == "separateur":
        feedback.set_problem_feedback(
            "Les coordonnées doivent être séparées par une virgule",
Пример #13
0
                         stderr=subprocess.STDOUT,
                         stdout=subprocess.PIPE)
    readelf_output = p.communicate()[0].decode('utf-8')
    for func in banned_funcs:
        if re.search("UND {}\n".format(func), readelf_output):
            feedback.set_tag("banned_funcs", True)
            feedback.set_global_result("failed")
            feedback.set_global_feedback(
                "Vous utilisez la fonction {}, qui n'est pas autorisée.".
                format(func))
            exit(0)

# Remove source files
subprocess.run("rm -rf *.c *.tpl *.h *.o", shell=True)

LANG = input.get_input('@lang')

# Run the code in a parallel container
p = subprocess.Popen(shlex.split(
    "run_student --time 20 --hard-time 60 ./tests LANGUAGE={}".format(LANG)),
                     stderr=subprocess.STDOUT,
                     stdout=subprocess.PIPE)
o, e = p.communicate()
print(o.decode("utf-8"))

# If run failed, exit with "failed" result
if p.returncode:
    feedback.set_global_result("failed")
    if p.returncode == 256 - 8:
        montest_output = rst.get_admonition(
            "warning", "**Erreur d'exécution**",
Пример #14
0
#! /usr/bin/python3
# -*- coding: utf-8 -*-

from inginious import input, feedback, rst

correct = "]-4;2]"  # Insérer la bonne réponse ici

answer = input.get_input("q1")  #Remplacer q1 par l'id du sous-problème
grade = 0
""" Vérifie que @n soit bien un nombre entier ou + ou - l'infini.

    pre: @n, une chaine de caractères
    post: renvoie
      @b, un boolean, vrai si @n représente un nombre entier ou +/- infini, faux sinon
      @s, une chaine de caractères contenant un commentaire
"""


def is_integer(n):
    if n in ["+inf", "-inf", "inf"]:
        return True, "+ ou - infini"

    try:
        int(n)
        return True, "correct"
    except:
        return False, "{} n'est pas un nombre correct".format(n)


""" Vérifie que @set soit bien un ensemble de nombres entiers.
Пример #15
0
import os, re, hashlib, subprocess, shlex, shutil
import tempfile, tarfile
from inginious import feedback, rst, input

#################
# Check filename
#################

fname = input.get_input("p1archive:filename")

if re.match(r"^[0-9]{6}00\.tar\.gz$", fname) is None:
    feedback.set_global_result("failed")
    feedback.set_global_feedback(
        "Nom de l'archive incorrect. Format attendu: NOMA.tar.gz (exemple: 12341500.tar.gz)"
    )
    exit(1)

noma = fname.replace(".tar.gz", "")

##################
# Extracting file
##################

fp = tempfile.TemporaryFile()
fp.write(input.get_input("p1archive:value"))
fp.seek(0)

try:
    tar = tarfile.open(fileobj=fp)
    tar.extractall()
    tar.close()
Пример #16
0
# Ce fichier doit être utilisé pour un exercice de type 'random' à un seul sous-problème

import re
#import math                Si nécessaire, effacer le '#'
from sympy import sympify, simplify
from sympy.parsing.latex import parse_latex
from inginious import input, feedback, rst

# Intégrer les variables que vous avez définie dans le sous-problème

# nom_de_variable = int(input.get_input("@random")[indice]*100)

# Ce qui correspond à l'exemple d'énoncé du TUTO (à remplacer) :

somme = 10000 * int(input.get_input("@random")[0] * 100 + 1)
plus2 = 1000 * int(input.get_input("@random")[1] * 100 + 1)
minus3 = 1000 * int(input.get_input("@random")[2] * 100 + 1)

# Définir comment la réponse correcte sera vérifiée avec les différents paramètres

# Ce qui correspond à l'exemple du TUTO (à remplacer) :

correct_equation = str(somme) + " = x + x + " + str(plus2) + " + x  + " + str(
    plus2) + " - " + str(minus3)


def parse_equation(latex_str):
    latex_str = re.sub("(\\\left|\\\\right)", "", latex_str)
    return parse_latex(latex_str)