EnHandleResult CServerDlg::OnError(CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
	::PostOnError(dwConnID, enOperation, iErrorCode);
	Statistics();

	return HR_OK;
}
void PharmacyManagement::initUI()
{
	Receipt();
	Check();
	Inventory();
	Statistics();
}
EnHandleResult CServerDlg::OnClose(CONNID dwConnID)
{
	::PostOnClose(dwConnID);
	Statistics();

	return HR_OK;
}
int main(int argc, char **argv)
{
	double time = 0;
	struct command_line_args object;
	memset(&object,0,sizeof(struct command_line_args));
	parse_command_line(argc,argv,&object);	
	Initialize();

	gettimeofday(&GlobalStartTime,0);
	LOG(stdout, "%012.3fms: emulation begins\n",time);	
	

	pthread_sigmask(SIG_BLOCK,&signal_set,NULL);
	if(TraceDriven){
		pthread_create(&packet_thread, 0, (void *)tracedriven_packet_procedure, &object);
	}	else
		pthread_create(&packet_thread, 0, (void *)&deterministic_packet_procedure, &object);
	
	
	pthread_create(&token_thread, 0,(void *)&token_bucket_procedure,&object);
	pthread_create(&server_thread, 0,(void *)&server_procedure,&object);
	pthread_create(&interrupt_thread, 0,(void *)&handler,NULL);
	
	pthread_join(packet_thread,0);
	pthread_join(token_thread,0);
	pthread_join(server_thread,0);
	join_interrupt = 1;
	pthread_join(interrupt_thread, 0);
	gettimeofday(&GlobalEndTime,0);
	Statistics(&object);
	My402ListUnlinkAll(&Q1PacketList);
	My402ListUnlinkAll(&Q2PacketList);
	return 0;
}
Exemple #5
0
void CDynGameData::SetupPlayers() 
{
	int b;

	for(b = 0; b < iLocalPlayer.size(); b++)
	{
		CPlayer* pl = iLocalPlayer[b];

		Statistics()->AddPlayer( pl , true );

		if ( strlen( iOptions->Data().iName[b]) <= 0 )
			strcpy(pl->iName,KUnknownSoldier );
		else
//			strcpy(pl->iName,iOptions->Data().iName[b]);
			pl->SetName(iOptions->Data().iName[b]);

		if (EF_DEBUG)
			pl->iCash = 50000;
		else
            pl->iCash = 500;

		pl->iDead = 0;

		pl->SetColorByIndex( b );

		GameMode()->SetupPlayerEpisode( pl );
	}
}
Exemple #6
0
Statistics Connection::getStatistics()
{
	prechecks();
	mpd_stats *stats = mpd_run_stats(m_connection.get());
	checkErrors();
	return Statistics(stats);
}
Exemple #7
0
  void
  TreeCanvas::reset(void) {
    QMutexLocker locker(&mutex);
    Space* rootSpace =
      root->getStatus() == FAILED ? NULL : 
                           root->getSpace(*na,curBest,c_d,a_d);
    if (curBest != NULL) {
      delete curBest;
      curBest = new BestNode(NULL);
    }
    if (root) {
      DisposeCursor dc(root,*na);
      PreorderNodeVisitor<DisposeCursor>(dc).run();
    }
    delete na;
    na = new Node::NodeAllocator(curBest != NULL);
    int rootIdx = na->allocate(rootSpace);
    assert(rootIdx == 0); (void) rootIdx;
    root = (*na)[0];
    root->setMarked(true);
    currentNode = root;
    pathHead = root;
    scale = 1.0;
    stats = Statistics();
    for (int i=bookmarks.size(); i--;)
      emit removedBookmark(i);
    bookmarks.clear();
    root->layout(*na);

    emit statusChanged(currentNode, stats, true);
    update();
  }
Exemple #8
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Maximize the window
    showMaximized();

    //Show welcome message
    ui->statusBar->showMessage("Bienvenue sur BOMBERMAN.", 15000);

    // Linking buttons to action triggered
    connect(ui->actionDemarrerPartieSolo,SIGNAL(triggered()),this,SLOT(BeginPartySolo()));
    connect(ui->actionDemarrerPartieMulti,SIGNAL(triggered()),this,SLOT(BeginPartyMulti()));
    connect(ui->actionChargerPartieSolo,SIGNAL(triggered()),this,SLOT(LoadPartySolo()));
    connect(ui->actionChargerPartieMulti,SIGNAL(triggered()),this,SLOT(LoadPartyMulti()));
    connect(ui->actionSauvegarderPartieSolo,SIGNAL(triggered()),this,SLOT(SavePartySolo()));
    connect(ui->actionQuitter,SIGNAL(triggered()),this,SLOT(Quit()));
    connect(ui->actionCommandes_de_jeu,SIGNAL(triggered()),this,SLOT(GameControls()));
    connect(ui->actionAffichage,SIGNAL(triggered()),this,SLOT(DisplaySetting()));
    connect(ui->actionAudio,SIGNAL(triggered()),this,SLOT(AudioSetting()));
    connect(ui->actionAide,SIGNAL(triggered()),this,SLOT(Help()));
    connect(ui->actionA_propos,SIGNAL(triggered()),this,SLOT(Credits()));
    connect(ui->actionAffichageStatistics,SIGNAL(triggered()),this,SLOT(Statistics()));
}
void RenderMessageHandler::HandleMessage(const SceneData& sd, const ViewData&, POVMSType ident, POVMS_Object& obj)
{
	if(ident != kPOVMsgIdent_Progress)
	{
		sd.console->flush();
		if(sd.streams[STATUS_STREAM] != NULL)
			sd.streams[STATUS_STREAM]->flush();
	}

	switch(ident)
	{
		case kPOVMsgIdent_RenderOptions:
			Options(sd.console.get(), obj, sd.consoleoutput[RENDER_STREAM]);
			if(sd.streams[RENDER_STREAM].get() != NULL)
				Message2Console::RenderOptions(obj, sd.streams[RENDER_STREAM].get());
			if(sd.streams[ALL_STREAM].get() != NULL)
				Message2Console::RenderOptions(obj, sd.streams[ALL_STREAM].get());
			break;
		case kPOVMsgIdent_RenderStatistics:
			Statistics(sd.console.get(), obj, sd.consoleoutput[STATISTIC_STREAM]);
			if(sd.streams[STATISTIC_STREAM].get() != NULL)
			{
				Message2Console::RenderStatistics(obj, sd.streams[STATISTIC_STREAM].get());
				Message2Console::RenderTime(obj, sd.streams[STATISTIC_STREAM].get());
			}
			if(sd.streams[ALL_STREAM].get() != NULL)
			{
				Message2Console::RenderStatistics(obj, sd.streams[ALL_STREAM].get());
				Message2Console::RenderTime(obj, sd.streams[ALL_STREAM].get());
			}
			break;
		case kPOVMsgIdent_Progress:
			Progress(sd.console.get(), obj, sd.verbose);
//			if(sd.streams[ALL_STREAM].get() != NULL)
//				Message2Console::Progress(obj, sd.streams[ALL_STREAM]);
			break;
		case kPOVMsgIdent_Warning:
			Warning(sd.console.get(), obj, sd.consoleoutput[WARNING_STREAM]);
			if(sd.streams[WARNING_STREAM].get() != NULL)
				Message2Console::Warning(obj, sd.streams[WARNING_STREAM].get());
			if(sd.streams[ALL_STREAM].get() != NULL)
				Message2Console::Warning(obj, sd.streams[ALL_STREAM].get());
			break;
		case kPOVMsgIdent_Error:
			Error(sd.console.get(), obj, sd.consoleoutput[WARNING_STREAM]);
			if(sd.streams[WARNING_STREAM].get() != NULL)
				Message2Console::Error(obj, sd.streams[WARNING_STREAM].get());
			if(sd.streams[ALL_STREAM].get() != NULL)
				Message2Console::Error(obj, sd.streams[ALL_STREAM].get());
			break;
		case kPOVMsgIdent_FatalError:
			FatalError(sd.console.get(), obj, sd.consoleoutput[FATAL_STREAM]);
			if(sd.streams[FATAL_STREAM].get() != NULL)
				Message2Console::FatalError(obj, sd.streams[FATAL_STREAM].get());
			if(sd.streams[ALL_STREAM].get() != NULL)
				Message2Console::FatalError(obj, sd.streams[ALL_STREAM].get());
			break;
	}
}
Exemple #10
0
void cGenIndex::Work(void)
{
  eof=error=pstart=false;
  memset(fileSize,0,sizeof(fileSize));

  if(rewrite) {
    writeFile=writeName->OpenWrite();
    if(writeFile<0) {
      printf("Failed to open output file(s)\n");
      return;
      }
    }

  replayFile=fileName->Open();
  readNo=fileName->FileNumber();
  fileSize[readNo]=fileName->FileSize();
  readOffset=0;

  fileNo=rewrite ? 1 : readNo;
  fileOffset=0;
  splitOffset=splitsize*MEGABYTE(1);
  sSize=0;

  if(replayFile>=0) {
    if(index->Open()) {
      int lastoff=0;
      while(!error && NextFile()) {
        int count=read(replayFile,buff,sizeof(buff));
        if(count<0) {
          printf("read vdr: %s\n",strerror(errno));
          return;
          }
        else if(count==0) {
          if(fileSize[readNo]!=readOffset)
            printf("file %d read/size mismatch\n",readNo);
          eof=true;
          continue;
          }
        else {
          readOffset+=count;

          if(!quiet && (readOffset<lastoff || readOffset>lastoff+KILOBYTE(256)) && fileSize[readNo]) {
            printf("offset %lld %d%%\r",readOffset,(int)(readOffset*100/fileSize[readNo])); fflush(stdout);
            lastoff=readOffset;
            }

          int used=Process(buff,count);
          if(used<0) {
            error=true;
            break;
            }
          if(count-used) printf("bummer, count!=0\n");
          }
        }
      if(!error && !quiet) Statistics();
      }
    }
  else printf("Failed to open input file(s)\n");
}
Exemple #11
0
void
DisplayStatistics(struct SymTab * table)
{
  struct Stats * stats = Statistics(table);
  fprintf(stdout,"Statistics min: %d max: %d avg: %d total: %d\n",
          stats->minLen,stats->maxLen,stats->avgLen,stats->entryCnt);
  free(stats);
}
int main()
{

Statistics s;
Statistics(5);
s.random_generate();
s.mean();
s.stddev();
}
Exemple #13
0
EnHandleResult CServerDlg::OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
	iErrorCode == SE_OK ? ::PostOnClose(dwConnID)	:
	::PostOnError(dwConnID, enOperation, iErrorCode);

	Statistics();

	return HR_OK;
}
Exemple #14
0
void main()
{
	std::vector<int> count;

	ReadResultFile(count);

	Statistics(count);

	system("pause");
}
void DrugStorageManagement::initUI()
{
	
    Storage();
    Allot();
	Inventory();
	Check();
	Pricing();
	Statistics();
}
BString TorrentObject::ErrorMessage() const
{
	if( !IsAnyErrorOrWarning() )
		return B_EMPTY_STRING;
		
	//
	//
	//
	return Statistics()->errorString;	
}
void HospitalizationManagement::initUI()
{
    Registry();
    Pay();
	Charge();
	Discharge();
	InternalPayment();
	Dailyreport();
	Statistics();
}
Exemple #18
0
TError TMemorySubsystem::GetAnonUsage(TCgroup &cg, uint64_t &usage) const {
    if (cg.Has(ANON_USAGE))
        return cg.GetUint64(ANON_USAGE, usage);

    TUintMap stat;
    TError error = Statistics(cg, stat);
    if (!error)
        usage = stat["total_inactive_anon"] +
                stat["total_active_anon"] +
                stat["unevictable"] +
                stat["total_swap"];
    return error;
}
Exemple #19
0
void CDynGameData::RemoveLocalPlayer( CPlayer *aPlayer ) 
{
	CheckPlayersLiving();

	// Things to do when player dies
	// 1. Add player to dead players' list (needed so that we know how many players there was)
	// 2. Remove from local players (so that screen disappears)
	// 3. Fix mouse control (is it needed nowadays?)
	// 4. something else?

	if (iLocalPlayer.size()>1)
	{
		// Remove player from active players
		MoveToDeads( aPlayer );
		CGameStatisticsData::TPlayerStats& stat = Statistics()->PlayerStats( aPlayer );
		stat.iLevelOfDeath = CurrentLevel();
	}
}
Exemple #20
0
void Key_Handler( void )
{

    (void)SetThreadName("SaganKeyhandler");

    while(1)
        {

            int key;

            key=getchar();

            if ( key != 0 )
                {
                    Statistics();
                }

        }
}
Exemple #21
0
void Moving (Vehicle *vehicle, int clock, int obstacle, int distance, int col, char *shape)
{
    col += (distance == 0) ? 0 : int (80.0 / distance * vehicle->Position ());

    move (10, 0);
    clrtoeol ();
    attron (A_STANDOUT);

    if (col >= 76)
        mvaddstr (10, 76, shape);
    else if (col < 0)
        mvaddstr (10, 0, shape);
    else
        mvaddstr (10, col, shape);

    attroff (A_STANDOUT);

    Statistics (clock, vehicle->Position (), obstacle, distance);
}
Exemple #22
0
void Crashing (Vehicle *vehicle, int clock, int obstacle, int distance, int col)
{
    col += int (80.0 / distance * vehicle->Position ());

    beep ();
    mvaddstr (17, 19, "Look out! There's something in the road!");

    if (col < 76)
    {
        mvaddstr (9,  col, "\\|/");
        mvaddstr (11, col, "/|\\");
    }
    else
    {
        mvaddstr (9,  76, "\\|/");
        mvaddstr (11, 76, "/|\\");
    }

    Statistics (clock, vehicle->Position (), obstacle, distance);
}
Exemple #23
0
BOOL CPop3Connection::List()
{
	//Must be connected to perform a "LIST"
	if(!m_bConnected)
	{
		//m_sLastCommandResponse = _T("ͨÐÅ佨Á¢");//<%IDS_Pop3_14%>
		m_sLastCommandResponse = ::FuncGetStringFromIDS("<%IDS_Pop3_14%>");
		return FALSE;
	}
	
	//if we haven't executed the STAT command then do it now
	int nNumberOfMails = m_nNumberOfMails;
	int nTotalMailSize;
	if (!m_bStatRetrieved)
	{
		if (!Statistics(nNumberOfMails, nTotalMailSize))
		{
			//m_sLastCommandResponse = _T("·¢ËÍSTATÃüÁîʧ°Ü");//<%IDS_Pop3_15%>
			m_sLastCommandResponse = ::FuncGetStringFromIDS("<%IDS_Pop3_15%>");
			return FALSE;
		}
		else
			m_bStatRetrieved = TRUE;
	}
	
	//Send the LIST command
	char sBuf[10];
	strcpy(sBuf, "LIST\r\n");
	int nCmdLength = strlen(sBuf);
	if (!m_pop.Send(sBuf, nCmdLength))
	{
		TRACE(_T("Failed to send the LIST command to the POP3 server\n"));
		//m_sLastCommandResponse = _T("·¢ËÍLISTÃüÁîʧ°Ü");//<%IDS_Pop3_16%>
		m_sLastCommandResponse = ::FuncGetStringFromIDS("<%IDS_Pop3_16%>");
		return FALSE;
	}
	//And check the response
	m_bListRetrieved = ReadListResponse(nNumberOfMails);
	return m_bListRetrieved;
}
Exemple #24
0
	sortMethod = gcnew SortMethod(sort, &Sort::Selection);
}

