int main() {
  int a[] = {3, 2, 3, 1, 3};
  assert(*majority(a, a + 5) == 3);
  int b[] = {2, 3, 3, 3, 2, 1};
  assert(majority(b, b + 6) == b + 6);
  return 0;
}
Example #2
0
	int majority(vector<int>& nums, int left, int right)
	{
		if(left == right) return nums[left];
		int mid = left + ((right - left)>>1);
		int lm = majority(nums,left,mid);
		int rm = majority(nums,mid+1,right);
		if(lm == rm) return lm;
		return return count(nums.begin() + left, nums.begin() + right + 1, lm) > count(nums.begin() + left, nums.begin() + right + 1, rm) ? lm : rm;
	}
Example #3
0
/**
 * proposer_ack_reject - Acknowledge an acceptor's reject.
 *
 * Increment the reject count of the appropriate Paxos instance.  If we have
 * a majority of rejects, try to reconnect to the acceptor we attempted to
 * force part.  If we are successful, re-decree null; otherwise, try the part
 * again.
 */
int
proposer_ack_reject(struct paxos_header *hdr)
{
  int r;
  struct paxos_instance *inst;
  struct paxos_acceptor *acc;
  struct paxos_continuation *k;

  // Our prepare succeeded, so we have only one possible ballot in our
  // lifetime in the system.
  assert(ballot_compare(hdr->ph_ballot, pax->ballot) == 0);

  // Find the decree of the correct instance and increment the reject count.
  inst = instance_find(&pax->ilist, hdr->ph_inum);
  inst->pi_rejects++;

  // Ignore the vote if we've already committed.
  if (inst->pi_committed) {
    return 0;
  }

  // We only reject parts.  However, we may continue to receive rejects even
  // after a majority rejects, in which case we may have re-decreed null.
  if (inst->pi_val.pv_dkind == DEC_NULL) {
    return 0;
  }
  assert(inst->pi_val.pv_dkind == DEC_PART);

  // If we have been rejected by a majority, attempt reconnection.
  if (DEATH_ADJUSTED(inst->pi_rejects) >= majority()) {
    // See if we can reconnect to the acceptor we tried to part.
    acc = acceptor_find(&pax->alist, inst->pi_val.pv_extra);
    assert(acc->pa_peer == NULL);

    // Defer computation until the client performs connection.  If it succeeds,
    // replace the part decree with a null decree; otherwise, just redecree
    // the part.  We bind the instance number of the decree as callback data.
    k = continuation_new(continue_ack_reject, acc->pa_paxid);
    k->pk_data.inum = inst->pi_hdr.ph_inum;
    ERR_RET(r, state.connect(acc->pa_desc, acc->pa_size, &k->pk_cb));
    return 0;
  }

  // If we have heard back from everyone but the accepts and rejects are tied,
  // just decree the part again.
  if (inst->pi_votes < majority() &&
      DEATH_ADJUSTED(inst->pi_rejects) < majority() &&
      inst->pi_votes + inst->pi_rejects == pax->live_count) {
    return paxos_broadcast_instance(inst);
  }

  return 0;
}
Example #4
0
int main(void)
{
	char b;
	int cnt = 0;
	
	printf("\n%5s%5s%5s%5s%5s%5s%7s%7s%11s\n\n",
			"Cnt", "b1", "b2", "b3", "b4", "b5",
			"fct1", "fct2", "majority");
	
	for (b = 0; b < 32; ++b) {
		printf("%5d%5d%5d%5d%5d%5d%6d%7d%9d\n",
			   ++cnt, b_val(5, b), b_val(4, b), b_val(3, b), b_val(2, b), b_val(1, b),
			   fct1(b), fct2(b), majority(b));
	}
	putchar('\n');
	return 0;					
}
SessionCatalogMigrationSource::SessionCatalogMigrationSource(OperationContext* opCtx,
                                                             NamespaceString ns)
    : _ns(std::move(ns)), _rollbackIdAtInit(repl::ReplicationProcess::get(opCtx)->getRollbackID()) {
    // Exclude entries for transaction.
    Query query;
    // Sort is not needed for correctness. This is just for making it easier to write deterministic
    // tests.
    query.sort(BSON("_id" << 1));

    DBDirectClient client(opCtx);
    auto cursor = client.query(NamespaceString::kSessionTransactionsTableNamespace, query);

    while (cursor->more()) {
        auto nextSession = SessionTxnRecord::parse(
            IDLParserErrorContext("Session migration cloning"), cursor->next());
        if (!nextSession.getLastWriteOpTime().isNull()) {
            _sessionOplogIterators.push_back(
                stdx::make_unique<SessionOplogIterator>(std::move(nextSession), _rollbackIdAtInit));
        }
    }

    {
        AutoGetCollection autoColl(opCtx, NamespaceString::kRsOplogNamespace, MODE_IX);
        writeConflictRetry(
            opCtx,
            "session migration initialization majority commit barrier",
            NamespaceString::kRsOplogNamespace.ns(),
            [&] {
                const auto message = BSON("sessionMigrateCloneStart" << _ns.ns());

                WriteUnitOfWork wuow(opCtx);
                opCtx->getClient()->getServiceContext()->getOpObserver()->onInternalOpMessage(
                    opCtx, _ns, {}, {}, message);
                wuow.commit();
            });
    }

    auto opTimeToWait = repl::ReplClientInfo::forClient(opCtx->getClient()).getLastOp();
    WriteConcernResult result;
    WriteConcernOptions majority(
        WriteConcernOptions::kMajority, WriteConcernOptions::SyncMode::UNSET, 0);
    uassertStatusOK(waitForWriteConcern(opCtx, opTimeToWait, majority, &result));
}
Example #6
0
int KnnClassifier::query(const Sample& sample) {
	return majority(query(sample, k));
}
Example #7
0
/**
 * proposer_ack_redirect - Resolve an acceptor's claim that we are not the
 * true proposer.
 *
 * If we send a prepare to an acceptor who does not believe us to be the
 * true proposer, the acceptor will respond with a redirect.  Since the
 * correctness of Paxos guarantees that the acceptor list has a consistent
 * total ordering, receiving a redirect means that there is someone more
 * fitting to be proposer who we have lost contact with.
 *
 * Note that this does not necessarily mean that the identified proposer is
 * still live; it is possible that we noticed a proposer failure and then
 * prepared before the acceptor who sent the redirect detected the failure.
 * To avoid this as much as possible, we wait for a majority of redirects
 * before accepting defeat and attempting reconnection to our superior.  If
 * we "win" with a majority completing the prepare, then we drop the former
 * proposer regardless of whether he has some connections still open.
 */
