If the user has already voted, we cancel her vote, else we create the vote.
TODO : we should distinguish between vote and like (so we should add the like field in post)
973723
public function ajaxVoteAction()
    {
        // Call this for the session lock to be released (other ajax calls can then be made)
        session_write_close();
        $postId = $this->getEvent()->getRouteMatch()->getParam('post');
        $commentId = $this->getEvent()->getRouteMatch()->getParam('comment');
        $request = $this->getRequest();
        $response = $this->getResponse();

        if (! $this->game) {
            $response->setContent(\Zend\Json\Json::encode(array(
                'success' => 0
            )));

            return $response;
        }

        if (!$this->zfcUserAuthentication()->hasIdentity()) {
            $response->setContent(\Zend\Json\Json::encode(array(
                'success' => 0
            )));
        } else {
            if ($request->isPost()) {
                $post = $this->getGameService()->getPostvotePostMapper()->findById($postId);
                $comment = ($commentId !== null) ? $this->getGameService()->getPostVoteCommentMapper()->findById($commentId) : null;
                if ($this->getGameService()->toggleVote(
                    $this->user,
                    $this->getRequest()->getServer('REMOTE_ADDR'),
                    $post,
                    $comment
                )) {
                    $response->setContent(
                        \Zend\Json\Json::encode(['success' => 1])
                    );
                } else {
                    $response->setContent(
                        \Zend\Json\Json::encode(['success' => 0])
                    );
                }
            }
        }

        return $response;
    }
38999
function(event) {
                if(event.preventDefault && event.cancelable)
                    event.preventDefault();
                else
                    event.returnValue = false;
            }
6908
public function ballot($user_id = 0, $ip = null)
	{
		if (User::isGuest())
		{
			$vote = new Vote();
			$vote->set('item_type', 'comment');
			$vote->set('item_id', $this->get('id'));
			$vote->set('created_by', $user_id);
			$vote->set('ip', $ip);

			return $vote;
		}

		$user = $user_id ? User::getInstance($user_id) : User::getInstance();
		$ip   = $ip ?: Request::ip();

		// See if a person from this IP has already voted in the last week
		$votes = $this->votes();

		if ($user->get('id'))
		{
			$votes->whereEquals('created_by', $user->get('id'));
		}
		elseif ($ip)
		{
			$votes->whereEquals('ip', $ip);
		}

		$vote = $votes
			->ordered()
			->limit(1)
			->row();

		if (!$vote || !$vote->get('id'))
		{
			$vote = new Vote();
			$vote->set('item_type', 'comment');
			$vote->set('item_id', $this->get('id'));
			$vote->set('created_by', $user_id);
			if ($ip)
			{
				$vote->set('ip', $ip);
			}
		}

		return $vote;
	}
321288
protected PollResponse handlePoll(PollRequest request) {
    // If the request term is not as great as the current context term then don't
    // vote for the candidate. We want to vote for candidates that are at least
    // as up to date as us.
    if (request.term() < context.getTerm()) {
      LOGGER.debug("{} - Rejected {}: candidate's term is less than the current term", context.getCluster().member().address(), request);
      return PollResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withAccepted(false)
        .build();
    } else if (isLogUpToDate(request.logIndex(), request.logTerm(), request)) {
      return PollResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withAccepted(true)
        .build();
    } else {
      return PollResponse.builder()
        .withStatus(Response.Status.OK)
        .withTerm(context.getTerm())
        .withAccepted(false)
        .build();
    }
  }
437659
public synchronized void storeVote(MemberId vote) {
    log.trace("Store vote {}", vote);
    metadataBuffer.writeString(8, vote != null ? vote.id() : null).flush();
  }
662578
def upvote(self):
        
        data = self.get_selected_item()
        if 'likes' not in data:
            self.term.flash()
        elif getattr(data['object'], 'archived'):
            self.term.show_notification("Voting disabled for archived post", style='Error')
        elif data['likes']:
            with self.term.loader('Clearing vote'):
                data['object'].clear_vote()
            if not self.term.loader.exception:
                data['likes'] = None
        else:
            with self.term.loader('Voting'):
                data['object'].upvote()
            if not self.term.loader.exception:
                data['likes'] = True
