Exemple #1
0
def get_assign(assign_name):
    try:
        with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
            assign_to_config = json.load(json_in)
    except:
        print(red_wrapper("Can not find assign mapping, did you already run ") + cyan_wrapper("oj update ") + red_wrapper("?"))
        return
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " + cyan_wrapper(hwmap + " [" + assign_to_config[hwmap]['contest_name'] + "]"))
        print("If you want to update latest homework assignment, type: [oj update] to update.")
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest/problem?contest_id={}&problem_id={}".format(
        contest_id, problem_id
    )
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    data = result["data"]
    if not data:
        print("Unexpected Error with Server")
        return
    try:
        samples = data["samples"]
    except:
        print("Unexpected Error in Parsing Response")
        print(data)
        return
    template = None
    if "C" in data["template"]:
        template = data["template"]["C"]
    else:
        template = "#include <stdio.h>\n\nint main() {\n    \n    return 0;\n}\n"
    dir_name = data["_id"]
    print("Made a [{}] folder in your current directory.".format(dir_name))
    template_path = dir_name + "/main.c"
    if not os.path.isdir(dir_name):
        os.mkdir(dir_name)
    with open(template_path, "wt") as fout:
        fout.write(template)
    for idx, sample in enumerate(samples):
        sample_num = idx + 1
        input_sample_path = dir_name + "/" + "{}.in".format(sample_num)
        input_ = sample["input"]
        with open(input_sample_path, "wt") as fout:
            try:
                fout.write(input_)
            except:
                print("ERROR: None-ascii character in input file")
        output_sample_path = dir_name + "/" + "{}.out".format(sample_num)
        output = sample["output"]
        with open(output_sample_path, "wt") as fout:
            try:
                fout.write(output)
            except:
                print("ERROR: None-ascii character in input file")
Exemple #2
0
def get_csrf_token():
    csrf_token = None
    try:
        with open(COOKIES_PATH) as fin:
            for line in fin:
                line = line.strip()
                if line == "" or line[0] == "#":
                    continue
                line = line.strip().split("\t")
                if line[-2] == "csrftoken":
                    csrf_token = line[-1]
                    return csrf_token
    except:
        print(red_wrapper("cookie file not found or parsing error"))
Exemple #3
0
def update_contest_map():
	if not os.path.isdir(STATEMENT_PATH):
		os.mkdir(STATEMENT_PATH)
	os.chmod(STATEMENT_PATH, 0700)
	print("Target Contest: " + cyan_wrapper(CONTEST_NAME))
	endpoint = "contests?offset=0&limit=10&status=0"
	inputstr = '{'
	result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
	counter = 1
	result2 = ""
	for i in range(0,len(result['data']['results'])):
		if(result['data']['results'][i]['title'] != CONTEST_NAME):
			continue
		contestid = result['data']['results'][i]['id']
		payload = {
				"contest_id" : str(contestid)
				}
		endpoint = "contest/problem?contest_id=" + str(contestid)
		result2 = json.loads(curl("get", payload=payload, endpoint=endpoint, use_x_csrf_token=True))
		if result2["error"] == "error":
			print("Error : " + result2["data"])
			continue
		for problems in range(0,len(result2['data'])):
			c_id = result2['data'][problems]['_id']
			name = result2['data'][problems]['title']
			r_id =  result2['data'][problems]['id']
			try:
				print("Found HomeWork: " + cyan_wrapper(str(c_id) + " [" + name + "]"))
			except:
				print("Found HomeWork: " + cyan_wrapper(str(c_id) + " [" + str(c_id) + "]"))
			if counter != 1:
				inputstr += ','
			try:
				inputstr += '"' + str(c_id) + '":{"contest_name":"' + str(name) + '","contest_id":' + str(contestid) + ',"contest_problem_id":"' + str(c_id)+ '","problem_id":' + str(r_id) + '}'
			except:
				inputstr += '"' + str(c_id) + '":{"contest_name":"' + str(c_id) + '","contest_id":' + str(contestid) + ',"contest_problem_id":"' + str(c_id)+ '","problem_id":' + str(r_id) + '}'
			counter += 1
	inputstr += '}'
	if not os.path.isdir(STATEMENT_PATH):
		os.mkdir(STATEMENT_PATH)
	f = open(ASSIGNMENT_MAPPING_PATH,'w')
	f.write(inputstr.encode("utf-8"))
	f.close
	if result2["error"] == "error":
		print(red_wrapper("Fail updating assign!"))
	else:
		print(green_wrapper("Updated assign successfully!"))
