def greedy(self): visited = [] to_visit = [deepcopy(self.__root)] while len(to_visit) > 0: if len(to_visit) == 0: return None current_node = to_visit.pop(0) if current_node not in visited: visited.append(current_node) if Problem.get_final(current_node): return current_node for expanded in Problem.expand(current_node): if expanded not in visited: if Problem.get_final(expanded): return expanded visited.append(expanded) to_visit = [expanded] + to_visit to_visit = sorted(to_visit, key=lambda state: Problem.heuristics(state), reverse=True) return None
def add(): form = request.form if validate_legitimacy(form, request.cookies): Problem.upsert(form) return redirect(url_for('.index')) else: abort(403)
def delete_problem(): problem_id = int(request.args.get("problem_id")) type = request.args.get("type") if validate_legitimacy(request.args, request.cookies): Problem.delete(type, problem_id) return redirect(url_for('.index')) else: abort(403)
def read_file(): form = request.form if validate_legitimacy(form, request.cookies): problem_list = XLS.add_record(request.files['file']) Problem.add_problem_from_xls(problem_list) return redirect(url_for('.index')) else: abort(403)
def edit_problem(type, problem_id): p = Problem.find(type, problem_id) subject_name = Problem.get_subject_name(p.subject_id) chapter_name = Problem.get_chapter_name(p.chapter_id) cookie = token_cookie() template = render_template( "problem/edit_problem.html", problem=p, subject_name=subject_name, chapter_name=chapter_name, token=cookie['token'], ) r = make_response(template) r.set_cookie(cookie['token'], cookie['id'], max_age=300) return r
def export_problem(id): """ SYZOJ式的导出题目 """ problem: Problem = Problem.by_id(id) if not problem or not problem.public: return ujson.dumps({ "success": False, "error": { "message": "无此题目", "nextUrls": {} } }) result = { "success": True, "obj": { "title": problem.title, "description": problem.background+"\n"+problem.content, "input_format": problem.input_format, "output_format": problem.output_format, "example": "\n\n".join((f"#### 样例{index} 输入\n{item['input']}\n\n#### 样例{index} 输出\n{item['output']}" for item, index in enumerate(problem.example))), "limit_and_hint": problem.hint, "time_limit": max((item["time_limit"] for item in problem.subtasks)), "memory_limit": max((item["memory_limit"] for item in problem.subtasks)), "file_io": problem.using_file_io, "file_io_input_name": problem.input_file_name, "file_io_output_name": problem.output_file_name, "type": problem.problem_type, "tags": [] } } return ujson.dumps(result)
def test_problem_add_tests(): problem = Problem(name="test", description="testdescription", tip="tiptest") problem.add_tests([{ "description": "testname", "tip": "testtip", "input": "1", "output": "2" }, { "description": "testname2", "input": "2", "output": "3" }]) assert problem.tests[0].description == "testname" assert problem.tests[1].description == "testname2"
def problems(): if not session or not session["user_id"]: return redirect("/login") user = dbsession.query(User).filter(User.id == session["user_id"]).first() if not user: session["user_id"] = None return redirect("/login") # Validate all the things if request.method == "POST": if not request.form.get("title"): flash("Title is required") return redirect("/problems") if not request.form.get("description"): flash("Description is required") return redirect("/problems") new_problem = Problem(title=request.form.get("title"), description=request.form.get("description"), user_id=user.id) dbsession.add(new_problem) dbsession.commit() flash("New problem created successfully") return redirect("/problems/" + str(new_problem.id)) #GET return render_template("problem_index.html", user=user)
def test_problem_create_no_tests(): problem = Problem(name="test", description="testdescription", tip="tiptest") assert problem.name == "test" assert problem.description == "testdescription" assert problem.tip == "tiptest" assert len(problem.tests) == 0
def index(): problem_list = Problem.all() cookie = token_cookie() template = render_template( "problem/problem.html", problems=problem_list, token=cookie['token'], ) # 如果要写入 cookie, 必须使用 make_response 函数 # 然后再用 set_cookie 来设置 cookie r = make_response(template) r.set_cookie(cookie['token'], cookie['id'], max_age=300) return r
def dfs(self): visited = [] to_visit = [deepcopy(self.__root)] final = [] while len(to_visit) > 0: if len(to_visit) == 0: return None current_node = to_visit.pop() if current_node not in visited: visited.append(current_node) if Problem.get_final(current_node): final.append(current_node) for expanded in Problem.expand(current_node): if expanded not in visited: visited.append(expanded) to_visit += [expanded] return final
def testdata_download(id): problem: Problem = Problem.by_id(id) if not problem or not problem.public: return 404 import pathlib import zipfile import tempfile import flask problem_path = pathlib.Path(config.UPLOAD_DIR)/str(problem.id) zip_file = tempfile.mktemp("zip") zipf = zipfile.ZipFile(zip_file, "w") for publicized_file in problem.downloads: zipf.write(problem_path/publicized_file, arcname=publicized_file) zipf.close() return flask.send_file(zip_file, as_attachment=True, attachment_filename="testdata.zip")
def new(): from models.subject import Subject from models.problem import Problem subject_list = Subject.all() problem_type = Problem.get_problem_type_list() cookie = token_cookie() template = render_template( "problem/new_problem.html", subjects=subject_list, types=problem_type, token=cookie['token'], ) r = make_response(template) r.set_cookie(cookie['token'], cookie['id'], max_age=300) return r
def test_problem_create_with_tests(): test1 = ProblemTest(description="testname", tip="testtip", input="2", output="3") test2 = ProblemTest(description="testname2", tip="testtip", input="2", output="3") problem = Problem(name="test", description="testdescription", tip="tiptest", tests=[test1, test2]) assert len(problem.tests) == 2 assert problem.tests[0].description == "testname" assert problem.tests[1].description == "testname2"
def team_update(): """ 更新团队信息 { "team_id":"团队ID", "data":{ "id":团队ID, "name":"团队名", "description":"团队描述", "tasks":[ {"name":"任务名","problems":[1,2,3]} ], "private":"是否为私有团队", "invite_code":"邀请码" } } """ if not session.get("uid"): return make_response(-1, message="请先登录") team: Team = Team.by_id(request.form["team_id"]) user: User = User.by_id(session.get("uid")) relationship = db.session.query(TeamMember).filter_by( uid=user.id, team_id=team.id, is_admin=True).one_or_none() if user.id != team.owner_id and not relationship and not permission_manager.has_permission( user, "team.manage"): return make_response(-1, message="你没有权限进行此操作") data: dict = decode_json(request.form["data"]) team.name = data["name"] team.description = data["description"] team.tasks = data["tasks"] team.private = data["private"] team.invite_code = data["invite_code"] for task in team.tasks: for problem in task["problems"]: if not Problem.has(problem): return make_response( -1, message=f"任务 {task['name']} 中的题目 {problem}不存在!") db.session.commit() return make_response(0, message="保存成功")
def __init__(self, populationSize, individualSize): self._problem = Problem(populationSize, individualSize)
class Controller: def __init__(self, populationSize, individualSize): self._problem = Problem(populationSize, individualSize) def resize(self, populationSize, individualSize): self._problem = Problem(populationSize, individualSize) def evolutionaryAlgorithm(self, numberOfIterations): result = None for i in range(numberOfIterations): self._problem.evolvePopulation() intermediaryResult = self._problem.evaluateLastPopulationEA() if result == None or result[-1] > intermediaryResult[-1]: result = intermediaryResult return result def hillClimb(self, individualSize, maximumIterations): urAverageGuy = Individual(individualSize) theBestYouCanGet = urAverageGuy while maximumIterations > 0: neighborhood = urAverageGuy.neighbors() for maybeBetterGuy in neighborhood: if maybeBetterGuy.fitness() < urAverageGuy.fitness(): urAverageGuy = maybeBetterGuy if theBestYouCanGet == urAverageGuy or theBestYouCanGet.fitness( ) == 0: return theBestYouCanGet theBestYouCanGet = urAverageGuy maximumIterations -= 1 return theBestYouCanGet def particleSwarnOptimisation(self, iterationsAllowed): w = 0.3 c1 = 0.8 c2 = 0.5 currentBest = self._problem.getLastIteration().bestIndividual() currentIteration = 2 while currentIteration < iterationsAllowed: possibleBest = self._problem.evolvePopulationPSO(w, c1, c2) if currentBest[0].fitness() > possibleBest[0].fitness(): currentBest = deepcopy(possibleBest) print(currentBest[0]) print(currentBest[1]) if currentBest[0].fitness() == 0: return currentBest currentIteration += 1 return currentBest def AdamAndEvas(self, fitnessTarget, individualSize): Adam = Individual(individualSize) bestSoFar = math.inf while bestSoFar > fitnessTarget: Evas = [Individual(individualSize) for i in range(20)] for Eva in Evas: children = Adam + Eva if children[0].fitness() < Adam.fitness(): Adam = deepcopy(children[0]) elif children[1].fitness() < Adam.fitness(): Adam = deepcopy(children[1]) if Adam.fitness() <= fitnessTarget: return Adam
def resize(self, populationSize, individualSize): self._problem = Problem(populationSize, individualSize)
def create_problem(self, name, description, tip, tags=None): problem = Problem(name=name, description=description, tip=tip) if tags: problem.add_tags(tags) return problem
def main(): problem = Problem('ant.in') controller = Controller('ant-params.in', problem) ui = UI(controller) ui.run()
def get_problem_list(): form = json.loads(request.get_data(as_text=True)) all_problem = Problem.find_all(subject_id=form["subject_id"]) return Response(json_util.dumps(all_problem, ensure_ascii=False), content_type='application/json')
def import_from_syzoj(url: str, willPublic: bool): """ 从SYZOJ导入题目 参数: url:str SYZOJ题目URL willPublic:int 新题目是否公开 返回 { "code":0, "uuid":'用于websocket的uuid', "message":"" } """ import urllib import tempfile import pathlib import traceback import zipfile import shutil import os import yaml import requests from io import BytesIO from utils import decode_json if not session.get("uid"): return make_response(-1, message="请先登录") user: User = User.by_id(session.get("uid")) if not permission_manager.has_any_permission(user.id, "problem.create", "problem.manage"): return make_response(-1, message="你没有权限执行此操作") try: with requests.get(f"{url}/export") as urlf: data = decode_json(urlf.content.decode())["obj"] print("JSON data: {}".format(data)) import datetime problem = Problem(uploader_id=user.id, title=data["title"], content=data["description"], input_format=data["input_format"], output_format=data["output_format"], hint=data["limit_and_hint"], using_file_io=data["file_io"], input_file_name=data["file_io_input_name"], output_file_name=data["file_io_output_name"], create_time=datetime.datetime.now() ) if willPublic: if not permission_manager.has_any_permission(user.id, "problem.publicize", "problem.manage"): return make_response(-1, message="你没有权限公开题目") problem.public = True problem.example = [] problem.hint = "### 样例\n" + \ data["example"]+"\n\n### Hint\n"+problem.hint time_limit = int(data["time_limit"]) memory_limit = int(data["memory_limit"]) db.session.add(problem) db.session.commit() work_dir = pathlib.PurePath(tempfile.mkdtemp()) with requests.get(f"{url}/testdata/download") as urlf: pack = zipfile.ZipFile(BytesIO(urlf.content)) pack.extractall(work_dir) pack.close() problem_data_dir = pathlib.PurePath( f"{config.UPLOAD_DIR}/{problem.id}") shutil.rmtree(problem_data_dir, ignore_errors=True) shutil.copytree(work_dir, problem_data_dir) shutil.rmtree(work_dir) # 更换新的word_dir work_dir = problem_data_dir for file in filter(lambda x: x.endswith(".lock"), os.listdir(work_dir)): os.remove(work_dir/file) file_list = [] for file in filter(lambda x: not x.endswith(".lock"), os.listdir(work_dir)): with open(work_dir/(file+".lock"), "w") as f: import time last_modified_time = time.time() f.write(str(last_modified_time)) file_list.append({ "name": file, "size": os.path.getsize(work_dir/file), "last_modified_time": last_modified_time }) problem.files = file_list pure_file_list = list(map(lambda x: x["name"], file_list)) for x in pure_file_list: if x.startswith("spj_"): problem.spj_filename = x break auto_generate = True subtasks = [] if os.path.exists(work_dir/"data.yml"): # 存在data.yml with open(work_dir/"data.yml", "r", encoding="utf-8") as f: data_obj = yaml.safe_load(f) # data.yml中钦定spj if "specialJudge" in data_obj: new_spj_filename = work_dir/( "spj_"+data_obj["specialJudge"]["language"]+"."+data_obj["specialJudge"]["fileName"].split(".")[-1]) print(new_spj_filename) print(work_dir/data_obj["specialJudge"]["fileName"]) shutil.move( work_dir/data_obj["specialJudge"]["fileName"], new_spj_filename) problem.spj_filename = new_spj_filename.name if "subtasks" in data_obj: auto_generate = False def make_input(x): return data_obj["inputFile"].replace("#", str(x)) def make_output(x): return data_obj["outputFile"].replace("#", str(x)) for i, subtask in enumerate(data_obj["subtasks"]): print(subtask) subtasks.append({ "name": f"Subtask{i+1}", "score": int(subtask["score"]), "method": subtask["type"], "time_limit": time_limit, "memory_limit": memory_limit, "testcases": [] }) testcases = subtasks[-1]["testcases"] score = subtasks[-1]["score"]//len(subtask["cases"]) for testcase in subtask["cases"]: testcases.append({ "input": make_input(testcase), "output": make_output(testcase), "full_score": score }) testcases[-1]["full_score"] = subtasks[-1]["score"] - \ score*(len(testcases)-1) if auto_generate: # 不存在data.yml,直接生成子任务 input_files = list( filter(lambda x: x.endswith(".in"), pure_file_list)) output_files = list( filter(lambda x: x.endswith(".out") or x.endswith(".ans"), pure_file_list)) if len(input_files) == len(output_files): pass for i, file in enumerate(input_files): pure_file_name = file[:file.rindex(".")] subtasks.append({ "name": f"Subtask{i+1}", "score": 100//len(input_files), "method": "sum", "time_limit": time_limit, "memory_limit": memory_limit, "testcases": [{"full_score": 100//len(input_files), "input": file, "output": f"{pure_file_name}.ans" if f"{pure_file_name}.ans" in output_files else f"{pure_file_name}.out"}], "comment": "" }) diff = 100-sum(map(lambda x: x["score"], subtasks)) subtasks[-1]["score"] += diff subtasks[-1]["testcases"][0]["full_score"] += diff for file in filter(lambda x: x.endswith(".lock"), os.listdir(work_dir)): os.remove(work_dir/file) for file in filter(lambda x: not x.endswith(".lock"), os.listdir(work_dir)): with open(work_dir/(file+".lock"), "w") as f: import time last_modified_time = time.time() f.write(str(last_modified_time)) problem.files = generate_file_list(problem.id) problem.subtasks = subtasks db.session.commit() except Exception: print(traceback.format_exc()) return make_response(-1, message=traceback.format_exc()) return make_response(0, problem_id=problem.id)
engine = create_engine('sqlite:///app.db', echo=True) Base.metadata.create_all(engine) DBSession = sessionmaker(engine) dbsession = DBSession() # PUT FIXTURES HERE # Apply fixtures if db is empty if not dbsession.query(User).first(): print("EMPTY DB DETECTED - APPLYING FIXTURES") global_problems_user = User(name="global", pw_hash=bcrypt.hashpw(os.environ['CODEZOOM_GLOBAL_USER_PW'].encode('ascii'), bcrypt.gensalt())) global_problems_user.problems = [ Problem( title="Reverse a string", description="String goes STDIN, string comes STDOUT reversed, you can't explain that!", tests=[ Test(input="Hello", output="olleH"), Test(input="World", output="dlroW"), Test(input="Hello world!", output="!dlrow olleH") ] ) ] dbsession.add(global_problems_user) dbsession.commit() dbsession.close() # @ROBUSTNESS this is language specific to python and a hack DEFAULT_CODE = "import sys\n\n# print out first command line argument\nprint(sys.argv[1])" # Configure application app = Flask(__name__)
def __init__(self): self.__instance = None self.__root = None self.__problem = Problem()
def api_utils_import_from_syzoj_ng(api_server: str, problem_id: str, public: bool, locale: str = "zh_CN"): def make_url(url: str): # print(url, "to", urljoin(api_server, url)) return urljoin(api_server, url) problem_data = requests.post(make_url("/api/problem/getProblem"), json={ "testData": True, "displayId": problem_id, "judgeInfo": True, "samples": True, "localizedContentsOfLocale": locale, "judgeInfoToBePreprocessed": True }).json() print(problem_data) stmt = StringIO() examples = [] for item in problem_data["localizedContentsOfLocale"]["contentSections"]: if item["type"] == "Text": stmt.write(f"### {item['sectionTitle']}\n\n{item['text']}\n\n") elif item["type"] == "Sample": curr = problem_data["samples"] id = item["sampleId"] examples.append({ "input": curr[id]["inputData"], "output": curr[id]["outputData"], }) judge_info = problem_data["judgeInfo"] time_limit = judge_info["timeLimit"] memory_limit = judge_info["memoryLimit"] score = 100//(len(judge_info["subtasks"])) last_score = 100 - score * len(judge_info["subtasks"]) subtasks = [ { "name": f"Subtask{i+1}", "score": score + (last_score if i == len(judge_info["subtasks"])-1 else 0), "method": {"groupmin": "min", "sum": "sum", "groupmul": "min"}[subtask["scoringType"].lower()], "testcases":[ { "input": testcase["inputFile"], "output":testcase["outputFile"] } for testcase in subtask["testcases"] ], "time_limit":time_limit, "memory_limit":memory_limit } for i, subtask in enumerate(judge_info["subtasks"]) ] for subtask in subtasks: score = subtask["score"] score_per_case = score//len(subtask["testcases"]) last_score - score - score_per_case*len(subtask["testcases"]) for item in subtask["testcases"]: item["full_score"] = score_per_case subtask["testcases"][-1]["full_score"] += last_score problem = Problem( uploader_id=session.get("uid"), title=problem_data["localizedContentsOfLocale"]["title"], content=stmt.getvalue(), example=examples, files=[{ "name": item["filename"], "size":item["size"], } for item in problem_data["testData"]], subtasks=subtasks, public=public, create_time=datetime.datetime.now() ) db.session.add(problem) db.session.commit() working_dir = pathlib.Path(config.UPLOAD_DIR)/str(problem.id) shutil.rmtree(working_dir, ignore_errors=True) os.mkdir(working_dir) file_links = requests.post(make_url("/api/problem/downloadProblemFiles"), json={ "filenameList": [item["filename"] for item in problem_data["testData"]], "problemId": problem_id, "type": "TestData" }).json() print(file_links) current_time = str(time.time()) for file in file_links["downloadInfo"]: print(f"Downloading {file['filename']}") with requests.get(file["downloadUrl"]) as resp: with open(working_dir/file["filename"], "wb") as f: for chunk in resp.iter_content(1024): f.write(chunk) with open(working_dir/(file["filename"]+".lock"), "w") as f: f.write(current_time) return make_response(0, problem_id=problem.id)
def show_team(): """ 参数 { "team_id":"团队ID" } 返回: { "code":0, "data":{ "canManage":"是否可以管理", "id":"团队ID", "name":"团队名", "description":"团队描述", "owner_id":"所有者ID", "owner_username":"******", "admins":[],//管理员列表[1,2,3] "members":[],//用户列表{"username":"******","uid":xxx} "create_time":"创建时间", "hasPermission":"是否有权限查看详情", "problems":[ // 团队题目列表 {"id":"题目ID","title":"题目名"} ], "contests":[ // 团队题目列表 {"id":"比赛ID","name":"比赛名"} ], "problemsets":[ // 团队题目列表 {"id":"习题集ID","name":"习题集名"} ], "tasks":[ { "name":"任务名", "problems":[ { "name":"题目名", "id":"题目ID", scores:[ { "uid":"用户ID", "username":"******" "score":"题目得分", "status":"题目状态", "submit_id":"提交ID" }, ] } ] } ] } } """ if not session.get("uid"): return make_response(-1, message="请先登录") user: User = User.by_id(session.get("uid")) team: Team = Team.by_id(request.form["team_id"]) user_relationship: TeamMember = db.session.query(TeamMember).filter_by( uid=user.id, team_id=team.id).one_or_none() has_permission = permission_manager.has_permission( user.id, f"team.use.{team.id}" ) or (not team.private) or user.id == team.owner_id or (user_relationship) # result = team.as_dict() members = db.session.query(TeamMember.uid, TeamMember.is_admin, User.username).join(User).filter( TeamMember.team_id == team.id).order_by( TeamMember.is_admin.desc()).order_by( User.username.asc()).all() result = { "id": team.id, "name": team.name, "description": team.description, "owner_id": team.owner_id, "tasks": team.tasks, "create_time": str(team.create_time), "private": bool(team.private), "team_problems": team.team_problems, "team_contests": team.team_contests, "team_problemsets": team.team_problemsets, "canManage": permission_manager.has_permission(session.get("uid", -1), "team.manage") } result["owner_username"] = User.by_id(result["owner_id"]).username result["hasPermission"] = has_permission result["team_problems"] = [{ "id": item, "title": db.session.query(Problem.title).filter_by(id=item).one().title } for item in result["team_problems"]] result["team_contests"] = [{ "id": item, "name": db.session.query(Contest.name).filter_by(id=item).one().name } for item in result["team_contests"]] result["team_problemsets"] = [{ "id": item, "name": db.session.query(ProblemSet.name).filter_by(id=item).one().name } for item in result["team_problemsets"]] if has_permission: for item in result["tasks"]: problems = [] for problem in item["problems"]: current: Problem = Problem.by_id(problem) last = {"id": current.id, "name": current.title, "scores": []} for user_ in members: user = user_.uid submit: Submission = db.session.query(Submission).filter( Submission.uid == user).filter( Submission.problem_id == current.id).order_by( Submission.status.asc()).order_by( Submission.submit_time.desc()) if submit.count() == 0: submit = None else: submit = submit.first() if submit: last["scores"].append({ "uid": user, "username": User.by_id(user).username, "score": submit.get_total_score(), "status": submit.status, "submit_id": submit.id }) else: last["scores"].append({ "uid": user, "username": User.by_id(user).username, "score": 0, "status": "unsubmitted" }) problems.append(last) item["problems"] = problems result["create_time"] = str(result["create_time"]) result["admins"] = [] result["members"] = [] for x in members: result["members"].append({"username": x.username, "uid": x.uid}) if x.is_admin: result["admins"].append(x.uid) # result["members"] = list(map(lambda x: {"username": User.by_id( # x).username, "uid": x}, result["members"])) else: result["description"] = "" result["admins"] = [] result["members"] = [] result["create_time"] = "" result["tasks"] = [] return make_response(0, message="操作完成", data=result)