Example #1
0
def import_ratings(f):
  votes = defaultdict(list)
  with open(f) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
      votes[row['id']].append(row["this_dish_is_an_entree_on_a_dinner_menu__as_opposed_to_beverages_appetizers_or_sides"])

  with open(f) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
      if valid_item(votes, row):
        try:
          item = MenuItem.objects.get(locu_id=row["id"])
        except MenuItem.DoesNotExist:
					print "Could not find a menuitem", row["id"]
					continue
        username = row["_worker_id"]
        try:
          user = User.objects.get(username=username)
        except User.DoesNotExist:
					user = User(username=username)
					user.save()
        if row["i_would_like_to_eat_this_dish"] == "Yes":
					value = Rating.LIKE
        else:
					value = Rating.DISLIKE
        r = Rating(user=user, menu_item=item, value=value)
        r.save()
  for m in MenuItem.objects.all():
    if not Rating.objects.filter(menu_item=m).exists():
      m.delete()
  for v in Venue.objects.all():
    if not MenuItem.objects.filter(venue=v).exists():
      v.delete()
Example #2
0
def company(id):
    form = RateCoForm()
    user = g.user
    values = Value.query.all()
    company = Company.query.filter_by(id = id).first()
    if form.validate_on_submit():
        for v in form.value_ratings:
            print v.value_id.data, v.value_rating.data
            corating = db.session.query(Rating).filter_by(author=user, reader=company, value_id = v.value_id.data).first()
            print "Got the rating from the db", corating

            if not corating:
                corating = Rating(author=user, reader=company, value_id = v.value_id.data)
                db.session.add(corating)

            print "ORIGINAL, NEW", corating.rating, v.value_rating.data
            corating.rating = v.value_rating.data

        db.session.commit()
        flash('Rating has been added.')
        return redirect(url_for('colist'))
    if request.method == "GET":
        for v in values:
            form.value_ratings.append_entry({"value_id": v.id,
                                             "value_name": v.name})

    return render_template('company_rate.html',
        form = form,
        user = user,
        values = values,
        company = company)
Example #3
0
def rate(request, cafe_id):
	# create a rating object for a cafe from POST data
	if request.method == 'POST':
		try:
			# get the value of the rating value from the form, redirect if value is invalid
			value = int(request.POST['rating'])
		except ValueError:
			messages.add_message(request, messages.INFO, 'please choose a valid rating')
			return redirect('/cafe_hop/')
		# create new rating object for current cafe with datetime set to current
		cafe = Cafe.objects.get(id = cafe_id)
		now = datetime.now()
		# throw error/redirect if rating > 5 or < 0
		if (value > 5 or value < 0):
			messages.add_message(request, messages.INFO, 'please choose rating from 1-5')
			return redirect('/')
		if validate(request.session, cafe_id):
			rating = Rating(value = value, cafe = cafe, time = now)
			rating.save()
		else:
			messages.add_message(request, messages.INFO, 'please wait before you rate again')
			return redirect('/')
	else:
		form = RatingForm()
	return redirect('/')
Example #4
0
def add_rating(request):
    target_model = request.POST.get('model', '').lower()
    target_name = request.POST.get('id', '').lower()
    rating = request.POST.get('rating', '').lower()
    errors = []

    if target_model.strip() and target_name.strip():
        try:
            cleaned_rating = int(rating)
            rating_object = Rating(target_model=target_model,
                                   target_name=target_name,
                                   rating=cleaned_rating)
            rating_object.save()

            try:
                total_rating_object = TotalRating.objects.get(
                    target_model=target_model, target_name=target_name)
            except ObjectDoesNotExist:
                total_rating_object = TotalRating(target_model=target_model,
                                                  target_name=target_name)
                total_rating_object.save()

            total_rating_object.total_rating = total_rating_object.total_rating + cleaned_rating
            total_rating_object.rating_count += 1
            total_rating_object.save()
        except Exception:
            errors.append('INVALID_RATING')

    response = {'success': True, 'errors': errors}
    return shortcuts.render_to_response(
        'json.html', {'response': json.dumps(response)},
        context_instance=RequestContext(request),
        mimetype="application/json")
 def put(self):
     args = self.reqparse.parse_args()
     token, regex_id, mark = args['token'], args['regex_id'], args['mark']
     user_id = int(r[token])
     if user_id == 1:
         abort(403)
     re = Regex.query.filter(Regex.id == regex_id).first()
     post = Rating.query.filter(Rating.regex_id == regex_id,
                                Rating.user_id == user_id).first()
     if not user_id == re.author_id:
         if post:
             if not post.mark:
                 post.mark = mark
                 db.session.add(post)
                 db.session.commit()
                 return {'message': {'status': 'Changed'}}, 200
         else:
             if mark:
                 post = Rating(user_id=user_id,
                               regex_id=regex_id,
                               mark=mark)
             else:
                 post = Rating(user_id=user_id, regex_id=regex_id)
             db.session.add(post)
             db.session.commit()
             return {'message': {'status': 'Created'}}, 200
     return {'message': {'status': 'Not modified'}}, 200
