示例#1
0
文件: simu.cpp 项目: COHRINT/cuTORCS
/* After pit stop */
void
SimReConfig(tCarElt *carElt)
{
    tCar *car = &(SimCarTable[carElt->index]);
    if (carElt->pitcmd.fuel > 0) {
		car->fuel += carElt->pitcmd.fuel;
		if (car->fuel > car->tank) car->fuel = car->tank;
    }
    if (carElt->pitcmd.repair > 0) {
		for (int i=0; i<4; i++) {
			carElt->_tyreCondition(i) = 1.01;
			carElt->_tyreT_in(i) = 50.0;
			carElt->_tyreT_mid(i) = 50.0;
			carElt->_tyreT_out(i) = 50.0;
			car->wheel[i].bent_damage_x = urandom();
			car->wheel[i].bent_damage_z = urandom();
			car->wheel[i].rotational_damage_x = 0.0;
			car->wheel[i].rotational_damage_z = 0.0;
			car->wheel[i].susp.damper.efficiency = 1.0;
		}
		
		// (no need to repair wings because effect depends on damage).
		car->dammage -= carElt->pitcmd.repair;
		if (car->dammage < 0) car->dammage = 0;
    }
}
示例#2
0
void
check_random (int argc, char *argv[])
{
  gmp_randstate_ptr  rands = RANDS;
  int            reps = 100;
  mpz_t          a;
  unsigned long  d;
  int            i;

  if (argc == 2)
    reps = atoi (argv[1]);

  mpz_init (a);

  for (i = 0; i < reps; i++)
    {
      /* exponentially within 2 to 257 bits */
      mpz_erandomb (a, rands, urandom () % 8 + 2);

      d = urandom () % 256;

      check_all (a, d);
    }

  mpz_clear (a);
}
示例#3
0
double gaussrand(int *phase, double *pV1, double *pV2, double *pS)
{
	double V1=*pV1, V2=*pV2, S=*pS;
	double X;

	if(*phase == 0) {
		do {
            double U1 = urandom();
			double U2 = urandom();

			V1 = 2 * U1 - 1;
			V2 = 2 * U2 - 1;
			S = V1 * V1 + V2 * V2;
			} while(S >= 1 || S == 0);

		X = V1 * sqrt(-2 * log(S) / S);
	} else
		X = V2 * sqrt(-2 * log(S) / S);

	*phase = 1 - *phase;
    *pV1=V1; *pV2=V2; *pS=S;

	return X;

}
示例#4
0
int spawn_one_mob (struct state *s, int i, int j, int k){
    
  if (s->grid.loc[i][j][k].id_mob != ID_NONE) { return 0; }

  /* location is fine */
  int prio_index = s->prio.num;
  int id = s->mobs.total_num;

  struct mob *m = &s->mobs.mb[id];

  /* setup the mob */
  m->coord.x = i;
  m->coord.y = j;
  m->coord.z = k;

  m->alive = 1;

  m->cl = aggressive;

  m->cond = zombie;

  m->senses.sound = 0;
  m->senses.smell = 0;
  m->senses.sight = 0;

  int outof = 3;
  switch (s->status.level) {
    case 1: outof = 1; break;
    case 2: outof = 2; break; 
    default: outof = 3;

  }
  switch (urandom(outof)) {
    case 0: m->senses.sound = 1; break;  /* oddy */
    case 1: m->senses.smell = 1; break;  /* sniffy */
    default: m->senses.sight = 1;        /* spotty */
  }

  m->hp = 1;

  m->portrait = urandom(3);

  m->vec = random_unit_vec();

  m->dir = dir_of_vec(&m->vec);

  s->grid.loc[i][j][k].id_mob = id;

  /* add the mob to prio */
  s->prio.ap[prio_index] = -0.01 + -2.0 * ((double) urandom(100)) / 100.0;
  s->prio.id[prio_index] = id;

  /* update total mob number */
  s->mobs.total_num = id+1;
  s->prio.num = prio_index+1;

  return 1;
}
示例#5
0
文件: aero.cpp 项目: COHRINT/cuTORCS
void SimAeroDamage(tCar *car, sgVec3 poc, tdble F)
{
    tAero* aero = &car->aero;
    tdble dmg = F*0.0001;

    aero->rot_front[0] += dmg*(urandom()-.5);
    aero->rot_front[1] += dmg*(urandom()-.5);
    aero->rot_front[2] += dmg*(urandom()-.5);
    if (sgLengthVec3(car->aero.rot_front) > 1.0) {
        sgNormaliseVec3 (car->aero.rot_front);
    }
    aero->rot_lateral[0] += dmg*(urandom()-.5);
    aero->rot_lateral[1] += dmg*(urandom()-.5);
    aero->rot_lateral[2] += dmg*(urandom()-.5);
    if (sgLengthVec3(car->aero.rot_lateral) > 1.0) {
        sgNormaliseVec3 (car->aero.rot_lateral);
    }
    aero->rot_vertical[0] += dmg*(urandom()-.5);
    aero->rot_vertical[1] += dmg*(urandom()-.5);
    aero->rot_vertical[2] += dmg*(urandom()-.5);
    if (sgLengthVec3(car->aero.rot_vertical) > 1.0) {
        sgNormaliseVec3 (car->aero.rot_vertical);
    }

    //printf ("aero damage:%f (->%f %f %f)\n", dmg, sgLengthVec3(car->aero.rot_front),
    //			sgLengthVec3(car->aero.rot_lateral), sgLengthVec3(car->aero.rot_vertical));



}
示例#6
0
void spawn_mobs (struct state *s, int num) {
  int id;
  s->mobs.total_num = num;

  int w = s->grid.width;
  int h = s->grid.height;

  for (id=0; id<num; ++id) {
    int i = w/4 + urandom(w/2);
    int j = h/4 + urandom(h/2);
    int k = zlevel(&s->grid, i, j);

    if (s->grid.loc[i][j][k].id_mob != ID_NONE) {continue;}

    struct mob *m = &s->mobs.mb[id];

    m->coord.x = i;
    m->coord.y = j;
    m->coord.z = k;

    m->alive = 1;

    m->cl = aggressive;

    m->cond = zombie;

    m->senses.sound = 0;
    m->senses.smell = 0;
    m->senses.sight = 0;
    switch (urandom(3)) {
      case 0: m->senses.sound = 1; break;
      case 1: m->senses.smell = 1; break;
      default: m->senses.sight = 1;
    }

    m->hp = 1;

    m->portrait = urandom(3);

    m->vec = random_unit_vec();

    m->dir = dir_of_vec(&m->vec);

    s->grid.loc[i][j][k].id_mob = id;

    /* add the mob to prio */
    int index = s->prio.num;
    s->prio.ap[index] = -0.01 + -2.0 * ((double) urandom(100)) / 100.0;
    s->prio.id[index] = id;
    s->prio.num++;
  }
}
示例#7
0
//==========================================================
// ANN_CalculateLayerOutputs()
//----------------------------------------------------------
/// Calculate layer outputs
void ANN_CalculateLayerOutputs(Layer * current_layer, bool stochastic)
{
	int i, j;
	int n_inputs = current_layer->n_inputs;
	int n_outputs = current_layer->n_outputs;
	real *x = current_layer->x;
	real *y = current_layer->y;
	real *z = current_layer->z;
	Connection *c;

	for (j = 0; j < n_outputs; j++) {
		z[j] = 0.0f;
	}
	c = current_layer->c;
	if (stochastic) {
		for (i = 0; i < n_inputs; i++) {
			for (j = 0; j < n_outputs; j++) {
				// using uniform bounded.. 
				real w = c->w + (urandom()-0.5f)*c->v ;
				z[j] += x[i] * w;
				c++;
			}
		}
		
		// bias
		for (j = 0; j < n_outputs; j++) {
			real w = c->w + (urandom()-0.5f)*c->v ;
			z[j] += w;
			c++;
		}
	} else {
		for (i = 0; i < n_inputs; i++) {
			for (j = 0; j < n_outputs; j++) {
				z[j] += x[i] * c->w;
				c++;
			}
		}
		
		// bias
		for (j = 0; j < n_outputs; j++) {
			z[j] += c->w;
			c++;
		}
	}
	
	for (j = 0; j < n_outputs; j++) {
		y[j] = current_layer->f(z[j]);
	}
}
NonDeterministicRandomData::NonDeterministicRandomData(int s)
{
#ifndef Q_OS_WIN
    {
        // Try urandom for UNIX platforms.
        QFile urandom("/dev/urandom");

        if (urandom.exists() && urandom.open(QIODevice::ReadOnly))
        {
            resize(s);

            if (urandom.read(data(), s) == s)
            {
                return;
            }
        }
    }
#endif

    /* Fallback, mostly for Windows, where UUID generation is supposed to be very good. */
    if (isEmpty())
    {
        reserve(s);

        while (size() < s)
        {
            append(QByteArray::fromHex(QUuid::createUuid().toString().remove('{').remove('}').remove('-').toLatin1()));
        }

        resize(s);
    }

#if 0
    /**
     * Implementation with boost::random_device.
     * Works on Windows only starting with boost 1.43,
     * before, only urandom is supported, but for that,
     * we have a easy code snippet already.
     */
    const int stepSize = sizeof(boost::random_device::result_type);
    int steps          = s / stepSize;

    if (s % stepSize)
    {
        ++steps;
    }

    resize(steps * stepSize);

    boost::random_device device;
    boost::random_device::result_type* ptr = reinterpret_cast<boost::random_device::result_type*>(data());

    for (int i = 0; i < stepSize; ++i)
    {
        *ptr++ = device();
    }

    resize(s);
#endif
}
示例#9
0
// ---------- action selection helpers -------------
int DiscretePolicy::confMax(real* Qs, real* vQs, real p) {
    real sum=0.0;
    int a;
#if 0
    for (a=0; a<n_actions; a++) {
        eval[a] = exp(pow(Qs[a]/sqrt(vQs[a]), p));
        sum += eval[a];
    }
#else
    for (a=0; a<n_actions; a++) {
        real Q = Qs[a];
        real cum = 1.0;
        //real v = sqrt(vQs[a]);
        for (int j=0; j<n_actions; j++) {
            if (j!=a) {
                cum += exp ((Qs[j]-Q)/sqrt(vQs[j]));
            }
        }
        eval[a] = 1.0f/(cum);//#exp(Qs[a]/sqrt(vQs[a]));
        sum += eval[a];
    }
#endif
    real X = urandom()*sum;
    real dsum = 0.0;
    for (a=0; a<n_actions; a++) {
        dsum += eval[a];
        if (X<=dsum)
            return a;

    }
    fprintf (stderr, "ConfMax: No action selected! %f %f %f\n",X,dsum,sum);
    return -1;
}
示例#10
0
文件: test.cpp 项目: pank7/pank7-test
int
main(int argc, char *argv[])
{
    constexpr int               c = get_size(false);
    std::array<int, c>          a;
    time_t                      seed = time(NULL);
    std::ifstream               urandom("/dev/urandom", std::fstream::in | std::fstream::binary);

    if (urandom.is_open()) {
        urandom.read(reinterpret_cast<char *>(&seed), sizeof(seed));
        std::cout << "Seed: " << seed << std::endl;
    }

    std::uniform_int_distribution<int>  u(0, 1000);
    std::default_random_engine  re(seed);

    for (auto &e : a) {
        e = u(re);
        std::cout << e << " ";
    }
    std::cout << std::endl;

    std::cout << "selection(a, 7) = "
              << *selection(a, 7)
              << std::endl;

    return 0;
}
示例#11
0
int
stressSQL_rep1(NDBT_Context* ctx, NDBT_Step* step)
{
  BaseString sqlStm;

  DbUtil master("TEST_DB");
  int loops = ctx->getNumLoops();
  uint record = 0;

  //Login to Master
  if (!master.connect())
  {
    ctx->stopTest();
    return NDBT_FAILED;
  }

  for (int j= 0; loops == 0 || j < loops; j++)
  {
    record = urandom(ctx->getNumRecords());
    sqlStm.assfmt("UPDATE TEST_DB.rep1 SET c2 = 33.3221 where c1 =  %u", record);
    if(!master.doQuery(sqlStm.c_str()))
    {
      return NDBT_FAILED;
    }
  }
  ctx->stopTest();
  return NDBT_OK;
}
示例#12
0
int random_vector(unsigned int seed, int code, DVEC(r)) {
    struct random_data buffer;
    char   random_state[128];
    memset(&buffer, 0, sizeof(struct random_data));
    memset(random_state, 0, sizeof(random_state));

    initstate_r(seed,random_state,sizeof(random_state),&buffer);
    // setstate_r(random_state,&buffer);
    // srandom_r(seed,&buffer);

    int phase = 0;
    double V1,V2,S;

    int k;
    switch (code) {
      case 0: { // uniform
        for (k=0; k<rn; k++) {
            rp[k] = urandom(&buffer);
        }
        OK
      }
      case 1: { // gaussian
        for (k=0; k<rn; k++) {
            rp[k] = gaussrand(&buffer,&phase,&V1,&V2,&S);
        }
        OK
      }

      default: ERROR(BAD_CODE);
    }
}
示例#13
0
void initPRNG()
{
  bool seedsuccess = false;

#ifdef WIN32
  HCRYPTPROV hCryptProv;
  BYTE* pbData = reinterpret_cast<BYTE*>(&prng_seed);

  if (CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0))
  {
    if (CryptGenRandom(hCryptProv, sizeof(prng_seed), pbData))
    {
      seedsuccess = true;
    }
    CryptReleaseContext(hCryptProv, 0);
  }
