예제 #1
0
 def remover(self):
     self.listar()
     indice = input("Digite o ID que deseja remover: ")
     result = session.query(ServidorModel).filter(
         ServidorModel.id == indice).first()
     session.delete(result)
     session.commit()
예제 #2
0
def remover_usuario():
    listar_usuario()
    indice = input("Digite o ID que deseja remover: ")
    result = session.query(UsuarioModel).filter(
        UsuarioModel.id == indice).first()
    session.delete(result)
    session.commit()
예제 #3
0
def del_client():
    log.info('Controle del_clients starts')
    if request.method == 'POST':
        # si la méthode du formaulaire est post on interroge la table Client avec comme contrainte le prénom et le nom de l'utilisateur
        client_account = db.query(Client).filter_by(
            firstname=request.form['firstname']).filter_by(
                lastname=request.form['lastname']
            )  #.filter_by(email=request.form['email'])
        #ensuite on récupère sous forme tuples la ligne du client
        client = db.execute(client_account).fetchone()
        #si le client n'existe pas on redirige l'utilisateur sur un page d'erreur
        if client is None:
            return render_template('redirectory_delete_client.html')

        else:
            #si il existe on récupère on id en interrogeant la table Client on récupère son id à l'indcice 0
            client_id = db.query(Client).get(client[0])
            #ensuite on interroge la table Bankaccount possédant tous les ocmptes bancaires du client à l'aide de  l'id du client,
            # ensuite on supprime le client de la table Bankaccount
            db.query(BankAccount).filter_by(
                client_id=client_id.client_id).delete()
            # enusite on supprime l'id du client existant dans la table Client, il n'y a plus de trace de lui
            db.delete(client_id)

            db.commit()
            return redirect(url_for('home_admin'))
    else:
        return render_template('delete_client.html')
예제 #4
0
def delete_tutorial(id):
	if not g.user_id:
		return redirect(url_for("index"))
	tutorial = db_session.query(Tutorial).get(id)
	db_session.delete(tutorial)
	db_session.commit()
	return redirect(url_for("list_tutorials"))
예제 #5
0
def update_watched_episodes():
    user_id = int(request.form.get("user_id"))
    episode_id = int(request.form.get("episode_id"))
    status = request.form.get("status")
    print "status", status
    
    if status == "true":
        watched_episode = model.WatchedEpisode(user_id=user_id, episode_id=episode_id)
        DB.add(watched_episode)
    else:
        watched_episode = DB.query(model.WatchedEpisode).filter_by(user_id=user_id, episode_id=episode_id).one()
        DB.delete(watched_episode)

    DB.commit()
    series = DB.query(Series).filter(Series.episodes.any(Episode.id == episode_id)).one()

    eps_list = DB.query(Episode).filter_by(series_id=series.id).order_by(Episode.season_num).all()
    season_dict = {}
    watched_ep_ids =[]

    watched_count = DB.query(model.WatchedEpisode).\
        join(model.WatchedEpisode.episode).\
        filter(model.Episode.series_id == series.id).\
        filter(model.WatchedEpisode.user_id == user_id).count()
    
    pct = round(100 * float(watched_count)/float(len(eps_list)), 1)

    response = {
        'success': True,
        'completion_percentage': pct,
    }

    return jsonify(response)
예제 #6
0
def delete_item():
	user = db_session.query(User).get(g.user_id)
	item = db_session.query(Item).get(request.args.get("id"))
	db_session.delete(item)
	db_session.commit()
	flash("item deleted", "info")
	return redirect(url_for('manage_items'))
예제 #7
0
def deletePerson():
    cno = int(request.form.get('cno'))
    person = session.query(Person).filter(Person.cno == cno).first()
    if person is not None:
        session.delete(person)
        session.commit()
    ret = {'code': 0, 'msg': '删除成功'}
    return jsonify(ret)
예제 #8
0
	def perform(user_id):
		# frab range of current queue ids for user
		exist_q = db_session.query(Queue).filter_by(user_id=user_id).all()
		exist = []
		for s in exist_q:
			exist.append(s.id)
		print exist

		stories = db_session.query(Stories).all()
		queued = []
		for item in stories:
			# determine probability that the user will like this item
			try:
				doc = Classifier.gettext(item.url) # strong of article words
				cl = FisherClassifier(Classifier.getwords, user_id) # returns instance 
				cl.setdb('news.db')
				# classification = 'yes'
				probability = cl.fisherprob(doc, 'yes')
				if probability > 0:
				# add item's probability to the queue dictionary
					tup = (item.id, probability)
					queued.append(tup)			
			except Exception:
				pass
		#sort queue by probability, lowest-->highest
		queue = sorted(queued, key=lambda x:x[1])	
		print queue 

		# grab top and low rated stories, add to Queue
		if len(queue)>=10:
			for i in queue[-8:]:
				story_id = i[0]
				score = i[1]
				# add story, user, and probability to db for pulling articles
				story = Queue(story_id=story_id, score=score, user_id=user_id)
				db_session.add(story)
			for i in queue[:2]:
				story_id = i[0]
				score = i[1]
				# add story, user, and probability to db for pulling articles
				story = Queue(story_id=story_id, score=score, user_id=user_id)
				db_session.add(story)
			db_session.commit()
		else:
			for i in queue:
				story_id = i[0]
				score = i[1]
				# add story, user, and probability to db for pulling articles
				story = Queue(story_id=story_id, score=score, user_id=user_id)
				db_session.add(story)
			db_session.commit()			

		# clear old stories out of Queue now that new ones are in there
		for i in exist:
			d = db_session.query(Queue).filter_by(id=i).first()
			db_session.delete(d)
		db_session.commit()
예제 #9
0
def cmd_purge(iid):
  """Purge (deletes completely) the given instance.
  """
  instance = get_instance(iid)
  if instance.state != DESTROYED:
    raise Exception("Can't purge an instance that is not destroyed")
  instance.purge()
  session.delete(instance)
  session.commit()
예제 #10
0
파일: window.py 프로젝트: Mulix/Pybiblio
 def del_book(self):
     a = self.liste.currentItem().text()
     b = session.query(Livre).filter_by(titre = a).first()
     session.delete(b)
     session.commit()
     item = self.liste.takeItem(self.liste.currentRow())
     item = None
     msgbox = QtGui.QMessageBox()
     msgbox.information(self, "Suppression", (u"Le livre: \"%s\" a bien était supprimé !" % unicode(a)))
예제 #11
0
def remove_from_favorites():
    user_id = int(request.form.get("user_id"))
    series_id = int(request.form.get("series_id"))

    fav = DB.query(model.Favorite).filter_by(series_id=series_id, 
                                        user_id=user_id).one()
    DB.delete(fav)
    DB.commit()

    return "Deleted fav!"
예제 #12
0
def remover_usuario():
    listar_usuario()
    indice = input("Digite o id do usuario: ")
    try:
        usuario = session.query(UsuarioModel).filter_by(id=indice).first()
        session.delete(usuario)
        session.commit()
    except Exception as e:
        session.rollback()
        print "Falhou ao remover usuario: ",e
예제 #13
0
def delete_sessions(session_uuid):
    ## load the session with given session id
    session = model.session.loadSession(session_uuid)
    if (session is None):
        return (json.dumps({"error": "invalid session"}), 500)

    ## delete the session
    session.delete()

    ## return status 204 "no content" instead of 200 "ok"
    return ("", 204)
예제 #14
0
def cmd_clean():
  """Drop database and remove all instances (useful for debugging).
  """
  for instance in all_instances():
    if instance.state == RUNNING:
      instance.stop()
    instance.purge()
    session.delete(instance)
    session.commit()

  #os.unlink(DB)
  system("rm -rf %s/nginx" % HOME)
예제 #15
0
def remover_servidor():
    listar_servidor()
    servidor_id  = input("Digite o id do servidor: ")
    
    try:
        servidor = session.query(ServidorModel) \
                          .filter_by(id=servidor_id).first()
        session.delete(servidor)
        session.commit()
        print "Servidor removido com sucesso!"
    except Exception as e:
        session.rollback()
        print "Falhou ao remover servidor: ",e   
예제 #16
0
def remover_servidor():
    listar_servidor()
    servidor_id = input("Digite o id do servidor: ")

    try:
        servidor = session.query(ServidorModel) \
                          .filter_by(id=servidor_id).first()
        session.delete(servidor)
        session.commit()
        print "Servidor removido com sucesso!"
    except Exception as e:
        session.rollback()
        print "Falhou ao remover servidor: ", e
예제 #17
0
def delete_past_carpools():
    # Removes passengers from TripPassenger table in DB
    # Removes past carpools from the Trip table in DB

    for record in db_session.query(model.Trip).all():
        departure = record.departure_date + " " + record.departure_time
        departureDT = parse(departure)
        if departureDT < datetime.datetime.now():
            passengers = db_session.query(model.TripPassenger).filter_by(trip_id=record.id)
            for p in passengers:
                db_session.delete(p)
            db_session.delete(record)
        db_session.commit()
    return "Old carpools deleted."
예제 #18
0
def deleteCatalog(catalog_id):
    """
    A route to delete a specific catalogs
    """
    deleteCatalog = session.query(Catalog).filter_by(
        id=catalog_id).one_or_none()
    if deleteCatalog is None:
        flash("The catalog you are looking for does not exist.")
        return redirect(url_for('catalog.showAllCatalogs'))
    if deleteCatalog.user_id != login_session['user_id']:
        flash("You are not authorized to delete.")
        return redirect(url_for('catalog.showAllCatalogs'))
    if deleteCatalog != [] and request.method == 'POST':
        session.delete(deleteCatalog)
        session.commit()
        flash(deleteCatalog.name + " is deleted!")
        return redirect(url_for('catalog.showAllCatalogs'))
    elif deleteCatalog != [] and request.method == 'GET':
        return render_template('catalogs_delete.html', catalog=deleteCatalog)
예제 #19
0
def fetch_info(user_url):
    uid = None
    response = requests.request("GET", user_url, headers=headers)
    soup = BeautifulSoup(response.text, features="lxml")
    try:
        info_str = soup.select(
            "div[class='u'] table td span[class='ctt']")[0].get_text()
        uid = avatar_re_pattern.findall(
            soup.select("div[class='u'] table td a")[0]['href'])[0]
        name, location = profile_re_pattern.findall(info_str)[0]
        logging.info("uid: {}, name: {}, location: {}".format(
            uid, name, location))
        try:
            user = User(uid, name, location)
            queue_follow(uid)
            # ele = FollowQueue(uid)
            session.add(user)
            # session.add(ele)
            session.commit()
        except IntegrityError:
            session.rollback()
            logging.info("repeat primary key")
    except IndexError:
        logging.error("Index out of range")
        t = 0
        with open('log/info_consumer/index_error_times.log', 'r') as f:
            t = int(f.read()) + 1
            if t > 4:
                first_info_obj = session.query(InfoQueue).order_by(
                    InfoQueue.create_time).first()
                session.delete(first_info_obj)
                session.commit()
                logging.info(
                    'remove first obj in info queue since there is some problems'
                )
        with open('log/info_consumer/index_error_times.log', 'w') as f:
            f.write(str(t))
        exit(-1)

    return uid
예제 #20
0
def dequeue_info():
    first_info_obj = session.query(InfoQueue).order_by(
        InfoQueue.create_time).first()
    if first_info_obj != None:
        # uid = first_info_obj.uid
        user_url = first_info_obj.url
        logging.info("got first url in info queue {}".format(user_url))
        uid = fetch_info(user_url)
        logging.info("got info of {}".format(uid))
        relations_in_buffer = session.query(InfoQueue).filter(InfoQueue.url==user_url)\
                                                      .all()
        for relation in relations_in_buffer:
            relation_obj = None
            if relation.follow_or_fan == FOLLOWEE:
                relation_obj = UserRelationship(uid, relation.source_uid)
                logging.info("build relationship between {} and {}".format(
                    uid, relation.source_uid))
            elif relation.follow_or_fan == FOLLOWER:
                relation_obj = UserRelationship(relation.source_uid, uid)
                logging.info("build relationship between {} and {}".format(
                    relation.source_uid, uid))
            try:
                session.add(relation_obj)
                session.delete(relation)
                logging.info("dequeue relationship between {} and {}".format(
                    relation.source_uid, uid))
                session.commit()
            except IntegrityError:
                session.rollback()
                logging.info("repeat primary key")
                session.delete(relation)
                logging.info(
                    "re-dequeue relationship between {} and {}".format(
                        relation.source_uid, uid))
                session.commit()

        with open('log/info_consumer/index_error_times.log', 'w') as f:
            f.write('0')
예제 #21
0
def deleteItem(catalog_id, item_id):
    """
    Delete an item
    """
    catalog = session.query(Catalog).filter_by(id=catalog_id).one_or_none()
    deleteItem = session.query(Item).filter_by(id=item_id).one_or_none()
    if catalog is None or item is None:
        flash("The catalog and/or you are looking for does not exist.")
        return redirect(url_for('catalog.showAllCatalogs'))

    if deleteItem.user_id != login_session['user_id']:
        flash("You are not authorized to delete.")
        return redirect(url_for('item.showAllItems', catalog_id=catalog.id))

    if deleteItem != [] and request.method == 'POST':
        session.delete(deleteItem)
        session.commit()
        flash(deleteItem.name + " is deleted!")
        return redirect(url_for('item.showAllItems', catalog_id=catalog_id))
    elif deleteItem != [] and request.method == 'GET':
        return render_template(
            'items_delete.html',
            catalog=catalog,
            item=deleteItem)
