def post(self, post_id, vote_default): post = post_exist(post_id) v = vote_exist(post_id, self.user.name) voteresult = self.request.get('voteresult') if not vote_default: vote_default = "votepost" if post: if self.user.name == post.created_by: error = "You cannot Like your own Post" self.render("errorpost.html", p=post, error=error) elif v.count() > 0: error = "You have already voted" self.render("errorpost.html", p=post, error=error) elif not voteresult: error = "You did not vote" + voteresult self.render(vote_default + ".html", p=post, error=error) else: v = Vote(parent=blog_key(), username_fk=self.user.name, post_id_fk=int(post_id), content=voteresult) v.put() self.redirect('/blog/%s' % post_id) else: self.redirect("/blog")
def upvote(): import json form = request.form vote = Vote(form) if not vote.is_voted(): vote.save() blog_id = int(form.get('blog_id', 0)) Blog.upvote(blog_id) blog = Blog.query.get(blog_id) upvotes = blog.upvotes response = dict(status=1, vote_num=upvotes, msg='点赞成功') else: response = dict(status=0, msg='点赞失败') return json.dumps(response)
def test_response(db_conn, posts_table): """ Expect a vote to require a response (None is okay). """ vote = Vote({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', }) del vote['response'] vote, errors = vote.save() assert len(errors) == 0 vote['response'] = True vote, errors = vote.save() assert len(errors) == 0
def update_entity_status(db_conn, proposal): """ Update the entity's status based on the vote power received. Move to accepted or blocked if qualified. TODO-2 Update this to work as described in: https://github.com/heiskr/sagefy/wiki/Planning%3A-Contributor-Ratings This requires knowing two things: - Number of learners the entity impacts - The vote and proposal history of the contributor """ # Get the entity version entity_version = get_version(db_conn, proposal['entity_version']['kind'], proposal['entity_version']['id']) votes = Vote.list(db_conn, replies_to_id=proposal['id']) changed, status = get_entity_status(entity_version['status'], votes) if changed: entity_version['status'] = status entity_version.save(db_conn) send_notices( db_conn, entity_id=proposal['entity_version']['id'], entity_kind=proposal['entity_version']['kind'], notice_kind=('block_proposal' if status == 'blocked' else 'accept_proposal'), notice_data={ 'user_name': '???', # TODO-2 'proposal_name': proposal['name'], 'entity_kind': proposal['entity_version']['kind'], 'entity_name': entity_version['name'], })
def game_results(game): votes = Vote.query(Vote.game == game.key).fetch(1000) player_votes = {} for vote in votes: three = vote.three if player_votes.has_key(three): player_votes[three].threes += 1 else: player_votes[three] = PlayerGameVotes(game=game.key, player=three, threes=1) two = vote.two if player_votes.has_key(two): player_votes[two].twos += 1 else: player_votes[two] = PlayerGameVotes(game=game.key, player=two, twos=1) one = vote.one if player_votes.has_key(one): player_votes[one].ones += 1 else: player_votes[one] = PlayerGameVotes(game=game.key, player=one, ones=1) if len(player_votes) < 3: # No votes cast return None sorted_votes = sorted(player_votes.items(), key=lambda p: -p[1].ranking_points()) players = [sorted_votes[0][0], sorted_votes[1][0], sorted_votes[2][0]] result = GameResults(game=game.key, three=players[0], two=players[1], one=players[2], voters=len(votes)) return result
def test_response(db_conn, posts_table, units_table): """ Expect a vote to require a response. """ create_proposal(posts_table, units_table, db_conn) vote = Vote({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', }) del vote['response'] vote, errors = vote.save(db_conn) assert len(errors) == 0 vote['response'] = True vote, errors = vote.save(db_conn) assert len(errors) == 0
def test_kind(db_conn, posts_table): """ Expect a vote to always have a kind of vote. """ vote = Vote({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', 'response': True, }) del vote['kind'] vote, errors = vote.save() assert len(errors) == 1 vote['kind'] = 'vote' vote, errors = vote.save() assert len(errors) == 0
def delete_game(self, game): tokens = Token.query(Token.game == game.key) keys = [token.key for token in tokens] votes = Vote.query(Vote.game == game.key) keys.extend([vote.key for vote in votes]) votes = SelfVote.query(SelfVote.game == game.key) keys.extend([vote.key for vote in votes]) ndb.delete_multi_async(keys) game.key.delete()
def vote_thread(slug_or_id): post_data = request.get_json() thread_id, user_id = Thread.check_user_and_thread( thread_slug_or_id=slug_or_id, nickname=post_data['nickname']) if not user_id and not thread_id: return json_response({'message': 'Thread OR USER not found'}, 404) thread = Vote.vote_for_thread(user_id, post_data['voice'], thread_id) thread['created'] = format_time(thread['created']) return json_response(thread, 200)
def post(self, article_id, vote_type): article = Article.get_by_id(int(article_id)) user = users.get_current_user() if user: user_key = JedditUser.key_from_user(user) # TODO Votes are now being created properly, Add update requests to a pull queue if vote_type == 'down': vote = Vote.create(article_key=article.key, user_key=user_key, value=DOWNVOTE) article.rating = article.rating - 1.0 else: vote = Vote.create(article_key=article.key, user_key=user_key, value=UPVOTE) article.rating = article.rating + 1.0 ndb.put_multi([article, vote]) return self.redirect('/', body="Thanks for your vote!")
def vote_on_a_poll(cls): poll_id = input("Enter the id of the poll you want to vote on: ") try: poll = Poll.select_by_id(int(poll_id)) except: print( "An error occurred. I can't find the poll id '{}' in the database. Please make sure you've entered a valid poll id." .format(poll_id)) cls.vote_on_a_poll() return options_list = Option.select_by_poll_id(poll_id) poll.print_poll_question() for option in options_list: option.print_option() users_vote = input("Enter an id of you answer: ") while users_vote not in [ str(option.option_id) for option in options_list ]: users_vote = input( "This is not a valid answer. Enter an id of you answer: ") users_name = input("Enter your name: ") while not users_name: users_name = input("Enter your name: ") users_timezone = input("Enter your timezone: ") while users_timezone not in pytz.all_timezones: users_timezone = input( "This is not a valid timezone. Try again. Enter your timezone: " ) users_timezone_obj = pytz.timezone(users_timezone) local_time_of_vote = users_timezone_obj.localize( datetime.datetime.now()) utc_timestamp = local_time_of_vote.astimezone(pytz.utc).timestamp() vote = Vote(users_vote, users_name, utc_timestamp) vote.save_to_db() input( f'\nThank you for participating in the poll, {users_name}! Press Enter to continue...' ) cls.select_from_menu()
def post(self, post_id): post = post_exist(post_id) v = vote_exist(post_id, self.user.name) if post: if self.user.name == post.created_by: error = "You cannot Like your own Post" self.render("errorpost.html", p=post, error=error) elif v: error = "You have already voted" self.render("errorpost.html", p=p, error=error) else: v = Vote(parent=blog_key(), user_fk=user, post_fk=post, content="Like") v.put() self.redirect('/blog/%s' % post_id) else: self.redirect("/blog")
def profile_page(id): try: admin = False ban = False self_profile = False if check.logged_in(): if id == session.get("user_id", ""): self_profile = True if admin_check.admin_logged_in(): admin = True user = User(id) if user.is_banned == True: ban = True parent_list = [] for vote in Vote.get_user_total_votes(user.id): if vote.is_comment == 1: parent_list.append(Comment(vote.comment_id)) elif vote.is_comment == 0: parent_list.append(Post(vote.post_id)) return render_template('profile.html', id=user.id, username=user.username, first_name=user.first_name, last_name=user.last_name, birth_date=user.birth_date, creation_date=user.date, posts=Post.get_user_post(user.id), email=user.email, self_profile=self_profile, total_votes=Vote.get_user_total_votes(user.id), comments=Comment.get_user_total_comments( user.id), reports=Report.get_user_all_reports(user.id), parent_list=parent_list, admin=admin, ban=ban) except NotImplementedError as error: flash("Error: " + str(error)) return redirect("/")
def select_random_winner(cls): poll_ids = Poll.show_poll_ids() poll_id = input( "Enter an id of a poll voters of which you want to select a random winner from: " ) while poll_id not in [str(id[0]) for id in poll_ids]: poll_id = input( "This is not a valid poll id. Enter a valid poll id: ") start_date = input( "Select a time period of which you want to pick up a random winner. \nEnter a start date and start hour (dd-mm-yyyy HH:MM): " ) end_date = input( "Enter the end date and the end hour (dd-mm-yyyy HH:MM): ") try: start_date_naive = datetime.datetime.strptime( start_date.strip(), "%d-%m-%Y %H:%M") end_date_naive = datetime.datetime.strptime( end_date.strip(), "%d-%m-%Y %H:%M") except ValueError: input( "At least one of the dates you've entered is not in a valid date format. Try again. Press Enter..." ) cls.select_random_winner() return if start_date_naive > end_date_naive: input( "End date cannot be older than the start date. Try again. Press Enter..." ) cls.select_random_winner() return timezone_ = input("Enter your timezone: ") while timezone_ not in pytz.all_timezones: input( "You've entered an invalid timezone. Please try again. Press Enter..." ) timezone_ = input("Enter your timezone: ") try: poll_id, poll_question, username, option_text, selectors_time_of_vote = Vote.select_random_winner( poll_id, start_date_naive, end_date_naive, timezone_) print( f'''\nA winner of a poll number {poll_id} answering a question "{poll_question}" is: {username}. The winner responded "{option_text}". Time of vote: {selectors_time_of_vote.strftime("%d-%m-%Y %H:%M")}. ''') input("\nPress Enter to continue...") except Exception: input("An error occurred. Press Enter...") finally: cls.select_from_menu()
def instance(data): """ Given data from the database, return an appropriate model instance based on the `kind` field. """ if data.get('kind') == 'proposal': return Proposal(data) if data.get('kind') == 'vote': return Vote(data) return Post(data)
def save(): if request.method == 'POST': try: imgList = ['1d0', 'aqm', 'ckf', 'asm', '47c', '6mq'] img = random.choice(imgList) valueInput = request.form['valueInput'] vote = Vote(value=int(valueInput), image_id=img) res = RequestsApi.save_api(vote) #print(res) return redirect(url_for('index')) except: return "Not saved"
def click(selected_value, id): if selected_value: votes = Vote(vote=1, option_id=selected_value) db.session.add(votes) db.session.commit() flash(f"You voted successfully!") results = db.session.query(Options.choice, Vote.vote,)\ .filter_by(question_id=id).\ outerjoin(Vote, Options.id == Vote.option_id).all() return render_template('polls/results.html', results=results) return redirect(url_for('detail_view'))
def vote_comment(user=None): payload = request.get_json() comment_id = payload["comment_id"] existing_vote = Vote.query.filter(Vote.comment_id == comment_id, Vote.user_id == user['id']).first() if existing_vote: existing_vote.score = 1 if existing_vote.score == 0 else 0 else: db.session.add(Vote(comment_id=comment_id, user_id=user['id'], score=1)) db.session.commit() return "success"
def test_replies(db_conn, posts_table): """ Expect a vote to require a replies to id. """ vote, errors = Vote.insert({ 'user_id': 'A', 'topic_id': 'B', 'response': True, }) assert len(errors) == 1 vote['replies_to_id'] = 'D' vote, errors = vote.save() assert len(errors) == 0
def post(self): token_string = self.request.get("token") token = Token.query(Token.value == token_string).get() if not token: template = jinja_environment.get_template("templates/error.html") self.response.out.write(template.render({'errmsg': "invalid voting token"})) return if token.used: template = jinja_environment.get_template("templates/error.html") self.response.out.write(template.render({'errmsg': "You've already voted!"})) return game = token.game voter = token.voter three = self.request.get("three") two = self.request.get("two") one = self.request.get("one") if one in [two, three] or two == three: return self.redirect("/vote/" + token.value + "?err=" + str(ERROR_DUPLICATE_VOTE)) if str(voter.id()) in [one, two, three]: return self.redirect("/vote/" + token.value + "?err=" + str(ERROR_VOTE_FOR_SELF)) three_player = Player.get_by_id(int(three)) two_player = Player.get_by_id(int(two)) one_player = Player.get_by_id(int(one)) vote = Vote(game=game, three=three_player.key, two=two_player.key, one=one_player.key) token.used = True vote.put() token.put() template = jinja_environment.get_template('templates/success.html') self.response.out.write(template.render({}))
def test_topic(db_conn, posts_table, units_table): """ Expect a vote to require a topic id. """ create_proposal(posts_table, units_table, db_conn) vote, errors = Vote.insert(db_conn, { 'user_id': 'A', 'replies_to_id': 'D', 'response': True, }) assert len(errors) == 1 vote['topic_id'] = 'B' vote, errors = vote.save(db_conn) assert len(errors) == 0
def test_body(db_conn, posts_table): """ Expect a vote to allow, but not require, a body. """ vote, errors = Vote.insert({ 'user_id': 'A', 'topic_id': 'B', 'replies_to_id': 'D', 'response': True, }) assert len(errors) == 0 vote['body'] = 'A' vote, errors = vote.save() assert len(errors) == 0
def make_vote(vote, mp, commons_division): if vote: vote_type = re.search(r'(?:#)(\w+?)(?:Vote)', vote['type']) vote_type = vote_type.group(1) else: vote_type = 'no_vote' vote = Vote() vote.set_vote_type(vote_type) vote.commons_division = commons_division vote.member_of_parliament = mp return vote
def createQuestionVote(accountId, questionId, value): vote = Vote() vote.AccountId = accountId vote.QuestionId = questionId vote.TimeStamp = datetime.datetime.now() if value is 1: vote.IsUpvote = True else: vote.IsUpvote = False db.session.add(vote) db.session.commit() return vote
def update_entity_status(proposal): """ Update the entity's status based on the vote power received. Move to accepted or blocked if qualified. TODO-2 Update this to work as described in: https://github.com/heiskr/sagefy/wiki/Planning%3A-Contributor-Ratings This requires knowing two things: - Number of learners the entity impacts - The vote and proposal history of the contributor """ # Get the entity version entity_version = get_version(proposal['entity_version']['kind'], proposal['entity_version']['id']) # Make sure the entity version status is not declined or accepted if entity_version['status'] in ('accepted', 'declined'): return # Count the "no" and "yes" vote power no_vote_power = 0 yes_vote_power = 1 # For now, we will assume the proposer is one "yes" vote until # contributor vote power is calculated votes = Vote.list(replies_to_id=proposal['id']) for vote in votes: if vote['response']: yes_vote_power = yes_vote_power + 1 else: no_vote_power = no_vote_power + 1 # If no power is great enough, then block the version if no_vote_power >= 1: entity_version['status'] = 'blocked' entity_version.save() send_notices( entity_id=proposal['entity_version']['id'], entity_kind=proposal['entity_version']['kind'], notice_kind='block_proposal', notice_data={ 'user_name': '???', # TODO-2 'proposal_name': proposal['name'], 'entity_kind': proposal['entity_version']['kind'], 'entity_name': entity_version['name'], } ) # If yes power is great enough, then accept the version if yes_vote_power >= 3: entity_version['status'] = 'accepted' entity_version.save() send_notices( entity_id=proposal['entity_version']['id'], entity_kind=proposal['entity_version']['kind'], notice_kind='accept_proposal', notice_data={ 'proposal_name': proposal['name'], 'entity_kind': proposal['entity_version']['kind'], 'entity_name': entity_version['name'], } )
def _vote(self, vote_pool_id: int): """ Make the vote requests. :param int vote_pool_id: Vote pool ID. """ # Push an app context. app = create_app() app.app_context().push() # We need to create the model again because the same db session cannot # be used from two different threads. vote_pool = VotePool.query.filter(VotePool.id == vote_pool_id).first() # Add this pool to the list of running vote pools. running_vote_pool_ids.append(vote_pool.id) # Get the id of the accounts that already voted on the poll. screen_names = [] duplicated_vote_pools = VotePool.query.\ filter(VotePool.id != vote_pool.id).\ filter(VotePool.tweet_id == vote_pool.tweet_id).all() if duplicated_vote_pools: vote_pool_ids = [vp.id for vp in duplicated_vote_pools] votes = Vote.query.\ filter(Vote.vote_pool_id.in_(vote_pool_ids)).\ filter(Vote.hit == True).all() screen_names = [v.screen_name for v in votes] # Get the accounts that are the most likely to make a successful vote. # Custom order for status column. whens = { Account.STATUS_LOGGED_IN: 1, None: 2, Account.STATUS_UNCONFIRMED_ACCESS: 3, Account.STATUS_UNDETERMINED: 4, Account.STATUS_WRONG_CREDENTIALS: 5, Account.STATUS_SUSPENDED: 6 } status_order = case(value=Account.status, whens=whens) accounts = Account.query.\ filter(Account.screen_name.notin_(screen_names)).\ order_by( status_order, Account.status_updated_at.desc(), Account.id.desc() ).\ limit(vote_pool.max_tries).all() # Try while there are available accounts and the intended hits was not # reached. while accounts and self._hits < vote_pool.intended_hits: # Sleep for a random amount of time if the previos try was a hit. # Error could be undeclared. if 'error' in locals() and not locals()['error']: sleep(random() * 60) # Sleep for a maximum of one minute. account = accounts.pop(0) error = None # Try to vote. try: twitter_login = TwitterLogin(account) twitter_poll = \ TwitterPoll(vote_pool.tweet_id, twitter_login) twitter_poll.vote(vote_pool.option_index) except Exception as e: error = str(e) # Save the result. vote = Vote(vote_pool_id=vote_pool.id, create_datetime=datetime.utcnow(), screen_name=account.screen_name, email=account.email, password=account.password, phone_number=account.phone_number, hit=not error, error=error) db.session.add(vote) db.session.commit() if not error: self._hits += 1 # The vote pool has finished. Update its status. vote_pool.update_status(VotePool.STATUS_FINISHED) # Remove it from the list of running vote pools. running_vote_pool_ids.remove(vote_pool.id)
def vote_post(parent_id, vote_type, parent_type): if check.logged_in(): if (parent_type == 0 or parent_type == 1) and (vote_type == 0 or vote_type == 1): ## parent type = 0 post ## parent type = 1 comment create_vote = False delete_vote = False try: if parent_type == 0: parent = Post(parent_id) user_vote = Vote.get_user_post_vote( session.get("user_id", ""), parent_id) elif parent_type == 1: parent = Comment(parent_id) user_vote = Vote.get_user_comment_vote( session.get("user_id", ""), parent_id) if not user_vote: #User did not vote this post before if (vote_type == 1 ): #If upvote increment the count, else decrement. parent.current_vote += 1 else: parent.current_vote -= 1 parent.save() create_vote = True else: #User voted this post before if user_vote[0].vote: #Previous vote was upvote if vote_type == 0: #User wants to change the vote to downwote parent.current_vote -= 2 user_vote[0].last_update_time = datetime.utcnow() user_vote[0].save() else: parent.current_vote -= 1 #User takes the vote back by clicking twice delete_vote = True #Vote will be delete else: #Previous vote was downvote if vote_type == 0: #Current vote is downvote parent.current_vote += 1 #Vote will be deleted since it was clicked twice delete_vote = True else: parent.current_vote += 2 #User wants to chane the vote to upvote user_vote[0].last_update_time = datetime.utcnow() user_vote[0].save() if delete_vote: user_vote[0].delete() else: user_vote[0].vote = bool(vote_type) user_vote[0].save() parent.save() #New vote gets created and sended as a JSON object if create_vote: vote = Vote() vote.date = datetime.utcnow() vote.is_comment = bool(parent_type) vote.vote = bool(vote_type) vote.vote_ip = request.remote_addr vote.last_update_time = datetime.utcnow() vote.user_id = session.get("user_id", "") vote.post_id = parent_id if parent_type == 0 else None vote.comment_id = parent_id if parent_type == 1 else None vote.save() return jsonify({ 'success': 'Successfuly voted!', 'final_vote': parent.current_vote }) except NotImplementedError as error: return jsonify({'error': str(error)}) return jsonify({'error': 'Invalid vote.'})