<commit_before>// Example of analysis class for the H1 data using code generated by MakeProxy.
// ===========================================================================
//
// This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.
// One can access these data sets (277 MBytes) from the standard Root web site
// at:       ftp://root.cern.ch/root/h1analysis/
// The Physics plots below generated by this example cannot be produced when
// using smaller data sets.
//
// There are several ways to analyze data stored in a Root Tree
//   -Using TTree::Draw: This is very convenient and efficient for small tasks.
//     A TTree::Draw call produces one histogram at the time. The histogram
//     is automatically generated. The selection expression may be specified
//     in the command line.
//
//   -Using the TTreeViewer: This is a graphical interface to TTree::Draw
//      with the same functionality.
//
//   -Using the code generated by TTree::MakeClass: In this case, the user
//      creates an instance of the analysis class. He has the control over
//      the event loop and he can generate an unlimited number of histograms.
//
//   -Using the code generated by TTree::MakeSelector. Like for the code
//      generated by TTree::MakeClass, the user can do complex analysis.
//      However, he cannot control the event loop. The event loop is controlled
//      by TTree::Process called by the user. This solution is illustrated
//      by the current code. The advantage of this method is that it can be run
//      in a parallel environment using PROOF (the Parallel Root Facility).
//
// A chain of 4 files (originally converted from PAW ntuples) is used
// to illustrate the various ways to loop on Root data sets.
// Each data set contains a Root Tree named "h42"
// The class definition in h1analysis.h has been generated automatically
// by the Root utility TTree::MakeSelector using one of the files with the
// following statement:
//       h42->MakeSelector("h1analysis");
// This produces two files: h1analysis.h and h1analysis.C (skeleton of this file)
// The h1analysis class is derived from the Root class TSelector.
//
// The following members functions are called by the TTree::Process functions.
//    Begin():      called everytime a loop on the tree starts.
//                  a convenient place to create your histograms.
//    SlaveBegin():
//
//    Notify():     This function is called at the first entry of a new Tree
//                  in a chain.
//    Process():    called to analyze each entry.
//
//    SlaveTerminate():
//
//    Terminate():    called at the end of a loop on a TTree.
//                  a convenient place to draw/fit your histograms.
//
//   To use this file, try the following session
//
// Root > gROOT->Time(); //will show RT & CPU time per command
//
//==>   A-  create a TChain with the 4 H1 data files
// The chain can be created by executed the short macro h1chain.C below:
// {
//   TChain chain("h42");
//   chain.Add("$H1/dstarmb.root");  //  21330730 bytes  21920 events
//   chain.Add("$H1/dstarp1a.root"); //  71464503 bytes  73243 events
//   chain.Add("$H1/dstarp1b.root"); //  83827959 bytes  85597 events
//   chain.Add("$H1/dstarp2.root");  // 100675234 bytes 103053 events
//   //where $H1 is a system symbol pointing to the H1 data directory.
// }
//
// Root > .x h1chain.C
//
//==>   B- loop on all events
// Root > chain.Process("h1analysis.C")
//
//==>   C- same as B, but in addition fill the event list with selected entries.
// The event list is saved to a file "elist.root" by the Terminate function.
// To see the list of selected events, you can do elist->Print("all").
// The selection function has selected 7525 events out of the 283813 events
// in the chain of files. (2.65 per cent)
// Root > chain.Process("h1analysis.C","fillList")
//
//==>   D- Process only entries in the event list
// The event list is read from the file in elist.root generated by step C
// Root > chain.Process("h1analysis.C","useList")
//
//==>   E- the above steps have been executed via the interpreter.
//      You can repeat the steps B, C and D using the script compiler
//      by replacing "h1analysis.C" by "h1analysis.C+" or "h1analysis.C++"
//
// in a new session with ,eg:
//
//==>   F- Create the chain as in A, then execute
// Root > chain.Process("h1analysis.C+","useList")
//
// The commands executed with the 4 different methods B,C,D and E
// produce two canvases shown below:
// begin_html the Dstar plot end_html
// begin_html the Tau D0 plot end_html
//
//Author; Philippe Canal from original h1analysis.C by Rene Brun

TEventList *elist;
Bool_t useList, fillList;
TH1F *hdmd;
TH2F *h2;

//_____________________________________________________________________
void h1analysisProxy_Begin(TTree * /* tree */ )
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (begin) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");
}

//_____________________________________________________________________
void h1analysisProxy_SlaveBegin(TTree *tree)
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //initialize the Tree branch addresses
   Init(tree);

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (slave) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");

   //create histograms
   hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17);
   h2   = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6);

   fOutput->Add(hdmd);
   fOutput->Add(h2);

   //process cases with event list
   fillList = kFALSE;
   useList  = kFALSE;
   tree->SetEventList(0);
   delete gDirectory->GetList()->FindObject("elist");

   // case when one creates/fills the event list
   if (option.Contains("fillList")) {
      fillList = kTRUE;
      elist = new TEventList("elist","selection from Cut",5000);
   } else elist = 0;

   // case when one uses the event list generated in a previous call
   if (option.Contains("useList")) {
      useList  = kTRUE;
      TFile f("elist.root");
      elist = (TEventList*)f.Get("elist");
      if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist
      tree->SetEventList(elist);
   }

}

Double_t h1analysisProxy() {
   return 0;
}

//_____________________________________________________________________
Bool_t h1analysisProxy_Process(Long64_t entry)
{
// entry is the entry number in the current Tree
// Selection function to select D* and D0.

   //in case one event list is given in input, the selection has already been done.
   if (!useList) {

      float f1 = md0_d;
      float f2 = md0_d-1.8646;
      bool test = TMath::Abs(md0_d-1.8646) >= 0.04;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;
      if (ptds_d <= 2.5) return kFALSE;
      if (TMath::Abs(etads_d) >= 1.5) return kFALSE;

      int cik = ik-1;    //original ik used f77 convention starting at 1
      int cipi = ipi-1;  //original ipi used f77 convention starting at 1

      f1 = nhitrp[cik];
      f2 = nhitrp[cipi];
      test = nhitrp[cik]*nhitrp[cipi] <= 1;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;
      if (rend[cik] -rstart[cik]  <= 22) return kFALSE;
      if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;
      if (nlhk[cik] <= 0.1)    return kFALSE;
      if (nlhpi[cipi] <= 0.1)  return kFALSE;
      // fix because read-only
      if (nlhpi[ipis-1] <= 0.1) return kFALSE;
      if (njets < 1)          return kFALSE;

   }
   // if option fillList, fill the event list
   if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));

   //fill some histograms
   hdmd->Fill(dm_d);
   h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d);

   return kTRUE;
}

//_____________________________________________________________________
void h1analysisProxy_SlaveTerminate()
{
   // nothing to be done
   printf("Terminate (slave) h1analysis\n");
}

