예제 #1
0
파일: routes.py 프로젝트: Transformt/peppe
def add_entry():
    form = PostForm()
    file = request.files["propics"]
    if "email" not in session:

        return redirect(url_for("home"))

    if request.method == "POST":
        if form.validate() == False:
            return render_template("welcome.html", form=form)
        else:

            g.post = db_session.query(User.id).filter(session["email"] == User.email).first()
            g.lastname = db_session.query(User.lastname).filter(session["email"] == User.email).first()
            g.firstname = db_session.query(User.firstname).filter(session["email"] == User.email).first()
            g.fullname = g.lastname + g.firstname

            file = request.files["propics"]
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
                # open(os.path.join(app.config['UPLOAD_FOLDER'], file), 'w').write(file)
                filename = filename

                entries = Post(form.subject.data, filename, form.body.data, user_id=g.post, author=g.fullname)
                # productimage = Image(form.body.data, filename)
                # db_session.add(productimage)
                db_session.add(entries)
                db_session.commit()
                flash("New entry was successfully posted")
            return redirect(url_for("show_entries"))

    return "It could go with the settings"
예제 #2
0
파일: routes.py 프로젝트: Transformt/peppe
def signin():
    form = SigninForm()

    if "email" in session:
        return redirect(url_for("welcome", form=form))

    if request.method == "POST":
        if form.validate() == False:
            return render_template("signin.html", form=form)
        else:
            session["email"] = form.email.data
            signin = User.query.filter_by(email=session["email"]).first()
            if signin:
                session["lastname"] = db_session.query(User.lastname).filter(User.email == session["email"]).first()
                session["firstname"] = db_session.query(User.firstname).filter(User.email == session["email"]).first()
                session["phone"] = db_session.query(User.phone).filter(User.email == session["email"]).first()
                session["country_id"] = db_session.query(User.country_id).filter(User.email == session["email"]).first()
            session["lastname"] = session["lastname"]
            session["firstname"] = session["firstname"]
            session["phone"] = session["phone"]
            session["country_id"] = session["country_id"]

            if session["country_id"] == db_session.query(User.country_id).filter(User.country_id == 1).first():
                session["country_id"] == "Nigerian"
            else:
                session["country_id"] == "Foreigner"

            return redirect(url_for("welcome", form=form))

    elif request.method == "GET":
        return render_template("signin.html", form=form)
예제 #3
0
	def calc_assn_weights(self):
		"""
			For each Course/Mentor pair (referred to as an assignment) calculate the weight value
		"""
		print_msg('Calculating Scores')
		sess.query(Assignment).delete()
		sess.commit()

		#For each pref_type, mentor, course triple, get all choices that match
		sess.execute(text("""
			INSERT INTO assignments (mentor_id, course_id, cost)
			SELECT M.mentor_id, C.course_id, SUM(COALESCE(PW.weight_value, PT.def_weight_val))
			FROM mentors M, courses C
			JOIN course2pref  C2P ON C2P.course_id = C.course_id
			JOIN prefs        P   ON P.pref_id = C2P.pref_id
			JOIN pref_types   PT  ON PT.pref_type_id = P.pref_type_id
			LEFT JOIN choices Ch  ON Ch.mentor_id = M.mentor_id AND Ch.pref_id = P.pref_id
			LEFT JOIN pref_weights PW  ON Ch.weight_id = PW.pref_weight_id
			GROUP BY M.mentor_id, C.course_id
			"""))

		sess.commit()

		#I don't know why these null assignments are getting added to the table
		sess.query(Assignment).filter(or_(Assignment.mentor_id == None, Assignment.course_id == None)).delete()

		sess.commit()

		assignments = sess.query(Assignment).all()
		for assignment in assignments:
			self.all_assns[(assignment.course_id,assignment.mentor_id)] = assignment

		print_msg('Succesfully Calculated Scores')
예제 #4
0
	def __init__(self):
		sess.query(Schedule).delete()
		sess.execute(text("DELETE FROM sched2assn")) #FIXME
		sess.commit()

		print_msg('Started Scheduling')

		#delcare data
		self.all_assns = {}

		#Get data out of DB
		self.courses = sess.query(Course).all()
		#courses.append(None) # add NO_ASSIGNMENT

		self.mentors = sess.query(Mentor).all()

		self.pre_assns = []
		self.req_assns = []
		self.add_assns = []
		self.schedule = Schedule()
		#mentor2course = {} #TODO for speeding up assn_valid

		self.req_mentor_slots = [] #required mentor slots
		self.add_mentor_slots = [] #additional mentor slots

		self.req_best_cost = 0
		self.add_best_cost = 0

		self.unassned_courses = set(self.courses) #discard items from this set as courses are assigned
예제 #5
0
def get_pref(pref_type, pref_name):

	#memoize, so we don't have to commit at each interval and also minimizes selects
	if (pref_type,pref_name) in get_pref.prefs:
		pref = get_pref.prefs[(pref_type, pref_name)]
		#app.logger.debug('pref %r found in cache' % pref)
		return pref

	try:
		pref = sess.query(Pref).join(PrefType).filter(Pref.name == pref_name).filter(PrefType.name == pref_type).one()
		get_pref.prefs[(pref_type,pref_name)] = pref
		#app.logger.debug('pref %r to found in db' % pref)
		return pref
	except NoResultFound:
		pref = Pref()
		pref_type_id = sess.query(PrefType.pref_type_id).filter(PrefType.name == pref_type).one()
		if pref_type_id is None:
			raise Exception('pref_type %s not found' % pref_type)
		pref.pref_type_id = pref_type_id.pref_type_id
		pref.name = pref_name
		#sess.add(pref)
		#sess.commit()
		get_pref.prefs[(pref_type,pref_name)] = pref

		#app.logger.debug('Adding pref %r to the db' % pref)
		return pref
예제 #6
0
def club_pictures(rowkey):
    if not check_auth(request):
        abort(403)
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return make_response('No file part', 400)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            return make_response('No file part', 400)
        if not allowed_file(file.filename):
            return make_response('The filetype is not allowed')
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filename = rowkey + "." + filename.rsplit('.', 1)[1]
            file.save(os.path.join(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], filename))
            db_picture = db_session.query(UserFile).filter_by(owner=rowkey, file_type='ProfilePicture')
            if len(list(db_picture)) == 0:
                db_picture = UserFile()
                db_picture.file_type = 'ProfilePicture'
                db_picture.owner = rowkey
                db_session.add(db_picture)
                db_session.commit()
                return make_response("",200)
            db_picture.update({"file_name":filename})
            db_session.commit()
            return make_response("", 200)
    if request.method == 'GET':
        filename = db_session.query(UserFile).filter_by(file_type='ProfilePicture', owner=rowkey)[0].file_name
        return jsonify({"filename":  str.replace(app.config['CLUB_PICTURE_UPLOAD_FOLDER'], "static\\Sloach\\", "") + "/" + filename})
예제 #7
0
def storedata():
 form = TapeForm()
 if request.method == 'POST':
    if form.validate() == False:
      return render_template('storedata.html', form=form)
    else:
      g.post = db_session.query(User.id).filter(session['email'] == User.email).first()
      g.lastname = db_session.query(User.lastname).filter(session['email'] == User.email).first()
      g.firstname = db_session.query(User.firstname).filter(session['email'] == User.email).first()
      g.fullname = g.lastname + g.firstname  
      g.newuser = Tape(form.tape_number.data, form.project_title.data, form.content.data,
      form.status.data, user_id=g.post, author=g.fullname)
      db_session.add(g.newuser)
      db_session.commit()
      
      session['tape_number'] = g.newuser.tape_number
      session['project_title'] = g.newuser.project_title
      session['content'] = g.newuser.content
      session['status'] = g.newuser.status
      flash('New Entry was Successful')    
                       
      return redirect(url_for('storedata'))
   
 elif request.method == 'GET':
    import psycopg2
    conn = psycopg2.connect("dbname='mydatabase' user='******' host='localhost' password='******'")
    cur = conn.cursor()
    cur.execute("""select tape_number, project_title, content, status, author, timestamp from tapes order by uid desc""")
    rows = cur.fetchall()
    entries = [dict(tape_number=row[0], project_title=row[1], content=row[2], author=row[3], timestamp=row[4]) for row in rows]
    return render_template('storedata.html', form=form, entries=entries)
