-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjudge.py
408 lines (314 loc) · 10.1 KB
/
judge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#coding:utf8
import sys, signal, os, subprocess, time,string,MySQLdb,syslog
reload(sys)
sys.setdefaultencoding('utf-8')
def debug(msg):
print msg
syslog.syslog(msg)
# check if two files are the same
def file_same(a,b):
fileA = open(a,'r')
fileB = open(b,'r')
value = False
fa=fileA.read()
fb=fileB.read()
fa=fa.replace('\r','')
fb=fb.replace('\r','')
fa=fa.rstrip('\n')
fb = fb.rstrip('\n')
if fa == fb:
value=True
# if fileA.readlines() == fileB.readlines():
# value = True
fileA.close()
fileB.close()
return value
def old_file_same(a, b):
fileA = open(a, "r")
fileB = open(b, "r")
linesA = fileA.readlines()
linesB = fileB.readlines()
fileA.close()
fileB.close()
if(len(linesA) != len(linesB)):
return False
for i in range(0, len(linesA)):
lineA = linesA[i].strip()
lineB = linesB[i].strip()
if(lineA != lineB):
return False
return True
# if two files are almost the same
def compare_files(a,b):
fileA = open(a,'r')
fileB = open(b,'r')
linesA = str(fileA.read())
linesB = str(fileB.read())
sa=linesA
sb=linesB
sa = sa.replace('\r', '')
sa = sa.replace('\n','')
sa = sa.replace('\t', '')
sa = sa.replace(' ', '')
sb = sb.replace('\r', '')
sb = sb.replace('\n', '')
sb = sb.replace('\t', '')
sb = sb.replace(' ', '')
fileA.close()
fileB.close()
# debug("A = \n" + linesA)
# debug("B = \n" + linesB)
if sa == sb:
debug("file is same")
return True
debug("file not same")
return False
def ModifyStatus(id,status):
db = MySQLdb.connect("localhost","root","WuYing","jxnuoj",charset="utf8")
cursor = db.cursor()
sql = "UPDATE user_problem SET judge_status = '%d' WHERE id = '%d'" % (status,id)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
def ModifyTimeAndMemoryAndStatus(id,time,memory,status):
db = MySQLdb.connect("localhost","root","WuYing","jxnuoj",charset="utf8")
cursor = db.cursor()
sql = "UPDATE user_problem SET judge_status = '%d',exe_time='%d',exe_memory='%d' WHERE id = '%d'" % (status,time,memory,id)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
def ModifyProblemInformation(problem_id):
db = MySQLdb.connect("localhost", "root", "WuYing", "jxnuoj", charset="utf8")
cursor = db.cursor()
sql1 = "select * from user_problem where judge_status = '%d' and problem_id = '%d' " % (0, problem_id)
# submissions
sql2 = "select * from user_problem where problem_id = '%d' " % (problem_id)
try:
acceptedNumber=cursor.execute(sql1)
allsubmissionsNumber = cursor.execute(sql2)
db.commit()
except:
db.rollback()
sql="UPDATE problem SET accepted = '%d',submissions='%d' WHERE id = '%d'" % (acceptedNumber,allsubmissionsNumber,problem_id)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
def ModifyUserInformation(user_id):
acceptedNumber=0
allsubmissionsNumber=0
solveNumber=0
submissionsProblemNumber=0
db = MySQLdb.connect("localhost","root","WuYing","jxnuoj",charset="utf8")
cursor = db.cursor()
# update accepted
sql1 = "select * from user_problem where judge_status = '%d' and user_id = '%d' " % (0,user_id)
#submissions
sql2 = "select * from user_problem where user_id = '%d' " % (user_id)
#solve_problem
sql3 = "select distinct problem_id from user_problem where judge_status = '%d' and user_id = '%d'" % (0, user_id)
#submissions_problem
sql4 = "select distinct problem_id from user_problem where user_id = '%d' " % (user_id)
try:
acceptedNumber=cursor.execute(sql1)
allsubmissionsNumber = cursor.execute(sql2)
solveNumber = cursor.execute(sql3)
submissionsProblemNumber = cursor.execute(sql4)
db.commit()
except:
db.rollback()
sql="UPDATE user SET accepted = '%d',submissions='%d',solve_problem='%d',Submitted_problem='%d' WHERE id = '%d'" % (acceptedNumber,allsubmissionsNumber,solveNumber,submissionsProblemNumber,user_id)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
def Judge(contest_id,sourcefile,problem,TIME_LIMIT,MEMORY_LIMIT):
answer={'exe_time':0,'exe_mem':0,'judge_status':0}
problem=str(problem)
PROBLEMDIR = 'problems'
# CODEDIR = 'codes'
# Verdicts
verdict = { 'ACCEPTED' : 0 ,'WA' : 1,'TLE' : 2,'MLE' : 3,'RE' : 4,'CE' : 5,'OLE' : 6,'ILE' : 7,'PE' : 8 }
# TIME_LIMIT = string.atoi(sys.argv[3],10)
# TIME_LIMIT = int(sys.argv[3])
# MEMORY_LIMIT = int(sys.argv[4])
# Parse commandlines options
# //for example $destFile="problems/wuying/1000_1.cpp"
# sourcefile = sys.argv[1]
debug("sourcefile"+sourcefile)
# problem = sys.argv[2]
# path = "."+os.sep+"tmp"
# ext = sourcefile.split(".")[1]
path = "/".join(sourcefile.split("/")[:-1])
ext = sourcefile.split(".")[1]
# runid = sourcefile.split(".")[0]
"""
print sourcefile 1.cpp
print problem 1001
print path ./tmp
print ext cpp
"""
# check if the code is too long
# a = open(CODEDIR+os.sep+sourcefile,"r")
a = open(sourcefile,"r")
codecode = a.read()
a.close()
if len(codecode) >= 500000:
debug("ILE")
# sys.exit(verdict["ILE"])
answer['judge_status']=7
return answer
if ext == "cpp":
compile = "g++ -lm %s -o %s 2> /dev/null" % (sourcefile, path + "/a.out")
elif ext == "c":
compile = "gcc -lm %s -o %s 2> /dev/null" % (sourcefile, path + "/a.out")
ModifyStatus(contest_id,9)
if os.system(compile):
debug("CE")
# sys.exit(verdict["CE"])
answer['judge_status'] = 5
return answer
# run = path+os.sep+runid
# infile = PROBLEMDIR + os.sep + problem + os.sep + problem + ".IN"
# outfile= path+os.sep+runid+".OUT"
# file = sourcefile.split("/")[-1]
infile = PROBLEMDIR + "/" + str(problem) + "/in"
outfile = path + "/op"
runid = "./a.out"
debug(infile)
debug(outfile)
# Run
ModifyStatus(contest_id, 10)
debug("Running...")
p = subprocess.Popen( runid,stdin=open(infile,"r"),stdout=open(outfile,"w"),stderr=open("/dev/null","w"),cwd=path)
start = time.time()
tt=0
mm=0
while p.poll() == None:
# s = file("/proc/"+str(p.pid)+"/status",'r').read()
s=open("/proc/"+str(p.pid)+"/status").read()
if s.find('RSS') <0:
continue
s=s[s.find('RSS')+6:]
s=s[:s.find('kB')-1]
if mm < int(s):
mm = int(s)
if mm > MEMORY_LIMIT:
p.kill()
debug("MLE")
answer['exe_time'] = tt
answer['exe_mem'] = mm
answer['judge_status'] = 3
return answer
tt = int((time.time()-start)*1000)
if tt > TIME_LIMIT:
p.kill()
debug("TLE")
answer['exe_time'] = tt
answer['exe_mem'] = mm
answer['judge_status'] = 2
return answer
print "time cost:"+str(tt)+"ms"
print "mem cost:"+str(mm)+"kb"
answer['exe_time']=tt
answer['exe_mem']=mm
r = p.returncode
debug("Exit status : %d " % r )
if r != 0:
debug("RE")
answer['judge_status'] = 4
return answer
# compare output with expected out
# outputProduced = outfile
# outputExpected = PROBLEMDIR + os.sep + problem + os.sep + problem + ".OUT"
outputProduced = path + "/op"
outputExpected = PROBLEMDIR + "/" + str(problem) + "/out"
debug(outputProduced)
debug(outputExpected)
a = open(outfile,'r')
codecode = a.read()
# debug(len(codecode))
if len(codecode) >= 10000000:
debug( "OLE")
answer['judge_status'] = 6
return answer
timefile= open(path+os.sep+problem+".TIME","w")
memfile = open(path+os.sep+problem+".MEM","w")
timefile.write(str(tt))
memfile.write(str(mm))
timefile.close()
memfile.close()
# if compare_files(outputProduced,outputExpected) == True:
# if file_same(outputProduced,outputExpected) == True:
# debug("AC")
# sys.exit( verdict["ACCEPTED"] )
# else:
# debug("PE")
# sys.exit( verdict["PE"] )
# else:
# debug("WA")
# sys.exit(verdict["WA"])
debug("start judge")
if file_same(outputProduced,outputExpected) == True:
debug("AC")
# sys.exit(verdict["ACCEPTED"])
answer['judge_status'] = 0
return answer
else :
if compare_files(outputProduced,outputExpected) == True:
debug("PE")
answer['judge_status'] = 11
return answer
else:
debug("WA")
answer['judge_status'] = 1
return answer
def getTimeAndMemory(id):
ans=[]
db = MySQLdb.connect("localhost","root","WuYing","jxnuoj",charset="utf8")
cursor = db.cursor()
sql = "select * from problem where id = '%d' " % (id)
try:
aa=cursor.execute(sql)
results = cursor.fetchall()
for row in results:
ans.append(row[2])
ans.append(row[3])
except:
print "Error: unable to fecth data"
db.close()
return ans
def Query():
verdict = {0:'ACCEPTED', 1:'WA', 2:'TLE', 3:'MLE', 4:'RE', 5:'CE', 6:'OLE', 7:'ILE', 8:'PE'}
db = MySQLdb.connect("localhost","root","WuYing","jxnuoj",charset="utf8")
cursor = db.cursor()
sql = "select * from user_problem where judge_status = '%d' " % (8)
try:
aa=cursor.execute(sql)
results = cursor.fetchall()
for row in results:
# ModifyStatus(row[0],9)
timeAndMemory=getTimeAndMemory(row[2])
answer=Judge(row[0],row[10],row[2],timeAndMemory[0],timeAndMemory[1])
ModifyTimeAndMemoryAndStatus(row[0],answer['exe_time'],answer['exe_mem'],answer['judge_status'])
ModifyUserInformation(row[1])
ModifyProblemInformation(row[2])
# ModifyStatus(row[0],10)
except:
print "Error: unable to fecth data"
db.close()
if __name__=="__main__":
while True:
Query()
time.sleep(0.5)
# Query()