Ejemplo n.º 1
0
def college_ratings_create(username: str):
    schema = Schema({
        "collegename": And(str, len, error="No College Name"),
        "academics": And(str, len, error="No Academics"),
        "athletics": And(str, len, error="No Athletics"),
        "dorms": And(str, len, error="No Dorms"),
        "dining": And(str, len, error="No Dining"),
        "username": And(str, len, error="No Username")
    })
    form = {
        "collegename": request.json.get("collegename"),
        "academics": request.json.get("academics"),
        "athletics": request.json.get("athletics"),
        "dorms": request.json.get("dorms"),
        "dining": request.json.get("dining"),
        "username": request.json.get("username")
    }
    print(request.json)
    print(form)
    validated = schema.validate(form)
    #print(validated)
    #user = User.objects(username=username).first()
    post = College(collegename=validated["collegename"],
                   academics=validated["academics"],
                   athletics=validated['athletics'],
                   dorms=validated["dorms"],
                   dining=validated["dining"],
                   username=validated["username"]).save()
    print(post)
    return jsonify(post.to_public_json())
Ejemplo n.º 2
0
def admin():
    form = ProfessorForm()
    form2 = CollegeForm()

    if form.add_professor.data and form.validate_on_submit():
        professor = Professor(first_name=form.first_name.data,
                              last_name=form.last_name.data,
                              department=form.department.data,
                              college=College.query.filter_by(
                                  college_acronym=form.college.data).first())
        db.session.add(professor)
        db.session.commit()
        flash('Professor Added')
        return redirect(url_for('professor', profname=professor.first_name))

    if form2.add_college.data and form2.validate_on_submit():
        college = College(college_name=form2.college_name.data,
                          college_acronym=form2.college_acronym.data,
                          state=form2.state.data)
        db.session.add(college)
        db.session.commit()
        flash('College Added')
        return redirect(url_for('main'))

    return render_template("admin.html", form=form, form2=form2, title='Admin')
Ejemplo n.º 3
0
def slackWebHook():
    text = "\n\n*College\t\tCourses\tStudents\tNotebooks\tUploads\tNew Profiles*\n"
    for college in College.query().fetch():
        num = memcache.get(college.key.urlsafe())
        if num is None:
            memcache.add(college.key.urlsafe(), 0, 86400)
            num = "Lost"
        stuNum = memcache.get("stu" + college.key.urlsafe())
        if stuNum is None:
            memcache.add("stu" + college.key.urlsafe(), 0, CLG_STATS_TIME)
            stuNum = "Lost"
        if college.abbreviation == "LNMIIT":
            abb = college.abbreviation.ljust(20, " ")
        else:
            abb = college.abbreviation.ljust(25, " ")
        det = abb + "\t\t" + str(len(college.courseIds)) + "\t\t\t\t"
        det += str(college.studentCount) + "\t\t\t\t"
        det += str(college.noteBookCount) + "\t\t\t\t\t"
        if "LNMIIT" in abb:
            det += str(num) + "\t\t\t\t\t" + str(stuNum)
        else:
            det += str(num) + "\t\t\t\t\t\t" + str(stuNum)
        text += det
        text += "\n"

    data = {
        "icon_url": "https://s-media-cache-ak0.pinimg.com/236x/d7/a4/34/d7a4343ec74ae5427708b429cbf82a20.jpg",
        "username": "******",
        "attachments": [{"title": "Yay!!!!!!", "text": text, "mrkdwn_in": ["text", "title"]}],
    }
    for url in WEBHOOK_URLS:
        req = urllib2.Request(url, json.dumps(data))
        urllib2.urlopen(req)
Ejemplo n.º 4
0
def add_college():
    if request.method == "POST":
        name = request.form.get('name')
        app_deadline = request.form.get('app_deadline')
        rec_deadline = request.form.get('rec_deadline')
        num_essays = request.form.get('num_essays')
        midyear_report = request.form.get('midyear_report')
        acceptance_rate = request.form.get('acceptance_rate')
        platform = request.form.get('platform')
        try:
            college = College(
                name=name,
                app_deadline=app_deadline,
                rec_deadline=rec_deadline,
                num_essays=num_essays,
                midyear_report=midyear_report,
                acceptance_rate=acceptance_rate,
                platform=platform,
            )
            if request.form.get('name') == "":
                raise ValueError(
                    'There is no name specified for the college. Please try again with a name.'
                )
            else:
                db.session.add(college)
                db.session.commit()
        except ValueError as v:
            flash(str(v))
            return redirect('/')
        except Exception as e:
            return str(e)
        return redirect('/')
    else:
        return render_template("college.html")