int
proposer_ack_redirect(struct paxos_header *hdr, msgpack_object *o)
{
  int r;
  struct paxos_header orig_hdr;
  struct paxos_acceptor *acc;
  struct paxos_continuation *k;

  // We dispatched as the proposer, so we do not need to check again whether
  // we think ourselves to be the proposer.  Instead, just sanity check that
  // the supposed true proposer has a lower ID than we do.  This should
  // always be the case because of the consistency of proposer ranks.
  assert(hdr->ph_inum < pax->self_id);

  // If we are not still preparing, either we succeeded or our prepare was
  // rejected.  In the former case, we should ignore the redirect because
  // we have affirmed our proposership with a majority vote.  In the latter
  // case, if we connected to the true proposer, we would have dispatched
  // as an acceptor; and if we did not successfully connect, we would have
  // sent out another prepare.  Hence, if we are not preparing, our prepare
  // succeeded and hence we should ignore the redirect.
  if (pax->prep == NULL) {
    return 0;
  }

  // Ensure that the redirect is for our current prepare; otherwise ignore.
  paxos_header_unpack(&orig_hdr, o);
  if (ballot_compare(orig_hdr.ph_ballot, pax->prep->pp_ballot) != 0) {
    return 0;
  }

  // Acknowledge the rejection of our prepare.
  pax->prep->pp_redirects++;

  // If we have been redirected by a majority, attempt reconnection.  If a
  // majority redirects, our prepare will never succeed, but we defer freeing
  // it until reconnection occurs.  This provides us with the guarantee (used
  // above) that an acceptor who identifies as the proposer and whose prepare
  // is non-NULL has either successfully prepared or has not yet begun its
  // prepare cycle.
  if (DEATH_ADJUSTED(pax->prep->pp_redirects) >= majority()) {
    // Connect to the higher-ranked acceptor indicated in the most recent
    // redirect message we received (i.e., this one).  It's possible that an
    // even higher-ranked acceptor exists, but we'll find that out when we
    // try to send a request.
    acc = acceptor_find(&pax->alist, hdr->ph_inum);
    assert(acc->pa_peer == NULL);

    // Defer computation until the client performs connection.  If it succeeds,
    // give up the prepare; otherwise, reprepare.
    k = continuation_new(continue_ack_redirect, acc->pa_paxid);
    ERR_RET(r, state.connect(acc->pa_desc, acc->pa_size, &k->pk_cb));
    return 0;
  }

  // If we have heard back from everyone but the acks and redirects are tied,
  // just prepare again.
  if (pax->prep->pp_acks < majority() &&
      DEATH_ADJUSTED(pax->prep->pp_redirects) < majority() &&
      pax->prep->pp_acks + pax->prep->pp_redirects == pax->live_count) {
    g_free(pax->prep);
    pax->prep = NULL;
    return proposer_prepare(NULL);
  }

  return 0;
}
Example #8
0
 int majorityElement(vector<int>& nums) {
     return majority(nums, 0, nums.size() - 1);
 }