Exemple #4
0
def status(submission_id):
    endpoint = "submission?id={}".format(submission_id)
    result = json.loads(curl("GET", endpoint=endpoint, use_x_csrf_token=True))
    response_data = result["data"]
    if response_data == "Submission doesn't exist":
        print("Submission doesn't exist")
        return
    print("Your code has been graded! Here's your results:\n")
    status_to_response = {
        -1:
        lambda idx: red_wrapper("Testcase {}: WA(Wrong Answer)".format(idx)
                                ),  # WA
        -2:
        lambda idx: cyan_wrapper("Testcase {}: CE(Compilation Error)".format(
            idx)),  # CE
        0:
        lambda idx: green_wrapper("Testcase {}: AC(Accept)".format(idx)),  # AC
        2:
        lambda idx: "Testcase {}: TLE(Time Limit Exceeded)".format(idx),  # TLE
        3:
        lambda idx: "Testcase {}: MLE(Memory Limit Exceeded)".format(idx
                                                                     ),  # MLE
        4:
        lambda idx: purple_wrapper("Testcase {}: RE(Runtime Error)".format(idx)
                                   ),  # RE
    }
    if "data" not in response_data["info"]:
        print(cyan_wrapper("CE(Compilation Error) before running testing"))
        return
    for idx, ans in enumerate(response_data["info"]["data"]):
        test_case_no = idx + 1
        answers_status = ans["result"]
        if answers_status not in status_to_response:
            print("Testcase {}: SE(System Error)".format(test_case_no))
            continue
        print(status_to_response[answers_status](test_case_no))
    print("For graphical results,\nplease visit: " + HOST + "status/" +
          submission_id)
