Beispiel #1
0
    def compile_with(self, extra, tst):
        try:
            util.copy_file(self.name + ".hs", "work.hs")
            if util.file_exists("judge.hs"):
                os.system("cat judge.hs >> work.hs")
            f = open("work.hs", "a")
            print("main = do", file=f)
            for line in open(tst + ".inp").readlines():
                line = line.rstrip()
                if line.startswith("let "):
                    print("    %s" % line, file=f)
                else:
                    print("    print (%s)" % line, file=f)
            f.close()
            self.execute_compiler('ghc ' + self.flags1() +
                                  ' work.hs -o work.exe 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False

        if util.file_exists('work.exe'):
            util.del_file("work.hi")
            util.del_file('work.exe')
            return True
        else:
            return False
Beispiel #2
0
    def compile(self):
        util.del_file(self.executable())
        util.del_dir(self.name + '.dir')
        os.mkdir(self.name + ".dir")

        try:
            if util.file_exists("solution.cc"):
                util.system('cp solution.cc ' + self.name + '.dir/' +
                            'program.cc')
            elif util.file_exists("solution.hh"):
                util.system('cp solution.hh ' + self.name + '.dir/program.hh')
            else:
                print("There is no solution.cc nor solution.hh")

            util.system('cp public/* ' + self.name + '.dir')
            util.system('cp private/* ' + self.name + '.dir')

            os.chdir(self.name + '.dir')
            self.execute_compiler('g++ ' + self.flags1() + ' *.cc -o ../' +
                                  self.executable())
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            os.chdir('..')
            util.del_file(self.executable())
            return False
        os.chdir('..')
        if util.file_exists(self.executable()):
            util.system("(cd public && tar cf ../public.tar *)")
            util.system("(cd private && tar cf ../private.tar *)")
            return True
        else:
            return False
Beispiel #3
0
def make_recursive_2():
    sys.stdout.flush()

    if util.file_exists("handler.yml"):
        print("------------------------------------------")
        print(os.getcwd())
        print("------------------------------------------")
        if util.file_exists("solution.cc") or util.file_exists("solution.hs"):
            try:
                if 1:
                    com = make_executable()
                    make_corrects(com)
                    if tex:
                        make_prints()
            except Exception as e:
                print("\a")
                print(e)
                errors.append((e, os.getcwd()))

    else:
        cwd = os.getcwd()
        for path in next(os.walk('.'))[1]:
            os.chdir(path)
            make_recursive_2()
            os.chdir(cwd)
Beispiel #4
0
    def compile_normal(self):
        util.del_file(self.executable())
        try:
            self.execute_compiler('ghc ' + self.flags1() + ' ' + self.name +
                                  '.hs -o ' + self.executable() +
                                  ' 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            return False

        util.del_file(self.name + '.hi')
        util.del_file(self.name + '.o')
        util.file_exists(self.executable())
        return True
Beispiel #5
0
def make_executable():
    """Compiles the solution in the cwd."""
    print(Style.BRIGHT + "Generating correct executable..." + Style.RESET_ALL)

    if not util.file_exists("handler.yml"):
        raise Exception("handler.yml does not exist")
    handler = util.read_yml("handler.yml")

    global com
    if 'compilers' in handler:
        com = compilers.compiler(handler.get('compilers', ''), handler,
                                 'solution')
    elif 'solution' in handler:
        if handler.get('solution', '') == 'Java':
            sol = 'JDK'
        elif handler.get('solution', '') == 'C':
            sol = 'GCC'
        elif handler.get('solution', '') == 'C++':
            sol = 'GXX'
        else:
            sol = handler.get('solution', '')
        com = compilers.compiler(sol, handler, 'solution')
    else:  # if handler.get('solution', '') == 'C++' or not specified
        com = compilers.compiler('GXX', handler, 'solution')

    ret = com.compile()
    if not ret:
        sys.exit(0)
    print()
    return com
Beispiel #6
0
def make_corrects(com, iterations=1):
    """Makes all correct files in the cwd."""
    print(Style.BRIGHT + "Generating correct files..." + Style.RESET_ALL)

    handler = util.read_yml("handler.yml")

    if not util.file_exists(com.executable()):
        raise Exception(Fore.RED + com.executable() + " does not exist" +
                        Style.RESET_ALL)
    for f in glob.glob("*.cor"):
        util.del_file(f)
    inps = sorted(glob.glob("*.inp"))
    for inp in inps:
        tst = os.path.splitext(inp)[0]
        time = com.execute(tst, True, iterations)

        if handler["handler"] == "graphic":
            os.rename("output.png", tst + ".cor")
        outsize = os.path.getsize(tst + ".cor")

        try:
            if 'Run' not in handler['compilers']:
                print()
        except Exception:
            print()

        print(Style.DIM + 'time: %f\t\tsize: %s' %
              (time, util.convert_bytes(outsize)) + Style.RESET_ALL)
Beispiel #7
0
 def compile_normal(self):
     # Compile original program
     util.del_file(self.executable())
     try:
         self.execute_compiler('g++ ' + self.flags1() + ' ' + self.name +
                               '.cc -o ' + self.executable())
     except CompilationTooLong:
         print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
               Style.RESET_ALL)
         util.del_file(self.executable())
         return False
     return util.file_exists(self.executable())
Beispiel #8
0
    def compile(self):
        util.del_file(self.executable())
        util.del_dir(self.name + ".dir")

        if not util.file_exists("solution"):
            raise Exception("There is no solution directory")
        if not util.file_exists("public"):
            raise Exception("There is no public directory")
        if not util.file_exists("private"):
            raise Exception("There is no private directory")

        try:
            util.mkdir(self.name + '.dir')
            util.system('cp solution/*  public/* private/* ' + self.name +
                        '.dir')
            os.chdir(self.name + '.dir')

            self.execute_compiler('make program.exe 1> make.log')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            os.chdir('..')
            return False

        os.chdir('..')

        if util.file_exists(self.name + '.dir/program.exe'):
            util.copy_file(self.name + '.dir/program.exe',
                           './' + self.executable())

        util.del_dir(self.name + ".dir")

        if util.file_exists(self.executable()):
            util.system("(cd public && tar cf ../public.tar *)")
            util.system("(cd private && tar cf ../private.tar *)")
            util.system("(cd solution && tar cf ../solution.tar *)")
            return True
        else:
            return False
Beispiel #9
0
    def compile_normal(self):
        for f in glob.glob('*.class'):
            util.del_file(f)
        try:
            util.copy_file(self.name + '.java', 'Main.java')
            self.gen_wrapper()
            self.execute_compiler('javac ' + self.flags1() + ' wrapper.java')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False

        self.del_wrapper()
        return util.file_exists(self.executable())
Beispiel #10
0
    def execute_compiler(self, cmd):
        """Executes the command cmd, but controlling the execution time."""
        pid = os.fork()
        if pid == 0:
            # Child
            logging.info(cmd)
            print(Style.DIM + cmd + Style.RESET_ALL)

            error = False
            result = ''
            try:
                result = subprocess.check_output(cmd,
                                                 shell=True,
                                                 stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as exec:
                print(exec.output.decode('utf-8'))
                error = True

            if error or len(result) != 0:
                if len(result) != 0:
                    print('\n' + result.decode('utf-8').strip() + '\n')
                print(Style.BRIGHT + Fore.RED + 'Compilation error! ' +
                      Style.NORMAL + 'Please check ' + self.name + '.' +
                      self.extension() + ' and try again.' + Style.RESET_ALL)
                os._exit(1)

            if util.file_exists('program.exe'):
                os.system('strip program.exe')
            os._exit(0)
        else:
            # Parent
            c = 0
            while c <= max_compilation_time:
                ret = os.waitpid(pid, os.WNOHANG)
                if ret[0] != 0:
                    # Ok!
                    if ret[1] != 0: sys.exit(0)
                    return

                time.sleep(0.1)
                c += 0.1
            os.kill(pid, signal.SIGKILL)
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            raise CompilationTooLong
Beispiel #11
0
    def compile_no_main(self):
        # Modify the program
        util.copy_file(self.name + '.cc', 'modified.cc')
        ori = util.read_file('modified.cc')
        main = util.read_file('main.cc')
        util.write_file(
            'modified.cc', """
#define main main__3

%s

#undef main
#define main main__2

%s

#undef main

int main() {
    return main__2();
}

""" % (ori, main))

        # Compile modified program
        util.del_file(self.executable())
        try:
            self.execute_compiler('g++ ' + self.flags2() + ' modified.cc -o ' +
                                  self.executable())
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            util.del_file('modified.cc')
            return False

        # We are almost there
        util.del_file('modified.cc')
        if util.file_exists(self.executable()):
            return True
        else:
            print(Style.BRIGHT + Fore.RED + 'Unreported error.' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            return False
Beispiel #12
0
    def compile_with(self, extra):
        try:
            util.copy_file(self.name + ".py", "work.py")
            os.system("echo '' >> work.py")
            os.system("echo '' >> work.py")
            if util.file_exists("judge.py"):
                os.system("cat judge.py >> work.py")
            os.system("cat %s >> work.py" % extra)
            self.gen_wrapper()
            self.execute_compiler('python3 py3c.py work.py 1> /dev/null')
            return True
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False

        self.del_wrapper()
        return False
Beispiel #13
0
    def compile_no_main(self):
        # esta fet a sac!!! cal fer-ho be

        for f in glob.glob('*.class'):
            util.del_file(f)
        try:
            # create Solution.class
            self.execute_compiler('javac ' + self.flags1() + ' ' + self.name +
                                  '.java')
            # create Main.class
            self.execute_compiler('javac ' + self.flags1() + ' main.java')
            # create JudgeMain.class
            self.gen_wrapper()
            self.execute_compiler('javac ' + self.flags1() + ' wrapper.java')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False
        self.del_wrapper()
        return util.file_exists('Main.class')
Beispiel #14
0
    def compile_no_main(self):
        util.copy_file(self.name + '.hs', 'modified.hs')
        ori = util.read_file('modified.hs')
        main = util.read_file('main.hs')
        util.write_file('modified.hs', """
%s

%s
""" % (ori, main))

        util.del_file(self.executable())
        try:
            self.execute_compiler('ghc ' + self.flags1() + ' modified.hs -o ' +
                                  self.executable() + ' 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            return False

        util.del_file('modified.hs')
        util.del_file('modified.hi')
        util.del_file('modified.o')
        return util.file_exists(self.executable())
Beispiel #15
0
def make_prints_3(lang, ori):

    ori = os.path.realpath(ori)
    dat = util.current_time()
    usr = util.get_username()
    hst = util.get_hostname()
    src = "%s@%s:%s" % (usr, hst, ori)

    sample2 = ""
    sample1 = ""
    tsts = sorted(glob.glob("*sample*.inp"))

    handler = util.read_yml("handler.yml")

    graphic = ""
    i = 0
    for j in tsts:
        i += 1
        jj = os.path.splitext(j)[0]
        if len(tsts) == 1:
            num = ""
        else:
            num = str(i)

        if handler["handler"] == "graphic":
            size = subprocess.getoutput(
                "identify -format '(%%w$\\\\times$%%h)' %s.cor" % jj)
            graphic = "[%s]" % size
            r = os.system("convert %s.cor %s.cor.eps" % (jj, jj))
            if r != 0:
                print(Fore.RED + "ImageMagick error!", end='')
                if r == 256:
                    print(
                        " You must change it's security policy to be able to convert the images to EPS.",
                        end='')
                print(Style.RESET_ALL)
                sys.exit(0)

        sample2 += r"\SampleTwoColInputOutput%s{%s}{%s}" % (graphic, jj, num)
        sample1 += r"\SampleOneColInputOutput%s{%s}{%s}" % (graphic, jj, num)

    scores = ""
    if util.file_exists("scores.yml"):
        scores = "scores.yml: \\verbatimtabinput{scores.yml}"

    t = r"""
\documentclass[11pt]{article}

    \usepackage{jutge}
    \usepackage{lang.%s}
    \lstMakeShortInline@

\begin{document}
    \newcommand{\SampleTwoCol}{%s}
    \newcommand{\SampleOneCol}{%s}
    \DoProblem{%s}

\subsection*{Metadata}
\begin{verbatim}
language: %s
source: %s
generation-time: %s\end{verbatim}
problem.%s.yml: \verbatimtabinput{problem.%s.yml}
handler.yml: \verbatimtabinput{handler.yml}
%s
\end{document}
    """ % (lang, sample2, sample1, lang, lang, src, dat, lang, lang, scores)

    util.write_file("main.tex", t)
    print(Style.BRIGHT + "Generating .pdf file...   ", end=Style.RESET_ALL)
    sys.stdout.flush()
    r = os.system("latex -interaction scrollmode main > main.err")
    if r != 0:
        os.system('cat main.err')
        raise Exception(Fore.RED + "\nLaTeX error!" + Style.RESET_ALL)

    r = os.system("dvips main -o 1> /dev/null 2>/dev/null")
    if r != 0:
        raise Exception(Fore.RED + "\ndvips error!" + Style.RESET_ALL)

    r = os.system("ps2pdf main.ps main.pdf 1> /dev/null 2>/dev/null")
    if r != 0:
        raise Exception(Fore.RED + "\nps2pdf error!" + Style.RESET_ALL)

    os.remove("main.ps")
    os.system("mv main.pdf %s/problem.%s.pdf" % (ori, lang))

    print(Fore.GREEN + 'Done!' + Style.RESET_ALL)
Beispiel #16
0
def verify_program(program, correct_extension='', iterations=1):
    """Verify that program compiles and gets AC for each test."""

    if not util.file_exists("handler.yml"):
        raise Exception("handler.yml does not exist")
    handler = util.read_yml("handler.yml")
    if handler["handler"] != "std" and handler["handler"] != "graphic":
        raise Exception("unknown handler")

    # compile
    available_list = []
    supported_list = compilers.compiler_extensions(handler.get('compilers'))

    file_list = [
        x for x in sorted(glob.glob(program + ".*")) if not x.endswith('.exe')
    ]
    if file_list == []:
        file_list = [program]

    solution_list = []
    excluded_extensions = ['exe', 'dir', correct_extension]
    for file in file_list:
        exclude = False
        for extension in excluded_extensions:
            if file.split('.')[-1] == extension: exclude = True
        if not exclude: solution_list.append(file)
    if solution_list == []: return

    print(Style.BRIGHT + "Compiling supported programs..." + Style.RESET_ALL)
    for solution in solution_list:
        name = os.path.splitext(solution)[0]
        ext = os.path.splitext(solution)[-1][1:]
        if ext in supported_list:
            com = compilers.compiler(supported_list[ext], handler, name)
            ret = com.compile()
            available_list.append([solution, com])

    print()
    unsupported_list = [
        x for x in solution_list
        if (x not in [y[0] for y in available_list] and x[-1] != '~'
            and not x.endswith('bak'))
    ]
    if unsupported_list != []:
        print(
            Fore.YELLOW +
            "NOTICE: The following solutions are still not supported and will NOT be verified: ",
            end='')
        for elem in unsupported_list:
            if elem != unsupported_list[-1]:
                print(elem, end=', ')
            else:
                print(elem + '\n' + Style.RESET_ALL)

    for f in glob.glob("*.out"):
        util.del_file(f)
    # execute on tests
    has_failed = False
    tests = sorted(glob.glob("*.inp"))
    for solution, compiler in sorted(available_list,
                                     key=lambda tup: tup[0].lower()):
        print("Verifying " + solution + "...")
        ext = os.path.splitext(solution)[-1]
        for test in tests:
            tst = os.path.splitext(test)[0]
            time = compiler.execute(tst, False, iterations)
            if handler["handler"] == "graphic":
                os.rename("output.png", tst + ext + ".out")
            outsize = os.path.getsize(tst + ext + ".out")

            r = subprocess.call(["cmp", tst + ext + ".out", tst + ".cor"])
            if r:
                has_failed = True
                msg = "WA"
            else:
                msg = "OK"
                util.del_file(tst + ext + ".out")
            print((Fore.GREEN if msg == 'OK' else Fore.RED) +
                  "%s.inp:\t\t%s\ntime: %f\t\tsize: %s" %
                  (tst, msg, time, util.convert_bytes(outsize)) +
                  Style.RESET_ALL)
            if outsize > 2000000 and not os.path.isfile(tst + ext + ".ops"):
                print(
                    Fore.YELLOW +
                    'Warning: The output file is bigger than 2MB, you may need a .ops file for this test case.'
                )
        print()

    if has_failed:
        print(
            Fore.RED +
            "Some solutions are not correct! Please check them and try again."
            + Style.RESET_ALL)
        sys.exit(0)