//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
   printf("Terminate (final) h1analysis\n");

   // function called at the end of the event loop

   hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
   h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));

   if (hdmd == 0 || h2 == 0) {
      Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
      return;
   }

   //create the canvas for the h1analysis fit
   gStyle->SetOptFit();
   TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
   c1->SetBottomMargin(0.15);
   hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
   hdmd->GetXaxis()->SetTitleOffset(1.4);

   //fit histogram hdmd with function f5 using the loglikelihood option
   TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
   f5->SetParameters(1000000, .25, 2000, .1454, .001);
   hdmd->Fit("f5","lr");

   //create the canvas for tau d0
   gStyle->SetOptFit(0);
   gStyle->SetOptStat(1100);
   TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
   c2->SetGrid();
   c2->SetBottomMargin(0.15);

   // Project slices of 2-d histogram h2 along X , then fit each slice
   // with function f2 and make a histogram for each fit parameter
   // Note that the generated histograms are added to the list of objects
   // in the current directory.
   TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
   f2->SetParameters(10000, 10);
   h2->FitSlicesX(f2,0,0,1,"qln");
   TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
   h2_1->GetXaxis()->SetTitle("#tau[ps]");
   h2_1->SetMarkerStyle(21);
   h2_1->Draw();
   c2->Update();
   TLine *line = new TLine(0,0,0,c2->GetUymax());
   line->Draw();

   //save the event list to a Root file if one was produced
   if (fillList) {
      TFile efile("elist.root","recreate");
      elist->Write();
   }
}
<commit_msg>Correctly indicate usage of the 'MakeProxy' selector'<commit_after>// Example of analysis class for the H1 data using code generated by MakeProxy.
// ===========================================================================
//
// This file uses 4 large data sets from the H1 collaboration at DESY Hamburg.
// One can access these data sets (277 MBytes) from the standard Root web site
// at:       ftp://root.cern.ch/root/h1analysis/
// The Physics plots below generated by this example cannot be produced when
// using smaller data sets.
//
// There are several ways to analyze data stored in a Root Tree
//   -Using TTree::Draw: This is very convenient and efficient for small tasks.
//     A TTree::Draw call produces one histogram at the time. The histogram
//     is automatically generated. The selection expression may be specified
//     in the command line.
//
//   -Using the TTreeViewer: This is a graphical interface to TTree::Draw
//      with the same functionality.
//
//   -Using the code generated by TTree::MakeClass: In this case, the user
//      creates an instance of the analysis class. He has the control over
//      the event loop and he can generate an unlimited number of histograms.
//
//   -Using the code generated by TTree::MakeSelector. Like for the code
//      generated by TTree::MakeClass, the user can do complex analysis.
//      However, he cannot control the event loop. The event loop is controlled
//      by TTree::Process called by the user. This solution is illustrated
//      by the current code. The advantage of this method is that it can be run
//      in a parallel environment using PROOF (the Parallel Root Facility).
//
// A chain of 4 files (originally converted from PAW ntuples) is used
// to illustrate the various ways to loop on Root data sets.
// Each data set contains a Root Tree named "h42"
//
// h1analysProxy.C can use either via TTree::Draw:
//       h42->Draw("h1analysisProxy.C");
// or it can be used directly with TTree::MakeProxy, for example to generate a
// shared library.   TTree::MakeProxy will generate a TSelector skeleton that
// include h1analysProxy.C:
//       h42->MakeProxy("h1sel","h1analysisProxy.C");
// This produces one file: h1sel.h which does a #include "h1analysProxy.C"
// The h1sel class is derived from the Root class TSelector and can then
// be used as:
//      h42->Process("h1sel.h+");
//
// The following members functions are called by the TTree::Process functions.
//    h1analysProxy_Begin():      called everytime a loop on the tree starts.
//                                a convenient place to create your histograms.
//    h1analysProxy_SlaveBegin():
//
//    h1analysProxy_Notify():     This function is called at the first entry of a new Tree
//                                in a chain.
//    h1analysProxy_Process():    called to analyze each entry.
//
//    h1analysProxy_SlaveTerminate():
//
//    h1analysProxy_Terminate():    called at the end of a loop on a TTree.
//                                  a convenient place to draw/fit your histograms.
//
//   To use this file, try the following session
//
// Root > gROOT->Time(); //will show RT & CPU time per command
//
//==>   A-  create a TChain with the 4 H1 data files
// The chain can be created by executed the short macro h1chain.C below:
// {
//   TChain chain("h42");
//   chain.Add("$H1/dstarmb.root");  //  21330730 bytes  21920 events
//   chain.Add("$H1/dstarp1a.root"); //  71464503 bytes  73243 events
//   chain.Add("$H1/dstarp1b.root"); //  83827959 bytes  85597 events
//   chain.Add("$H1/dstarp2.root");  // 100675234 bytes 103053 events
//   //where $H1 is a system symbol pointing to the H1 data directory.
// }
//
// Root > .x h1chain.C
//
//==>   B- loop on all events
// Root > chain.Draw("h1analysisProxy.C")
//
//==>   C- same as B, but in addition fill the event list with selected entries.
// The event list is saved to a file "elist.root" by the Terminate function.
// To see the list of selected events, you can do elist->Print("all").
// The selection function has selected 7525 events out of the 283813 events
// in the chain of files. (2.65 per cent)
// Root > chain.Draw("h1analysisProxy.C","","fillList")
//
//==>   D- Process only entries in the event list
// The event list is read from the file in elist.root generated by step C
// Root > chain.Draw("h1analysisProxy.C","","useList")
////
// The commands executed with the 3 different methods B,C and D
// produce two canvases shown below:
// begin_html the Dstar plot end_html
// begin_html the Tau D0 plot end_html
//
//Author; Philippe Canal from original h1analysis.C by Rene Brun

TEventList *elist;
Bool_t useList, fillList;
TH1F *hdmd;
TH2F *h2;

//_____________________________________________________________________
void h1analysisProxy_Begin(TTree * /* tree */ )
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (begin) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");
}

//_____________________________________________________________________
void h1analysisProxy_SlaveBegin(TTree *tree)
{
// function called before starting the event loop
//  -it performs some cleanup
//  -it creates histograms
//  -it sets some initialisation for the event list

   //initialize the Tree branch addresses
   Init(tree);

   //print the option specified in the Process function.
   TString option = GetOption();
   printf("Starting (slave) h1analysis with process option: %s\n",option.Data());

   //some cleanup in case this function had already been executed
   //delete any previously generated histograms or functions
   gDirectory->Delete("hdmd");
   gDirectory->Delete("h2*");
   delete gROOT->GetFunction("f5");
   delete gROOT->GetFunction("f2");

   //create histograms
   hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17);
   h2   = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6);

   fOutput->Add(hdmd);
   fOutput->Add(h2);

   //process cases with event list
   fillList = kFALSE;
   useList  = kFALSE;
   tree->SetEventList(0);
   delete gDirectory->GetList()->FindObject("elist");

   // case when one creates/fills the event list
   if (option.Contains("fillList")) {
      fillList = kTRUE;
      elist = new TEventList("elist","selection from Cut",5000);
   } else elist = 0;

   // case when one uses the event list generated in a previous call
   if (option.Contains("useList")) {
      useList  = kTRUE;
      TFile f("elist.root");
      elist = (TEventList*)f.Get("elist");
      if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist
      tree->SetEventList(elist);
   }

}

Double_t h1analysisProxy() {
   return 0;
}

//_____________________________________________________________________
Bool_t h1analysisProxy_Process(Long64_t entry)
{
// entry is the entry number in the current Tree
// Selection function to select D* and D0.

   //in case one event list is given in input, the selection has already been done.
   if (!useList) {

      float f1 = md0_d;
      float f2 = md0_d-1.8646;
      bool test = TMath::Abs(md0_d-1.8646) >= 0.04;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE;
      if (ptds_d <= 2.5) return kFALSE;
      if (TMath::Abs(etads_d) >= 1.5) return kFALSE;

      int cik = ik-1;    //original ik used f77 convention starting at 1
      int cipi = ipi-1;  //original ipi used f77 convention starting at 1

      f1 = nhitrp[cik];
      f2 = nhitrp[cipi];
      test = nhitrp[cik]*nhitrp[cipi] <= 1;
      if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n",
                            fChain->GetReadEntry(),f1,f2,test);

      if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE;
      if (rend[cik] -rstart[cik]  <= 22) return kFALSE;
      if (rend[cipi]-rstart[cipi] <= 22) return kFALSE;
      if (nlhk[cik] <= 0.1)    return kFALSE;
      if (nlhpi[cipi] <= 0.1)  return kFALSE;
      // fix because read-only
      if (nlhpi[ipis-1] <= 0.1) return kFALSE;
      if (njets < 1)          return kFALSE;

   }
   // if option fillList, fill the event list
   if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry));

   //fill some histograms
   hdmd->Fill(dm_d);
   h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d);

   return kTRUE;
}

//_____________________________________________________________________
void h1analysisProxy_SlaveTerminate()
{
   // nothing to be done
   printf("Terminate (slave) h1analysis\n");
}

//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
   printf("Terminate (final) h1analysis\n");

   // function called at the end of the event loop

   hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
   h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));

   if (hdmd == 0 || h2 == 0) {
      Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
      return;
   }

   //create the canvas for the h1analysis fit
   gStyle->SetOptFit();
   TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
   c1->SetBottomMargin(0.15);
   hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
   hdmd->GetXaxis()->SetTitleOffset(1.4);

   //fit histogram hdmd with function f5 using the loglikelihood option
   TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
   f5->SetParameters(1000000, .25, 2000, .1454, .001);
   hdmd->Fit("f5","lr");

   //create the canvas for tau d0
   gStyle->SetOptFit(0);
   gStyle->SetOptStat(1100);
   TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
   c2->SetGrid();
   c2->SetBottomMargin(0.15);

   // Project slices of 2-d histogram h2 along X , then fit each slice
   // with function f2 and make a histogram for each fit parameter
   // Note that the generated histograms are added to the list of objects
   // in the current directory.
   TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
   f2->SetParameters(10000, 10);
   h2->FitSlicesX(f2,0,0,1,"qln");
   TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
   h2_1->GetXaxis()->SetTitle("#tau[ps]");
   h2_1->SetMarkerStyle(21);
   h2_1->Draw();
   c2->Update();
   TLine *line = new TLine(0,0,0,c2->GetUymax());
   line->Draw();

   //save the event list to a Root file if one was produced
   if (fillList) {
      TFile efile("elist.root","recreate");
      elist->Write();
   }
}
<|endoftext|>


<commit_before>//
// (C) CharLS Team 2014, all rights reserved. See the accompanying "License.txt" for licensed use.
//

#include "stdafx.h"

#include "CppUnitTest.h"
#include "..\src\encoderstrategy.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

class EncoderStrategyTester : EncoderStrategy
{
public:
    EncoderStrategyTester(const JlsParameters& info) : EncoderStrategy(info)
    {
    }

    virtual void SetPresets(const JlsCustomParameters&)
    {
    }

    virtual size_t EncodeScan(std::unique_ptr<ProcessLine>, ByteStreamInfo*, void*)
    {
        return 0;
    }

    virtual ProcessLine* CreateProcess(ByteStreamInfo)
    {
        return nullptr;
    }

    void AppendToBitStreamTest(int32_t value, int32_t length)
    {
        AppendToBitStream(value, length);
    }
};

namespace CharLSUnitTest
{
    TEST_CLASS(EncoderStrategyTest)
    {
    public:
        TEST_METHOD(AppendToBitStream)
        {
            JlsParameters info;

            EncoderStrategyTester es(info);

            es.AppendToBitStreamTest(0, 0);
        }
    };
}
<commit_msg>Method argument updated to match base class.<commit_after>//
// (C) CharLS Team 2014, all rights reserved. See the accompanying "License.txt" for licensed use.
//

#include "stdafx.h"

#include "CppUnitTest.h"
#include "..\src\encoderstrategy.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

class EncoderStrategyTester : EncoderStrategy
{
public:
    EncoderStrategyTester(const JlsParameters& info) : EncoderStrategy(info)
    {
    }

    virtual void SetPresets(const JlsCustomParameters&)
    {
    }

    virtual size_t EncodeScan(std::unique_ptr<ProcessLine>, ByteStreamInfo&, void*)
    {
        return 0;
    }

    virtual ProcessLine* CreateProcess(ByteStreamInfo)
    {
        return nullptr;
    }

    void AppendToBitStreamTest(int32_t value, int32_t length)
    {
        AppendToBitStream(value, length);
    }
};

namespace CharLSUnitTest
{
    TEST_CLASS(EncoderStrategyTest)
    {
    public:
        TEST_METHOD(AppendToBitStream)
        {
            JlsParameters info;

            EncoderStrategyTester es(info);

            es.AppendToBitStreamTest(0, 0);
        }
    };
}
<|endoftext|>


<commit_before>
#include <iostream>
#include <gtest/gtest.h>
#include "TestHelpers.h"
#include "dart/dynamics/SoftBodyNode.h"

using namespace dart;
using namespace math;
using namespace dynamics;

//==============================================================================
TEST(NameManagement, Basic)
{
  //--------------------------------------------------------------------------
  //
  //--------------------------------------------------------------------------
  // Bodies
  BodyNode* body1 = new BodyNode;
  BodyNode* body2 = new BodyNode;
  BodyNode* body3 = new BodyNode;

  // TODO: Add some SoftBodyNodes into this test.
  // Grey is not familiar with construction of SoftBodyNodes,
  // so he is leaving that for someone else for the time being.

  // Joints
  Joint* joint1 = new RevoluteJoint(Eigen::Vector3d::UnitX(), "joint");
  Joint* joint2 = new TranslationalJoint("joint");
  Joint* joint3 = new FreeJoint("joint");

  // Testing whether DegreesOfFreedom get named correctly
  EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");

  EXPECT_TRUE(joint2->getDof(0)->getName() == "joint_x");
  EXPECT_TRUE(joint2->getDof(1)->getName() == "joint_y");
  EXPECT_TRUE(joint2->getDof(2)->getName() == "joint_z");

  EXPECT_TRUE(joint3->getDof(0)->getName() == "joint_rot_x");
  EXPECT_TRUE(joint3->getDof(1)->getName() == "joint_rot_y");
  EXPECT_TRUE(joint3->getDof(2)->getName() == "joint_rot_z");
  EXPECT_TRUE(joint3->getDof(3)->getName() == "joint_pos_x");
  EXPECT_TRUE(joint3->getDof(4)->getName() == "joint_pos_y");
  EXPECT_TRUE(joint3->getDof(5)->getName() == "joint_pos_z");

  // Skeleton
  Skeleton* skel = new Skeleton;

  body1->setParentJoint(joint1);
  body2->setParentJoint(joint2);
  body3->setParentJoint(joint3);

  body1->addChildBodyNode(body2);
  body2->addChildBodyNode(body3);

  skel->addBodyNode(body1);
  skel->addBodyNode(body2);
  skel->addBodyNode(body3);

  skel->init();

  // Testing whether the repeated names of BodyNodes and Joints get resolved
  // correctly as BodyNodes get added to the Skeleton
  EXPECT_FALSE(body1->getName() == body2->getName());
  EXPECT_FALSE(body2->getName() == body3->getName());
  EXPECT_FALSE(body3->getName() == body1->getName());

  EXPECT_FALSE(joint1->getName() == joint2->getName());
  EXPECT_FALSE(joint2->getName() == joint3->getName());
  EXPECT_FALSE(joint3->getName() == joint1->getName());

  EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");

  EXPECT_TRUE(joint2->getDof(0)->getName() == "joint(1)_x");
  EXPECT_TRUE(joint2->getDof(1)->getName() == "joint(1)_y");
  EXPECT_TRUE(joint2->getDof(2)->getName() == "joint(1)_z");

  EXPECT_TRUE(joint3->getDof(0)->getName() == "joint(2)_rot_x");
  EXPECT_TRUE(joint3->getDof(1)->getName() == "joint(2)_rot_y");
  EXPECT_TRUE(joint3->getDof(2)->getName() == "joint(2)_rot_z");
  EXPECT_TRUE(joint3->getDof(3)->getName() == "joint(2)_pos_x");
  EXPECT_TRUE(joint3->getDof(4)->getName() == "joint(2)_pos_y");
  EXPECT_TRUE(joint3->getDof(5)->getName() == "joint(2)_pos_z");

  // Testing whether the repeated names of BodyNodes get resolved correctly
  // as they are changed with BodyNode::setName(~)
  std::string newname1 = body1->setName("same_name");
  std::string newname2 = body2->setName("same_name");
  std::string newname3 = body3->setName("same_name");

  EXPECT_FALSE(body1->getName() == body2->getName());
  EXPECT_FALSE(body2->getName() == body3->getName());
  EXPECT_FALSE(body3->getName() == body1->getName());

  EXPECT_TRUE(body1->getName() == newname1);
  EXPECT_TRUE(body2->getName() == newname2);
  EXPECT_TRUE(body3->getName() == newname3);

  EXPECT_TRUE(skel->getBodyNode(newname1) == body1);
  EXPECT_TRUE(skel->getBodyNode(newname2) == body2);
  EXPECT_TRUE(skel->getBodyNode(newname3) == body3);

  // Testing whether the repeated names of Joints get resolved correctly
  // as they are changed with Joint::setName(~)
  newname1 = joint1->setName("another_name");
  newname2 = joint2->setName("another_name");
  newname3 = joint3->setName("another_name");

  EXPECT_FALSE(joint1->getName() == joint2->getName());
  EXPECT_FALSE(joint2->getName() == joint3->getName());
  EXPECT_FALSE(joint3->getName() == joint1->getName());

  EXPECT_TRUE(joint1->getName() == newname1);
  EXPECT_TRUE(joint2->getName() == newname2);
  EXPECT_TRUE(joint3->getName() == newname3);

  EXPECT_TRUE(skel->getJoint(newname1) == joint1);
  EXPECT_TRUE(skel->getJoint(newname2) == joint2);
  EXPECT_TRUE(skel->getJoint(newname3) == joint3);

  // Testing whether unique names get accidentally changed by the NameManager
  std::string unique_name = body2->setName("a_unique_name");
  EXPECT_TRUE(body2->getName() == "a_unique_name");
  EXPECT_TRUE(skel->getBodyNode("a_unique_name") == body2);

  EXPECT_FALSE(body1->getName() == body2->getName());
  EXPECT_FALSE(body2->getName() == body3->getName());
  EXPECT_FALSE(body3->getName() == body1->getName());

  unique_name = joint3->setName("a_unique_name");
  EXPECT_TRUE(joint3->getName() == "a_unique_name");
  EXPECT_TRUE(skel->getJoint("a_unique_name") == joint3);

  // Testing whether the DegreeOfFreedom names get updated correctly upon their
  // joint's name change
  EXPECT_TRUE(joint3->getDof(0)->getName() == "a_unique_name_rot_x");
  EXPECT_TRUE(joint3->getDof(1)->getName() == "a_unique_name_rot_y");
  EXPECT_TRUE(joint3->getDof(2)->getName() == "a_unique_name_rot_z");
  EXPECT_TRUE(joint3->getDof(3)->getName() == "a_unique_name_pos_x");
  EXPECT_TRUE(joint3->getDof(4)->getName() == "a_unique_name_pos_y");
  EXPECT_TRUE(joint3->getDof(5)->getName() == "a_unique_name_pos_z");

  EXPECT_TRUE(joint3->getDof(0) == skel->getDof("a_unique_name_rot_x"));
  EXPECT_TRUE(joint3->getDof(3) == skel->getDof("a_unique_name_pos_x"));

  // Note: The following assumes the joint order in the Skeleton is:
  // RevoluteJoint -> TranslationalJoint -> FreeJoint
  EXPECT_TRUE(joint1->getDof(0) == skel->getDof(0));

  EXPECT_TRUE(joint2->getDof(0) == skel->getDof(1));
  EXPECT_TRUE(joint2->getDof(1) == skel->getDof(2));
  EXPECT_TRUE(joint2->getDof(2) == skel->getDof(3));

  EXPECT_TRUE(joint3->getDof(0) == skel->getDof(4));
  EXPECT_TRUE(joint3->getDof(1) == skel->getDof(5));
  EXPECT_TRUE(joint3->getDof(2) == skel->getDof(6));
  EXPECT_TRUE(joint3->getDof(3) == skel->getDof(7));
  EXPECT_TRUE(joint3->getDof(4) == skel->getDof(8));
  EXPECT_TRUE(joint3->getDof(5) == skel->getDof(9));

  // Test whether the return of getIndexInSkeleton() and the index of the
  // corresponding DegreeOfFreedom in the Skeleton are same
  for (size_t i = 0; i < skel->getNumDofs(); ++i)
    EXPECT_TRUE(skel->getDof(i)->getIndexInSkeleton() == i);

  // Test whether all the joint names are still unique
  EXPECT_FALSE(joint1->getName() == joint2->getName());
  EXPECT_FALSE(joint2->getName() == joint3->getName());
  EXPECT_FALSE(joint3->getName() == joint1->getName());

  // Make sure that the Skeleton gives back NULL for non existent names
  EXPECT_TRUE(skel->getBodyNode("nonexistent_name") == NULL);
  EXPECT_TRUE(skel->getJoint("nonexistent_name") == NULL);
  EXPECT_TRUE(skel->getSoftBodyNode("nonexistent_name") == NULL);

  Joint* oldJoint = body3->getParentJoint();
  std::string oldJointName = oldJoint->getName();
  Joint* newJoint = new RevoluteJoint(Eigen::Vector3d(1,0,0), "a_new_joint");
  body3->setParentJoint(newJoint);
  EXPECT_TRUE(skel->getJoint("a_new_joint") == newJoint);

  // Make sure that the Skeleton returns NULL on any Joint names that have been
  // taken away from it
  EXPECT_FALSE(skel->getJoint(oldJointName) == oldJoint);
  EXPECT_TRUE(skel->getJoint(oldJointName) == NULL);
}

//==============================================================================
TEST(NameManagement, SetPattern)
{
  dart::common::NameManager<BodyNode> test_mgr;

  BodyNode* bn0 = new BodyNode("name");
  BodyNode* bn1 = new BodyNode("name");
  BodyNode* bn2 = new BodyNode("name");

  test_mgr.setPattern("%s(%d)");

  test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
  test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
  test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);

  EXPECT_TRUE( test_mgr.getObject("name") == bn0);
  EXPECT_TRUE( test_mgr.getObject("name(1)") == bn1);
  EXPECT_TRUE( test_mgr.getObject("name(2)") == bn2);

  test_mgr.clear();

  bn0->setName("bodynode");
  bn1->setName("bodynode");
  bn2->setName("bodynode");

  test_mgr.setPattern("(%d)-%s");
  test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
  test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
  test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);

  EXPECT_TRUE( test_mgr.getObject("bodynode") == bn0);
  EXPECT_TRUE( test_mgr.getObject("(1)-bodynode") == bn1 );
  EXPECT_TRUE( test_mgr.getObject("(2)-bodynode") == bn2 );

  delete bn0;
  delete bn1;
  delete bn2;
}