예제 #22
0
def remover_usuario():
    listar_usuario()
    indice = input("Digite o ID que deseja remover: ")
    result = session.query(UsuarioModel).filter(UsuarioModel.id==indice).first()
    session.delete(result)
    session.commit()
예제 #23
0
 def remover(self):
     self.listar()
     indice = input("Digite o ID que deseja remover: ")
     result = session.query(ServidorModel).filter(ServidorModel.id==indice).first()
     session.delete(result)
     session.commit()
예제 #24
0
    def perform(self, user_id):
        # grab range of current queue ids for user
        exist_q = db_session.query(Queue).filter_by(user_id=user_id).all()
        exist = []
        for s in exist_q:
            exist.append(s.id)

	    # grab all RSS stories from Story table of db
        stories = db_session.query(Stories).all()
	    # set up a queue for ranked stories
        queue = []
        for item in stories:
		    # determine probability that the user will like this item
            try:
                doc = Classifier.gettext(item.url) # strong of article words
            except Exception:
                pass
            cl = FisherClassifier(Classifier.getwords, user_id) # returns FC instance
            print cl
            print cl. getfeatures
            print cl.user_id
            print cl.cprob

            cl.setdb('news.db')
            # find the probability that a user will like a given article
            probability = cl.fisherprob(doc, 'yes')
            if probability > 0:
            # add item's probability to the queue dictionary
               tup = (item.id, probability)
               queue.append(tup)
        	    # queue[item.id]=probability
		# sort queue by probability, lowest --> highest
	    queue = sorted(queue, key=lambda x: x[1])
		
		# grab top and lower rated stories, add to Queue 
	    if len(queue)>=10:
		    for i in queue[:2]:
			    story_id = i[0]
			    score = i[1]
			    # add story, user, and probabiilty to the db for pulling articles for users
			    story = Queue(story_id=story_id, score=score, user_id=user_id)
			    db_session.add(story)
		    for i in queue[-8:]:
			    story_id = i[0]
			    score = i[1]
				# add story, user, and probabiilty to the db for pulling articles for users
			    story = Queue(story_id=story_id, score=score, user_id=user_id)
			    db_session.add(story)
		    db_session.commit()
	    else:
		    for i in queue:
			    story_id = i[0]
			    score = i[1]
			    # add story, user, and probabiilty to the db for pulling articles for users
			    story = Queue(story_id=story_id, score=score, user_id=user_id)
			    db_session.add(story)
		    db_session.commit()

		# clear old stories out of queue once new have been added
	    for i in exist:
		    d = db_session.query(Queue).filter_by(id=i).first()
		    db_session.delete(d)
	    db_session.commit()


	# set mins and get values (default to 0)
	def setminimum(self, cat, min):
		self.minimums[cat] = min


	def getminimum(self, cat):
		if cat not in self.minimums:
			return 0
		return self.minimums[cat]


	def cprob(self, f, cat):
		# frequency of this feature in this category
		clf = self.fprob(f, cat)
		if clf == 0: 
			return 0
		# frequency of this feature in all categories
		freqsum = sum([self.fprob(f,c) for c in self.categories()])
		# probability is the frequency in this category divided by overall frequency
		p = clf / (freqsum)
		return p # the probability that an item w/feature belongs in specified category, assuming equal items in each cat.


	# estimate overall probability: mult all probs together, take log, mult by -2
	def fisherprob(self, item, cat):
		# multiply all probabilities together	
		features = self.getwords(item) # list of words
		p = 1
		for f in features: # iterate through list
			p = p*(self.weightedprob(f, cat, self.cprob)) 
			# account for articles that are wildly not aligned with user's interests, since log(0) will break the classifier...
			if p == 0:
				return 0
		# take natural log and multiply by -2
		fscore = (-2)*math.log(p)

		# use inverse chi2 function to get a probability
		return self.invchi2(fscore, len(features)*2)

	# inverse chi-square function
	# by feeding fisher calculation to this, we get the probability that
	# a random  set of probabilities would return a high number for 
	# an item belonging in the category (eq. from CI book, p. 130)
	def invchi2(self, chi, df):
		m = chi / 2.0
		sum = term = math.exp(-m)
		for i in range(1, df//2):
			term *= m / i
			sum += term
		return min(sum, 1.0)