예제 #8
0
파일: views.py 프로젝트: gluker/jaot
def showProblem(problem_id):
    problem = db_session.query(Problem).get(problem_id)
    if problem is None:
        abort(404)
    pset = db_session.query(ProblemSet).get(problem.problemset_id)
    course = db_session.query(Course).get(pset.course_id)
    rate = 0
    trials = None 
    for up in current_user.problems:
        if up.problem == problem:
            rate = up.rate
            trials = up.trials
            break
    '''
    if None in [pset,course,problem] or \
                pset.course_id != course_id or \
                problem.problemset_id != pset_id:
        abort(404)
        '''
    if course not in current_user.courses and current_user.type == "student":
        abort(403)
    text = problem.text
    next_problem = problem_id+1 if len(pset.problems)>problem_id else None
        
    return render_template("showproblem.html",
        course=course,pset=pset,problem=problem,text=text,
        next_problem=next_problem,rate=rate,trials=trials)
예제 #9
0
def create_club():
    if not check_auth(request):
        abort(403)
    idclub = "0"
    name = ""
    description = ""
    if not request.json or not 'name' in request.json:
        abort(400)
    if not request.json or not 'description' in request.json:
        abort(400)
    if 'idclub' in request.json:
        idclub = request.json['idclub']
    if 'name' in request.json:
        name = request.json['name']
    if 'description' in request.json:
        description = request.json['description']
    club = Club(name=name, description=description)
    if str(idclub) != "0":
        db_session.query(Club).filter_by(idclub=int(idclub)).update({"name": name, "description": description})
        db_session.commit()
    else:
        db_session.add(club)
        db_session.commit()

    return jsonify({"status": "OK"})
예제 #10
0
 def getDiagnoseCountByDoctorId(cls,session,doctorId,score=None):
     if doctorId is None:
         return
     if score or score==0:
         return session.query(Diagnose.id).filter(Diagnose.doctorId==doctorId,Diagnose.score==score).count()
     else:
         return  session.query(Diagnose.id).filter(Diagnose.doctorId==doctorId).count()
예제 #11
0
def getEvents():
    aid  = int(request.args.get('article_id'))
    evs  = []
    rvar = ['form', 'issue', 'loc']

    ## get a summary of the existing events for this article
    for event in db_session.query(Event).filter(Event.article_id == aid).all():
        ev   = {}
        repr = []
        ev['id'] = event.id

        csps = db_session.query(CodeSecondPass).filter_by(event_id = event.id, coder_id = current_user.id).order_by(CodeSecondPass.variable).all()

        ## if this event doesn't belong to this user, skip it
        if len(csps) == 0:
            continue

        for csp in csps:
            if csp.variable in rvar:
                repr.append(csp.value)

        ev['repr'] = "-".join(repr)
        if len(ev['repr']) > 30:
            ev['repr'] = ev['repr'][0:15] + " ... " + ev['repr'][-15:]

        evs.append(ev)

    return jsonify({'events': evs})
예제 #12
0
def code1(aid):
    article    = db_session.query(ArticleMetadata).filter_by(id = aid).first()
    text, html = prepText(article)

    aq = db_session.query(ArticleQueue).filter_by(coder_id = current_user.id, article_id = aid).first()

    return render_template("code1.html", vars = vars, aid = aid, text = html.decode('utf-8'))
예제 #13
0
파일: main.py 프로젝트: agamaloni/anyway
 def index(self):
     if request.method=='GET':
         user_emails = db_session.query(User).filter(User.new_features_subscription == True)
         email_list = []
         for user in user_emails:
             email_list.append(user.email)
             email_list.append(';')
         context = {'user_emails': email_list}
         return self.render('sendemail.html', **context)
     else:
         jsondata = request.get_json(force=True)
         users_send_email_to = db_session.query(User).filter(User.new_features_subscription == True)
         message = Mail()
         message.set_subject(jsondata['subject'].encode("utf8"))
         message.set_text(jsondata['message'].encode("utf8"))
         message.set_from('ANYWAY Team <*****@*****.**>')
         for user in users_send_email_to:
             message.add_bcc(user.email)
         try:
             status, msg = sg.send(message)
         except SendGridClientError:
             return "Error occurred while trying to send the emails"
         except SendGridServerError:
             return "Error occurred while trying to send the emails"
         return "Email/s Sent"
예제 #14
0
def delCode(pn):
    """ Deletes a record from first or second pass codings. """
    if False:
        pass
    elif pn == '1':
        a = db_session.query(CodeFirstPass).filter_by(
            article_id = request.args.get('article'),
            variable   = request.args.get('variable'),
            value      = request.args.get('value'),
            coder_id   = current_user.id
        ).all()
    elif pn == '2':
        a = db_session.query(CodeSecondPass).filter_by(
            article_id = request.args.get('article'),
            variable   = request.args.get('variable'),
            value      = request.args.get('value'),
            event_id   = request.args.get('event'),
            coder_id   = current_user.id
        ).all()
    else:
        return make_response("Invalid model", 404)

    if len(a) > 0:
        for o in a:
            db_session.delete(o)

        db_session.commit()

        return jsonify(result={"status": 200})
    else:
        return make_response("", 404)
예제 #15
0
파일: hello.py 프로젝트: 72L/72L.github.io
def savefilters():
	if request.method == 'POST':
		db_session.query(User).filter(User.email == request.form['email']).update({User.filters: request.form['filters']})
		db_session.commit()
		return 'filters saved'
	else:
		return db_session.query(User).filter(User.email == request.args.get('email')  )[0].filters
예제 #16
0
def rank():
    # users = db_session.query(User, Paste).filter_by()
    d["top_tags"] = db_session.query(Tag).order_by("times DESC").all()[:20]
    d["top_pastes"] = db_session.query(Paste).order_by("views DESC").all()[:10]
    d["new_pastes"] = db_session.query(Paste).order_by("created_time DESC").all()[:10]
    d["top_users"] = db_session.query(User).order_by("paste_num DESC").all()[:20]
    return render_template("rankapp/rank.html", **d)
예제 #17
0
파일: user.py 프로젝트: LichuanLu/blueberry
 def get_by_name(cls, user_name):
     if user_name is None or user_name < 1:
         return
     if '@' in user_name:
         return session.query(User).filter(User.email == user_name, User.status == ModelStatus.Normal).first()
     else:
         return session.query(User).filter(User.phone == user_name, User.status == ModelStatus.Normal).first()
예제 #18
0
    def check_user(cls, id):
        id = int(id)
        u = User.USERS.get(id)
        if u is not None:
            return u
        if id in range(5000, 6000):
            try:
                s = db_session.query(Student).filter_by(sid=id).one()
            except:
                s = None
            if s is not None:
                u = User(id=s.sid, name=s.sname, role="student")
                User.USERS[id] = u
                return u
        elif id in range(4000, 5000):
            try:
                f = db_session.query(Faculty).filter_by(fid=id).one()
            except:
                f = None
            if f is not None:
                u = User(id=f.fid, name=f.fname, role="faculty", dept=f.deptid)
                User.USERS[id] = u
                return u
        elif id in range(3000, 4000):
            try:
                s = db_session.query(Staff).filter_by(sid=id).one()
            except:
                s = None
            if s is not None:
                u = User(id=s.sid, name=s.sname, role="staff", dept=s.deptid)
                User.USERS[id] = u
                return u

        return None
예제 #19
0
def map_page():

    # Check if we need to update the services table
    is_update_needed = check_if_need_update("service", datetime.now(), SERVICES_UPDATE_RATE)
    if is_update_needed:
        update_services_stops()

    # Get all service numbers
    service_names = db_session.query(Service.name).all()
    favourites_array = []
    no_favourites = True

    if not current_user.is_anonymous():
        q = db_session.query(UserService, Service)
        favourites_assoc = q.filter(UserService.user_id == g.user.id).filter(Service.id == UserService.service_id).all()

        # Create array of serialised objects
        for favourite in favourites_assoc:
            favourites_array.append(favourite[1].name)

        if len(favourites_array) == 0:
            no_favourites = True
        else:
            no_favourites = False

    # Convert each name from unicode to string
    service_names_array = [service_name[0] for service_name in service_names]
    return render_template('pages/map.html', service_names=service_names_array, favourite_names= favourites_array, no_favourites=no_favourites)