//==============================================================================
int main(int argc, char* argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>added copyright to unit test<commit_after>/*
 * Copyright (c) 2014, Georgia Tech Research Corporation
 * All rights reserved.
 *
 * Author(s): Michael X. Grey <mxgrey@gatech.edu>
 *
 * Georgia Tech Graphics Lab and Humanoid Robotics Lab
 *
 * Directed by Prof. C. Karen Liu and Prof. Mike Stilman
 * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include <iostream>
#include <gtest/gtest.h>
#include "TestHelpers.h"
#include "dart/dynamics/SoftBodyNode.h"

using namespace dart;
using namespace math;
using namespace dynamics;

//==============================================================================
TEST(NameManagement, Basic)
{
  //--------------------------------------------------------------------------
  //
  //--------------------------------------------------------------------------
  // Bodies
  BodyNode* body1 = new BodyNode;
  BodyNode* body2 = new BodyNode;
  BodyNode* body3 = new BodyNode;

  // TODO: Add some SoftBodyNodes into this test.
  // Grey is not familiar with construction of SoftBodyNodes,
  // so he is leaving that for someone else for the time being.

  // Joints
  Joint* joint1 = new RevoluteJoint(Eigen::Vector3d::UnitX(), "joint");
  Joint* joint2 = new TranslationalJoint("joint");
  Joint* joint3 = new FreeJoint("joint");

  // Testing whether DegreesOfFreedom get named correctly
  EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");

  EXPECT_TRUE(joint2->getDof(0)->getName() == "joint_x");
  EXPECT_TRUE(joint2->getDof(1)->getName() == "joint_y");
  EXPECT_TRUE(joint2->getDof(2)->getName() == "joint_z");

  EXPECT_TRUE(joint3->getDof(0)->getName() == "joint_rot_x");
  EXPECT_TRUE(joint3->getDof(1)->getName() == "joint_rot_y");
  EXPECT_TRUE(joint3->getDof(2)->getName() == "joint_rot_z");
  EXPECT_TRUE(joint3->getDof(3)->getName() == "joint_pos_x");
  EXPECT_TRUE(joint3->getDof(4)->getName() == "joint_pos_y");
  EXPECT_TRUE(joint3->getDof(5)->getName() == "joint_pos_z");

  // Skeleton
  Skeleton* skel = new Skeleton;

  body1->setParentJoint(joint1);
  body2->setParentJoint(joint2);
  body3->setParentJoint(joint3);

  body1->addChildBodyNode(body2);
  body2->addChildBodyNode(body3);

  skel->addBodyNode(body1);
  skel->addBodyNode(body2);
  skel->addBodyNode(body3);

  skel->init();

  // Testing whether the repeated names of BodyNodes and Joints get resolved
  // correctly as BodyNodes get added to the Skeleton
  EXPECT_FALSE(body1->getName() == body2->getName());
  EXPECT_FALSE(body2->getName() == body3->getName());
  EXPECT_FALSE(body3->getName() == body1->getName());

  EXPECT_FALSE(joint1->getName() == joint2->getName());
  EXPECT_FALSE(joint2->getName() == joint3->getName());
  EXPECT_FALSE(joint3->getName() == joint1->getName());

  EXPECT_TRUE(joint1->getDof(0)->getName() == "joint");

  EXPECT_TRUE(joint2->getDof(0)->getName() == "joint(1)_x");
  EXPECT_TRUE(joint2->getDof(1)->getName() == "joint(1)_y");
  EXPECT_TRUE(joint2->getDof(2)->getName() == "joint(1)_z");

  EXPECT_TRUE(joint3->getDof(0)->getName() == "joint(2)_rot_x");
  EXPECT_TRUE(joint3->getDof(1)->getName() == "joint(2)_rot_y");
  EXPECT_TRUE(joint3->getDof(2)->getName() == "joint(2)_rot_z");
  EXPECT_TRUE(joint3->getDof(3)->getName() == "joint(2)_pos_x");
  EXPECT_TRUE(joint3->getDof(4)->getName() == "joint(2)_pos_y");
  EXPECT_TRUE(joint3->getDof(5)->getName() == "joint(2)_pos_z");

  // Testing whether the repeated names of BodyNodes get resolved correctly
  // as they are changed with BodyNode::setName(~)
  std::string newname1 = body1->setName("same_name");
  std::string newname2 = body2->setName("same_name");
  std::string newname3 = body3->setName("same_name");

  EXPECT_FALSE(body1->getName() == body2->getName());
  EXPECT_FALSE(body2->getName() == body3->getName());
  EXPECT_FALSE(body3->getName() == body1->getName());

  EXPECT_TRUE(body1->getName() == newname1);
  EXPECT_TRUE(body2->getName() == newname2);
  EXPECT_TRUE(body3->getName() == newname3);

  EXPECT_TRUE(skel->getBodyNode(newname1) == body1);
  EXPECT_TRUE(skel->getBodyNode(newname2) == body2);
  EXPECT_TRUE(skel->getBodyNode(newname3) == body3);

  // Testing whether the repeated names of Joints get resolved correctly
  // as they are changed with Joint::setName(~)
  newname1 = joint1->setName("another_name");
  newname2 = joint2->setName("another_name");
  newname3 = joint3->setName("another_name");

  EXPECT_FALSE(joint1->getName() == joint2->getName());
  EXPECT_FALSE(joint2->getName() == joint3->getName());
  EXPECT_FALSE(joint3->getName() == joint1->getName());

  EXPECT_TRUE(joint1->getName() == newname1);
  EXPECT_TRUE(joint2->getName() == newname2);
  EXPECT_TRUE(joint3->getName() == newname3);

  EXPECT_TRUE(skel->getJoint(newname1) == joint1);
  EXPECT_TRUE(skel->getJoint(newname2) == joint2);
  EXPECT_TRUE(skel->getJoint(newname3) == joint3);

  // Testing whether unique names get accidentally changed by the NameManager
  std::string unique_name = body2->setName("a_unique_name");
  EXPECT_TRUE(body2->getName() == "a_unique_name");
  EXPECT_TRUE(skel->getBodyNode("a_unique_name") == body2);

  EXPECT_FALSE(body1->getName() == body2->getName());
  EXPECT_FALSE(body2->getName() == body3->getName());
  EXPECT_FALSE(body3->getName() == body1->getName());

  unique_name = joint3->setName("a_unique_name");
  EXPECT_TRUE(joint3->getName() == "a_unique_name");
  EXPECT_TRUE(skel->getJoint("a_unique_name") == joint3);

  // Testing whether the DegreeOfFreedom names get updated correctly upon their
  // joint's name change
  EXPECT_TRUE(joint3->getDof(0)->getName() == "a_unique_name_rot_x");
  EXPECT_TRUE(joint3->getDof(1)->getName() == "a_unique_name_rot_y");
  EXPECT_TRUE(joint3->getDof(2)->getName() == "a_unique_name_rot_z");
  EXPECT_TRUE(joint3->getDof(3)->getName() == "a_unique_name_pos_x");
  EXPECT_TRUE(joint3->getDof(4)->getName() == "a_unique_name_pos_y");
  EXPECT_TRUE(joint3->getDof(5)->getName() == "a_unique_name_pos_z");

  EXPECT_TRUE(joint3->getDof(0) == skel->getDof("a_unique_name_rot_x"));
  EXPECT_TRUE(joint3->getDof(3) == skel->getDof("a_unique_name_pos_x"));

  // Note: The following assumes the joint order in the Skeleton is:
  // RevoluteJoint -> TranslationalJoint -> FreeJoint
  EXPECT_TRUE(joint1->getDof(0) == skel->getDof(0));

  EXPECT_TRUE(joint2->getDof(0) == skel->getDof(1));
  EXPECT_TRUE(joint2->getDof(1) == skel->getDof(2));
  EXPECT_TRUE(joint2->getDof(2) == skel->getDof(3));

  EXPECT_TRUE(joint3->getDof(0) == skel->getDof(4));
  EXPECT_TRUE(joint3->getDof(1) == skel->getDof(5));
  EXPECT_TRUE(joint3->getDof(2) == skel->getDof(6));
  EXPECT_TRUE(joint3->getDof(3) == skel->getDof(7));
  EXPECT_TRUE(joint3->getDof(4) == skel->getDof(8));
  EXPECT_TRUE(joint3->getDof(5) == skel->getDof(9));

  // Test whether the return of getIndexInSkeleton() and the index of the
  // corresponding DegreeOfFreedom in the Skeleton are same
  for (size_t i = 0; i < skel->getNumDofs(); ++i)
    EXPECT_TRUE(skel->getDof(i)->getIndexInSkeleton() == i);

  // Test whether all the joint names are still unique
  EXPECT_FALSE(joint1->getName() == joint2->getName());
  EXPECT_FALSE(joint2->getName() == joint3->getName());
  EXPECT_FALSE(joint3->getName() == joint1->getName());

  // Make sure that the Skeleton gives back NULL for non existent names
  EXPECT_TRUE(skel->getBodyNode("nonexistent_name") == NULL);
  EXPECT_TRUE(skel->getJoint("nonexistent_name") == NULL);
  EXPECT_TRUE(skel->getSoftBodyNode("nonexistent_name") == NULL);

  Joint* oldJoint = body3->getParentJoint();
  std::string oldJointName = oldJoint->getName();
  Joint* newJoint = new RevoluteJoint(Eigen::Vector3d(1,0,0), "a_new_joint");
  body3->setParentJoint(newJoint);
  EXPECT_TRUE(skel->getJoint("a_new_joint") == newJoint);

  // Make sure that the Skeleton returns NULL on any Joint names that have been
  // taken away from it
  EXPECT_FALSE(skel->getJoint(oldJointName) == oldJoint);
  EXPECT_TRUE(skel->getJoint(oldJointName) == NULL);
}

//==============================================================================
TEST(NameManagement, SetPattern)
{
  dart::common::NameManager<BodyNode> test_mgr;

  BodyNode* bn0 = new BodyNode("name");
  BodyNode* bn1 = new BodyNode("name");
  BodyNode* bn2 = new BodyNode("name");

  test_mgr.setPattern("%s(%d)");

  test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
  test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
  test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);

  EXPECT_TRUE( test_mgr.getObject("name") == bn0);
  EXPECT_TRUE( test_mgr.getObject("name(1)") == bn1);
  EXPECT_TRUE( test_mgr.getObject("name(2)") == bn2);

  test_mgr.clear();

  bn0->setName("bodynode");
  bn1->setName("bodynode");
  bn2->setName("bodynode");

  test_mgr.setPattern("(%d)-%s");
  test_mgr.issueNewNameAndAdd(bn0->getName(), bn0);
  test_mgr.issueNewNameAndAdd(bn1->getName(), bn1);
  test_mgr.issueNewNameAndAdd(bn2->getName(), bn2);

  EXPECT_TRUE( test_mgr.getObject("bodynode") == bn0);
  EXPECT_TRUE( test_mgr.getObject("(1)-bodynode") == bn1 );
  EXPECT_TRUE( test_mgr.getObject("(2)-bodynode") == bn2 );

  delete bn0;
  delete bn1;
  delete bn2;
}

//==============================================================================
int main(int argc, char* argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>

static const int64 nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0)
{
    numBlocksAtStartup = -1;

    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    return nBestHeight;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

QDateTime ClientModel::getLastBlockDate() const
{
    return QDateTime::fromTime_t(pindexBest->GetBlockTime());
}

void ClientModel::updateTimer()
{
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();
    int newNumBlocksOfPeers = getNumBlocksOfPeers();

    if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers)
        emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers);

    cachedNumBlocks = newNumBlocks;
    cachedNumBlocksOfPeers = newNumBlocksOfPeers;
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false);
        }
    }

    // Emit a numBlocksChanged when the status message changes,
    // so that the view recomputes and updates the status bar.
    emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers());
}

bool ClientModel::isTestNet() const
{
    return fTestNet;
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

int ClientModel::getNumBlocksOfPeers() const
{
    return GetNumBlocksOfPeers();
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
    // This notification is too frequent. Don't trigger a signal.
    // Don't remove it, though, as it might be useful later.
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
<commit_msg>only update cached values in ClientModel::updateTimer() when they are changed<commit_after>#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>

static const int64 nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0)
{
    numBlocksAtStartup = -1;

    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    return nBestHeight;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

QDateTime ClientModel::getLastBlockDate() const
{
    return QDateTime::fromTime_t(pindexBest->GetBlockTime());
}

void ClientModel::updateTimer()
{
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();
    int newNumBlocksOfPeers = getNumBlocksOfPeers();

    if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers)
    {
        cachedNumBlocks = newNumBlocks;
        cachedNumBlocksOfPeers = newNumBlocksOfPeers;

        emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers);
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false);
        }
    }

    // Emit a numBlocksChanged when the status message changes,
    // so that the view recomputes and updates the status bar.
    emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers());
}

bool ClientModel::isTestNet() const
{
    return fTestNet;
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

int ClientModel::getNumBlocksOfPeers() const
{
    return GetNumBlocksOfPeers();
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
    // This notification is too frequent. Don't trigger a signal.
    // Don't remove it, though, as it might be useful later.
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
<|endoftext|>


<commit_before>// ------------------------------------------------------------------------
// Pion is a development platform for building Reactors that process Events
// ------------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Pion is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Pion is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for
// more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Pion.  If not, see <http://www.gnu.org/licenses/>.
//

#include <pion/PionConfig.hpp>
#include <pion/platform/ConfigManager.hpp>
#include <boost/test/unit_test.hpp>

using namespace pion;
using namespace pion::platform;

BOOST_AUTO_TEST_CASE(checkCreateUUID) {
	std::string UUID = ConfigManager::createUUID();
	BOOST_CHECK_EQUAL(UUID.length(), static_cast<std::size_t>(36));
}

BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsRelative) {
	std::string base_path("/opt/pion/config/platform.xml");
	std::string relative_path("../ui");
#if defined(_MSC_VER)
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "c:\\opt\\pion\\config\\..\\ui");
#else
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui");
#endif
}

BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsNotRelative) {
	std::string base_path("/opt/pion/config/platform.xml");
#if defined(_MSC_VER)
	std::string relative_path("C:\\opt\\pion\\ui");
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "C:\\opt\\pion\\ui");
#else
	std::string relative_path("/opt/pion/ui");
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui");
#endif
}
<commit_msg>Updated checkResolveRelativePathThatIsRelative so it passes again for MSVC.<commit_after>// ------------------------------------------------------------------------
// Pion is a development platform for building Reactors that process Events
// ------------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Pion is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Pion is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for
// more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Pion.  If not, see <http://www.gnu.org/licenses/>.
//

#include <pion/PionConfig.hpp>
#include <pion/platform/ConfigManager.hpp>
#include <boost/test/unit_test.hpp>

using namespace pion;
using namespace pion::platform;

BOOST_AUTO_TEST_CASE(checkCreateUUID) {
	std::string UUID = ConfigManager::createUUID();
	BOOST_CHECK_EQUAL(UUID.length(), static_cast<std::size_t>(36));
}

BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsRelative) {
	std::string base_path("/opt/pion/config/platform.xml");
	std::string relative_path("../ui");
#if defined(_MSC_VER)
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "c:\\opt\\pion\\ui");
#else
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui");
#endif
}

BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsNotRelative) {
	std::string base_path("/opt/pion/config/platform.xml");
#if defined(_MSC_VER)
	std::string relative_path("C:\\opt\\pion\\ui");
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "C:\\opt\\pion\\ui");
#else
	std::string relative_path("/opt/pion/ui");
	BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui");
#endif
}
<|endoftext|>


<commit_before>#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "alert.h"
#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>

static const int64 nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), cachedNumBlocksOfPeers(0), numBlocksAtStartup(-1), pollTimer(0)
{
    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    return nBestHeight;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

QDateTime ClientModel::getLastBlockDate() const
{
    return QDateTime::fromTime_t(pindexBest->GetBlockTime());
}

void ClientModel::updateTimer()
{
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();
    int newNumBlocksOfPeers = getNumBlocksOfPeers();

    if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers)
    {
        cachedNumBlocks = newNumBlocks;
        cachedNumBlocksOfPeers = newNumBlocksOfPeers;

        // ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI
        emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks));
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR);
        }
    }

    emit alertsChanged(getStatusBarWarnings());
}

bool ClientModel::isTestNet() const
{
    return fTestNet;
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

enum BlockSource ClientModel::getBlockSource() const
{
    if (fReindex)
        return BLOCK_SOURCE_REINDEX;
    if (fImporting)
        return BLOCK_SOURCE_DISK;
    return BLOCK_SOURCE_NETWORK;
}

int ClientModel::getNumBlocksOfPeers() const
{
    return GetNumBlocksOfPeers();
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
    // This notification is too frequent. Don't trigger a signal.
    // Don't remove it, though, as it might be useful later.
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
<commit_msg>Prevent Qt crash at startup with an empty data directory<commit_after>#include "clientmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "alert.h"
#include "main.h"
#include "ui_interface.h"

#include <QDateTime>
#include <QTimer>

static const int64 nClientStartupTime = GetTime();

ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), optionsModel(optionsModel),
    cachedNumBlocks(0), cachedNumBlocksOfPeers(0), numBlocksAtStartup(-1), pollTimer(0)
{
    pollTimer = new QTimer(this);
    pollTimer->setInterval(MODEL_UPDATE_DELAY);
    pollTimer->start();
    connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections() const
{
    return vNodes.size();
}

int ClientModel::getNumBlocks() const
{
    return nBestHeight;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

QDateTime ClientModel::getLastBlockDate() const
{
    if (pindexBest)
        return QDateTime::fromTime_t(pindexBest->GetBlockTime());
    else
        return QDateTime::fromTime_t(1231006505); // Genesis block's time
}

void ClientModel::updateTimer()
{
    // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
    // Periodically check and update with a timer.
    int newNumBlocks = getNumBlocks();
    int newNumBlocksOfPeers = getNumBlocksOfPeers();

    if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers)
    {
        cachedNumBlocks = newNumBlocks;
        cachedNumBlocksOfPeers = newNumBlocksOfPeers;

        // ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI
        emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks));
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    emit numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert(const QString &hash, int status)
{
    // Show error message notification for new alert
    if(status == CT_NEW)
    {
        uint256 hash_256;
        hash_256.SetHex(hash.toStdString());
        CAlert alert = CAlert::getAlertByHash(hash_256);
        if(!alert.IsNull())
        {
            emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR);
        }
    }

    emit alertsChanged(getStatusBarWarnings());
}

bool ClientModel::isTestNet() const
{
    return fTestNet;
}

bool ClientModel::inInitialBlockDownload() const
{
    return IsInitialBlockDownload();
}

enum BlockSource ClientModel::getBlockSource() const
{
    if (fReindex)
        return BLOCK_SOURCE_REINDEX;
    if (fImporting)
        return BLOCK_SOURCE_DISK;
    return BLOCK_SOURCE_NETWORK;
}

int ClientModel::getNumBlocksOfPeers() const
{
    return GetNumBlocksOfPeers();
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel *ClientModel::getOptionsModel()
{
    return optionsModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

// Handlers for core signals
static void NotifyBlocksChanged(ClientModel *clientmodel)
{
    // This notification is too frequent. Don't trigger a signal.
    // Don't remove it, though, as it might be useful later.
}

static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
    // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
                              Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
    OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status);
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
                              Q_ARG(QString, QString::fromStdString(hash.GetHex())),
                              Q_ARG(int, status));
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 ARM Limited
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 *          Andreas Hansson
 */

#include "base/trace.hh"
#include "debug/Drain.hh"
#include "debug/PacketQueue.hh"
#include "mem/packet_queue.hh"

using namespace std;

PacketQueue::PacketQueue(EventManager& _em, const std::string& _label)
    : em(_em), sendEvent(this), drainManager(NULL), label(_label),
      waitingOnRetry(false)
{
}

PacketQueue::~PacketQueue()
{
}

void
PacketQueue::retry()
{
    DPRINTF(PacketQueue, "Queue %s received retry\n", name());
    assert(waitingOnRetry);
    sendDeferredPacket();
}

bool
PacketQueue::checkFunctional(PacketPtr pkt)
{
    pkt->pushLabel(label);

    DeferredPacketIterator i = transmitList.begin();
    DeferredPacketIterator end = transmitList.end();
    bool found = false;

    while (!found && i != end) {
        // If the buffered packet contains data, and it overlaps the
        // current packet, then update data
        found = pkt->checkFunctional(i->pkt);
        ++i;
    }

    pkt->popLabel();

    return found;
}

void
PacketQueue::schedSendEvent(Tick when)
{
    // if we are waiting on a retry, do not schedule a send event, and
    // instead rely on retry being called
    if (waitingOnRetry) {
        assert(!sendEvent.scheduled());
        return;
    }

    if (!sendEvent.scheduled()) {
        em.schedule(&sendEvent, when);
    } else if (sendEvent.when() > when) {
        em.reschedule(&sendEvent, when);
    }
}

void
PacketQueue::schedSendTiming(PacketPtr pkt, Tick when, bool send_as_snoop)
{
    // we can still send a packet before the end of this tick
    assert(when >= curTick());

    // express snoops should never be queued
    assert(!pkt->isExpressSnoop());

    // nothing on the list, or earlier than current front element,
    // schedule an event
    if (transmitList.empty() || when < transmitList.front().tick) {
        // note that currently we ignore a potentially outstanding retry
        // and could in theory put a new packet at the head of the
        // transmit list before retrying the existing packet
        transmitList.push_front(DeferredPacket(when, pkt, send_as_snoop));
        schedSendEvent(when);
        return;
    }

    // list is non-empty and this belongs at the end
    if (when >= transmitList.back().tick) {
        transmitList.push_back(DeferredPacket(when, pkt, send_as_snoop));
        return;
    }

    // this belongs in the middle somewhere, insertion sort
    DeferredPacketIterator i = transmitList.begin();
    ++i; // already checked for insertion at front
    while (i != transmitList.end() && when >= i->tick)
        ++i;
    transmitList.insert(i, DeferredPacket(when, pkt, send_as_snoop));
}

void PacketQueue::trySendTiming()
{
    assert(deferredPacketReady());

    // take the next packet off the list here, as we might return to
    // ourselves through the sendTiming call below
    DeferredPacket dp = transmitList.front();
    transmitList.pop_front();

    // use the appropriate implementation of sendTiming based on the
    // type of port associated with the queue, and whether the packet
    // is to be sent as a snoop or not
    waitingOnRetry = !sendTiming(dp.pkt, dp.sendAsSnoop);

    if (waitingOnRetry) {
        // put the packet back at the front of the list (packet should
        // not have changed since it wasn't accepted)
        assert(!sendEvent.scheduled());
        transmitList.push_front(dp);
    }
}

void
PacketQueue::scheduleSend(Tick time)
{
    // the next ready time is either determined by the next deferred packet,
    // or in the cache through the MSHR ready time
    Tick nextReady = std::min(deferredPacketReadyTime(), time);

    if (nextReady != MaxTick) {
        // if the sendTiming caused someone else to call our
        // recvTiming we could already have an event scheduled, check
        if (!sendEvent.scheduled())
            em.schedule(&sendEvent, std::max(nextReady, curTick() + 1));
    } else {
        // no more to send, so if we're draining, we may be done
        if (drainManager && transmitList.empty() && !sendEvent.scheduled()) {
            DPRINTF(Drain, "PacketQueue done draining,"
                    "processing drain event\n");
            drainManager->signalDrainDone();
            drainManager = NULL;
        }
    }
}

void
PacketQueue::sendDeferredPacket()
{
    // try to send what is on the list, this will set waitingOnRetry
    // accordingly
    trySendTiming();

    // if we succeeded and are not waiting for a retry, schedule the
    // next send
    if (!waitingOnRetry) {
        scheduleSend();
    }
}

void
PacketQueue::processSendEvent()
{
    assert(!waitingOnRetry);
    sendDeferredPacket();
}

unsigned int
PacketQueue::drain(DrainManager *dm)
{
    if (transmitList.empty() && !sendEvent.scheduled())
        return 0;
    DPRINTF(Drain, "PacketQueue not drained\n");
    drainManager = dm;
    return 1;
}

MasterPacketQueue::MasterPacketQueue(EventManager& _em, MasterPort& _masterPort,
                                     const std::string _label)
    : PacketQueue(_em, _label), masterPort(_masterPort)
{
}

bool
MasterPacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop)
{
    // attempt to send the packet and return according to the outcome
    if (!send_as_snoop)
        return masterPort.sendTimingReq(pkt);
    else
        return masterPort.sendTimingSnoopResp(pkt);
}

SlavePacketQueue::SlavePacketQueue(EventManager& _em, SlavePort& _slavePort,
                                   const std::string _label)
    : PacketQueue(_em, _label), slavePort(_slavePort)
{
}

bool
SlavePacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop)
{
    // we should never have queued snoop requests
    assert(!send_as_snoop);
    return slavePort.sendTimingResp(pkt);
}
<commit_msg>mem: Add sanity check to packet queue size<commit_after>/*
 * Copyright (c) 2012 ARM Limited
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 *          Andreas Hansson
 */

#include "base/trace.hh"
#include "debug/Drain.hh"
#include "debug/PacketQueue.hh"
#include "mem/packet_queue.hh"

using namespace std;

PacketQueue::PacketQueue(EventManager& _em, const std::string& _label)
    : em(_em), sendEvent(this), drainManager(NULL), label(_label),
      waitingOnRetry(false)
{
}

PacketQueue::~PacketQueue()
{
}

void
PacketQueue::retry()
{
    DPRINTF(PacketQueue, "Queue %s received retry\n", name());
    assert(waitingOnRetry);
    sendDeferredPacket();
}

bool
PacketQueue::checkFunctional(PacketPtr pkt)
{
    pkt->pushLabel(label);

    DeferredPacketIterator i = transmitList.begin();
    DeferredPacketIterator end = transmitList.end();
    bool found = false;

    while (!found && i != end) {
        // If the buffered packet contains data, and it overlaps the
        // current packet, then update data
        found = pkt->checkFunctional(i->pkt);
        ++i;
    }

    pkt->popLabel();

    return found;
}