Example #6
0
def add_rating(form_data, yelp_id, user_id, rating_id=None):
    """adds a rating form data and business_id"""
    print 'yelp_id in add_rating:', yelp_id

    if Business.query.filter_by(yelp_id=yelp_id).first() is None:
        validate_db(yelp_by_id(yelp_id))
    score = int(form_data.get("score"))
    review = form_data.get("review")
    # if a rating already existed, updates the score and the review
    print yelp_id
    if rating_id:
        rating = Rating.query.get(rating_id)
        rating.score = score
        if review:
            rating.review = review
        db.session.commit()
        return "Your rating has been updated"

    else:
        business = Business.query.filter_by(yelp_id=yelp_id).first()
        print 'business in add_rating:', business
        business_id = business.business_id
        created_at = datetime.now()

        rating = Rating(business_id=business_id,
                        user_id=user_id,
                        score=score,
                        created_at=created_at)
        if review:
            rating.review = review

        db.session.add(rating)
        db.session.commit()

        return "Your rating has been added!"
Example #7
0
def add_rating(request):
    target_model = request.POST.get('model', '').lower()
    target_name = request.POST.get('id', '').lower()
    rating = request.POST.get('rating', '').lower()
    errors = []
    
    if target_model.strip() and target_name.strip():
        try:
            cleaned_rating = int(rating)
            rating_object = Rating(target_model = target_model, 
                                   target_name = target_name, 
                                   rating = cleaned_rating)
            rating_object.save()
            
            try:
                total_rating_object = TotalRating.objects.get(target_model = target_model,
                                                              target_name = target_name)
            except ObjectDoesNotExist:
                total_rating_object = TotalRating(target_model = target_model,
                                                  target_name = target_name)
                total_rating_object.save()
            
            total_rating_object.total_rating = total_rating_object.total_rating + cleaned_rating
            total_rating_object.rating_count += 1
            total_rating_object.save()
        except Exception:
            errors.append('INVALID_RATING')
    
    response = {'success':True, 'errors':errors}
    return shortcuts.render_to_response('json.html',
                                         {'response':json.dumps(response)},
                                         context_instance = RequestContext(request),
                                         mimetype = "application/json") 
Example #8
0
def seed_rating(filename):
    linecount = 0
    f = open(filename)
    for row in f:
        row = row.rstrip()
        row = row.split("|")
        print linecount
        time = datetime.now()
        print time
        if not Rating.query.filter_by(user_id=row[0], business_id=row[1]).first():
            rating = Rating(user_id=row[0], business_id=row[1], score=row[2], created_at=time)
            if row[3] != '':
                rating.review = row[3]
            else:
                pass
            try:
                db.session.add(rating)
                db.session.commit()
            except:
                db.session.rollback()
                print "is borked."
            linecount += 1
            print "added", linecount
        print "complete", linecount, "ratings added"
    f.close()
Example #9
0
def _add_rating(tray, user, points):
    """
    Add a rating to a tray for a user, deleting other ratings by that user 
    first.
    """
    Rating.objects.filter(tray=tray, added_by=user).delete()
    rating = Rating(tray=tray, points=points, added_by=user)
    rating.save()
Example #10
0
def recreate_database():
    Song.collection().drop()
    Rating.collection().drop()
    Song.insert_many(songs_from_json())

    Song.collection().create_index([
        ('artist', TEXT),
        ('title', TEXT),
    ])
Example #11
0
def rate(request,movie_id,rating_value):
    user = _getuser(request)
    try:
        rating = Rating.objects.get(user__id=user.id,movie__id=movie_id)
        rating.rating = rating_value
    except Rating.DoesNotExist:
        rating = Rating(user=user,movie=Movie.objects.get(id=movie_id),rating=rating_value)
    rating.save()
    print rating
    return redirect('/movie/'+movie_id)
Example #12
0
def add_rating(request, profID):
	if request.method == 'POST':
		form = RatingForm(request.POST)
		if form.is_valid():
			rating = Rating()
			rating.professor = Professor.objects.get(id=profID)
			rating.poster = request.user
			rating.overall = form.cleaned_data['overall']
			rating.humor = form.cleaned_data['humor']
			rating.difficulty = form.cleaned_data['difficulty']
			rating.availability = form.cleaned_data['availability']
			if Rating.objects.filter(poster=request.user).filter(professor=rating.professor).count > 0:
				params = {
					'message': 'You cannot rate a professor multiple times',
				}
				return render(request, 'message.html', params)
			rating.save()
		return HttpResponseRedirect('/accounts/profs/profID/' + profID + '/')
	else:
		form = RatingForm()
		prof = Professor.objects.get(id=profID)
		params = {
			'form': form,
			'formTitle': 'Add a rating for ' + str(prof.firstName) + ' ' + str(prof.lastName),
		}
		return render(request, 'profSearch.html', params)
Example #13
0
def submitRating(request, bookName):

        book = Book.objects.filter(name=bookName)[0]
        user = request.user
        profile = Profile.objects.filter(user = user)[0]
        rating = request.POST['star']
        rating = int(rating)
        rating = Rating(book=book, profile = profile, rating = rating)
        rating.save()
        
        return HttpResponseRedirect('/books/' + bookName)
Example #14
0
def rate_coffee(payload, coffee_id):
    body = request.get_json()
    value = body['value']
    rating = Rating(value=value, coffee_id=coffee_id, user_id=payload['sub'])

    try:
        Rating.insert(rating)
    except:
        abort(500)

    return jsonify(success=True, rating=rating.value)
Example #15
0
 def post(self, request, *args, **kwargs):
     if not request.is_ajax():
         return HttpResponseBadRequest()
     data = request.POST.copy()
     vote = 1 if data['action'] == "add" else -1
     guest_message = GuestMessage.objects.get(pk=data['message_id'])
     guest_message.rating += vote
     guest_message.save()
     rating = Rating(guest_message=guest_message, session_id=request.session['guest_id'])
     rating.save()
     return HttpResponse(guest_message.rating)
Example #16
0
def place_delete(place_id, place_key_str):
    try:
        pkey = Place.make_key(place_id, place_key_str)
        cluster_ratings = ClusterRating.get_list({'place': pkey.urlsafe()})
        for cr in cluster_ratings:
            ClusterRating.delete(cr.key)
        user_ratings = Rating.get_list({'place': pkey.urlsafe()})
        for r in user_ratings:
            Rating.delete(r.key)
        res = Place.delete(pkey)
    except TypeError, e:
        return None, str(e), 400
Example #17
0
def saveRating(request, feed_id):
	print "hi"
	print request.POST["rating"]
	feed = get_object_or_404(NewsFeed, pk=feed_id)
	if (request.POST["rating"] >= 1):
		print request.POST["rating"]
		rating = Rating()
		rating.rating = request.POST["rating"];
		rating.save()
		feed.ratings.add(rating);
		feed.save()
		print feed
	return HttpResponseRedirect("/feed/" + str(feed.id))
Example #18
0
 def post(self):
     user, user_values = self.get_current_user(redirect=True)
     if not user: return False
     
     for rating, content_id in zip(self.request.POST.getall('stars'), \
                                   self.request.POST.getall('content_id')):
         rating = Rating(user=user, 
                         rating=int(rating),
                         content=ndb.Key(urlsafe=content_id),
                         parent=ndb.Key('Rating', ANNOTATION_NAME))
         rating.put()
     
     self.redirect('/annotate')
Example #19
0
def rate(request, slug):
    restaurant = get_object_or_404(Restaurant, slug=slug)
    score = request.GET["value"]
    ratings = Rating.objects.filter(restaurant=restaurant).filter(user=request.user)
    if len(ratings) > 0:
        ratings[0].score = int(score)
        ratings[0].save()
    else:
        newRating = Rating(restaurant=restaurant, user=request.user, score=int(score))
        newRating.save()
    newScore = restaurant.get_int_rating()
    to_return = {"score":newScore}
    serialized = simplejson.dumps(to_return)
    return HttpResponse(serialized, mimetype="application/json")
Example #20
0
def go(request):
	
	tabselected = None
	filtertag = request.META['PATH_INFO']
	if filtertag.find('/idea/') >= 0:
		filtertag = filtertag[6:]
		tabselected = filtertag.replace('/', '')
#		tabselected = 4
	else:
		filtertag = None
		
 	user = request.user
 	
 	rating = None
 	if user.is_authenticated():
		
		person = views.getPerson(request)
	 	if person:
	 		pratings = Rating.objects().order_by('score')
	 		if pratings and len(pratings)>=0:
	 			for prating in pratings:
	 				if person.currentRating >= prating.score:
	 					rating = prating
	 				else:
						break
	 	else:
			person = Person()
			person.email = user.email
			person.name = str(user)
			person.activationdate = datetime.datetime.now()
			person.save()
			views.incrementStat('users',1)
	 		pratings = Rating.objects().order_by('score')
	 		if pratings and len(pratings)>=0:
	 			for prating in pratings:
	 				if person.currentRating >= prating.score:
	 					rating = prating
					else:
						break
 		
 	
	template_values = {
 		'user':user,
 		'tabselected':tabselected,
 		'filtertag':None,
 		'rating':rating,
	}
	path = os.path.join(os.path.dirname(__file__), 'templates/ideas/index.html')
	return render_to_response(path, template_values)
Example #21
0
def create_bulk_ratings(rows):
    fields = [Rating.udemy_id, Rating.created, Rating.rating_score]

    count = len(rows)
    print('creating {} rows'.format(count))
    database = SqliteDatabase('ratings.db')
    with database.atomic():
        step_range = 250 #scale down as needed
        for step in range(0, count, step_range):
            Rating.insert_many(
                rows[step:step+step_range],
                fields=fields
            ).execute()

    print('done creating rows')
Example #22
0
def addrating(product_id):
    if request.method == 'POST':
        rating = request.form.get('rating')
        comment = request.form.get('comment')

        rating = float(rating)
        if rating > 5 or rating < 0:
            return redirect(url_for('product', product_id=product_id))

        checker = Rating.query.filter_by(user_id=current_user.id).filter_by(
            product_id=product_id).first()
        if checker:
            return redirect(url_for('product', product_id=product_id))

        r = Rating(user_id=current_user.id,
                   product_id=product_id,
                   rating=rating,
                   comment=comment)
        product = Product.query.filter_by(id=product_id).first()
        product.rating_count += 1

        db.session.add(r)
        db.session.commit()

    return redirect(url_for('product', product_id=product_id))
Example #23
0
def rating_list_get(filters):
    """
    It retrieves a list of Ratings satisfying the characteristics described in filter.

    Parameters:
    - filters: a dict containing the characteristics the objects in the resulting list should have.

    Available filters:
    - 'user': the user key in string format
        setting only 'user', the function retrieves all the ratings of this user
    - 'place': the place key is string format
        setting only 'place', the function retrieves all the ratings of this place
    - 'purpose': the purpose
        setting only 'purpose', the function retrieves all the ratings added to any place by any user about this purpose
        usually it is used in combination with other filters
    - 'users' : list of user ids we are interested in
    - 'places' : list of place ids we are interested in

    It returns a tuple: 
    - the list of Ratings that satisfy the filters (or None in case of errors in the input),
    - the status (a string indicating whether an error occurred)
    - the http code indicating the type of error, if any
    """
    try:
        res = Rating.get_list(filters)
    except (TypeError, ValueError) as e:
        return None, str(e), 400

    return res, "OK", 200
Example #24
0
def ratingMessage(demand_id, recipient):
    """
    The '/bid/<demand_id>/rating/<recipient>/message' route directs the user to explain their
    rating if it is below a certain amount.
    """
    if 'username' not in session:
        return redirect(url_for('login'))

    if 'username' in session and ('rating' + demand_id) in session:
        form = RatingMessageForm()
        if request.method == "GET":
            return render_template("ratingMessage.html",
                                   form=form,
                                   demand_id=demand_id,
                                   recipient=recipient)
        elif request.method == "POST":
            if form.message.validate(form):
                Rating(demand_id, recipient, session['username'],
                       session['rating' + demand_id], form.message.data)
                del session['rating' + demand_id]
                return render_template('ratingFinished.html',
                                       recipient=recipient)
            else:
                return render_template("ratingMessage.html",
                                       form=form,
                                       demand_id=demand_id,
                                       recipient=recipient)
    return render_template('access_denied.html')
Example #25
0
def fetch_ratings():
    """
    fetches ratings from the database, or from the API if they don't exist
    """

    #if the DB is empty, fetch the data
    if (Rating.select().count() == 0):
        clean_and_update_ratings(clean=False)

    print('getting ratings from DB')
    date_labels, average_axis, count_axis = format_averages_for_chartjs(
        calc_ratings_over_time(
            request.args.get('date_filter', 'all')
        )
    )
    print('returning data')

    current_average = udemy_api.get_current_average()
    return jsonify({
        'chart_data': {
            'date_labels': date_labels,
            'average_axis': average_axis,
            'count_axis': count_axis,
        },
        'current_average': current_average,
    })
    def sqlite_save(self):
        with app.app_context() as context:
            db.init_app(context.app)

            now =  datetime.utcnow()

            #fill table with scrapped data
            for y in range(0, len(self.results)):
                coin = Coins(self.results[y][1], self.results[y][2])

                #add coin if necessary
                result = Coins.query.filter_by(symbol = coin.symbol) 
                if result.count() == 0:
                    db.session.add(coin)
                    db.session.commit()
                else:
                    coin = result[0] 

                #add rating
                rate = Rating(self.results[y][0], coin, self.results[y][3],
                           self.results[y][4], self.results[y][5], self.results[y][6],
                           self.results[y][7], self.results[y][8], self.results[y][9], now )
                db.session.add(rate)
            db.session.commit()
        print('SQLite saved!!!')
Example #27
0
def songs_avg_rating(song_id):
    try:
        song_id = bson.ObjectId(song_id)
    except InvalidId:
        raise NotFound  # TODO: should return this also when valid ObjectId, but song with the id doesn't exist
    try:
        result = next(Rating.collection().aggregate(pipeline=[
            {
                '$match': {
                    'song_id': bson.ObjectId(song_id)
                },
            },
            {
                '$group': {
                    '_id': '$song_id',
                    'average_rating': {
                        '$avg': '$rating'
                    },
                    'min_rating': {
                        '$min': '$rating'
                    },
                    'max_rating': {
                        '$max': '$rating'
                    },
                },
            },
        ]))
        del result['_id']
    except StopIteration:
        result = dict(
            average_rating=None,
            min_rating=None,
            max_rating=None,
        )
    return jsonify(result)
