def create_problem(): """ Input data contains the key value pair, which is passed to the api in order to create the problemID""" client = ProblemsClientV4(problem_accessToken, problem_endpoint) data = request.get_json() output = client.problems.create(data['name'], masterjudge_id=1001, body=data['body']) time.sleep(0.5) connection = mysql.connector.connect(host=database_auth['DB Host'], user=database_auth['DB Username'], port=3306, passwd=database_auth['DB Password'], db=database_auth['Database']) cursor = connection.cursor() Created_Date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') level = data['level'] response = client.problems.get(output['id']) val = (response['id'], response['code'], response['name'], response['shortBody'], response['body'], json.dumps(response['type']), response['interactive'], json.dumps(response['masterjudge']['id']), json.dumps(response['testcases']), json.dumps(response['lastModified']), json.dumps(response['permissions']), Created_Date, level) sql_query = "INSERT INTO sphere_engine_problem_details (id,code,name,shortBody,body,type,interactive,masterjudge,testcases,lastModified, permissions,Created_Date,level) VALUES (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s,%s,%s,%s)" cursor.execute(sql_query, val) connection.commit() connection.close() return jsonify(output)
def testing(request, test_case_id): try: b = Test.objects.get(test_case_id=test_case_id) except: raise Http404("Завдання не знайдені") test_time = b.test_case.case_duration * 60 accessToken = '82c0c5507c39a743ef533af852e97b11' endpoint = 'd32fffd4.problems.sphere-engine.com' client = ProblemsClientV4(accessToken, endpoint) problemId = b.sphere_id try: response = client.problems.get(problemId) except SphereEngineException as e: if e.code == 401: print('Invalid access token') elif e.code == 403: print('Access to the problem is forbidden') elif e.code == 404: print('Problem does not exist') return render(request, 'test/test.html', {'test_case': b, 'subjects_list': subjects_list, 'response': response, 'test_time': test_time})
def create_testcases(): client = ProblemsClientV4(problem_accessToken, problem_endpoint) test_data = request.get_json() response = client.problems.createTestcase(test_data['id'], test_data['input_file'], test_data['output_file'], test_data['timelimit'], test_data['judgeId']) time.sleep(0.5) """ Submission of test cases into the database """ connection = mysql.connector.connect(host=database_auth['DB Host'], user=database_auth['DB Username'], port=3306, passwd=database_auth['DB Password'], db=database_auth['Database']) cursor = connection.cursor() cursor.execute("""select problem_id from sphere_engine_testcase;""") list_probids = cursor.fetchall() problemids = [str(list_probids[i][0]) for i in range(len(list_probids))] lang = list(test_data['check_file'].keys())[0] if str(test_data['id']) not in problemids: sql_query = """INSERT INTO sphere_engine_testcase (number,problem_id,input_file,output_file,created_date,timelimit,judgeId,check_file) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);""" val = (response['number'], test_data['id'], test_data['input_file'], test_data['output_file'], datetime.now().strftime('%Y-%m-%d'), test_data['timelimit'], test_data['judgeId'], json.dumps(test_data['check_file'])) cursor.execute(sql_query, val) connection.commit() else: cursor.execute("SET SQL_SAFE_UPDATES=0") connection.commit() """ get the available check_file dictionary from the database""" cursor.execute( """Select check_file from sphere_engine_testcase where problem_id = {}""" .format(test_data['id'])) check_file_dictionary = eval(cursor.fetchall()[0][0]) if lang in check_file_dictionary: check_file_dictionary[lang] = test_data['check_file'][lang] else: check_file_dictionary[lang] = test_data['check_file'][lang] sql_query = """INSERT INTO sphere_engine_testcase (number,problem_id,input_file,output_file,created_date,timelimit,judgeId,check_file) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);""" val = (response['number'], test_data['id'], test_data['input_file'], test_data['output_file'], datetime.now().strftime('%Y-%m-%d'), test_data['timelimit'], test_data['judgeId'], str(json.dumps(check_file_dictionary))) cursor.execute(sql_query, val) connection.commit() cursor.close() connection.close() metadata = response metadata.update(test_data) return jsonify(metadata)
def update_problem(): client = ProblemsClientV4(problem_accessToken, problem_endpoint) data = request.get_json() response = client.problems.update(data['id'], data['name'], 1001, data['body'], data['interactive']) # update the same in local database. connection = mysql.connector.connect(host=database_auth['DB Host'], user=database_auth['DB Username'], port=3306, passwd=database_auth['DB Password'], db=database_auth['Database']) cursor = connection.cursor() cursor.execute("SET SQL_SAFE_UPDATES=0") connection.commit() response = client.problems.get(data['id']) list_sphere_keys = list(response.keys()) values = (response['id'], response['code'], response['name'], response['shortBody'], response['body'], json.dumps(response['type']), response['interactive'], json.dumps(response['masterjudge']['id']), json.dumps(response['testcases']), json.dumps(response['lastModified']), json.dumps(response['permissions'])) """ update the fields in the database on the basis of incoming data from sphere engine""" for i in range(len(list_sphere_keys)): cursor.execute( """UPDATE sphere_engine_problem_details SET {}=%s where id=%s;""". format(list_sphere_keys[i]), ( values[i], data['id'], )) connection.commit() cursor.close() connection.close() return jsonify({ "Data Updated in the database": "True", 'newproblemName': response['name'] })
""" Example presents error handling for submissions.createWithTarSource() API method """ from sphere_engine import ProblemsClientV4 from sphere_engine.exceptions import SphereEngineException # define access parameters accessToken = '<access_token>' endpoint = '<endpoint>' # initialization client = ProblemsClientV4(accessToken, endpoint) # API usage problemId = 42 tarSource = '<tar_source>' compiler = 11 # C language try: response = client.submissions.createWithTarSource(problemId, tarSource, compiler) # response['id'] stores the ID of the created submission except SphereEngineException as e: if e.code == 401: print('Invalid access token') elif e.code == 402: print('Unable to create submission') elif e.code == 400: print('Error code: ' + str(e.error_code) + ', details available in the message: ' + str(e))
def setUp(self): self.client = ProblemsClientV4('access-token', 'endpoint')
def update_testcase(): client = ProblemsClientV4(problem_accessToken, problem_endpoint) data = request.get_json() key_list = list(data.keys()) list_all_params = [ 'id', 'number', 'input_file', 'output_file', 'timelimit', 'judgeId', 'active', 'check_file' ] diff_list = list(set(list_all_params) - set(key_list)) """ Assign each element in diff_list as None""" val = {} for i in range(len(data)): val[key_list[i]] = data[key_list[i]] optional_params = {} for i in range(len(diff_list)): optional_params[diff_list[i]] = None val.update(optional_params) response = client.problems.updateTestcase(val['id'], val['number'], val['input_file'], val['output_file'], val['timelimit'], val['judgeId'], val['active']) # update the same in local database. connection = mysql.connector.connect(host=database_auth['DB Host'], user=database_auth['DB Username'], port=3306, passwd=database_auth['DB Password'], db=database_auth['Database']) cursor = connection.cursor() cursor.execute('set innodb_lock_wait_timeout=10000') connection.commit() cursor.execute("SET SQL_SAFE_UPDATES=0") connection.commit() """ get the latest updated testcases of the problemId""" url = "https://{}/api/v4/problems/{}/testcases?access_token={}".format( problem_auth['endpoint'], data['id'], problem_auth['token']) testcases = requests.get(url).json() numbers = [ testcases['items'][i]['number'] for i in range(len(testcases['items'])) ] active = [ testcases['items'][i]['active'] for i in range(len(testcases['items'])) ] judge_id = [ testcases['items'][i]['judge'] for i in range(len(testcases['items'])) ] testcase_dict = {'number': numbers, 'active': active, 'judge_id': judge_id} key_list_excl_id = key_list[1:] ## check if the check file is passed or not? if 'check_file' in key_list_excl_id: #data['check_file'] =json.dumps(data['check_file']) cursor.execute( """select check_file from sphere_engine_testcase where problem_id= {}""" .format((data['id']))) check_file_dict = eval(cursor.fetchall()[0][0]) check_file_dict.update(data['check_file']) cursor.execute( """update sphere_engine_testcase set check_file=%s where problem_id=%s""", (json.dumps(check_file_dict), data['id'])) connection.commit() cursor.execute( """update sphere_engine_testcase SET test_case_dict=%s where problem_id=%s""", (str(json.dumps(testcase_dict)), data['id'])) connection.commit() else: for i in range(len(key_list_excl_id)): if key_list_excl_id[i] in ['number', 'active']: cursor.execute( """update sphere_engine_testcase set test_case_dict=%s where problem_id=%s""", (str(json.dumps(testcase_dict)), data['id'])) connection.commit() else: cursor.execute( """update sphere_engine_testcase set {}=%s where problem_id=%s""" .format(key_list_excl_id[i]), (data[key_list_excl_id[i]], data['id'])) connection.commit() connection.close() cursor.close() return jsonify({'Updated': True})
def get_result(): client = ProblemsClientV4(problem_accessToken, problem_endpoint) connection = mysql.connector.connect(host=database_auth['DB Host'], user=database_auth['DB Username'], port=3306, passwd=database_auth['DB Password'], db=database_auth['Database']) cursor = connection.cursor() query_parameters = request.args candidatename = query_parameters.get('userName') problem_name = query_parameters.get('problemName') cursor.execute( """select id from sphere_engine_problem_details where name=%s; """, (problem_name, )) problem_id = cursor.fetchall()[0][0] cursor.execute( """select id from sphere_engine_submissionid where candidatename=%s and problemId=%s; """, ( candidatename, problem_id, )) submission = cursor.fetchall() # Instantiate dict to store the values from the json result = {} string_id = [str(submission[i][0]) for i in range(len(submission))] for i in range(len(submission)): try: response = client.submissions.get(int(submission[i][0])) result[string_id[i]] = response except SphereEngineException as e: if e.code == 401: result = 'Invalid access token' elif e.code == 403: result = 'Access to the submission is forbidden' elif e.code == 404: result = 'Submission does not exist' # Store the data if and only if the Submission id is not in databse time.sleep(5.0) ids = [submission[i][0] for i in range(len(submission))] # match submission id with result table in databse cursor.execute( """select submissionid from result_sphere_engine where candidateName=%s and problem_name=%s""", ( candidatename, problem_name, )) result_db_ids = cursor.fetchall() result_db_ids = [result_db_ids[i][0] for i in range(len(result_db_ids))] for ID in ids: if ID in result_db_ids: None else: """ Result Insertion into DB""" cursor = connection.cursor() sql_query = """show columns from result_sphere_engine;""" cursor.execute(sql_query) column_keys = cursor.fetchall() columns = [column_keys[i][0] for i in range(len(column_keys) - 1)] list_result_keys = list(result.keys()) place_holder = ['%s' for i in range(len(columns))] for i in range(len(list_result_keys)): sql_query = """INSERT INTO result_sphere_engine ({}) VALUES({});""".format( ",".join(columns), ",".join(place_holder)) val = ( list_result_keys[i], result[list_result_keys[i]]['compiler']['id'], result[list_result_keys[i]]['compiler']['version']['name'], result[list_result_keys[i]]['executing'], result[list_result_keys[i]]['problem']['code'], result[list_result_keys[i]]['problem']['id'], result[list_result_keys[i]]['problem']['name'], json.dumps(result[list_result_keys[i]]['result']), result[list_result_keys[i]]['result']['status']['name'], candidatename) cursor.execute(sql_query, val) connection.commit() connection.close() return jsonify(result)
def submission_id(): client = ProblemsClientV4(problem_accessToken, problem_endpoint) submission_data = request.get_json() source = submission_data['source'] lang = submission_data['language'] problem_name = submission_data['problem_name'] candidate_name = submission_data['candidate_name'] connection = mysql.connector.connect(host=database_auth['DB Host'], user=database_auth['DB Username'], port=3306, passwd=database_auth['DB Password'], db=database_auth['Database']) cursor = connection.cursor() try: cursor.execute( """select compilerID from sphere_engine_languages where language=%s""", (lang, )) compilerID = cursor.fetchall()[0][0] except IndexError: cursor.execute("""select language from sphere_engine_languages;""") all_lang = cursor.fetchall() response = Response( json.dumps( "Please enter the correct language. Avalialable languages are {}" .format(all_lang))) response.status_code = 400 cursor.execute( """select id from sphere_engine_problem_details where name = %s;""", (problem_name, )) problem_id = cursor.fetchone()[0] """get the required pckgs for the checkfile for specific language""" cursor.execute( """select required_pckgs from sphere_engine_testcase where problem_id=%s;""", (problem_id, )) required_pckgs = cursor.fetchall()[0][0] required_pckgs = eval(required_pckgs) # get required package for specific language try: opening_statement = required_pckgs[lang] except KeyError: opening_statement = "\n" """ get the checker file specfic to the compiler and the problemId""" cursor.execute( """select check_file from sphere_engine_testcase where problem_id=%s;""", (problem_id, )) check_file_all = eval(cursor.fetchall()[0][0]) try: check_file = check_file_all[lang] """ Send the file to the compiler""" submission_file = opening_statement + source + check_file except KeyError: None """ Submission file """ try: try: response = client.submissions.create(problem_id, submission_file, compilerID) """ Database Insertion of Submission Ids""" sql_query = """INSERT INTO sphere_engine_submissionid (id,language,sourcefile,problemId,candidatename) VALUES(%s, %s,%s,%s,%s);""" val = (response['id'], lang, source, problem_id, candidate_name) response = json.dumps({"submissionId": response['id']}) cursor.execute(sql_query, val) connection.commit() except NameError: None except SphereEngineException as e: if e.code == 401: response = 'Invalid access token' elif e.code == 402: response = 'Unable to create submission' elif e.code == 400: response = 'Error code: ' + str( e.error_code) + ', details available in the message: ' + str(e) connection.close() cursor.close() return response
'Content-Type', 'Authorization', 'Origin', 'X-Requested-With', 'Accept' ], "methods": ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] } }) problem_auth = { 'endpoint': 'b47c8916.problems.sphere-engine.com', 'token': '4c1e602f25ea827d81f3f84dbdbd9527' } # define access parameters problem_accessToken = problem_auth['token'] problem_endpoint = problem_auth['endpoint'] client = ProblemsClientV4(problem_accessToken, problem_endpoint) ### Compiler API compiler_auth = { "endpoint": "b47c8916.compilers.sphere-engine.com", "token": "6fc402f585b35ef7accf61facc636af0" } # define access parameters compiler_accessToken = compiler_auth["token"] compiler_endpoint = compiler_auth["endpoint"] compiler_client = CompilersClientV4(compiler_accessToken, compiler_endpoint) # Problem API initialization try: