def home(): if request.method == 'GET': return render_template('index.html') else: codes = request.form['codes'].split('\n') delete_tmp_file('code.txt') delete_tmp_file('result.txt') judge(codes) return redirect('/result')
def main(): server_port = int(sys.argv[1]) judge_port = int(sys.argv[2]) player_num = int(sys.argv[3]) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.bind((socket.gethostname(), server_port)) ssock.listen(10) csocklist = [] caddrlist = [] while 1: (csock, address) = ssock.accept() csocklist.append(csock) caddrlist.append(address) if(len(csocklist) == player_num): pid = os.fork() if pid == 0: # child myjudge = judge(judge_port, player_num) myjudge.run() # send judge info to clients time.sleep(1) for i in xrange(player_num): csocklist[i].send(str(judge_port))
def _work(): m6connector = M6Connector() m6connector.on_load() config.logger.info("等待判题请求") submission = m6connector.get_submission() config.logger.info("已得到可用的判题请求") if submission['validator'] == 'Text Validator': is_spj = False spj_lang = 0 else: is_spj = True spj_lang = submission['spj_type'] lang = submission['compiler'] if lang == 'GCC': lang = config.LANG_C elif lang == 'GPP': lang = config.LANG_CPP elif lang == 'Java': lang = config.LANG_JAVA config.logger.info("开始判题") result = judge(config.lastSource, lang, submission['testDataId'], submission['timeLimit'], submission['memoryLimit'], is_spj, spj_lang) result['submissionId'] = submission['submissionId'] m6connector.send_result(result) config.logger.info("判题完成")
def judge_(): record.save() return_list = pronunciation.pronunciation(history[-1]) global file_wav file_wav = return_list[0] s = judge.judge("record.wav", return_list[0]) return redirect(url_for('index', score=str(int(s))))
def main(): '''Entrance''' parser = argparse.ArgumentParser() parser.add_argument('--quota', type=int, default=24, required=False) parser.add_argument('--window', type=int, default=600, required=False) parser.add_argument('--team-list', dest='team', type=str, default='team.csv', required=False) parser.add_argument('--result-dir', dest='result', type=str, default='result', required=False) parser.add_argument('--answer', type=str, required=True) parser.add_argument('--score', choices=['rank', 'fscore'], default='rank', required=False) parser.add_argument('--selector', choices=['last', 'best'], default='last', required=False) parser.add_argument('--beta', type=float, default=0.5, required=False) parameters = parser.parse_args() data = {} with open(parameters.team) as obj: for line in obj: team = line.strip() path = os.path.join(parameters.result, '%s.log' % (team, )) if not os.path.exists(path): warnings.warn('Result for team "%s" not found' % (team, )) continue data[team] = judge.judge(parameters.answer, path, quota=parameters.quota, window=parameters.window) size = set() for team in data: size.add(len(data[team])) if len(size) > 1: warnings.warn('Results vary in size!') return size = size.pop() scorer = create_scorer(parameters.beta) selector = _get_last if parameters.selector == 'best': selector = _get_best if parameters.score == 'rank': print(rank(data, size, scorer, selector)) else: print(fscore(data, size, scorer, selector))
def main(): global connection, cursor, jobs, multi_enabled signal.signal(signal.SIGINT, terminate) cfg = configparser.ConfigParser() cfg.read('./config.ini', 'UTF-8') connection = pymysql.connect(host=cfg.get('database', 'host'), user=cfg.get('database', 'user'), password=cfg.get('database', 'password'), db=cfg.get('database', 'database'), charset=cfg.get('database', 'charset'), cursorclass=pymysql.cursors.DictCursor) connection.autocommit(True) cursor = connection.cursor() job_limit = cfg.getint('limit', 'thread') multi_enabled = (job_limit != -1) if multi_enabled: jobs = {} while True: # Main loop sql = 'select id from `submissions` WHERE status in ("WJ","WR")' cursor.execute(sql) for row in cursor.fetchall(): i = row['id'] if multi_enabled: if i not in jobs and (job_limit == 0 or len(jobs) < job_limit): jobs[i] = multiprocessing.Process(target=judge.judge, args=(i, )) jobs[i].start() else: judge.judge(i) if multi_enabled: for i in jobs.copy(): if not jobs[i].is_alive(): del jobs[i] else: # signal should be ignored only in judge.judge() signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGINT, terminate) sleep(1)
def handle(submission): global session logging.info('Judging submission {}'.format(submission['id'])) logging.debug(submission) problem_dir = 'testdata/{}'.format(submission['problem_id']) os.system('mkdir -p {}'.format(problem_dir)) os.system('touch {}/digest'.format(problem_dir)) with open('{}/digest'.format(problem_dir), 'r') as f: digest_local = f.read() resp = session.get(config.address + '/problems/{}/digest'.format(submission['problem_id'])) digest_server = json.loads(resp.text)['digest'] if digest_local != digest_server: logging.info('Updating testdata for problem {}'.format( submission['problem_id'])) resp = session.get( config.address + '/problems/{}/fetch'.format(submission['problem_id'])) testdata = json.loads(resp.text)['testdata'] testdata = base64.b64decode(testdata) with open('{}/problem.zip'.format(problem_dir), 'wb') as f: f.write(testdata) os.system('unzip {0}/problem.zip -d {0}'.format(problem_dir)) with open('{}/digest'.format(problem_dir), 'w') as f: f.write(digest_server) os.system('mkdir -p temp') with open('temp/target.cpp', 'w') as f: f.write(submission['source']) result = judge.judge('{}/problem/problem.json'.format(problem_dir), 'temp/target.cpp') logging.info('Judge complete') logging.debug(result) resp = session.get(config.address + '/submissions/{}/edit'.format(submission['id'])) soup = BeautifulSoup(resp.text, features="lxml") token = soup.find('input', attrs={'name': '_token'})['value'] payload = { '_token': token, 'status': result['status'], 'score': result['score'], 'detail': json.dumps(result['detail']) } if result['time']: payload['time'] = round(result['time'] * 1000) if result['memory']: payload['memory'] = round(result['memory'] * 1024) print(payload) resp = session.patch(config.address + '/submissions/{}'.format(submission['id']), data=payload)
def _judgeThread(threadData, config, keywords): if judge(threadData, keywords): postLog(threadData, ('console')) if not config['debug']: return True else: stdLog(u'请确认是否删除(按y删除):', 'info', ('console'), '') if raw_input() == 'y': stdLog(u'已确认删除帖子...', 'debug') return True else: stdLog(u'跳过删帖', 'debug') return False
def main(use_cache=True, test=False, test_name=None, exhaustive=False): print "Let's label this bantling!" all_names = gather_all_names.gather(yob_years, use_cache, test) print "Some example names:\n", '\n'.join( [str(n) for n in random.sample(all_names, 3)]) print "Popular names:\n", '\n'.join( [str(name) for name in all_names[:3]]) print "Spellability scores:" for name in random.sample(all_names, 3): print name, phonetics.spellability(name, test) if test_name: test_name = [n for n in all_names if n.name.lower() == test_name.lower()][0] print "Ways to spell %s:"%test_name.name print '\n'.join( ["%.6f\t%s"%(phonetics.spellability(name), name) for name in phonetics.similar_names(test_name, all_names, 10)]) if not exhaustive: all_names = [name for name in all_names if name.get_popularity(normalized=True) > 0.01] #if random.random() < 0.01] # Later we can lower the threshold or run the exhaustive version. print "Scoring only most popular %d names." % len(all_names) else: all_names = [name for name in all_names if name.get_popularity(normalized=True) > 0.00001] print "Can only fit up to %d names." % len(all_names) # Rank all the names! for i, name in enumerate(all_names): try: score = judge.judge(name) except KeyboardInterrupt: break if i % 100 == 0: print '\r%d\t%03.1f\t%s '%(i, score, name), sys.stdout.flush() print scored = [n for n in all_names if hasattr(n, "score")] scored.sort(key=lambda n: n.score) scored.reverse() print "Top names:\n", '\n'.join( ["%s\t%.3f"%(name, name.score) for name in scored[:10]]) print "Worst names:\n", '\n'.join( ["%s\t%.3f"%(name, name.score) for name in scored[-10:]]) export_names.export_json(all_names)
def customize(): form = MyForm() print(form.validate_on_submit()) if form.validate_on_submit(): obj = request.form.to_dict() del obj['csrf_token'] obj['varlist'] = obj['varlist'].split(',') obj['colist'] = obj['colist'].split(',') obj['xstart'] = int(obj['xstart']) obj['ystart'] = int(obj['ystart']) obj['zstart'] = int(obj['zstart']) obj['xend'] = int(obj['xend']) obj['yend'] = int(obj['yend']) obj['zend'] = int(obj['zend']) obj['precision'] = float(obj['precision']) if (not judge.judge(obj['function'], obj['colist'] + obj['varlist'])): return render_template('customize.html', form=form) else: print("ok") sender.sender(obj, asyncio.new_event_loop()) return redirect('/success') return render_template('customize.html', form=form)
def main(RobotID, PORT=9559): motionProxy = ALProxy('ALMotion', RobotID, PORT) postureProxy = ALProxy('ALRobotPosture', RobotID, PORT) flag = 1 while True: # not flag and flag2 != 3: img = getImag(RobotID, PORT, 0) # -------------------------------调整角度对准中心点------------------------------------------------- rotation1 = motionProxy.getAngles('HeadYaw', True) rotation2 = motionProxy.getAngles('HeadPitch', True) anglelist = getangle(judge(img), rotation1, rotation2) names = "HeadYaw" angleLists = anglelist[0] * almath.TO_RAD timeLists = 1.0 isAbsolute = True motionProxy.angleInterpolation(names, angleLists, timeLists, isAbsolute) names1 = "HeadPitch" angleLists1 = anglelist[1] * almath.TO_RAD timeLists1 = 1.0 isAbsolute1 = True motionProxy.angleInterpolation(names1, angleLists1, timeLists1, isAbsolute1) theta = motionProxy.getAngles('HeadPitch') * almath.TO_RAD # -----------------------------------------获取距离------------------------------------------------- distanceX = getdistance(theta) print distanceX # 返回距离值 cv.imshow("src", img) # ------------------------------------------------------------------------------------------- print distanceX # 调试使用 move(distanceX, flag, RobotID, PORT) # flag = - flag # result = motionProxy.getRobotVelocity() # if result[0] == 0 and result[1] == 0 and result[2] == 0: # judgement = True # else: # judgement = False cv.waitKey(1)
def worker(): '''工作线程,循环扫描队列,获得评判任务并执行''' while True: if init.queue.empty() is True: # 队列为空,空闲 continue task = init.queue.get() # 获取任务,如果队列为空则阻塞 submission_id = task['submission_id'] language_id = task['language_id'] time = task['time'] memory = task['memory'] log.log_info('Task input, %d' % submission_id) log.log_info('Start judging, %d' % submission_id) program_info = judge.judge(submission_id, time, memory, language_id) if program_info not False: log.log_info('Judging complete, %d' % submission_id) init.dblock.acquire() update.write_result(submission_id, program_info) # 将结果写入数据库 update.write_output(submission_id) init.dblock.release() log.log_info('Update INFO complete, %d' % submission_id) else: log.log_error('Running Error, %d' % submission_id) init.dblock.acquire() update.write_result(submission_id, config.COMPILATION_ERROR) # 将结果写入数据库 update.write_output(submission_id) init.dblock.release() if config.auto_clean_work: # 清理work目录 clean.clean_work_dir(submission_id) if config.auto_clean_data: clean.clean_data_dir(submission_id) init.queue.task_done() # 一个任务完成
user_info.close() # l.append(doc) # print(adapter_ip) # 将字典逐个写入 csv # print(doc["uname"]) # print(doc["adapter_ip"]) ipl = [] for key in doc["adapter_ip"]: ips = "+".join(doc["adapter_ip"][key]) if ips: ipl.append(key + ":" + ips) adapter_ips = " ".join(ipl) # print(adapter_ips) # 调用判断是否违规 judgelst = judge.judge(doc["adapter_ip"]) # linelist = [ # doc["uname"], # doc["user_info"]["city"], # doc["user_info"]["name"], # doc["user_info"]["department"], # doc["system"], # doc["ip_server"], # str(doc["ip_count"]), # adapter_ips, # str(judgelst) # ] d = { "uname": doc["uname"],
print "Is camera opened ?", camProxy.isCameraOpen(1) print "getting images in remote" while True: img = camProxy.getImageRemote(nameID) # cv2.SetData(img,imgData[6]) ### imagHeader0 = np.array(img[6]) imagHeader = map(ord, img[6]) camProxy.releaseImage(nameID) imagHeader = np.reshape(imagHeader, [240, 320, 3]) img = np.uint8(imagHeader) cv.imshow("src", img) rotation1 = motionProxy.getAngles('HeadYaw', True) rotation2 = motionProxy.getAngles('HeadPitch', True) anglelist = getangle(judge(img), rotation1, rotation2) print anglelist[0] print anglelist[1] motionProxy.setStiffnesses("Head", 1.0) names = "HeadYaw" angleLists = anglelist[0] * almath.TO_RAD timeLists = 1.0 isAbsolute = True motionProxy.angleInterpolation(names, angleLists, timeLists, isAbsolute) names1 = "HeadPitch" angleLists1 = anglelist[1] * almath.TO_RAD timeLists1 = 1.0 isAbsolute1 = True motionProxy.angleInterpolation(names1, angleLists1, timeLists1, isAbsolute1) time.sleep(1.0) theta = str(motionProxy.getAngles('HeadPitch', True))
driver.find_element_by_id('getcode_num').click() time.sleep(1) # 设置截图保存位置 driver.save_screenshot('YourScreenShot') ocr = driver.find_element_by_id('img') location = ocr.location size = ocr.size r = int(location['x']), int( location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']) pic = Image.open('YourScreenShot') frame = pic.crop(r) frame = deal(frame) num = judge(frame) s = '' for x in num.itervalues(): s += str(x) if s.__len__() < 4: continue ocr = driver.find_element_by_id('code_num') ocr.send_keys(s) check = driver.find_element_by_name('remember') check.click() login = driver.find_element_by_id('btn') login.click() if driver.current_url != u'http://user.snh48.com/code/login_nodb.php': suc = True # TODO(Emilio) 线程方式完成多页面点选,增加超时重启
def translateFile(): global targetFile if not os.path.exists(ORIGENAL_DICTIONARY): print('File does not exist!') return count = -1 # count lines countNum = 0 with open(ORIGENAL_DICTIONARY) as f: c=0 while(rest_server.loading): print('loading') while(True): # for block in range(0, 3): blockMeaning = '' # 记录块结果,减少去重所需时间 res = [] wrongList = [] fileSlice = '' if countNum is 0: countNum = 1+ countNum try: with open(COUNT_DICTIONARY) as cf: content = cf.readline().split(' ') blockMeaning = content[0] count = int(content[1]) for i in range(0, count): f.readline() except: print('No counting record') while(True): line = f.readline() comment = '' if len(line.split('#')) ==1 else line.split('#')[-1] # print(line) cameoCode = str(re.findall(r"\[(.+?)\]", line)) cameoCode = cameoCode.replace('\'','').replace('[','').replace(']','') # 跳过含有明显介词的行 if '(' in line: continue # 块开头 elif line.startswith('---'): segs = line.split() blockMeaning = segs[1] print(segs, blockMeaning) # block_code = segs[2] res.append(line) # +开头的词组使用翻译API elif line.startswith('+'): tempLine = re.compile('\{.*?\}').sub('', line) words = tempLine[1:].split()[0] # 提取词组 tempWordList = translateByAPI(words) tempJudgeList = [] for tempTransRes in tempWordList: # 跳过明显偏离 if tempTransRes in wrongList: continue # 跳过已含有的词汇 if ifInBlockRes(tempTransRes, res): continue tempJudgeList.append({ 'class': blockMeaning, 'origin': 'v. '+words.replace('_', ' '), 'code': cameoCode, 'Chinese': tempTransRes, 'comment': comment }) print(tempJudgeList, '111') returnRes = judge(tempJudgeList) for item in tempJudgeList: if item in returnRes: res.append(tempLine.replace( words.replace('_', ' '), item['Chinese'])) else: wrongList.append(item['Chinese']) # judgeResult = judge( # blockMeaning, 'v. '+words.replace('_', ' '), cameoCode, temp) # if(judgeResult == 'y'): # res.append(tempLine.replace(words, temp)) # elif(judgeResult == 'n'): # wrongList.append(temp) # else: # res.append(line) # 名词搭配 elif line.startswith('-'): # 去掉不必要的符号 word = line[1:].split("#")[0].split( '[')[0].replace('*', '') # 消除开头空格,判断单词个数 words = word.replace('&', '').replace( "}", "").replace("{", "").split() originWords = ' '.join(words) # words=TESTLIST wordList = [] # index = 0 # for singleWord in words: # wordList.append([]) # for synset in wn.synsets(singleWord, lang='eng'): # for lemma in synset.lemma_names('cmn'): # # wordnet中对形容词翻译含有该符号,清除,如“前面+的” # lemma = lemma.replace('+', '') # wordList[index].append(lemma) # wordList[index] = list(set(wordList[index])) # 去除重复项 # index += 1 # # 笛卡尔积,对词组中每个词的翻译结果进行组合 # # 准确率低,考虑删去中 # for item in itertools.product(*wordLists): # translatedWords = '' # # 删去英文字典中取同义词集的符号 # temp = line.replace('&', '') # # 按顺序分别替换对应单词 # for i in range(0, len(words)): # translatedWords = translatedWords+item[i] # temp = temp.replace(words[i], item[i]) # # print(temp) # # 跳过明显偏离 # if translatedWords in wrongList: # continue # # 跳过已含有的词汇,除非本行存在cameo编号 # if ifInBlockRes(translatedWords, res) and cameoCode == '[]': # continue # judgeResult = judge( # blockMeaning, 'n. '+originWords, cameoCode, translatedWords) # if(judgeResult == 'y'): # res.append(temp) # elif(judgeResult == 'n'): # wrongList.append(translatedWords) if len(words) == 1: isFound = False # 判断单词是否能被找到 for synset in wn.synsets(words[0], lang='eng'): for lemma in synset.lemma_names('cmn'): isFound = True # wordnet中对形容词翻译含有该符号,如“前面+的” # 此处应全部为动词,不存在形容词,故遇到形容词跳过 if '+' in lemma: continue # 比较相似度,去除差距明显过大词汇,但阈值未严格测试 # if(sim(blockMeaning, lemma) < 0.2): # continue wordList.append(lemma) if isFound: wordList = list(set(wordList)) # 去重 else: wordList = translateByAPI(words[0]) tempJudgeList = [] for tempTransRes in wordList: tempJudgeList.append({ 'class': blockMeaning, 'origin': 'n. '+originWords, 'code': cameoCode, 'Chinese': tempTransRes, 'comment': comment }) print(tempJudgeList, '222') returnRes = judge(tempJudgeList) for item in tempJudgeList: if item in returnRes: res.append(line.replace('&', '').replace(originWords, item['Chinese'])) else: wrongList.append(item['Chinese']) # judgeResult = judge(blockMeaning, 'n. '+originWords, # cameoCode, result) # if(judgeResult == 'y'): # temp = line.replace('&', '').replace( # originWords, result) # # for i in range(1, len(words)): # # temp = temp.replace(words[i], '') # res.append(temp) # elif(judgeResult == 'n'): # wrongList.append(result else: # 使用API翻译直接翻译词组 translatedWordList = translateByAPI(originWords) tempJudgeList = [] for tempTransRes in translatedWordList: # 跳过明显偏离 if tempTransRes in wrongList: continue # 跳过已含有的词汇 if ifInBlockRes(tempTransRes, res): continue tempJudgeList.append({ 'class': blockMeaning, 'origin': 'n. '+originWords, 'code': cameoCode, 'Chinese': tempTransRes, 'comment': comment }) print(tempJudgeList, '333') returnRes = judge(tempJudgeList) for item in tempJudgeList: if item in returnRes: res.append(line.replace('&', '').replace( originWords, item['Chinese'])) else: wrongList.append(item['Chinese']) # judgeResult = judge(blockMeaning, 'n. '+originWords, # cameoCode, translatedWords) # if(judgeResult == 'y'): # temp = line.replace('&', '').replace( # originWords, translatedWords) # # for i in range(1, len(words)): # # temp = temp.replace(words[i], '') # res.append(temp) # elif(judgeResult == 'n'): # wrongList.append(translatedWords) # 空行 elif line == '\n': res.append(line) # 加入以得到合适的带有空行的翻译文件 # 开头无任何特殊标记 else: # 中文无时态区别。若不去除将影响replace结果 line = re.compile('\{.*?\}').sub('', line) # 去除不必要的内容,仅留下动词。 verb = line.split('#')[0].split('[')[0] # 存在结尾出现空格或换行符的情况 verb = verb.replace('\n', '').replace(' ', '') wordList = [] isFound = False # 判断单词是否能被找到 for synset in wn.synsets(verb, lang='eng'): for lemma in synset.lemma_names('cmn'): print(blockMeaning, lemma) isFound = True # wordnet中对形容词翻译含有该符号,如“前面+的” # 此处应全部为动词,不存在形容词,故遇到形容词跳过 if '+' in lemma: continue # 比较相似度,去除差距明显过大词汇,但阈值未严格测试 if(sim(blockMeaning, lemma) < 0.2): continue wordList.append(lemma) if isFound: wordList = list(set(wordList)) # 去重 else: wordList = translateByAPI(verb) tempJudgeList = [] for tempTransRes in wordList: # 跳过明显偏离 if tempTransRes in wrongList: continue # 跳过已含有的词汇 if ifInBlockRes(tempTransRes, res): continue print(blockMeaning, verb, cameoCode, tempTransRes) tempJudgeList.append({ 'class': blockMeaning, 'origin': 'v. '+verb, 'code': cameoCode, 'Chinese': tempTransRes, 'comment': comment }) print(wordList, tempJudgeList) returnRes = judge(tempJudgeList) for item in tempJudgeList: if item in returnRes: res.append(line.replace(verb, item['Chinese'])) else: wrongList.append(item['Chinese']) # judgeResult = judge( # blockMeaning, 'v. '+verb, cameoCode, word) # if(judgeResult == 'y'): # res.append(line.replace(verb, word)) # elif(judgeResult == 'n'): # wrongList.append(word) count += 1 # count lines read if line == '\n': # 块结尾,退出循环 break if rest_server.end_signal(): break targetFile = targetFile+res print('jump?!') if rest_server.end_signal(): writeFile(blockMeaning, count) break # if count>=20: # break if line == '': # 文件结尾,退出循环 writeFile(blockMeaning, count) break f.close()
# 3.read csv from csv_file_path date_list, close_list = dataLoad.read_csv("./002055.csv") # 4.insert data into database for ii in range(len(date_list)): dataLoad.insert_mysql(ii, date_list[ii], close_list[ii]) # 5.query all data from database stock_data = dataLoad.query_mysql() # print(stock_data) # 6.calculate RSI curve short_RSI = dataProcess.calculate_RSI(stock_data, 6) long_RSI = dataProcess.calculate_RSI(stock_data, 12) # 7.calculate BOLL curve BOLL = dataProcess.calculate_BOLL(stock_data, 20, 2) # 8.judge whether any condition is satisfied, give 'buy' / 'sell' / 'warning' signals buy, warning, sell = judge.judge(BOLL, short_RSI, long_RSI, start_index=20) # 9.backtesting backtest_result = backtesting.backtest(stock_data, buy, sell) # 10.draw BOLL curve, RSI curve, trade_signals curve and backtesting curve drawCurves.draw_BOLL_and_RSI(stock_data, BOLL, short_RSI, long_RSI) drawCurves.draw_trade_signals(stock_data, BOLL, short_RSI, long_RSI, buy, warning, sell) drawCurves.draw_backtesting(backtest_result)
import cv2 as cv from judge import judge # filename = 'red.jpg' filename1 = 'true.jpg' # filename2 = 'yellow.jpg' print filename1 # judge(filename) # print filename1 print judge(filename1) # print filename2 # judge(filename2) # cap = cv.VideoCapture('test.mp4') # flag, frame = cap.read() # while True: # ret, frame = cap.read() # # print ImagProgress(frame)[0] # #print 'this is all' # # print ImagProgress(frame)[1] # print judge(frame) # cv.imshow('test', frame) # cv.waitKey(1) # cap.release()
def solver(task): start = time.time() duration, n_intersec, n_streets, n_cars, bonus, streets, cars, intersections = read(path + task + '.txt') output = [] for car in cars: car.score = 1 * len(car.streets) * (sum(street.time for street in car.streets)) # TODO street_score_min = 9999999999 street_score_max = -1 for i, street in streets.items(): if len(street.cars) == 0: street.score = 0 else: street.score = sum(car.score for car in street.cars) * len(street.cars) * (street.time) # TODO if street_score_min > street.score: street_score_min = street.score if street_score_max < street.score: street_score_max = street.score score_norm_debug = [] # Schedule for inter in intersections: bool = False schedule = Schedule([], inter) for street in inter.streets_in: COST_TIME = 35 # TODO score_norm = int( ceil(COST_TIME * (street.score - street_score_min) / (street_score_max - street_score_min))) # TODO score_norm_debug.append(score_norm) if score_norm > 0: bool = True sp = SchedulePair(street, score_norm) schedule.pairs.append(sp) if bool: output.append(schedule) # Debug plt.plot(score_norm_debug) plt.show() temp = [] for s in streets.values(): temp.append(s.score) plt.plot(temp) plt.show() # print(street_score_max, street_score_min) # print(duration) write('./output/' + task + '.txt', output) score = judge(output) print(task, str(time.time() - start))
def do_POST(self): ''' Respond to POST request.''' # Extract and print the contents of the POST logging.debug('Received post request at '+self.path) recvTime = int(time.time()) length = int(self.headers['Content-Length']) post_data = urlparse.parse_qs(self.rfile.read(length).decode('utf-8')) teamname = post_data['teamname'][0] teampass = post_data['teampassword'][0] if self.path=='/submit': problemNo = post_data['problemnumber'][0] filename = post_data['filename'][0] try: filedata = b64decode(post_data['filedata'][0]) except Exception as e: logging.info ('Caught exception %s', e) self.do_HEAD() self.wfile.write(FILEDATA_MISSING) return logging.debug('Post request details :\t' + 'teamname = %s ;;' + 'teampass = %s ;;' + 'problemNo = %s ;;' + 'filename = %s ;;', teamname, teampass, problemNo, filename) if not db.authenticate(teamname, teampass): self.do_HEAD() self.wfile.write(INVALID_AUTHENTICATION) return # Check if the folder for the user exists folder = os.path.join(TEMP_DIR, teamname, problemNo) if not os.path.exists(folder): os.makedirs(folder) # Create filename using the folder information filename = os.path.join(folder, filename) # Dump data into file self.dumpFile(filename, filedata) score = 0 # Judge solution try: score, errors = judge (problemNo, filename) except NoSuchProblemException as e: self.do_HEAD() self.wfile.write(INVALID_PROBLEM) logging.debug(str(e)) return # Rename file so as to be able to keep older versions. newfilename = filename + str(recvTime) os.rename(filename, newfilename) db.updateSubmissions(teamname, problemNo, recvTime, newfilename, score, errors) # Return evaluation results self.do_HEAD() self.wfile.write("Score earned for solution : " + str(score)) if errors: self.wfile.write("\nErrors\n" + errors) return elif self.path == '/leaderboard': self.do_HEAD() leaderboard = db.getLeaderboard() self.wfile.write(leaderboard) return elif self.path == '/score': if not db.authenticate(teamname, teampass): self.do_HEAD() self.wfile.write(INVALID_AUTHENTICATION) return self.do_HEAD() scores = db.getScores(teamname) self.wfile.write(scores)
def decode(): try: for op, value in opts: if op == '--passwd': password = value print password for op, value in opts: if op == '--help': usage() sys.exit() elif op == '-e': mark = 1 # mark对-e进行处理,如果没有加密方式参数就提交给自动判断加密方式函数处理 print value + ' decode:' if value == 'base64': # 对base家族的解码 print base64.b64decode(password) elif value == 'base32': password = password.replace("'", '') print base64.b32decode(password) elif value == 'base16': password = password.replace("'", '') print base64.b16decode(password) elif value == 'md5': # 对md5的解码,MD5解码过程中采用多线程查询多个网站数据库,防止出现单个网站查询不出数据的情况。 md5Decode.crack(password) elif value == 'url': # 对url编码的解码 if urllib.unquote(password) == urllib.unquote_plus( password ): # 这里url编码中有两中编码方式,一种是将空格转为%20,另一种用+来代替。一般两种方式的解码结果一样,这里做一下防范。 print urllib.unquote(password).decode( 'utf-8').encode( 'gb2312' ) # 这里由于cmd中不支持直接的中文输出,所以我将其解码再重新编码 else: print urllib.unquote(password).decode( 'utf-8').encode('gb2312') print urllib.unquote_plus(password).decode( 'utf-8').encode('gb2312') elif value == 'morse': # morse code 有两种格式一种间隔用空格表示,另一种则用/表示 password = password.strip("\'") if re.search('/', password): # /表示的morse解密 morsepass = re.compile(r'/').split(password) morsecode = '' for code in morsepass: morsecode = morsecode + morsecoding.UNCODE[code] print morsecode elif args: # 空格隔断的morse解密 code = morsecoding.UNCODE[password] for i in args: print i code = code + morsecoding.UNCODE[i] print code else: # 单个morse code decode print morsecoding.UNCODE[password] elif value == 'javascript' or value == 'escape': # javascript解密 print urllib.unquote( password.replace('%u', '\\u').decode('unicode-escape')) elif value == 'shanlan': password = raw_input( 'please input your rail fence cipher again\n' ) # 这里的再次输入为了防止长密文中出现空格的情况 shanlandecode.shanlan(password) elif value == 'caesar': password = raw_input('please input your password\n ' ) # 防止出现空格而无法读取全部字符串的情况 password = password.replace(' ', '') a = kaisacoding.Caesar(password).decipher() print a elif value == 'vigenere': password = raw_input('please input your ciphertext\n') key = raw_input('please input your key\n') if key == '': print '由于无密钥破解vigenerecipher时采用的是猜解的方法,所以无密钥破解时提供的密文长度越长密钥长度越短结果越精确,而在提供的密文长度有限而密钥又相对较长时结果有一定的误差'.decode( 'utf-8').encode('gb2312') vigenerecode.decode(password) else: vig = Vigenere(key).decipher(password) vigs = [] for i in vig: vigs.append(i) for i in range(0, len(password)): if password[i] == ' ': vigs.insert(i, ' ') vig = '' for i in vigs: vig += i print 'the data after decode:%s\n' % vig elif value == 'rot13': print rot13code.rot(password, 13) elif value == 'rot5': rotdecode.rot5decode(password) elif value == 'rot18': rotdecode.rot18decode(password) elif value == 'rot47': rotdecode.rot47decode(password) elif value == 'ascii': password = raw_input('please input your cipher\n') password = password.split(' ') code = '' for i in password: code += chr(int(i)) print code elif value == 'shellcode': shellcode.decode(password) elif value == 'quoted-printable': a = quopri.decodestring(password) print a.decode('utf-8').encode('gb2312') elif value == 'ATbash': password = raw_input('please input your cipher:\n') print ATbash.myAtbash(password) elif value == 'xxencode': xxencode.xxdecode(password) elif value == 'cloTransport': password = raw_input('please input the passwd:') key = raw_input('please input the key:') cloTransport.cloTransport_decode(password, key) elif value == 'base': # base家族半模糊查询 basestr = 0 basenum = 0 for i in password: if 97 <= ord(i) <= 122: print 'the cipher may be base64,the plaintext is:', base64.b64decode( password) exit() if 71 <= ord(i) <= 90: basestr = 1 if i == 0 or i == 1 or i == 8 or i == 9: basenum = 1 if basestr == 1 and basenum == 0: print 'the cipher may be base32,the plaintext is:', base64.b32decode( password) if basestr == 0 and basenum == 1: print 'the cipher may be base16,the plaintext is:', base64.b16decode( password) elif value == 'rot': mark = 0 # 判断密文中是否有特殊字符,有酒说明是rot47 marknotrot5 = 0 # 判断密文中是否有字母,有就说明不是rot5 marknotrot13 = 0 # 判断密文中是否有数字,有就说明不是rot13 for i in password: if ord(i) < 48 or 57 < ord(i) < 97 or ord(i) > 122: mark = 1 if 97 <= ord(i) <= 122: marknotrot5 = 1 if 48 <= ord(i) <= 57: marknotrot13 = 1 if mark == 1: print 'rot47 decode:', rotdecode.rot47decode( password) elif marknotrot5 == 0: # 在确定密文中没有字母的情况下,可能是rot5,也可能是rot18,还可能使rot47 print 'str is not in the password,it maybe rot5:', rotdecode.rot5decode( password) print 'str is not in the password,it maybe rot18:', rotdecode.rot18decode( password) print 'str is not in the password,it maybe rot47:', rotdecode.rot47decode( password) elif marknotrot13 == 0: print 'num is not in the password,it maybe rot13:', rot13code.rot( password, 13) print 'num is not in the password,it maybe rot18:', rotdecode.rot18decode( password) print 'num is not in the password,it maybe rot47:', rotdecode.rot47decode( password) elif marknotrot13 == 1 and marknotrot5 == 1: print 'rot18 decode:', rotdecode.rot18decode( password) else: print 'encrypt method error' sys.exit() elif op != '--passwd': print 'you should input your password you need to decode' if mark != 1: judge.judge(password) except getopt.GetoptError: print '参数获取失败'.decode('utf-8').encode('gb2312') sys.exit()