def setScoreForAssignment(self,score, assignmentNumber, credit): exists = False for a in self.assignments: if a.number == assignmentNumber: exists = True a.score = score break if not exists: assignment = Assignment() assignment.number = assignmentNumber assignment.score = score assignment.credit = credit self.assignments.append(assignment)
def marking(): name = request.args["name"] return render_template("marking.html", name=name, files=execute_files(name), css=HtmlFormatter().get_style_defs(), assignment=Assignment())
def show_feedback(name): if request.method == "POST": a = Assignment(MARKING_SCHEME) # TODO: fix this at some point data = [ float(val) if val else 0.0 for (field, val) in request.values.items() if field != "submit" ] questions = [ v['contents'] for k, v in a.contents.items() if k != "Total" ] questions = list(chain.from_iterable(questions)) questions = [f"/{q['mark']} - {q['description']}" for q in questions] grade = sum(data) data.append(f"<b>Total: {grade}</b>") total = a.contents["Total"] pct = grade / total * 100 questions.append(f"<b>/{total} ({pct:.2f}%)</b>") return render_template("feedback.html", author=(a.marked_by, a.email), data=zip(questions, data), name=name, remarks="Nice job! " if pct > 80 else "") return "failure"
def test_add(self): assignments = Assignments() self.assertIsNotNone(assignments) assignment1 = Assignment(title="Title1", due_time="2018-01-01") assignments.add(assignment1) self.assertEqual(assignments[0], assignment1) self.assertEqual(len(assignments), 1) assignment2 = Assignment(title="Title2", due_time="2018-01-01") assignments.add(assignment2) self.assertEqual(len(assignments), 2) self.assertEqual(assignments[1], assignment2) assignments.remove(0) self.assertRaises(KeyError, lambda: assignments[0]) assignment3 = Assignment("Title3", "2018-1-1") assignments.add(assignment3) self.assertEqual(assignments[0], assignment3)
def assign_diversity(graph_name_list, method, dir, weight_prob=[],pp=0): p_list =['0.1', '0.2', '0.3'] fitness_list =[1, 2 ,3 ,4] kk = 5 for i in range(kk): print(i) for graph_name in graph_name_list: name = (graph_name.split('/')[-1]).replace('.gpickle', '') for f in fitness_list: for pr in p_list: flag= False if pp==0: name_new = dir + 'Results/' + name + '(P=' + pr + ')(f=' + str( f) + ')(method=' + str( method) + ')(weight=' + str(weight_prob) + ')(' + str(i) + ')' else: name_new = dir + 'Results/' + name + '(P=' + pr + ')(f=' + str( f) + ')(method=' + str( method) + ')(weight=' + str(pp) + ')(' + str(i) + ')' try: nx.read_gpickle(name_new + '.gpickle') except: flag=True if flag: G, position_list, candidate_dic, fitness_dic = Setup.read_sampled_graphs(dir, name,pr,i,f) G_new, M = FA.assignment(candidate_dic.copy(), position_list.copy(), fitness_dic.copy(),G,method=method, weight_probability=weight_prob.copy(),kk=pp) file = open(name_new + '.txt', 'w') for (u, v) in M: file.writelines(str(u) + '\t' + str(v) + '\n') file.close() nx.write_gpickle(G_new, name_new + '.gpickle')
def show_feedback(name): if request.method == "POST": a = Assignment() data = [ float(x[1]) if x[1].isnumeric() else 0 for x in request.values.items() if x[1] != "Create Feedback" ] questions = [q.contents for _, q in a.questions.items()] questions = list(chain.from_iterable(questions)) assert len(data) == len( questions), "Questions and marks are not the same length" grade = sum(data) data.append(grade) pct = grade / a.total * 100 questions.append(f"/{a.total} Total ({pct:.2f}%)") return render_template("feedback.html", data=dict(zip(questions, data)), name=name, remarks="Nice job! " if pct > 80 else "") return "failure"
def testloadratings(ratingstablename, filepath, openconnection, rowsininpfile): """ Tests the load ratings function :param ratingstablename: Argument for function to be tested :param filepath: Argument for function to be tested :param openconnection: Argument for function to be tested :param rowsininpfile: Number of rows in the input file provided for assertion :return:Raises exception if any test fails """ MyAssignment.loadratings(ratingstablename, filepath, openconnection) # Test 1: Count the number of rows inserted with openconnection.cursor() as cur: cur.execute('SELECT COUNT(*) from {0}'.format(RATINGS_TABLE)) count = int(cur.fetchone()[0]) if count != rowsininpfile: raise Exception( 'Expected {0} rows, but {1} rows in \'{2}\' table'.format(rowsininpfile, count, RATINGS_TABLE))
def testSetDeadline(self): deadline = "17-Apr-17" questionA = Question.Question("25306175", "MCQ", "What is 13 + 13", "26", "1", "Unit 1 Test", "01-Nov-17", "1", "1") ass1 = Assignment.Assignment("123", [questionA]) ass1.setDeadline(deadline) self.assertTrue(ass1.getDeadline() == deadline)
def testroundrobinpartition(ratingstablename, numberofpartitions, openconnection, robinpartitiontableprefix, partitionstartindex): """ Tests the round robin partitioning for Completness, Disjointness and Reconstruction :param ratingstablename: Argument for function to be tested :param numberofpartitions: Argument for function to be tested :param openconnection: Argument for function to be tested :param robinpartitiontableprefix: This function assumes that you tables are named in an order. Eg: robinpart1, robinpart2... :param partitionstartindex: Indicates how the table names are indexed. Do they start as robinpart1, 2 ... or robinpart0, 1, 2... :return:Raises exception if any test fails """ try: MyAssignment.roundrobinpartition(ratingstablename, numberofpartitions, openconnection) except Exception: # ignore any exceptions raised by function pass testrangeandrobinpartitioning(numberofpartitions, openconnection, robinpartitiontableprefix, partitionstartindex)
def testSetAssignmentId(self): deadline = "02-Feb-18" questionA = Question.Question("25306175", "MCQ", "What is 13 + 13", "26", "1", "Unit 1 Test", "01-Nov-17", "1", "1") ass1 = Assignment.Assignment("123", [questionA]) newId = "123" ass1.setAssignmentId(newId) self.assertTrue(ass1.getAssignmentId() == newId)
def testSetVisibilityFalse(self): questionC = Question.Question("33333333", "MCQ", "What is 22 + 33", "55", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionD = Question.Question("44444444", "MCQ", "What is 33 + 44", "77", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionC, questionD] ass1 = Assignment.Assignment("123", listOfQ) self.assertFalse(ass1.getVisibility())
def testGetNameNone(self): questionC = Question.Question("33333333", "MCQ", "What is 22 + 33", "55", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionD = Question.Question("44444444", "MCQ", "What is 33 + 44", "77", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionC, questionD] ass1 = Assignment.Assignment("123", listOfQ) self.assertTrue(ass1.getName() == None)
def testGetListOfQuestions(self): questionA = Question.Question("25306175", "MCQ", "What is 13 + 13", "26", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionB = Question.Question("21111111", "MCQ", "What is 13 + 14", "27", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionA, questionB] ass1 = Assignment.Assignment("123", listOfQ) self.assertTrue(ass1.getListOfQuestions() == listOfQ)
def testCheckIfPerfectTrue(self): questionC = Question.Question("33333333", "MCQ", "What is 22 + 33", "55", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionD = Question.Question("44444444", "MCQ", "What is 33 + 44", "77", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionC, questionD] ass1 = Assignment.Assignment("123", listOfQ) self.assertFalse(ass1.checkIfPerfect())
def testrangeinsert(ratingstablename, userid, itemid, rating, openconnection, expectedtablename): """ Tests the range insert function by checking whether the tuple is inserted in he Expected table you provide :param ratingstablename: Argument for function to be tested :param userid: Argument for function to be tested :param itemid: Argument for function to be tested :param rating: Argument for function to be tested :param openconnection: Argument for function to be tested :param expectedtablename: The expected table to which the record has to be saved :return:Raises exception if any test fails """ try: MyAssignment.rangeinsert(ratingstablename, userid, itemid, rating, openconnection) except Exception: # ignore any exceptions raised by function pass if not testrangerobininsert(expectedtablename, itemid, openconnection, rating, userid): raise Exception( 'Range insert failed! Couldnt find ({0}, {1}, {2}) tuple in {3} table'.format(userid, itemid, rating, expectedtablename))
def assign_diversity_bruteforth(graph_name_list, method, dir, weight_prob=[]): p_list = ['0.1'] fitness_list = [1, 2] kk = 2 for graph_name in graph_name_list: name = (graph_name.split('/')[-1]).replace('.gpickle', '') print('#####################################################') print(name) for f in fitness_list: print('#####################################################') print(f) for pr in p_list: print('#####################################################') print(pr) for i in range(kk): print(i) flag = False weight_prob1 = [1, 1, 0] name_new = dir + 'Results/' + name + '(P=' + pr + ')(f=' + str( f) + ')(method=' + str(40) + ')(weight=' + str( weight_prob1) + ')(' + str(i) + ')' try: nx.read_gpickle(name_new + '.gpickle') except: flag = True if flag: G, position_list, candidate_dic, fitness_dic = Setup.read_sampled_graphs( dir, name, pr, i, f) Gs = FA.assignment(candidate_dic.copy(), position_list.copy(), fitness_dic.copy(), G, method=method, weight_probability=weight_prob) j = 0 for G_new, M in Gs: name_new = dir + 'Results/' + name + '(P=' + pr + ')(f=' + str( f) + ')(method=' + str(method) + str( j) + ')(weight=' + str( weight_prob) + ')(' + str( i) + ')' # .gpickle' j += 1 file = open(name_new + '.txt', 'w') for (u, v) in M: file.writelines(str(u) + '\t' + str(v) + '\n') file.close() nx.write_gpickle(G_new, name_new + '.gpickle')
def testSetStudentAnswerAtIndex(self): questionA = Question.Question("25306175", "MCQ", "What is 13 + 13", "26", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionB = Question.Question("21111111", "MCQ", "What is 13 + 14", "27", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionA, questionB] ass1 = Assignment.Assignment("123", listOfQ) studentAnswer = 27 ass1.setStudentAnswerAtIndex(1, studentAnswer) self.assertTrue(questionB.getStudentAnswer() == studentAnswer)
def get_assignments_for_criteria(db, cr_id): c = db.cursor() c.execute("SELECT * FROM assignments WHERE criteria_id=?;", (cr_id, )) y = [] for rows in c.fetchall(): criteria_id = rows[1] if criteria_id == -1: raise Exception('Assignment ' + rows[2] + ' does not have a valid criteria') criteria = CriteriaDBHelper.get_criteria(db, criteria_id) y.append( Assignment(rows[0], criteria, rows[2], rows[3], rows[4], Grade(rows[6], rows[5]), rows[7])) return y
def testInit(self): questionA = Question.Question("25306175", "MCQ", "What is 13 + 13", "26", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionB = Question.Question("25301111", "MCQ", "What is 56 - 26", "30", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionA, questionB] myAssignment = Assignment.Assignment("123", listOfQ) initSuccess = ((len(myAssignment.getAssignmentId()) == 3) and (myAssignment.getVisibility() == False) and (myAssignment.getDeadline() == None) and (myAssignment.getName() == None) and myAssignment.getListOfQuestions() == listOfQ) self.assertTrue(initSuccess)
def makeAssignment(L, addInfo, profId, assignmentId): '''(list, list, str, str) -> Assignment Return an Assignment object based on the given questions in L, the additional information in addInfo, the professor id, and the assignment id Note: the returned Assignment object will consist of Question objects Note: L is the list of all the selected questions [[q1], [q2], [q3], ...], where each q consists of the question id, question topic, question type, question body, range of variables, and question formula ''' questionObjs = [] result = [] for question in L: allrange = question[4].split(',') vals = [] for index in allrange: vals.append(RandomInRange(index.split('|'))) i = 0 Q_B = question[3] Q_A = question[5] for val in vals: old = 'VAR' + str(i) Q_B = Q_B.replace(old, str(vals[i])) Q_A = Q_A.replace(old, str(vals[i])) leftk = Q_B.find('(') rightk = Q_B.find(')') Q_B = Q_B[:leftk] + Q_B[rightk + 1:] i += 1 answer = cal_exp(mixed_operation(Q_A)) # Initialize a new Question object newQ = Question(question[0], question[2], Q_B, answer, assignmentId, addInfo[0], addInfo[1], profId, addInfo[2]) # Append the new question into questionObjs questionObjs.append(newQ) # Append the necessary question info into result result.append([ question[0], question[2], Q_B, answer, assignmentId, addInfo[0], addInfo[1], profId, addInfo[2] ]) newAssignmentObj = Assignment(assignmentId, questionObjs) with open("Assignment.csv", "a") as csvfile: csvfile.seek(0) writer = csv.writer(csvfile) writer.writerows(result) return newAssignmentObj
def testSetListOfQuestions(self): questionA = Question.Question("25306175", "MCQ", "What is 13 + 13", "26", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionB = Question.Question("21111111", "MCQ", "What is 13 + 14", "27", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ = [questionA, questionB] ass1 = Assignment.Assignment("123", listOfQ) questionC = Question.Question("33333333", "MCQ", "What is 22 + 33", "55", "1", "Unit 1 Test", "01-Nov-17", "1", "1") questionD = Question.Question("44444444", "MCQ", "What is 33 + 44", "77", "1", "Unit 1 Test", "01-Nov-17", "1", "1") listOfQ2 = [questionC, questionD] ass1.setListOfQuestions(listOfQ2) self.assertTrue(ass1.getListOfQuestions() == listOfQ2)
def getAllAssignments(s): # # Find all files in the Assignment folder for the <s> tag, reads its content and return an array with assignment data # # Return: # array of all files' data or None if <Assignments> does not exists # dir = assignmentFolder assignments = [] if type(s) is not str: return None if os.path.isdir(dir): # list file names in the assignment folder files = os.listdir(dir) for f in files: # looking for homework files if s in f: try: openedFile = open(dir + "/" + f, "r") #reading content numStudents = int(openedFile.readline().split(',')[1]) assignmentType = openedFile.readline().split(',')[1] assignmentName = openedFile.readline().split(',')[1] assignedDate = openedFile.readline().split(',')[1] dueDate = openedFile.readline().split(',')[1] maxPoints = openedFile.readline().split(',')[1] studentScoreData = [] openedFile.readline() openedFile.readline() for x in range(0, numStudents): studentScoreData.append(openedFile.readline()[:-1]) openedFile.close() a = Assignment.Assignment(assignmentType, assignmentName, assignedDate, dueDate, maxPoints, studentScoreData) assignments.append(a) except IOError: return None return assignments #sorted(assignments,key=lambda x : x.assignmentName) return None
def get_assignment(db, id): # # query db for specified assignment c = db.cursor() c.execute("SELECT * FROM assignments WHERE id=?", (id, )) # # get a row from the cursor rows = c.fetchone() if not rows == None: # get the criteria if it exists criteria_id = rows[1] if criteria_id == -1: raise Exception('Assignment ' + rows[3] + ' does not have a valid criteria') criteria = CriteriaDBHelper.get_criteria(db, criteria_id) return Assignment(rows[0], criteria, rows[2], rows[3], rows[4], Grade(rows[6], rows[5]), rows[7]) else: return None
def assign_diversity(graph_name_list, method, dir, weight_prob=[], pp=0): p_list = ['0.1', '0.2', '0.3'] kk = 100 for i in range(kk): print(i) for name in graph_name_list: G1 = nx.read_gpickle(dir + 'datasets/' + name + '.gpickle') G1 = Setup.pre_process(G1) for pr in p_list: G = G1.copy() position_list, candidate_dic = Setup.generate_PC(G.copy(), p=float(pr), k=1) att = nx.get_node_attributes(G, 'att') for node in position_list: att[node] = 'None' nx.set_node_attributes(G, att, 'att') position_list = [str(item) for item in position_list] fitness_dic = gen_fitness_team(name, position_list, candidate_dic, G) if pp == 0: name_new = dir + 'Results/' + name + '(P=' + pr + ')(f=' + str( 1) + ')(method=' + str(method) + ')(weight=' + str( weight_prob) + ')(' + str(i) + ')' else: name_new = dir + 'Results/' + name + '(P=' + pr + ')(f=' + str( 1) + ')(method=' + str(method) + ')(weight=' + str( pp) + ')(' + str(i) + ')' G_new, M = FA.assignment(candidate_dic.copy(), position_list.copy(), fitness_dic.copy(), G, method=method, weight_probability=weight_prob.copy(), kk=pp) file = open(name_new + '.txt', 'w') for (u, v) in M: file.writelines(str(u) + '\t' + str(v) + '\n') file.close() nx.write_gpickle(G_new, name_new + '.gpickle')
def marking(): name = request.args["name"] file_dir = FROM_UPLOADS(name.replace(" ", "-")) file_list = [Path(p) for p in glob(f"{file_dir}/*.py")] out = execute_files(file_list) """ try: out = execute_files(file_list) except Exception as e: return f"ERR HERE: {e.with_traceback(e.__traceback__)}" """ if not out: return f"Empty output: {file_list}" return render_template("marking.html", name=re.sub(r"(?<!-.)-", ", ", name, count=1).replace("-", " "), files=out, css=HtmlFormatter().get_style_defs(), assignment=Assignment(MARKING_SCHEME))
def after_test_script_ends_middleware(openconnection, databasename): # Use it if you want to MyAssignment.after_test_script_ends_middleware(openconnection, databasename)
def before_test_script_starts_middleware(openconnection, databasename): MyAssignment.before_test_script_starts_middleware(openconnection, databasename)
def after_db_creation_middleware(databasename): # Use it if you want to MyAssignment.after_db_creation_middleware(databasename)
def before_db_creation_middleware(): # Use it if you want to MyAssignment.before_db_creation_middleware()
def testdelete(openconnection): # Not testing this piece!!! MyAssignment.deletepartitionsandexit(openconnection)
def testdelete(openconnection): # Not testing this piece!!! MyAssignment.deleteeverythingandexit(openconnection)