Ejemplo n.º 5
0
def parse_colleges():
    if len(colleges) != 0:
        logger.error("colleges list existed, ignore parsing")
        return
    hao123_parser = Hao123_211_Parser(Config.C211_URL)
    if hao123_parser.run():
        for item in hao123_parser.rlist:
            college = College(item['href'], item.string)
            colleges.append(college)
            print("href:%s" % item['href'])
Ejemplo n.º 6
0
    def post(self, request):
        """
        Create college record in database
        :param request: Key value pair data
        :return: status & respective message
        """
        data = request.data
        course_ids = None
        if "course_ids" in data:
            course_ids = data["course_ids"]
            data.pop("course_ids")

        try:
            college = College(**data)
            college.save()
            LOGGER.info("College created successfully")
        except Exception, error:
            LOGGER.error("Error:%s", str(error))
            return Response({"status": "FAILED", "message": str(error)})
Ejemplo n.º 7
0
def user_created(sender, user, request, **kwargs):
    form = UserRegistrationForm(request.POST)
    user_profile = UserProfile(user=user, user_type='P')
    user_profile.save()
    participant = Participant(user=user_profile)
    participant.name = form.data["fullname"]
    user.firstname = participant.name
    participant.email_id = user.email
    participant.phone_no = form.data["phone_no"]
    if int(form.data["college"]) == -1:
        if form.data["add_your_college"] is not None:
            new_college = College(name=form.data["add_your_college"])
            new_college.save()
            participant.college = new_college
        else:
            raise Exception("No College name specified")
    else:
        participant.college = College.objects.get(pk=form.data["college"])
    participant.roll_no = form.data['rollno']
    participant.save()
Ejemplo n.º 8
0
def major_approve():
    if g.user.get_name() != 'sndnyang':
        abort(404)
    no = request.json.get('id', None)
    action = str(request.json.get('type', None))
    if not no or not action:
        return json.dumps({'error': '%s %s not right' % (no, action)},
                          ensure_ascii=False)

    app.logger.debug(no + ' ' + action)
    try:
        college = TempCollege.query.get(no)
        if action == 1:
            db.session.delete(college)
        else:
            result = College.query.filter_by(
                name=college.name, major=college.major,
                degree=college.degree).one_or_none()
            if result is None:
                result = College(college.name, college.degree, college.major,
                                 college.site_url, college.program_name)
                result.set(college)
                db.session.add(result)
            else:
                result.set(college)
            db.session.delete(college)
        db.session.commit()
        return json.dumps({'info': 'success'}, ensure_ascii=False)
    except Exception, e:
        app.logger.debug(traceback.print_exc())
Ejemplo n.º 9
0
def csv_to_colleges():
    with open(path_of(Config.COL_CSV_FILE), 'rb') as csvfp:
        fieldnames = ['name', 'eng_name', 'url']
        reader = csv.DictReader(csvfp,
                                fieldnames=fieldnames,
                                delimiter=',',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)
        for row in reader:
            colleges.append(College(row['url'], row['name'], row['eng_name']))
        csvfp.close()
    logger.info("All %d colleges laod from to %s done" %
                (len(colleges), path_of(Config.COL_CSV_FILE)))
Ejemplo n.º 10
0
def home():
    colleges = None
    if request.form:
        try:
            #db.session.query(College).delete()
            college = College(schoolname=request.form.get("schoolname"))
            db.session.add(college)
            db.session.commit()
        except SQLAlchemyError:
            flash("Failed to add college, as it might be a duplicate")
            return redirect(url_for('home'))

    colleges = College.query.all()
    return render_template("home.html", colleges=colleges)
Ejemplo n.º 11
0
def create_college():
    """
    Allows admin to create Promo Code for User's discount
    :param college_name:
    :param college_logo:
    :return:
    """
    req = request.get_json()
    try:
        college = College(**req)
        db.session.add(college)
        db.session.commit()
        return ""
    except exc.IntegrityError:
        return Error('College already exists', 400)()
Ejemplo n.º 12
0
def create():
    today = datetime.date.today()
    bucketName = BUCKET_NAME
    fileName = bucketName + '/' + 'summary.csv'
    gcsFile = gcs.open(fileName, mode='w', content_type='text/csv',
                       options={'x-goog-acl': 'public-read'})
    data = readFile()
    gcsFile.write(data)
    gcsFile.write("\n")
    gcsFile.write("Date,College,Courses,Students,Notebooks\n")
    for college in College.query().fetch():
        det = [str(today), str(college.collegeName), str(len(college.courseIds)),
               str(college.studentCount), str(college.noteBookCount)]
        gcsFile.write(",".join(det))
        gcsFile.write("\n")
    gcsFile.close()