void
PacketQueue::schedSendEvent(Tick when)
{
    // if we are waiting on a retry, do not schedule a send event, and
    // instead rely on retry being called
    if (waitingOnRetry) {
        assert(!sendEvent.scheduled());
        return;
    }

    if (!sendEvent.scheduled()) {
        em.schedule(&sendEvent, when);
    } else if (sendEvent.when() > when) {
        em.reschedule(&sendEvent, when);
    }
}

void
PacketQueue::schedSendTiming(PacketPtr pkt, Tick when, bool send_as_snoop)
{
    // we can still send a packet before the end of this tick
    assert(when >= curTick());

    // express snoops should never be queued
    assert(!pkt->isExpressSnoop());

    // add a very basic sanity check on the port to ensure the
    // invisible buffer is not growing beyond reasonable limits
    if (transmitList.size() > 100) {
        panic("Packet queue %s has grown beyond 100 packets\n",
              name());
    }

    // nothing on the list, or earlier than current front element,
    // schedule an event
    if (transmitList.empty() || when < transmitList.front().tick) {
        // note that currently we ignore a potentially outstanding retry
        // and could in theory put a new packet at the head of the
        // transmit list before retrying the existing packet
        transmitList.push_front(DeferredPacket(when, pkt, send_as_snoop));
        schedSendEvent(when);
        return;
    }

    // list is non-empty and this belongs at the end
    if (when >= transmitList.back().tick) {
        transmitList.push_back(DeferredPacket(when, pkt, send_as_snoop));
        return;
    }

    // this belongs in the middle somewhere, insertion sort
    DeferredPacketIterator i = transmitList.begin();
    ++i; // already checked for insertion at front
    while (i != transmitList.end() && when >= i->tick)
        ++i;
    transmitList.insert(i, DeferredPacket(when, pkt, send_as_snoop));
}