Example #28
0
def RatingView(request, postID, valor):
	try:
		usuario = request.user
		rate = valor
		publicacion = Post.objects.get(id = postID)

		rate = Rating(usuario=usuario.profile, rate=rate, publicacion=publicacion)		
		publicacion.set_rate(valor)
		rate.save()
			
	except Post.DoesNotExist:
		raise Http404
	
	return HttpResponseRedirect('/Posts/'+postID)
	
	
Example #29
0
def put_user_in_cluster(user):
    
    ratings = Rating.get_list({'user': user.key.id()})
    rlist = {}
    for rating in ratings:
        if rating.not_known is False and rating.value > 0:
            place = rating.place.urlsafe()
            rlist['%s-%s' % (place, rating.purpose)] = rating.value
    ruser = {'ratings': rlist}
    
    centroids = {}
    cratings = ClusterRating.get_list({})
    for rating in cratings:
        if rating.cluster_id not in centroids:
            centroids[rating.cluster_id] = {'key': rating.cluster_id, 'ratings': {}}
        if rating.avg_value > 0:
            place = rating.place.urlsafe()
            centroids[rating.cluster_id]['ratings']['%s-%s' % (place, rating.purpose)] = rating.avg_value
    max_sim = 0
    cluster_id = None
    for clid in centroids:
        sim = logic.similarity(ruser, centroids[clid])
        if sim >= max_sim:
            max_sim = sim
            cluster_id = clid
    user.cluster_id = cluster_id
    user.put()
    return cluster_id
Example #30
0
def add_instructor_rating(instid):
    inst = Instructor.query.get(instid)
    if inst == None:
        flash('Invalid instructor id or unauthorized')
        return 'Invalid instructor id or unauthorized', 401
    rate = Rating.query.get((current_user.id, instid))
    if rate != None:
        flash('Already rated this insructor')
        return 'Already rated this insructor', 403
    data = request.get_json()
    rating = Rating(userid=current_user.id,
                    instructorid=instid,
                    rating1=data["rating1"],
                    rating2=data["rating2"],
                    rating3=data["rating3"],
                    rating4=data["rating4"],
                    rating5=data["rating5"],
                    rating6=data["rating6"],
                    rating7=data["rating7"],
                    rating8=data["rating8"],
                    rating9=data["rating9"],
                    rating10=data["rating10"],
                    rating11=data["rating11"])
    db.session.add(rating)
    db.session.commit()
    flash('Instructor rated')
    return "Instructor rated", 201
    def post(self):
        """
		Rate a post
		"""
        data = api.payload
        rating_value = data.get("value")
        if rating_value > 5 or rating_value < 0:
            abort(400,
                  {"Value": "la valeur d\'évaluation doit être entre 0 et 5!"})
        post_id = data.get("post_id")
        user_id = g.user.id
        post = Post.query.get(post_id)
        if not post:
            abort(404)

        rating = Rating.query.filter_by(user_id=user_id,
                                        post_id=post.id).first()
        if rating:
            rating.value = rating_value
        else:
            rating = Rating(value=rating_value,
                            user_id=user_id,
                            post_id=post_id)
        db.session.add(rating)
        db.session.commit()

        return {"element": post.to_json()}, 201
Example #32
0
def create_rating(session, user, note, rating):
    """Creates a rating based on a unique owner, note, and the value of the rating """

    check_permission(session, PermissionType.READ, user, note)

    rating = Rating(owner_id=user.id, note_id=note.id, value=rating)
    session.add(rating)
    return rating
def get_user_rate():
    rows = Rating.query.all()
    rating_list = []
    for row in rows:
        rating_list.append(Rating.as_dict(row))
    user_rate_dict = reader.get_user_rate(rating_list)

    return user_rate_dict
Example #34
0
def clean_and_update_ratings(clean=True):
    """
    wipes database, requeries API and creates db rows

    In a full project, instead of dangerously wiping all Rating data,
     I'd leave them there and compare the new data to the old, and
     only add the ones I haven't added already.
    """
    if clean:
        print('deleting all Ratings')
        Rating.delete().execute()

    print('fetching from API Ratings')
    all_ratings = udemy_api.get_all_ratings()
    print('adding rows')
    create_bulk_ratings(all_ratings)
    print('done clean_and_update_ratings')
def show_user_rate():
    rows = Rating.query.all()
    rating_list = []
    for row in rows[:1000]:
        rating_list.append(Rating.as_dict(row))
    user_rate_dict = reader.get_user_rate(rating_list)

    return json.dumps(user_rate_dict)