Ejemplo n.º 13
0
def college():
    # Display all of the properties on the page
    # Query the database to get the vote counts for each attribute of this college
    # Display the page
    if request.method=="GET":
        # Calculate all of the
        return render_template("college.html")
    #Get the college page and dislay
    if request.form:
        try:
            #db.session.query(College).delete()
            college = College(schoolname=request.form.get("schoolname"))
            db.session.add(college)
            db.session.commit()
        except SQLAlchemyError:
            flash("Failed to add college, as it might be a duplicate")
            return redirect(url_for('home'))
    college =  College.query.all()
    return render_template("college.html", college=college)
Ejemplo n.º 14
0
def slackWebHook():
    text = "\n\n*College\t\tCourses\tStudents\tNotebooks\tUploads\tNew Profiles*\n"
    for college in College.query().fetch():
        num = memcache.get(college.key.urlsafe())
        if num is None:
            memcache.add(college.key.urlsafe(), 0, 86400)
            num = "Lost"
        stuNum = memcache.get('stu' + college.key.urlsafe())
        if stuNum is None:
            memcache.add('stu' + college.key.urlsafe(), 0, CLG_STATS_TIME)
            stuNum = "Lost"
        if college.abbreviation == 'LNMIIT':
            abb = college.abbreviation.ljust(20, ' ')
        else:
            abb = college.abbreviation.ljust(25, ' ')
        det = abb + '\t\t' + str(len(college.courseIds)) + '\t\t\t\t'
        det += str(college.studentCount) + '\t\t\t\t'
        det += str(college.noteBookCount) + '\t\t\t\t\t'
        if 'LNMIIT' in abb:
            det += str(num) + '\t\t\t\t\t' + str(stuNum)
        else:
            det += str(num) + '\t\t\t\t\t\t' + str(stuNum)
        text += det
        text += '\n'
    text += "csv link: https://storage.googleapis.com/uploadnotes-2016.appspot.com/summary.csv"

    data = {'icon_url': 'https://s-media-cache-ak0.pinimg.com/236x/d7/a4/34/d7a4343ec74ae5427708b429cbf82a20.jpg',
            'username': '******',
            "attachments": [
                {
                    "title": "Yay!!!!!!",
                    "text": text,
                    "mrkdwn_in": [
                        "text",
                        "title"
                    ]
                }
            ]}
    for url in WEBHOOK_URLS:
        req = urllib2.Request(url, json.dumps(data))
        urllib2.urlopen(req)
Ejemplo n.º 15
0
def create_inst():
    if request.method == "GET":
        return render_template('register.html')
    if request.method == "POST":
        print(request.form)
        name = request.form["name"]
        email = request.form["email"]
        password = request.form["password"]
        # confirm_password = request.form["confirm_password"]
        option = {1: 'school', 2: 'college'}[int(request.form['option'])]
        # if not confirm_password == password:
        #     return redirect(url_for('.home_page'))
        if option == 'school':
            new_school = School(name, email, password)
            db_session.add(new_school)
            db_session.commit()
            log('School created')
        elif option == 'college':
            new_college = College(name, email, password)
            db_session.add(new_college)
            db_session.commit()
            log('College Created')
        return redirect(url_for('.home_page'))