예제 #20
0
def view(paste_id):
    try:
        paste_id = int(paste_id)
    except:
        abort(404)
    else:
        user_id, user = None, None
        if 'user' in session:
            user_id = session['user']['id']
        model = db_session.query(Paste).get(paste_id)
        if user_id:
            user = db_session.query(User).get(user_id)
        if model:
            model.views = model.views + 1
            lexer = get_lexer_by_name(model.syntax.syntax, stripall=True)
            output = request.args.get('output', 'html')
            if output == 'html':
                formatter = HtmlFormatter(linenos='table', cssclass="source")
                d['code'] = highlight(model.content, lexer, formatter)
                d['model'] = model
                d['user'] = user
                return render_template('pasteapp/view.html', **d)
            if output == 'image':
                formatter = ImageFormatter(image_format='png', font_name='DejaVu Sans MONO', line_numbers=True, unicodeoutput=True)
                f = StringIO()
                highlight(model.content, lexer, formatter, outfile=f)
                f.seek(0)
                if request.args.get('attachment', 'false').lower() == 'true':
                    return send_file(f, mimetype="image/png", as_attachment=True,
                            attachment_filename='davidpaste_%s.png' % model.id)
                return send_file(f, mimetype="image/png")
        else:
            abort(404)
예제 #21
0
def create():
    form = PasteForm(request.form, csrf_enabled=False)
    if request.method == 'POST' and form.validate_on_submit() and form.captcha.data.lower() == session['captcha'].lower():
        if 'user' in session:
            user_id = session['user']['id']
        else:
            user_id = 1
        model = Paste(form.syntax.data, form.title.data, form.content.data)
        model.user_id = user_id
        if user_id != 1:
            user = db_session.query(User).get(user_id)
            user.paste_num = int(user.paste_num) + 1
            db_session.add(user)
        if form.title.data:
            model.title = form.title.data
        else:
            model.title = u'未知标题'
        db_session.add(model)
        try:
            db_session.commit()
            syntax = db_session.query(Syntax).get(form.syntax.data)
            tags = form.tag.data.lower().strip().split()
            tags.append(syntax.name)
            updateTags(db_session, model, set(tags))
        except Exception, e:
            abort(500)
        else:
            return redirect(url_for('view', paste_id=model.id))
예제 #22
0
def delete_pic():
	#pic_id= request.args.get('pic_id', 0, type=str)
	pic_id=4
	userid = 1
	error=None
	error = checklogin()

	#删除照片
	if (db_session.query(Picture).filter(Picture.id==pic_id).first()):

		this_pic = db_session.query(Picture).filter(Picture.id==pic_id).first()
		if this_pic.user_id == session['userid']:
			db_session.delete(this_pic)
			db_session.commit()
		else:
			session['error'] = "对不起,您没有该权限"
	else:
		session['error'] = "该照片不存在"

	if 'error' in session:
		result = session['error']
		session.pop('error',None)
	else:
		error = ''

	return jsonify(error=error)
    def update(self, collection, document, identifier):
        """ update the content of an existing document
        the document is updated merging the two documents

            arguments:
                identifier -- the identifier of the item we want to update
                collection -- string name of the collection (or table)
                document -- the document in JSON format to be inserted

            returns:
                True/False
        """

        table_ = getattr(db, collection)
        try:
            old = db_session.query(table_).filter(table_.identifier == identifier).one()
            new_document = old.document.copy()
            new_document.update(document)
            db_session.query(table_).filter(table_.identifier==identifier).update({"document":new_document})
            self.log.debug("item {0} updated".format(identifier))
            res = db_session.commit()
            return res
        except Exception, e:
            self.log.error("database update error: {0}".format(e))
            return False
예제 #24
0
파일: views.py 프로젝트: scutarius/book
def edit_book():
    forms = EditBook()
    form = SearchForm()

    a = request.args.get('a')
    b = request.args.get('b')
    if request.method == 'POST':
        book = forms.book.data

        query = db_session.query(Book.id, Book.name, Author.name).\
                            select_from(Book, Author).\
                            filter(Author.books, Book.name==b, Author.name==a).first()
        id = query.id
        
        db_session.query(Book).filter(Book.id==id).update({'name': book})
        db_session.commit()

        return redirect(url_for('index'))

    return render_template('book/edit_book.html',
        title = 'edit form',
        forms = forms,
        form = form,
        name_a = a,
        name_b = b
        )
예제 #25
0
def athlete_sessions(rowkey, idathlete):
    if not check_auth(request):
        abort(401)
    if request.method == 'GET':
        club = application_cache.get_club_by_sessiontoken(request.headers.get('sessiontoken'))
        if rowkey != club:
            abort(401)
        athlete = db_session.query(Athlete).filter_by(club=rowkey,id=idathlete)
        retSessions = {"athleteSessions": []}
        if len(list(athlete)) == 0:
            abort(404)
        else:
            training_sessions = db_session.query(TrainingSession)\
                .join(Group).join(GroupMember).join(Athlete).filter_by(id=idathlete).order_by(TrainingSession.fromtime.desc())

            if len(list(training_sessions)) > 0:
                for ts in training_sessions:
                    retSessions["athleteSessions"].append({"name":ts.name,
                                        "description": ts.description,
                                        "fromtime": str(ts.fromtime.isoformat()),
                                        "totime": str(ts.totime.isoformat()),
                                        "id": ts.id
                    })

        return jsonify(retSessions)
예제 #26
0
def get_current_rate():
    all_rates = db_session.query(DollarRate.id).distinct().all()
    all_rates = [each[0] for each in all_rates]
    current_id = all_rates[-1]
    current_rate = db_session.query(DollarRate.rate).filter(DollarRate.id == current_id).first()
    current_rate = current_rate[0]
    return current_rate
예제 #27
0
def view_schedule():
	schedule = sess.query(Schedule).one()
	assignments = schedule.assignments

	schedule = sess.query(Schedule).one()

	errors = []
	for assn in schedule.assignments:
		if assn.course is None:
			errors.append('%r missing course' % assn)

		if assn.mentor is None:
			errors.append('%r missing mentor' % assn)

		if assn.assn_id is None:
			errors.append('%r missing id' % assn)

	if errors:
		raise Exception('%r' % errors)

	#Calculate statistics
	total_cost = sum(map(lambda x: x.cost, assignments))
	avg_cost = total_cost/len(assignments)

	return render_response('view_schedule.html', locals())
예제 #28
0
def scrape(alerts):

    for alert in alerts:
        if alert.status:
            soup = url_to_soup(alert.link)
            ids, dates, descs, prices, links = pull_data(soup)
            last_update = db_session.query(Scrape).filter_by(alert=alert).order_by(desc('dt')).first()
            new_post_cnt = 0
            if last_update != None:
                for i in ids:
                    if i not in last_update.post_ids:
                        new_post_cnt +=1
            now = datetime.datetime.now()
            scrape = Scrape(post_ids=dumps(ids), dates=dumps(dates), 
                            descs=dumps(descs), prices=dumps(prices), 
                            links=dumps(links), dt=now,
                            new_posts=new_post_cnt, alert=alert)
            db_session.add(scrape)
            db_session.commit()
            #update the last_24 field in the alerts table by getting the last 12 scrapes (assuming
            #that the scrapes are done every 2 hours) and adding up any new posts
            past_24 = db_session.query(Scrape).filter_by(alert=alert).order_by(desc('dt')).limit(24)
            delta24 = datetime.timedelta(hours=24)
            last_24 = 0
            for past in past_24:
                if now - past.dt <= delta24:
                    last_24 += past.new_posts
            alert.last_24 = last_24
            alert.post_cnt += new_post_cnt
            db_session.add(alert)
            db_session.commit()
    print "Scheduled scrape was run:", datetime.datetime.now()
예제 #29
0
파일: app.py 프로젝트: andyhull/janApp
def add_entry():
    # clean the entered phone number
    newPhone = cleanphone(request.form['phone'])
    # did we get a valid number?????
    if newPhone != '-1':
        db_session.add(Numbers(newPhone))
        db_session.commit()
        # Find the numbers that do not have a buddy
        newBud = db_session.query(Numbers).filter(Numbers.buddy==None, Numbers.phone != newPhone).first()
        if newBud:
            # Add the buddy number to the newly added phone number
            db_session.query(Numbers).filter(Numbers.phone==newPhone).update({Numbers.buddy: newBud.phone})
            # Add the number to the buddy list 
            db_session.query(Numbers).filter(Numbers.phone==newBud.phone).update({Numbers.buddy: newPhone})
            db_session.commit()
            body = "Thanks for signing up! You've been matched with a buddy. You can text this number to start sharing!"
            send_sms(newPhone, body)
            send_sms(newBud.phone, body)
            return redirect(url_for('index'))
        else:
            body = "Thanks for signing up! We're still waiting to match you. We'll contact you when we get a match, usually in a day or two."
            send_sms(newPhone, body)
            return redirect(url_for('index'))

    else:
        flash('Sorry that is not a valid number')
        return redirect(url_for('index'))
예제 #30
0
def FightHistoryToJson(fighterData, currentFightId):
    #Finds all fights that given fighter was in
    histories = db_session.query(Fight).filter(or_(Fight.fighter1_id ==fighterData.id,
                                                    Fight.fighter2_id == fighterData.id)).filter(Fight.id != currentFightId)
    
    appendedJsonHistory = []
    for fightHistory in histories:
        winLose = None
        #Must determine if the fighter was player 1 or player 2 and set bets occordingly
        if fightHistory.fighter1_id == fighterData.id:
            opponentId = fightHistory.fighter2_id
            betFor = fightHistory.bet1
            betAgainst = fightHistory.bet2
        else:
            opponentId = fightHistory.fighter1_id
            betFor = fightHistory.bet2
            betAgainst = fightHistory.bet1

        if fightHistory.winner_id == fighterData.id:
            winLose = True
        else:
            winLose = False

        historyJson = {'opponentName':db_session.query(Fighter).get(opponentId).name,
                        'winLose': winLose,
                        'betFor':betFor,
                        'betAgainst':betAgainst}
        appendedJsonHistory.append(historyJson)

        return appendedJsonHistory
예제 #31
0
def map_get():
    c = db_session.query(carte).first()
    region = {
        "center": {
            "latitude": 0,
            "longitude": 0
        },
        "span": {
            "latitudeSpan": c.carte_largeur,
            "longitudeSpan": c.carte_longueur
        }
    }
    r = joueur.query.all()
    rankedPlayer = joueur.query.order_by(joueur.joueur_budget.desc()).all()
    ranking = [i.getProp('joueur_pseudo') for i in rankedPlayer]
    itemsByPlayer = {}
    additionalPropPlayerInfo = {}
    drinksByPlayer = {}

    for e_joueur in r:
        prop = []
        zones = e_joueur.zones
        for zone in zones:
            zone_location = \
                {
                    "latitude": zone.zone_posX,
                    "longitude": zone.zone_posY
                }
            prop.append({
                "kind": zone.zone_type,
                "owner": e_joueur.getProp('joueur_pseudo'),
                "influence": zone.zone_rayon,
                "location": zone_location
            })

        itemsByPlayer[e_joueur.getProp('joueur_pseudo')] = prop

        if e_joueur.getProp('joueur_pseudo'
                            ) not in json_model.actualRecettesNumberAndPrices:
            json_model.actualRecettesNumberAndPrices[e_joueur.getProp(
                'joueur_pseudo')] = []

        propPlayerProperties = \
            {
                "cash": e_joueur.joueur_budget,
                "sales": e_joueur.joueur_ventes,
                "profit": e_joueur.joueur_profit,
                "drinksOffered": json_model.actualRecettesNumberAndPrices[e_joueur.getProp('joueur_pseudo')]
            }

        additionalPropPlayerInfo[e_joueur.getProp(
            'joueur_pseudo')] = propPlayerProperties
        drinksByPlayer[e_joueur.getProp(
            'joueur_pseudo')] = json_model.actualRecettesNumberAndPrices[
                e_joueur.getProp('joueur_pseudo')]

    final_map = \
        {
            "region": region,
            "ranking": ranking,
            "itemsByPlayer": itemsByPlayer,
            "playerInfo": additionalPropPlayerInfo,
            "drinksByPlayer": drinksByPlayer
        }
    return final_map
예제 #32
0
 def get_user(self):
     return db_session.query(User).filter_by(email=self.email.data).first()
예제 #33
0
def list_all_securities():
    """Lists all saved db securities"""
    securities = db_session.query(Security).all()
    for s in securities:
        print(s)
예제 #34
0
def plot_all():
    """Creates a plot for each entry in table security"""
    securities = db_session.query(Security).all()
    for s in securities:
        dc.plot_security(s.symbol)
예제 #35
0
def getExecutionRequest(execution_id):
    return db_session.query(ExecutionRequest).filter(
        ExecutionRequest.execution_id == execution_id).first()
예제 #36
0
 def load_user(user_id):
     return db_session.query(User).get(user_id)
예제 #37
0
 def getCateUrls(self):
     urls = []
     for c in db_session.query(piccategory).all():
         urls.append(c)
     return urls
예제 #38
0
def experiment_nousers(expid):
    """Invite a user via email"""
    exp=db_session.query(Experiment).get(expid)
    if not exp:
        return render_template('error.html',message="Experimento no definido",recent=recent.get())
    return  render_template('nousers.html',projname=exp.name)
예제 #39
0
def get_current_user_first_name():
    cur_id = current_user.get_id()
    cur_user = db_session.query(User).filter(User.id == cur_id).first()
    if cur_user is not None:
        return cur_user.first_name
    return "User"
예제 #40
0
 def get_user(self):
     return db_session.query(User).filter_by(
         username=self.username.data).first()
예제 #41
0
def get_locations():
    locations = db_session.query(Location).all()
    return [location.location_id for location in locations]
예제 #42
0
 def validate_login(self, field):
     if db_session.query(User).filter_by(
             username=self.username.data).count() > 0:
         raise validators.ValidationError('Duplicate username')
예제 #43
0
 def get_patient_by_id(cls, id):
     if id:
         return session.query(Patient).filter(Patient.id == id).first()
예제 #44
0
def index():
    books = db_session.query(Book).all()
    return render_template('index.html', books=books)
예제 #45
0
def resultControl():
    if(request.method == 'POST'):

        # 클라이언트에서 sentenceId & wav file 받아옴
        wav = request.files['receiveFile']
        filename = request.form['fileName']
        sentenceId = request.form['sentenceId']

        # upload 디렉터리에 저장
        wav.save(FILE_DIRECTORY + secure_filename(wav.filename))

        ##### upload 디렉터리에 있는 파일을 STT로 변한

        # 임시 path
        args = easydict.EasyDict({"local_file_path": "./uploadFile/"+filename})

        # TODO Credential Error
        # print(sample_recognize(args.local_file_path))


        # sentenceId를 통해 DB에서 표준 발음 텍스트 가져옴
        Pick_sentence = db_session.query(Sentence).filter(Sentence.sentenceId == sentenceId).first()

        receiveSTTData = sample_recognize(args.local_file_path)
        receiveData = similaritySentence(receiveSTTData, Pick_sentence.standard)
        #receiveData = "날시가 참 말따"
        print("STT result : ", receiveData)

        # print(Pick_sentence)
        ##### 분석 알고리즘

        hannanum = Hannanum()

        StandardSentence = Pick_sentence.standard
        sentenceData = Pick_sentence.sentenceData

        # 공백 인덱스 리스트 생성
        # 공백 개수는 일치
        userBlankList = [i for i, value in enumerate(receiveData) if value == " "]
        standardBlankList = [i for i, value in enumerate(StandardSentence) if value == " "]
        # print(BlankList)

        # 문자열 길이가 다르거나 공백 개수가 다르면
        # 재시도 요청
        if (len(receiveData) != len(StandardSentence) or len(userBlankList) != len(standardBlankList)):
            os.remove("./uploadFile/"+filename)

            return jsonify(
                status="failure",
                resultData=receiveData,
                errorMessage="repeat",
            )

        # 공백 제거
        UserSentence = receiveData.replace(" ", "")
        StandardSentence = StandardSentence.replace(" ", "")
        sentenceData = sentenceData.replace(" ", "")

        # print(UserSentence)
        # print(StandardSentence)

        Total_pho = 0           # 총 음소 개수
        Wrong_total_pho = 0     # 틀린 음소 개수
        Wrong_word_index_list = []   # 틀린 글자 데이터가 들어있는 리스트
        Wrong_word_list = []         # 틀린 단어 데이터가 들어있는 리스트
        Wrong_pho_dict = {'u' : {},
                          'm' : {},     # 틀린 음소가 저장되는 딕셔너리
                          'b' : {}}     # u : 자음, m : 모음, b : 받침


        for index, standard in enumerate(StandardSentence):
            StandPho = phonemeConvert(standard)

            # 글자가 일치하는 경우
            if(UserSentence[index] == standard):
                if(StandPho[2] == ' '):
                    Total_pho += 2
                else:
                    Total_pho += 3
            # 글자가 일치하지 않는 경우
            # 음소 분해
            else:
                Wrong_word_index_list.append(index)
                UserPho = phonemeConvert(UserSentence[index])
                SentencePho = phonemeConvert(sentenceData[index])

                if(UserPho[2] == ' ' and StandPho[2] == ' '):
                    Total_pho += 2
                else:
                    Total_pho += 3

                    if(UserPho[2] != StandPho[2]):
                        Wrong_total_pho += 1

                        if StandPho[2] != ' ':
                            if StandPho[2] in Wrong_pho_dict['b']:
                                Wrong_pho_dict['b'][SentencePho[2]] += 1
                            else:
                                Wrong_pho_dict['b'][SentencePho[2]] = 1

                if (UserPho[0] != StandPho[0]):
                    Wrong_total_pho += 1
                    if StandPho[0] in Wrong_pho_dict['u']:
                        Wrong_pho_dict['u'][SentencePho[0]] += 1
                    else:
                        Wrong_pho_dict['u'][SentencePho[0]] = 1

                if (UserPho[1] != StandPho[1]):
                    Wrong_total_pho += 1
                    if StandPho[1] in Wrong_pho_dict['m']:
                        Wrong_pho_dict['m'][SentencePho[1]] += 1
                    else:
                        Wrong_pho_dict['m'][SentencePho[1]] = 1

        # print(Wrong_pho_dict)


        ######### 틀린 음소 record 테이블에 count 올림 -> TEST SUCCESS
        for type in Wrong_pho_dict:
            for pho in Wrong_pho_dict[type]:
                # print(pho)
                updateData = db_session.query(Record).filter(Record.recordType == type)\
                                                    .filter(Record.recordData == pho).first()
                # print(updateData.type, updateData.recordData)
                updateData.count += Wrong_pho_dict[type][pho]
                db_session.commit()



        # 일치율
        Correct_rate = round(1 - (Wrong_total_pho / Total_pho), 4)
        """
        # 일치율 100%인 경우
        if Correct_rate == 1:
            os.remove("./uploadFile/" + filename)

            return jsonify(
                status="perfect",
                resultData=receiveData,
                score=Correct_rate,
            )
        """
        # print(Wrong_word_list)

        # 변경 후
        # print(Wrong_word_index_list)
        sentenceData_split = Pick_sentence.sentenceData.split()
        # print(sentenceData_split)
        # 틀린 인덱스가 포함된 단어 선택
        word_start_point = 0
        for sentence_word in sentenceData_split:
            word_end_point = word_start_point + len(sentence_word)-1

            # print(word_start_point, word_end_point)

            for wrong_index in Wrong_word_index_list:
                if word_start_point <= wrong_index and word_end_point >= wrong_index:
                    word_to_pos = hannanum.pos(sentence_word)

                    # print(word_to_pos)
                    wrong_word_pho_list = phonemeConvert(sentenceData[wrong_index])
                    # print(wrong_word_pho_list)
                    for pos in word_to_pos:
                        #TODO 틀린 단어에 N이나 P가 여러개 들어있으면??
                        if pos[1] == 'N' or pos[1] == 'P':
                            for pos_word in pos[0]:
                                pos_word_pho_list = phonemeConvert(pos_word)
                                # print(pos_word_pho_list)
                                if wrong_word_pho_list[0] == pos_word_pho_list[0]:
                                    Wrong_word_list.append(pos)

                    break

            word_start_point += len(sentence_word)

        print(Wrong_word_list)

        # 틀린 글자 인덱스를 원래 문장을 기준으로 변경
        for i in userBlankList:
            for index, j in enumerate(Wrong_word_index_list):
                if(j >= i):
                    Wrong_word_index_list[index] += 1

        # print(Wrong_word_index)

        ######## result 테이블에 결과값 저장 -> TEST SUCCESS
        resultData = Result(stid=sentenceId, rsdata=receiveData, score=Correct_rate)
        db_session.add(resultData)
        db_session.commit()


        # 일치율 100%인 경우
        if Correct_rate == 1:
            os.remove("./uploadFile/" + filename)

            return jsonify(
                status="perfect",
                resultData=receiveData,
                score=Correct_rate,
            )

        ######## 가장 많이 틀린 단어에 대한 추천 문장 1개

        recommend_OtoD = dict(sentenceId=-1, sentenceData="", standard="")
        recommend_word = ""

        # 틀린 단어 리스트에 단어가 존재할 경우
        if Wrong_word_list:
            random.shuffle(Wrong_word_list)

            for random_select_word in Wrong_word_list:
                Word_query = db_session.query(Word).filter(Word.wordData == random_select_word[0])\
                    .filter(Word.wordType == random_select_word[1]).filter(Word.sentenceId != sentenceId)
                Word_entry = [pq.sentenceId for pq in Word_query]

                if Word_entry:
                    recommend_word = random_select_word[0]
                    if random_select_word[1] == 'P':
                        recommend_word += '다'
                    random_select_setencdId = random.choice(Word_entry)
                    Recommend_sentence = db_session.query(Sentence).filter(Sentence.sentenceId == random_select_setencdId).first()
                    recommend_OtoD['sentenceId'] = Recommend_sentence.sentenceId
                    recommend_OtoD['sentenceData'] = Recommend_sentence.sentenceData
                    recommend_OtoD['standard'] = Recommend_sentence.standard
                    break

    os.remove("./uploadFile/" + filename)

    # response해줄 틀린 단어 리스트
    wordList = []

    for w in Wrong_word_list:
        if w[1] == "P":
            wordList.append(w[0]+"다")
        else:
            wordList.append(w[0])

    # 결과 데이터를 모두 json으로 묶음
    return jsonify(
        status = "success",
        score = Correct_rate,
        wordList = wordList,
        userBlank = userBlankList,
        standardBlank = standardBlankList,
        wrongIndex = Wrong_word_index_list,
        resultData = receiveData
    )
예제 #46
0
 def getAllHospitals(session):
     return session.query(Hospital).filter(
         Hospital.status == constant.ModelStatus.Normal).all()
