def handle(self, *args, **options): course_id = 1 BASE_DIR = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) workbook = openpyxl.load_workbook(BASE_DIR + '/course_data.xlsx') sheet = workbook.get_sheet_by_name("Sheet1") for row in sheet: if row[0].row == 1: continue course_time_spaces = self.__get_course_times(row[8].value) course = Course(course_id=course_id, course_no=row[0].value, semester=row[1].value, university=row[2].value, campus=row[3].value, classification=row[4].value, course_name=row[5].value, professor=row[6].value, credit=row[7].value) course.save() course_id += 1 for course_time_space in course_time_spaces: course_time_space.course = course course_time_space.save()
class NotificationTests(TestCase): '''Tests related to the actual Notification functionality.''' def setUp(self): '''Set up the user infrastructure.''' #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() self.question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) self.question.save() def test_notification_creation(self): '''Test the creation of a notification.''' notification = Notification.objects.create( text="Notification test", recipient=self.user, link=self.question.get_absolute_url()) notification.read = True notification.save()
def save(self, **kw): u = Course(name=kw['name'], purpose=kw['purpose'], techerId=kw['techerId'], techerNumber=kw['techerNumber'], techerName=kw['techerName']) u.save()
def test_subcategory_creation(self): '''Tests creating a subcategory.''' course = Course(name="testing course", slug="testing-course") course.save() coursesection = CourseSection(name="Section 1", course=course) coursesection.save() category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=coursesection, ) category.save() subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=category, ) subcategory.save() assert len(course.get_all_categories()) == 1 assert len(course.get_all_subcategories()) == 1 #Test get_absolute_url resp = self.client.get(subcategory.get_absolute_url()) self.assertEqual(resp.status_code, 302)
def create_course_view(request): context = {} if request.method == 'POST': course_form = CourseCreateForm(request.POST, request.FILES, instance=request.user) course = Course() if course_form.is_valid(): data = course_form.cleaned_data course.name = data['name'] course.target_language = data['target_language'] course.source_language = data['source_language'] course.description = data['description'] course.author = request.user if (data['image']): course.image = data['image'] try: course.save() return redirect('course:detail', course.slug) except IntegrityError: print("error") context[ 'course_error'] = "You have already created a course with this name. Choose a different one." else: course_form = CourseCreateForm(instance=request.user) context['course_form'] = course_form return render(request, 'course/create_course.html', context)
def setUpTestData(cls): course = Course(title='TDDD12', body='Big boody') course.save() Comment.objects.create(author='TDDX21', body='Ave maria its ti me to shower', course=course)
def test_parse_course_object(self): test_data = { "id": "fc:fs:fs:emne:ntnu.no:EXPH0004:1", "type": "fc:fs:emne", "parent": "fc:org:ntnu.no", "membership": { "basic": "member", "fsroles": ["STUDENT"], "active": True, "notAfter": "2017-12-14T23:00:00Z", "subjectRelations": "undervisning", "displayName": "Student" }, "displayName": "Examen philosophicum for naturvitenskap og teknologi" } course = Course( course_code="EXPH0004", course_name="Examen philosophicum for naturvitenskap og teknologi", credit=7.5, average_grade=0, pass_rate=100.0) course.save() course_info = parse_course_object(test_data) self.assertEqual(course_info["course_code"], "EXPH0004") self.assertEqual( course_info["course_name"], "Examen philosophicum for naturvitenskap og teknologi") self.assertEqual(course_info["semester"], "H2017")
def setUpTestData(cls): course = Course(title='TDDD12', body='Big boody') course.save() assignment = Assignment(title='TDDD11', description='Very big yes', deadline=datetime.today(), course=course) assignment.save()
class UserProfileTests(TestCase): '''Tests related to the actual UserProfile and Model manager functionality.''' def setUp(self): '''Set up the user infrastructure.''' #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #User2 creation self.user2 = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #User3 creation self.user3 = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() def test_user_profile_creation(self): '''Test the user profile automatic creation.''' assert len(UserProfile.objects.all()) == 3 def test_user_profile_querysets(self): '''Test the user profile querysets.''' self.user.profile.update(course=self.course) self.user2.profile.update(course=self.course) self.user3.profile.update(course=self.course) self.user.profile.update(state="California") self.user2.profile.update(state="California") self.user3.profile.update(state="Nevada") self.user.profile.update(major="Engineering") self.user2.profile.update(major="Engineering") assert len( UserProfile.objects.get_profiles_by_course( course=self.course)) == 3 assert len( UserProfile.objects.get_profiles_by_major( course=self.course, major="Engineering")) == 2 assert len( UserProfile.objects.get_profiles_by_state(course=self.course, state="California")) == 2
def post(self, request): '''删除课程''' course_code = request.POST.get('courseCode') if not Course.objects.filter(code=course_code).exists(): return self.error(msg=f"course not exist", err=request.POST) else: try: course = Course(code=course_code, deleted=True) course.save() except Exception as e: return self.error(msg=str(e), err=e.args)
def seed_course_table(): course = Course(name="Testing 101", number=3342, credit_hours=3, department=(Department.get(Department.id == 1))) course.save() course = Course(name="Database Management Systems", number=4523, credit_hours=3, department=(Department.get(Department.id == 2))) course.save()
def test_post_review_invalid_JSON_formatting_and_values_course_exists(self): invalid_test_data = {"course_code": "TDT4290", "score": -2, "workload": "abx", "difficulty": 0} course = Course(course_code="TDT4290", course_name="Customer Driven Project", credit=15, average_grade=1, pass_rate=100.0) course.save() c = APIClient() c.credentials(HTTP_AUTHORIZATION='valid_token') response = c.post("/review/", data=invalid_test_data, format="json") self.assertEqual(response.status_code, 400)
def get_course(): """ 生成一个课程 :author: lishanZheng :date: 2020/01/03 """ clazz = get_clazz() teacher = get_teacher() course_data = get_course_data() course = Course(**course_data, clazz=clazz, teacher=teacher) course.save() return course
def setUpTestData(cls): course = Course(title='TDDD12', body='Big boody') course.save() assignment = Assignment(title='TDDD11', description='Very big yes', deadline=datetime.today(), course=course) assignment.save() handin = Handin.objects.create(holder='TDDX21', attached_files='ada/beda/ceda', assignment=assignment) handin.save()
def test_category_uniqueness(self): '''Testing the uniqueness of a Category.''' course = Course(name="testing course", slug="testing-course") course.save() coursesection = CourseSection(name="Section 1", course=course) coursesection.save() category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=coursesection, ) category.save() category2 = Category( name="Category 2 for testing course", slug="cat-2-testing-course", section=coursesection, ) category2.save() course2 = Course(name="testing course2", slug="testing-course2") course2.save() assert len(coursesection.category_set.all()) == 2 coursesection2 = CourseSection(name="Section 2", course=course2) coursesection2.save() category3 = Category( name="Category 2 for testing course", slug="cat-3-testing-course2", section=coursesection2, ) category3.save() #Same category name, different coursesection #Attempt to save to the same category category3.section = coursesection try: category3.save() #If save was successful, category and category3 violate uniqueness raise RuntimeError("category3 has the same credentials as course") except: pass
def fill(request): bank_courses = parse_page() bank_names = map(lambda b: b['bank'], bank_courses) db_banks = list(Bank.objects.all()) for b in bank_names: if len([i for i in db_banks if i.normal_name == b.lower()]) == 0: b_ = Bank(exact_name=b, normal_name=b.lower()) b_.save() db_banks.append(b_) for course in bank_courses: bank = [i for i in db_banks if i.normal_name == course['bank'].lower()][0] date = datetime.now().strftime("%Y-%m-%d %H:00") c = Course(currency=0, sell=course['usd']['sell'], buy=course['usd']['buy'], bank=bank, date=date) c.save() c = Course(currency=1, sell=course['eur']['sell'], buy=course['eur']['buy'], bank=bank, date=date) c.save() return render(request, 'fill.html', {})
def add_course(request): person = Person.objects.get(user=request.user) if person.role == 'TEACHER': if request.method == 'POST': try: title = request.POST['title'] description = request.POST['body'] code = request.POST['code'] print title, description, code new_course = Course(title=title, description=description, code=code, teacher=person, college=person.college) new_course.save() except Exception as e: print e else: return render_to_response('404.html', locals(), context_instance=RequestContext(request)) return render_to_response('add_course.html', locals(), context_instance=RequestContext(request))
def handle_noargs(self, **options): courses = simplejson.load(open(os.path.join(settings.COMMANDS_ROOT[0], 'courses.json'))) institute = Institute.objects.get(name='University of Waterloo') for course in courses['courses']: course = course['course'] title = course['title'] abbrev = course['faculty_acronym'] + ' ' + course['course_number'] description = course['description'] try: Course.objects.get(title=title) except Course.DoesNotExist: new_course = Course() new_course.title = title new_course.abbrev = abbrev new_course.institute = institute new_course.description = description new_course.save() print 'Added: %s' % new_course.abbrev
def setUpTestData(cls): test_user1 = User.objects.create_user(username='******', password='******') test_user1.save() course = Course(title='TDDD12', body='Big boody') course.save() assignment = Assignment(title='TDDD11', description='A desc.', deadline=datetime.today(), course=Course.objects.get(id=1)) assignment.save() Handin.objects.create(holder=f'Studentname', attached_files=f'tests/test.txt', assignment=assignment)
def addCourse(request): if not request.user.is_superuser: return printError( 'You have no permission to this page, please contact administration' ) errors = [] form = CourseForm() if request.method == 'POST': form = CourseForm(request.POST) if form.is_valid(): data = form.cleaned_data course = Course(title=data['title'], creater=request.user) course.save() return HttpResponseRedirect('/courselist/') context = {'form': form, 'errors': errors} return render_to_response('addcourse.html', context, context_instance=RequestContext(request))
def setUpTestData(cls): test_user1 = User.objects.create_user(username='******', password='******') test_user1.save() course = Course(title='TDDD12', body='Big boody') course.save() number_of_handins = 13 assignment = Assignment(title='TDDD11', description='A desc.', deadline=datetime.today(), course=Course.objects.get(id=1)) assignment.save() for handin_id in range(number_of_handins): Handin.objects.create(holder=f'Student {handin_id}', attached_files=f'url {handin_id}', assignment=assignment)
def test_parse_course_object_get_current_semester(self): test_data = { "id": "fc:fs:fs:emne:ntnu.no:TDT4290:1", "type": "fc:fs:emne", "parent": "fc:org:ntnu.no", "membership": { "basic": "member", "fsroles": ["STUDENT"], "active": True, "displayName": "Student" }, "displayName": "Kundestyrt prosjekt" } course = Course(course_code="TDT4290", course_name="Kundestyrt prosjekt", credit=15, average_grade=0, pass_rate=100.0) course.save() course_info = parse_course_object(test_data) self.assertEqual(course_info["course_code"], "TDT4290") self.assertEqual(course_info["course_name"], "Kundestyrt prosjekt") self.assertEqual(course_info["semester"], get_current_semester())
def import_course(self): print("Start import courses") for course in data: name = course['name'] timestamp = datetime.fromtimestamp(course['date']) languages = ', '.join(course['language']) level = ', '.join(course['level']) description = course['description'] subjects = ', '.join(course['subjects']) length = course['length'] effort = course['effort'] price = course['price'] institution = course['institution'] about = course['about-course'] content = course['content-course'] link_image = course['link-image'] print(course['name'], course['subjects']) if not Course.objects.filter(name=name, length=length).exists(): new_course = Course( name=name, timestamp=timestamp, language=languages, level=level, description=description, subject=subjects, length=length, effort=effort, price=price, institution=institution, about=about, content=content, link_image=link_image ) new_course.save() print("Import courses done")
def handle(self, *args, **options): updateR = False if options['rating']: updateR = True url = "http://www.registrar.ufl.edu/soc/201401/all/" page = urllib2.urlopen(url) soup = BeautifulSoup(page) list1 = list() # list of categories list2 = list() #list of website endings soup2 = [option.get('value') for option in soup.findAll('option')] contents = [str(x.text) for x in soup.find_all('option')] x = 0 for value in contents: # all option values all DEPARTMENTS list1.append(value) for value in soup2: # all endings for the web addresses per department list2.append(value) for idx, website in enumerate(list2): temp1 = website.strip() if not not temp1: print "OPENING: " + url + website page = urllib2.urlopen(url+ website) pages = str( page.read()) started = False moveA = False count = 0 y = 0 g = Course('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0') pq = PyQuery(pages) tag = pq('td') index = list2.index(website) for c in pq('td'): if (pq(c).text().__len__() == 8 and pq(c).text()[3:4] == " ") or (pq(c).text().__len__() == 9 and pq(c).text()[3:4] == " "): y = 0 x= x+1 if g.name != '0': g.dept = list1[index] # Department added to each course g.save() g = Course(x,' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ') g.name = pq(c).text() started = True moveA = False if (not (pq(c).text().__len__() == 8 and pq(c).text()[3:4] == " ") or (pq(c).text().__len__() == 9 and pq(c).text()[3:4] == " ")) and started == True: y = y+1 if y == 7 and moveA != True: g.lday = pq(c).text() if y == 21 and moveA != True: g.dday = pq(c).text() if y == 22 and moveA != True: g.dtime = pq(c).text() if y == 23 and moveA != True: g.dbuild = pq(c).text() if y == 24 and moveA != True: g.droom = pq(c).text() if y == 5 and moveA != True: if (len(pq(c).text()) == 0) or (len(pq(c).text()) == 1): moveA = True else: g.section = pq(c).text() if y == 6 and moveA != True: g.cedits = pq(c).text() if y == 8 and moveA != True: g.ltime = pq(c).text() if y == 9 and moveA != True: g.lbuild = pq(c).text() if y == 10 and moveA != True: g.lroom = pq(c).text() if y == 12 and moveA != True: g.cname = pq(c).text() if y == 13 and moveA != True: g.cinst = pq(c).text() if updateR: g.rmpr = getrmp(g.cinst,count) count = count +1 if y == 6 and moveA == True: g.section = pq(c).text() if y == 7 and moveA == True: g.cedits = pq(c).text() if y == 9 and moveA == True: g.ltime = pq(c).text() if y == 22 and moveA == True: g.dday = pq(c).text() if y == 23 and moveA == True: g.dtime = pq(c).text() if y == 24 and moveA == True: g.dbuild = pq(c).text() if y == 25 and moveA == True: g.dbuild = pq(c).text() if y == 8 and moveA == True: g.lday = pq(c).text() if y == 10 and moveA == True: g.lbuild = pq(c).text() if y == 11 and moveA == True: g.lroom = pq(c).text() if y == 13 and moveA == True: g.cname = pq(c).text() if y == 14 and moveA == True: g.cinst = pq(c).text() if updateR: g.rmpr = getrmp(g.cinst,count) count = count +1 if y == 36 and moveA == True: g.d2day = pq(c).text() if y == 37 and moveA == True: g.d2time = pq(c).text() if y == 38 and moveA == True: g.d2build = pq(c).text() if y == 39 and moveA == True: g.d2room = pq(c).text()
class AnalyticsTests(TestCase): '''Tests related to the actual Analytics functionality.''' def setUp(self): '''Set up the test and category infrastructure.''' #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) self.user2 = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #Question creation self.question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", index=1, ) self.question.save() def tearDown(self): '''Tear down the infrastructure.''' pass def test_category_data_set_creation(self): '''Tests creating a category data set.''' CategoryDataSet.objects.create( user=self.user, category=self.category, ) def test_subcategory_data_set_creation(self): '''Tests creating a subcategory data set.''' SubCategoryDataSet.objects.create( user=self.user, subcategory=self.subcategory, ) def test_category_data_set_misc(self): '''Test add_correct and add_miss.''' dataset = CategoryDataSet.objects.create( user=self.user, category=self.category, ) #Test attributes over 50 data entries missed = 0 correct = 0 for i in range(50): if i % 2: dataset.add_miss() missed += 1 assert dataset.missed == missed assert dataset.correct == correct assert dataset.percent == (correct * 100) / (correct + missed) else: dataset.add_correct() correct += 1 assert dataset.missed == missed assert dataset.correct == correct assert dataset.percent == (correct * 100) / (correct + missed) def test_subcategory_data_set_misc(self): '''Test add_correct and add_miss.''' dataset = SubCategoryDataSet.objects.create( user=self.user, subcategory=self.subcategory, ) #Test attributes over 50 data entries missed = 0 correct = 0 for i in range(50): if i % 2: dataset.add_miss() missed += 1 assert dataset.missed == missed assert dataset.correct == correct assert dataset.percent == (correct * 100) / (correct + missed) else: dataset.add_correct() correct += 1 assert dataset.missed == missed assert dataset.correct == correct assert dataset.percent == (correct * 100) / (correct + missed) def test_category_data_set_by_state(self): '''Test the retrieval by state function.''' self.user.profile.update(course=self.course) self.user2.profile.update(course=self.course) self.user.profile.update(state="California") self.user2.profile.update(state="California") self.user.profile.update(major="Engineering") self.user2.profile.update(major="Engineering") self.user.profile.update(university="UC Berkeley") self.user2.profile.update(university="UC Berkeley") dataset = CategoryDataSet.objects.create( user=self.user, category=self.category, ) dataset.add_correct() dataset.add_correct() dataset.add_correct() dataset.add_miss() dataset.add_miss() assert CategoryDataSet.objects.stats_by_state( category=self.category, state="California") == (3, 5) assert CategoryDataSet.objects.stats_by_major( category=self.category, major="Engineering") == (3, 5) assert CategoryDataSet.objects.stats_by_university( category=self.category, university="UC Berkeley") == (3, 5) dataset2 = CategoryDataSet.objects.create( user=self.user2, category=self.category, ) dataset2.add_correct() assert CategoryDataSet.objects.stats_by_state( category=self.category, state="California") == (4, 6) assert CategoryDataSet.objects.stats_by_major( category=self.category, major="Engineering") == (4, 6) assert CategoryDataSet.objects.stats_by_university( category=self.category, university="UC Berkeley") == (4, 6) def test_subcategory_data_set_by_state(self): '''Test the retrieval by state function.''' self.user.profile.update(course=self.course) self.user2.profile.update(course=self.course) self.user.profile.update(state="California") self.user2.profile.update(state="California") self.user.profile.update(major="Engineering") self.user2.profile.update(major="Engineering") self.user.profile.update(university="UC Berkeley") self.user2.profile.update(university="UC Berkeley") dataset = SubCategoryDataSet.objects.create( user=self.user, subcategory=self.subcategory, ) dataset.add_correct() dataset.add_correct() dataset.add_correct() dataset.add_miss() dataset.add_miss() assert SubCategoryDataSet.objects.stats_by_state( subcategory=self.subcategory, state="California") == (3, 5) assert SubCategoryDataSet.objects.stats_by_major( subcategory=self.subcategory, major="Engineering") == (3, 5) assert SubCategoryDataSet.objects.stats_by_university( subcategory=self.subcategory, university="UC Berkeley") == (3, 5) dataset = SubCategoryDataSet.objects.create( user=self.user2, subcategory=self.subcategory, ) dataset.add_correct() assert SubCategoryDataSet.objects.stats_by_state( subcategory=self.subcategory, state="California") == (4, 6) assert SubCategoryDataSet.objects.stats_by_major( subcategory=self.subcategory, major="Engineering") == (4, 6) assert SubCategoryDataSet.objects.stats_by_university( subcategory=self.subcategory, university="UC Berkeley") == (4, 6)
def test_subcategory_uniqueness(self): '''Testing the uniqueness of a SubCategory.''' course = Course(name="testing course", slug="testing-course") course.save() coursesection = CourseSection(name="Section 1", course=course) coursesection.save() category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=coursesection, ) category.save() subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=category, ) subcategory.save() subcategory2 = SubCategory( name="SubCategory 2 for testing course", slug="subcategory-2-testing-course", category=category, ) subcategory2.save() course2 = Course(name="testing course2", slug="testing-course2") course2.save() coursesection2 = CourseSection(name="Section 2", course=course2) coursesection2.save() category2 = Category( name="Category 1 for testing course", slug="cat-1-testing-course2", section=coursesection2, ) category2.save() #Saving a subcategory with the same name as another one that exists under a new category #Should save properly subcategory4 = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course2", category=category2, ) subcategory4.save() subcategory3 = SubCategory( name="SubCategory 2 for testing course", slug="subcategory-3-testing-course", category=category, ) try: subcategory3.save() #If save was successful, subcategory and subcategory3 violate uniqueness raise RuntimeError( "subcategory3 has the same credentials as course") except: pass
def handle(self, *args, **options): updateR = False if options['rating']: updateR = True url = "http://www.registrar.ufl.edu/soc/201401/all/" page = urllib2.urlopen(url) soup = BeautifulSoup(page) list1 = list() # list of categories list2 = list() #list of website endings soup2 = [option.get('value') for option in soup.findAll('option')] contents = [str(x.text) for x in soup.find_all('option')] x = 0 for value in contents: # all option values all DEPARTMENTS list1.append(value) for value in soup2: # all endings for the web addresses per department list2.append(value) for idx, website in enumerate(list2): temp1 = website.strip() if not not temp1: print "OPENING: " + url + website page = urllib2.urlopen(url + website) pages = str(page.read()) started = False moveA = False count = 0 y = 0 g = Course('0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0') pq = PyQuery(pages) tag = pq('td') index = list2.index(website) for c in pq('td'): if (pq(c).text().__len__() == 8 and pq(c).text()[3:4] == " ") or (pq(c).text().__len__() == 9 and pq(c).text()[3:4] == " "): y = 0 x = x + 1 if g.name != '0': g.dept = list1[ index] # Department added to each course g.save() g = Course(x, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ') g.name = pq(c).text() started = True moveA = False if (not (pq(c).text().__len__() == 8 and pq(c).text()[3:4] == " ") or (pq(c).text().__len__() == 9 and pq(c).text()[3:4] == " ")) and started == True: y = y + 1 if y == 7 and moveA != True: g.lday = pq(c).text() if y == 21 and moveA != True: g.dday = pq(c).text() if y == 22 and moveA != True: g.dtime = pq(c).text() if y == 23 and moveA != True: g.dbuild = pq(c).text() if y == 24 and moveA != True: g.droom = pq(c).text() if y == 5 and moveA != True: if (len(pq(c).text()) == 0) or (len(pq(c).text()) == 1): moveA = True else: g.section = pq(c).text() if y == 6 and moveA != True: g.cedits = pq(c).text() if y == 8 and moveA != True: g.ltime = pq(c).text() if y == 9 and moveA != True: g.lbuild = pq(c).text() if y == 10 and moveA != True: g.lroom = pq(c).text() if y == 12 and moveA != True: g.cname = pq(c).text() if y == 13 and moveA != True: g.cinst = pq(c).text() if updateR: g.rmpr = getrmp(g.cinst, count) count = count + 1 if y == 6 and moveA == True: g.section = pq(c).text() if y == 7 and moveA == True: g.cedits = pq(c).text() if y == 9 and moveA == True: g.ltime = pq(c).text() if y == 22 and moveA == True: g.dday = pq(c).text() if y == 23 and moveA == True: g.dtime = pq(c).text() if y == 24 and moveA == True: g.dbuild = pq(c).text() if y == 25 and moveA == True: g.dbuild = pq(c).text() if y == 8 and moveA == True: g.lday = pq(c).text() if y == 10 and moveA == True: g.lbuild = pq(c).text() if y == 11 and moveA == True: g.lroom = pq(c).text() if y == 13 and moveA == True: g.cname = pq(c).text() if y == 14 and moveA == True: g.cinst = pq(c).text() if updateR: g.rmpr = getrmp(g.cinst, count) count = count + 1 if y == 36 and moveA == True: g.d2day = pq(c).text() if y == 37 and moveA == True: g.d2time = pq(c).text() if y == 38 and moveA == True: g.d2build = pq(c).text() if y == 39 and moveA == True: g.d2room = pq(c).text()
def post(self, request): test = YouTubeTranscriptApi.get_transcript("R9rLCPW-eUI", languages=['id', 'en']) employee = Employee.objects.get(user=request.user) try: with transaction.atomic(): if employee.status == 0: raise PermissionDenied("user is not admin") courseName = request.data['course']['name'] category = request.data['course']['category'] img = request.data['course']['img'] description = request.data['course']['description'] price = request.data['course']["price"] learningPoint = request.data['course']["sylabus"] estimateTime = datetime.strptime(request.data['course']["estimate_time"], '%H:%M:%S') categoryObject = Topic.objects.filter(topic=category) if len(category) == 0 : categoryObject = Topic(topic=category) else : categoryObject = Topic.objects.filter(topic=category) course = Course(name=courseName, img=img, price =price, description=description, learningPoint=learningPoint, estimateTime=estimateTime) course.save() for i in categoryObject : course.topic.add(i) for i in request.data['course']['section'] : sectionTitle = i['title'] sectionDescription = i['description'] section = Section(title=sectionTitle, description=sectionDescription) section.save() course.section.add(section) for j in i['lesson'] : lessonTitle = j["title"] lesson = Lesson(title=lessonTitle) lesson.save() allStep = [] for k in j["step"] : stepTitle = k["title"] stepType = k['type'] if stepType == 0 : stepContentText = k["content_text"] stepTimeMinimum = datetime.strptime(k['time_minimum'], '%H:%M:%S') step = Step(title=stepTitle, type=stepType, contentText=stepContentText, timeMinimum=stepTimeMinimum) step.save() allStep.append(step) elif stepType == 1 : stepContentVideo = k["content_video"] stepTimeMinimum = datetime.strptime(k['time_minimum'], '%H:%M:%S') step = Step(title=stepTitle, type=stepType, contentText=stepContentVideo,timeMinimum=stepTimeMinimum) step.save() allStep.append(step) for k in range(len(allStep)) : if len(allStep) == 1 : continue elif k == 0 : allStep[k].nextID = allStep[k+1] allStep[k].save() elif k == (len(allStep) -1) : allStep[k].prevID = allStep[k - 1] allStep[k].save() else : allStep[k].prevID = allStep[k - 1] allStep[k].nextID = allStep[k+1] allStep[k].save() for k in allStep : lesson.step.add(k) course.totalStepAndQuiz += 1 section.lesson.add(lesson) quizTitle = i['quiz']["title"] quizDescription = i['quiz']["description"] quizMinimumScore = i['quiz']["minimum_score"] quizSection = QuizSection(title=quizTitle, description=quizDescription, minimumQuizScore=quizMinimumScore ) quizSection.save() section.quizSection = quizSection section.save() for k in i['quiz']["quiz"] : question = k["question"] point = k['point'] quizChoice1Object = Choice(choice= k['choice_1']['choice'], isRight= True if k['choice_1']["is_right"] == "true" else False ) quizChoice2Object = Choice(choice=k['choice_2']['choice'], isRight=True if k['choice_2']["is_right"] == "true" else False) quizChoice3Object = Choice(choice=k['choice_3']['choice'], isRight=True if k['choice_3']["is_right"] == "true" else False) quizChoice4Object = Choice(choice=k['choice_4']['choice'], isRight=True if k['choice_4']["is_right"] == "true" else False) quizChoice1Object.save() quizChoice2Object.save() quizChoice3Object.save() quizChoice4Object.save() quizObject = Quiz(question=question, choice1= quizChoice1Object, choice2=quizChoice2Object, choice3=quizChoice3Object, choice4=quizChoice4Object, point=point) quizObject.save() quizSection.quiz.add(quizObject) course.totalStepAndQuiz += 1 course.section.add(section) course.save() return Response({ "status" : 201, "message" : "success", }, status=status.HTTP_201_CREATED) except PermissionDenied as e : return PermissionDeniedHandler(e)
class QuestionTests(TestCase): '''Tests related to the actual Category and Subcategory functionality.''' def setUp(self): '''Set up the test and category infrastructure.''' #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() self.course2 = Course(name="testing course2", slug="testing-course2") self.course2.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() self.coursesection2 = CourseSection(name="Section 2", course=self.course2) self.coursesection2.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() self.category2 = Category( name="Category 1 for testing course", slug="cat-1-testing-course2", section=self.coursesection2, ) self.category2.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() self.subcategory2 = SubCategory( name="SubCategory 2 for testing course", slug="subcategory-2-testing-course", category=self.category2, ) self.subcategory2.save() #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) def tearDown(self): '''Tear down the infrastructure.''' pass def test_question_creation(self): '''Tests creating a question.''' question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) question.save() def test_question_response_creation(self): '''Tests creating a question response.''' question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) question.save() response = QuestionResponse.objects.create_response( user=self.user, question=question, attempt="A", ) assert response.correct def test_question_index_creation(self): '''Tests the automatic index creation.''' question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) question.save() assert question.index == 1 question2 = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is another example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) question2.save() assert question2.index == 2 question3 = Question( course=self.course2, section=self.coursesection2, category=self.category2, subcategory=self.subcategory2, question_text="Here is another example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) question3.save() assert question3.index == 1 question4 = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is another another example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", ) question4.save() assert question4.index == 3
class CommentTests(TestCase): '''Tests related to the actual Comment functionality.''' def setUp(self): '''Set up the test and category infrastructure.''' #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #Question creation self.question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", index=1, ) self.question.save() def tearDown(self): '''Tear down the infrastructure.''' pass def test_comment_creation(self): '''Tests creating a question.''' Comment.objects.create_comment( user=self.user, text="Testing Comment Creation", question=self.question, ) def test_reply_creation(self): '''Tests creating a reply.''' new_comment = Comment.objects.create_comment( user=self.user, text="Testing Comment Creation", question=self.question, ) Comment.objects.create_comment( user=self.user, parent=new_comment, text="Testing Reply Creation", question=self.question, ) def test_comment_misc(self): '''Testing the Comment model methods and misc attributes.''' new_comment = Comment.objects.create_comment( user=self.user, text="Testing Comment Creation", question=self.question, ) new_reply = Comment.objects.create_comment( user=self.user, parent=new_comment, text="Testing Reply Creation", question=self.question, ) #Test is_child assert not new_comment.is_child() assert new_reply.is_child() #Test get_children assert len(new_comment.get_children()) == 1 assert new_comment.get_children()[0] == new_reply assert new_reply.get_children() is None
meneghetti.save() atique.save() monari.save() zani.save() tanaka.save() jordao.save() menegatto.save() perez.save() leite.save() luke.save() course = Course( name='Sistemas Evolutivos e Aplicados à Robótica', code='SCC-713', ) course.save() course.teachers.set([simoes.id]) course = Course( name='Informação Profissional e Tutoria \ Acadêmica em Ciências da Computação', code='SCC-200', ) course.save() course.teachers.set([thiago.id, jfernando.id]) course = Course( name='Introdução à Ciência de Computação I', code='SCC-221', ) course.save()
class CourseLoader(object): def __init__(self, *args, **kwargs): self.dir = args[0] def process(self): self.get_course_or_create() self.save_meta_course() self.save_lessons() def get_course_or_create(self): try: self.course = Course.objects.get(name_slug=self.dir) except: self.course = Course() self.course.name_slug = self.dir self.course.save() def save_meta_course(self): path = DATA_DIR + '/' + self.dir + '/meta.yml' print('Saving meta for %s' % self.course.name_slug) meta = self.get_meta(path) self.course.name = meta['title_ru'] self.course.meta_keywords = meta['meta_keywords_ru'] self.course.meta_title = meta['meta_title_ru'] self.course.meta_description = meta['meta_description_ru'] self.course.desc = meta['desc_ru'] self.course.save() try: im_path = DATA_DIR + '/' + self.dir + '/image.png' print('Loading image %s' % im_path) with open(im_path, 'rb') as img_file: self.course.image.save('image.png', File(img_file), save=True) except Exception as e: print(str(e)) def save_lessons(self): path = DATA_DIR + '/' + self.dir + '/ru' onlydirs = [f for f in listdir(path) if isdir(join(path, f))] for d in onlydirs: lesson_yml_path = path + '/' + d + '/meta.yml' data = self.get_meta(lesson_yml_path) print(data) try: lesson = Lesson.objects.get(name_slug=d) except: lesson = Lesson() lesson.name_slug = d lesson.title = data['name'] lesson.course = self.course lesson.save() print('Saving lesson...%s' % data['slug']) for f in data['files']: try: topic = Topic.objects.get(lesson=lesson, filename=f['file']) except: topic = Topic.objects.create(filename=f['file'], title=f['title'], lesson=lesson) topic.check_video(f) print('Saving topic %s' % f['file']) def get_meta(self, path): if isfile(path): f = open(path, 'r') str = f.read() f.close() yml = yaml.load(str, Loader=yaml.FullLoader) return yml else: return False @staticmethod def get_active_courses_dirs(): out = [] onlydirs = [f for f in listdir(DATA_DIR) if isdir(join(DATA_DIR, f))] for d in onlydirs: if d.find('.') == -1: out.append(d) return out
class CourseLoader(object): def __init__(self, *args, **kwargs): self.dir = args[0] def process(self): self.get_course_or_create() self.save_meta_course() self.save_lessons() def save_meta_course(self): path = DATA_DIR + '/' + self.dir + '/meta.yml' print('Saving meta for %s' % self.course.name_slug) meta = self.get_meta(path) self.course.name = meta['title'] self.course.is_active = meta['is_active'] self.course.meta_keywords = meta['meta_keywords'] self.course.meta_title = meta['meta_title'] self.course.meta_description = meta['meta_description'] self.course.desc = meta['desc'] try: self.course.cost = meta['cost'] except: pass self.course.save() try: im_path = DATA_DIR + '/' + self.dir + '/image.png' print('Loading image %s' % im_path) with open(im_path, 'rb') as img_file: self.course.image.save('image.png', File(img_file), save=True) except Exception as e: print(str(e)) def get_course_or_create(self): try: self.course = Course.objects.get(name_slug=self.dir) except: self.course = Course() self.course.name_slug = self.dir self.course.save() def get_meta(self, path): if isfile(path): f = open(path, 'r') str = f.read() f.close() yml = yaml.load(str, Loader=yaml.FullLoader) return yml else: return False def save_lessons(self): path = DATA_DIR + '/' + self.dir onlydirs = [f for f in listdir(path) if isdir(join(path, f))] for d in onlydirs: if d != 'code': lesson_yml_path = path + '/' + d + '/meta.yml' data = self.get_meta(lesson_yml_path) slug = '%s--%s' % (self.course.name_slug, d) try: lesson = Lesson.objects.get(name_slug=slug) except: lesson = Lesson() number = d.split('-')[0] lesson.name_slug = slug lesson.number = number try: lesson.title = data['name'] except: lesson.title = 'Не определено!' print('Ошибка в %s' % lesson_yml_path) sys.exit() try: lesson.desc = data['desc'] except: print('Error with desc in %s' % lesson_yml_path) try: lesson.created_at = data['created'] except: lesson.created_at = '2000-01-01' lesson.meta_keywords = data['meta_keywords'] lesson.meta_title = data['meta_title'] lesson.meta_description = data['meta_description'] lesson.course = self.course lesson.save() ## add tags if 'tags' in data: tags = data['tags'].split(' ') for tag in tags: Tag.objects.add_tag(lesson, tag) print('Saving lesson...%s' % data['slug']) for f in data['files']: try: topic = Topic.objects.get(lesson=lesson, filename=f['file']) except Exception as e: topic = Topic.objects.create(filename=f['file'], course=self.course, title=f['title'], lesson=lesson, created_at='2000-01-01') ## make order try: order = f['order'] topic.order = order topic.save() except: pass try: order = f['created'] topic.created_at = f['created'] topic.save() except: pass print('Saving topic %s' % f['file']) topic.check_video(f) @staticmethod def get_active_courses_dirs(): out = [] onlydirs = [f for f in listdir(DATA_DIR) if isdir(join(DATA_DIR, f))] for d in onlydirs: if d.find('.') == -1 and d != 'articles': out.append(d) return out
teacher_users.permissions.add(teacher_view) student_users.save() teacher_users.save() rob = User.objects.create_user('rob', '*****@*****.**', 'thomas') rob.groups.add(student_users) rob.save() durga = User.objects.create_user('durga', '*****@*****.**', 'thomas') durga.groups.add(teacher_users) durga.save() #Copy and paste everything above into a manage.py shell session course1 = Course(title="course 1", slug="course-1", description="description", teacher=bob) course1.save() week_from_today = datetime.timedelta(days=7) sample_due_date = datetime.date.today() + week_from_today assignment1 = Assignment(name="assignment 1", slug="assignment-1", description="Assignment 1 description", #due_date=datetime.datetime(2012, 7, 31, 5, 0, tzinfo=<UTC>), due_date=sample_due_date, teacher=bob, course=course1) assignment1.save() grade1 = Grade(letter_grade="A",course=course1,assignment=assignment1) grade1.save()
a = User.objects.create_user(teacher, "*****@*****.**", "jtdxjwk") newteacher = Teacher() newteacher.teacher = a newteacher.is_teacher = True newteacher.save() teacher = newteacher print("we have save a new user %r" % teacher, end="||") from course.models import Course try: course = Course.objects.get(name=course) except: newcourse = Course() newcourse.name = course newcourse.teacher = theuser newcourse.save() course = newcourse from teachingtask.models import TeachingTask, Semester try: semester = Semester.objects.get(semester_year=semester_year, semester_period=semester_period) except: newsemester = Semester() newsemester.semester_year = semester_year newsemester.semester_period = semester_period newsemester.save() semester = newsemester try: teachingtask = TeachingTask.objects.get( \
def parse_courses(self, term, page): # Get rows from the table rows = page.get_element_by_id('GridView1').xpath('tbody')[0] skip = True added = 0 updated = 0 # Parse all rows for row in rows: # Skip the first row (titles) if skip is True: skip = False continue # Parse elements crn = int(row.getchildren()[0].text.strip()) course = row.getchildren()[1].xpath('a')[0].text.strip() course_link = row.getchildren()[1].xpath('a')[0].attrib['href'] section = row.getchildren()[2].text.strip() title = row.getchildren()[3].xpath('a')[0].text.strip() bookstore_link = row.getchildren()[3].xpath('a')[0].attrib['href'] hours = row.getchildren()[4].text.strip() attrstring = row.getchildren()[5].xpath('span')[0].text attributes = attrstring.strip() if attrstring else '' ctype = row.getchildren()[6].text.strip() meeting_times = [] # Possibility of having multiple meeting times days_list = list(row.getchildren()[7].itertext()) times_list = list(row.getchildren()[8].itertext()) for i, days in enumerate(days_list): days = days.strip() # These don't have a meeting time at all if len(days) == 0: continue time = MeetingTime(days=days) # Not all meeting times have a specific start/end time if len(times_list) >= i: timestring = times_list[i].strip() if len(timestring) > 0: start_time = timestring.split('-')[0] if len(start_time) == 3: start_time = '0' + start_time end_time = timestring.split('-')[1] if len(end_time) == 3: end_time = '0' + end_time start_time = datetime.datetime.strptime(start_time, '%H%M').time() end_time = datetime.datetime.strptime(end_time, '%H%M').time() time.start_time = start_time time.end_time = end_time # Add it to the database try: obj = MeetingTime.objects.get(days=days, start_time=time.start_time, end_time=time.end_time) time = obj except MeetingTime.DoesNotExist: time.save() meeting_times.append(time) location = row.getchildren()[9].text.strip() if location == 'ARR': location = None instructor = row.getchildren()[10].text.strip() # Parse the instructor if instructor and len(instructor) > 0: instructor = self.parse_instructor(instructor) else: instructor = None seats = int(row.getchildren()[11].xpath('span')[0].text.strip()) statusstring = row.getchildren()[12].xpath('span')[0].text.strip() status = 1 if statusstring == 'Open' else 0 if statusstring == 'Closed' else -1 # Create the course course = Course(term=term, crn=crn, course=course, course_link=course_link, section=section, title=title, bookstore_link=bookstore_link, hours=hours, attributes=attributes, ctype=ctype, location=location, instructor=instructor, seats=seats, status=status) # Add it to the database try: obj = Course.objects.get(term=term, crn=crn) if not course.instructor: course.instructor = obj.instructor opts = obj._meta changed = False for f in opts.fields: if f.name not in ['id', 'meeting_times']: old_attr = getattr(obj, f.name) new_attr = getattr(course, f.name) if old_attr != new_attr: logger.debug('Changed value ' + f.name + ': ' + str(old_attr) + ' -> ' + str(new_attr)) changed = True setattr(obj, f.name, new_attr) if len([item for item in obj.meeting_times.all() if item not in meeting_times]) > 0: logger.debug('Changed meeting times ' + str(obj.meeting_times.all()) + ' -> ' + str(meeting_times)) changed = True obj.meeting_times = meeting_times if changed: logger.debug('Course listed as changed: /' + str(obj.term.value) + '/' + str(obj.crn)) updated += 1 obj.save() except Course.DoesNotExist: course.save() course.meeting_times = meeting_times added += 1 self.stdout.write('-> Parsed ' + str(len(rows) - 1) + ' courses. ' + str(added) + ' added, ' + str(updated) + ' updated.') self.total_parsed += len(rows) - 1 self.total_added += added self.total_updated += updated