Ejemplo n.º 16
0
def submitted_major():
    verification_code = request.form['verification_code']
    code_text = session['code_text']
    if verification_code != code_text:
        return json.dumps({'error': u'验证码错误'}, ensure_ascii=False)
    code_img, code_string = create_validate_code()
    session['code_text'] = code_string
    try:
        cid = request.form['id']
        name = request.form['name']
        degree = request.form['degree']
        major = request.form['major']
        program_name = request.form['program_name']
        site_url = request.form['site_url']
        if not name or not degree or not major:
            return json.dumps({'error': u'关键信息缺失'}, ensure_ascii=False)
        result = College.query.get(cid)
        if result is None:
            result = College.query.filter_by(
                name=name,
                major=major,
                degree=degree,
                program_name=program_name).one_or_none()
        if result is None:
            if g.user and g.user.is_authenticated and g.user.get_name(
            ) == 'sndnyang':
                college = College(name, degree, major, site_url, program_name)
            else:
                college = TempCollege(name, degree, major, site_url,
                                      program_name)
        else:
            college = result

        college.program_name = program_name
        college.gpa = request.form['gpa'] if request.form['gpa'] else 6.6
        college.gpa_url = request.form['gpa_url']
        college.tuition = request.form['tuition'] if request.form[
            'tuition'] else 66666

        college.tuition_url = request.form['tuition_url']
        college.deadline_url = request.form['deadline_url']
        college.fall = request.form['fall']
        college.spring = request.form['spring']
        college.gre = request.form['gre']
        college.gre_url = request.form['gre_url']
        college.toefl = request.form['toefl'] if request.form['toefl'] else 6.6

        college.ielts = request.form['ielts'] if request.form['ielts'] else 6.6

        college.eng_url = request.form['eng_url']
        college.rl = request.form['rl']
        college.evalue = request.form['evalue']
        college.finance = request.form['finance']
        college.docum_url = request.form['docum_url']
        college.int_docum_url = request.form['int_docum_url']

        info = {}
        l = (len(request.form.keys()) - 23) / 2
        for i in range(l):
            info['label%d' % i] = request.form.get('label%d' % i, '')
            info['input%d' % i] = request.form.get('input%d' % i, '')
        college.info = info

        if result is None:
            db.session.add(college)
        db.session.commit()
    except Exception, e:
        app.logger.debug(traceback.print_exc())
        return json.dumps({'error': u'错误'}, ensure_ascii=False)
Ejemplo n.º 17
0
from models import db, Student, Book, College

stud1 = Student("Yashika")
stud2 = Student("Ram")

db.session.add_all([stud1, stud2])
db.session.commit()

print(Student.query.all())

stud1 = Student.query.filter_by(name="Ram").first()

#create college of this stud

college1 = College("SKIT", stud1.id)

# some books of stud

book1 = Book("DBMS", stud1.id)
book2 = Book("MATHS", stud1.id)

db.session.add_all([college1, book1, book2])
db.session.commit()

# Grab this stud after those additions
stud1 = Student.query.filter_by(name='Ram').first()
print(stud1)
Ejemplo n.º 18
0
def mutual_break_from_selected_schools(request): # returns info on schools passed as a comma separated list
	ls_selectedSchools_json = []
	school_list_string = request.GET.get('term')
	school_ids_list = school_list_string.split(",")

	#Handle empty url
	if (school_ids_list)==1:
		if school_ids_list[0]=='':
			return ''

	print 'school_ids_list', school_ids_list

	#To find mutual breaks for each break, find the earliest end date. Then check the latest start date.
	#If the startDate < endDate, return them
	#Else, there are no mutual break times

	schools = [] #List of College objects
	#Latest start
	#Earliest end
	mutual_spring_start = dt.date(dt.MINYEAR,1,1)
	mutual_spring_end = dt.date(dt.MAXYEAR,12,31)
	mutual_summer_start = dt.date(dt.MINYEAR,1,1)
	mutual_summer_end = dt.date(dt.MAXYEAR,12,31)
	mutual_winter_start = dt.date(dt.MINYEAR,1,1)
	mutual_winter_end = dt.date(dt.MAXYEAR,12,31)
	for school_id_s in school_ids_list:
		school_id = int(school_id_s)
		matches = College.objects.filter(id=school_id)#Q(name__contains=school_id) | Q(name_variations__contains=school_id))
		if len(matches) == 1:
			school = matches[0]
			print school 
			schools.append(school)
			#Update the latest start_date
			if school.spring_start == None or mutual_spring_start == None: mutual_spring_start = None
			elif school.spring_start > mutual_spring_start: mutual_spring_start = school.spring_start
			
			if school.summer_start == None or mutual_summer_start == None: mutual_summer_start = None
			elif school.summer_start > mutual_summer_start: mutual_summer_start = school.summer_start

			if school.winter_start == None or mutual_winter_start == None: mutual_winter_start = None
			elif school.winter_start > mutual_winter_start: mutual_winter_start = school.winter_start

			#Update the earliest end_date
			if school.spring_end == None or mutual_spring_end == None: mutual_spring_end = None
			elif school.spring_end < mutual_spring_end: mutual_spring_end = school.spring_end 
			
			if school.summer_end == None or mutual_summer_end == None: mutual_summer_end = None
			elif school.summer_end < mutual_summer_end: mutual_summer_end = school.summer_end
			
			if school.winter_end == None or mutual_winter_end == None: mutual_winter_end = None
			elif school.winter_end < mutual_winter_end: mutual_winter_end = school.winter_end

		elif len(matches) > 1:
			print '{0} schools found for'.format(len(school)), school_id
		else: 
			print 'No match found for', school_id
			return ''

	#After this, all mutual break dates are guaranteed to not be MIN or MAX

	#If the startDate < endDate, return them
	#Else, there are no mutual break times
	if mutual_spring_start > mutual_spring_end:
		mutual_spring_start = None
		mutual_spring_end = None
	if mutual_summer_start > mutual_summer_end:
		mutual_summer_start = None
		mutual_summer_end = None
	if mutual_winter_start > mutual_winter_end:
		mutual_winter_start = None
		mutual_winter_end = None

	mutual_breaks_dict =  College.jsonDictFromDates(
		id = ','.join([str(s.id) for s in schools]),
		name = ','.join([s.name for s in schools]), 
		spring_start = mutual_spring_start,
		spring_end = mutual_spring_end,
		summer_start = mutual_summer_start,
		summer_end = mutual_summer_end,
		winter_start = mutual_winter_start,
		winter_end = mutual_winter_end
	)
	return HttpResponse(json.dumps(mutual_breaks_dict))