예제 #47
0
def get_price_history(app):
    now = datetime.now()
    one_hour_ago = now - timedelta(hours=1)
    one_day_ago = now - timedelta(days=1)

    price_history = [
        ['Tid', 'Kjøp', 'Salg'],
    ]

    # The date point begins at the start of the chart and will increment with the chart granularity
    date_point = one_day_ago

    # Let's always start the chart at *the start of* an hour. This'll make caching easier
    date_point -= timedelta(
        minutes=date_point.minute,
        seconds=date_point.second,
        microseconds=date_point.microsecond,
    )

    # Include an extra hour, which might be fetched by cache or query, in order to make sure the price *previous to the
    # very first one in the chart* is included. If it weren't, that data point would be null, since price history would
    # by definition start *after* that data point. If the case is that no trades have happened in that hour, the data
    # point will still be null (and further ones after that until a trade has happened).
    one_hour_before_date_point = date_point - timedelta(hours=1)

    # Now retrieve as many cached query results as possible, before selecting the remainder
    query_start_date = one_hour_before_date_point
    prices = []
    while True:
        price_hour = cache.get('price.history.query.by_hour.%s' %
                               query_start_date.strftime("%d.%m.%Y.%H:%M"))
        if price_hour is None:
            # End of cache; stop
            break
        elif query_start_date >= one_hour_ago:
            # Cached up to an hour ago? We don't want that; stop
            break
        else:
            prices.extend(price_hour)
            query_start_date += timedelta(hours=1)

    # Select *remaining* prices and cache them by the hour
    # Note that this query actually is quite heavy on the CPU because of decimal conversions
    remaining_prices = db_session.query(Price).filter(
        Price.datetime >= query_start_date,
        Price.datetime <= now,
    ).order_by(Price.datetime)
    prices.extend(remaining_prices)
    for hour, hour_prices in groupby(
            remaining_prices, key=lambda p: p.datetime.strftime("%H:00")):
        # Cache by hour, up until, but not including, the last hour
        hour_prices = list(hour_prices)
        if hour_prices[0].datetime < one_hour_ago:
            cache.set(
                'price.history.query.by_hour.%s' %
                (hour_prices[0].datetime.strftime("%d.%m.%Y.%H:00")),
                hour_prices,
                60 * 60 *
                25,  # Note that we're caching for 25 hours since we'll be quering 25 hours back
            )

    # Now that we've retrieved or queried all prices, there should be some extra ones from the hour *before* 24h ago.
    # Find the latest one of them (if any), and set that one as the previous price
    previous_price = None
    prices_before_chart_start = [p for p in prices if p.datetime < date_point]
    if len(prices_before_chart_start) > 0:
        previous_price = prices_before_chart_start[-1]

    # Finally group the prices by date and hour, so we can easily calculate plot points per hour
    prices_by_hour = {}
    for group, price_group in groupby(
            prices, key=lambda p: p.datetime.strftime("%d.%H:00")):
        prices_by_hour[group] = list(price_group)

    # Now iterate each hour, calculate the prices for each of them and cache most of the results, except for the very
    # last hour - we'll want to recalculate that with new trade data each request until a complete hour history has
    # been recorded. After caching we'll remove prices older than 24h ago, so that the chart plots exactly 24h at any
    # time.
    twentyfour_hours_ago = now - timedelta(hours=24)
    while date_point < one_hour_ago:
        hour_set = cache.get('price.history.result.by_hour.%s' %
                             date_point.strftime("%d.%m.%Y.%H:%M"))
        if hour_set is None:
            try:
                prices_this_hour = prices_by_hour[date_point.strftime(
                    "%d.%H:00")]
            except KeyError:
                # Probably won't occur here unless
                # a) there's a serious issue with the stock exchange, or
                # b) our ticker has stopped for over an hour
                prices_this_hour = []
            hour_set = _calculate_hour(app, date_point, now, previous_price,
                                       prices_this_hour)
            cache.set(
                'price.history.result.by_hour.%s' %
                date_point.strftime("%d.%m.%Y.%H:%M"), hour_set, 60 * 60 * 24)
        hour_history, previous_price = hour_set

        # Remove results older than 24h ago, now that they're cached
        if date_point < twentyfour_hours_ago:
            hour_history_within_24h = []
            for h in hour_history:
                _, minute = h[0].split(":")
                if int(minute) >= now.minute:
                    hour_history_within_24h.append(h)
            hour_history = hour_history_within_24h

        price_history.extend(hour_history)
        date_point += timedelta(hours=1)

    # We're at the last hour; calculate that without caching it
    try:
        prices_this_hour = prices_by_hour[date_point.strftime("%d.%H:00")]
    except KeyError:
        # Might occur at the start of a new hour when no trades have been recorded
        prices_this_hour = []
    hour_set = _calculate_hour(app, date_point, now, previous_price,
                               prices_this_hour)
    hour_history, previous_price = hour_set
    price_history.extend(hour_history)
    return price_history
예제 #48
0
def clear_testcase():
    db_session.query(TestRun).delete()
    db_session.query(Testcase).delete()
    db_session.commit()
예제 #49
0
def view_tool():
    session['url'] = request.url[len(request.url_root):]
    if request.method == 'GET':
        if 'name' in request.args:
            name = request.args.get('name')
            result = db_session.query(Tool).filter_by(name=name).first()
            return render_template('tool.html',
                                   result=result,
                                   title='cutrenet',
                                   subtitle=name)
        elif not current_user.has_role('admin'):
            flash(u'No tienes permisos para editar esta herramienta', 'error')
            return redirect('/tools', code=302)
        elif 'add' in request.args:
            form = ToolForm()
            return render_template('tool.html',
                                   form=form,
                                   title='cutrenet',
                                   subtitle="new tool")
        elif 'edit' in request.args:
            ename = request.args.get('edit')
            form = ToolForm(self_edit=ename)
            result = db_session.query(Tool).filter_by(name=ename).first()
            form.description.data = result.description  # Prepopulate textarea with past information, can´t do it at render time
            if result.maintainer is not None:
                form.maintainer.data = result.maintainer.dni
            return render_template('tool.html',
                                   form=form,
                                   result=result,
                                   title='cutrenet',
                                   subtitle=ename)
        elif 'delete_img' in request.args:
            del_img = request.args.get('delete_img')
            tool = db_session.query(Tool).filter_by(name=del_img).first()
            if tool.image:
                os.remove(tool.image)  # Delete old image
                tool.image = None
                db_session.commit()
                flash(u'Imagen eliminada', 'success')
            else:
                flash(u'No hay imagen que eliminar', 'alert')
            return render_template('tool.html',
                                   result=tool,
                                   title='cutrenet',
                                   subtitle=tool.name)
        elif 'delete' in request.args:
            delete = request.args.get('delete')
            tool = db_session.query(Tool).filter_by(name=delete).first()
            db_session.delete(tool)
            db_session.commit()
            flash(u'Herramienta eliminada', 'success')
            return redirect('/tools', code=302)
        else:
            flash(u'Tienes que seleccionar una herramienta', 'error')
            return redirect('/tools', code=302)

    if request.method == 'POST' and current_user.has_role('admin'):
        if 'edit' in request.args:
            ename = request.args.get('edit')
            tool = db_session.query(Tool).filter_by(name=ename).first()
            form = ToolForm(self_edit=ename)
            if form.validate_on_submit():
                tool.name = request.form['name']
                tool.description = request.form['description']
                tool.location = request.form['location']
                tool.manual = request.form['manual']
                tool.documentation = request.form['documentation']

                maintainer = db_session.query(User).filter_by(
                    dni=request.form['maintainer']).first()
                if maintainer is not None:
                    maintainer.tool_maintainer.append(tool)

                if form.image.data:
                    if tool.image is not None:
                        os.remove(tool.image)  # Delete old image
                    f = form.image.data
                    filename = secure_filename(f.filename)
                    directory = app.config['UPLOAD_FOLDER'] + '/tools'
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    file_path = os.path.join(directory, filename)
                    f.save(file_path)
                    tool.image = file_path  # Save the file path of the Tool image in the database

                db_session.commit()
                flash(u'Herramienta editada', 'success')
            return render_template('tool.html',
                                   form=form,
                                   result=tool,
                                   title='cutrenet',
                                   subtitle=tool.name)
        elif 'add' in request.args:
            tool = Tool()
            form = ToolForm()
            if form.validate_on_submit():
                tool.name = request.form['name']
                tool.description = request.form['description']
                tool.location = request.form['location']
                tool.manual = request.form['manual']
                tool.documentation = request.form['documentation']

                maintainer = db_session.query(User).filter_by(
                    dni=request.form['maintainer']).first()
                if maintainer is not None:
                    maintainer.tool_maintainer.append(tool)

                if form.image.data:
                    if tool.image is not None:
                        os.remove(tool.image)  # Delete old image
                    f = form.image.data
                    filename = secure_filename(f.filename)
                    directory = app.config['UPLOAD_FOLDER'] + '/tools'
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    file_path = os.path.join(directory, filename)
                    f.save(file_path)
                    tool.image = file_path  # Save the file path of the Tool image in the database

                db_session.add(tool)
                db_session.commit()
                flash(u'Herramienta añadida', 'success')
                return redirect('tools', code=302)
            return render_template('tool.html',
                                   form=form,
                                   title='cutrenet',
                                   subtitle="new tool")