Example #36
0
        def post(self):
                user = users.get_current_user()
                movie = self.request.get('movietitle')
                rating = self.request.get('rating')
                ratingBefore = 0

                myresponse = {}

                query = Rating.query(Rating.movietitle == movie, Rating.username == user)
                currentRating = None

                for q in query:
                    currentRating = q

                if currentRating == None:
                    currentRating = Rating(username = user, movietitle = movie, movierating = int(rating))
                else:
                    ratingBefore = currentRating.movierating
                    currentRating.movierating = int(rating)

                query = UserRecord.query(UserRecord.username == user)
                userRecord = None

                for q in query:
                    userRecord = q

                if userRecord == None:
                    userRecord = UserRecord(username = user, totalratings = int(rating), numofratings = 1, averagerating = float(rating))
                else:
                    userRecord.totalratings = userRecord.totalratings - ratingBefore + int(rating)
                    if ratingBefore == 0:
                        userRecord.numofratings += 1

                    userRecord.averagerating = float(userRecord.totalratings) / float(userRecord.numofratings)

                logging.debug("Rating: " + rating)
                logging.debug("Username: "******"Movie: " + movie)
                currentRating.put()
                logging.debug("Total Ratings: " + str(userRecord.totalratings))
                logging.debug("Number of Ratings: " + str(userRecord.numofratings))
                logging.debug("Average Rating: " + str(userRecord.averagerating))
                userRecord.put()

                self.response.out.write(json.dumps(myresponse))
Example #37
0
def get_drink(drink_id):
    """Shows drink info page, handles creating/deleting ratings"""
    try:
        user_id = session['user']
    except KeyError:
        flash('Log in to rate/favorite drinks', 'warning')
        pass

    drink = Drink.query.get(drink_id)

    if request.method == 'POST':
        rating = request.json['rating']
        if float(rating) < 0 or float(rating) > 5:
            flash('Please enter a rating between 0 and 5', 'danger')
            return redirect(f'/drinks/{drink_id}')

        rating_check = Rating.query.filter(Rating.user_id == user_id).filter(
            Rating.drink_id == drink_id).first()

        if rating_check is None:
            new_rating = Rating(rating=rating,
                                user_id=user_id,
                                drink_id=drink_id)
            db.session.add(new_rating)
            db.session.commit()
        else:
            update_rating = Rating.query.get(rating_check.id)
            update_rating.rating = rating
            db.session.commit()

        return redirect(f'/drinks/{drink_id}')
    else:

        drink = Drink.query.get(drink_id)
        if 'user' not in session:
            rating = None
            fav_check = None
        else:
            rating = Rating.query.filter(Rating.user_id == user_id).filter(
                Rating.drink_id == drink_id).first()
            fav_check = Favorite.query.filter(
                Favorite.drink_id == drink_id).filter(
                    Favorite.user_id == user_id).first()

        ingredients = Drinks_Ingredients.query.filter(
            Drinks_Ingredients.drink_id == drink.id).all()
        names = []
        for ingredient in ingredients:
            ingredient_name = Ingredients.query.get(ingredient.ingredient_id)
            names.append(ingredient_name)

        return render_template('drink.html',
                               drink=drink,
                               ingredients=ingredients,
                               fav_check=fav_check,
                               rating=rating,
                               names=names)
Example #38
0
def create_comment(request, user_id):
    for_user = User.objects.get(id=user_id)
    rater = request.user
    #stop user from rating them
    score = request.POST.get('score', None)
    review = request.POST.get('review', None)

    if score and review:
        rating = Rating(
            for_user=for_user,
            rater=rater,
            score=score,
            review=review
        )
        rating.save()

    user_url = '/users/%s' % user_id
    return redirect(user_url)
Example #39
0
def dislikepost(postid):
    user = User.query.get(g.user.id)
    post = Post.query.get(postid)

    newrating = Rating(dislike=1, user_idd=user.id, post_idd=post.id)
    db.session.add(newrating)
    db.session.commit()

    return redirect(f'/{user.id}')
Example #40
0
def likepost(postid):
    user = User.query.get(g.user.id)
    post = Post.query.get(postid)

    newrating = Rating(like=1, user_idd=user.id, post_idd=post.id)
    db.session.add(newrating)
    db.session.commit()
    #user likes then it goes to match route and then to matches will redirect if not
    return redirect(f'/{user.id}/match')
Example #41
0
    def get(self):
        query = Rating.query(ancestor=ndb.Key('Rating', ANNOTATION_NAME))
        
        counts = defaultdict(int)
        for rating in query.fetch():
            counts[rating.user] += 1

        values = {"counts": sorted(counts.iteritems(), key=lambda x: x[1], reverse=True)}
        self.template_response('leaderboard.html', values)
Example #42
0
def feedback():
    form_rating = RatingForm()
    if form_rating.is_submitted():
        new_review = Rating(id_reviewer=form_rating.id_reviewer.data.upper(), type=form_rating.type.data,
                            review=form_rating.review.data)
        db.session.add(new_review)
        db.session.commit()
        return redirect('home')
    return render_template('feedback.html', form_rating=form_rating)
Example #43
0
def RatingDetailApi(rating_id):
    url = '/rating/detail/'
    values = {'rating_id': rating_id}
    raw = request_get(url, values)

    raw_obj = json.loads(raw)
    if raw_obj.get('rating') == None:
        return None
    rating = Rating(raw_obj['rating'])
    return rating