434142
public function vote(Request $request)
    {
    	/* Check if user is loged in*/
    	if (!Auth::check()) {
    		return response()->json(['flag' => 0]);
    	}

    	/* Prepare data */
    	$userId = Auth::user()->id;
    	$itemId = $request->item_id;
    	$vote = $request->vote;

    	/* Get item's current like, dislike total */
    	$totalLike = TotalLike::where('item_id', $itemId)->first();

    	/* Get user's vote on this item */
		$like = Like::where(['user_id' => $userId, 'item_id' => $itemId])->first();

		/* Check if users vote on this item exists */
		if ($like != null) {
			if ($like->vote == 1) {	// if previous vote was like
				$totalLike->total_like--;	// decrease item's total like by 1
				$totalLike->total_like = $totalLike->total_like == null ? 0 : $totalLike->total_like;	// set 0 if total like is null
				if ($vote == 1) {	// if current vote is like
					$vote = 0;	// previous vote and current vote is same so discarde vote
				}
			} else if ($like->vote == -1) {	// if previous vote was dislike
				$totalLike->total_dislike--;	// decrease item's total like by 1
				$totalLike->total_dislike = $totalLike->total_dislike == null ? 0 : $totalLike->total_dislike;	// set 0 if total dislike is null
				if ($vote == -1) {	// if current vote is dislike
					$vote = 0;	// previous vote and current vote is same so discarde vote
				}
			}
		} else {
			$like = new Like;	// create new like object if previous vote not exists
		}

		/* Update vote data */
		$like->user_id = $userId;
		$like->item_id = $itemId;
		$like->vote = $vote;

		if ($vote == 1) {
			$totalLike->total_like++;	// increase total like if vote is like
		} else if ($vote == -1) {
			$totalLike->total_dislike++;	// increase total dislike if vote is dislike
		}

		$like->save();		// save like
		$totalLike->save();	//save total like,dislike

    	return response()->json(['flag' => 1, 'vote' => $vote, 'totalLike' => $totalLike->total_like, 'totalDislike' => $totalLike->total_dislike]);
    }
533507
def vote(self, identifier, weight=100.0):
        ''' 
        '''
        for num_of_retries in range(default.max_retry):
            try:
                self.steem_instance().vote(identifier, 
                    weight, self.mainaccount)
                self.msg.message("voted for " + identifier)
                time.sleep(5)
            except Exception as e:
                if re.search(r'You have already voted in a similar way', str(e)):
                    self.msg.error_message('''Already voted on 
                                        {}'''.format(identifier))
                    return "already voted"
                else:
                    self.util.retry('''COULD NOT VOTE ON 
                                    {}'''.format(identifier), 
                                    e, num_of_retries, default.wait_time)
                    self.s = None
            else:
                return True
240369
def upvote
      security_transgression_unless @comment.can_be_voted_on_by?(@user)

      @comment.upvote_from @user

      respond_to do |format|
        format.html { redirect_to @thread }
        format.js { render :vote }
      end
    end