예제 #50
0
def view_voting():
    votes = {}
    if request.method == 'GET':
        if 'id' in request.args:
            uid = request.args.get('id')
            result = db_session.query(Voting).filter_by(id=uid).first()

            form = VoteForm()
            options = db_session.query(Option).filter_by(voting_id=uid).all()
            choices = []
            votes['number'] = {}
            votes['user'] = 0
            for option in options:
                choices.append((option.id, option.name))
                votes['number'][option.name] = db_session.query(
                    VotesUsers).filter_by(option_id=option.id).count()
                votes['user'] += db_session.query(VotesUsers).filter_by(
                    option_id=option.id).filter_by(
                        user_id=current_user.id).count()
            form.option.choices = choices

            if result.end_date + timedelta(1) > date.today(
            ):  #bigger means older
                votes['end'] = 0
            else:
                votes['end'] = 1

            return render_template('voting.html',
                                   result=result,
                                   form=form,
                                   votes=votes,
                                   title='cutrenet',
                                   subtitle=result.name)
        elif not current_user.has_role('admin'):
            flash(u'No tienes permisos para añadir o borrar votaciones',
                  'error')
            return redirect('/votaciones', code=302)
        elif 'add' in request.args:
            form = VotingForm()
            return render_template('voting.html',
                                   form=form,
                                   title='cutrenet',
                                   subtitle="new voting")
        elif 'delete' in request.args:
            delete = request.args.get('delete')
            voting = db_session.query(Voting).filter_by(id=delete).first()
            db_session.delete(voting)
            db_session.commit()
            flash(u'Votación eliminada', 'success')
            return redirect('/votaciones', code=302)
        else:
            flash(u'Tienes que seleccionar una votación', 'error')
            return redirect('/votaciones', code=302)

    if request.method == 'POST':
        if 'add' in request.args and current_user.has_role('admin'):
            voting = Voting()
            form = VotingForm()
            if form.validate_on_submit():
                voting.name = request.form['name']
                voting.description = request.form['description']
                voting.start_date = form.start_date.data
                voting.end_date = form.end_date.data
                names = request.form['options'].split('|')

                for name in names:
                    option = Option()
                    option.name = name
                    voting.options.append(option)

                db_session.add(voting)
                db_session.commit()
                flash(u'Votación añadida', 'success')
                return redirect('votaciones', code=302)
            return render_template('voting.html',
                                   form=form,
                                   votes=votes,
                                   title='cutrenet',
                                   subtitle="new voting")
        elif 'vote' in request.args:
            uid = request.args.get('vote')
            form = VoteForm()
            options = db_session.query(Option).filter_by(voting_id=uid).all()
            choices = []
            votes['number'] = {}
            votes['user'] = 0
            for option in options:
                choices.append((option.id, option.name))
                votes['number'][option.name] = db_session.query(
                    VotesUsers).filter_by(option_id=option.id).count()
                votes['user'] += db_session.query(VotesUsers).filter_by(
                    option_id=option.id).filter_by(
                        user_id=current_user.id).count()
            form.option.choices = choices

            result = db_session.query(Voting).filter_by(id=uid).first()
            if result.end_date + timedelta(1) > date.today(
            ):  #bigger means older
                votes['end'] = 0
            else:
                votes['end'] = 1
            if form.validate_on_submit():
                if votes['user'] == 0:
                    option = db_session.query(Option).filter_by(
                        id=request.form['option']).first()
                    user = db_session.query(User).filter_by(
                        id=current_user.id).first()
                    option.votes.append(user)
                    db_session.add(option)
                    db_session.commit()
                    votes['user'] = 0
                    for option in options:
                        votes['number'][option.name] = db_session.query(
                            VotesUsers).filter_by(option_id=option.id).count()
                    votes['user'] = 1
                    flash(u'Voto registrado', 'success')
                else:
                    flash(u'Ya has votado, mamón', 'alert')
            return render_template('voting.html',
                                   form=form,
                                   result=result,
                                   votes=votes,
                                   title='cutrenet',
                                   subtitle=u"voted ✔️")
예제 #51
0
def member_profile():
    if request.method == 'GET':
        if 'dni' in request.args:
            dni = request.args.get('dni')
            if current_user.dni == dni or current_user.has_role('admin'):
                user = db_session.query(User).filter_by(dni=dni).first()

                enlisted_workshops = []
                for workshop in user.workshops:
                    inscription = db_session.query(WorkshopsUsers).filter_by(
                        workshop_id=workshop.id).filter_by(
                            user_id=user.id).first()
                    enlisted_workshops.append({
                        "workshop": workshop,
                        "paid": inscription.paid,
                        "complete": inscription.complete
                    })
                return render_template('profile.html',
                                       result=user,
                                       title='cutrenet',
                                       enlisted_workshops=enlisted_workshops,
                                       subtitle=user.first_name + ' ' +
                                       user.last_name)
            else:
                flash(u'No tienes permisos para ver este perfil', 'error')
                return redirect('/', code=302)
        elif 'edit' in request.args:
            dni = request.args.get('edit')
            user = db_session.query(User).filter_by(dni=dni).first()
            if int(session["user_id"]) == int(
                    user.id) or current_user.has_role('admin'):
                form = EditMemberForm(self_edit_dni=dni,
                                      self_edit_email=user.email)
                return render_template('profile.html',
                                       form=form,
                                       result=user,
                                       title='cutrenet',
                                       subtitle=user.first_name + ' ' +
                                       user.last_name)
            else:
                flash(u'No tienes permisos para editar este perfil', 'error')
                return redirect('/', code=302)
        elif 'delete' in request.args and current_user.has_role('admin'):
            dni = request.args.get('delete')
            if current_user.dni == dni or current_user.has_role('admin'):
                db_session.query(User).filter_by(dni=dni).delete()
                db_session.commit()
                flash(u'Perfil borrado', 'success')
            else:
                flash(u'No tienes permisos para borrar este perfil', 'error')
            if current_user.has_role(
                    'admin'
            ):  # Si el usuario es administrador le mandamos a la lista de miembros, si no al inicio
                results = db_session.query(User).all()
                return render_template('profile_list.html',
                                       results=results,
                                       title='cutrenet',
                                       subtitle='miembros')
            else:
                return redirect('/', code=302)
        else:
            flash(u'Tienes que seleccionar un perfil', 'error')
            results = db_session.query(User).all()
            return render_template('profile_list.html',
                                   results=results,
                                   title='cutrenet',
                                   subtitle='miembros')

    if request.method == 'POST' and current_user.has_role('admin'):
        if 'edit' in request.args:
            dni = request.args.get('edit')
            user = db_session.query(User).filter_by(dni=dni).first()
            form = EditMemberForm(self_edit_dni=dni,
                                  self_edit_email=user.email)
            print('Nombre: ' + request.form['first_name'])
            if form.validate() == True:
                print('Nombre: ' + request.form['first_name'])
                user.last_name = request.form['last_name']
                user.first_name = request.form['first_name']
                user.email = request.form['email']
                user.dni = request.form['dni']
                user.school = request.form['school']
                user.degree = request.form['degree']
                user.year = request.form['year']
                user.telegram = request.form['telegram']
                db_session.commit()
                flash(u'Perfil editado', 'success')
            if form.validate() == False:
                print('Nombre: ' + request.form['first_name'] + 'NO')
                flash(u'Error al editar', 'error')
            return render_template('profile.html',
                                   form=form,
                                   result=user,
                                   title='cutrenet',
                                   subtitle=user.first_name + ' ' +
                                   user.last_name)