Example #44
0
def rate_recipe(recipe_id,rating):
    """Rate the recipe only for registered and athenticated users"""

    rated_query = Rating.query.filter((Rating.recipe_id == recipe_id) & (Rating.user_id==g.user.id)).first()
    if rated_query:
        rated_query.rating = rating
    else:
        rating = Rating(recipe_id=recipe_id,user_id=g.user.id,rating=rating)
        db.session.add(rating)
    db.session.commit()
Example #45
0
    def post(self, url_name):
        company = Company.all().filter('urlname = ', url_name).fetch(1)
        company = company[0]

	review = Review()
        review.company = company
	review.text = self.request.get('content')
        rating = Rating()
        rating.overall = self.GetIntOrDefault('overall')
        rating.benefits = self.GetIntOrDefault('benefits')
        rating.salary = self.GetIntOrDefault('salary')
        rating.environment = self.GetIntOrDefault('environment')
        rating.peers = self.GetIntOrDefault('peers')
        rating.location = self.GetIntOrDefault('location')
        rating.growth = self.GetIntOrDefault('growth')
        rating.put()
        review.rating = rating
	review.put()
	self.redirect('/companies/view/' + company.urlname)
def rating_query_all():
    rows = Rating.query.all()
    response = {}
    rating_list = []
    for row in rows[:100]:
        rating_list.append(Rating.as_dict(row))

    response['ok'] = True
    response['data'] = rating_list

    return json.dumps(response)
def rate_event_process(external_id, rating, token):
    """
    Insert, Update or delete the event
    """
    if int(rating) < 0:
        try:
            Rating.objects.get(event=Event.objects.get(external_id=external_id)).delete()
        except ObjectDoesNotExist:
            #  The value doesn't exist, so it's already deleted
            pass
    else:
        e = Event.objects.get(external_id=external_id)
        u = User.objects.get(external_id=Graph(token).get_me()['id'])
        r = None
        try:
            r = Rating.objects.get(event=e, user=u)
            r.rating = rating
        except ObjectDoesNotExist:
            r = Rating(event=e, user=u, rating=rating)
        r.save()
Example #48
0
    def get(self, request, recorded=False):
        scores = Rating.objects.all()
        try:
            curr_users_score = Rating.objects.get(user = request.user)
        except ObjectDoesNotExist:
            rating = Rating(user=request.user,
                           score=500)
            rating.save()
            curr_users_score = rating

        [score.calculate_game(curr_users_score) for score in scores]
        message = None
        if recorded:
            message = 'Score Recorded'
        return render_to_response(
            'handicap.html', {
                'curr_users_score': curr_users_score,
                'scores': scores,
                'message': message},
            context_instance=RequestContext(request))
Example #49
0
def rating_get(rating_id, rating_key_str):
    """
    It retrieves the rating.

    Parameters:
    - rating_id: the string id of the Rating
    - rating_key_str: the urlsafe string representing the key.

    Only one between rating_id and rating_key_str should be set, since they represent the same information, 
    but encoded in two different ways. They are both accepted for generality. If both are set, the id is used.

    It returns a tuple: 
    - the requested rating (or None in case of errors in the input),
    - the status (a string indicating whether an error occurred),
    - the http code indicating the type of error, if any
    """
    try:
        res = Rating.get_by_key(Rating.make_key(rating_id, rating_key_str))
    except TypeError as e:
        return None, str(e), 400
    return res, "OK", 200
def rating_user_book(user_id, book_id):
    row = Rating.query.filter_by(user_id=user_id, book_id=book_id).first()

    response = {}
    if row is not None:
        rating = Rating.as_dict(row)
        response = {'ok': True, 'data': rating}

    else:
        response = {'ok': False, 'data': {}}

    return json.dumps(response)
def rate_event_process(external_id, rating, token):
    """
    Insert, Update or delete the event
    """
    if int(rating) < 0:
        try:
            Rating.objects.get(event=Event.objects.get(
                external_id=external_id)).delete()
        except ObjectDoesNotExist:
            #  The value doesn't exist, so it's already deleted
            pass
    else:
        e = Event.objects.get(external_id=external_id)
        u = User.objects.get(external_id=Graph(token).get_me()['id'])
        r = None
        try:
            r = Rating.objects.get(event=e, user=u)
            r.rating = rating
        except ObjectDoesNotExist:
            r = Rating(event=e, user=u, rating=rating)
        r.save()
Example #52
0
def saveRatingSource(request, source_id):
	# print "saving rating event"

	if request.POST["userID"] == "None":
		userID = -1
	else:
		userID = request.POST["userID"]

	if request.POST["rating"] >= 1:
		ratings = Rating.objects.filter(ratee_id=source_id, rater_id=userID)
		source = NewsSource.objects.get(id=source_id)
		if len(ratings) > 0:
			rating = ratings[0]
			
			source.score -= rating.rating
			
		else:
			rating = Rating()

		rating.rating = request.POST["rating"]
		rating.rater_id = userID
		rating.ratee_id = source_id
		source.score += request.POST["rating"]


		if userID != -1:
			print userID
			rating.save()
		else:
			print "just kidding"

	return HttpResponse("woohoo")
