示例#1
0
def configure_docker():
    """Function used to configure base profile."""
    profiles = [
        epicbox.Profile("linter", "epicbox-linter:latest"),
        epicbox.Profile("formatter", "epicbox-formatter:latest"),
    ]
    epicbox.configure(profiles=profiles)
示例#2
0
def python(code: str, testcase_dir: str) -> SubmissionResult:
    files = [{'name': 'main.py', 'content': code}]

    result = SubmissionResult()

    epicbox.configure(
        profiles=[epicbox.Profile('python', 'python:3.6.5-alpine')])

    test_no = 0
    while test_no < MAX_NUMBER_OF_TESTCASES:
        stdin, expected = get_input_expected_output(testcase_dir, test_no)

        if stdin == None or expected == None:
            break

        output = epicbox.run('python',
                             'python3 main.py',
                             stdin=stdin,
                             files=files,
                             limits=limits['py'])

        process_output(test_no, output, expected, result)

        test_no += 1
    return result
示例#3
0
def translate_keras(filename):
    """Translate a keras model defined in a file into the neural network graph.

    Arguments:
        filename {String} -- name of the file to be translated

    Returns:
        object -- the result of this translation, can be an error
    """
    if keras_ext in filename:
        try:
            return graph_from_model_file(filename)
        except Exception as err:
            return {
                'error_class': '',
                'line_number': 1,
                'detail':
                "Model could not be loaded correctly. Error: " + str(err)
            }
    else:
        epicbox.configure(
            profiles=[epicbox.Profile('python', 'tf_plus_keras:latest')])
        general_reader = open('translate/keras_loader.txt', 'rb')
        general_code = general_reader.read()
        with open(filename, 'rb') as myfile:
            keras_code = myfile.read()
            try:
                return graph_from_external_file(keras_code, general_code)
            except Exception as err:
                return {
                    'error_class': '',
                    'line_number': 1,
                    'detail': str(err)
                }
示例#4
0
def configure(docker_url):
    epicbox.configure(
        profiles=[
            epicbox.Profile('python3',
                            'stepic/epicbox-python',
                            user='******',
                            read_only=True),
            epicbox.Profile('gcc', 'stepik/epicbox-gcc:5.3.0'),
        ],
        docker_url=docker_url,
    )
    structlog.configure(
        processors=[
            structlog.processors.TimeStamper(fmt='iso'),
            structlog.processors.KeyValueRenderer(key_order=['event']),
        ],
        logger_factory=structlog.PrintLoggerFactory(),
    )