Exemple #5
0
def status(submission_id):
    endpoint = "submission?id={}".format(submission_id)
    result = json.loads(curl("GET", endpoint=endpoint, use_x_csrf_token=True))
    this_result = result["data"]["result"]
    error_counter = 0
    while (str(this_result) == "7" and error_counter < 10):
        time.sleep(1.0)
        result = json.loads(
            curl("GET", endpoint=endpoint, use_x_csrf_token=True))
        this_result = result["data"]["result"]
        error_counter += 1
    response_data = result["data"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(TimeLimitExceeded)"),  # TLE
        3: purple_wrapper("MLE(MemoryLimitExceeded)"),  # MLE
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    if "info" in response_data:
        if response_data == "Submission doesn't exist":
            print("Submission doesn't exist")
            return
        print("========================================================")
        try:
            print("Result: {:40}  Score:{:4}".format(
                status_to_response[this_result],
                response_data["statistic_info"]["score"]))
            if "data" not in response_data["info"]:
                print(gray_wrapper(
                    response_data["statistic_info"]["err_info"]))
                print(
                    "========================================================")
                return
            print("|ID |Status                       |   Time|  Mem| Score|")
            for ans in result["data"]["info"]["data"]:
                print("|#{:2}|{:40}|{:5}ms|{:3}MB| {:5}|".format(
                    ans["test_case"], status_to_response[ans["result"]],
                    ans["real_time"], (ans["memory"] / 1048576) + 1,
                    ans["score"]))
            print("========================================================")
        except:
            print(result)
            print(
                "Bad response! Please check your internet connection and ask TAs!"
            )
    else:
        if response_data == "Submission doesn't exist":
            print("Submission doesn't exist")
            return
        print("==============================================")
        try:
            print("Result: {:40}".format(status_to_response[this_result]))
            if "err_info" in response_data["statistic_info"]:
                print(gray_wrapper(
                    response_data["statistic_info"]["err_info"]))
                print("==============================================")
                return
            print("|Status                       |   Time|  Mem|")
            print("|{:40}|{:5}ms|{:3}MB|".format(
                status_to_response[this_result],
                response_data["statistic_info"]["time_cost"],
                (response_data["statistic_info"]["memory_cost"] / 1048576) +
                1))
            print("==============================================")
        except:
            print(result)
            print(
                "Bad response! Please check your internet connection and ask TAs!"
            )
Exemple #6
0
def get_problem(problem_id):
    try:
        with open(PROBLEM_MAPPING_PATH, "rt") as json_in:
            problem_to_config = json.load(json_in)
    except:
        print(
            red_wrapper("Can not find problem mapping, did you already run ") +
            cyan_wrapper("oj update_p") + red_wrapper("?"))
        return
    if problem_id not in problem_to_config:
        print(
            cyan_wrapper("Invalid problem id!") +
            " Please confirm your input.")
        return
    pid = problem_to_config[problem_id]["query_id"]
    endpoint = "problem?problem_id={}".format(pid)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    data = result["data"]
    if not data:
        print("Unexpected Error with Server")
        return
    try:
        samples = data["samples"]
        templates = data["template"]
        languages = data["languages"]
    except:
        print("Unexpected Error in Parsing Response:")
        print(data)
        return
    dir_name = "problem_{}".format(problem_id)
    if not os.path.isdir(dir_name):
        os.mkdir(dir_name)
        print("Made a [{}] folder in your current directory.".format(dir_name))
    for language in languages:
        if language not in templates:
            continue
        template_file = dir_name + "/{}".format(TEMPLATE_FILENAME[language])
        content = templates[language]
        with open(template_file, "wt") as fout:
            try:
                fout.write(content)
            except:
                print("None-ascii character in template")
            # TODO: Update to support utf-8 encoding.
    for idx, sample in enumerate(samples):
        sample_num = idx + 1
        input_sample_path = dir_name + "/" + "{}.in".format(sample_num)
        input_ = sample["input"]
        with open(input_sample_path, "wt") as fout:
            try:
                fout.write(input_)
            except:
                print("None-ascii character in input file")
            # TODO: Update to support utf-8 encoding.
        output_sample_path = dir_name + "/" + "{}.out".format(sample_num)
        output = sample["output"]
        with open(output_sample_path, "wt") as fout:
            try:
                fout.write(output)
            except:
                print("None-ascii character in ouput file")
Exemple #7
0
def my_contests_status(assign_name):
    with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
        assign_to_config = json.load(json_in)
    try:
        with open(MY_STATUS_PATH, "rt") as json_in:
            status_config = json.load(json_in)
            if assign_name in status_config:
                status(status_config[assign_name]["id"])
                return
    except:
        pass
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " +
                  cyan_wrapper(hwmap + " [" +
                               assign_to_config[hwmap]['contest_name'] + "]"))
        print(
            "If you want to update latest homework assignment, type: [oj update] to update."
        )
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest_submissions?myself=1&contest_id={}&limit=20&problem_id={}".format(
        contest_id, assign_name)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result["error"] == "error":
        print("Error : " + result["data"])
        return
    result = result["data"]["results"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        2: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        3: purple_wrapper("MLE(Memory Limit Exceeded)"),  # ML 
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    print(
        "============================================================================"
    )
    print('|  Problem Name: {:58}|'.format(
        assign_to_config[assign_name]["contest_problem_id"] + " [" +
        assign_to_config[assign_name]["contest_name"] + "]"))
    print(
        "============================================================================"
    )
    print('|{:12}|{:27}|   {:4}|  {:3}|               When|'.format(
        "ID  ", "Status", "Time", "Mem"))
    inputstr = '{'
    idx = 0
    for i in result:
        if i["problem"] != assign_to_config[assign_name]["contest_problem_id"]:
            continue
        timestr = i["create_time"].split("T")[0]
        timestr += " " + i["create_time"].split("T")[1].split(".")[0]
        mydatetmp = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
        hours_added = timedelta(hours=8)
        timestr = mydatetmp + hours_added
        timestr.strftime("%m/%d/%Y, %H:%M:%S")
        if i["result"] != -2:
            print('|ID{:10}|{:38}|{:5}ms|{:3}MB|{}|'.format(
                idx, status_to_response[i["result"]],
                i["statistic_info"]["time_cost"],
                (i["statistic_info"]["memory_cost"] / 1048576) + 1, timestr))
        else:
            print('|ID{:10}|{:38}|{:5}--|{:3}--|{}|'.format(
                idx, status_to_response[i["result"]], "-----", "---", timestr))
        if idx != 0:
            inputstr += ','
        inputstr += '"ID' + str(idx) + '":{"id":"' + i["id"] + '"}'
        idx += 1
    print(
        "============================================================================"
    )
    inputstr += '}'
    if not os.path.isdir(STATEMENT_PATH):
        os.mkdir(STATEMENT_PATH)
    f1 = open(MY_STATUS_PATH, 'w')
    f1.write(inputstr.encode('utf-8'))
    f1.close
Exemple #8
0
def contests_result(assign_name):
    with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
        assign_to_config = json.load(json_in)
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " +
                  cyan_wrapper(hwmap + " [" +
                               assign_to_config[hwmap]['contest_name'] + "]"))
        print(
            "If you want to update latest homework assignment, type: [oj update] to update."
        )
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest_rank?myself=0&contest_id={}&limit=100".format(
        contest_id)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result["error"] == "error":
        print("Error : " + result["data"])
        return
    endpoint = "contest/problem?contest_id={}&problem_id={}".format(
        contest_id, assign_name)
    result2 = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result2["error"] == "error":
        print("Error : " + result2["data"])
        return
    result = result["data"]["results"]
    result2 = result2["data"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        2: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        3: purple_wrapper("MLE(Memory Limit Exceeded)"),  # ML 
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    if result2["my_status"] == None:
        print("Your status of " +
              assign_to_config[assign_name]["contest_problem_id"] +
              " : No record")
    else:
        print("Your status of " +
              assign_to_config[assign_name]['contest_problem_id'] + " : " +
              status_to_response[result2["my_status"]])
    print("================================================")
    blockstatus = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for usr in result:
        try:
            problem_index = str(assign_to_config[assign_name]["problem_id"])
            blocks = usr["submission_info"][problem_index] / 10
            blocks -= 1
            if blocks <= 0:
                blocks = 0
            blockstatus[blocks] += 1
        except:
            continue
    ic = 0
    for i in blockstatus:
        stastr = ''
        if ic == 0:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[0],
                    result2["statistic_info"]["0"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[0], 0))
        elif ic == 10:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[4],
                    result2["statistic_info"]["4"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[4], 0))
        elif ic == 20:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[8],
                    result2["statistic_info"]["8"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[8], 0))
        elif ic == 30:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-1],
                    result2["statistic_info"]["-1"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-1], 0))
        elif ic == 40:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-2],
                    result2["statistic_info"]["-2"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-2], 0))
        elif ic == 50:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[1],
                    result2["statistic_info"]["1"] +
                    result2["statistic_info"]["2"]))
            except:
                try:
                    print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                        ic + 1, ic + 10, i, status_to_response[1],
                        result2["statistic_info"]["2"]))
                except:
                    try:
                        print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                            ic + 1, ic + 10, i, status_to_response[1],
                            result2["statistic_info"]["1"]))
                    except:
                        print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                            ic + 1, ic + 10, i, status_to_response[1], 0))
        elif ic == 60:
            print(' {:3}~{:3} :{:3}  |--------------------------------'.format(
                ic + 1, ic + 10, i))
        elif ic == 70:
            print(' {:3}~{:3} :{:3}  |  {:24} : {}'.format(
                ic + 1, ic + 10, i, "Total submissions",
                result2["submission_number"]))
        else:
            print(' {:3}~{:3} :{:3}  |'.format(ic + 1, ic + 10, i))
        ic += 10
    print(
        "================================================\nFor real time score ranking, please go to the website."
    )