Example #53
0
	def load_urm(self):
		self._run("load('urmFull.mat')")
		self._run("A=full(urm)")
		urm = self._get("A")
		#force matlab to close and free memory
		self._close_matlab()
		print 'Out of matlab!'
		for (row,col),value in numpy.ndenumerate(urm):
			print 'processing rating %i for user %i and item %i' % (value, row, col)
			if value is not 0:
				self.db.add(Rating(user_id=row+1, item_id=col+1, rating=value))
				self.db.flush()	
				self.db.commit()
Example #54
0
def app_fixtures():
    u1 = User(username='******')
    u2 = User(username='******')
    u3 = User(username='******')
    ecv.session.add(u1)
    ecv.session.add(u2)
    ecv.session.add(u3)

    hours = 6
    time_ready = datetime.datetime.utcnow() + datetime.timedelta(hours=hours)
    o1 = Offer(host=u1,
               portions=2,
               price=3.50,
               info="spaghetti gambanero, non-vegetarian",
               time_ready=time_ready)
    ecv.session.add(o1)

    res1 = Reservation(user=u2, offer=o1, portions=1)
    res2 = Reservation(user=u3, offer=o1, portions=1)
    ecv.session.add(res1)
    ecv.session.add(res2)

    rat1 = Rating(
        user=u2,
        host=u1,
        stars=2,
        comment=
        "I liked the sauce, but the company was terrible! I think his father was drunk..."
    )
    rat2 = Rating(user=u3,
                  host=u1,
                  stars=5,
                  comment="had a good time =) his dad is a fun guy")
    ecv.session.add(rat1)
    ecv.session.add(rat2)

    # commit changes
    ecv.session.commit()
Example #55
0
def rate_item(request, data):

	dajax = Dajax()
	unserializedData = simplejson.loads(data)
	itemId = int(unserializedData['item_id'])
	ratingValue = int(unserializedData['value'])
	user = request.user

	logger.debug('Rating item id [%s] value [%d] for user [%s]' % (itemId, ratingValue, user.username))

	ratedDate = datetime.today()
	# Update the rating if it exists, otherwise create it
	try:
		rating = Rating.objects.get( user=user, item=itemId )
		rating.value = ratingValue
		rating.created_datetime = ratedDate
	except (Rating.DoesNotExist):
		item = Item.objects.get(id=itemId)
		rating = Rating( user=user, item=item, value=ratingValue, created_datetime=ratedDate )

	rating.save()

	return dajax.json()
Example #56
0
def make_rate(teacher_id, **values):
    """ Perform the teacher rate

        Args:
            teacher_id (int):  Teacher id.
            user_id (int):  User id.

        Kwargs:
            values (list):  Values of rating of evil, easier, vague and brainy kinds.

        Raises:
            ObjectDoesNotExist

    """
    try:
        rating = Rating(teacher=Teacher.objects.get(pk=teacher_id),
                        evil_value=values['evil_value'], easier_value=values['easier_value'],
                        vague_value=values['vague_value'], brainy_value=values['brainy_value'])
        rating.save()

        _update_global_rating(rating)

    except (Teacher.DoesNotExist, User.DoesNotExist) as e:
        raise ObjectDoesNotExist(e.message)
Example #57
0
    def get(self):
        
        logging.info('kmeans.RecomputeClustersHandler.get START')
#         if 'X-AppEngine-QueueName' not in self.request.headers:
#             logging.info('recommender.RecomputeClustersHandler.get END called not from queue - 403')
#             # the request is not coming from a queue!!
#             self.response.set_status(403)
#             self.response.write("You cannot access this method!!!")
#             return
         
        client = memcache.Client()
        do_recompute = client.gets('recompute_clusters')
#         if do_recompute == True:
        if True:
            logging.info('KmeansComputeHandler -- recompute needed')
            #new ratings have been added, so clusters need to be recomputed
#             logging.info("Starting pipeline for kmeans computation!")
            ClusterRating.delete_all()
            logging.info("Removed old cluster ratings")
            # identify and store k random centroids
            centroids = {}
            users = PFuser().query().fetch(NUM_CLUSTERS, offset=10)
            num = 0
#         logging.info("USERS: " + str(len(users)))
            for user in users:
                ratings = Rating.get_list({'user': user.key.id()})
                rlist = {}
                for rating in ratings:
                    if rating.not_known is False and rating.value > 0:
                        place = rating.place.urlsafe()
                        rlist['%s-%s' % (place, rating.purpose)] = rating.value

                user = {'key': 'center_%s' % str(num), 'ratings': rlist}
                centroids['center_%s' % str(num)] = user
                num = num + 1
            logging.info("Centroids at start: %s" % str(centroids))
            store_to_dfbucket(CENTROIDS_FILE, str(centroids))

            pipe = KmeansPipeline()
            pipe.start()
            i =0
            while i<20:
                i+=1
                if client.cas('recompute_clusters', False):
                    break;
        logging.info('recommender.RecomputeClustersHandler.get END')
        self.response.write('OK')