def genCode(self, pid, codetype): PrintUtil.info('代码文件生成中...') p = self.getProblemInfo(globalVar.BASE_CONF.get('contest', 'cid'), pid) title = p.title.split('(')[0].strip() code = '/*' + p.problemContent() + '\n*/\n\n' code = re.sub(r'\r', '', code) ccode = '#include <stdio.h>\n\nint main(){\n\n return 0;\n}' cppcode = '#include <iostream> \n\n#include <cstdio>\nusing namespace std;\nint main()\n{\n\n return 0;\n}' javacode = 'import java.util.*;\n\npublic class Main{\n public static void main(String args[]){\n\n }\n}' suffix = '.c' if codetype == 'c': code = code + ccode suffix = '.c' elif codetype == 'cpp': suffix = '.cpp' code = code + cppcode elif codetype == 'java': suffix = '.java' code = code + javacode fileName = pid + '.' + title + suffix f = open("./" + fileName, "w") f.write(code) f.flush() f.close() PrintUtil.info('文件 [ ' + fileName + ' ] 保存成功 :) ')
def showProblemDetail(self, pid): PrintUtil.info("正在加载题目...") p = self.getProblemInfo(globalVar.BASE_CONF.get('contest', 'cid'), pid) if not p: return os.system('clear') print(p.problemDetail())
def showProblemList(self): PrintUtil.info("正在加载题目列表...") # 先尝试从缓存的文件中加载 i = 1 try: with open(globalVar.BASE_CONF_PATH + 'problemList', 'rb') as file_object: pList = pickle.load(file_object) for p in pList: print(p.problemSimple, end=' ') if i % 3 == 0: print('') i = i + 1 print('') except: # 出错就从oj线上加载 pList = self.getProblemList( globalVar.BASE_CONF.get('contest', 'cid')) for p in pList: print(p.problemSimple(), end=' ') if i % 3 == 0: print('') i = i + 1 print('')
def input_name_pass_login(ojOperate): username = input(termcolor.colored('请输入用户名: ', 'cyan')) password = getpass.getpass(termcolor.colored('请输入密码: ', 'cyan')) loginSuccess = ojOperate.login(username, password) if loginSuccess: # 保存cookie RequestUtil.session.cookies.save(ignore_discard=True, ignore_expires=True) PrintUtil.info('登录成功!') # 保存账号密码 option = input(termcolor.colored(u'\n是否保存用户名及密码? (yes/no) ', 'cyan')) if option == 'yes': # 保存密码 try: globalVar.BASE_CONF.set('user', 'username', username) # 先简单base64编码加密意思意思... bytesString = password.encode(encoding="utf-8") encodestr = base64.b64encode(bytesString) globalVar.BASE_CONF.set('user', 'password', encodestr.decode(encoding='utf-8')) with open(globalVar.BASE_CONF_PATH, 'w') as fw: globalVar.BASE_CONF.write(fw) PrintUtil.success('保存密码成功 :)') except Exception as e: PrintUtil.info("保存密码失败 :(") PrintUtil.error(e) else: sys.exit(0)
def saveContestInfo(self, cid): PrintUtil.info('正在获取比赛信息...') # 保存比赛信息 globalVar.BASE_CONF.set('contest', 'cid', cid) with open(globalVar.BASE_PATH + 'base.conf', 'w') as fw: globalVar.BASE_CONF.write(fw) self.saveProblemList() PrintUtil.info("设置比赛成功!\n")
def showRanking(self): cid = globalVar.BASE_CONF.get('contest', 'cid') PrintUtil.info("加载排名中...") rList = self.getRankingList(cid) # rList = rList.reverse() for i in range(0, len(rList))[::-1]: rList[i].showUserInfo()
def showPassedDetail(self, pid): cid = globalVar.BASE_CONF.get('contest', 'cid') problem = self.getPassedDetail(cid, pid) try: problem.code.index('输入描述') PrintUtil.info(problem.code) except: print(problem.problemDetail()) PrintUtil.success(problem.score)
def saveProblemList(self): PrintUtil.info('正在缓存题目信息...') pList = self.getProblemList(globalVar.BASE_CONF.get('contest', 'cid')) if not pList: PrintUtil.warn('获取题目信息失败') try: with open(globalVar.BASE_PATH + 'problemList', 'wb') as file_object: pickle.dump(pList, file_object) except Exception as e: PrintUtil.error('缓存失败 :(') print(e) pass
def check_login(ojOperate): # 判断是否登录 if not os.path.exists(globalVar.BASE_PATH + ".cookies/" + globalVar.OJ_NAME): logo = "" \ " \n" \ " █████╗ ██████╗ ██╗ \n" \ " ██╔══██╗ ██╔═══██╗ ██║ \n" \ " ███████║ ██║ ██║ ██║ \n" \ " ██╔══██║ ██║ ██║ ██ ██║ \n" \ " ██║ ██║ ╚██████╔╝ ╚█████╔╝ \n" \ " ╚═╝ ╚═╝ ╚═════╝ ╚════╝ \n" \ PrintUtil.info(logo) PrintUtil.info("欢迎使用 aoj ,登录后享受丝滑刷题") PrintUtil.info("使用\'aoj help\' 查看帮助信息") sys.exit(0) elif not ojOperate.isLogin(): PrintUtil.info('登录失效') # 验证用户是否已经保存密码 try: username = globalVar.BASE_CONF.get('user', 'username') encodePassword = globalVar.BASE_CONF.get('user', 'password') # 解码 password = base64.b64decode( encodePassword.encode('utf-8')).decode('utf-8') if username == '' or password == '': input_name_pass_login(ojOperate) else: # 账号密码不为空, 尝试自动登录 PrintUtil.info('正在尝试重新登录...') isSuccess = ojOperate.login(username, password) if isSuccess: # 保存cookie RequestUtil.session.cookies.save(ignore_discard=True, ignore_expires=True) PrintUtil.success("自动登录成功!") else: globalVar.BASE_CONF.set('user', 'password', '') with open(globalVar.BASE_CONF_PATH, 'w') as fw: globalVar.BASE_CONF.write(fw) PrintUtil.error("尝试自动登录失败, 手动登录 :(") input_name_pass_login(ojOperate) except KeyboardInterrupt: pass except: PrintUtil.error("登录失败,请稍后重试 :<") sys.exit(0)
def saveContestInfo(self, cid): PrintUtil.info('正在获取比赛信息...') resp = RequestUtil.doGet(AojApi.getUrl('contest')) jdata = json.loads(resp.text) datalist = jdata.get('list') ctype = '1' # 类型 ...1代表c 0表示java cpass = '******' # 是否需要密码 0为不需要 # 根据比赛id查找比赛类型 for data in datalist: if str(data['id']) == cid: ctype = data['isjava'] break # 判断是否需要密码 data = {'id': cid, 'type': ctype} needPasswordTest = RequestUtil.doGet(AojApi.getUrl('problems'), data) # Struts Problem Report页面报错编码不是utf-8 if 'ISO-8859-1' in needPasswordTest.encoding: PrintUtil.error('没有该比赛 -_-\"') return try: # 如果不需要密码就没有这个头信息会抛异常,比之前的解析内容判断速度快,虽然不雅 hasKeyContentLength = needPasswordTest.headers['Content-Length'] cpass = '******' passwd = input(termcolor.colored(u'你需要输入密码参加该比赛: ', 'green')) joindata = {'password': passwd, 'id': cid} passwdisRight = RequestUtil.doGet(AojApi.getUrl('pwdProblems'), joindata) if passwdisRight.text == 'no': PrintUtil.error('密码错误!') return except: pass # 保存比赛信息 globalVar.BASE_CONF.set('contest', 'cid', cid) globalVar.BASE_CONF.set('contest', 'ctype', ctype) globalVar.BASE_CONF.set('contest', 'cpass', cpass) with open(globalVar.BASE_PATH + 'base.conf', 'w') as fw: globalVar.BASE_CONF.write(fw) self.saveProblemList() PrintUtil.info("设置比赛成功! 'coj list -p' 显示题目列表\n")
def help_commond(): info = "\n" \ " list -c | 列出所有正在进行的比赛\n" \ " use id | 根据id选择比赛\n" \ " list -p | 列出当前比赛题目\n" \ " show id | 显示id对应题目的详细信息\n" \ " show id -g c | 显示题目信息并生成c语言代码文件 可选参数cpp java\n" \ " submit filename | 提交代码文件判题\n" \ " show ranking | 显示当前参加比赛对应的排名\n" \ " list -c -a | 列出所有进行和已结束的比赛\n" \ " passed | 显示所有已提交过的题目列表\n" \ " passed id | 显示已提交题目详细信息\n" \ " login | 登录\n" \ " checkout 'ojName'| 切换oj\n" \ " help | 显示此帮助信息\n" \ "\n" \ "--------------------------------------------------\n" PrintUtil.info(info) sys.exit(0)
def testCode(self, fileName): # 编译 compilep = subprocess.Popen(['g++', fileName], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) res = '' for line in compilep.stdout.readlines(): res = res + line.decode() if res.find('error') >= 0: PrintUtil.info('编译错误') PrintUtil.error(res) return # 执行 ## 读取测试数据 pid = fileName.split('.')[0] problem = self.getProblemInfo( globalVar.BASE_CONF.get('contest', 'cid'), pid) ex_input = problem.ex_input ex_output = problem.ex_output execp = subprocess.Popen(['./a.out'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = execp.communicate(input=ex_input.encode()) PrintUtil.info("测试输出:") print(out.decode(), end="") PrintUtil.info("正确输出:") print(ex_output, end="")