示例#1
0
void CharacterNetwork::RandomizeVariables(void)
{
    printf("Character %llu--------RandomizeVariables\n", GetNetworkID());
    if (randomMT()%2)
    {
        _x = randomMT();
        printf("x changed to %5.2f\n", _x);
    }
    if (randomMT()%2)
    {
        _y = randomMT();
        printf("y changed to %5.2f\n", _y);
    }
    if (randomMT()%2)
    {
        _velocityX = randomMT();
        printf("_velocityX changed to %5.2f\n", _velocityX);
    }
    if (randomMT()%2)
    {
        _velocityY = randomMT();
        printf("_velocityX changed to %5.2f\n", _velocityY);
    }
    if (randomMT()%2)
    {
        _state = randomMT();
        printf("_state changed to %i\n", _state);
    }
    
    // write history
    transformationHistory.Write(_x, _y, _velocityX, _velocityY, _state, RakNet::GetTimeMS());
}
示例#2
0
static PyObject *sendAuthChallenge(PyObject *self, PyObject *args)
{
	//cn, domain, reqid, publicKey
	//return answer to challenge
	int cn;
	char *domain;
	uint id;
	char *publicKey;
	server::clientinfo *ci;
	if(!PyArg_ParseTuple(args, "isIs", &cn, &domain, &id, &publicKey))
		return 0;
	ci = server::getinfo(cn);
	if(!ci)
	{
		PyErr_SetString(PyExc_ValueError, "Invalid cn specified");
		return 0;
	}

    uint seed[3] = { randomMT(), randomMT(), randomMT() };
    vector<char> challengeBuf;
    vector<char> answerBuf;
    void *parsedKey = parsepubkey(publicKey);
    genchallengestr(parsedKey, seed, sizeof(seed), challengeBuf, answerBuf);

    freepubkey(parsedKey);
    sendf(ci->clientnum, 1, "risis", N_AUTHCHAL, domain, id, challengeBuf.getbuf());

    return Py_BuildValue("s", answerBuf.getbuf());
}
示例#3
0
static void
sample_cosweight(ri_vector_t *outdir, const ri_vector_t normal)
{
	int   i;
	double r[2];
	double cost, sint, phi;
	ri_vector_t v;
	ri_vector_t basis[3];

	ri_ortho_basis(basis, normal);

	r[0] = randomMT();
	r[1] = randomMT();

	cost = sqrt(r[0]);
	sint = sqrt(1.0 - r[0]);
	phi = 2.0 * M_PI * r[1];

	v.f[0] = (float)(cos(phi) * sint);
	v.f[1] = (float)(sin(phi) * sint);
	v.f[2] = (float)cost;

	for (i = 0; i < 3; i++) {
		outdir->f[i] = v.f[0] * basis[0].f[i]
			     + v.f[1] * basis[1].f[i]
			     + v.f[2] * basis[2].f[i];
	}
	outdir->f[3] = 1.0;
}
示例#4
0
/* Sample a random point on the subpixel (x, y). */
static int
sample_pixel(ri_vector_t *dir, int x, int y)
{
	double p[2];			/* random sampling point */
	float  fov;
	float  flen;			/* focal length */

	ri_vector_t        v;
	ri_camera_t       *camera;

	camera = ri_render_get()->context->option->camera;
	fov    = camera->fov;
	flen   = 1.0f / (float)tan((fov * M_PI / 180.0) * 0.5);

	p[0] = (randomMT() + x);
	p[1] = (randomMT() + y);

	dir->f[0] = (2.0 * p[0] - (double)pixwidth ) / (double)pixwidth;
	dir->f[0] *= (camera->screen_window[1] - camera->screen_window[0]) / 2;
	dir->f[1] = (2.0 * p[1] - (double)pixheight) / (double)pixheight;
	dir->f[1] *= (camera->screen_window[3] - camera->screen_window[2]) / 2;
	dir->f[2] = flen;
	dir->f[3] = 1.0f;
	//assert(dir->f[0] >= -1.0);
	//assert(dir->f[0] <=  1.0);
	//assert(dir->f[1] >= -1.0);
	//assert(dir->f[1] <=  1.0);

	ri_vector_transform(&v, *dir, &c2w);	/* camera to world */
	/* dir = v - camera.pos */
	ri_vector_sub(dir, v, cam_pos);
	ri_vector_normalize3(dir);

	return 1;
}
示例#5
0
文件: reg_RF.cpp 项目: CVML/drfi_cpp
double unif_rand(){
    //double value=((double)rand())/RAND_MAX;
    //mexPrintf("%f, RAND_MAX %d\n", value, RAND_MAX);
    //return value;
	//return ((double)rand())/RAND_MAX;
    return (((double)randomMT())/((double)MAX_UINT_COKUS));
}
示例#6
0
static unsigned char
sample_reflection_type(const ri_material_t *material)
{
	unsigned char type;
	double d, s, t;
	double r;

	d = ri_vector_ave(material->kd);
	s = ri_vector_ave(material->ks);
	t = ri_vector_ave(material->kt);
	assert(d + s + t <= 1.0);

	r = randomMT() * (d + s + t);


	/* randomly choose reflection type */

	if (r < d) {			/* diffuse */
		type = 'D';
	} else if (r < d + s) {		/* specular reflection */
		type = 'S';
	} else {  			/* specular refraction */
		type = 'T';
	}

	return type;
}
int main(void) {
    int j, k;
    
    // you can seed with any uint32, but the best are odds in 0..(2^32 - 1)
    
    seedMT(4357);
    uint32 MAX=pow(2, 32)-1;

// print the first 2,002 random numbers seven to a line as an example
//    for(j=0; j<2002; j++)
//        printf(" %10lu%s", (unsigned long) randomMT(), (j%7)==6 ? "\n" : "");
    
    double test_val;
    for(k=0;k<100;k++)
        for(j=0; j<2000002; j++) {
            test_val = ((double)randomMT()/(double)MAX);
            if (test_val>=1.0){
                printf("Problem");
                return(0);
            }
            //printf(" %f%s", test_val , (j%7)==6 ? "\n" : "");
        }
    printf("Success");
    return(1);
}
示例#8
0
double rfrac(void)
{
    /*
     * Return a pseudo-random value in the range { 0.0 <= x < 1.0 }.
     * Use randomMT() which returns a 32 bit PRN and multiply by 1/(1<<32).
     */
    return (double) (randomMT() * 0.00000000023283064365386962890625);
}
void GameState::GivePerkToPlayer(int perk, int team, bool calledFromNetwork)
{
	int i;
	unsigned char perksLost[NUMBER_OF_PERKS_TO_LOSE_FROM_VICIOUS_HEX];
	assert(team==1 || team==2);

	if (team==user->GetTeam())
	{
		// Once we choose a perk, choose our next group of random perks
		FillPerksArray();
		directSound->PlaySound(soundContainer->sounds[SELECTED_PERK_SOUND], false);
	}

	players[team-1].GiveUnhandledEventPerk(perk);

	// Handle instaneous effect perks
	if (perk==EARTH_ELEMENTAL)
	{
		// 10% of max castle health to damage for the opposite team
		DamageCastle(!(team-1), CASTLE_HEALTH/10.0f);
	}
	else if (perk==FIRE_ELEMENTAL)
	{
		// Immediately kill all enemy demons
		for (i=0; i < (int)demonList.size(); i++)
			if (demonList[i]->GetTeam() != team)
				demonList[i]->Die(UNKNOWN_DAMAGE, false, false); // Not necessary to send a packet for each demon dying
	}
	else if (perk==WATER_ELEMENTAL)
	{
		// Immediate full mana
		players[team-1].SetMana(players[team-1].GetMaxMana());
	}
	else if (perk==AIR_ELEMENTAL && calledFromNetwork==false) // Switch teams sends the packet and switches the team manually so don't do it again here
	{
		// Half the enemy demons join your team
		for (i=0; i < (int)demonList.size(); i++)
			if (demonList[i]->GetTeam() != team && (randomMT() % 2 == 0))
				demonList[i]->SwitchTeams(true); // This function is called only for the local player and from the network code, so is always a direct trigger
	}
	else if (perk==VICIOUS_HEX && calledFromNetwork==false) // Network code takes away the perks manually
	{
		// Enemy loses two perks
		players[!(team-1)].LosePerks(NUMBER_OF_PERKS_TO_LOSE_FROM_VICIOUS_HEX, perksLost);
	}
	else if (perk==UNHOLY_PACT)
	{
		// +3 perks, castle has 1 hp
		castleHealth[team-1]=1;
        players[team-1].SetRemainingPerks(players[team-1].GetRemainingPerks()+3);
	}

	if (team==user->GetTeam() && (rakServer->IsActive() || rakClient->IsConnected()) && calledFromNetwork==false)
	{
		// This is a trigger so send it out over the network
		TransmitChoosePerk(perk,perksLost[0],perksLost[1]);
	}
}
void FullyConnectedMesh2::AssignOurFCMGuid(unsigned int responseAssignedConnectionCount)
{
	// Only assigned once ever
	RakAssert(ourFCMGuid==0);
	unsigned int randomNumber = randomMT();
	ourFCMGuid |= randomNumber;
	uint64_t reponse64 = responseAssignedConnectionCount;
	ourFCMGuid |= reponse64<<32;
}
void FullyConnectedMesh2::AssignOurFCMGuid(void)
{
	// Only assigned once ever
	RakAssert(ourFCMGuid==0);
	unsigned int randomNumber = randomMT();
	randomNumber ^= (unsigned int) (RakNet::GetTimeUS() & 0xFFFFFFFF);
	randomNumber ^= (unsigned int) (rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS).g & 0xFFFFFFFF);
	ourFCMGuid |= randomNumber;
	uint64_t reponse64 = totalConnectionCount;
	ourFCMGuid |= reponse64<<32;
}
示例#12
0
文件: Corpus.cpp 项目: ml-lab/BayesPA
bool Corpus::genBinaryTrainingData( string class1) {
	if( !documentType) {
		debug( "error: document type assigned is NULL. \n");
		return false;
	}
	vector<DataSample*> *trainDataVec = new vector<DataSample*>(),
	*testDataVec = new vector<DataSample*>();
	this->documentType = documentType;
	// count documents to balance posi/neg examples.
	int doc1 = 0, docp = 0;
	for( int gi = 0; gi < this->newsgroupN; gi++) {
		for( int di = 0; di < this->D[gi]; di++) {
			Document* doc = documents[gi][di];
			if( doc->newsgroup == class1) {
				doc1++;
			}
			docp++;
		}
	}
	int train_pos = 0, train_neg = 0, test_pos = 0, test_neg = 0;
	for( int gi = 0; gi < this->newsgroupN; gi++) {
		for( int di = 0; di < this->D[gi]; di++) {
			Document* doc = documents[gi][di];
			if( doc->newsgroup != class1
			   && (double)randomMT()/(double)UINT32_MAX >= (double)doc1/(double)(docp-doc1)) // join or not, flip a coin.
				continue;
			DataSample* sample = new DataSample();
			sample->W = doc->W;
			if( doc->W == 0)
				continue;
			sample->label = (doc->newsgroup == class1 ? 1 : -1);
			sample->words = doc->words;
			if( documentType[gi][di] == true) { // then it is training data.
				trainDataVec->push_back(sample);
				train_pos += (sample->label+1)/2;
				train_neg += (1-sample->label)/2;
			}else{
				testDataVec->push_back(sample);
				test_pos += (sample->label+1)/2;
				test_neg += (1-sample->label)/2;
			}
		}
	}
	debug( "Binary Training [%s], train split:%d/%d, test split:%d/%d\n",
		  class1.c_str(), train_pos, train_neg, test_pos, test_neg);
	this->trainData = &trainDataVec->at(0);
	this->trainDataSize = trainDataVec->size();
	this->testData = &testDataVec->at(0);
	this->testDataSize = testDataVec->size();
	this->documentType = documentType;
	return true;
}
示例#13
0
void
ri_random_vector_cosweight(
    ri_vector_t        v_out,
    const ri_vector_t  n)
{
    double      theta, phi;
    ri_vector_t tn, bn, nn;
    ri_vector_t tb;

    calc_tangent_and_binormal(tn, bn, n);

    theta = acos(sqrt(1.0 - randomMT()));
    phi   = 2.0 * M_PI * randomMT();

    ri_vector_copy(nn, n);

    /* D = T*cos(phi)*sin(theta) + B*sin(phi)*sin(theta) + N*cos(theta) */
    ri_vector_scale(tn, tn, cos(phi) * sin(theta));
    ri_vector_scale(bn, bn, sin(phi) * sin(theta));
    ri_vector_scale(nn, nn, cos(theta));

    ri_vector_add(tb, tn, bn);
    ri_vector_add(v_out, tb, nn);
}
示例#14
0
bool RakServer::Start( unsigned short AllowedPlayers, unsigned long connectionValidationInteger, int threadSleepTimer, unsigned short port )
{
	bool init;
	
	RakPeer::Disconnect( 30L );
	
	init = RakPeer::Initialize( AllowedPlayers, port, threadSleepTimer );
	RakPeer::SetMaximumIncomingConnections( AllowedPlayers );
	
	// Random number seed
	long time = RakNet::GetTime();
	seedMT( time );
	seed = randomMT();
	
	if ( seed % 2 == 0 )   // Even
		seed--; // make odd
		
	nextSeed = randomMT();
	
	if ( nextSeed % 2 == 0 )   // Even
		nextSeed--; // make odd
		
	return init;
}
示例#15
0
bool RakServer::Start( unsigned short AllowedPlayers, unsigned int depreciated, int threadSleepTimer, unsigned short port, const char *forceHostAddress )
{
	bool init;

	RakPeer::Disconnect( 30 );

	init = RakPeer::Initialize( AllowedPlayers, port, threadSleepTimer, forceHostAddress );
	RakPeer::SetMaximumIncomingConnections( AllowedPlayers );

	// Random number seed
	long time = RakNet::GetTime();
	seedMT( time );
	seed = randomMT();

	if ( seed % 2 == 0 )   // Even
		seed--; // make odd

	nextSeed = randomMT();

	if ( nextSeed % 2 == 0 )   // Even
		nextSeed--; // make odd

	return init;
}
void SystemAddressList::RandomizeOrder(void)
{
	unsigned index, size, randIndex;
	SystemAddress temp;
	size = systemList.Size();
	for (index=0; index < size; index++)
	{
		randIndex=index + (randomMT() % (size-index));
		if (randIndex!=index)
		{
			temp=systemList[index];
			systemList[index]=systemList[randIndex];
			systemList[randIndex]=temp;
		}
	}
}
示例#17
0
// Fill the output array with up to NUMBER_OF_PERKS_TO_DRAW perks you can still select and return how much of the array was filled.
int Player::GetUnusedPerks(int output[NUMBER_OF_PERKS_TO_DRAW])
{
	int outputIndex=0, numberOfUnusedPerks;

	numberOfUnusedPerks = GetNumberOfUnusedPerks();

	if (numberOfUnusedPerks <= NUMBER_OF_PERKS_TO_DRAW)
	{
		// Just return all the remaining perks
		for (int i=0; i < NUMBER_OF_PERKS; i++)
		{
			if (hasPerk[i]==false)
			{
				output[outputIndex++]=i;
				if (outputIndex==NUMBER_OF_PERKS_TO_DRAW)
					break;
			}
		}
	}
	else // We have more perks available than we want to pick
	{
		// Randomly pick NUMBER_OF_PERKS_TO_DRAW.  This is not the most efficient way to do it but it doesn't matter in this situation
		while (outputIndex < NUMBER_OF_PERKS_TO_DRAW)
		{
			do
			{
				// Pick one
				output[outputIndex] = randomMT() % NUMBER_OF_PERKS;
			} while (hasPerk[output[outputIndex]]==true); // If it is already used pick again

			hasPerk[output[outputIndex]]=true; // Temporarily set to true so we don't pick it twice

			outputIndex++;
		}

		// Set the ones we temporarily set to true to false again
		for (int i=0; i < outputIndex; i++)
			hasPerk[output[i]]=false;

	}

	return outputIndex;
}
示例#18
0
// Lose some number of perks
void Player::LosePerks(int numberOfPerksToLose, unsigned char perksLost[])
{
	assert(numberOfPerksToLose>0);
	int index,perksLostIndex=0;

	int numberOfLosablePerks = GetNumberOfLosablePerks();
	if (numberOfLosablePerks <= numberOfPerksToLose)
	{
		// Just go down the array and set all perks to false
		// Just return all the remaining perks
		for (int i=0; i < NUMBER_OF_PERKS; i++)
		{
			if (perkLosable[i])
			{
				if (hasPerk[i]==true)
				{
					hasPerk[i]=false;
					assert(perksLostIndex < numberOfPerksToLose);
					perksLost[perksLostIndex++]=i;
				}
			}
		}
	}
	else
	{
		// Keep picking among losable perks until we hit the desired amount
		// Randomly pick NUMBER_OF_PERKS_TO_DRAW.  This is not the most efficient way to do it but it doesn't matter in this situation
		while (numberOfPerksToLose>0)
		{
			do
			{
				// Pick one
				index = randomMT() % NUMBER_OF_PERKS;
			} while (hasPerk[index]==false || perkLosable[index]==false); // If we cannot lose this perk because it is not losable or we don't have it pick again

			hasPerk[index]=false;
			assert(perksLostIndex < numberOfPerksToLose);
			perksLost[perksLostIndex++]=index;

			numberOfPerksToLose--;
		}
	}
}
示例#19
0
/*
 * russian roulette to choose whether continue tracing or not according to
 * surface material.
 * return 1 for continue, return 0 not.
 *
 */
static int
russian_roulette(const ri_material_t *material)
{
	double d, s, t;
	double r;

	r = randomMT();

	d = ri_vector_ave(material->kd);
	s = ri_vector_ave(material->ks);
	t = ri_vector_ave(material->kt);
	assert(d + s + t <= 1.0);

	if (r > d + s + t) {	/* reject */
		return 0;
	}

	return 1;

}
示例#20
0
文件: Corpus.cpp 项目: ml-lab/BayesPA
bool Corpus::genTrainingDataRandom( double percent) {
//	srand( (unsigned)time( NULL));
	vector<DataSample*> *trainDataVec = new vector<DataSample*>(),
									*testDataVec = new vector<DataSample*>();
	if( percent < 0 || percent > 1) {
		debug( "error: random percentage is out of range [0,1].\n");
		return false;
	}
	if( documentType != NULL) { // clean document type.
		for( int i = 0; i < newsgroupN; i++) {
			if( documentType[i] != NULL) delete documentType[i];
		}
		delete documentType;
	}
	documentType = new bool*[newsgroupN];
	for( int gi = 0; gi < this->newsgroupN; gi++) {
		documentType[gi] = new bool[D[gi]];
		for( int di = 0; di < D[gi]; di++) {
			double proposed = (double)(randomMT()%1000000)/1000000.0;
			Document* doc = documents[gi][di];
			DataSample* sample = new DataSample();
			sample->W = doc->W;
			sample->label = gi;
			sample->words = doc->words;
			if( proposed <= percent) {// give to training.
				documentType[gi][di] = true;
				trainDataVec->push_back(sample);
			}else{
				documentType[gi][di] = false;
				testDataVec->push_back(sample);
			}
		}
	}
	if( this->trainData != 0) delete[] trainData;
	if( this->testData != 0) delete[] testData;
	this->trainData = &trainDataVec->at(0);
	this->trainDataSize = trainDataVec->size();
	this->testData = &testDataVec->at(0);
	this->testDataSize = testDataVec->size();
	return true;
}
// Function name   : StrangeLivingCreature::StrangeLivingCreature
// Description     : 
// Return type     : 
// Argument        : StrangeNNGene* aGene
StrangeLivingCreature::StrangeLivingCreature( StrangeNNGene* aGene )
    : gene_( aGene )
    , spawnCount_( 0 )
    , feedCount_( 0 )
    , angle_( randomMT() % 360 )
    , eyeRadius_( 50 )
    , eyeAngle_( 45 )
    , xLevel_( 0 )
    , yLevel_( 0 )
    , angleLevel_( 0 )
    , eyeRadiusLevel_( 0 )
    , eyeAngleLevel_( 0 )
    , bodyRadius_( MIN_BODY_RADIUS )
    , bodyRadiusLevel_( 0 )
    , angleChange_( 0 )
{
    // Construct the brain
    if ( gene_.get() != NULL )
        brain_.reset(new StrangeNeuralNetwork( gene_.get() ));

}
示例#22
0
void mexFunction( int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[]) {
    mwSize Lenx;
    mwIndex i, j, ij;
    double *x, *RND, *Lsum, *prob;
    double maxx, r;    
    Lenx = mxGetM(prhs[0])*mxGetN(prhs[0]);
    x = mxGetPr(prhs[0]);
    r = mxGetScalar(prhs[1]);
    
    
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    Lsum = mxGetPr(plhs[0]);
    
    if(nrhs>=3)
        RND = mxGetPr(prhs[2]);
    
    if(nrhs>=4)
        maxx =  mxGetScalar(prhs[3]);
    else
        for(i=0, maxx=0;i<Lenx;i++)
            if (maxx<x[i]) maxx = x[i];
    
    prob = (double *) mxCalloc(maxx, sizeof(double));
    
    for(i=0;i<maxx;i++)
        prob[i] = r/(r+i);
    
    for(ij=0, i=0, Lsum[0]=0;i<Lenx;i++)
        for(j=0;j<x[i];j++) {
        if(nrhs<3) {
            /*if ( ((double) randomMT() / (double) 4294967296.0) <prob[j])     Lsum[0]++;*/
            if  ((double) randomMT() <= prob[j]*RAND_MAX_32)     Lsum[0]++;
            /*if ( (double) rand() <= prob[j]*RAND_MAX)     Lsum[0]++;*/
        }
        else {
            if (RND[ij++]<=prob[j])     Lsum[0]++;
        }
        }
}
示例#23
0
文件: random.c 项目: lollek/imoria
integer randint(integer maxval)
{
/* Generates a random integer x where 1<=X<=MAXVAL	-RAK-	*/

  integer r = 0;
  
  if (maxval) {
#if USE_MTWIST
    r = ((randomMT() % maxval) + 1);
#else
    r = ((rand() % maxval) + 1);
#endif
  }

  /*
#if DO_DEBUG
   fprintf(debug_file, "   rand:  %ld\t(%ld)\n", r, maxval);
   fflush(debug_file);
#endif	  
*/

  return r;
};
示例#24
0
double unif_rand(){
    return (((double)randomMT())/((double)MAX_UINT_COKUS));
}
示例#25
0
Packet* RakServer::Receive( void )
{
	Packet * packet = RakPeer::Receive();

	// This is just a regular time based update.  Nowhere else good to put it

	if ( RakPeer::IsActive() && occasionalPing )
	{
		unsigned int time = RakNet::GetTime();

		if ( time > broadcastPingsTime || ( packet && packet->data[ 0 ] == ID_RECEIVED_STATIC_DATA ) )
		{
			if ( time > broadcastPingsTime )
				broadcastPingsTime = time + 30000; // Broadcast pings every 30 seconds

			unsigned i, count;

			RemoteSystemStruct *remoteSystem;
			RakNet::BitStream bitStream( ( PlayerID_Size + sizeof( short ) ) * 32 + sizeof(unsigned char) );
			unsigned char typeId = ID_BROADCAST_PINGS;

			bitStream.Write( typeId );

			for ( i = 0, count = 0; count < 32 && i < remoteSystemListSize; i++ )
			{
				remoteSystem = remoteSystemList + i;

				if ( remoteSystem->playerId != UNASSIGNED_PLAYER_ID )
				{
					bitStream.Write( remoteSystem->playerId.binaryAddress );
					bitStream.Write( remoteSystem->playerId.port );
					bitStream.Write( remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].pingTime );
					count++;
				}
			}

			if ( count > 0 )   // If we wrote anything
			{

				if ( packet && packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )   // If this was a new connection
					Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false ); // Send to the new connection
				else
					Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, UNASSIGNED_PLAYER_ID, true ); // Send to everyone
			}
		}
	}

	// This is just a regular time based update.  Nowhere else good to put it
	if ( RakPeer::IsActive() && synchronizedRandomInteger )
	{
		unsigned int time = RakNet::GetTime();

		if ( time > nextSeedUpdate || ( packet && packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION ) )
		{
			if ( time > nextSeedUpdate )
				nextSeedUpdate = time + 9000; // Seeds are updated every 9 seconds

			seed = nextSeed;

			nextSeed = randomMT();

			if ( nextSeed % 2 == 0 )   // Even
				nextSeed--; // make odd

			/*
			SetRandomNumberSeedStruct s;

			s.ts = ID_TIMESTAMP;
			s.timeStamp = RakNet::GetTime();
			s.typeId = ID_SET_RANDOM_NUMBER_SEED;
			s.seed = seed;
			s.nextSeed = nextSeed;
			RakNet::BitStream s_BitS( SetRandomNumberSeedStruct_Size );
			s.Serialize( s_BitS );
			*/

			RakNet::BitStream outBitStream(sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned int));
			outBitStream.Write((unsigned char) ID_TIMESTAMP);
			outBitStream.Write((unsigned int) RakNet::GetTime());
			outBitStream.Write((unsigned char) ID_SET_RANDOM_NUMBER_SEED);
			outBitStream.Write(seed);
			outBitStream.Write(nextSeed);

			if ( packet && packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )
				Send( &outBitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false );
			else
				Send( &outBitStream, SYSTEM_PRIORITY, RELIABLE, 0, UNASSIGNED_PLAYER_ID, true );
		}
	}

	if ( packet )
	{
		// Intercept specific client / server feature packets. This will do an extra send and still pass on the data to the user

		if ( packet->data[ 0 ] == ID_RECEIVED_STATIC_DATA )
		{
			if ( relayStaticClientData )
			{
				// Relay static data to the other systems but the sender
				RakNet::BitStream bitStream( packet->length + PlayerID_Size );
				unsigned char typeId = ID_REMOTE_STATIC_DATA;
				bitStream.Write( typeId );
				bitStream.Write( packet->playerId.binaryAddress );
				bitStream.Write( packet->playerId.port );
				bitStream.Write( packet->playerIndex );
				bitStream.Write( ( char* ) packet->data + sizeof(unsigned char), packet->length - sizeof(unsigned char) );
				Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, true );
			}
		}

		else
			if ( packet->data[ 0 ] == ID_DISCONNECTION_NOTIFICATION || packet->data[ 0 ] == ID_CONNECTION_LOST || packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )
			{
				// Relay the disconnection
				RakNet::BitStream bitStream( packet->length + PlayerID_Size );
				unsigned char typeId;

				if ( packet->data[ 0 ] == ID_DISCONNECTION_NOTIFICATION )
					typeId = ID_REMOTE_DISCONNECTION_NOTIFICATION;
				else
					if ( packet->data[ 0 ] == ID_CONNECTION_LOST )
						typeId = ID_REMOTE_CONNECTION_LOST;
					else
						typeId = ID_REMOTE_NEW_INCOMING_CONNECTION;

				bitStream.Write( typeId );
				bitStream.Write( packet->playerId.binaryAddress );
				bitStream.Write( packet->playerId.port );
				bitStream.Write( ( unsigned short& ) packet->playerIndex );

				Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, true );

				if ( packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )
				{
					unsigned i;

					for ( i = 0; i < remoteSystemListSize; i++ )
					{
						if ( remoteSystemList[ i ].playerId != UNASSIGNED_PLAYER_ID && packet->playerId != remoteSystemList[ i ].playerId )
						{
							bitStream.Reset();
							typeId = ID_REMOTE_EXISTING_CONNECTION;
							bitStream.Write( typeId );
							bitStream.Write( remoteSystemList[ i ].playerId.binaryAddress );
							bitStream.Write( remoteSystemList[ i ].playerId.port );
							bitStream.Write( ( unsigned short ) i );
							// One send to tell them of the connection
							Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false );

							if ( relayStaticClientData )
							{
								bitStream.Reset();
								typeId = ID_REMOTE_STATIC_DATA;
								bitStream.Write( typeId );
								bitStream.Write( remoteSystemList[ i ].playerId.binaryAddress );
								bitStream.Write( remoteSystemList[ i ].playerId.port );
								bitStream.Write( (unsigned short) i );
								bitStream.Write( ( char* ) remoteSystemList[ i ].staticData.GetData(), remoteSystemList[ i ].staticData.GetNumberOfBytesUsed() );
								// Another send to tell them of the static data
								Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false );
							}
						}
					}
				}
			}
	}

	return packet;
}
void GibbsSamplerLDA( double ALPHA, double BETA, int W, int T, int D, int NN, int OUTPUT, int n, 
                       int *z, int *d, int *w, int *wp, int *ztot, int *order, double *probs, int startcond,
                       mwIndex *irtd, mwIndex *jctd, double *srdp, mwIndex *irdp, mwIndex *jcdp )
{
  int wi,di,i,ii,j,topic, rp, temp, iter, wioffset, dioffset, rowindex, TAVAIL;
  int n1,n2,ftopic;
  double totprob, WBETA, r, max;

  if (startcond == 1) {
      /* start from previously saved state */
      for (i=0; i<n; i++)
      {
          wi = w[ i ];
          di = d[ i ];
          topic = z[ i ];
          wp[ wi*T + topic ]++; // increment wp count matrix

          // increment sparse dp count matrix
          n1 = (int) *( jcdp + di  );
          n2 = (int) *( jcdp + di + 1 );         
          TAVAIL = (n2-n1);
          ftopic = -1;
          rowindex = -1;
          while ((ftopic != topic) & (rowindex < TAVAIL-1)) {
             rowindex++;
             ftopic = (int) *( irdp + n1 + rowindex );
          }
          if (ftopic != topic) mexErrMsgTxt("Error....(10)");          
          srdp[ n1 + rowindex ]++;
          
          ztot[ topic ]++; // increment ztot matrix
      }
  }
  
  if (startcond == 0) {
  /* random initialization */
      if (OUTPUT==2) mexPrintf( "Starting Random initialization\n" );
      for (i=0; i<n; i++)
      {
          wi = w[ i ];
          di = d[ i ];
          
          // what are the available tags?
          // look up the start and end index for tags associated with this document
          n1 = (int) *( jctd + di     );
          n2 = (int) *( jctd + di + 1 );         
          TAVAIL = (n2-n1);
                    
          // pick a random topic 0..TAVAIL-1
          rowindex = (int) ( (double) randomMT() * (double) TAVAIL / (double) (4294967296.0 + 1.0) );
          
          // convert into a tag
          topic = (int) *( irtd + n1 + rowindex );  
          
          z[ i ] = topic; // assign this word token to this topic
          wp[ wi*T + topic ]++; // increment wp count matrix
          ztot[ topic ]++; // increment ztot matrix
          
          // increment sparse dp count matrix
          n1 = (int) *( jcdp + di  );
          n2 = (int) *( jcdp + di + 1 );         
          TAVAIL = (n2-n1);
          ftopic = -1;
          rowindex = -1;
          while ((ftopic != topic) & (rowindex < TAVAIL-1)) {
             rowindex++;
             ftopic = (int) *( irdp + n1 + rowindex );
          }
          if (ftopic != topic) {
              mexPrintf( "n1 = %d n2=%d\n" , n1 , n2 );
              mexPrintf( "n1 = %d n2=%d  (TD)\n" , (int) *( jctd + di     ) , (int) *( jctd + di + 1 ) );
              mexPrintf( "TAVAIL=%d rowindex=%d topic=%d di=%d\n" , TAVAIL , rowindex , topic , di);
              for (rowindex=0; rowindex < TAVAIL; rowindex++)
              {
                 mexPrintf( "rowindex=%d  topic=%d topic2=%d \n" , rowindex , (int) *( irdp + n1 + rowindex ) , (int) *( irtd + n1 + rowindex )); 
              }
              mexErrMsgTxt("Error....(11)");
              
          }
          srdp[ n1 + rowindex ]++;
      }
  }
    
  if (OUTPUT==2) mexPrintf( "Determining random order update sequence\n" );
  
  for (i=0; i<n; i++) order[i]=i; // fill with increasing series
  for (i=0; i<(n-1); i++) {
      // pick a random integer between i and nw
      rp = i + (int) ((double) (n-i) * (double) randomMT() / (double) (4294967296.0 + 1.0));
      
      // switch contents on position i and position rp
      temp = order[rp];
      order[rp]=order[i];
      order[i]=temp;
  }
  
  //for (i=0; i<n; i++) mexPrintf( "i=%3d order[i]=%3d\n" , i , order[ i ] );
  WBETA = (double) (W*BETA);
  for (iter=0; iter<NN; iter++) {
      if (OUTPUT >=1) {
          if ((iter % 10)==0) mexPrintf( "\tIteration %d of %d\n" , iter , NN );
          if ((iter % 10)==0) mexEvalString("drawnow;");
      }
      for (ii = 0; ii < n; ii++) {
          i = order[ ii ]; // current word token to assess
          
          wi  = w[i]; // current word index
          di  = d[i]; // current document index  
          topic = z[i]; // current topic assignment to word token
          ztot[topic]--;  // substract this from counts
          
          wioffset = wi*T;
          dioffset = di*T;
          
          wp[wioffset+topic]--;
          
          // decrement sparse dp count matrix
          n1 = (int) *( jcdp + di  );
          n2 = (int) *( jcdp + di + 1 );         
          TAVAIL = (n2-n1);
          ftopic = -1;
          rowindex = -1;
          while ((ftopic != topic) & (rowindex < TAVAIL-1)) {
             rowindex++;
             ftopic = (int) *( irdp + n1 + rowindex );
          }
          if (ftopic != topic) mexErrMsgTxt("Error....(12)");          
          srdp[ n1 + rowindex ]--;
          
          
          
          
          //mexPrintf( "(1) Working on ii=%d i=%d wi=%d di=%d topic=%d wp=%d dp=%d\n" , ii , i , wi , di , topic , wp[wi+topic*W] , dp[wi+topic*D] );
          n1 = (int) *( jctd + di     );
          n2 = (int) *( jctd + di + 1 );         
          TAVAIL = (n2-n1);
          
          totprob = (double) 0;
          for (j = 0; j < TAVAIL; j++) 
          {
              topic = (int) *( irtd + n1 + j ); 
              probs[j] = ((double) wp[ wioffset+topic ] + (double) BETA)/
                         ( (double) ztot[topic]+ (double) WBETA) *
                         ( (double) srdp[ n1 + j ] + (double) ALPHA / (double) TAVAIL);
              totprob += probs[j];
          }
          
          // sample a topic from the distribution
          r = (double) totprob * (double) randomMT() / (double) 4294967296.0;
          max = probs[0];
          j = 0;
          while (r>max) {
              j++;
              max += probs[j];
          }
           
          if (j>=TAVAIL) mexErrMsgTxt("Wrong value sampled");
          
          topic = (int) *( irtd + n1 + j ); 
          
          z[i] = topic; // assign current word token i to topic j
          wp[wioffset + topic ]++; // and update counts
          ztot[topic]++;
          
          // increment sparse dp count matrix
          n1 = (int) *( jcdp + di  );
          n2 = (int) *( jcdp + di + 1 );         
          TAVAIL = (n2-n1);
          ftopic = -1;
          rowindex = -1;
          while ((ftopic != topic) & (rowindex < TAVAIL-1)) {
             rowindex++;
             ftopic = (int) *( irdp + n1 + rowindex );
          }
          if (ftopic != topic) mexErrMsgTxt("Error....(13)");          
          srdp[ n1 + rowindex ]++;
          
          
          //mexPrintf( "(2) Working on ii=%d i=%d wi=%d di=%d topic=%d wp=%d dp=%d\n" , ii , i , wi , di , topic , wp[wi+topic*W] , dp[wi+topic*D] );
      }
  }
}
示例#27
0
static void make_seed(unsigned int * output, std::size_t n)
{
    if(!urandom || fread(output, sizeof(unsigned int), n, urandom) < n)
        loopi(n) output[i] = randomMT();
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[])
{
  double *PQ0, *PQ1, *PQ2, *GAMMA, *X, *XD, *PQ, *probs;
  double totweight, sumlogprob, pwz, pwd, pwc, proute0, proute1, proute2, prob, rn, max;
  int *dims, *x, *xtot;
  int NQ, D, BURNIN, S, NS, NN, LAG, SEED, OUTPUT, i, iter, d, route, r, oldroute, newroute;
    
    
  // Check for proper number of arguments.
  if (nrhs < 9) {
    mexErrMsgTxt("At least 9 input arguments required");
  } else if (nlhs < 3) {
    mexErrMsgTxt("3 output arguments required");
  }
  
  // process the input arguments
  if (mxIsDouble( prhs[ 0 ] ) != 1) mexErrMsgTxt("PQ0 input matrix must be a double precision matrix");
  if (mxIsDouble( prhs[ 1 ] ) != 1) mexErrMsgTxt("PQ1 input matrix must be a double precision matrix");
  if (mxIsDouble( prhs[ 2 ] ) != 1) mexErrMsgTxt("PQ2 input matrix must be a double precision matrix");
  if (mxIsDouble( prhs[ 3 ] ) != 1) mexErrMsgTxt("GAMMA input vector must be a double precision matrix");
 
  // pointer to PQ0 matrix
  PQ0 = mxGetPr( prhs[ 0 ] );
  NQ = mxGetM( prhs[ 0 ] );
  D  = mxGetN( prhs[ 0 ] );
  
  // pointer to PQ1 matrix
  PQ1 = mxGetPr( prhs[ 1 ] );
  if ( mxGetM( prhs[ 1 ] ) != NQ ) mexErrMsgTxt("PQ1 matrix should have same dimensions as PQ0 matrix");
  if ( mxGetN( prhs[ 1 ] ) != D )  mexErrMsgTxt("PQ1 matrix should have same dimensions as PQ0 matrix");
  
  // pointer to PQ2 matrix
  PQ2 = mxGetPr( prhs[ 2 ] );
  if ( mxGetM( prhs[ 2 ] ) != 1 )  mexErrMsgTxt("PQ2 matrix should be a row vector");
  if ( mxGetN( prhs[ 2 ] ) != NQ )  mexErrMsgTxt("PQ2 matrix should same number of query words as PQ0 matrix");
    
  // pointer to gamma hyperparameter vector
  GAMMA = mxGetPr( prhs[ 3 ] );
  if ( mxGetM( prhs[ 3 ] ) != 1 ) mexErrMsgTxt("GAMMA input vector must be a row vector");
  if ( mxGetN( prhs[ 3 ] ) != 3 ) mexErrMsgTxt("GAMMA input vector must have three entries");
  
  BURNIN    = (int) mxGetScalar(prhs[4]);
  if (BURNIN<1) mexErrMsgTxt("Number of burnin iterations must be positive");

  NS    = (int) mxGetScalar(prhs[5]);
  if (NS<1) mexErrMsgTxt("Number of samples must be greater than zero");
  
  LAG    = (int) mxGetScalar(prhs[6]);
  if (LAG<1) mexErrMsgTxt("Lag must be greater than zero");
  
  // seeding
  SEED = (int) mxGetScalar(prhs[7]);
  seedMT( 1 + SEED * 2 ); // seeding only works on uneven numbers
  
  OUTPUT = (int) mxGetScalar(prhs[8]);
  
  // create output matrices
  plhs[ 0 ] = mxCreateDoubleMatrix( D , 3, mxREAL );
  X = mxGetPr( plhs[ 0 ] );

  dims = (int *) mxCalloc( 3 , sizeof( int ));
  dims[ 0 ] = D;
  dims[ 1 ] = 3;
  dims[ 2 ] = NQ;
  
  plhs[ 1 ] = mxCreateNumericArray( 3,dims,mxDOUBLE_CLASS,mxREAL);
  XD = mxGetPr( plhs[ 1 ] );
  
  plhs[ 2 ] = mxCreateDoubleMatrix( NQ , D, mxREAL );
  PQ = mxGetPr( plhs[ 2 ] );
  
  if (OUTPUT==2) 
  {
      mexPrintf( "Running Special Word Retrieval Gibbs Sampler Version 1.0\n" );
      mexPrintf( "Arguments:\n" );
      mexPrintf( "\tNumber of docs          D = %d\n" , D );
      mexPrintf( "\tNumber of query words  NQ = %d\n" , NQ );        
      mexPrintf( "\tHyperparameter     GAMMA0 = %4.4f\n" , GAMMA[0] );
      mexPrintf( "\tHyperparameter     GAMMA1 = %4.4f\n" , GAMMA[1] );
      mexPrintf( "\tHyperparameter     GAMMA2 = %4.4f\n" , GAMMA[2] );
      mexPrintf( "\tSeed number          SEED = %d\n" , SEED );
      mexPrintf( "\tBurnin             BURNIN = %d\n" , BURNIN );
      mexPrintf( "\tNumber of samples      NS = %d\n" , NS );
      mexPrintf( "\tLag between samples   LAG = %d\n" , LAG );
  }
  
  // allocate memory for sampling arrays
  x  = (int *) mxCalloc( NQ * D , sizeof( int ));
  xtot = (int *) mxCalloc( 3 * D , sizeof( int ));
  probs = (double *) mxCalloc( 3 , sizeof( double ));
  
  // initialize the sampler
  for (d=0; d<D; d++)
  {
      for (i=0; i<NQ; i++)
      {
          // pick a random route between 0 and 2
          route = (int) ( (double) randomMT() * (double) 3 / (double) (4294967296.0 + 1.0) );
          
          // assign this query word to this route
          x[ i + d * NQ ] = route;
          
          // update total
          xtot[ route + d * 3 ] += 1;
          
          //if (d<5) mexPrintf( "d=%d i=%d route=%d\n" , d , i , route );
      }
  }
  
  // RUN THE GIBBS SAMPLER
  NN = BURNIN + NS * LAG - LAG + 1;
  S = 0;
  for (iter=0; iter<NN; iter++)
  {
      if (OUTPUT >=1)
      {
          if ((iter % 10)==0) mexPrintf( "\tIteration %d of %d\n" , iter , NN );
          if ((iter % 10)==0) mexEvalString("drawnow;");
      }
      
      // do an iteration
      for (d=0; d<D; d++) // loop over all docs
      {
          for (i=0; i<NQ; i++) // loop over all words in query
          {
              oldroute = x[ i + d * NQ ];
              xtot[ oldroute + d * 3 ]--; // subtract this from the counts
                      
              pwz = PQ0[ i + d * NQ ];
              pwd = PQ1[ i + d * NQ ];
              pwc = PQ2[ i ];
        
              probs[ 0 ] = ((double) xtot[ 0 + d * 3 ] + (double) GAMMA[ 0 ] ) * pwz;  
              probs[ 1 ] = ((double) xtot[ 1 + d * 3 ] + (double) GAMMA[ 1 ] ) * pwd;
              probs[ 2 ] = ((double) xtot[ 2 + d * 3 ] + (double) GAMMA[ 2 ] ) * pwc;
              
              totweight = probs[ 0 ] + probs[ 1 ] + probs[ 2 ];
              
              // sample a route from this distribution
              rn = (double) totweight * (double) randomMT() / (double) 4294967296.0;
              max = probs[0];
              newroute = 0;
              while (rn>max) {
                  newroute++;
                  max += probs[newroute];
              }

              x[ i + d * NQ ] = newroute;
              xtot[ newroute + d * 3 ]++; // add this to the counts
          }
      }
      
      
      if ((iter >= BURNIN) && (((iter - BURNIN) % LAG) == 0))
      {
          S++;
          
          if (OUTPUT >=1)
          {
              //mexPrintf( "\tDrawing sample %d of %d\n" , S , NS );
              //mexEvalString("drawnow;");
          }
          
          // update the return variables with the new counts
          for (d=0; d<D; d++)
          {
              
              X[ d + 0 * D ] += (double) xtot[ 0 + d * 3 ] + GAMMA[ 0 ];
              X[ d + 1 * D ] += (double) xtot[ 1 + d * 3 ] + GAMMA[ 1 ];
              X[ d + 2 * D ] += (double) xtot[ 2 + d * 3 ] + GAMMA[ 2 ];
              
              for (i=0; i<NQ; i++)
              {
                  route = x[ i + d * NQ ]; // current route assignment
                  
                  for (r=0; r<3; r++)
                  {
                      if (r==route)
                      {   
                          XD[ d + r*D + i*D*3 ] += (double) 1 + GAMMA[ r ];  // D x 3 x NQ
                      } else
                      {
                          XD[ d + r*D + i*D*3 ] += (double) GAMMA[ r ];  // D x 3 x NQ
                      }
                  } 
                           
              }
          }
      }
  }
  
  // NOW CALCULATE PROBABILITY DISTRIBUTIONS
  for (d=0; d<D; d++)
  {      
     totweight = 0;
     for (route=0; route<3; route++) totweight += X[ d + route * D ];
     for (route=0; route<3; route++) X[ d + route * D ] /= totweight; 
     
     for (i=0; i<NQ; i++)
     {
        totweight = 0;
        for (route=0; route<3; route++) totweight += XD[ d + route*D + i*D*3 ];
        for (route=0; route<3; route++) XD[ d + route*D + i*D*3 ] /= totweight;
     }
  }
  
  // NOW CALCULATE RETRIEVAL PROBABILITY
  for (d=0; d<D; d++)
  {  
     // the following is correct with a model that has lambda outside the plate -- one route probability for each query 
     proute0 = X[ d + 0 * D ];
     proute1 = X[ d + 1 * D ];
     proute2 = X[ d + 2 * D ];
      
     for (i=0; i<NQ; i++)
     {
        // the following is correct with a model that has lambda inside the plate -- a separate probability for each word       
        //proute0 = XD[ d + 0 * D + i * D * 3 ];
        //proute1 = XD[ d + 1 * D + i * D * 3 ];
        //proute2 = XD[ d + 2 * D + i * D * 3 ];
          
        pwz = PQ0[ i + d * NQ ];
        pwd = PQ1[ i + d * NQ ];
        pwc = PQ2[ i ];
        
        prob = proute0 * pwz + proute1 * pwd + proute2 * pwc;
        
        PQ[ i + d * NQ ] = prob;
        //if (d<5) mexPrintf( "d=%d i=%d prob=%4.7f logprob=%4.7f p0=%4.5f p1=%4.5f p2=%4.5f  pwz=%4.5f  pwd=%4.5f  pwc=%4.5f\n" , d , i , prob , sumlogprob , proute0 , proute1 , proute2 , pwz , pwd , pwc );
     }
     
     //if (d<5) mexPrintf( "d=%d  logprob=%4.4f\n" , d , sumlogprob );
          
  }
   
}
示例#29
0
char ProfanityFilter::RandomBanChar()
{
	return BANCHARS[randomMT() % (sizeof(BANCHARS) - 1)];
}
int ReliableOrderedConvertedTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	RakPeerInterface *sender, *receiver;
	unsigned int packetNumberSender[32],packetNumberReceiver[32], receivedPacketNumberReceiver, receivedTimeReceiver;
	char str[256];
	char ip[32];
	TimeMS sendInterval, nextSend, currentTime, quitTime;
	unsigned short remotePort, localPort;
	unsigned char streamNumberSender,streamNumberReceiver;
	BitStream bitStream;
	Packet *packet;
	bool doSend=false;

	for (int i=0; i < 32; i++)
	{
		packetNumberSender[i]=0;
		packetNumberReceiver[i]=0;

	}

	/*
	if (argc==2)
	{
	fp = fopen(argv[1],"wt");
	SetMalloc_Ex(LoggedMalloc);
	SetRealloc_Ex(LoggedRealloc);
	SetFree_Ex(LoggedFree);
	}
	else
	*/
	fp=0;
	destroyList.Clear(false,_FILE_AND_LINE_);

	sender =RakPeerInterface::GetInstance();
	destroyList.Push(	sender ,_FILE_AND_LINE_);
	//sender->ApplyNetworkSimulator(.02, 100, 50);

	/*
	if (str[0]==0)
	sendInterval=30;
	else
	sendInterval=atoi(str);*///possible future params

	sendInterval=30;

	/*
	printf("Enter remote IP: ");
	Gets(ip, sizeof(ip));
	if (ip[0]==0)*/
	strcpy(ip, "127.0.0.1");

	/*
	printf("Enter remote port: ");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "60000");
	remotePort=atoi(str);
	/*
	printf("Enter local port: ");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "0");
	localPort=atoi(str);

	if (isVerbose)
		printf("Connecting...\n");

	sender->Startup(1, &SocketDescriptor(localPort,0), 1);
	sender->Connect(ip, remotePort, 0, 0);

	receiver =RakPeerInterface::GetInstance();
	destroyList.Push(	receiver ,_FILE_AND_LINE_);

	/*
	printf("Enter local port: ");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "60000");
	localPort=atoi(str);

	if (isVerbose)
		printf("Waiting for connections...\n");

	receiver->Startup(32, &SocketDescriptor(localPort,0), 1);
	receiver->SetMaximumIncomingConnections(32);

	//	if (sender)
	//		sender->ApplyNetworkSimulator(128000, 50, 100);
	//	if (receiver)
	//		receiver->ApplyNetworkSimulator(128000, 50, 100);

	/*printf("How long to run this test for, in seconds?\n");
	Gets(str, sizeof(str));
	if (str[0]==0)*/
	strcpy(str, "12");

	currentTime = GetTimeMS();
	quitTime = atoi(str) * 1000 + currentTime;

	nextSend=currentTime;

	while (currentTime < quitTime)
		//while (1)
	{

		packet = sender->Receive();
		while (packet)
		{
			// PARSE TYPES
			switch(packet->data[0])
			{
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				doSend=true;
				nextSend=currentTime;
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)
					printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("ID_CONNECTION_LOST\n");
				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("Connection attempt failed\n");
				break;
			}

			sender->DeallocatePacket(packet);
			packet = sender->Receive();
		}

		while (doSend && currentTime > nextSend)
		{
			streamNumberSender=0;
			//	streamNumber = randomMT() % 32;
			// Do the send
			bitStream.Reset();
			bitStream.Write((unsigned char) (ID_USER_PACKET_ENUM+1));
			bitStream.Write(packetNumberSender[streamNumberSender]++);
			bitStream.Write(streamNumberSender);
			bitStream.Write(currentTime);
			char *pad;
			int padLength = (randomMT() % 5000) + 1;
			pad = new char [padLength];
			bitStream.Write(pad, padLength);
			delete [] pad;
			// Send on a random priority with a random stream
			// if (sender->Send(&bitStream, HIGH_PRIORITY, (PacketReliability) (RELIABLE + (randomMT() %2)) ,streamNumber, UNASSIGNED_SYSTEM_ADDRESS, true)==false)
			if (sender->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED ,streamNumberSender, UNASSIGNED_SYSTEM_ADDRESS, true)==false)
				packetNumberSender[streamNumberSender]--; // Didn't finish connecting yet?

			RakNetStatistics *rssSender;
			rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));
			if (isVerbose)
				printf("Snd: %i.\n", packetNumberSender[streamNumberSender]);

			nextSend+=sendInterval;

			// Test halting
			//	if (rand()%20==0)
			//		nextSend+=1000;
		}

		packet = receiver->Receive();
		while (packet)
		{
			switch(packet->data[0])
			{
			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("ID_CONNECTION_LOST\n");
				break;
			case ID_USER_PACKET_ENUM+1:
				bitStream.Reset();
				bitStream.Write((char*)packet->data, packet->length);
				bitStream.IgnoreBits(8); // Ignore ID_USER_PACKET_ENUM+1
				bitStream.Read(receivedPacketNumberReceiver);
				bitStream.Read(streamNumberReceiver);
				bitStream.Read(receivedTimeReceiver);

				if (receivedPacketNumberReceiver!=packetNumberReceiver[streamNumberReceiver])
				{

					//WARNING: If you modify the below code make sure the whole string remains in bounds, sprintf will NOT do it for you. 
					//The error string is 512 in length

					//Note: Removed buffer checking because chance is insignificant, left code if wanted in future. Needs limits.h ISO C standard.

					/*
					int maxIntWorkingCopy= INT_MAX;

					int maxIntCharLen =0; 

					while (maxIntWorkingCopy>0)
					{maxIntCharLen++;
					maxIntWorkingCopy/=10;
					}

					if (strlen(lastError)>maxIntCharLen* 3 +27)//512 should be a good len for now
					{*/

					sprintf(lastError,"Expecting %i got %i (channel %i).",packetNumberReceiver[streamNumberReceiver], receivedPacketNumberReceiver, streamNumberReceiver);

					/*
					}
					else
					{
					sprintf(lastError,"Did not get what was expected. More details can be given if the error string buffer size is increased.");

					}*/

					if (isVerbose)
					{

						RakNetStatistics *rssSender,*rssReceiver;
						char message[2048];

						rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));

						rssReceiver=receiver->GetStatistics(receiver->GetSystemAddressFromIndex(0));
						StatisticsToString(rssSender, message, 2);
						printf("Server stats %s\n", message);
						StatisticsToString(rssReceiver, message, 2);
						printf("Client stats%s", message);

						DebugTools::ShowError(lastError,!noPauses && isVerbose,__LINE__,__FILE__);
					}

					return 1;
				}
				else
					if (isVerbose)
					{
						printf("Got %i.Channel %i.Len %i.", packetNumberReceiver[streamNumberReceiver], streamNumberReceiver, packet->length);

						printf("Sent=%u Received=%u Diff=%i.\n", receivedTimeReceiver, currentTime, (int)currentTime - (int) receivedTimeReceiver);
					}

					packetNumberReceiver[streamNumberReceiver]++;
					break;
			}

			receiver->DeallocatePacket(packet);
			packet = receiver->Receive();
		}

		RakSleep(0);

		currentTime=GetTimeMS();
	}

	if (isVerbose)
	{

		RakNetStatistics *rssSender,*rssReceiver;
		char message[2048];

		rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));

		rssReceiver=receiver->GetStatistics(receiver->GetSystemAddressFromIndex(0));
		StatisticsToString(rssSender, message, 2);
		printf("Server stats %s\n", message);
		StatisticsToString(rssReceiver, message, 2);
		printf("Client stats%s", message);
	}

	if (fp)
		fclose(fp);

	return 0;
}