示例#1
0
def get_tailcode(self, subm_id, suf):
    if submission_status(self.url, self.cookie,
                         subm_id) not in ('Compilation error',
                                          'Compiler failed'):
        raise BruteError("Submission didn't fail to compile")
    err = compile_error(self.url, self.cookie, subm_id)
    if err == None: err = ''
    err = err.strip()
    lines = {}
    it = iter(err.split('\n'))
    for line in it:
        if not line[:1].isspace():
            l = (line + ':::').split(':')
            if l[0].endswith(suf) and l[1].isnumeric() and l[2].isnumeric():
                lineno = int(l[1])
                if lineno not in lines:
                    try:
                        lines[lineno] = next(it).strip()
                    except StopIteration:
                        break
    if not lines: return ''
    minno = min(lines)
    maxno = max(lines)
    ans = ''
    for i in range(minno, maxno + 1):
        ans += lines.get(i, '###### FAILED TO FETCH ######') + '\n'
    return ans
示例#2
0
def submission_list_item(id):
    id = int(id)
    url, cookie = force_session()
    score = bj.submission_score(url, cookie, id)
    status = bj.submission_status(url, cookie, id)
    data = {'status': status}
    if score != None:
        data['score'] = score
    return data
示例#3
0
def submission_list_item(id):
    id = int(id)
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        score = bj.submission_score(url, cookie, id)
        status = bj.submission_status(url, cookie, id)
        gsc = bj.scores(url, cookie)
        gst = bj.status(url, cookie)
    data = {'status': status}
    if score != None:
        data['score'] = score
    data['global'] = {'status': gst, 'scores': gsc}
    return data
示例#4
0
def format_submissions(task=None):
    url, cookie = force_session()
    json_data = {}
    with bj.may_cache(url, cookie):
        a, b = bj.submission_list(url, cookie)
        json_data['list'] = [a, b]
        ans = ''
        have_score = False
        status_arr = []
        stats_arr = []
        for i, t in zip(a, b):
            status = bj.submission_status(url, cookie, i)
            stats = bj.submission_score(url, cookie, i)
            status_arr.append(status)
            if stats != None and task in (t, None): have_score = True
            stats_arr.append(stats)
        tt = pkgutil.get_data(
            'ejui', 'subm.html'
            if have_score else 'subm_no_score.html').decode('utf-8')
        status_arr = iter(status_arr)
        stats_arr = iter(stats_arr)
        any_subms = False
        for i, t in zip(a, b):
            status = next(status_arr)
            stats = next(stats_arr)
            json_item = {'status': status}
            if stats != None: json_item['score'] = stats
            else: stats = ''
            json_data[i] = json_item
            if task in (t, None):
                any_subms = True
                ans += tt.format(id=i,
                                 task=html.escape(t),
                                 status=html.escape(status),
                                 score=stats,
                                 color=get_submission_color(status, stats))
        return (pkgutil.get_data(
            'ejui', 'subms_t.html' if have_score else
            'subms_no_score.html').decode('utf-8').format(data=ans), any_subms,
                json_data)
示例#5
0
def incat(self, task, task_id, filepath, f, filter='', custom_include=None):
    if isinstance(filepath, str): filepath = (filepath, )
    filepath = tuple('/'.join(['..'] * 15) + i if i.startswith('/') else i
                     for i in filepath)
    lans = 0
    rot_str = '\\|/-'
    idx = 0
    while True:
        sys.stderr.write(rot_str[idx])
        sys.stderr.flush()
        subm1 = list(zip(*submission_list(self.url, self.cookie)))
        idx = (idx + 1) % 4
        sys.stderr.write('\b' + rot_str[idx])
        sys.stderr.flush()
        include_code = ('.incbin \\"%s\\"\\n' if custom_include == None else
                        custom_include) % filepath
        cerr_output = r"""
    if(%d < included_s.size())
        cerr << included_s.substr(%d, 65536);""" % (lans + 65536, lans + 65536)
        submit_solution(
            self.url, self.cookie, task_id,
            get_possible_lang_id(self, ('g++', 'g++-32'), task_id), r"""
asm("included:\n%s.byte 0\nincluded_length:\n.long included_length-included-1");

//random: %r

#include <bits/stdc++.h>

using namespace std;

extern char included[];
extern int included_length;

int main()
{
    string included_s(included, included_length);
    %sif(%d < included_s.size())
        %s << included_s.substr(%d, 65536);%s
    return 0;
}
""" % (include_code, random.random(), (filter.strip() + '\n').replace(
                '\n', '\n    '), lans, 'ifstream("%s")' %
        self.input_file if hasattr(self, 'input_file') else 'cout', lans,
        cerr_output if not isinstance(self.url, CodeForces) else ''))
        idx = (idx + 1) % 4
        sys.stderr.write('\b' + rot_str[idx])
        sys.stderr.flush()
        subm2 = list(zip(*submission_list(self.url, self.cookie)))
        if subm2[1:] != subm1 or not subm2 or subm2[0][1] != task:
            raise BruteError("Error while sending.")
        subm_id = subm2[0][0]
        while True:
            idx = (idx + 1) % 4
            sys.stderr.write('\b' + rot_str[idx])
            sys.stderr.flush()
            if not still_running(
                    submission_status(self.url, self.cookie, subm_id)):
                break
        sys.stderr.write('\b \b')
        sys.stderr.flush()
        idx = (idx + 1) % 4
        if submission_status(self.url, self.cookie,
                             subm_id) in ('Compilation error',
                                          'Compiler failed'):
            raise IncatCompileError(
                "Compilation error.",
                compile_error(self.url, self.cookie, subm_id))
        samples = get_samples(self.url, self.cookie, subm_id)
        if not samples:
            raise BruteError("No sample tests for this task.")
        sample = next(iter(samples.values()))
        if 'Output' not in sample:
            raise BruteError("Output missing from report.")
        f.write(sample['Output'])
        lans += len(sample['Output'])
        if len(sample['Output']) < 65536: break
        if 'Stderr' in sample:
            f.write(sample['Stderr'])
            lans += len(sample['Stderr'])
            if len(sample['Stderr']) < 65536: break