996334
protected VoteResponse handleVote(VoteRequest request) {
    // If the request term is not as great as the current context term then don't
    // vote for the candidate. We want to vote for candidates that are at least
    // as up to date as us.
    if (request.term() < raft.getTerm()) {
      log.debug("Rejected {}: candidate's term is less than the current term", request);
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
    // If a leader was already determined for this term then reject the request.
    else if (raft.getLeader() != null) {
      log.debug("Rejected {}: leader already exists", request);
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
    // If the requesting candidate is not a known member of the cluster (to this
    // node) then don't vote for it. Only vote for candidates that we know about.
    else if (!raft.getCluster().getRemoteMemberStates().stream().map(m -> m.getMember().memberId()).collect(Collectors.toSet()).contains(request.candidate())) {
      log.debug("Rejected {}: candidate is not known to the local member", request);
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
    // If no vote has been cast, check the log and cast a vote if necessary.
    else if (raft.getLastVotedFor() == null) {
      if (isLogUpToDate(request.lastLogIndex(), request.lastLogTerm(), request)) {
        raft.setLastVotedFor(request.candidate());
        return VoteResponse.builder()
            .withStatus(RaftResponse.Status.OK)
            .withTerm(raft.getTerm())
            .withVoted(true)
            .build();
      } else {
        return VoteResponse.builder()
            .withStatus(RaftResponse.Status.OK)
            .withTerm(raft.getTerm())
            .withVoted(false)
            .build();
      }
    }
    // If we already voted for the requesting server, respond successfully.
    else if (raft.getLastVotedFor() == request.candidate()) {
      log.debug("Accepted {}: already voted for {}", request, raft.getCluster().getMember(raft.getLastVotedFor()).memberId());
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(true)
          .build();
    }
    // In this case, we've already voted for someone else.
    else {
      log.debug("Rejected {}: already voted for {}", request, raft.getCluster().getMember(raft.getLastVotedFor()).memberId());
      return VoteResponse.builder()
          .withStatus(RaftResponse.Status.OK)
          .withTerm(raft.getTerm())
          .withVoted(false)
          .build();
    }
  }
262681
public void cancelCancellable() {

        if (timeoutMessageCancellable != null) {
            timeoutMessageCancellable.cancel();
        }
        if (getResponseFuture() != null && !getResponseFuture().isDone()) {
            getResponseFuture().cancel(true);
        }
    }
1049413
public void voteFor(WeightedItem<T> weightedItem) {
        reorganizationCounter++;
        weightedItem.vote();
        if (reorganizationCounter == maxVotesBeforeReorganization) {
            reorganizationCounter = 0;
            organizeAndAdd(null);
        }
    }
1363604
public function voteMinus($post_id)
    {
        $this->checkId($post_id);

        return $this->vote($post_id, self::VOTE_MINUS);
    }
612774
ServerContext setLastVotedFor(int candidate) {
    // If we've already voted for another candidate in this term then the last voted for candidate cannot be overridden.
    Assert.stateNot(lastVotedFor != 0 && candidate != 0L, "Already voted for another candidate");
    ServerMember member = cluster.member(candidate);
    Assert.state(member != null, "unknown candidate: %d", candidate);
    this.lastVotedFor = candidate;
    meta.storeVote(this.lastVotedFor);

    if (candidate != 0) {
      LOGGER.debug("{} - Voted for {}", cluster.member().address(), member.address());
    } else {
      LOGGER.trace("{} - Reset last voted for", cluster.member().address());
    }
    return this;
  }
655837
public void setLastVotedFor(MemberId candidate) {
    // If we've already voted for another candidate in this term then the last voted for candidate cannot be overridden.
    checkState(!(lastVotedFor != null && candidate != null), "Already voted for another candidate");
    DefaultRaftMember member = cluster.getMember(candidate);
    checkState(member != null, "Unknown candidate: %d", candidate);
    this.lastVotedFor = candidate;
    meta.storeVote(this.lastVotedFor);

    if (candidate != null) {
      log.debug("Voted for {}", member.memberId());
    } else {
      log.trace("Reset last voted for");
    }
  }
398996
def cancellable?(options = {})
      @logger.debug("[cancellable?] options=#{options.inspect}")

      validate_required_params!(options, :transaction_id)

      response = execute_request(:status, options)
      response.cancellable?
    end
29186
private final void cancelCancellable() {
        if (timeoutMessageCancellable != null
                && !timeoutMessageCancellable.isCancelled()) {
            timeoutMessageCancellable.cancel();
        }
        if (pollMessageCancellable != null
                && !pollMessageCancellable.isCancelled()) {
            pollMessageCancellable.cancel();
        }
    }