Ejemplo n.º 19
0
def college_ratings_getCollegeRatings():
    ratings = College.objects().order_by("-created")
    return jsonify([rating.to_public_json() for rating in ratings])
Ejemplo n.º 20
0
            'level': 3
        }, {
            "question": "实体完整性是指关系中的____ 不允许取空值。",
            "answer": ["主键"],
            "level": 3
        }],
        "解答题": [{
            "question": "",
            "answer": "",
            "level": 2
        }]
    }
}
college_code = 9
for college_name in students_data.keys():
    college = College()
    college.name = college_name
    db.session.add(college)
    college_code += 1
    major_code = 9
    print(college_name)
    for major_name in students_data[college_name].keys():
        major = Major()
        major.name = major_name
        college.majors.append(major)
        major_code += 1
        print(major_name)
        for grade in students_data[college_name][major_name].keys():
            print(grade)
            for class_code in range(10, 15):
                class_name = grade + "级" + major_name + str(class_code) + "班"
Ejemplo n.º 21
0
def populate_tables(data):
    # skip column names
    next(data)

    for row in data:
        name = row[NAME]
        state = row[STATE]
        lon = row[LON]
        lat = row[LAT]
        in_state = row[IN_STATE]
        out_state = row[OUT_STATE]
        book = row[BOOK]
        on_campus = row[ON_CAMPUS]
        off_campus = row[OFF_CAMPUS]
        aid = row[AID]
        instruction = row[INSTRUCTION]
        research = row[RESEARCH]
        public = row[PUBLIC]
        academic = row[ACADEMIC]
        other = -1

        # must haves
        if not (name and state and lon and lat and
                (in_state or out_state) and book and
                (on_campus or off_campus)):
            print 'missing crucial column for row: {}'.format(row)
            continue

        # fix tuition
        in_state = in_state or (int(out_state) - 5325)
        out_state = out_state or (int(in_state) + 6382)

        # fix housing
        on_campus = on_campus or (int(off_campus) + 1356)
        off_campus = off_campus or (int(on_campus) - 1456)

        # fix aid
        aid = aid or randint(2000, 10000)

        # fix expenditures
        instruction = instruction or randint(1, 10)
        research = research or randint(1, 10)
        public = public or randint(1, 10)
        academic = academic or randint(1, 10)

        # format
        name = str(name)
        state = str(state)
        lon = float(lon)
        lat = float(lat)
        in_state = int(in_state)
        out_state = int(out_state)
        book = int(book)
        on_campus = int(on_campus)
        aid = int(aid)
        instruction = int(instruction)
        research = int(research)
        public = int(public)
        academic = int(academic)
        other = 100 - (instruction + research + public + academic)

        try:
            # add to college
            college = College(name, state, lat, lon)
            db.session.add(college)
            db.session.commit()

            # necessary for foreign key
            college_id = college.id

            # add to student_expense
            student_expense = StudentExpense(college_id, in_state, out_state,
                                             book, on_campus, off_campus, aid)
            db.session.add(student_expense)
            db.session.commit()

            # add to college_expense
            college_expense = CollegeExpense(college_id, instruction, research,
                                             public, academic, other)
            db.session.add(college_expense)
            db.session.commit()
        except Exception as e:
            print e
            db.session.rollback()