Example #9
0
/* compute a path in the given pixmap, separating black from white.
   Start path at the point (x0,x1), which must be an upper left corner
   of the path. Also compute the area enclosed by the path. Return a
   new path_t object, or NULL on error (note that a legitimate path
   cannot have length 0). Sign is required for correct interpretation
   of turnpolicies. */
static path_t *findpath(potrace_bitmap_t *bm, int x0, int y0, int sign, int turnpolicy) {
  int x, y, dirx, diry, len, size, area;
  int c, d, tmp;
  point_t *pt, *pt1;
  path_t *p = NULL;

  x = x0;
  y = y0;
  dirx = 0;
  diry = -1;

  len = size = 0;
  pt = NULL;
  area = 0;
  
  while (1) {
    /* add point to path */
    if (len>=size) {
      size += 100;
      size = (int)(1.3 * size);
      pt1 = (point_t *)realloc(pt, size * sizeof(point_t));
      if (!pt1) {
	goto error;
      }
      pt = pt1;
    }
    pt[len].x = x;
    pt[len].y = y;
    len++;
    
    /* move to next point */
    x += dirx;
    y += diry;
    area += x*diry;
    
    /* path complete? */
    if (x==x0 && y==y0) {
      break;
    }
    
    /* determine next direction */
    c = BM_GET(bm, x + (dirx+diry-1)/2, y + (diry-dirx-1)/2);
    d = BM_GET(bm, x + (dirx-diry-1)/2, y + (diry+dirx-1)/2);
    
    if (c && !d) {               /* ambiguous turn */
      if (turnpolicy == POTRACE_TURNPOLICY_RIGHT
	  || (turnpolicy == POTRACE_TURNPOLICY_BLACK && sign == '+')
	  || (turnpolicy == POTRACE_TURNPOLICY_WHITE && sign == '-')
	  || (turnpolicy == POTRACE_TURNPOLICY_RANDOM && detrand(x,y))
	  || (turnpolicy == POTRACE_TURNPOLICY_MAJORITY && majority(bm, x, y))
	  || (turnpolicy == POTRACE_TURNPOLICY_MINORITY && !majority(bm, x, y))) {
	tmp = dirx;              /* right turn */
	dirx = diry;
	diry = -tmp;
      } else {
	tmp = dirx;              /* left turn */
	dirx = -diry;
	diry = tmp;
      }
    } else if (c) {              /* right turn */
      tmp = dirx;
      dirx = diry;
      diry = -tmp;
    } else if (!d) {             /* left turn */
      tmp = dirx;
      dirx = -diry;
      diry = tmp;
    }
  } /* while this path */

  /* allocate new path object */
  p = path_new();
  if (!p) {
    goto error;
  }

  p->priv->pt = pt;
  p->priv->len = len;
  p->area = area;
  p->sign = sign;

  return p;
 
 error:
   free(pt);
   return NULL; 
}