예제 #52
0
def view_workshop():
    session['url'] = request.url[len(request.url_root):]
    if request.method == 'GET':
        enlisted = {}
        if 'id' in request.args:
            uid = request.args.get('id')
            workshop = db_session.query(Workshop).filter_by(id=uid).first()

            if 'paid' in request.args:
                # Mark user as paid or not
                dni = request.args.get('paid')
                user = db_session.query(User).filter_by(dni=dni).first()
                inscription = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=user.id).first()
                inscription.paid = not inscription.paid
                db_session.commit()

            if 'complete' in request.args:
                # Mark user as paid or not
                dni = request.args.get('complete')
                user = db_session.query(User).filter_by(dni=dni).first()
                inscription = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=user.id).first()
                inscription.complete = not inscription.complete
                db_session.commit()

            enlisted['number'] = db_session.query(WorkshopsUsers).filter_by(
                workshop_id=workshop.id).count()
            enlisted['list'] = []
            users = User.query.filter(User.workshops.any(id=workshop.id)).all()
            for user in users:
                inscription = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=user.id).first()
                enlisted['list'].append({
                    "user": user,
                    "paid": inscription.paid,
                    "complete": inscription.complete
                })

            # Check if user is already enlisted. 1 for enlisted, 0 for not enlisted, 2 for not logged in
            if current_user.is_authenticated:
                enlisted['user'] = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=current_user.id).count()
            else:
                enlisted['user'] = 2
            return render_template('workshop.html',
                                   result=workshop,
                                   enlisted=enlisted,
                                   title='cutrenet',
                                   subtitle=workshop.name)
        elif current_user.is_authenticated and 'enlist' in request.args:
            workshop_id = request.args.get('enlist')
            workshop = db_session.query(Workshop).filter_by(
                id=workshop_id).first()
            user = db_session.query(User).filter_by(id=current_user.id).first()

            enlisted['number'] = db_session.query(WorkshopsUsers).filter_by(
                workshop_id=workshop.id).count()

            if workshop.participants > enlisted['number']:
                if workshop.members_only and not user.has_role('member'):
                    flash(u'Este taller es solo para miembros', 'error')
                else:
                    workshop.users.append(user)
                    db_session.commit()
                    inscription = db_session.query(WorkshopsUsers).filter_by(
                        user_id=user.id).first()
                    inscription.paid = False
                    inscription.complete = False
                    db_session.commit()
                    flash(u'Inscrito en el taller', 'success')
            else:
                flash(u'El taller está lleno', 'alert')

            if current_user.is_authenticated:
                enlisted['user'] = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=current_user.id).count()
            else:
                enlisted['user'] = 2
            enlisted['number'] = db_session.query(WorkshopsUsers).filter_by(
                workshop_id=workshop.id).count()
            enlisted['list'] = []
            users = User.query.filter(User.workshops.any(id=workshop.id)).all()
            for user in users:
                inscription = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=user.id).first()
                enlisted['list'].append({
                    "user": user,
                    "paid": inscription.paid,
                    "complete": inscription.complete
                })
            return render_template('workshop.html',
                                   result=workshop,
                                   enlisted=enlisted,
                                   title='cutrenet',
                                   subtitle=workshop.name)
        elif current_user.is_authenticated and 'unenlist' in request.args:
            workshop_id = request.args.get('unenlist')
            workshop = db_session.query(Workshop).filter_by(
                id=workshop_id).first()

            if current_user.is_authenticated:
                enlisted['user'] = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop_id).filter_by(
                        user_id=current_user.id).count()
            else:
                enlisted['user'] = 2

            if enlisted['user'] == 1:
                user = db_session.query(User).filter_by(
                    id=current_user.id).first()
                workshop.users.remove(user)
                db_session.commit()
                enlisted['user'] = 0
                flash(u'Desinscrito en el taller', 'alert')
            else:
                flash(u'El usuario no está inscrito en el taller', 'error')

            enlisted['number'] = db_session.query(WorkshopsUsers).filter_by(
                workshop_id=workshop_id).count()
            enlisted['list'] = []
            users = User.query.filter(User.workshops.any(id=workshop.id)).all()
            for user in users:
                inscription = db_session.query(WorkshopsUsers).filter_by(
                    workshop_id=workshop.id).filter_by(
                        user_id=user.id).first()
                enlisted['list'].append({
                    "user": user,
                    "paid": inscription.paid,
                    "complete": inscription.complete
                })
            return render_template('workshop.html',
                                   result=workshop,
                                   enlisted=enlisted,
                                   title='cutrenet',
                                   subtitle=workshop.name)
        elif not current_user.has_role('admin'):
            flash(u'No tienes permisos para editar este taller', 'error')
            return redirect('/workshops', code=302)
        elif 'add' in request.args:
            form = WorkshopForm()
            return render_template('workshop.html',
                                   form=form,
                                   title='cutrenet',
                                   subtitle="new tool")
        elif 'edit' in request.args:
            eid = request.args.get('edit')
            form = WorkshopForm()
            result = db_session.query(Workshop).filter_by(id=eid).first()
            form.description.data = result.description  # Prepopulate fields with past information, can´t do it at render time
            form.members_only.data = result.members_only
            form.instructor.data = result.instructor.dni
            return render_template('workshop.html',
                                   form=form,
                                   result=result,
                                   title='cutrenet',
                                   subtitle=result.name)
        elif 'delete_img' in request.args:
            del_img = request.args.get('delete_img')
            workshop = db_session.query(Workshop).filter_by(id=del_img).first()
            if tool.image:
                os.remove(tool.image)  # Delete old image
                tool.image = None
                db_session.commit()
                flash(u'Imagen eliminada', 'success')
            else:
                flash(u'No hay imagen que eliminar', 'alert')
            return render_template('workshop.html',
                                   result=tool,
                                   title='cutrenet',
                                   subtitle=tool.name)
        elif 'delete' in request.args:
            delete = request.args.get('delete')
            workshop = db_session.query(Workshop).filter_by(
                name=delete).first()
            db_session.delete(workshop)
            db_session.commit()
            flash(u'Taller eliminado', 'success')
            return redirect('/workshops', code=302)
        else:
            flash(u'Tienes que seleccionar un taller', 'error')
            return redirect('/workshops', code=302)

    if request.method == 'POST' and current_user.has_role('admin'):
        if 'edit' in request.args:
            eid = request.args.get('edit')
            workshop = db_session.query(Workshop).filter_by(id=eid).first()
            form = WorkshopForm()
            if form.validate_on_submit():
                workshop.name = request.form['name']
                workshop.description = request.form['description']
                workshop.location = request.form['location']
                workshop.date = form.date.data
                workshop.participants = int(request.form['participants'])
                workshop.members_only = form.members_only.data

                instructor = db_session.query(User).filter_by(
                    dni=request.form['instructor']).first()
                if instructor is not None:
                    instructor.workshop_instructor.append(workshop)
                tool = db_session.query(Tool).filter_by(
                    id=request.form['tooling']).first()
                if tool is not None:
                    tool.workshops.append(workshop)

                if form.image.data:
                    if workshop.image is not None:
                        os.remove(tool.image)  # Delete old image
                    f = form.image.data
                    filename = secure_filename(f.filename)
                    directory = app.config['UPLOAD_FOLDER'] + '/workshops'
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    file_path = os.path.join(directory, filename)
                    f.save(file_path)
                    tool.image = file_path  # Save the file path of the Tool image in the database

                db_session.commit()
                flash(u'Taller editado', 'success')
            return render_template('workshop.html',
                                   form=form,
                                   result=workshop,
                                   title='cutrenet',
                                   subtitle=workshop.name)
        elif 'add' in request.args:
            name = request.args.get('add')
            workshop = Workshop()
            form = WorkshopForm()
            if form.validate_on_submit():
                workshop.name = request.form['name']
                workshop.description = request.form['description']
                workshop.location = request.form['location']
                workshop.date = form.date.data
                workshop.participants = int(request.form['participants'])
                workshop.members_only = form.members_only.data

                instructor = db_session.query(User).filter_by(
                    dni=request.form['instructor']).first()
                if instructor is not None:
                    instructor.workshop_instructor.append(workshop)
                tool = db_session.query(Tool).filter_by(
                    id=request.form['tooling']).first()
                if tool is not None:
                    tool.workshops.append(workshop)

                if form.image.data:
                    if tool.image is not None:
                        os.remove(tool.image)  # Delete old image
                    f = form.image.data
                    filename = secure_filename(f.filename)
                    directory = app.config['UPLOAD_FOLDER'] + '/workshops'
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    file_path = os.path.join(directory, filename)
                    f.save(file_path)
                    tool.image = file_path  # Save the file path of the Tool image in the database

                db_session.add(workshop)
                db_session.commit()
                flash(u'Taller añadido', 'success')
                return redirect('workshops', code=302)
            return render_template('workshop.html',
                                   form=form,
                                   result=workshop,
                                   title='cutrenet',
                                   subtitle=workshop.name)
예제 #53
0
 def getPatientDraftByPatienId(cls, id):
     if id:
         return session.query(Patient).filter(
             Patient.id == id,
             Patient.status.in_([ModelStatus.Draft,
                                 PatientStatus.diagnose])).first()
예제 #54
0
 def get_identityPhone_by_patientID(cls, patientID):
     if patientID:
         return session.query(
             Patient.identityPhone).filter(Patient.id == patientID).first()
예제 #55
0
def getExecutionResponse(execution_id, access_token):
    return db_session.query(
        ExecutionResponse.result, ExecutionResponse.execution_id).filter(
            and_(ExecutionResponse.execution_id == execution_id,
                 ExecutionResponse.access_token == access_token)).first()
예제 #56
0
 def get_patient_draft(cls, id):
     if id:
         return session.query(Patient).filter(
             Patient.userID == id,
             Patient.status == ModelStatus.Draft).first()
예제 #57
0
def getProcessorRequest(state):
    return db_session.query(ProcessorRequest).filter(
        ProcessorRequest.state == state).first()
예제 #58
0
def getProcessorRequests():
    return db_session.query(ProcessorRequest).all()
예제 #59
0
 def getDocUrls(self):
     urls = []
     for c in db_session.query(picdocument).all():
         urls.append(c)
         self.urlBeen.add(c.docpath)
     return urls
예제 #60
0
 def get_patient_by_user(cls, userId):
     if userId:
         return session.query(Patient).filter(
             Patient.userID == userId,
             Patient.status == PatientStatus.diagnose).all()