void PacketQueue::trySendTiming()
{
    assert(deferredPacketReady());

    // take the next packet off the list here, as we might return to
    // ourselves through the sendTiming call below
    DeferredPacket dp = transmitList.front();
    transmitList.pop_front();

    // use the appropriate implementation of sendTiming based on the
    // type of port associated with the queue, and whether the packet
    // is to be sent as a snoop or not
    waitingOnRetry = !sendTiming(dp.pkt, dp.sendAsSnoop);

    if (waitingOnRetry) {
        // put the packet back at the front of the list (packet should
        // not have changed since it wasn't accepted)
        assert(!sendEvent.scheduled());
        transmitList.push_front(dp);
    }
}

void
PacketQueue::scheduleSend(Tick time)
{
    // the next ready time is either determined by the next deferred packet,
    // or in the cache through the MSHR ready time
    Tick nextReady = std::min(deferredPacketReadyTime(), time);

    if (nextReady != MaxTick) {
        // if the sendTiming caused someone else to call our
        // recvTiming we could already have an event scheduled, check
        if (!sendEvent.scheduled())
            em.schedule(&sendEvent, std::max(nextReady, curTick() + 1));
    } else {
        // no more to send, so if we're draining, we may be done
        if (drainManager && transmitList.empty() && !sendEvent.scheduled()) {
            DPRINTF(Drain, "PacketQueue done draining,"
                    "processing drain event\n");
            drainManager->signalDrainDone();
            drainManager = NULL;
        }
    }
}

void
PacketQueue::sendDeferredPacket()
{
    // try to send what is on the list, this will set waitingOnRetry
    // accordingly
    trySendTiming();

    // if we succeeded and are not waiting for a retry, schedule the
    // next send
    if (!waitingOnRetry) {
        scheduleSend();
    }
}

void
PacketQueue::processSendEvent()
{
    assert(!waitingOnRetry);
    sendDeferredPacket();
}

unsigned int
PacketQueue::drain(DrainManager *dm)
{
    if (transmitList.empty() && !sendEvent.scheduled())
        return 0;
    DPRINTF(Drain, "PacketQueue not drained\n");
    drainManager = dm;
    return 1;
}

MasterPacketQueue::MasterPacketQueue(EventManager& _em, MasterPort& _masterPort,
                                     const std::string _label)
    : PacketQueue(_em, _label), masterPort(_masterPort)
{
}

bool
MasterPacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop)
{
    // attempt to send the packet and return according to the outcome
    if (!send_as_snoop)
        return masterPort.sendTimingReq(pkt);
    else
        return masterPort.sendTimingSnoopResp(pkt);
}

SlavePacketQueue::SlavePacketQueue(EventManager& _em, SlavePort& _slavePort,
                                   const std::string _label)
    : PacketQueue(_em, _label), slavePort(_slavePort)
{
}

bool
SlavePacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop)
{
    // we should never have queued snoop requests
    assert(!send_as_snoop);
    return slavePort.sendTimingResp(pkt);
}
<|endoftext|>