Exemple #9
0
def contests_status(assign_name):
    with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
        assign_to_config = json.load(json_in)
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " +
                  cyan_wrapper(hwmap + " [" +
                               assign_to_config[hwmap]['contest_name'] + "]"))
        print(
            "If you want to update latest homework assignment, type: [oj update] to update."
        )
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest_submissions?myself=0&contest_id={}&limit=20&problem_id={}".format(
        contest_id, assign_name)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result["error"] == "error":
        print("Error : " + result["data"])
        return
    result = result["data"]["results"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        2: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        3: purple_wrapper("MLE(Memory Limit Exceeded)"),  # ML 
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    print(
        "============================================================================"
    )
    print('|  Problem Name: {:58}|'.format(
        assign_to_config[assign_name]["contest_problem_id"] + " [" +
        assign_to_config[assign_name]["contest_name"] + "]"))
    print(
        "============================================================================"
    )
    print('|{:12}|{:27}|   Time|  Mem|               When|'.format(
        "User", "Status"))
    for i in result:
        if i["problem"] != assign_to_config[assign_name]["contest_problem_id"]:
            continue
        timestr = i["create_time"].split("T")[0]
        timestr += " " + i["create_time"].split("T")[1].split(".")[0]
        mydatetmp = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
        hours_added = timedelta(hours=8)
        timestr = mydatetmp + hours_added
        timestr.strftime("%m/%d/%Y, %H:%M:%S")
        if i["result"] != -2:
            try:
                usrname = i["username"].encode('ascii').decode()
            except UnicodeEncodeError:
                usrname = "UCuser"
            print('|{:12}|{:38}|{:5}ms|{:3}MB|{}|'.format(
                usrname, status_to_response[i["result"]],
                i["statistic_info"]["time_cost"],
                (i["statistic_info"]["memory_cost"] / 1048576) + 1, timestr))
        else:
            try:
                usrname = i["username"].encode('ascii').decode()
            except UnicodeEncodeError:
                usrname = "UCuser"
            print('|{:12}|{:38}|{:5}--|{:3}--|{}|'.format(
                usrname, status_to_response[i["result"]], "-----", "---",
                timestr))
    print(
        "============================================================================"
    )