示例#5
0
 def post(self, request):
     """Post method to execute code."""
     serializer = CodeSerializerExercise(data=request.data)
     if serializer.is_valid():
         main_code = render_main(serializer.validated_data["code_input"], )
         exercise = get_object_or_404(
             Exercise,
             id=serializer.validated_data["exercise_id"],
         )
         epicbox.configure(profiles=[
             epicbox.Profile(
                 exercise.docker_image.profile_name,
                 exercise.docker_image.image_name,
             ),
         ])
         result_run1 = docker_run(
             exercise.docker_image.profile_name,
             "python {0}".format(serializer.validated_data["filename"]),
             files=[
                 {
                     "name": serializer.validated_data["filename"],
                     "content": main_code.encode(),
                 },
             ],
             limits={
                 "cputime": 50,
                 "memory": 128
             },
         )
         errors_set = set()
         for template in exercise.errors_template.all():
             for error in template.errors.all().distinct().values_list(
                     "code", flat=True):
                 errors_set.add(error)
         if len(errors_set) > 0:
             errors_string = " ".join(errors_set)
         else:
             errors_string = None
         result_run2 = lint(serializer, errors_string)
         result_run1["lint_results"] = result_run2["lint_results"]
         create_submission.delay(
             self.request.user.mail,
             serializer.validated_data["exercise_id"],
             serializer.validated_data["code_input"],
             result_run1,
             serializer.validated_data["final"],
         )
         return Response(result_run1, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#6
0
    def __init__(self, grader_root='/tmp/', fork_per_item=True, logger_name=__name__,
                 fail_on_error=False, alert_mail=None):
        """
        grader_root = root path to graders
        fork_per_item = fork a process for every request
        logger_name = name of logger
        alert_mail = SMTP credentials and recipients list
        """
        self.log = logging.getLogger(logger_name)
        self.grader_root = path(grader_root)

        self.fork_per_item = fork_per_item
        self.fail_on_error = fail_on_error
        self.alert_mail = alert_mail if check_mail(alert_mail, self.log) else None

        epicbox.configure(profiles=[
            epicbox.Profile('python', 'python:3.7-alpine'),
            epicbox.Profile('python-server', 'python-server:1.0'),
        ])

        self.server_files = [
            {"name": "main.py", "content": get_server_file("main.py")},
            {"name": "helper.py", "content": get_server_file("helper.py")},
        ]
示例#7
0
from flask import Flask, render_template, request, session
import random, epicbox, os

# docker pull

epicbox.configure(profiles=[epicbox.Profile('python', 'python:3.9.6-alpine')])

app = Flask(__name__)
app.secret_key = os.urandom(16)
flag = open('flag.txt').read()


@app.route('/')
def yeet():
    return render_template('yeet.html')


@app.route('/yeet')
def yeetyeet():
    return render_template('yeetyeet.html')


@app.route('/yeetyeet', methods=['POST'])
def yeetyeetyeet():
    if 'run' in session and session['run']:
        return {
            'error': True,
            'msg':
            'You already have code running, please wait for it to finish.'
        }
    session['run'] = True
示例#8
0
import epicbox

epicbox.configure(
    profiles=[
        epicbox.Profile('python', 'python:3.6.5-alpine')
    ]
)
files = [{'name': 'main.py', 'content': b'print(42)'}]
limits = {'cputime': 1, 'memory': 64}
result = epicbox.run('python', 'python3 main.py', files=files, limits=limits)
示例#9
0
from flask_cors import CORS
from flask_pymongo import PyMongo
from psypl.experiments import EXPERIMENTS
from bson import json_util
import epicbox

app = Flask(__name__)
CORS(app)
app.debug = True

app.config[
    "MONGO_URI"] = "mongodb://*****:*****@localhost:27017/experiments?authSource=admin"

mongo = PyMongo(app)
experiments_db = mongo.db.experiments
epicbox.configure(profiles=[epicbox.Profile('rust', 'rust')])


def get_experiment(name):
    name = ''.join(name.split('_') + ['experiment'])
    cls = [e for e in EXPERIMENTS if e.__name__.lower() == name][0]
    return cls()


@app.route("/")
def index():
    return render_template('index.html',
                           experiments=[{
                               'url':
                               '_'.join([s.lower() for s in e.name_parts()]),
                               'name':
示例#10
0
import epicbox

epicbox.configure(profiles=[
    # epicbox.Profile('python', 'python:3.6.5-alpine')
    epicbox.Profile('python', 'continuumio/anaconda3:latest')
])


class ResponseWrapper:
    def __init__(self, exit_code: int, stdout: bytes, stderr: bytes,
                 duration: float, timeout: bool, oom_killed: bool):
        self.exit_code = exit_code
        self.output: str = stdout.decode("ascii")
        self.stderr: bytes = stderr.decode("ascii")
        self.duration: bytes = duration
        self.timeout: float = timeout
        self.oom_killed: bool = oom_killed


def getProcessResponse(content: bytes):
    files = [{'name': 'main.py', 'content': content}]
    limits = {'cputime': 1, 'memory': 64}
    result = epicbox.run('python',
                         'python3 main.py',
                         files=files,
                         limits=limits)
    return ResponseWrapper(**result)
示例#11
0
def profile_read_only(docker_image):
    return epicbox.Profile('python_read_only',
                           docker_image,
                           command='python3 -c \'print("profile stdout")\'',
                           read_only=True)
示例#12
0
def profile(docker_image):
    return epicbox.Profile('python',
                           docker_image,
                           command='python3 -c \'print("profile stdout")\'')
示例#13
0
文件: epictest.py 项目: agajews/hlbox
import epicbox

epicbox.configure(
    profiles=[
        epicbox.Profile('python', 'czentye/matplotlib-minimal')
    ]
)
files = [{'name': 'main.py', 'content': b'x = input(); print(x); y = input(); print("Hi " + y)'}]
limits = {'cputime': 10, 'memory': 64}
result = epicbox.run('python', 'python3 -u main.py', stdin=b'x\nalex\n', files=files, limits=limits)
print(result)

示例#14
0
def profile_unknown_image():
    return epicbox.Profile('unknown_image',
                           'unknown_image:tag',
                           command='unknown')
示例#15
0
 def __init__(self):
     epicbox.configure(
         profiles=[epicbox.Profile('python', self.DOCKER_IMAGE)])
示例#16
0
from xblockutils.resources import ResourceLoader
from xblockutils.studio_editable import StudioEditableXBlockMixin
from xmodule.contentstore.content import StaticContent

from nand2tetris.utils import (file_contents_iter, get_file_modified_time_utc,
                               get_file_storage_path, get_sha1)
from nand2tetris.tasks import (get_zip_file_name, get_zip_file_path,
                               zip_student_submissions)

log = logging.getLogger(__name__)
loader = ResourceLoader(__name__)

ITEM_TYPE = "nand2tetrisxblock"

epicbox.configure(profiles=[
    epicbox.Profile('nand2tetris',
                    'tcarreira/nand2tetris-autograder:2.6.1-epicbox')
])
limits = {'cputime': 1, 'memory': 64}


def reify(meth):
    """
    Decorator which caches value so it is only computed once.
    Keyword arguments:
    inst
    """
    def getter(inst):
        """
        Set value to meth name in dict and returns value.
        """
        value = meth(inst)
示例#17
0
import epicbox
import hashlib
from random import randint
from sys import stderr

epicbox.configure(profiles=[
    #epicbox.Profile('python', 'python:3.6.5-alpine')
    epicbox.Profile('python', 'hortune/python3.6-alpine')
])

q_num = 0


def is_valid(digest, diff):
    bits = ''.join(bin(i)[2:].zfill(8) for i in digest)
    return bits[:diff] == '0' * diff


def proofofwork():
    hardness = 23
    prefix = hex(
        randint(1000000000000000000000000000000000000,
                123123123213123000000123213**3))[-18:-2]
    print(f'prefix = "{prefix}"')
    print(f'sha256(prefix + answer) has {hardness} leading zeros. (In binary)')
    print("input:")
    inp = input().strip()
    s = prefix + inp
    assert is_valid(hashlib.sha256(s.encode()).digest(), hardness)

示例#18
0
def grade_epicbox(
    submission: dict,
    script_name: str,
    prepared_files: list,
    docker_profile: dict,
    docker_limits: dict,
) -> dict:
    """
    Running grading script in a separate Docker container.
    https://github.com/StepicOrg/epicbox

    :param submission: Student submission received from message broker.
    :param script_name: Name of the grading script.
    :param prepared_files: List of files and their paths.
    :param docker_profile: Epicbox profile.
    :param docker_limits: Docker container limits.
    :return: Results of grading.
    """
    logger: Logger = get_logger("process_answer")

    epicbox.configure(profiles=[
        epicbox.Profile(
            name="python",
            docker_image=docker_profile["docker_image"],
            user=docker_profile["user"],
            read_only=docker_profile["read_only"],
            network_disabled=docker_profile["network_disabled"],
        )
    ])

    # Get all files used during grading
    # Content field should be bytes
    files: list = []

    # Grading script
    with Path(PATH_GRADER_SCRIPTS_DIRECTORY / script_name /
              "grade.py").open("rb") as f:
        files.append({"name": "grade.py", "content": f.read()})

    # Required files
    for file in prepared_files:
        with Path(file["path"]).open("rb") as f:
            files.append({"name": file["name"], "content": f.read()})

    # Student submission
    files.append({
        "name": "student_response.txt",
        "content": submission_get_response(submission).encode(),
    })

    # Script parameters
    files.append({
        "name":
        "script_parameters.json",
        "content":
        submission["xqueue_body"]["grader_payload"].encode(),
    })

    result: dict = epicbox.run("python",
                               "python3 grade.py",
                               files=files,
                               limits=docker_limits)
    logger.debug("Result: %s", result)

    grade: dict = {"correct": False, "score": 0, "msg": ""}

    # Handling result
    if result["timeout"]:
        grade["msg"] = "Проверка заняла слишком много времени."
    elif result["oom_killed"]:
        grade["msg"] = "Проверка заняла слишком много памяти."
    else:
        try:
            try:
                grade["score"] = int(result["stdout"].decode().split("\n")[-2])
            except ValueError:
                grade["score"] = float(
                    result["stdout"].decode().split("\n")[-2])
            grade["msg"] = result["stderr"].decode()  # .split("\n")[-2] + "\n"
            grade["correct"] = bool(grade["score"])
        except ValueError:
            raise InvalidGraderScriptException(
                "Grading script returned invalid results: %s", result)

    return grade