示例#6
0
def do_score100(self, cmd):
    """
    usage: score100 <task> <test_cnt> || score100 <subm_id> || score100 <task> <start-end>

    Submit a solution that will get a score of 100.
    If `task` and `test_cnt` are supplied, will submit a solution for task `task` that will pass `test_cnt` tests.
    If `subm_id` is supplied, `task` and `test_cnt` will be taken from that.
    If `start` and `end` are supplied, the task is assumed to have from `start` to `end` tests, the exact number will be retrieved using binary search.
    """
    brutejudge.cheats.cheating(self)
    sp = cmd.split()
    if len(sp) not in (1, 2):
        return self.do_help('score100')
    if not isinstance(self.url, Ejudge):
        raise BruteError("score100 only works on ejudge.")
    lx, ly = submission_list(self.url, self.cookie)
    if len(sp) == 1:
        if not sp[0].isnumeric():
            raise BruteError("Submission ID must be a number.")
        subm_id = int(sp[0])
        try: sp[0] = ly[lx.index(subm_id)].strip()
        except (ValueError, IndexError):
            raise BruteError("No such submission.")
        x, y = submission_results(self.url, self.cookie, subm_id)
        sp.append(str(len(x)))
    tasks = task_list(self.url, self.cookie)
    if sp[0] not in tasks:
        raise BruteError("No such task.")
    task_id = tasks.index(sp[0])
    try:
        if '-' in sp[1]:
            spa, spb = sp[1].split('-', 1)
            test_cnt_low = int(spa)
            test_cnt_high = int(spb) + 1
        else:
            test_cnt_low = test_cnt_high = int(sp[1])
            test_cnt_low -= 1
            test_cnt_high += 1
    except ValueError:
        raise BruteError("test_cnt must be a number or a pair of numbers. (e.g. 1 or 1-2)")
    contest_id = self.url.contest_id
    code0 = ('//random: %r\n#define EXECUTE_FLAGS 08\n#include "'+'../'*16+'home/judges/%06d/problems/%s/Makefile"\n')%(random.random(), contest_id, sp[0])
    lang_id = get_possible_lang_id(self, ('g++', 'g++-32', 'gcc', 'gcc-32'), task_id)
    submit(self.url, self.cookie, task_id, lang_id, code0)
    lx2, ly2 = submission_list(self.url, self.cookie)
    if len(lx2) == len(lx):
        raise BruteError("Error while sending.")
    while still_running(submission_status(self.url, self.cookie, lx2[0])): pass
    tailcode = get_tailcode(self, lx2[0], 'Makefile')
    tp = '%02d'
    cp = '%02d.a'
    for l in tailcode.split('\n'):
        if l.startswith('EXECUTE_FLAGS = '):
            tp = l.split('--test-pattern=', 1)[1].split()[0]
            cp = l.split('--corr-pattern=', 1)[1].split()[0]
    while test_cnt_high - test_cnt_low > 1:
        test_cnt = (test_cnt_high + test_cnt_low) // 2
        code = ''
        for i in range(test_cnt):
            code += ('asm("test_%d:\\n.incbin \\"'+'../'*16+'home/judges/%06d/problems/%s/tests/'+tp+'\\"\\n.byte 0");\n')%(i, contest_id, sp[0], i + 1)
            code += ('asm("ans_%d:\\n.incbin \\"'+'../'*16+'home/judges/%06d/problems/%s/tests/'+cp+'\\"\\n.byte 0");\n')%(i, contest_id, sp[0], i + 1)
            code += 'extern char test_%d[];\n'%i
            code += 'extern char ans_%d[];\n'%i
        code += '\n//random: %r\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main()\n{'%random.random()+r'''
    int buf_sz = 1;
    void* buf = (void*)0;
    while (1) {
        buf = realloc(buf, buf_sz);
        int bytes_read = fread((void*)(((char*)buf)+buf_sz/2), 1, (buf_sz+1)/2, stdin);
        if (bytes_read < (buf_sz+1)/2) {
            *(((char*)buf)+buf_sz/2+bytes_read) = 0;
            break;
        }
        buf_sz *= 2;
    }
    fprintf(stderr, "%s", (char*)buf);
'''
        for i in range(test_cnt):
            code += '    if (!strcmp((char*)buf, test_%d)) {\n'%i
            code += '        printf("%%s", ans_%d);\n'%i
            code += '        return 0;\n    }\n'
        code += '    printf("Sorry, I don\'t know the answer!\\n");\n'
        code += '    return 0;\n}\n'
        submit(self.url, self.cookie, task_id, lang_id, code)
        lx3, ly3 = submission_list(self.url, self.cookie)
        if len(lx2) == len(lx3):
            raise BruteError("Error while sending.")
        lx2, ly2 = lx3, ly3
        while True:
            status = submission_status(self.url, self.cookie, lx2[0])
            if not still_running(status): break
        if status == 'OK': return
        elif status == ('Compilation error', 'Compiler failed'): test_cnt_high = test_cnt
        else: test_cnt_low = test_cnt
    raise BruteError("Unknown failure, probably an interactive task.")