array<String^>^ Manager::runSort(int setSizeModifier) {
	array<int>^ originalSet = af->MakeArray(setSizeModifier);
	String^ orginalSetStr = arrayToString(originalSet);

	array<int>^ sortedSet   = sortMethod(originalSet);
	String^ sortedSetStr = arrayToString(sortedSet);

	array<String^>^ result = { orginalSetStr, sortedSetStr };
	return result;
}

void Manager::RunTests(String^ fileName) {
	Statistics^ stats = gcnew Statistics();
	Sort^ sorter = gcnew Sort(stats);
	stats->OpenFile(fileName);

	stats->WriteToFile("Bubble Sort");
	SortMethod^ bubble = gcnew SortMethod(sorter, &Sort::Bubble);
	RunTest(bubble, stats);

	stats->WriteToFile("Insertion Sort");
	SortMethod^ insert = gcnew SortMethod(sorter, &Sort::Insertion);
	RunTest(insert, stats);

	stats->WriteToFile("Merge Sort");
	SortMethod^ merge = gcnew SortMethod(sorter, &Sort::Merge);
	RunTest(merge, stats);
Exemple #25
0
WebContext::Statistics& WebContext::statistics()
{
    static Statistics statistics = Statistics();

    return statistics;
}
void StarSystem::Statistics::CheckVitals( StarSystem *ss )
{
    int faction = FactionUtil::GetFactionIndex( UniverseUtil::GetGalaxyFaction( ss->getFileName() ) );
    if (faction != system_faction) {
        *this = Statistics();                    //invoke copy constructor to clear it
        this->system_faction = faction;
        Unit *un;
        for (un_iter ui = ss->getUnitList().createIterator();
             (un = *ui) != NULL;
             ++ui)
            this->AddUnit( un );                 //siege will take some time
        return;                                          //no need to check vitals now, they're all set
    }
    size_t iter = navCheckIter;
    int    k    = 0;
    if ( iter >= navs[0].size() ) {
        iter -= navs[0].size();
        k     = 1;
    }
    if ( iter >= navs[1].size() ) {
        iter -= navs[1].size();
        k     = 2;
    }
    size_t totalnavchecking = 25;
    size_t totalsyschecking = 25;
    while ( iter < totalnavchecking && iter < navs[k].size() ) {
        if (navs[k][iter].GetUnit() == NULL) {
            navs[k].erase( navs[k].begin()+iter );
        } else {
            ++iter;
            ++navCheckIter;
        }
    }
    if ( k == 2 && iter >= navs[k].size() )
        navCheckIter = 0;                        //start over next time
    size_t sortedsize = ss->collidemap[Unit::UNIT_ONLY]->sorted.size();
    int    sysfac     = system_faction;
    size_t counter    = checkIter+totalsyschecking;
    for (; checkIter < counter && checkIter < sortedsize; ++checkIter) {
        Collidable *collide = &ss->collidemap[Unit::UNIT_ONLY]->sorted[checkIter];
        if (collide->radius > 0) {
            Unit *un  = collide->ref.unit;
            float rel = UnitUtil::getRelationFromFaction( un, sysfac );
            if ( FactionUtil::isCitizenInt( un->faction ) ) {
                ++newcitizencount;
            } else {
                if (rel > 0.05)
                    ++newfriendlycount;
                else if (rel < 0.)
                    ++newenemycount;
                else
                    ++newneutralcount;
            }
        }
    }
    if (checkIter >= sortedsize && sortedsize
        > (unsigned int) (enemycount+neutralcount+friendlycount
                          +citizencount)/4 /*suppose at least 1/4 survive a given frame*/) {
        citizencount     = newcitizencount;
        newcitizencount  = 0;
        enemycount = newenemycount;
        newenemycount    = 0;
        neutralcount     = newneutralcount;
        newneutralcount  = 0;
        friendlycount    = newfriendlycount;
        newfriendlycount = 0;
        checkIter = 0;                           //start over with list
    }
}
Exemple #27
0
  void Histogram::InitializeFromCube(Cube &cube, const int band, Progress *progress) {
    // Make sure band is valid
    if ((band < 0) || (band > cube.Bands())) {
      string msg = "Invalid band in [Histogram constructor]";
      throw Isis::iException::Message(Isis::iException::Programmer,msg,_FILEINFO_);
    }

    double min,max;
    int nbins;

    if (cube.PixelType() == Isis::UnsignedByte) {
      min = 0.0 * cube.Multiplier() + cube.Base();
      max = 255.0 * cube.Multiplier() + cube.Base();
      nbins = 256;
    }
    else if (cube.PixelType() == Isis::SignedWord) {
      min = -32768.0 * cube.Multiplier() + cube.Base();
      max = 32767.0 * cube.Multiplier() + cube.Base();
      nbins = 65536;
    }
    else if (cube.PixelType() == Isis::Real) {
      // Determine the band for statistics
      int bandStart = band;
      int bandStop = band;
      int maxSteps = cube.Lines();
      if (band == 0){
        bandStart = 1;
        bandStop = cube.Bands();
        maxSteps = cube.Lines() * cube.Bands();
      }

      // Construct a line buffer manager and a statistics object
      LineManager line(cube);
      Statistics stats = Statistics();

      // Prep for reporting progress if necessary
      if (progress != NULL) {
        string save = progress->Text ();
        progress->SetText("Computing min/max for histogram");
        progress->SetMaximumSteps(maxSteps);
        progress->CheckStatus();
      }

      for (int useBand = bandStart ; useBand <= bandStop ; useBand++){
        // Loop and get the statistics for a good minimum/maximum
        for (int i=1; i<=cube.Lines(); i++) {
          line.SetLine(i,useBand);
          cube.Read(line);
          stats.AddData (line.DoubleBuffer(),line.size());
          if (progress != NULL) progress->CheckStatus();
        }
      }

      // Get the min/max for constructing a histogram object
      if (stats.ValidPixels() == 0) {
        min = 0.0;
        max = 1.0;
      }
      else {
        min = stats.BestMinimum ();
        max = stats.BestMaximum ();
      }

      nbins = 65536;
    }
    else {
      std::string msg = "Unsupported pixel type";
      throw iException::Message(Isis::iException::Programmer,msg,_FILEINFO_);
    }

    // Set the bins and range
    SetBinRange(min,max);
    SetBins(nbins);
  }
Exemple #28
0
int main(int argc, char *argv[]) {

#ifdef EPETRA_MPI
  MPI_Init(&argc,&argv);
  Epetra_MpiComm Comm (MPI_COMM_WORLD);
#else
  Epetra_SerialComm Comm;
#endif

  cout << Comm << endl;

  int MyPID = Comm.MyPID();

  bool verbose = false;
  bool verbose1 = true;
  if (MyPID==0) verbose = true;

  if(argc < 2 && verbose) {
    cerr << "Usage: " << argv[0] 
	 << " HB_filename [level_fill [level_overlap [absolute_threshold [ relative_threshold]]]]" << endl
	 << "where:" << endl
	 << "HB_filename        - filename and path of a Harwell-Boeing data set" << endl
	 << "level_fill         - The amount of fill to use for ILU(k) preconditioner (default 0)" << endl
	 << "level_overlap      - The amount of overlap used for overlapping Schwarz subdomains (default 0)" << endl
	 << "absolute_threshold - The minimum value to place on the diagonal prior to factorization (default 0.0)" << endl
	 << "relative_threshold - The relative amount to perturb the diagonal prior to factorization (default 1.0)" << endl << endl
	 << "To specify a non-default value for one of these parameters, you must specify all" << endl
	 << " preceding values but not any subsequent parameters. Example:" << endl
	 << "ifpackHpcSerialMsr.exe mymatrix.hpc 1  - loads mymatrix.hpc, uses level fill of one, all other values are defaults" << endl
	 << endl;
    return(1);

  }

  // Uncomment the next three lines to debug in mpi mode
  //int tmp;
  //if (MyPID==0) cin >> tmp;
  //Comm.Barrier();

  Epetra_Map * readMap;
  Epetra_CrsMatrix * readA; 
  Epetra_Vector * readx; 
  Epetra_Vector * readb;
  Epetra_Vector * readxexact;
   
  // Call routine to read in HB problem
  Trilinos_Util_ReadHb2Epetra(argv[1], Comm, readMap, readA, readx, readb, readxexact);

  // Create uniform distributed map
  Epetra_Map map(readMap->NumGlobalElements(), 0, Comm);

  // Create Exporter to distribute read-in matrix and vectors

  Epetra_Export exporter(*readMap, map);
  Epetra_CrsMatrix A(Copy, map, 0);
  Epetra_Vector x(map);
  Epetra_Vector b(map);
  Epetra_Vector xexact(map);

  Epetra_Time FillTimer(Comm);
  x.Export(*readx, exporter, Add);
  b.Export(*readb, exporter, Add);
  xexact.Export(*readxexact, exporter, Add);
  Comm.Barrier();
  double vectorRedistributeTime = FillTimer.ElapsedTime();
  A.Export(*readA, exporter, Add);
  Comm.Barrier();
  double matrixRedistributeTime = FillTimer.ElapsedTime() - vectorRedistributeTime;
  assert(A.FillComplete()==0);    
  Comm.Barrier();
  double fillCompleteTime = FillTimer.ElapsedTime() - matrixRedistributeTime;
  if (Comm.MyPID()==0)	{
    cout << "\n\n****************************************************" << endl;
    cout << "\n Vector redistribute  time (sec) = " << vectorRedistributeTime<< endl;
    cout << "    Matrix redistribute time (sec) = " << matrixRedistributeTime << endl;
    cout << "    Transform to Local  time (sec) = " << fillCompleteTime << endl<< endl;
  }
  Epetra_Vector tmp1(*readMap);
  Epetra_Vector tmp2(map);
  readA->Multiply(false, *readxexact, tmp1);

  A.Multiply(false, xexact, tmp2);
  double residual;
  tmp1.Norm2(&residual);
  if (verbose) cout << "Norm of Ax from file            = " << residual << endl;
  tmp2.Norm2(&residual);
  if (verbose) cout << "Norm of Ax after redistribution = " << residual << endl << endl << endl;

  //cout << "A from file = " << *readA << endl << endl << endl;

  //cout << "A after dist = " << A << endl << endl << endl;

  delete readA;
  delete readx;
  delete readb;
  delete readxexact;
  delete readMap;

  Comm.Barrier();

  bool smallProblem = false;
  if (A.RowMap().NumGlobalElements()<100) smallProblem = true;

  if (smallProblem)
    cout << "Original Matrix = " << endl << A   << endl;

  x.PutScalar(0.0);

  Epetra_LinearProblem FullProblem(&A, &x, &b);
  double normb, norma;
  b.NormInf(&normb);
  norma = A.NormInf();
  if (verbose)
    cout << "Inf norm of Original Matrix = " << norma << endl
	 << "Inf norm of Original RHS    = " << normb << endl;
  
  Epetra_Time ReductionTimer(Comm);
  Epetra_CrsSingletonFilter SingletonFilter;
  Comm.Barrier();
  double reduceInitTime = ReductionTimer.ElapsedTime();
  SingletonFilter.Analyze(&A);
  Comm.Barrier();
  double reduceAnalyzeTime = ReductionTimer.ElapsedTime() - reduceInitTime;

  if (SingletonFilter.SingletonsDetected())
    cout << "Singletons found" << endl;
  else {
    cout << "Singletons not found" << endl;
    exit(1);
  }
  SingletonFilter.ConstructReducedProblem(&FullProblem);
  Comm.Barrier();
  double reduceConstructTime = ReductionTimer.ElapsedTime() - reduceInitTime;

  double totalReduceTime = ReductionTimer.ElapsedTime();

  if (verbose)
    cout << "\n\n****************************************************" << endl
	 << "    Reduction init  time (sec)           = " << reduceInitTime<< endl
	 << "    Reduction Analyze time (sec)         = " << reduceAnalyzeTime << endl
	 << "    Construct Reduced Problem time (sec) = " << reduceConstructTime << endl
	 << "    Reduction Total time (sec)           = " << totalReduceTime << endl<< endl;

  Statistics(SingletonFilter);

  Epetra_LinearProblem * ReducedProblem = SingletonFilter.ReducedProblem();

  Epetra_CrsMatrix * Ap = dynamic_cast<Epetra_CrsMatrix *>(ReducedProblem->GetMatrix());
  Epetra_Vector * bp = (*ReducedProblem->GetRHS())(0);
  Epetra_Vector * xp = (*ReducedProblem->GetLHS())(0);
  

  if (smallProblem)
    cout << " Reduced Matrix = " << endl << *Ap << endl
	 << " LHS before sol = " << endl << *xp << endl
	 << " RHS            = " << endl << *bp << endl;

  // Construct ILU preconditioner

  double elapsed_time, total_flops, MFLOPs;
  Epetra_Time timer(Comm);

  int LevelFill = 0;
  if (argc > 2)  LevelFill = atoi(argv[2]);
  if (verbose) cout << "Using Level Fill = " << LevelFill << endl;
  int Overlap = 0;
  if (argc > 3) Overlap = atoi(argv[3]);
  if (verbose) cout << "Using Level Overlap = " << Overlap << endl;
  double Athresh = 0.0;
  if (argc > 4) Athresh = atof(argv[4]);
  if (verbose) cout << "Using Absolute Threshold Value of = " << Athresh << endl;

  double Rthresh = 1.0;
  if (argc > 5) Rthresh = atof(argv[5]);
  if (verbose) cout << "Using Relative Threshold Value of = " << Rthresh << endl;

  Ifpack_IlukGraph * IlukGraph = 0;
  Ifpack_CrsRiluk * ILUK = 0;

  if (LevelFill>-1) {
    elapsed_time = timer.ElapsedTime();
    IlukGraph = new Ifpack_IlukGraph(Ap->Graph(), LevelFill, Overlap);
    assert(IlukGraph->ConstructFilledGraph()==0);
    elapsed_time = timer.ElapsedTime() - elapsed_time;
    if (verbose) cout << "Time to construct ILUK graph = " << elapsed_time << endl;


    Epetra_Flops fact_counter;
  
    elapsed_time = timer.ElapsedTime();
    ILUK = new Ifpack_CrsRiluk(*IlukGraph);
    ILUK->SetFlopCounter(fact_counter);
    ILUK->SetAbsoluteThreshold(Athresh);
    ILUK->SetRelativeThreshold(Rthresh);
    //assert(ILUK->InitValues()==0);
    int initerr = ILUK->InitValues(*Ap);
    if (initerr!=0) {
      cout << endl << Comm << endl << "  InitValues error = " << initerr;
      if (initerr==1) cout << "  Zero diagonal found, warning error only";
      cout << endl << endl;
    }
    assert(ILUK->Factor()==0);
    elapsed_time = timer.ElapsedTime() - elapsed_time;
    total_flops = ILUK->Flops();
    MFLOPs = total_flops/elapsed_time/1000000.0;
    if (verbose) cout << "Time to compute preconditioner values = " 
		    << elapsed_time << endl
		    << "MFLOPS for Factorization = " << MFLOPs << endl;
    //cout << *ILUK << endl;
  double Condest;
  ILUK->Condest(false, Condest);

  if (verbose) cout << "Condition number estimate for this preconditioner = " << Condest << endl;
  }
  int Maxiter = 100;
  double Tolerance = 1.0E-8;

  Epetra_Flops counter;
  Ap->SetFlopCounter(counter);
  xp->SetFlopCounter(*Ap);
  bp->SetFlopCounter(*Ap);
  if (ILUK!=0) ILUK->SetFlopCounter(*Ap);

  elapsed_time = timer.ElapsedTime();

  double normreducedb, normreduceda;
  bp->NormInf(&normreducedb);
  normreduceda = Ap->NormInf();
  if (verbose) 
    cout << "Inf norm of Reduced Matrix = " << normreduceda << endl
	 << "Inf norm of Reduced RHS    = " << normreducedb << endl;

  BiCGSTAB(*Ap, *xp, *bp, ILUK, Maxiter, Tolerance, &residual, verbose);

  elapsed_time = timer.ElapsedTime() - elapsed_time;
  total_flops = counter.Flops();
  MFLOPs = total_flops/elapsed_time/1000000.0;
  if (verbose) cout << "Time to compute solution = " 
		    << elapsed_time << endl
		    << "Number of operations in solve = " << total_flops << endl
		    << "MFLOPS for Solve = " << MFLOPs<< endl << endl;

  SingletonFilter.ComputeFullSolution();

  if (smallProblem)
  cout << " Reduced LHS after sol = " << endl << *xp << endl
       << " Full    LHS after sol = " << endl << x << endl
       << " Full  Exact LHS         = " << endl << xexact << endl;

  Epetra_Vector resid(x);

  resid.Update(1.0, x, -1.0, xexact, 0.0); // resid = xcomp - xexact

  resid.Norm2(&residual);
  double normx, normxexact;
  x.Norm2(&normx);
  xexact.Norm2(&normxexact);

  if (verbose) 
    cout << "2-norm of computed solution                               = " << normx << endl
	 << "2-norm of exact solution                                  = " << normxexact << endl
	 << "2-norm of difference between computed and exact solution  = " << residual << endl;
    
  if (verbose1 && residual>1.0e-5) {
    if (verbose)
      cout << "Difference between computed and exact solution appears large..." << endl
	   << "Computing norm of A times this difference.  If this norm is small, then matrix is singular"
	   << endl;
    Epetra_Vector bdiff(b);
    assert(A.Multiply(false, resid, bdiff)==0);
    assert(bdiff.Norm2(&residual)==0);
    if (verbose) 
      cout << "2-norm of A times difference between computed and exact solution  = " << residual << endl;
    
  }
  if (verbose) 
    cout << "********************************************************" << endl
	 << "              Solving again with 2*Ax=2*b" << endl
	 << "********************************************************" << endl;

  A.Scale(1.0); // A = 2*A
  b.Scale(1.0); // b = 2*b
  x.PutScalar(0.0);
  b.NormInf(&normb);
  norma = A.NormInf();
  if (verbose)
    cout << "Inf norm of Original Matrix = " << norma << endl
	 << "Inf norm of Original RHS    = " << normb << endl;
  double updateReducedProblemTime = ReductionTimer.ElapsedTime();
  SingletonFilter.UpdateReducedProblem(&FullProblem);
  Comm.Barrier();
  updateReducedProblemTime = ReductionTimer.ElapsedTime() - updateReducedProblemTime;
  if (verbose)
    cout << "\n\n****************************************************" << endl
	 << "    Update Reduced Problem time (sec)           = " << updateReducedProblemTime<< endl
	 << "****************************************************" << endl;
  Statistics(SingletonFilter);

  if (LevelFill>-1) {

    Epetra_Flops fact_counter;
  
    elapsed_time = timer.ElapsedTime();

    int initerr = ILUK->InitValues(*Ap);
    if (initerr!=0) {
      cout << endl << Comm << endl << "  InitValues error = " << initerr;
      if (initerr==1) cout << "  Zero diagonal found, warning error only";
      cout << endl << endl;
    }
    assert(ILUK->Factor()==0);
    elapsed_time = timer.ElapsedTime() - elapsed_time;
    total_flops = ILUK->Flops();
    MFLOPs = total_flops/elapsed_time/1000000.0;
    if (verbose) cout << "Time to compute preconditioner values = " 
		    << elapsed_time << endl
		    << "MFLOPS for Factorization = " << MFLOPs << endl;
    double Condest;
    ILUK->Condest(false, Condest);
    
    if (verbose) cout << "Condition number estimate for this preconditioner = " << Condest << endl;
  }
  bp->NormInf(&normreducedb);
  normreduceda = Ap->NormInf();
  if (verbose) 
    cout << "Inf norm of Reduced Matrix = " << normreduceda << endl
	 << "Inf norm of Reduced RHS    = " << normreducedb << endl;

  BiCGSTAB(*Ap, *xp, *bp, ILUK, Maxiter, Tolerance, &residual, verbose);

  elapsed_time = timer.ElapsedTime() - elapsed_time;
  total_flops = counter.Flops();
  MFLOPs = total_flops/elapsed_time/1000000.0;
  if (verbose) cout << "Time to compute solution = " 
		    << elapsed_time << endl
		    << "Number of operations in solve = " << total_flops << endl
		    << "MFLOPS for Solve = " << MFLOPs<< endl << endl;

  SingletonFilter.ComputeFullSolution();

  if (smallProblem)
  cout << " Reduced LHS after sol = " << endl << *xp << endl
       << " Full    LHS after sol = " << endl << x << endl
       << " Full  Exact LHS         = " << endl << xexact << endl;

  resid.Update(1.0, x, -1.0, xexact, 0.0); // resid = xcomp - xexact

  resid.Norm2(&residual);
  x.Norm2(&normx);
  xexact.Norm2(&normxexact);

  if (verbose) 
    cout << "2-norm of computed solution                               = " << normx << endl
	 << "2-norm of exact solution                                  = " << normxexact << endl
	 << "2-norm of difference between computed and exact solution  = " << residual << endl;
    
  if (verbose1 && residual>1.0e-5) {
    if (verbose)
      cout << "Difference between computed and exact solution appears large..." << endl
	   << "Computing norm of A times this difference.  If this norm is small, then matrix is singular"
	   << endl;
    Epetra_Vector bdiff(b);
    assert(A.Multiply(false, resid, bdiff)==0);
    assert(bdiff.Norm2(&residual)==0);
    if (verbose) 
      cout << "2-norm of A times difference between computed and exact solution  = " << residual << endl;
    
  }
 


  if (ILUK!=0) delete ILUK;
  if (IlukGraph!=0) delete IlukGraph;
				       
#ifdef EPETRA_MPI
  MPI_Finalize() ;
#endif

return 0 ;
}
Exemple #29
0
WebProcessPool::Statistics& WebProcessPool::statistics()
{
    static Statistics statistics = Statistics();

    return statistics;
}
Exemple #30
0
/////////////////////////////
// Fenetre Background gestion des appels TCP
//
LRESULT CALLBACK TftpClientProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
DWORD          nbWrt;
struct tftphdr *tpr, *tps;
time_t            dNow;
int             Ark;
HWND            hCBWnd, hParentWnd;

  time (&dNow);
  switch (message)
  {

    /////////////////////////
    // Message Windows

    case WM_INITCLIENT :
      // only one client transfer available
      hTftpClientSemaphore = CreateSemaphore(NULL, 1, 1, TFTP_CLIENT_SEMAPHORE);

         hTftpClientWnd = hWnd;
        hParentWnd = GetParent (hWnd);
         EnableWindow (GetDlgItem (hParentWnd, IDC_CLIENT_BREAK_BUTTON), FALSE);
         SetDlgItemText (hParentWnd, IDC_CLIENT_BLOCK, "");

       // populate combo with proposed block sizes
        hCBWnd = GetDlgItem (hParentWnd, IDC_CB_DATASEG);
      for (Ark=0 ;  Ark<SizeOfTab (tBlkSize); Ark++)
                ComboBox_AddString (hCBWnd, tBlkSize[Ark].szBlkSize);
       ComboBox_SetCurSel (hCBWnd, 0);

       // uncheck "Send full path to server"
      SendDlgItemMessage (hParentWnd, IDC_CLIENT_FULL_PATH, BM_SETCHECK, BST_UNCHECKED, 0);   

      // edittext IDC_CLIENT_FILE will accept dropped file (works only because it is on the top in Z-Order
       DragAcceptFiles (GetDlgItem (hParentWnd, IDC_CLIENT_LOCALFILE), TRUE);
          // fEditBoxProc = (WNDPROC) SetWindowLong (GetDlgItem (hParentWnd, IDC_CLIENT_LOCALFILE), GWL_WNDPROC, (LONG) TftpClientFileNameProc);
          fEditBoxProc = (WNDPROC) SetWindowLongPtr (GetDlgItem (hParentWnd, IDC_CLIENT_LOCALFILE), GWLP_WNDPROC, (LONG_PTR) TftpClientFileNameProc);
//    SetWindowLong (GetDlgItem (hParentWnd, IDC_CLIENT_FILE), GWL_USERDATA, (LONG) TftpClientFileNameProc);
    SetWindowLongPtr (GetDlgItem (hParentWnd, IDC_CLIENT_LOCALFILE), GWLP_USERDATA, (LONG_PTR) TftpClientFileNameProc);
         break;

    case WM_CLOSE :
LogToMonitor ("GUI: Closing Tftp Client");
         CloseHandle (hTftpClientSemaphore);
         CloseHandle (sTC.hFile);
         closesocket (sTC.s);
         break;

    case WM_COMMAND :
          Handle_VM_Command (hWnd, wParam, lParam);
          break;


    case WM_TIMER :
         KillTimer(hWnd, wParam);
         PostMessage (hWnd, wParam, 0, (LPARAM) -1);    // pour pas confondre
         break;

      //////////////////////
      // Download : fichier envoyé par le serveur
     case WM_CLIENT_DATA :
        // WSAAsyncSelect (sTC.s, hWnd, 0, 0);  A SUPPRIMER
        KillTimer(hWnd, wParam);
        if (sTC.bBreak) return FALSE;
        sTC.nRcvd = 0;
        // On est reveillé par un message reçu
        tpr = (struct tftphdr *) sTC.BufRcv;
        if (WSAGETSELECTEVENT(lParam) == FD_READ)
        {
            if (! UdpRecv ())
                return BadEndOfTransfer ("Error in Recv.\nError code is %d (%s)", WSAGetLastError (), LastErrorText() );
          // parcours des codes retours
          switch (htons (tpr->th_opcode))
            {
              case TFTP_ERROR :
                   return BadEndOfTransfer ("Server stops the transfer.\nError #%d: %s", htons (tpr->th_code), tpr->th_msg);
             case TFTP_OACK :
                    if (sTC.nCount==0) TftpProcessOACK ();
                     break;
                case TFTP_DATA :
                   // a data packet has been received. Check #block
                   if ( htons (tpr->th_block) == (unsigned short) (sTC.nCount+1) )
                    {
                      if (     !WriteFile (sTC.hFile, tpr->th_data, sTC.nRcvd - TFTP_DATA_HEADERSIZE, & nbWrt, NULL)
                          ||  sTC.nRcvd-TFTP_DATA_HEADERSIZE!=nbWrt)
                            return BadEndOfTransfer ("Error in writing file.\nError code is %d (%s)", GetLastError(), LastErrorText());
                       sTC.nCount++;
                       sTC.nRetransmit = 0;
                       // prepare Ack block
                       tps = (struct tftphdr *) sTC.BufSnd;
                       tps->th_opcode = htons (TFTP_ACK),  tps->th_block = htons ((unsigned short) sTC.nCount);
                       sTC.nToSend = TFTP_DATA_HEADERSIZE;
                       // compute MD5
                       MD5Update (& sTC.m.ctx, tpr->th_data, nbWrt);
                    }
                  break;
             default :
                 return BadEndOfTransfer ("Server sent illegal opcode %d", htons (tpr->th_opcode));
          } // switch opcode
        } // il y a un message à recevoir
        // La comparaison marche si le paquet est le bon ou une répétition du précédent message
        if ( htons (tpr->th_block) == (unsigned short) sTC.nCount)
        {
           if (sTC.nRetransmit)  sTC.nTotRetrans ++;
           if (sTC.nRetransmit++ > TFTP_RETRANSMIT)
                return BadEndOfTransfer ("Timeout waiting block #%d", sTC.nCount+1);
            send (sTC.s, sTC.BufSnd, sTC.nToSend, 0);
            SetTimer (hWnd, WM_CLIENT_DATA, sTC.dwTimeout, NULL);
        }
      // sTC.nRcvd ne peut être inférieur que si on a reçu un block
        if (  htons (tpr->th_opcode)==TFTP_DATA
          &&  sTC.nRcvd!=0
           && sTC.nRcvd < sTC.nPktSize + TFTP_DATA_HEADERSIZE)
                    return TransferOK (dNow);
      Statistics (dNow);
        break;

     ////////////////////////
    // Upload : server sends ACK
     case WM_CLIENT_ACK :
        KillTimer(hWnd, wParam);
       if (sTC.bBreak  ||  sTC.s==INVALID_SOCKET) return FALSE;
       
       // socket not closed by StopTransfer
        tpr = (struct tftphdr *) sTC.BufRcv;
        if ( WSAGETSELECTEVENT(lParam) == FD_READ )
        {
            if (! UdpRecv ())
                return BadEndOfTransfer ("Error in Recv.\nError code is %d (%s)", WSAGetLastError (), LastErrorText() );
            switch (htons (tpr->th_opcode))
            {
              case TFTP_ERROR :
                   return BadEndOfTransfer ("Server stops the transfer.\nError #%d: %s", htons (tpr->th_code), tpr->th_msg);

                case TFTP_OACK :
                    if (sTC.nCount!=0)  break; // ignore message
                   TftpProcessOACK ();
                    tpr->th_block = htons(0);  // pour passer en dessous
                   // Fall through

              case TFTP_ACK :
                    if ( htons (tpr->th_block) == (unsigned short) sTC.nCount )
                    {
                      // prepare Data block
                       tps = (struct tftphdr *) sTC.BufSnd;
                       if ( !ReadFile (sTC.hFile, tps->th_data, sTC.nPktSize, & sTC.nRcvd, NULL) )
                       {
                          if (sTC.nToSend == TFTP_DATA_HEADERSIZE + sTC.nPktSize)  // file was exactly N * PkSize
                                  return TransferOK (dNow);
                            else  return BadEndOfTransfer ("Error in reading file.\nError code is %d (%s)", GetLastError(), LastErrorText());
                       }
                       if (sTC.nRcvd == 0) // EOF 
                        {
                          if (sTC.nToSend < TFTP_DATA_HEADERSIZE + sTC.nPktSize) 
                                return TransferOK (dNow);
                      }
                      sTC.nCount++;
                      sTC.nRetransmit = 0;
                      tps->th_opcode = htons (TFTP_DATA),  tps->th_block = htons ((unsigned short) sTC.nCount);
                      sTC.nToSend = TFTP_DATA_HEADERSIZE + sTC.nRcvd;
                      // compute MD5
                      MD5Update (& sTC.m.ctx, tps->th_data, sTC.nRcvd);
                    }
                  break;
             default :
                   return BadEndOfTransfer ("Server sent illegal opcode %d", htons (tpr->th_opcode));
            } // switch opcode
        } // il y a un message à recevoir

        // Timeout or ack of previous block
        else if ( htons (tpr->th_block) == (unsigned short) (sTC.nCount-1) )
        {
           if (sTC.nRetransmit)  sTC.nTotRetrans ++;
           if (sTC.nRetransmit++ > TFTP_RETRANSMIT)
                return BadEndOfTransfer ("Timeout while waiting ack block #%d", sTC.nCount);
            // une possibilité : on est au dernier message et le serveur TFTP n'a pas acquitté
            // --> on renvoie, mais sur Timeout, on signale un transfert OK
            if (sTC.nToSend < TFTP_DATA_HEADERSIZE + sTC.nPktSize  &&  sTC.nRetransmit<TFTP_RETRANSMIT)
                return TransferOK (dNow);
        }

        send (sTC.s, sTC.BufSnd, sTC.nToSend, 0);
        SetTimer (hWnd, WM_CLIENT_ACK, sTC.dwTimeout, NULL);
      Statistics (dNow);
        break;
   } // switch message

return DefWindowProc (hWnd, message, wParam, lParam);
} // TftpProc