#else
  std::ifstream urandom("/dev/urandom");
  if (urandom)
  {
    urandom.read(reinterpret_cast<char*>(&prng_seed), sizeof(prng_seed));
    seedsuccess = true;
  }
#endif

  if (!seedsuccess)
  {
    prng_seed = static_cast<seed_type>(std::time(NULL));
  }

  //std::cout << "Seeding the PRNG with: 0x" << std::hex << std::uppercase << std::setfill('0')
  //          << std::setw(2 * sizeof(MyRNG::result_type)) << prng_seed << std::endl;

  prng.seed(prng_seed);
}
示例#14
0
// Taken from numerical recipes in C
real NormalDistribution::generate()
{
	if(!cache) {
		normal_x = urandom();
		normal_y = urandom();
		normal_rho = sqrt(-2.0f * log(1.0f - normal_y));
		cache = true;
	} else {
		cache = false;
	}
	
	if (cache) {
		return normal_rho * cos(2.0f * PI * normal_x) * s + m;
	} else {
		return normal_rho * sin(2.0f * PI * normal_x) * s + m;	
	}
}
示例#15
0
static uint
urandom(uint m)
{
  if (m == 0)
    return NDBT_OK;
  uint r = urandom();
  r = r % m;
  return r;
}
示例#16
0
static int
runCreateIndex(NDBT_Context* ctx, NDBT_Step* step)
{
  srandom(1);
  NDBT_Table* pTab = ctx->getTab();
  Ndb* pNdb = GETNDB(step);
  unsigned numTabAttrs = pTab->getNumAttributes();
  unsigned numIndex = 0;
  while (numIndex < MaxIndexes) {
    if (numIndex != 0 && urandom(10) == 0)
      break;
    char buf[200];
    sprintf(buf, "%s_X%03d", pTab->getName(), numIndex);
    NDBT_Index* pInd = new NDBT_Index(buf);
    pInd->setTable(pTab->getName());
    pInd->setType(NdbDictionary::Index::OrderedIndex);
    pInd->setLogging(false);
    unsigned numAttrs = 0;
    while (numAttrs < MaxIndexAttrs) {
      if (numAttrs != 0 && urandom(5) == 0)
	break;
      unsigned i = urandom(numTabAttrs);
      const NDBT_Attribute* pAttr = pTab->getAttribute(i);
      bool found = false;
      for (unsigned j = 0; j < numAttrs; j++) {
	if (strcmp(pAttr->getName(), pInd->getAttribute(j)->getName()) == 0) {
	  found = true;
	  break;
	}
      }
      if (found)
	continue;
      pInd->addAttribute(*pAttr);
      numAttrs++;
    }
    g_info << "Create index:" << endl << *pInd;
    if (pInd->createIndexInDb(pNdb, false) != 0)
      continue;
    numIndex++;
  }
  setTableProperty(ctx, pTab, "numIndex", numIndex);
  g_info << "Created " << numIndex << " indexes on " << pTab->getName() << endl;
  return NDBT_OK;
}
示例#17
0
void
check_random (int argc, char *argv[])
{
  gmp_randstate_ptr rands = RANDS;
  mpz_t   a, c, d, ra, rc;
  int     i;
  int     want;
  int     reps = 50000;

  if (argc >= 2)
    reps = atoi (argv[1]);

  mpz_init (a);
  mpz_init (c);
  mpz_init (d);
  mpz_init (ra);
  mpz_init (rc);

  for (i = 0; i < reps; i++)
    {
      mpz_errandomb (a, rands, 8*BITS_PER_MP_LIMB);
      MPZ_CHECK_FORMAT (a);
      mpz_errandomb (c, rands, 8*BITS_PER_MP_LIMB);
      MPZ_CHECK_FORMAT (c);
      mpz_errandomb_nonzero (d, rands, 8*BITS_PER_MP_LIMB);

      mpz_negrandom (a, rands);
      MPZ_CHECK_FORMAT (a);
      mpz_negrandom (c, rands);
      MPZ_CHECK_FORMAT (c);
      mpz_negrandom (d, rands);

      mpz_fdiv_r (ra, a, d);
      mpz_fdiv_r (rc, c, d);

      want = (mpz_cmp (ra, rc) == 0);
      check_one (a, c, d, want);

      mpz_sub (ra, ra, rc);
      mpz_sub (a, a, ra);
      MPZ_CHECK_FORMAT (a);
      check_one (a, c, d, 1);

      if (! mpz_pow2abs_p (d))
        {
          refmpz_combit (a, urandom() % (8*BITS_PER_MP_LIMB));
          check_one (a, c, d, 0);
        }
    }

  mpz_clear (a);
  mpz_clear (c);
  mpz_clear (d);
  mpz_clear (ra);
  mpz_clear (rc);
}
示例#18
0
static Uint32
random_coprime(Uint32 n)
{
  Uint32 prime[] = { 101, 211, 307, 401, 503, 601, 701, 809, 907 };
  Uint32 count = sizeof(prime) / sizeof(prime[0]);
  assert(n != 0);
  while (1) {
    Uint32 i = urandom(count);
    if (n % prime[i] != 0)
      return prime[i];
  }
}
示例#19
0
int get_random_seed() {
	int seedtmp;
	ifstream urandom("/dev/urandom", ios::binary);
	if(urandom.bad()) {
		cerr<<"/dev/urandom gives bad stream, falling back to time + getpid + number_of_instances"<<endl;
		seedtmp = time(NULL) + getpid();
	} else {
		urandom.read(reinterpret_cast<char*>(&seedtmp),sizeof(seedtmp));
		urandom.close();
	}
	return seedtmp;
}
示例#20
0
real DiscreteDistribution::generate()
{
	real d=urandom();
	real sum = 0.0;
	for (int i=0; i<n_outcomes; i++) {
		sum += p[i];
		if (d < sum) {
			return (real) i;
		}
	}
	return 0.0;
}
示例#21
0
int DiscretePolicy::eGreedy(real* Qs) {
    real X = urandom();
    int amax = argMax(Qs);
    real base_prob = temp/((real) n_actions);
    for (int a=0; a<n_actions; a++) {
        eval[a] = base_prob;
    }
    eval[amax] += 1.0f-temp;
    if (X<temp) {
        return rand()%n_actions;
    }
    return argMax(Qs);
}
示例#22
0
void
check_rand (void)
{
  gmp_randstate_t  rands;
  unsigned long  got, want;
  int    i;
  mpz_t  x, y;

  mpz_init (x);
  mpz_init (y);
  gmp_randinit_default(rands);

  for (i = 0; i < 2000; i++)
    {
      mpz_erandomb (x, rands, 6 * GMP_NUMB_BITS);
      mpz_negrandom (x, rands);
      mpz_mul_2exp (x, x, urandom(rands) % (4 * GMP_NUMB_BITS));

      mpz_erandomb (y, rands, 6 * GMP_NUMB_BITS);
      mpz_negrandom (y, rands);
      mpz_mul_2exp (y, y, urandom(rands) % (4 * GMP_NUMB_BITS));

      want = refmpz_hamdist (x, y);
      got = mpz_hamdist (x, y);
      if (got != want)
        {
          printf    ("mpz_hamdist wrong on random\n");
          printf    ("  got  %lu\n", got);
          printf    ("  want %lu\n", want);
          mpz_trace ("  x   ", x);
          mpz_trace ("  y   ", y);
          abort();
        }
    }
  mpz_clear (x);
  mpz_clear (y);
  gmp_randclear(rands);
}
示例#23
0
real LaplacianDistribution::generate()
{
	real x = urandom(-1.0, 1.0);
	real absx = fabs (x);
	real sgnx;
	if (x>0.0) {
		sgnx = 1.0;
	} else {
		sgnx = -1.0;
	}
	
	return m + sgnx * log(1.0f - absx) / l;

}
示例#24
0
void find_where_to_start (struct state *s, int *x, int *y, int *z){
  int found = 0;
  int w = s->grid.width;
  int h = s->grid.height;
  
  int i, j, k;

  int margin = MIN(w/7,h/7) + 1;

  while (!found){
    /* pick coordinates */
    i = margin + urandom(w - 2*margin);
    j = margin + urandom(h - 2*margin);
    
    k = zlevel(&s->grid, i, j);
  
    if (is_good_to_start(s,i,j,k)) {
      *x = i;
      *y = j;
      *z = k;
      return;
    }
  }
}
示例#25
0
文件: t-sub.c 项目: BrianGladman/mpir
void
check_random (void)
{
  mp_limb_t  want_dh,want_dl, got_dh,got_dl, mh,ml, sh,sl;
  int  i;
  gmp_randstate_t rands;
  
  gmp_randinit_default(rands);

  for (i = 0; i < 20; i++)
    {
      mh = urandom (rands);
      ml = urandom (rands);
      sh = urandom (rands);
      sl = urandom (rands);

      refmpn_sub_ddmmss (&want_dh,&want_dl, mh,ml, sh,sl);

      sub_ddmmss (got_dh,got_dl, mh,ml, sh,sl);

      if (got_dh != want_dh || got_dl != want_dl)
        {
          printf ("check_data wrong at data[%d]\n", i);
          mp_limb_trace ("  mh", mh);
          mp_limb_trace ("  ml", ml);
          mp_limb_trace ("  sh", sh);
          mp_limb_trace ("  sl", sl);
          mp_limb_trace ("  want dh", want_dh);
          mp_limb_trace ("  want dl", want_dl);
          mp_limb_trace ("  got dh ", got_dh);
          mp_limb_trace ("  got dl ", got_dl);
          abort ();
        }
    }
    gmp_randclear(rands);
}
void
check_random (int argc, char *argv[])
{
  gmp_randstate_ptr rands = RANDS;
  int    reps = 5000;
  mpz_t  a, q, got;
  int    i, qneg;
  unsigned long  d;

  if (argc == 2)
    reps = atoi (argv[1]);

  mpz_init (a);
  mpz_init (q);
  mpz_init (got);

  for (i = 0; i < reps; i++)
    {
      d = (unsigned long) urandom();
      mpz_erandomb (q, rands, 512);
      mpz_mul_ui (a, q, d);

      for (qneg = 0; qneg <= 1; qneg++)
        {
          mpz_divexact_ui (got, a, d);
          MPZ_CHECK_FORMAT (got);
          if (mpz_cmp (got, q) != 0)
            {
              printf    ("mpz_divexact_ui wrong\n");
              mpz_trace ("    a", a);
              printf    ("    d=%lu\n", d);
              mpz_trace ("    q", q);
              mpz_trace ("  got", got);
              abort ();
            }

          mpz_neg (q, q);
          mpz_neg (a, a);
        }

    }

  mpz_clear (a);
  mpz_clear (q);
  mpz_clear (got);
}
示例#27
0
int DiscretePolicy::softMax(real* Qs) {
    real sum=0.0f;
    real beta = 1.0f/temp;
    int a;
    for (a=0; a<n_actions; a++) {
        eval[a] = exp(beta * Qs[a]);
        sum += eval[a];
    }
    real X = urandom()*sum;
    real dsum = 0.0;
    for (a=0; a<n_actions; a++) {
        dsum += eval[a];
        if (X<=dsum)
            return a;

    }
    fprintf (stderr, "softMax: No action selected! %f %f %f\nT:%f\n",X,dsum,sum,temp);
    return -1;
}
示例#28
0
文件: ip.c 项目: zidier215/tcpip
/* Execute random quench algorithm on an interface's output queue */
void
rquench(
struct iface *ifp,
int drop
){
	struct mbuf *bp,*bplast;
	int i;
	struct qhdr qhdr;
	struct ip ip;
	struct mbuf *bpdup;

	if((i = len_q(ifp->outq)) == 0)
		return;	/* Queue is empty */

	i = urandom(i);	/* Select a victim */

	/* Search for i-th message on queue */
	bplast = NULL;
	for(bp = ifp->outq;bp != NULL && i>0;i--,bplast=bp,bp=bp->anext)
		;
	if(bp == NULL)
		return;	/* "Can't happen" */

	/* Send a source quench */
	dup_p(&bpdup,bp,0,len_p(bp));
	pullup(&bpdup,&qhdr,sizeof(qhdr));
	ntohip(&ip,&bpdup);
	icmp_output(&ip,bpdup,ICMP_QUENCH,0,NULL);
	free_p(&bpdup);
	if(!drop)
		return;	/* All done */

	/* Drop the packet */
	if(bplast != NULL)
		bplast->anext = bp->anext;
	else
		ifp->outq = bp->anext;	/* First on list */
	free_p(&bp);
}
示例#29
0
int dir_of_vec(struct vec *v) {
  double x = v->x;
  double y = v->y;
  const double z = 0.9239;
  const double mz = -0.9239; 
  double len = vec_norm(v);
  
  int d = urandom(8);
  
  if (len > 0.0001) {
    x = x/len;
    y = y/len;
    {
    if (x > z) 
      d = 0; // E 
    else if (x < mz)
      d = 4; // W
    else if (y > z) 
      d = 2; // N 
    else if (y < mz)
      d = 6; // S
    else if (x > 0.0) {
      if (y > 0.0) 
        d = 1; // NE 
      else 
        d = 7; // SE
    }
    else {
      if (y > 0.0)
        d = 3; // NW 
      else 
        d = 5; // SW
    }
    }
  }

  return d;
}
示例#30
0
// ext4enc:TODO this can't be the only place keys are read from /dev/urandom
// we should unite those places.
static std::string e4crypt_get_key(
    const std::string &key_path,
    bool create_if_absent)
{
    std::string content;
    if (android::base::ReadFileToString(key_path, &content)) {
        if (content.size() != key_length/8) {
            SLOGE("Wrong size key %zu in  %s", content.size(), key_path.c_str());
            return "";
        }
        return content;
    }
    if (!create_if_absent) {
        SLOGE("No key found in %s", key_path.c_str());
        return "";
    }
    std::ifstream urandom("/dev/urandom");
    if (!urandom) {
        SLOGE("Unable to open /dev/urandom (%s)", strerror(errno));
        return "";
    }
    char key_bytes[key_length / 8];
    errno = 0;
    urandom.read(key_bytes, sizeof(key_bytes));
    if (!urandom) {
        SLOGE("Unable to read key from /dev/urandom (%s)", strerror(errno));
        return "";
    }
    std::string key(key_bytes, sizeof(key_bytes));
    if (!android::base::WriteStringToFile(key, key_path)) {
        SLOGE("Unable to write key to %s (%s)",
                key_path.c_str(), strerror(errno));
        return "";
    }
    return key;
}