text
stringlengths
54
60.6k
<commit_before>/* $Id$ */ // // Script to calculate PtvsEta correction map using the CorrectionMatrix2D class. // makeCorrectionPtEta(Char_t* dataDir, Int_t nRuns=20) { Char_t str[256]; //gSystem->Load("/home/poghos/CERN2006/pp/esdTrackCuts/libESDtrackQuality.so"); gSystem->Load("libPWG0base"); gSystem->Load("libCorrectionMatrix2D.so"); // ######################################################## // selection of esd tracks AliESDtrackCuts* esdTrackCuts = new AliESDtrackCuts(); esdTrackCuts->DefineHistograms(1); esdTrackCuts->SetMinNClustersTPC(50); esdTrackCuts->SetMaxChi2PerClusterTPC(3.5); esdTrackCuts->SetMaxCovDiagonalElements(2,2,0.5,0.5,2); esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetMinNsigmaToVertex(3); esdTrackCuts->SetAcceptKingDaughters(kFALSE); AliLog::SetClassDebugLevel("AliESDtrackCuts",1); AliLog::SetClassDebugLevel("ESDtrackQualityCuts",1); // ######################################################## // definition of PtEta correction object CorrectionMatrix2D* PtEtaMap = new CorrectionMatrix2D("CorrectionMatrix2"); PtEtaMap->SetHist("PtEta",80,0.,10.,120,-2.,2.); //Float_t x[]={-20., -15., -5., 0., 6., 20.}; //Float_t y[]={-6. , -3., -1., 2., 3., 6. }; //PtEtaMap->SetHist("PtEta",5,x,5,y); PtEtaMap->SetHistTitle("p_{t}","#eta"); // ######################################################## // get the data dir Char_t execDir[256]; sprintf(execDir,gSystem->pwd()); TSystemDirectory* baseDir = new TSystemDirectory(".",dataDir); TList* dirList = baseDir->GetListOfFiles(); Int_t nDirs = dirList->GetEntries(); // go back to the dir where this script is executed gSystem->cd(execDir); // ######################################################## // definition of used pointers TFile* esdFile; TTree* esdTree; TBranch* esdBranch; AliESD* esd =0; // ######################################################## // loop over runs Int_t nRunCounter = 0; for (Int_t r=0; r<nDirs; r++) { TSystemFile* presentDir = (TSystemFile*)dirList->At(r); if (!presentDir || !presentDir->IsDirectory()) continue; // check that the files are there TString currentDataDir; currentDataDir.Form("%s/%s",dataDir, presentDir->GetName()); cout << "Processing directory " << currentDataDir.Data() << endl; if ((!gSystem->Which(currentDataDir,"galice.root")) || (!gSystem->Which(currentDataDir,"AliESDs.root"))) continue; if (nRunCounter++ >= nRuns) break; cout << "run #" << nRunCounter << endl; // ######################################################### // setup galice and runloader if (gAlice) { delete gAlice->GetRunLoader(); delete gAlice; gAlice=0; } sprintf(str,"%s/galice.root",currentDataDir.Data()); AliRunLoader* runLoader = AliRunLoader::Open(str); runLoader->LoadgAlice(); gAlice = runLoader->GetAliRun(); runLoader->LoadKinematics(); runLoader->LoadHeader(); // ######################################################### // open esd file and get the tree sprintf(str,"%s/AliESDs.root",currentDataDir.Data()); // close it first to avoid memory leak if (esdFile) if (esdFile->IsOpen()) esdFile->Close(); esdFile = TFile::Open(str); esdTree = (TTree*)esdFile->Get("esdTree"); if (!esdTree) continue; esdBranch = esdTree->GetBranch("ESD"); esdBranch->SetAddress(&esd); if (!esdBranch) continue; // ######################################################## // Magnetic field AliTracker::SetFieldMap(gAlice->Field(),kTRUE); // kTRUE means uniform magnetic field //AliKalmanTrack::SetConvConst(1000/0.299792458/5.); // ######################################################## // getting number of events Int_t nEvents = (Int_t)runLoader->GetNumberOfEvents(); Int_t nESDEvents = esdBranch->GetEntries(); if (nEvents!=nESDEvents) { cout << " Different number of events from runloader and esdtree!!!" << nEvents << " / " << nESDEvents << endl; return; } // ######################################################## // loop over number of events cout << " looping over events..." << endl; for(Int_t i=0; i<nEvents; i++) { esdBranch->GetEntry(i); runLoader->GetEvent(i); // ######################################################## // get the EDS vertex AliESDVertex* vtxESD = esd->GetVertex(); Double_t vtx[3]; Double_t vtx_res[3]; vtxESD->GetXYZ(vtx); vtx_res[0] = vtxESD->GetXRes(); vtx_res[1] = vtxESD->GetYRes(); vtx_res[2] = vtxESD->GetZRes(); // the vertex should be reconstructed if (strcmp(vtxESD->GetName(),"default")==0) continue; // the resolution should be reasonable??? if (vtx_res[2]==0 || vtx_res[2]>0.1) continue; // ######################################################## // loop over mc particles AliStack* particleStack = runLoader->Stack(); Int_t nPrim = particleStack->GetNprimary(); for (Int_t i_mc=0; i_mc<nPrim; i_mc++) { TParticle* part = particleStack->Particle(i_mc); if (!part || strcmp(part->GetName(),"XXX")==0) continue; TParticlePDG* pdgPart = part->GetPDG(); Bool_t prim = kFALSE; // check if it's a primary particle - is there a better way ??? if ((part->GetFirstDaughter() >= nPrim) || (part->GetFirstDaughter()==-1)) { if (TMath::Abs(pdgPart->PdgCode())>10 && pdgPart->PdgCode()!=21 && strcmp(pdgPart->ParticleClass(),"Unknown")!=0) prim = kTRUE; } if (!prim) continue; if (pdgPart->Charge()==0) continue; if (prim) PtEtaMap->FillGene(part->Pt(), part->Eta()); }// end of mc particle // ######################################################## // loop over esd tracks Int_t nTracks = esd->GetNumberOfTracks(); for (Int_t t=0; t<nTracks; t++) { AliESDtrack* esdTrack = esd->GetTrack(t); // cut the esd track? if (!esdTrackCuts->AcceptTrack(esdTrack)) continue; Double_t Ptr0[3]; if(!esdTrack->GetPxPyPz(Ptr0)) continue; fTrP= new TVector3(Ptr0); PtEtaMap->FillMeas(fTrP->Pt(), fTrP->Eta()); } // end of track loop } // end of event loop } // end of run loop PtEtaMap->Finish(); TFile* fout = new TFile("PtEtaCorrectionMap.root","RECREATE"); esdTrackCuts->SaveHistograms("EsdTrackCuts"); PtEtaMap->SaveHistograms(); fout->Write(); fout->Close(); } <commit_msg>small fix (martin)<commit_after>/* $Id$ */ // // Script to calculate PtvsEta correction map using the CorrectionMatrix2D class. // makeCorrectionPtEta(Char_t* dataDir, Int_t nRuns=20) { Char_t str[256]; gSystem->Load("../libPWG0base.so"); // ######################################################## // selection of esd tracks AliESDtrackCuts* esdTrackCuts = new AliESDtrackCuts(); esdTrackCuts->DefineHistograms(1); esdTrackCuts->SetMinNClustersTPC(50); esdTrackCuts->SetMaxChi2PerClusterTPC(3.5); esdTrackCuts->SetMaxCovDiagonalElements(2,2,0.5,0.5,2); esdTrackCuts->SetRequireTPCRefit(kTRUE); esdTrackCuts->SetMinNsigmaToVertex(3); esdTrackCuts->SetAcceptKingDaughters(kFALSE); AliLog::SetClassDebugLevel("AliESDtrackCuts",1); AliLog::SetClassDebugLevel("ESDtrackQualityCuts",1); // ######################################################## // definition of PtEta correction object CorrectionMatrix2D* PtEtaMap = new CorrectionMatrix2D("PtvsEta","PtvsEta",80,0.,10.,120,-2.,2.); //PtEtaMap->SetHist("PtEta",80,0.,10.,120,-2.,2.); //Float_t x[]={-20., -15., -5., 0., 6., 20.}; //Float_t y[]={-6. , -3., -1., 2., 3., 6. }; //PtEtaMap->SetHist("PtEta",5,x,5,y); //PtEtaMap->SetHistTitle("p_{t}","#eta"); // ######################################################## // get the data dir Char_t execDir[256]; sprintf(execDir,gSystem->pwd()); TSystemDirectory* baseDir = new TSystemDirectory(".",dataDir); TList* dirList = baseDir->GetListOfFiles(); Int_t nDirs = dirList->GetEntries(); // go back to the dir where this script is executed gSystem->cd(execDir); // ######################################################## // definition of used pointers TFile* esdFile; TTree* esdTree; TBranch* esdBranch; AliESD* esd =0; // ######################################################## // loop over runs Int_t nRunCounter = 0; for (Int_t r=0; r<nDirs; r++) { TSystemFile* presentDir = (TSystemFile*)dirList->At(r); if (!presentDir || !presentDir->IsDirectory()) continue; // check that the files are there TString currentDataDir; currentDataDir.Form("%s/%s",dataDir, presentDir->GetName()); cout << "Processing directory " << currentDataDir.Data() << endl; if ((!gSystem->Which(currentDataDir,"galice.root")) || (!gSystem->Which(currentDataDir,"AliESDs.root"))) continue; if (nRunCounter++ >= nRuns) break; cout << "run #" << nRunCounter << endl; // ######################################################### // setup galice and runloader if (gAlice) { delete gAlice->GetRunLoader(); delete gAlice; gAlice=0; } sprintf(str,"%s/galice.root",currentDataDir.Data()); AliRunLoader* runLoader = AliRunLoader::Open(str); runLoader->LoadgAlice(); gAlice = runLoader->GetAliRun(); runLoader->LoadKinematics(); runLoader->LoadHeader(); // ######################################################### // open esd file and get the tree sprintf(str,"%s/AliESDs.root",currentDataDir.Data()); // close it first to avoid memory leak if (esdFile) if (esdFile->IsOpen()) esdFile->Close(); esdFile = TFile::Open(str); esdTree = (TTree*)esdFile->Get("esdTree"); if (!esdTree) continue; esdBranch = esdTree->GetBranch("ESD"); esdBranch->SetAddress(&esd); if (!esdBranch) continue; // ######################################################## // Magnetic field AliTracker::SetFieldMap(gAlice->Field(),kTRUE); // kTRUE means uniform magnetic field //AliKalmanTrack::SetConvConst(1000/0.299792458/5.); // ######################################################## // getting number of events Int_t nEvents = (Int_t)runLoader->GetNumberOfEvents(); Int_t nESDEvents = esdBranch->GetEntries(); if (nEvents!=nESDEvents) { cout << " Different number of events from runloader and esdtree!!!" << nEvents << " / " << nESDEvents << endl; return; } // ######################################################## // loop over number of events cout << " looping over events..." << endl; for(Int_t i=0; i<nEvents; i++) { esdBranch->GetEntry(i); runLoader->GetEvent(i); // ######################################################## // get the EDS vertex AliESDVertex* vtxESD = esd->GetVertex(); Double_t vtx[3]; Double_t vtx_res[3]; vtxESD->GetXYZ(vtx); vtx_res[0] = vtxESD->GetXRes(); vtx_res[1] = vtxESD->GetYRes(); vtx_res[2] = vtxESD->GetZRes(); // the vertex should be reconstructed if (strcmp(vtxESD->GetName(),"default")==0) continue; // the resolution should be reasonable??? if (vtx_res[2]==0 || vtx_res[2]>0.1) continue; // ######################################################## // loop over mc particles AliStack* particleStack = runLoader->Stack(); Int_t nPrim = particleStack->GetNprimary(); for (Int_t i_mc=0; i_mc<nPrim; i_mc++) { TParticle* part = particleStack->Particle(i_mc); if (!part || strcmp(part->GetName(),"XXX")==0) continue; TParticlePDG* pdgPart = part->GetPDG(); Bool_t prim = kFALSE; // check if it's a primary particle - is there a better way ??? if ((part->GetFirstDaughter() >= nPrim) || (part->GetFirstDaughter()==-1)) { if (TMath::Abs(pdgPart->PdgCode())>10 && pdgPart->PdgCode()!=21 && strcmp(pdgPart->ParticleClass(),"Unknown")!=0) prim = kTRUE; } if (!prim) continue; if (pdgPart->Charge()==0) continue; if (prim) PtEtaMap->FillGene(part->Pt(), part->Eta()); }// end of mc particle // ######################################################## // loop over esd tracks Int_t nTracks = esd->GetNumberOfTracks(); for (Int_t t=0; t<nTracks; t++) { AliESDtrack* esdTrack = esd->GetTrack(t); // cut the esd track? if (!esdTrackCuts->AcceptTrack(esdTrack)) continue; Double_t Ptr0[3]; if(!esdTrack->GetPxPyPz(Ptr0)) continue; fTrP= new TVector3(Ptr0); PtEtaMap->FillMeas(fTrP->Pt(), fTrP->Eta()); } // end of track loop } // end of event loop } // end of run loop PtEtaMap->Divide(); PtEtaMap->RemoveEdges(); TFile* fout = new TFile("PtEtaCorrectionMap.root","RECREATE"); esdTrackCuts->SaveHistograms("EsdTrackCuts"); PtEtaMap->SaveHistograms(); fout->Write(); fout->Close(); } <|endoftext|>
<commit_before>void RunAlignmentDataFilterITS() { // // Macro to extract AliTrackPoints for ITS // A.Dainese, [email protected] // // Input Bool_t singlefile=kFALSE; //TString esdpath="/home/dainesea/alignData/RAWdata_CosmicsSum09/RecoSPD/chunk."; TString esdpath="/home/dainesea/alignData/RAWdata_CosmicsSum09/RecoITS_B_mille_SPD_SDDSSDsurvey_SSDHLayer_th50_130709/chunk."; Int_t ifirst=1, ilast=11; // Int_t nentries=1234567890; Int_t firstentry=0; // Load PWG1 library gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libPWG1.so"); // Create the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("testAnalysis"); // Create the task AliAlignmentDataFilterITS *taskFilter = new AliAlignmentDataFilterITS("filterITS"); AliLog::SetClassDebugLevel("AliAlignmentDataFilterITS",10); // configuration via AliITSRecoParam (should be taken from OCDB) AliITSRecoParam *itsRecoParam = AliITSRecoParam::GetCosmicTestParam(); itsRecoParam->SetAlignFilterUseLayer(0,kTRUE); itsRecoParam->SetAlignFilterUseLayer(1,kTRUE); itsRecoParam->SetAlignFilterUseLayer(2,kFALSE); itsRecoParam->SetAlignFilterUseLayer(3,kFALSE); itsRecoParam->SetAlignFilterUseLayer(4,kFALSE); itsRecoParam->SetAlignFilterUseLayer(5,kFALSE); taskFilter->SetITSRecoParam(itsRecoParam); taskFilter->SetOnlySPDFO(); // Add ESD handler AliESDInputHandler *esdH = new AliESDInputHandler(); mgr->SetInputEventHandler(esdH); TChain *chainESD = new TChain("esdTree"); if(singlefile) { chainESD->Add("AliESDs.root"); } else { for(Int_t i=ifirst; i<=ilast; i++) { TString esdfile=esdpath; esdfile+=i; esdfile.Append("/AliESDs.root"); chainESD->Add(esdfile.Data()); } } // Attach input cInput = mgr->CreateContainer("cInput",TChain::Class(),AliAnalysisManager::kInputContainer); //mgr->ConnectInput(taskFilter, 0, cInput); // v4-16-Release mgr->ConnectInput(taskFilter,0,mgr->GetCommonInputContainer()); // Attach output cOutput0= mgr->CreateContainer("cOutput0",TTree::Class(),AliAnalysisManager::kOutputContainer,"AliTrackPoints.root"); mgr->ConnectOutput(taskFilter,0,cOutput0); cOutput1= mgr->CreateContainer("cOutput1",TList::Class(),AliAnalysisManager::kOutputContainer,"AliTrackPoints.root"); mgr->ConnectOutput(taskFilter,1,cOutput1); // Enable debug printouts mgr->SetDebugLevel(10); // Run analysis mgr->InitAnalysis(); mgr->PrintStatus(); mgr->StartAnalysis("local",chainESD,nentries,firstentry); return; } <commit_msg>Remove obsolete macro<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabvwshg.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2006-07-21 15:18:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- //#define SI_VCDRAWOBJ #include <tools/urlobj.hxx> #include <svx/fmglob.hxx> #include <svx/svdouno.hxx> #include <svx/svdpagv.hxx> #include <sfx2/objsh.hxx> #include <sfx2/docfile.hxx> #include <com/sun/star/form/FormButtonType.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/awt/XControlModel.hpp> using namespace com::sun::star; #include "tabvwsh.hxx" #include "document.hxx" #include "drawview.hxx" #include "globstr.hrc" #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> #endif //------------------------------------------------------------------------ void ScTabViewShell::InsertURLButton( const String& rName, const String& rURL, const String& rTarget, const Point* pInsPos ) { // Tabelle geschuetzt ? ScViewData* pViewData = GetViewData(); ScDocument* pDoc = pViewData->GetDocument(); SCTAB nTab = pViewData->GetTabNo(); if ( pDoc->IsTabProtected(nTab) ) { ErrorMessage(STR_PROTECTIONERR); return; } MakeDrawLayer(); ScTabView* pView = pViewData->GetView(); // SdrView* pDrView = pView->GetSdrView(); ScDrawView* pDrView = pView->GetScDrawView(); SdrModel* pModel = pDrView->GetModel(); SdrObject* pObj = SdrObjFactory::MakeNewObject(FmFormInventor, OBJ_FM_BUTTON, pDrView->GetPageViewPvNum(0)->GetPage(), pModel); SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, pObj); uno::Reference<awt::XControlModel> xControlModel = pUnoCtrl->GetUnoControlModel(); DBG_ASSERT( xControlModel.is(), "UNO-Control ohne Model" ); if( !xControlModel.is() ) return; uno::Reference< beans::XPropertySet > xPropSet( xControlModel, uno::UNO_QUERY ); uno::Any aAny; aAny <<= rtl::OUString(rName); xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "Label" ), aAny ); ::rtl::OUString aTmp = INetURLObject::GetAbsURL( pDoc->GetDocumentShell()->GetMedium()->GetBaseURL(), rURL ); aAny <<= aTmp; xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetURL" ), aAny ); if( rTarget.Len() ) { aAny <<= rtl::OUString(rTarget); xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetFrame" ), aAny ); } form::FormButtonType eButtonType = form::FormButtonType_URL; aAny <<= eButtonType; xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "ButtonType" ), aAny ); if ( Sound::IsSoundFile( rURL ) ) { // #105638# OJ aAny <<= sal_True; xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DispatchURLInternal" )), aAny ); } Point aPos; if (pInsPos) aPos = *pInsPos; else aPos = GetInsertPos(); // Groesse wie in 3.1: Size aSize = GetActiveWin()->PixelToLogic(Size(140, 20)); if ( pDoc->IsNegativePage(nTab) ) aPos.X() -= aSize.Width(); pObj->SetLogicRect(Rectangle(aPos, aSize)); // pObj->Resize(Point(), Fraction(1, 1), Fraction(1, 1)); // am alten VC-Button musste die Position/Groesse nochmal explizit // gesetzt werden - das scheint mit UnoControls nicht noetig zu sein // nicht markieren wenn Ole pDrView->InsertObjectSafe( pObj, *pDrView->GetPageViewPvNum(0) ); } <commit_msg>INTEGRATION: CWS aw024 (1.8.88); FILE MERGED 2006/08/03 19:36:00 aw 1.8.88.4: RESYNC: (1.9-1.10); FILE MERGED 2005/09/20 04:01:04 aw 1.8.88.3: RESYNC: (1.8-1.9); FILE MERGED 2005/05/26 11:16:19 aw 1.8.88.2: #i39531# 2005/05/19 12:08:18 aw 1.8.88.1: #i39529#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabvwshg.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2006-11-14 16:00:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- //#define SI_VCDRAWOBJ #include <tools/urlobj.hxx> #include <svx/fmglob.hxx> #include <svx/svdouno.hxx> #include <svx/svdpagv.hxx> #include <sfx2/objsh.hxx> #include <sfx2/docfile.hxx> #include <com/sun/star/form/FormButtonType.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/awt/XControlModel.hpp> using namespace com::sun::star; #include "tabvwsh.hxx" #include "document.hxx" #include "drawview.hxx" #include "globstr.hrc" #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> #endif //------------------------------------------------------------------------ void ScTabViewShell::InsertURLButton( const String& rName, const String& rURL, const String& rTarget, const Point* pInsPos ) { // Tabelle geschuetzt ? ScViewData* pViewData = GetViewData(); ScDocument* pDoc = pViewData->GetDocument(); SCTAB nTab = pViewData->GetTabNo(); if ( pDoc->IsTabProtected(nTab) ) { ErrorMessage(STR_PROTECTIONERR); return; } MakeDrawLayer(); ScTabView* pView = pViewData->GetView(); // SdrView* pDrView = pView->GetSdrView(); ScDrawView* pDrView = pView->GetScDrawView(); SdrModel* pModel = pDrView->GetModel(); SdrObject* pObj = SdrObjFactory::MakeNewObject(FmFormInventor, OBJ_FM_BUTTON, pDrView->GetSdrPageView()->GetPage(), pModel); SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, pObj); uno::Reference<awt::XControlModel> xControlModel = pUnoCtrl->GetUnoControlModel(); DBG_ASSERT( xControlModel.is(), "UNO-Control ohne Model" ); if( !xControlModel.is() ) return; uno::Reference< beans::XPropertySet > xPropSet( xControlModel, uno::UNO_QUERY ); uno::Any aAny; aAny <<= rtl::OUString(rName); xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "Label" ), aAny ); ::rtl::OUString aTmp = INetURLObject::GetAbsURL( pDoc->GetDocumentShell()->GetMedium()->GetBaseURL(), rURL ); aAny <<= aTmp; xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetURL" ), aAny ); if( rTarget.Len() ) { aAny <<= rtl::OUString(rTarget); xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetFrame" ), aAny ); } form::FormButtonType eButtonType = form::FormButtonType_URL; aAny <<= eButtonType; xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "ButtonType" ), aAny ); if ( Sound::IsSoundFile( rURL ) ) { // #105638# OJ aAny <<= sal_True; xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DispatchURLInternal" )), aAny ); } Point aPos; if (pInsPos) aPos = *pInsPos; else aPos = GetInsertPos(); // Groesse wie in 3.1: Size aSize = GetActiveWin()->PixelToLogic(Size(140, 20)); if ( pDoc->IsNegativePage(nTab) ) aPos.X() -= aSize.Width(); pObj->SetLogicRect(Rectangle(aPos, aSize)); // pObj->Resize(Point(), Fraction(1, 1), Fraction(1, 1)); // am alten VC-Button musste die Position/Groesse nochmal explizit // gesetzt werden - das scheint mit UnoControls nicht noetig zu sein // nicht markieren wenn Ole pDrView->InsertObjectSafe( pObj, *pDrView->GetSdrPageView() ); } <|endoftext|>
<commit_before>// // Class AliRsnEventCuts // // This class constitutes an interface to the AliEventCuts class // supported and maintained by the DPG starting from LHC Run 2 // for period-by-period standard cuts on events, including // vertex cuts, background and pileup rejection, etc... // // authors: P. Ganoti, F. Bellini // #include "AliRsnEventCuts.h" #include "AliEventCuts.h" //#include "AliESDtrackCuts.h" //#include "AliMultSelection.h" //#include "AliMCEvent.h" //#include "AliMCParticle.h" //#include "AliAODMCParticle.h" //#include <AliHeader.h> //#include <AliAODMCHeader.h> //#include <AliGenDPMjetEventHeader.h> ClassImp(AliRsnEventCuts) //_________________________________________________________________________________________________ AliRsnEventCuts::AliRsnEventCuts(const char *name) : AliRsnCut(name, AliRsnCut::kEvent), fEvCuts(0x0) { // // Main constructor. // } //_________________________________________________________________________________________________ AliRsnEventCuts::AliRsnEventCuts(const AliRsnEventCuts &copy) : AliRsnCut(copy), fEvCuts(copy.fEvCuts) { // // Copy constructor. // } //------------------------------------------------------------------------------------------------- AliRsnEventCuts &AliRsnEventCuts::operator=(const AliRsnEventCuts &copy) { // // Assignment operator. // Works like copy constructor. // AliRsnCut::operator=(copy); if (this == &copy) return *this; fEvCuts = copy.fEvCuts; return (*this); } //_________________________________________________________________________________________________ Bool_t AliRsnEventCuts::Init(TObject *object) { // fills data member objects without applying cuts if (!TargetOK(object)) return kFALSE; return kTRUE; } //_________________________________________________________________________________________________ Bool_t AliRsnEventCuts::IsSelected(TObject *object) { // // Cut checker // // coherence check // which also fills data member objects if (!Init(object)) return kFALSE; // retrieve event AliVEvent *vevt = dynamic_cast<AliVEvent *>(fEvent->GetRef()); if (!vevt) return kFALSE; fEvCuts = new AliEventCuts(); if (fUsePbPb2018) fEvCuts->SetupPbPb2018(); Bool_t accept = kTRUE; if (!fEvCuts->AcceptEvent(vevt)) return kFALSE; return accept; } <commit_msg>add MultSelection object<commit_after>// // Class AliRsnEventCuts // // This class constitutes an interface to the AliEventCuts class // supported and maintained by the DPG starting from LHC Run 2 // for period-by-period standard cuts on events, including // vertex cuts, background and pileup rejection, etc... // // authors: P. Ganoti, F. Bellini // #include "AliRsnEventCuts.h" #include "AliEventCuts.h" //#include "AliESDtrackCuts.h" #include "AliMultSelection.h" //#include "AliMCEvent.h" //#include "AliMCParticle.h" //#include "AliAODMCParticle.h" //#include <AliHeader.h> //#include <AliAODMCHeader.h> //#include <AliGenDPMjetEventHeader.h> ClassImp(AliRsnEventCuts) //_________________________________________________________________________________________________ AliRsnEventCuts::AliRsnEventCuts(const char *name) : AliRsnCut(name, AliRsnCut::kEvent), fEvCuts(0x0) { // // Main constructor. // } //_________________________________________________________________________________________________ AliRsnEventCuts::AliRsnEventCuts(const AliRsnEventCuts &copy) : AliRsnCut(copy), fEvCuts(copy.fEvCuts) { // // Copy constructor. // } //------------------------------------------------------------------------------------------------- AliRsnEventCuts &AliRsnEventCuts::operator=(const AliRsnEventCuts &copy) { // // Assignment operator. // Works like copy constructor. // AliRsnCut::operator=(copy); if (this == &copy) return *this; fEvCuts = copy.fEvCuts; return (*this); } //_________________________________________________________________________________________________ Bool_t AliRsnEventCuts::Init(TObject *object) { // fills data member objects without applying cuts if (!TargetOK(object)) return kFALSE; return kTRUE; } //_________________________________________________________________________________________________ Bool_t AliRsnEventCuts::IsSelected(TObject *object) { // // Cut checker // // coherence check // which also fills data member objects if (!Init(object)) return kFALSE; // retrieve event AliVEvent *vevt = dynamic_cast<AliVEvent *>(fEvent->GetRef()); if (!vevt) return kFALSE; fEvCuts = new AliEventCuts(); if (fUsePbPb2018) fEvCuts->SetupPbPb2018(); Bool_t accept = kTRUE; if(!IsAcceptedMultSelection()) return kFALSE; if (!fEvCuts->AcceptEvent(vevt)) return kFALSE; return accept; } //_________________________________________________________________________________________________ Bool_t AliRsnEventCuts::IsAcceptedMultSelection() { AliMultSelection *MultSelection=0; if(!fEvent) return kFALSE; AliESDEvent* esdEvt=0; Bool_t isESD=fEvent->IsESD(); if(isESD) esdEvt=dynamic_cast<AliESDEvent *>(fEvent->GetRef()); if(isESD && esdEvt){ MultSelection=(AliMultSelection*) esdEvt->FindListObject("MultSelection"); if(!MultSelection) return kTRUE; if(MultSelection->IsEventSelected()) return kTRUE; return kFALSE; } return kFALSE; } <|endoftext|>
<commit_before>#include <fstream> #include <sstream> #include <vector> #include <iostream> #include <utility> #include <optional> #include "core/argparse.h" #include "core/io.h" #include "core/image.h" #include "core/image_draw.h" #include "core/pack.h" using namespace euphoria::core; struct ImageAndFile { ImageAndFile() {} ImageAndFile(const std::string& f, const Image& i) : file(f) , image(i) {} std::string file; Image image; }; std::vector<Sizei> CollectSizes ( const std::vector<ImageAndFile>& images, int padding ) { auto sizes = std::vector<Sizei>{}; for(const auto& img: images) { sizes.emplace_back(Sizei::FromWidthHeight ( img.image.GetWidth() + padding, img.image.GetHeight() + padding )); } return sizes; } std::vector<ImageAndFile> LoadImages(const std::vector<std::string>& files) { auto images = std::vector<ImageAndFile>{}; for(const auto& f: files) { auto chunk = io::FileToChunk(f); if(chunk == nullptr) { std::cerr << "failed to read " << f << "\n"; return {}; } auto loaded_image = LoadImage(chunk, f, AlphaLoad::Keep); if(loaded_image.error.empty() == false) { std::cerr << "failed to read image " << loaded_image.error << "\n"; return {}; } images.emplace_back(f, loaded_image.image); } return images; } struct PackedImage { PackedImage() : rect(Recti::FromWidthHeight(0,0)) {} PackedImage(const std::string& f, const Image& i, const Recti& p) : file(f) , image(i) , rect(p) {} std::string file; Image image; Recti rect; }; std::vector<PackedImage> PackImage ( const Sizei& image_size, const std::vector<ImageAndFile>& images, int padding ) { const auto image_sizes = CollectSizes(images, padding); const auto packed = Pack(image_size, image_sizes); auto ret = std::vector<PackedImage>{}; int i = 0; for(const auto& rect: packed) { const auto& src = images[i]; i += 1; if(rect.has_value() == false) { std::cerr << "failed to pack " << src.file << "\n"; } else { ret.emplace_back(src.file, src.image, *rect); } } return ret; } Sizei PackTight ( const Sizei& default_size, std::vector<PackedImage>* images, int padding ) { std::optional<Recti> bb = std::nullopt; for(const auto& img: *images) { const auto& rect = img.rect; if(bb.has_value()) { bb->Include(rect); } else { bb = rect; } } if(!bb) { return default_size; } const auto size = bb->GetSize(); const auto dx = -bb->left; const auto dy = -bb->bottom; for(auto& img: *images) { img.rect.Offset(dx, dy); } return Sizei::FromWidthHeight(size.width + padding, size.height+padding); } Image DrawImage ( const std::vector<PackedImage>& images, const Sizei& size, const Rgbi& background_color ) { auto composed_image = Image{}; composed_image.SetupWithAlphaSupport ( size.width, size.height ); Clear(&composed_image, background_color); for(const auto& image: images) { PasteImage ( &composed_image, image.rect.BottomLeft(), image.image, PixelsOutside::Discard ); } return composed_image; } bool HandlePack ( const std::string& output_file, const Sizei& requested_size, int padding, Rgbi background_color, bool pack_image, const std::vector<std::string>& files ) { if( requested_size.width < padding || requested_size.height < padding) { std::cerr << "padding too large\n"; return false; } const auto image_size = Sizei::FromWidthHeight ( requested_size.width - padding, requested_size.height - padding ); // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // pack images auto packed = PackImage(image_size, images, padding); if(packed.empty()) { return false; } // optionally reduce image size const auto size = pack_image ? PackTight(requested_size, &packed, padding) : requested_size ; // border-theory: // reuqested_size is decreased with padding // the tighlty packed size is increased with padding // the packed image-sizes is increased with padding // and finally all the images are offseted by padding // all to keep padding-sized border between the images for(auto& img: packed) { img.rect.Offset(padding, padding); } // draw new image auto composed_image = DrawImage(packed, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } int main(int argc, char* argv[]) { auto parser = argparse::Parser { "pack smaller images into a bigger one" }; auto subs = parser.AddSubParsers(); subs->Add ( "pack", "pack images according to the stb rect-pack algorithm", [](argparse::SubParser* sub) { // todo(Gustav): expose as commandline arguments auto image_size = Sizei::FromWidthHeight(1024, 1024); Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; bool pack_image = true; std::vector<std::string> files; sub->Add("--size", &image_size) .AllowBeforePositionals() .Nargs("S") .Help("change the image size") ; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->SetFalse("--no-pack", &pack_image) .AllowBeforePositionals() .Help("don't pack the resulting image and keep the whitespace") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; return sub->OnComplete([&] { const auto was_packed = HandlePack ( output_file, image_size, padding, background_color, pack_image, files ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); return ParseFromMain(&parser, argc, argv); } <commit_msg>added collage grid algorithm<commit_after>#include <fstream> #include <sstream> #include <vector> #include <iostream> #include <utility> #include <optional> #include "core/argparse.h" #include "core/io.h" #include "core/image.h" #include "core/image_draw.h" #include "core/pack.h" using namespace euphoria::core; struct ImageAndFile { ImageAndFile() {} ImageAndFile(const std::string& f, const Image& i) : file(f) , image(i) {} std::string file; Image image; }; std::vector<Sizei> CollectSizes ( const std::vector<ImageAndFile>& images, int padding ) { auto sizes = std::vector<Sizei>{}; for(const auto& img: images) { sizes.emplace_back(Sizei::FromWidthHeight ( img.image.GetWidth() + padding, img.image.GetHeight() + padding )); } return sizes; } std::vector<ImageAndFile> LoadImages(const std::vector<std::string>& files) { auto images = std::vector<ImageAndFile>{}; for(const auto& f: files) { auto chunk = io::FileToChunk(f); if(chunk == nullptr) { std::cerr << "failed to read " << f << "\n"; return {}; } auto loaded_image = LoadImage(chunk, f, AlphaLoad::Keep); if(loaded_image.error.empty() == false) { std::cerr << "failed to read image " << loaded_image.error << "\n"; return {}; } images.emplace_back(f, loaded_image.image); } return images; } struct PackedImage { PackedImage() : rect(Recti::FromWidthHeight(0,0)) {} PackedImage(const std::string& f, const Image& i, const Recti& p) : file(f) , image(i) , rect(p) {} std::string file; Image image; Recti rect; }; std::vector<PackedImage> PackImage ( const Sizei& image_size, const std::vector<ImageAndFile>& images, int padding ) { const auto image_sizes = CollectSizes(images, padding); const auto packed = Pack(image_size, image_sizes); auto ret = std::vector<PackedImage>{}; int i = 0; for(const auto& rect: packed) { const auto& src = images[i]; i += 1; if(rect.has_value() == false) { std::cerr << "failed to pack " << src.file << "\n"; } else { ret.emplace_back(src.file, src.image, *rect); } } return ret; } Sizei PackTight ( const Sizei& default_size, std::vector<PackedImage>* images, int padding ) { std::optional<Recti> bb = std::nullopt; for(const auto& img: *images) { const auto& rect = img.rect; if(bb.has_value()) { bb->Include(rect); } else { bb = rect; } } if(!bb) { return default_size; } const auto size = bb->GetSize(); const auto dx = -bb->left; const auto dy = -bb->bottom; for(auto& img: *images) { img.rect.Offset(dx, dy); } return Sizei::FromWidthHeight(size.width + padding, size.height+padding); } Image DrawImage ( const std::vector<PackedImage>& images, const Sizei& size, const Rgbi& background_color ) { auto composed_image = Image{}; composed_image.SetupWithAlphaSupport ( size.width, size.height ); Clear(&composed_image, background_color); for(const auto& image: images) { PasteImage ( &composed_image, image.rect.BottomLeft(), image.image, PixelsOutside::Discard ); } return composed_image; } std::pair<std::vector<PackedImage>, Sizei> GridLayout(const std::vector<ImageAndFile>& images, int padding) { const auto images_per_row = Ceil(Sqrt(images.size())); auto ret = std::vector<PackedImage>{}; int x = padding; int y = padding; int current_height = 0; int column = 0; int max_x = 0; auto new_row = [&] { max_x = Max(max_x, x); column = 0; x = padding; y += current_height + padding; current_height = 0; }; for(const auto& src: images) { const auto width = src.image.GetWidth(); const auto height = src.image.GetHeight(); ret.emplace_back ( src.file, src.image, Recti::FromBottomLeftWidthHeight ( vec2i(x, y), width, height ) ); x += width + padding; current_height = Max(current_height, height); column += 1; if(column >= images_per_row) { new_row(); } } if(column != 0) { new_row(); } return {ret, Sizei::FromWidthHeight(max_x, y)}; } bool HandleGrid ( const std::string& output_file, int padding, Rgbi background_color, const std::vector<std::string>& files ) { // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // layout images in grid and calculate image size from grid const auto [image_grid, size] = GridLayout(images, padding); // draw new image auto composed_image = DrawImage(image_grid, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } bool HandlePack ( const std::string& output_file, const Sizei& requested_size, int padding, Rgbi background_color, bool pack_image, const std::vector<std::string>& files ) { if( requested_size.width < padding || requested_size.height < padding) { std::cerr << "padding too large\n"; return false; } const auto image_size = Sizei::FromWidthHeight ( requested_size.width - padding, requested_size.height - padding ); // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // pack images auto packed = PackImage(image_size, images, padding); if(packed.empty()) { return false; } // optionally reduce image size const auto size = pack_image ? PackTight(requested_size, &packed, padding) : requested_size ; // border-theory: // reuqested_size is decreased with padding // the tighlty packed size is increased with padding // the packed image-sizes is increased with padding // and finally all the images are offseted by padding // all to keep padding-sized border between the images for(auto& img: packed) { img.rect.Offset(padding, padding); } // draw new image auto composed_image = DrawImage(packed, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } int main(int argc, char* argv[]) { auto parser = argparse::Parser { "pack smaller images into a bigger one" }; auto subs = parser.AddSubParsers(); subs->Add ( "grid", "lay put images in a grid", [](argparse::SubParser* sub) { Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; std::vector<std::string> files; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; return sub->OnComplete([&] { const auto was_packed = HandleGrid ( output_file, padding, background_color, files ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); subs->Add ( "pack", "pack images according to the stb rect-pack algorithm", [](argparse::SubParser* sub) { auto image_size = Sizei::FromWidthHeight(1024, 1024); Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; bool pack_image = true; std::vector<std::string> files; sub->Add("--size", &image_size) .AllowBeforePositionals() .Nargs("S") .Help("change the image size") ; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->SetFalse("--no-pack", &pack_image) .AllowBeforePositionals() .Help("don't pack the resulting image and keep the whitespace") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; return sub->OnComplete([&] { const auto was_packed = HandlePack ( output_file, image_size, padding, background_color, pack_image, files ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); return ParseFromMain(&parser, argc, argv); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/net/url_fixer_upper.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" namespace { const wchar_t kDocRoot[] = L"chrome/test/data"; } // namespace typedef UITest CollectedCookiesTest; TEST_F(CollectedCookiesTest, TestDoubleDisplay) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); // Disable cookies. ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES, CONTENT_SETTING_BLOCK)); // Load a page with cookies. ASSERT_TRUE(tab->NavigateToURL(server->TestServerPage("files/cookie1.html"))); // Click on the info link twice. ASSERT_TRUE(tab->ShowCollectedCookiesDialog()); ASSERT_TRUE(tab->ShowCollectedCookiesDialog()); } TEST_F(CollectedCookiesTest, NavigateAway) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); // Disable cookies. ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES, CONTENT_SETTING_BLOCK)); // Load a page with cookies. ASSERT_TRUE(tab->NavigateToURL(server->TestServerPage("files/cookie1.html"))); // Click on the info link. ASSERT_TRUE(tab->ShowCollectedCookiesDialog()); // Navigate to another page. ASSERT_TRUE(tab->NavigateToURL(server->TestServerPage("files/cookie2.html"))); } <commit_msg>Marked TEST_F(CollectedCookiesTest, FAILS_TestDoubleDisplay) and TEST_F(CollectedCookiesTest, FAILS_NavigateAway) because they were causing issues in the build waterfall.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/net/url_fixer_upper.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" namespace { const wchar_t kDocRoot[] = L"chrome/test/data"; } // namespace typedef UITest CollectedCookiesTest; TEST_F(CollectedCookiesTest, FAILS_TestDoubleDisplay) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); // Disable cookies. ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES, CONTENT_SETTING_BLOCK)); // Load a page with cookies. ASSERT_TRUE(tab->NavigateToURL(server->TestServerPage("files/cookie1.html"))); // Click on the info link twice. ASSERT_TRUE(tab->ShowCollectedCookiesDialog()); ASSERT_TRUE(tab->ShowCollectedCookiesDialog()); } TEST_F(CollectedCookiesTest, FAILS_NavigateAway) { scoped_refptr<HTTPTestServer> server = HTTPTestServer::CreateServer(kDocRoot, NULL); ASSERT_TRUE(NULL != server.get()); scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); // Disable cookies. ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES, CONTENT_SETTING_BLOCK)); // Load a page with cookies. ASSERT_TRUE(tab->NavigateToURL(server->TestServerPage("files/cookie1.html"))); // Click on the info link. ASSERT_TRUE(tab->ShowCollectedCookiesDialog()); // Navigate to another page. ASSERT_TRUE(tab->NavigateToURL(server->TestServerPage("files/cookie2.html"))); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/ui/ui_test.h" #include "base/test/test_timeouts.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/dom_ui/new_tab_ui.h" #include "chrome/browser/prefs/pref_value_store.h" #include "chrome/browser/sync/signin_manager.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/json_pref_store.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/testing_pref_service.h" // This tests are failing consistently on "Linux (dbg)" and "Mac (dbg)" bots. // See http://crbug.com/72286. #ifndef OS_WIN #define NavBeforeNTPCommits FAILS_NavBeforeNTPCommits #define AboutHangInNTP FAILS_AboutHangInNTP #define NTPHasThumbnails FAILS_NTPHasThumbnails #endif class NewTabUITest : public UITest { public: NewTabUITest() { dom_automation_enabled_ = true; // Set home page to the empty string so that we can set the home page using // preferences. set_homepage(""); // Setup the DEFAULT_THEME profile (has fake history entries). set_template_user_data(UITest::ComputeTypicalUserDataSource( ProxyLauncher::DEFAULT_THEME)); } }; TEST_F(NewTabUITest, NTPHasThumbnails) { // Switch to the "new tab" tab, which should be any new tab after the // first (the first is about:blank). scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); // TopSites should return at least 3 non-filler pages. // 8 - 3 = max 5 filler pages. ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"", L"window.domAutomationController.send(" L"document.getElementsByClassName('filler').length <= 5)", TestTimeouts::action_max_timeout_ms())); } // Sometimes hangs: http://crbug.com/70157 TEST_F(NewTabUITest, DISABLED_NTPHasLoginName) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername, "[email protected]")); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); std::wstring displayed_username; // The login span should be eventually populated and have the // correct value. ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"", L"window.domAutomationController.send(" L"document.getElementById('login-username').innerText.length > 0)", TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(tab->ExecuteAndExtractString( L"", L"window.domAutomationController.send(" L"document.getElementById('login-username').innerText)", &displayed_username)); EXPECT_EQ(L"[email protected]", displayed_username); } // Loads about:hang into two NTP tabs, ensuring we don't crash. // See http://crbug.com/59859. TEST_F(NewTabUITest, AboutHangInNTP) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); // Navigate to about:hang to stall the process. ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); // Visit about:hang again in another NTP. Don't bother waiting for the // NTP to load, because it's hung. ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab2 = window->GetActiveTab(); ASSERT_TRUE(tab2.get()); ASSERT_TRUE(tab2->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); } // Allows testing NTP in process-per-tab mode. class NewTabUIProcessPerTabTest : public NewTabUITest { public: NewTabUIProcessPerTabTest() : NewTabUITest() {} protected: virtual void SetUp() { launch_arguments_.AppendSwitch(switches::kProcessPerTab); UITest::SetUp(); } }; // Navigates away from NTP before it commits, in process-per-tab mode. // Ensures that we don't load the normal page in the NTP process (and thus // crash), as in http://crbug.com/69224. TEST_F(NewTabUIProcessPerTabTest, NavBeforeNTPCommits) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); // Navigate to about:hang to stall the process. ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); // Visit a normal URL in another NTP that hasn't committed. ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab2 = window->GetActiveTab(); ASSERT_TRUE(tab2.get()); ASSERT_TRUE(tab2->NavigateToURL(GURL("data:text/html,hello world"))); } // Fails about ~5% of the time on all platforms. http://crbug.com/45001 TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Go to the "new tab page" using its old url, rather than chrome://newtab. scoped_refptr<TabProxy> tab = window->GetTab(0); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:"))); int load_time; ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); // Ensure there are some thumbnails loaded in the page. int thumbnails_count = -1; ASSERT_TRUE(tab->ExecuteAndExtractInt(L"", L"window.domAutomationController.send(" L"document.getElementsByClassName('thumbnail-container').length)", &thumbnails_count)); EXPECT_GT(thumbnails_count, 0); } // Flaky on XP bots: http://crbug.com/51726 TEST_F(NewTabUITest, FLAKY_UpdateUserPrefsVersion) { // PrefService with JSON user-pref file only, no enforced or advised prefs. scoped_ptr<PrefService> prefs(new TestingPrefService); // Does the migration NewTabUI::RegisterUserPrefs(prefs.get()); ASSERT_EQ(NewTabUI::current_pref_version(), prefs->GetInteger(prefs::kNTPPrefVersion)); // Reset the version prefs->ClearPref(prefs::kNTPPrefVersion); ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion)); bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get()); ASSERT_TRUE(migrated); ASSERT_EQ(NewTabUI::current_pref_version(), prefs->GetInteger(prefs::kNTPPrefVersion)); migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get()); ASSERT_FALSE(migrated); } <commit_msg>Revert 74110 - Adds "FAILS_" to failing tests This change adds "FAILS_" prefix to NavBeforeNTPCommits, AboutHangInNTP, and NTPHasThumbnails on Linux and Mac since it started failing since around r74087.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/ui/ui_test.h" #include "base/test/test_timeouts.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/dom_ui/new_tab_ui.h" #include "chrome/browser/prefs/pref_value_store.h" #include "chrome/browser/sync/signin_manager.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/json_pref_store.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/testing_pref_service.h" class NewTabUITest : public UITest { public: NewTabUITest() { dom_automation_enabled_ = true; // Set home page to the empty string so that we can set the home page using // preferences. set_homepage(""); // Setup the DEFAULT_THEME profile (has fake history entries). set_template_user_data(UITest::ComputeTypicalUserDataSource( ProxyLauncher::DEFAULT_THEME)); } }; TEST_F(NewTabUITest, NTPHasThumbnails) { // Switch to the "new tab" tab, which should be any new tab after the // first (the first is about:blank). scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); // TopSites should return at least 3 non-filler pages. // 8 - 3 = max 5 filler pages. ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"", L"window.domAutomationController.send(" L"document.getElementsByClassName('filler').length <= 5)", TestTimeouts::action_max_timeout_ms())); } // Sometimes hangs: http://crbug.com/70157 TEST_F(NewTabUITest, DISABLED_NTPHasLoginName) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername, "[email protected]")); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); std::wstring displayed_username; // The login span should be eventually populated and have the // correct value. ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"", L"window.domAutomationController.send(" L"document.getElementById('login-username').innerText.length > 0)", TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(tab->ExecuteAndExtractString( L"", L"window.domAutomationController.send(" L"document.getElementById('login-username').innerText)", &displayed_username)); EXPECT_EQ(L"[email protected]", displayed_username); } // Loads about:hang into two NTP tabs, ensuring we don't crash. // See http://crbug.com/59859. TEST_F(NewTabUITest, AboutHangInNTP) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); // Navigate to about:hang to stall the process. ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); // Visit about:hang again in another NTP. Don't bother waiting for the // NTP to load, because it's hung. ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab2 = window->GetActiveTab(); ASSERT_TRUE(tab2.get()); ASSERT_TRUE(tab2->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); } // Allows testing NTP in process-per-tab mode. class NewTabUIProcessPerTabTest : public NewTabUITest { public: NewTabUIProcessPerTabTest() : NewTabUITest() {} protected: virtual void SetUp() { launch_arguments_.AppendSwitch(switches::kProcessPerTab); UITest::SetUp(); } }; // Navigates away from NTP before it commits, in process-per-tab mode. // Ensures that we don't load the normal page in the NTP process (and thus // crash), as in http://crbug.com/69224. TEST_F(NewTabUIProcessPerTabTest, NavBeforeNTPCommits) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Bring up a new tab page. ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab = window->GetActiveTab(); ASSERT_TRUE(tab.get()); // Navigate to about:hang to stall the process. ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); // Visit a normal URL in another NTP that hasn't committed. ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB)); scoped_refptr<TabProxy> tab2 = window->GetActiveTab(); ASSERT_TRUE(tab2.get()); ASSERT_TRUE(tab2->NavigateToURL(GURL("data:text/html,hello world"))); } // Fails about ~5% of the time on all platforms. http://crbug.com/45001 TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) { scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); ASSERT_TRUE(window.get()); // Go to the "new tab page" using its old url, rather than chrome://newtab. scoped_refptr<TabProxy> tab = window->GetTab(0); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:"))); int load_time; ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); // Ensure there are some thumbnails loaded in the page. int thumbnails_count = -1; ASSERT_TRUE(tab->ExecuteAndExtractInt(L"", L"window.domAutomationController.send(" L"document.getElementsByClassName('thumbnail-container').length)", &thumbnails_count)); EXPECT_GT(thumbnails_count, 0); } // Flaky on XP bots: http://crbug.com/51726 TEST_F(NewTabUITest, FLAKY_UpdateUserPrefsVersion) { // PrefService with JSON user-pref file only, no enforced or advised prefs. scoped_ptr<PrefService> prefs(new TestingPrefService); // Does the migration NewTabUI::RegisterUserPrefs(prefs.get()); ASSERT_EQ(NewTabUI::current_pref_version(), prefs->GetInteger(prefs::kNTPPrefVersion)); // Reset the version prefs->ClearPref(prefs::kNTPPrefVersion); ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion)); bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get()); ASSERT_TRUE(migrated); ASSERT_EQ(NewTabUI::current_pref_version(), prefs->GetInteger(prefs::kNTPPrefVersion)); migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get()); ASSERT_FALSE(migrated); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/toolbar/toolbar_model.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete_input.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/ssl_error_info.h" #include "chrome/browser/ui/toolbar/toolbar_model_delegate.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/cert_store.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/content_constants.h" #include "content/public/common/ssl_status.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/cert_status_flags.h" #include "net/base/net_util.h" #include "ui/base/l10n/l10n_util.h" using content::NavigationController; using content::NavigationEntry; using content::SSLStatus; using content::WebContents; ToolbarModel::ToolbarModel(ToolbarModelDelegate* delegate) : delegate_(delegate), input_in_progress_(false) { } ToolbarModel::~ToolbarModel() { } // ToolbarModel Implementation. string16 ToolbarModel::GetText() const { GURL url(chrome::kAboutBlankURL); std::string languages; // Empty if we don't have a |navigation_controller|. NavigationController* navigation_controller = GetNavigationController(); if (navigation_controller) { Profile* profile = Profile::FromBrowserContext(navigation_controller->GetBrowserContext()); languages = profile->GetPrefs()->GetString(prefs::kAcceptLanguages); NavigationEntry* entry = navigation_controller->GetVisibleEntry(); if (!ShouldDisplayURL()) { url = GURL(); } else if (entry) { url = entry->GetVirtualURL(); } } if (url.spec().length() > content::kMaxURLDisplayChars) url = url.IsStandard() ? url.GetOrigin() : GURL(url.scheme() + ":"); // Note that we can't unescape spaces here, because if the user copies this // and pastes it into another program, that program may think the URL ends at // the space. return AutocompleteInput::FormattedStringWithEquivalentMeaning( url, net::FormatUrl(url, languages, net::kFormatUrlOmitAll, net::UnescapeRule::NORMAL, NULL, NULL, NULL)); } bool ToolbarModel::ShouldDisplayURL() const { // Note: The order here is important. // - The WebUI test must come before the extension scheme test because there // can be WebUIs that have extension schemes (e.g. the bookmark manager). In // that case, we should prefer what the WebUI instance says. // - The view-source test must come before the WebUI test because of the case // of view-source:chrome://newtab, which should display its URL despite what // chrome://newtab's WebUI says. NavigationController* controller = GetNavigationController(); NavigationEntry* entry = controller ? controller->GetVisibleEntry() : NULL; if (entry) { if (entry->IsViewSourceMode() || entry->GetPageType() == content::PAGE_TYPE_INTERSTITIAL) { return true; } } WebContents* web_contents = delegate_->GetActiveWebContents(); if (web_contents && web_contents->GetWebUIForCurrentState()) return !web_contents->GetWebUIForCurrentState()->ShouldHideURL(); if (entry && entry->GetURL().SchemeIs(chrome::kExtensionScheme)) return false; return true; } ToolbarModel::SecurityLevel ToolbarModel::GetSecurityLevel() const { if (input_in_progress_) // When editing, assume no security style. return NONE; NavigationController* navigation_controller = GetNavigationController(); if (!navigation_controller) // We might not have a controller on init. return NONE; NavigationEntry* entry = navigation_controller->GetVisibleEntry(); if (!entry) return NONE; const SSLStatus& ssl = entry->GetSSL(); switch (ssl.security_style) { case content::SECURITY_STYLE_UNKNOWN: case content::SECURITY_STYLE_UNAUTHENTICATED: return NONE; case content::SECURITY_STYLE_AUTHENTICATION_BROKEN: return SECURITY_ERROR; case content::SECURITY_STYLE_AUTHENTICATED: if (!!(ssl.content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)) return SECURITY_WARNING; if (net::IsCertStatusError(ssl.cert_status)) { DCHECK(net::IsCertStatusMinorError(ssl.cert_status)); return SECURITY_WARNING; } if ((ssl.cert_status & net::CERT_STATUS_IS_EV) && content::CertStore::GetInstance()->RetrieveCert(ssl.cert_id, NULL)) return EV_SECURE; return SECURE; default: NOTREACHED(); return NONE; } } int ToolbarModel::GetIcon() const { static int icon_ids[NUM_SECURITY_LEVELS] = { IDR_OMNIBOX_HTTP, IDR_OMNIBOX_HTTPS_VALID, IDR_OMNIBOX_HTTPS_VALID, IDR_OMNIBOX_HTTPS_WARNING, IDR_OMNIBOX_HTTPS_INVALID, }; DCHECK(arraysize(icon_ids) == NUM_SECURITY_LEVELS); return icon_ids[GetSecurityLevel()]; } string16 ToolbarModel::GetEVCertName() const { DCHECK_EQ(GetSecurityLevel(), EV_SECURE); scoped_refptr<net::X509Certificate> cert; // Note: Navigation controller and active entry are guaranteed non-NULL or // the security level would be NONE. content::CertStore::GetInstance()->RetrieveCert( GetNavigationController()->GetVisibleEntry()->GetSSL().cert_id, &cert); return GetEVCertName(*cert); } // static string16 ToolbarModel::GetEVCertName(const net::X509Certificate& cert) { // EV are required to have an organization name and country. if (cert.subject().organization_names.empty() || cert.subject().country_name.empty()) { NOTREACHED(); return string16(); } return l10n_util::GetStringFUTF16( IDS_SECURE_CONNECTION_EV, UTF8ToUTF16(cert.subject().organization_names[0]), UTF8ToUTF16(cert.subject().country_name)); } NavigationController* ToolbarModel::GetNavigationController() const { // This |current_tab| can be NULL during the initialization of the // toolbar during window creation (i.e. before any tabs have been added // to the window). WebContents* current_tab = delegate_->GetActiveWebContents(); return current_tab ? &current_tab->GetController() : NULL; } <commit_msg>Drive: Hide the URL on opening files on Drive.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/toolbar/toolbar_model.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete_input.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ssl/ssl_error_info.h" #include "chrome/browser/ui/toolbar/toolbar_model_delegate.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/cert_store.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/common/content_constants.h" #include "content/public/common/ssl_status.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/cert_status_flags.h" #include "net/base/net_util.h" #include "ui/base/l10n/l10n_util.h" using content::NavigationController; using content::NavigationEntry; using content::SSLStatus; using content::WebContents; ToolbarModel::ToolbarModel(ToolbarModelDelegate* delegate) : delegate_(delegate), input_in_progress_(false) { } ToolbarModel::~ToolbarModel() { } // ToolbarModel Implementation. string16 ToolbarModel::GetText() const { GURL url(chrome::kAboutBlankURL); std::string languages; // Empty if we don't have a |navigation_controller|. NavigationController* navigation_controller = GetNavigationController(); if (navigation_controller) { Profile* profile = Profile::FromBrowserContext(navigation_controller->GetBrowserContext()); languages = profile->GetPrefs()->GetString(prefs::kAcceptLanguages); NavigationEntry* entry = navigation_controller->GetVisibleEntry(); if (!ShouldDisplayURL()) { url = GURL(); } else if (entry) { url = entry->GetVirtualURL(); } } if (url.spec().length() > content::kMaxURLDisplayChars) url = url.IsStandard() ? url.GetOrigin() : GURL(url.scheme() + ":"); // Note that we can't unescape spaces here, because if the user copies this // and pastes it into another program, that program may think the URL ends at // the space. return AutocompleteInput::FormattedStringWithEquivalentMeaning( url, net::FormatUrl(url, languages, net::kFormatUrlOmitAll, net::UnescapeRule::NORMAL, NULL, NULL, NULL)); } bool ToolbarModel::ShouldDisplayURL() const { // Note: The order here is important. // - The WebUI test must come before the extension scheme test because there // can be WebUIs that have extension schemes (e.g. the bookmark manager). In // that case, we should prefer what the WebUI instance says. // - The view-source test must come before the WebUI test because of the case // of view-source:chrome://newtab, which should display its URL despite what // chrome://newtab's WebUI says. NavigationController* controller = GetNavigationController(); NavigationEntry* entry = controller ? controller->GetVisibleEntry() : NULL; if (entry) { if (entry->IsViewSourceMode() || entry->GetPageType() == content::PAGE_TYPE_INTERSTITIAL) { return true; } } WebContents* web_contents = delegate_->GetActiveWebContents(); if (web_contents && web_contents->GetWebUIForCurrentState()) return !web_contents->GetWebUIForCurrentState()->ShouldHideURL(); if (entry && entry->GetURL().SchemeIs(chrome::kExtensionScheme)) return false; #if defined(OS_CHROMEOS) if (entry && entry->GetURL().SchemeIs(chrome::kDriveScheme)) return false; #endif return true; } ToolbarModel::SecurityLevel ToolbarModel::GetSecurityLevel() const { if (input_in_progress_) // When editing, assume no security style. return NONE; NavigationController* navigation_controller = GetNavigationController(); if (!navigation_controller) // We might not have a controller on init. return NONE; NavigationEntry* entry = navigation_controller->GetVisibleEntry(); if (!entry) return NONE; const SSLStatus& ssl = entry->GetSSL(); switch (ssl.security_style) { case content::SECURITY_STYLE_UNKNOWN: case content::SECURITY_STYLE_UNAUTHENTICATED: return NONE; case content::SECURITY_STYLE_AUTHENTICATION_BROKEN: return SECURITY_ERROR; case content::SECURITY_STYLE_AUTHENTICATED: if (!!(ssl.content_status & SSLStatus::DISPLAYED_INSECURE_CONTENT)) return SECURITY_WARNING; if (net::IsCertStatusError(ssl.cert_status)) { DCHECK(net::IsCertStatusMinorError(ssl.cert_status)); return SECURITY_WARNING; } if ((ssl.cert_status & net::CERT_STATUS_IS_EV) && content::CertStore::GetInstance()->RetrieveCert(ssl.cert_id, NULL)) return EV_SECURE; return SECURE; default: NOTREACHED(); return NONE; } } int ToolbarModel::GetIcon() const { static int icon_ids[NUM_SECURITY_LEVELS] = { IDR_OMNIBOX_HTTP, IDR_OMNIBOX_HTTPS_VALID, IDR_OMNIBOX_HTTPS_VALID, IDR_OMNIBOX_HTTPS_WARNING, IDR_OMNIBOX_HTTPS_INVALID, }; DCHECK(arraysize(icon_ids) == NUM_SECURITY_LEVELS); return icon_ids[GetSecurityLevel()]; } string16 ToolbarModel::GetEVCertName() const { DCHECK_EQ(GetSecurityLevel(), EV_SECURE); scoped_refptr<net::X509Certificate> cert; // Note: Navigation controller and active entry are guaranteed non-NULL or // the security level would be NONE. content::CertStore::GetInstance()->RetrieveCert( GetNavigationController()->GetVisibleEntry()->GetSSL().cert_id, &cert); return GetEVCertName(*cert); } // static string16 ToolbarModel::GetEVCertName(const net::X509Certificate& cert) { // EV are required to have an organization name and country. if (cert.subject().organization_names.empty() || cert.subject().country_name.empty()) { NOTREACHED(); return string16(); } return l10n_util::GetStringFUTF16( IDS_SECURE_CONNECTION_EV, UTF8ToUTF16(cert.subject().organization_names[0]), UTF8ToUTF16(cert.subject().country_name)); } NavigationController* ToolbarModel::GetNavigationController() const { // This |current_tab| can be NULL during the initialization of the // toolbar during window creation (i.e. before any tabs have been added // to the window). WebContents* current_tab = delegate_->GetActiveWebContents(); return current_tab ? &current_tab->GetController() : NULL; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbOpticalCalibration.h" #include <iostream> #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageToLuminanceImageFilter.h" #include "otbLuminanceToReflectanceImageFilter.h" #include "otbReflectanceToSurfaceReflectanceImageFilter.h" #include "otbStreamingImageFileWriter.h" #include "otbStandardWriterWatcher.h" #include "otbPipelineMemoryPrintCalculator.h" #include "otbMultiplyByScalarImageFilter.h" namespace otb { int OpticalCalibration::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("OpticalCalibration"); descriptor->SetDescription("Perform optical calibration TOA/TOC(Top Of Atmosphere/Top Of Canopy). Output image is in milli-reflectance."); descriptor->AddInputImage(); descriptor->AddOutputImage(); descriptor->AddOptionNParams("Level", "Level of calibration TOA(Top Of Atmosphere) or TOC(Top Of Canopy) (default is TOA)", "level", false, otb::ApplicationDescriptor::String); descriptor->AddOption("RelativeSpectralResponseFile","Sensor relative spectral response file(by default the application gets these informations in the metadata)","rsr",1,false, otb::ApplicationDescriptor::FileName); descriptor->AddOption("AerosolModel","AerosolModel: NO_AEROSOL(0), CONTINENTAL(1), MARITIME(2), URBAN(3), DESERTIC(5); default 0","aerosol", 1, false, otb::ApplicationDescriptor::Integer); descriptor->AddOption("OzoneAmount","Amount of Ozone ","oz", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("WaterVaporAmount","WaterVaporAmount ","wa", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("AtmosphericPressure","Atmospheric pressure ","atmo", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("AerosolOptical","AerosolOptical ","opt", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("AeronetFile","Aeronet file to get atmospheric parameters","aeronet",1,false, otb::ApplicationDescriptor::FileName); descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram",1,false, otb::ApplicationDescriptor::Integer); return EXIT_SUCCESS; } int OpticalCalibration::Execute(otb::ApplicationOptionsResult* parseResult) { typedef otb::VectorImage<unsigned short int, 2> ImageType; typedef otb::VectorImage<float,2> FloatImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingImageFileWriter<ImageType> WriterType; typedef ImageToLuminanceImageFilter<ImageType, FloatImageType> ImageToLuminanceImageFilterType; typedef LuminanceToReflectanceImageFilter<FloatImageType, FloatImageType> LuminanceToReflectanceImageFilterType; typedef otb::MultiplyByScalarImageFilter<FloatImageType,ImageType> ScaleFilterType; typedef ReflectanceToSurfaceReflectanceImageFilter<FloatImageType, FloatImageType> ReflectanceToSurfaceReflectanceImageFilterType; typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType FilterFunctionValuesType; typedef FilterFunctionValuesType::ValuesVectorType ValuesVectorType; typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType; typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType; typedef otb::PipelineMemoryPrintCalculator MemoryCalculatorType; // Read input image information ReaderType::Pointer reader=ReaderType::New(); reader->SetFileName(parseResult->GetInputImage().c_str()); reader->GenerateOutputInformation(); //Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance itk::MetaDataDictionary dict = reader->GetOutput()->GetMetaDataDictionary(); OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict); // Test if needed data are available. try { // ImageToLuminance lImageMetadataInterface->GetPhysicalGain(); lImageMetadataInterface->GetPhysicalBias(); // LuminanceToReflectance lImageMetadataInterface->GetDay(); lImageMetadataInterface->GetMonth(); lImageMetadataInterface->GetSolarIrradiance(); lImageMetadataInterface->GetSunElevation(); } catch (itk::ExceptionObject& err) { std::cout << "Invalid input image medadata. The parsing returns the following error:\n" << std::endl; return EXIT_FAILURE; } //Instantiate the pipeline memory print estimator MemoryCalculatorType::Pointer calculator = MemoryCalculatorType::New(); const double byteToMegabyte = 1./vcl_pow(2.0, 20); if (parseResult->IsOptionPresent("AvailableMemory")) { long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory")); calculator->SetAvailableMemory(memory / byteToMegabyte); } else { calculator->SetAvailableMemory(256 / byteToMegabyte); } ImageToLuminanceImageFilterType ::Pointer imageToLuminanceFilter = ImageToLuminanceImageFilterType::New(); LuminanceToReflectanceImageFilterType::Pointer luminanceToReflectanceFilter = LuminanceToReflectanceImageFilterType::New(); ReflectanceToSurfaceReflectanceImageFilterType::Pointer reflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New(); imageToLuminanceFilter->SetInput(reader->GetOutput()); luminanceToReflectanceFilter->SetInput(imageToLuminanceFilter->GetOutput()); reflectanceToSurfaceReflectanceFilter->SetInput(luminanceToReflectanceFilter->GetOutput()); ScaleFilterType::Pointer scaleFilter = ScaleFilterType::New(); scaleFilter->SetCoef(1000.); if(parseResult->GetParameterString("Level") == "toc") { AtmosphericCorrectionParametersType::Pointer atmosphericParam = reflectanceToSurfaceReflectanceFilter->GetCorrectionParameters(); AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL; if(parseResult->IsOptionPresent("AerosolModel")) { aeroMod = static_cast<AerosolModelType>(parseResult->GetParameterUInt("AerosolModel")); } atmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(aeroMod)); double ozoneAmount = 0.; double waterVaporAmount = 2.5; double atmosphericPressure = 1030.; double aerosolOptical = 0.2; if (parseResult->IsOptionPresent("OzoneAmount")) { ozoneAmount = parseResult->GetParameterFloat("OzoneAmount"); } atmosphericParam->SetOzoneAmount(ozoneAmount); if (parseResult->IsOptionPresent("WaterVaporAmount")) { waterVaporAmount = parseResult->GetParameterFloat("WaterVaporAmount"); } atmosphericParam->SetWaterVaporAmount(waterVaporAmount); if (parseResult->IsOptionPresent("AtmosphericPressure")) { atmosphericPressure = parseResult->GetParameterFloat("AtmosphericPressure"); } atmosphericParam->SetAtmosphericPressure(atmosphericPressure); if (parseResult->IsOptionPresent("AerosolOptical")) { aerosolOptical = parseResult->GetParameterFloat("AerosolOptical"); } atmosphericParam->SetAerosolOptical(aerosolOptical); if (parseResult->IsOptionPresent("RelativeSpectralResponseFile")) { reflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(parseResult->GetParameterString("RelativeSpectralResponseFile",0)); } else { atmosphericParam->SetWavelengthSpectralBand(lImageMetadataInterface->GetSpectralSensitivity()); } if (parseResult->IsOptionPresent("AeronetFile")) { reflectanceToSurfaceReflectanceFilter->SetAeronetFileName(parseResult->GetParameterString("AeronetFile",0)); } AtmosphericRadiativeTerms::Pointer radTerms = AtmosphericRadiativeTerms::New(); radTerms->ValuesInitialization(reader->GetOutput()->GetNumberOfComponentsPerPixel()); reflectanceToSurfaceReflectanceFilter->SetAtmosphericRadiativeTerms(radTerms); reflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(true); reflectanceToSurfaceReflectanceFilter->GenerateAtmosphericRadiativeTerms(); reflectanceToSurfaceReflectanceFilter->GenerateParameters(); reflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false); //rescale the surface reflectance in milli-reflectance scaleFilter->SetInput(reflectanceToSurfaceReflectanceFilter->GetOutput()); calculator->SetDataToWrite(reflectanceToSurfaceReflectanceFilter->GetOutput()); } else { //Rescale luminanceToReflectance filter output (TOA level) scaleFilter->SetInput(luminanceToReflectanceFilter->GetOutput()); calculator->SetDataToWrite(imageToLuminanceFilter->GetOutput()); } //Instantiate the writer WriterType::Pointer writer = WriterType::New(); writer->SetFileName(parseResult->GetOutputImage()); writer->SetInput(scaleFilter->GetOutput()); writer->SetWriteGeomFile(true); //Compute the pipeline memory print estimation calculator->Compute(); writer->SetTilingStreamDivisions(calculator->GetOptimalNumberOfStreamDivisions()); std::cout << "Guess the pipeline memory print " << calculator->GetMemoryPrint()*byteToMegabyte << " Mo" << std::endl; std::cout << "Number of stream divisions : " << calculator->GetOptimalNumberOfStreamDivisions() << std::endl; otb::StandardWriterWatcher watcher(writer,"OpticalCalibration"); writer->Update(); return EXIT_SUCCESS; } } <commit_msg>STYLE<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbOpticalCalibration.h" #include <iostream> #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageToLuminanceImageFilter.h" #include "otbLuminanceToReflectanceImageFilter.h" #include "otbReflectanceToSurfaceReflectanceImageFilter.h" #include "otbStreamingImageFileWriter.h" #include "otbStandardWriterWatcher.h" #include "otbPipelineMemoryPrintCalculator.h" #include "otbMultiplyByScalarImageFilter.h" namespace otb { int OpticalCalibration::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("OpticalCalibration"); descriptor->SetDescription("Perform optical calibration TOA/TOC(Top Of Atmosphere/Top Of Canopy). Output image is in milli-reflectance."); descriptor->AddInputImage(); descriptor->AddOutputImage(); descriptor->AddOptionNParams("Level", "Level of calibration TOA(Top Of Atmosphere) or TOC(Top Of Canopy) (default is TOA)", "level", false, otb::ApplicationDescriptor::String); descriptor->AddOption("RelativeSpectralResponseFile","Sensor relative spectral response file(by default the application gets these informations in the metadata)","rsr", 1, false, otb::ApplicationDescriptor::FileName); descriptor->AddOption("AerosolModel","AerosolModel: NO_AEROSOL(0), CONTINENTAL(1), MARITIME(2), URBAN(3), DESERTIC(5); default 0","aerosol", 1, false, otb::ApplicationDescriptor::Integer); descriptor->AddOption("OzoneAmount","Amount of Ozone ","oz", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("WaterVaporAmount","WaterVaporAmount ","wa", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("AtmosphericPressure","Atmospheric pressure ","atmo", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("AerosolOptical","AerosolOptical ","opt", 1, false, otb::ApplicationDescriptor::Real); descriptor->AddOption("AeronetFile","Aeronet file to get atmospheric parameters","aeronet", 1, false, otb::ApplicationDescriptor::FileName); descriptor->AddOption("AvailableMemory","Set the maximum of available memory for the pipeline execution in mega bytes (optional, 256 by default)","ram", 1, false, otb::ApplicationDescriptor::Integer); return EXIT_SUCCESS; } int OpticalCalibration::Execute(otb::ApplicationOptionsResult* parseResult) { typedef otb::VectorImage<unsigned short int, 2> ImageType; typedef otb::VectorImage<float, 2> FloatImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingImageFileWriter<ImageType> WriterType; typedef ImageToLuminanceImageFilter<ImageType, FloatImageType> ImageToLuminanceImageFilterType; typedef LuminanceToReflectanceImageFilter<FloatImageType, FloatImageType> LuminanceToReflectanceImageFilterType; typedef otb::MultiplyByScalarImageFilter<FloatImageType, ImageType> ScaleFilterType; typedef ReflectanceToSurfaceReflectanceImageFilter<FloatImageType, FloatImageType> ReflectanceToSurfaceReflectanceImageFilterType; typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType FilterFunctionValuesType; typedef FilterFunctionValuesType::ValuesVectorType ValuesVectorType; typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType; typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType; typedef otb::PipelineMemoryPrintCalculator MemoryCalculatorType; // Read input image information ReaderType::Pointer reader=ReaderType::New(); reader->SetFileName(parseResult->GetInputImage().c_str()); reader->GenerateOutputInformation(); //Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance itk::MetaDataDictionary dict = reader->GetOutput()->GetMetaDataDictionary(); OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict); // Test if needed data are available. try { // ImageToLuminance lImageMetadataInterface->GetPhysicalGain(); lImageMetadataInterface->GetPhysicalBias(); // LuminanceToReflectance lImageMetadataInterface->GetDay(); lImageMetadataInterface->GetMonth(); lImageMetadataInterface->GetSolarIrradiance(); lImageMetadataInterface->GetSunElevation(); } catch (itk::ExceptionObject& err) { std::cout << "Invalid input image medadata. The parsing returns the following error:\n" << std::endl; return EXIT_FAILURE; } //Instantiate the pipeline memory print estimator MemoryCalculatorType::Pointer calculator = MemoryCalculatorType::New(); const double byteToMegabyte = 1./vcl_pow(2.0, 20); if (parseResult->IsOptionPresent("AvailableMemory")) { long long int memory = static_cast <long long int> (parseResult->GetParameterUInt("AvailableMemory")); calculator->SetAvailableMemory(memory / byteToMegabyte); } else { calculator->SetAvailableMemory(256 / byteToMegabyte); } ImageToLuminanceImageFilterType ::Pointer imageToLuminanceFilter = ImageToLuminanceImageFilterType::New(); LuminanceToReflectanceImageFilterType::Pointer luminanceToReflectanceFilter = LuminanceToReflectanceImageFilterType::New(); ReflectanceToSurfaceReflectanceImageFilterType::Pointer reflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New(); imageToLuminanceFilter->SetInput(reader->GetOutput()); luminanceToReflectanceFilter->SetInput(imageToLuminanceFilter->GetOutput()); reflectanceToSurfaceReflectanceFilter->SetInput(luminanceToReflectanceFilter->GetOutput()); ScaleFilterType::Pointer scaleFilter = ScaleFilterType::New(); scaleFilter->SetCoef(1000.); if(parseResult->GetParameterString("Level") == "toc") { AtmosphericCorrectionParametersType::Pointer atmosphericParam = reflectanceToSurfaceReflectanceFilter->GetCorrectionParameters(); AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL; if(parseResult->IsOptionPresent("AerosolModel")) { aeroMod = static_cast<AerosolModelType>(parseResult->GetParameterUInt("AerosolModel")); } atmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(aeroMod)); double ozoneAmount = 0.; double waterVaporAmount = 2.5; double atmosphericPressure = 1030.; double aerosolOptical = 0.2; if (parseResult->IsOptionPresent("OzoneAmount")) { ozoneAmount = parseResult->GetParameterFloat("OzoneAmount"); } atmosphericParam->SetOzoneAmount(ozoneAmount); if (parseResult->IsOptionPresent("WaterVaporAmount")) { waterVaporAmount = parseResult->GetParameterFloat("WaterVaporAmount"); } atmosphericParam->SetWaterVaporAmount(waterVaporAmount); if (parseResult->IsOptionPresent("AtmosphericPressure")) { atmosphericPressure = parseResult->GetParameterFloat("AtmosphericPressure"); } atmosphericParam->SetAtmosphericPressure(atmosphericPressure); if (parseResult->IsOptionPresent("AerosolOptical")) { aerosolOptical = parseResult->GetParameterFloat("AerosolOptical"); } atmosphericParam->SetAerosolOptical(aerosolOptical); if (parseResult->IsOptionPresent("RelativeSpectralResponseFile")) { reflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(parseResult->GetParameterString("RelativeSpectralResponseFile", 0)); } else { atmosphericParam->SetWavelengthSpectralBand(lImageMetadataInterface->GetSpectralSensitivity()); } if (parseResult->IsOptionPresent("AeronetFile")) { reflectanceToSurfaceReflectanceFilter->SetAeronetFileName(parseResult->GetParameterString("AeronetFile", 0)); } AtmosphericRadiativeTerms::Pointer radTerms = AtmosphericRadiativeTerms::New(); radTerms->ValuesInitialization(reader->GetOutput()->GetNumberOfComponentsPerPixel()); reflectanceToSurfaceReflectanceFilter->SetAtmosphericRadiativeTerms(radTerms); reflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(true); reflectanceToSurfaceReflectanceFilter->GenerateAtmosphericRadiativeTerms(); reflectanceToSurfaceReflectanceFilter->GenerateParameters(); reflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false); //rescale the surface reflectance in milli-reflectance scaleFilter->SetInput(reflectanceToSurfaceReflectanceFilter->GetOutput()); calculator->SetDataToWrite(reflectanceToSurfaceReflectanceFilter->GetOutput()); } else { //Rescale luminanceToReflectance filter output (TOA level) scaleFilter->SetInput(luminanceToReflectanceFilter->GetOutput()); calculator->SetDataToWrite(imageToLuminanceFilter->GetOutput()); } //Instantiate the writer WriterType::Pointer writer = WriterType::New(); writer->SetFileName(parseResult->GetOutputImage()); writer->SetInput(scaleFilter->GetOutput()); writer->SetWriteGeomFile(true); //Compute the pipeline memory print estimation calculator->Compute(); writer->SetTilingStreamDivisions(calculator->GetOptimalNumberOfStreamDivisions()); std::cout << "Guess the pipeline memory print " << calculator->GetMemoryPrint()*byteToMegabyte << " Mo" << std::endl; std::cout << "Number of stream divisions : " << calculator->GetOptimalNumberOfStreamDivisions() << std::endl; otb::StandardWriterWatcher watcher(writer,"OpticalCalibration"); writer->Update(); return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/offline/offline_load_page.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "content/browser/tab_contents/interstitial_page.h" #include "content/browser/tab_contents/test_tab_contents.h" #include "content/test/test_browser_thread.h" using content::BrowserThread; static const char* kURL1 = "http://www.google.com/"; static const char* kURL2 = "http://www.gmail.com/"; namespace chromeos { class OfflineLoadPageTest; namespace { // An OfflineLoadPage class that does not create windows. class TestOfflineLoadPage : public chromeos::OfflineLoadPage { public: TestOfflineLoadPage(TabContents* tab_contents, const GURL& url, OfflineLoadPageTest* test_page) : chromeos::OfflineLoadPage(tab_contents, url, CompletionCallback()), test_page_(test_page) { interstitial_page_->DontCreateViewForTesting(); } // chromeos::OfflineLoadPage override. virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE; private: OfflineLoadPageTest* test_page_; DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage); }; } // namespace class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness { public: // The decision the user made. enum UserResponse { PENDING, OK, CANCEL }; OfflineLoadPageTest() : ui_thread_(BrowserThread::UI, MessageLoop::current()), io_thread_(BrowserThread::IO, MessageLoop::current()) { } virtual void SetUp() { ChromeRenderViewHostTestHarness::SetUp(); user_response_ = PENDING; } void OnBlockingPageComplete(bool proceed) { if (proceed) user_response_ = OK; else user_response_ = CANCEL; } void Navigate(const char* url, int page_id) { contents()->TestDidNavigate( contents()->GetRenderViewHost(), page_id, GURL(url), content::PAGE_TRANSITION_TYPED); } void ShowInterstitial(const char* url) { new TestOfflineLoadPage(contents(), GURL(url), this); } // Returns the OfflineLoadPage currently showing or NULL if none is // showing. InterstitialPage* GetOfflineLoadPage() { return InterstitialPage::GetInterstitialPage(contents()); } UserResponse user_response() const { return user_response_; } private: UserResponse user_response_; content::TestBrowserThread ui_thread_; content::TestBrowserThread io_thread_; // Initializes / shuts down a stub CrosLibrary. chromeos::ScopedStubCrosEnabler stub_cros_enabler_; DISALLOW_COPY_AND_ASSIGN(OfflineLoadPageTest); }; void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) { test_page_->OnBlockingPageComplete(proceed); } TEST_F(OfflineLoadPageTest, OfflinePageProceed) { // Start a load. Navigate(kURL1, 1); // Load next page. controller().LoadURL(GURL(kURL2), content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); // Simulate the load causing an offline browsing interstitial page // to be shown. ShowInterstitial(kURL2); InterstitialPage* interstitial = GetOfflineLoadPage(); ASSERT_TRUE(interstitial); MessageLoop::current()->RunAllPending(); // Simulate the user clicking "proceed". interstitial->Proceed(); MessageLoop::current()->RunAllPending(); EXPECT_EQ(OK, user_response()); // The URL remains to be URL2. EXPECT_EQ(kURL2, contents()->GetURL().spec()); // Commit navigation and the interstitial page is gone. Navigate(kURL2, 2); EXPECT_FALSE(GetOfflineLoadPage()); } // Tests showing an offline page and not proceeding. TEST_F(OfflineLoadPageTest, OfflinePageDontProceed) { // Start a load. Navigate(kURL1, 1); controller().LoadURL(GURL(kURL2), content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); // Simulate the load causing an offline interstitial page to be shown. ShowInterstitial(kURL2); InterstitialPage* interstitial = GetOfflineLoadPage(); ASSERT_TRUE(interstitial); MessageLoop::current()->RunAllPending(); // Simulate the user clicking "don't proceed". interstitial->DontProceed(); // The interstitial should be gone. EXPECT_EQ(CANCEL, user_response()); EXPECT_FALSE(GetOfflineLoadPage()); // We did not proceed, the pending entry should be gone. EXPECT_FALSE(controller().GetPendingEntry()); // the URL is set back to kURL1. EXPECT_EQ(kURL1, contents()->GetURL().spec()); } } // namespace chromeos <commit_msg>fix cros again<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/offline/offline_load_page.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "content/browser/tab_contents/interstitial_page.h" #include "content/browser/tab_contents/test_tab_contents.h" #include "content/test/test_browser_thread.h" using content::BrowserThread; static const char* kURL1 = "http://www.google.com/"; static const char* kURL2 = "http://www.gmail.com/"; namespace chromeos { class OfflineLoadPageTest; // An OfflineLoadPage class that does not create windows. class TestOfflineLoadPage : public chromeos::OfflineLoadPage { public: TestOfflineLoadPage(TabContents* tab_contents, const GURL& url, OfflineLoadPageTest* test_page) : chromeos::OfflineLoadPage(tab_contents, url, CompletionCallback()), test_page_(test_page) { interstitial_page_->DontCreateViewForTesting(); } // chromeos::OfflineLoadPage override. virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE; private: OfflineLoadPageTest* test_page_; DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage); }; class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness { public: // The decision the user made. enum UserResponse { PENDING, OK, CANCEL }; OfflineLoadPageTest() : ui_thread_(BrowserThread::UI, MessageLoop::current()), io_thread_(BrowserThread::IO, MessageLoop::current()) { } virtual void SetUp() { ChromeRenderViewHostTestHarness::SetUp(); user_response_ = PENDING; } void OnBlockingPageComplete(bool proceed) { if (proceed) user_response_ = OK; else user_response_ = CANCEL; } void Navigate(const char* url, int page_id) { contents()->TestDidNavigate( contents()->GetRenderViewHost(), page_id, GURL(url), content::PAGE_TRANSITION_TYPED); } void ShowInterstitial(const char* url) { new TestOfflineLoadPage(contents(), GURL(url), this); } // Returns the OfflineLoadPage currently showing or NULL if none is // showing. InterstitialPage* GetOfflineLoadPage() { return InterstitialPage::GetInterstitialPage(contents()); } UserResponse user_response() const { return user_response_; } private: UserResponse user_response_; content::TestBrowserThread ui_thread_; content::TestBrowserThread io_thread_; // Initializes / shuts down a stub CrosLibrary. chromeos::ScopedStubCrosEnabler stub_cros_enabler_; DISALLOW_COPY_AND_ASSIGN(OfflineLoadPageTest); }; void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) { test_page_->OnBlockingPageComplete(proceed); } TEST_F(OfflineLoadPageTest, OfflinePageProceed) { // Start a load. Navigate(kURL1, 1); // Load next page. controller().LoadURL(GURL(kURL2), content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); // Simulate the load causing an offline browsing interstitial page // to be shown. ShowInterstitial(kURL2); InterstitialPage* interstitial = GetOfflineLoadPage(); ASSERT_TRUE(interstitial); MessageLoop::current()->RunAllPending(); // Simulate the user clicking "proceed". interstitial->Proceed(); MessageLoop::current()->RunAllPending(); EXPECT_EQ(OK, user_response()); // The URL remains to be URL2. EXPECT_EQ(kURL2, contents()->GetURL().spec()); // Commit navigation and the interstitial page is gone. Navigate(kURL2, 2); EXPECT_FALSE(GetOfflineLoadPage()); } // Tests showing an offline page and not proceeding. TEST_F(OfflineLoadPageTest, OfflinePageDontProceed) { // Start a load. Navigate(kURL1, 1); controller().LoadURL(GURL(kURL2), content::Referrer(), content::PAGE_TRANSITION_TYPED, std::string()); // Simulate the load causing an offline interstitial page to be shown. ShowInterstitial(kURL2); InterstitialPage* interstitial = GetOfflineLoadPage(); ASSERT_TRUE(interstitial); MessageLoop::current()->RunAllPending(); // Simulate the user clicking "don't proceed". interstitial->DontProceed(); // The interstitial should be gone. EXPECT_EQ(CANCEL, user_response()); EXPECT_FALSE(GetOfflineLoadPage()); // We did not proceed, the pending entry should be gone. EXPECT_FALSE(controller().GetPendingEntry()); // the URL is set back to kURL1. EXPECT_EQ(kURL1, contents()->GetURL().spec()); } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "JSBigString.h" #include <fcntl.h> #include <sys/stat.h> #include <glog/logging.h> #include <folly/Memory.h> #include <folly/portability/SysMman.h> #include <folly/ScopeGuard.h> namespace facebook { namespace react { JSBigFileString::JSBigFileString(int fd, size_t size, off_t offset /*= 0*/) : m_fd { -1 } , m_data { nullptr } { folly::checkUnixError(m_fd = dup(fd), "Could not duplicate file descriptor"); // Offsets given to mmap must be page aligend. We abstract away that // restriction by sending a page aligned offset to mmap, and keeping track // of the offset within the page that we must alter the mmap pointer by to // get the final desired offset. if (offset != 0) { const static auto ps = getpagesize(); auto d = lldiv(offset, ps); m_mapOff = d.quot; m_pageOff = d.rem; m_size = size + m_pageOff; } else { m_mapOff = 0; m_pageOff = 0; m_size = size; } } JSBigFileString::~JSBigFileString() { if (m_data) { munmap((void *)m_data, m_size); } close(m_fd); } const char *JSBigFileString::c_str() const { if (!m_data) { m_data = (const char *) mmap(0, m_size, PROT_READ, MAP_SHARED, m_fd, m_mapOff); CHECK(m_data != MAP_FAILED) << " fd: " << m_fd << " size: " << m_size << " offset: " << m_mapOff << " error: " << std::strerror(errno); } return m_data + m_pageOff; } size_t JSBigFileString::size() const { return m_size - m_pageOff; } int JSBigFileString::fd() const { return m_fd; } std::unique_ptr<const JSBigFileString> JSBigFileString::fromPath(const std::string& sourceURL) { int fd = ::open(sourceURL.c_str(), O_RDONLY); folly::checkUnixError(fd, "Could not open file", sourceURL); SCOPE_EXIT { CHECK(::close(fd) == 0); }; struct stat fileInfo; folly::checkUnixError(::fstat(fd, &fileInfo), "fstat on bundle failed."); return folly::make_unique<const JSBigFileString>(fd, fileInfo.st_size); } } // namespace react } // namespace facebook <commit_msg>JSBigString to map via MAP_PRIVATE not MAP_SHARED<commit_after>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "JSBigString.h" #include <fcntl.h> #include <sys/stat.h> #include <glog/logging.h> #include <folly/Memory.h> #include <folly/portability/SysMman.h> #include <folly/ScopeGuard.h> namespace facebook { namespace react { JSBigFileString::JSBigFileString(int fd, size_t size, off_t offset /*= 0*/) : m_fd { -1 } , m_data { nullptr } { folly::checkUnixError(m_fd = dup(fd), "Could not duplicate file descriptor"); // Offsets given to mmap must be page aligend. We abstract away that // restriction by sending a page aligned offset to mmap, and keeping track // of the offset within the page that we must alter the mmap pointer by to // get the final desired offset. if (offset != 0) { const static auto ps = getpagesize(); auto d = lldiv(offset, ps); m_mapOff = d.quot; m_pageOff = d.rem; m_size = size + m_pageOff; } else { m_mapOff = 0; m_pageOff = 0; m_size = size; } } JSBigFileString::~JSBigFileString() { if (m_data) { munmap((void *)m_data, m_size); } close(m_fd); } const char *JSBigFileString::c_str() const { if (!m_data) { m_data = (const char *) mmap(0, m_size, PROT_READ, MAP_PRIVATE, m_fd, m_mapOff); CHECK(m_data != MAP_FAILED) << " fd: " << m_fd << " size: " << m_size << " offset: " << m_mapOff << " error: " << std::strerror(errno); } return m_data + m_pageOff; } size_t JSBigFileString::size() const { return m_size - m_pageOff; } int JSBigFileString::fd() const { return m_fd; } std::unique_ptr<const JSBigFileString> JSBigFileString::fromPath(const std::string& sourceURL) { int fd = ::open(sourceURL.c_str(), O_RDONLY); folly::checkUnixError(fd, "Could not open file", sourceURL); SCOPE_EXIT { CHECK(::close(fd) == 0); }; struct stat fileInfo; folly::checkUnixError(::fstat(fd, &fileInfo), "fstat on bundle failed."); return folly::make_unique<const JSBigFileString>(fd, fileInfo.st_size); } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>#include "Function.h" #include <functional> #include <iostream> #include <chrono> // Sample Function int SomeFunction(bool SomeParam) { return (SomeParam ? 1 : 0); } int main() { using namespace Red::Function; // Sample Lambda int MyInt = 3; auto MyLambda = [&MyInt](bool SomeParam) -> int { return (SomeParam ? 0 : 1) + MyInt; }; // Some Demo Instantiations Function<int(bool)> MyFunctionPtrObj(&SomeFunction); Function<int(bool)> MyFunctionPtrObj2 = &SomeFunction; Function<int(bool)> MyLambdaObj(MyLambda); Function<int(bool)> MyLambdaObj2 = MyLambda; // Some Demo Calls MyFunctionPtrObj(false); MyFunctionPtrObj2(true); MyLambdaObj(false); MyLambdaObj2(true); // Sizes of Each Object std::cout << "Sizeof Red::Function::Delegate: " << sizeof(Delegate<UClass, int, bool>) << std::endl; std::cout << "Sizeof Red::Function::Function: " << sizeof(Function<int(bool)>) << std::endl; std::cout << "Sizeof Std::Function: " << sizeof(std::function<int(bool)>) << std::endl; // Execution Time of 500000 Calls to Red::Function::Function auto Start1 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 500000; ++i) MyFunctionPtrObj(true); auto End1 = std::chrono::high_resolution_clock::now(); std::cout << "Call Time (500k Executions) | Red::Function: " << std::chrono::duration_cast<std::chrono::milliseconds>(End1 - Start1).count() << "ms" << std::endl; // Creating Same Function Type in Std::Function std::function<int(bool)> MyStdFunc = &SomeFunction; // Execution Time of 500000 Calls to Std::Function auto Start2 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 500000; ++i) MyStdFunc(true); auto End2 = std::chrono::high_resolution_clock::now(); std::cout << "Call Time (50k Executions) | Std::Function: " << std::chrono::duration_cast<std::chrono::milliseconds>(End2 - Start2).count() << "ms" << std::endl; system("pause"); return 0; }<commit_msg>Fixed Typo<commit_after>#include "Function.h" #include <functional> #include <iostream> #include <chrono> // Sample Function int SomeFunction(bool SomeParam) { return (SomeParam ? 1 : 0); } int main() { using namespace Red::Function; // Sample Lambda int MyInt = 3; auto MyLambda = [&MyInt](bool SomeParam) -> int { return (SomeParam ? 0 : 1) + MyInt; }; // Some Demo Instantiations Function<int(bool)> MyFunctionPtrObj(&SomeFunction); Function<int(bool)> MyFunctionPtrObj2 = &SomeFunction; Function<int(bool)> MyLambdaObj(MyLambda); Function<int(bool)> MyLambdaObj2 = MyLambda; // Some Demo Calls MyFunctionPtrObj(false); MyFunctionPtrObj2(true); MyLambdaObj(false); MyLambdaObj2(true); // Sizes of Each Object std::cout << "Sizeof Red::Function::Delegate: " << sizeof(Delegate<UClass, int, bool>) << std::endl; std::cout << "Sizeof Red::Function::Function: " << sizeof(Function<int(bool)>) << std::endl; std::cout << "Sizeof Std::Function: " << sizeof(std::function<int(bool)>) << std::endl; // Execution Time of 500000 Calls to Red::Function::Function auto Start1 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 500000; ++i) MyFunctionPtrObj(true); auto End1 = std::chrono::high_resolution_clock::now(); std::cout << "Call Time (500k Executions) | Red::Function: " << std::chrono::duration_cast<std::chrono::milliseconds>(End1 - Start1).count() << "ms" << std::endl; // Creating Same Function Type in Std::Function std::function<int(bool)> MyStdFunc = &SomeFunction; // Execution Time of 500000 Calls to Std::Function auto Start2 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 500000; ++i) MyStdFunc(true); auto End2 = std::chrono::high_resolution_clock::now(); std::cout << "Call Time (500k Executions) | Std::Function: " << std::chrono::duration_cast<std::chrono::milliseconds>(End2 - Start2).count() << "ms" << std::endl; system("pause"); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" class ExtensionManagementTest : public ExtensionBrowserTest { protected: // Helper method that returns whether the extension is at the given version. // This calls version(), which must be defined in the extension's bg page, // as well as asking the extension itself. // // Note that 'version' here means something different than the version field // in the extension's manifest. We use the version as reported by the // background page to test how overinstalling crx files with the same // manifest version works. bool IsExtensionAtVersion(Extension* extension, const std::string& expected_version) { // Test that the extension's version from the manifest and reported by the // background page is correct. This is to ensure that the processes are in // sync with the Extension. ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension); EXPECT_TRUE(ext_host); if (!ext_host) return false; std::string version_from_bg; bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString( ext_host->render_view_host(), L"", L"version()", &version_from_bg); EXPECT_TRUE(exec); if (!exec) return false; if (version_from_bg != expected_version || extension->VersionString() != expected_version) return false; return true; } // Helper method that installs a low permission extension then updates // to the second version requiring increased permissions. Returns whether // the operation was completed successfully. bool InstallAndUpdateIncreasingPermissionsExtension() { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t size_before = service->extensions()->size(); // Install the initial version, which should happen just fine. if (!InstallExtension( test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1)) return false; // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. if (service->extensions()->size() != size_before + 1) return false; if (!UpdateExtension( service->extensions()->at(size_before)->id(), test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1)) return false; EXPECT_EQ(size_before, service->extensions()->size()); if (service->disabled_extensions()->size() != 1u) return false; return true; } }; // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); FilePath old_path = service->extensions()->back()->path(); // Install an extension with the same version. The previous install should be // overwritten. ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_same_version.crx"), 0)); FilePath new_path = service->extensions()->back()->path(); EXPECT_FALSE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); EXPECT_NE(old_path.value(), new_path.value()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); // Cancel this install. StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx")); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } // Tests that installing and uninstalling extensions don't crash with an // incognito window open. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) { // Open an incognito window to the extensions management page. We just // want to make sure that we don't crash while playing with extensions when // this guy is around. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL(chrome::kChromeUIExtensionsURL)); ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1)); UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf"); } #if defined(OS_LINUX) // See http://crbug.com/32906 and http://crbug.com/36890 #define MAYBE_UpdatePermissions DISABLED_UpdatePermissions #else #define MAYBE_UpdatePermissions UpdatePermissions #endif // Tests the process of updating an extension to one that requires higher // permissions. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_UpdatePermissions) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try reenabling it. service->EnableExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that we can uninstall a disabled extension. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try uninstalling it. UninstallExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that disabling and re-enabling an extension works. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) { ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); // Load an extension, expect the background page to be available. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("good").AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"))); ASSERT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); Extension* extension = service->extensions()->at(size_before); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // After disabling, the background page should go away. service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(1u, service->disabled_extensions()->size()); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // And bring it back. service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); } // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1)); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_TRUE(service->HasInstalledExtensions()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("1.0", extensions->at(size_before)->VersionString()); // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); // Run autoupdate and make sure version 2 of the extension was installed. service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v3.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstallError()); // Make sure the extension state is the same as before. extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); } <commit_msg>Marking the test as flaky since it fails 14% of the time.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" class ExtensionManagementTest : public ExtensionBrowserTest { protected: // Helper method that returns whether the extension is at the given version. // This calls version(), which must be defined in the extension's bg page, // as well as asking the extension itself. // // Note that 'version' here means something different than the version field // in the extension's manifest. We use the version as reported by the // background page to test how overinstalling crx files with the same // manifest version works. bool IsExtensionAtVersion(Extension* extension, const std::string& expected_version) { // Test that the extension's version from the manifest and reported by the // background page is correct. This is to ensure that the processes are in // sync with the Extension. ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension); EXPECT_TRUE(ext_host); if (!ext_host) return false; std::string version_from_bg; bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString( ext_host->render_view_host(), L"", L"version()", &version_from_bg); EXPECT_TRUE(exec); if (!exec) return false; if (version_from_bg != expected_version || extension->VersionString() != expected_version) return false; return true; } // Helper method that installs a low permission extension then updates // to the second version requiring increased permissions. Returns whether // the operation was completed successfully. bool InstallAndUpdateIncreasingPermissionsExtension() { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t size_before = service->extensions()->size(); // Install the initial version, which should happen just fine. if (!InstallExtension( test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1)) return false; // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. if (service->extensions()->size() != size_before + 1) return false; if (!UpdateExtension( service->extensions()->at(size_before)->id(), test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1)) return false; EXPECT_EQ(size_before, service->extensions()->size()); if (service->disabled_extensions()->size() != 1u) return false; return true; } }; // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); FilePath old_path = service->extensions()->back()->path(); // Install an extension with the same version. The previous install should be // overwritten. ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_same_version.crx"), 0)); FilePath new_path = service->extensions()->back()->path(); EXPECT_FALSE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); EXPECT_NE(old_path.value(), new_path.value()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); // Cancel this install. StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx")); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } #if defined(OS_MACOSX) // See http://crbug.com/46097 #define MAYBE_Incognito FLAKY_Incognito #else #define MAYBE_Incognito Incognito #endif // Tests that installing and uninstalling extensions don't crash with an // incognito window open. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_Incognito) { // Open an incognito window to the extensions management page. We just // want to make sure that we don't crash while playing with extensions when // this guy is around. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL(chrome::kChromeUIExtensionsURL)); ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1)); UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf"); } #if defined(OS_LINUX) // See http://crbug.com/32906 and http://crbug.com/36890 #define MAYBE_UpdatePermissions DISABLED_UpdatePermissions #else #define MAYBE_UpdatePermissions UpdatePermissions #endif // Tests the process of updating an extension to one that requires higher // permissions. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_UpdatePermissions) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try reenabling it. service->EnableExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that we can uninstall a disabled extension. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try uninstalling it. UninstallExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that disabling and re-enabling an extension works. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) { ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); // Load an extension, expect the background page to be available. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("good").AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"))); ASSERT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); Extension* extension = service->extensions()->at(size_before); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // After disabling, the background page should go away. service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(1u, service->disabled_extensions()->size()); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // And bring it back. service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); } // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1)); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_TRUE(service->HasInstalledExtensions()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("1.0", extensions->at(size_before)->VersionString()); // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); // Run autoupdate and make sure version 2 of the extension was installed. service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v3.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstallError()); // Make sure the extension state is the same as before. extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" class ExtensionManagementTest : public ExtensionBrowserTest { protected: // Helper method that returns whether the extension is at the given version. // This calls version(), which must be defined in the extension's bg page, // as well as asking the extension itself. // // Note that 'version' here means something different than the version field // in the extension's manifest. We use the version as reported by the // background page to test how overinstalling crx files with the same // manifest version works. bool IsExtensionAtVersion(Extension* extension, const std::string& expected_version) { // Test that the extension's version from the manifest and reported by the // background page is correct. This is to ensure that the processes are in // sync with the Extension. ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension); EXPECT_TRUE(ext_host); if (!ext_host) return false; std::string version_from_bg; bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString( ext_host->render_view_host(), L"", L"version()", &version_from_bg); EXPECT_TRUE(exec); if (!exec) return false; if (version_from_bg != expected_version || extension->VersionString() != expected_version) return false; return true; } // Helper method that installs a low permission extension then updates // to the second version requiring increased permissions. Returns whether // the operation was completed successfully. bool InstallAndUpdateIncreasingPermissionsExtension() { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t size_before = service->extensions()->size(); // Install the initial version, which should happen just fine. if (!InstallExtension( test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1)) return false; // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. if (service->extensions()->size() != size_before + 1) return false; if (!UpdateExtension( service->extensions()->at(size_before)->id(), test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1)) return false; EXPECT_EQ(size_before, service->extensions()->size()); if (service->disabled_extensions()->size() != 1u) return false; return true; } }; // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); FilePath old_path = service->extensions()->back()->path(); // Install an extension with the same version. The previous install should be // overwritten. ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_same_version.crx"), 0)); FilePath new_path = service->extensions()->back()->path(); EXPECT_FALSE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); EXPECT_NE(old_path.value(), new_path.value()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); // Cancel this install. StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx")); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } #if defined(OS_MACOSX) // See http://crbug.com/46097 #define MAYBE_Incognito FLAKY_Incognito #else #define MAYBE_Incognito Incognito #endif // Tests that installing and uninstalling extensions don't crash with an // incognito window open. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_Incognito) { // Open an incognito window to the extensions management page. We just // want to make sure that we don't crash while playing with extensions when // this guy is around. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL(chrome::kChromeUIExtensionsURL)); ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1)); UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf"); } // Tests the process of updating an extension to one that requires higher // permissions. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try reenabling it. service->EnableExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that we can uninstall a disabled extension. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try uninstalling it. UninstallExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that disabling and re-enabling an extension works. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) { ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); // Load an extension, expect the background page to be available. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("good").AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"))); ASSERT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); Extension* extension = service->extensions()->at(size_before); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // After disabling, the background page should go away. service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(1u, service->disabled_extensions()->size()); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // And bring it back. service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); } // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1)); listener1.WaitUntilSatisfied(); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_TRUE(service->HasInstalledExtensions()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("1.0", extensions->at(size_before)->VersionString()); // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); // Run autoupdate and make sure version 2 of the extension was installed. ExtensionTestMessageListener listener2("v2 installed", false); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); listener2.WaitUntilSatisfied(); extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v3.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstallError()); // Make sure the extension state is the same as before. extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); } // See http://crbug.com/57378 for flakiness details. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, FLAKY_ExternalUrlUpdate) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const char* kExtensionId = "ogjcoiohnmldgjemafoockdghcjciccf"; // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); // The code that reads external_extensions.json uses this method to inform // the ExtensionsService of an extension to download. Using the real code // is race-prone, because instantating the ExtensionService starts a read // of external_extensions.json before this test function starts. service->AddPendingExtensionFromExternalUpdateUrl( kExtensionId, GURL("http://localhost/autoupdate/manifest")); // Run autoupdate and make sure version 2 of the extension was installed. service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ(kExtensionId, extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Uninstalling the extension should set a pref that keeps the extension from // being installed again the next time external_extensions.json is read. UninstallExtension(kExtensionId); std::set<std::string> killed_ids; service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() != killed_ids.find(kExtensionId)) << "Uninstalling should set kill bit on externaly installed extension."; // Installing from non-external source. ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Reinstalling should clear the kill bit."; // Uninstalling from a non-external source should not set the kill bit. UninstallExtension(kExtensionId); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Uninstalling non-external extension should not set kill bit."; } <commit_msg>Unmark ExtensionManagementTest.Incognito as FLAKY on Mac.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "chrome/browser/browser.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/extensions/extension_updater.h" #include "chrome/browser/profile.h" #include "chrome/common/url_constants.h" #include "chrome/test/ui_test_utils.h" class ExtensionManagementTest : public ExtensionBrowserTest { protected: // Helper method that returns whether the extension is at the given version. // This calls version(), which must be defined in the extension's bg page, // as well as asking the extension itself. // // Note that 'version' here means something different than the version field // in the extension's manifest. We use the version as reported by the // background page to test how overinstalling crx files with the same // manifest version works. bool IsExtensionAtVersion(Extension* extension, const std::string& expected_version) { // Test that the extension's version from the manifest and reported by the // background page is correct. This is to ensure that the processes are in // sync with the Extension. ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension); EXPECT_TRUE(ext_host); if (!ext_host) return false; std::string version_from_bg; bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString( ext_host->render_view_host(), L"", L"version()", &version_from_bg); EXPECT_TRUE(exec); if (!exec) return false; if (version_from_bg != expected_version || extension->VersionString() != expected_version) return false; return true; } // Helper method that installs a low permission extension then updates // to the second version requiring increased permissions. Returns whether // the operation was completed successfully. bool InstallAndUpdateIncreasingPermissionsExtension() { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t size_before = service->extensions()->size(); // Install the initial version, which should happen just fine. if (!InstallExtension( test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1)) return false; // Upgrade to a version that wants more permissions. We should disable the // extension and prompt the user to reenable. if (service->extensions()->size() != size_before + 1) return false; if (!UpdateExtension( service->extensions()->at(size_before)->id(), test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1)) return false; EXPECT_EQ(size_before, service->extensions()->size()); if (service->disabled_extensions()->size() != 1u) return false; return true; } }; // Tests that installing the same version overwrites. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); FilePath old_path = service->extensions()->back()->path(); // Install an extension with the same version. The previous install should be // overwritten. ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_same_version.crx"), 0)); FilePath new_path = service->extensions()->back()->path(); EXPECT_FALSE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); EXPECT_NE(old_path.value(), new_path.value()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install_older_version.crx"), 0)); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(InstallExtension( test_data_dir_.AppendASCII("install/install.crx"), 1)); // Cancel this install. StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx")); EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(size_before), "1.0")); } // Tests that installing and uninstalling extensions don't crash with an // incognito window open. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) { // Open an incognito window to the extensions management page. We just // want to make sure that we don't crash while playing with extensions when // this guy is around. ui_test_utils::OpenURLOffTheRecord(browser()->profile(), GURL(chrome::kChromeUIExtensionsURL)); ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1)); UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf"); } // Tests the process of updating an extension to one that requires higher // permissions. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try reenabling it. service->EnableExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that we can uninstall a disabled extension. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension()); const size_t size_before = service->extensions()->size(); // Now try uninstalling it. UninstallExtension(service->disabled_extensions()->at(0)->id()); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); } // Tests that disabling and re-enabling an extension works. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) { ExtensionProcessManager* manager = browser()->profile()-> GetExtensionProcessManager(); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); // Load an extension, expect the background page to be available. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("good").AppendASCII("Extensions") .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa") .AppendASCII("1.0"))); ASSERT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); Extension* extension = service->extensions()->at(size_before); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // After disabling, the background page should go away. service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before, service->extensions()->size()); EXPECT_EQ(1u, service->disabled_extensions()->size()); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); // And bring it back. service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa"); EXPECT_EQ(size_before + 1, service->extensions()->size()); EXPECT_EQ(0u, service->disabled_extensions()->size()); EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension)); ASSERT_TRUE(service->HasInstalledExtensions()); } // Tests extension autoupdate. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); ExtensionsService* service = browser()->profile()->GetExtensionsService(); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1)); listener1.WaitUntilSatisfied(); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_TRUE(service->HasInstalledExtensions()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("1.0", extensions->at(size_before)->VersionString()); // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); // Run autoupdate and make sure version 2 of the extension was installed. ExtensionTestMessageListener listener2("v2 installed", false); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); listener2.WaitUntilSatisfied(); extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v3.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstallError()); // Make sure the extension state is the same as before. extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); } // See http://crbug.com/57378 for flakiness details. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, FLAKY_ExternalUrlUpdate) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); const char* kExtensionId = "ogjcoiohnmldgjemafoockdghcjciccf"; // We don't want autoupdate blacklist checks. service->updater()->set_blacklist_checks_enabled(false); FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor()); URLFetcher::enable_interception_for_tests(true); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", basedir.AppendASCII("manifest_v2.xml")); interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", basedir.AppendASCII("v2.crx")); const size_t size_before = service->extensions()->size(); ASSERT_TRUE(service->disabled_extensions()->empty()); // The code that reads external_extensions.json uses this method to inform // the ExtensionsService of an extension to download. Using the real code // is race-prone, because instantating the ExtensionService starts a read // of external_extensions.json before this test function starts. service->AddPendingExtensionFromExternalUpdateUrl( kExtensionId, GURL("http://localhost/autoupdate/manifest")); // Run autoupdate and make sure version 2 of the extension was installed. service->updater()->CheckNow(); ASSERT_TRUE(WaitForExtensionInstall()); const ExtensionList* extensions = service->extensions(); ASSERT_EQ(size_before + 1, extensions->size()); ASSERT_EQ(kExtensionId, extensions->at(size_before)->id()); ASSERT_EQ("2.0", extensions->at(size_before)->VersionString()); // Uninstalling the extension should set a pref that keeps the extension from // being installed again the next time external_extensions.json is read. UninstallExtension(kExtensionId); std::set<std::string> killed_ids; service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() != killed_ids.find(kExtensionId)) << "Uninstalling should set kill bit on externaly installed extension."; // Installing from non-external source. ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v2.crx"), 1)); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Reinstalling should clear the kill bit."; // Uninstalling from a non-external source should not set the kill bit. UninstallExtension(kExtensionId); killed_ids.clear(); service->extension_prefs()->GetKilledExtensionIds(&killed_ids); EXPECT_TRUE(killed_ids.end() == killed_ids.find(kExtensionId)) << "Uninstalling non-external extension should not set kill bit."; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/external_pref_extension_provider.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/version.h" // Constants for keeping track of extension preferences. const wchar_t kLocation[] = L"location"; const wchar_t kState[] = L"state"; const wchar_t kExternalCrx[] = L"external_crx"; const wchar_t kExternalVersion[] = L"external_version"; ExternalPrefExtensionProvider::ExternalPrefExtensionProvider( DictionaryValue* prefs) { DCHECK(prefs); prefs_.reset(prefs); } ExternalPrefExtensionProvider::~ExternalPrefExtensionProvider() { } void ExternalPrefExtensionProvider::VisitRegisteredExtension( Visitor* visitor, const std::set<std::string>& ids_to_ignore) const { for (DictionaryValue::key_iterator i = prefs_->begin_keys(); i != prefs_->end_keys(); ++i) { const std::wstring& extension_id = *i; if (ids_to_ignore.find(WideToASCII(extension_id)) != ids_to_ignore.end()) continue; DictionaryValue* extension = NULL; if (!prefs_->GetDictionary(extension_id, &extension)) { continue; } int location; if (extension->GetInteger(kLocation, &location) && location != Extension::EXTERNAL_PREF) { continue; } int state; if (extension->GetInteger(kState, &state) && state == Extension::KILLBIT) { continue; } FilePath::StringType external_crx; std::string external_version; if (!extension->GetString(kExternalCrx, &external_crx) || !extension->GetString(kExternalVersion, &external_version)) { LOG(WARNING) << "Malformed extension dictionary for extension: " << extension_id.c_str(); continue; } scoped_ptr<Version> version; version.reset(Version::GetVersionFromString(external_version)); visitor->OnExternalExtensionFound( WideToASCII(extension_id), version.get(), FilePath(external_crx)); } } Version* ExternalPrefExtensionProvider::RegisteredVersion( std::string id, Extension::Location* location) const { DictionaryValue* extension = NULL; if (!prefs_->GetDictionary(ASCIIToWide(id), &extension)) { NOTREACHED() << "Cannot read extension " << id.c_str() << " from dictionary."; return NULL; } std::string external_version; if (!extension->GetString(kExternalVersion, &external_version)) return NULL; if (location) *location = Extension::EXTERNAL_PREF; return Version::GetVersionFromString(external_version); } <commit_msg>Fix a crash during extension installation (debug only).<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/external_pref_extension_provider.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/version.h" // Constants for keeping track of extension preferences. const wchar_t kLocation[] = L"location"; const wchar_t kState[] = L"state"; const wchar_t kExternalCrx[] = L"external_crx"; const wchar_t kExternalVersion[] = L"external_version"; ExternalPrefExtensionProvider::ExternalPrefExtensionProvider( DictionaryValue* prefs) { DCHECK(prefs); prefs_.reset(prefs); } ExternalPrefExtensionProvider::~ExternalPrefExtensionProvider() { } void ExternalPrefExtensionProvider::VisitRegisteredExtension( Visitor* visitor, const std::set<std::string>& ids_to_ignore) const { for (DictionaryValue::key_iterator i = prefs_->begin_keys(); i != prefs_->end_keys(); ++i) { const std::wstring& extension_id = *i; if (ids_to_ignore.find(WideToASCII(extension_id)) != ids_to_ignore.end()) continue; DictionaryValue* extension = NULL; if (!prefs_->GetDictionary(extension_id, &extension)) { continue; } int location; if (extension->GetInteger(kLocation, &location) && location != Extension::EXTERNAL_PREF) { continue; } int state; if (extension->GetInteger(kState, &state) && state == Extension::KILLBIT) { continue; } FilePath::StringType external_crx; std::string external_version; if (!extension->GetString(kExternalCrx, &external_crx) || !extension->GetString(kExternalVersion, &external_version)) { LOG(WARNING) << "Malformed extension dictionary for extension: " << extension_id.c_str(); continue; } scoped_ptr<Version> version; version.reset(Version::GetVersionFromString(external_version)); visitor->OnExternalExtensionFound( WideToASCII(extension_id), version.get(), FilePath(external_crx)); } } Version* ExternalPrefExtensionProvider::RegisteredVersion( std::string id, Extension::Location* location) const { DictionaryValue* extension = NULL; if (!prefs_->GetDictionary(ASCIIToWide(id), &extension)) return NULL; std::string external_version; if (!extension->GetString(kExternalVersion, &external_version)) return NULL; if (location) *location = Extension::EXTERNAL_PREF; return Version::GetVersionFromString(external_version); } <|endoftext|>
<commit_before>#include <cmath> #include <Eigen/Eigenvalues> #include <esn/create_network_nsli.h> #include <network_nsli.h> namespace ESN { std::unique_ptr< Network > CreateNetwork( const NetworkParamsNSLI & params ) { return std::unique_ptr< NetworkNSLI >( new NetworkNSLI( params ) ); } NetworkNSLI::NetworkNSLI( const NetworkParamsNSLI & params ) : mParams( params ) , mIn( params.inputCount ) , mWIn( params.neuronCount, params.inputCount ) , mX( params.neuronCount ) , mW( params.neuronCount, params.neuronCount ) , mOut( params.outputCount ) , mWOut( params.outputCount, params.neuronCount ) , mWFB( params.neuronCount, params.outputCount ) , mAdaptiveFilter( params.neuronCount ) { if ( params.inputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::inputCount must be not null" ); if ( params.neuronCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::neuronCount must be not null" ); if ( params.outputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::outputCount must be not null" ); if ( !( params.leakingRate > 0.0 && params.leakingRate <= 1.0 ) ) throw std::invalid_argument( "NetworkParamsNSLI::leakingRate must be withing " "interval [0,1)" ); mWIn = Eigen::MatrixXf::Random( params.neuronCount, params.inputCount ); Eigen::MatrixXf randomWeights = Eigen::MatrixXf::Random( params.neuronCount, params.neuronCount ); float spectralRadius = randomWeights.eigenvalues().cwiseAbs().maxCoeff(); mW = ( randomWeights / spectralRadius ).sparseView() ; mWFB = Eigen::MatrixXf::Random( params.neuronCount, params.outputCount ); } NetworkNSLI::~NetworkNSLI() { } void NetworkNSLI::SetInputs( const std::vector< float > & inputs ) { if ( inputs.size() != mIn.rows() ) throw std::invalid_argument( "Wrong size of the input vector" ); mIn = Eigen::Map< Eigen::VectorXf >( const_cast< float * >( inputs.data() ), inputs.size() ); } void NetworkNSLI::Step( float step ) { if ( step <= 0.0f ) throw std::invalid_argument( "Step size must be positive value" ); mX = ( 1 - mParams.leakingRate ) * mX + mParams.leakingRate * ( mWIn * mIn + mW * mX + mWFB * mOut ).unaryExpr( [] ( float x ) -> float { return std::tanh( x ); } ); mOut = mWOut * mX; } void NetworkNSLI::CaptureOutput( std::vector< float > & output ) { if ( output.size() != mParams.outputCount ) throw std::invalid_argument( "Size of the vector must be equal " "actual number of outputs" ); for ( int i = 0; i < mParams.outputCount; ++ i ) output[ i ] = mOut( i ); } void NetworkNSLI::Train( const std::vector< std::vector< float > > & inputs, const std::vector< std::vector< float > > & outputs ) { if ( inputs.size() == 0 ) throw std::invalid_argument( "Number of samples must be not null" ); if ( inputs.size() != outputs.size() ) throw std::invalid_argument( "Number of input and output samples must be equal" ); const unsigned kSampleCount = inputs.size(); Eigen::MatrixXf matX( mParams.neuronCount, kSampleCount ); Eigen::MatrixXf matY( mParams.outputCount, kSampleCount ); for ( int i = 0; i < kSampleCount; ++ i ) { SetInputs( inputs[i] ); Step( 0.1f ); matX.col( i ) = mX; matY.col( i ) = Eigen::Map< Eigen::VectorXf >( const_cast< float * >( outputs[i].data() ), mParams.outputCount ); } Eigen::MatrixXf matXT = matX.transpose(); mWOut = ( matY * matXT * ( matX * matXT ).inverse() ); } void NetworkNSLI::TrainOnline( const std::vector< float > & output ) { Eigen::VectorXf w = mWOut.row( 0 ).transpose(); mAdaptiveFilter.Train( w, mOut( 0 ), output[0], mX ); mWOut.row( 0 ) = w.transpose(); } } // namespace ESN <commit_msg>esn : NetworkNSLI : random inital activations<commit_after>#include <cmath> #include <Eigen/Eigenvalues> #include <esn/create_network_nsli.h> #include <network_nsli.h> namespace ESN { std::unique_ptr< Network > CreateNetwork( const NetworkParamsNSLI & params ) { return std::unique_ptr< NetworkNSLI >( new NetworkNSLI( params ) ); } NetworkNSLI::NetworkNSLI( const NetworkParamsNSLI & params ) : mParams( params ) , mIn( params.inputCount ) , mWIn( params.neuronCount, params.inputCount ) , mX( params.neuronCount ) , mW( params.neuronCount, params.neuronCount ) , mOut( params.outputCount ) , mWOut( params.outputCount, params.neuronCount ) , mWFB( params.neuronCount, params.outputCount ) , mAdaptiveFilter( params.neuronCount ) { if ( params.inputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::inputCount must be not null" ); if ( params.neuronCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::neuronCount must be not null" ); if ( params.outputCount <= 0 ) throw std::invalid_argument( "NetworkParamsNSLI::outputCount must be not null" ); if ( !( params.leakingRate > 0.0 && params.leakingRate <= 1.0 ) ) throw std::invalid_argument( "NetworkParamsNSLI::leakingRate must be withing " "interval [0,1)" ); mWIn = Eigen::MatrixXf::Random( params.neuronCount, params.inputCount ); Eigen::MatrixXf randomWeights = Eigen::MatrixXf::Random( params.neuronCount, params.neuronCount ); float spectralRadius = randomWeights.eigenvalues().cwiseAbs().maxCoeff(); mW = ( randomWeights / spectralRadius ).sparseView() ; mWFB = Eigen::MatrixXf::Random( params.neuronCount, params.outputCount ); mX = Eigen::VectorXf::Random( params.neuronCount ); } NetworkNSLI::~NetworkNSLI() { } void NetworkNSLI::SetInputs( const std::vector< float > & inputs ) { if ( inputs.size() != mIn.rows() ) throw std::invalid_argument( "Wrong size of the input vector" ); mIn = Eigen::Map< Eigen::VectorXf >( const_cast< float * >( inputs.data() ), inputs.size() ); } void NetworkNSLI::Step( float step ) { if ( step <= 0.0f ) throw std::invalid_argument( "Step size must be positive value" ); mX = ( 1 - mParams.leakingRate ) * mX + mParams.leakingRate * ( mWIn * mIn + mW * mX + mWFB * mOut ).unaryExpr( [] ( float x ) -> float { return std::tanh( x ); } ); mOut = mWOut * mX; } void NetworkNSLI::CaptureOutput( std::vector< float > & output ) { if ( output.size() != mParams.outputCount ) throw std::invalid_argument( "Size of the vector must be equal " "actual number of outputs" ); for ( int i = 0; i < mParams.outputCount; ++ i ) output[ i ] = mOut( i ); } void NetworkNSLI::Train( const std::vector< std::vector< float > > & inputs, const std::vector< std::vector< float > > & outputs ) { if ( inputs.size() == 0 ) throw std::invalid_argument( "Number of samples must be not null" ); if ( inputs.size() != outputs.size() ) throw std::invalid_argument( "Number of input and output samples must be equal" ); const unsigned kSampleCount = inputs.size(); Eigen::MatrixXf matX( mParams.neuronCount, kSampleCount ); Eigen::MatrixXf matY( mParams.outputCount, kSampleCount ); for ( int i = 0; i < kSampleCount; ++ i ) { SetInputs( inputs[i] ); Step( 0.1f ); matX.col( i ) = mX; matY.col( i ) = Eigen::Map< Eigen::VectorXf >( const_cast< float * >( outputs[i].data() ), mParams.outputCount ); } Eigen::MatrixXf matXT = matX.transpose(); mWOut = ( matY * matXT * ( matX * matXT ).inverse() ); } void NetworkNSLI::TrainOnline( const std::vector< float > & output ) { Eigen::VectorXf w = mWOut.row( 0 ).transpose(); mAdaptiveFilter.Train( w, mOut( 0 ), output[0], mX ); mWOut.row( 0 ) = w.transpose(); } } // namespace ESN <|endoftext|>
<commit_before>#include <Toolbox/Time/Time.h> #include <ctime> #include <chrono> namespace Toolbox::Time { namespace { const std::string removeTrailingNewline (const std::string & text) { return text.substr (0, text.length () - 1); } } // end anonymous namespace const std::string getCurrentTime (void) { std::time_t now = std::chrono::system_clock::to_time_t (std::chrono::system_clock::now ()); std::tm localNow; #ifdef _WIN32 // localtime_s is not in namespace std on vc++ libraries for some reason localtime_s(&localNow, &now); #else localtime_r(&localNow, &now); #endif constexpr int dateSize = 26; char format[] = "%c"; std::string timestamp{dateSize}; std::strftime(timestamp.data(), dateSize, format, &localNow); return removeTrailingNewline (timestamp); } } // namespace Toolbox::Time <commit_msg>Changed ordering of arguments to localtime_r for linux<commit_after>#include <Toolbox/Time/Time.h> #include <ctime> #include <chrono> namespace Toolbox::Time { namespace { const std::string removeTrailingNewline (const std::string & text) { return text.substr (0, text.length () - 1); } } // end anonymous namespace const std::string getCurrentTime (void) { std::time_t now = std::chrono::system_clock::to_time_t (std::chrono::system_clock::now ()); std::tm localNow; #ifdef _WIN32 // localtime_s is not in namespace std on vc++ libraries for some reason localtime_s(&localNow, &now); #else localtime_r(&now, &localNow); #endif constexpr int dateSize = 26; char format[] = "%c"; std::string timestamp{dateSize}; std::strftime(timestamp.data(), dateSize, format, &localNow); return removeTrailingNewline (timestamp); } } // namespace Toolbox::Time <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD) #define XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD // Base include file. Must be first. #include "XalanTransformerDefinitions.hpp" // Xalan header files. #include <XSLT/ProblemListenerDefault.hpp> class XALAN_TRANSFORMER_EXPORT XalanTransformerProblemListener : public ProblemListener { public: XalanTransformerProblemListener( #if defined(XALAN_NO_NAMESPACES) ostream* theWarningStream, #else std::ostream* theWarningStream, #endif PrintWriter* thePrintWriter); virtual ~XalanTransformerProblemListener(); // These methods are inherited from ProblemListener ... virtual void setPrintWriter(PrintWriter* pw); virtual void problem( eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset); private: ProblemListenerDefault m_problemListener; #if defined(XALAN_NO_NAMESPACES) ostream* m_warningStream; #else std::ostream* m_warningStream; #endif }; #endif // XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD <commit_msg>Fixed problem on HP 11 with -AA switch.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD) #define XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD // Base include file. Must be first. #include "XalanTransformerDefinitions.hpp" #if defined(XALAN_OLD_STREAMS) class ostream; #else #include <iosfwd> #endif // Xalan header files. #include <XSLT/ProblemListenerDefault.hpp> class XALAN_TRANSFORMER_EXPORT XalanTransformerProblemListener : public ProblemListener { public: XalanTransformerProblemListener( #if defined(XALAN_NO_NAMESPACES) ostream* theWarningStream, #else std::ostream* theWarningStream, #endif PrintWriter* thePrintWriter); virtual ~XalanTransformerProblemListener(); // These methods are inherited from ProblemListener ... virtual void setPrintWriter(PrintWriter* pw); virtual void problem( eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset); private: ProblemListenerDefault m_problemListener; #if defined(XALAN_NO_NAMESPACES) ostream* m_warningStream; #else std::ostream* m_warningStream; #endif }; #endif // XALAN_XALANTRANSFORMERPROBLEMLISTENER_HEADER_GUARD <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/behavior/signal_light_scenario.h" #include <algorithm> #include <limits> #include <string> #include <vector> #include "gflags/gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/util/map_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_internal.pb.h" namespace apollo { namespace planning { using apollo::common::adapter::AdapterManager; using apollo::common::util::WithinBound; using apollo::perception::TrafficLight; using apollo::perception::TrafficLightDetection; int SignalLightScenario::ComputeScenarioDecision( Frame* frame, ReferenceLineInfo* const reference_line_info, PlanningTarget* planning_target) { CHECK(frame != nullptr); auto signals_from_map = FindValidSignalLightFromMap(reference_line_info); if (signals_from_map.empty()) { ADEBUG << "No valid signal light along reference line"; return 0; } auto detected_signals = GetPerceptionDetectedSignals(); StopPoint stop_point; stop_point.set_s(std::numeric_limits<double>::max()); stop_point.set_type(StopPoint::HARD); for (const auto signal_from_map : signals_from_map) { auto it_signal = detected_signals.find(signal_from_map->object_id); if (it_signal == detected_signals.end()) { AWARN << "Cannot detect signal which is marked on the map; signal id: " << signal_from_map->object_id; continue; } if (signal_from_map->start_s < stop_point.s()) { stop_point.set_s(signal_from_map->start_s); if (it_signal->second->color() == TrafficLight::RED) { stop_point.set_type(StopPoint::HARD); } else if (it_signal->second->color() == TrafficLight::YELLOW) { stop_point.set_type(StopPoint::SOFT); } } } if (stop_point.s() < std::numeric_limits<double>::max() && stop_point.has_type()) { planning_target->mutable_stop_point()->set_s(stop_point.s()); planning_target->mutable_stop_point()->set_type(stop_point.type()); } return 0; } std::vector<const hdmap::PathOverlap*> SignalLightScenario::FindValidSignalLightFromMap( ReferenceLineInfo* const reference_line_info) { const std::vector<hdmap::PathOverlap>& signal_lights = reference_line_info->reference_line().map_path().signal_overlaps(); if (signal_lights.size() == 0) { ADEBUG << "No signal lights from reference line."; return std::vector<const hdmap::PathOverlap*>(); } ADEBUG << "Found signal_lights size=" << signal_lights.size(); std::vector<const hdmap::PathOverlap*> signal_lights_along_reference_line; for (const auto& signal_light : signal_lights) { if (signal_light.start_s + FLAGS_max_stop_distance_buffer > reference_line_info->AdcSlBoundary().end_s()) { signal_lights_along_reference_line.push_back(&signal_light); } } return signal_lights_along_reference_line; } std::unordered_map<std::string, const TrafficLight*> SignalLightScenario::GetPerceptionDetectedSignals() { if (AdapterManager::GetTrafficLightDetection()->Empty() || (AdapterManager::GetTrafficLightDetection()->GetDelaySec() > FLAGS_signal_expire_time_sec)) { ADEBUG << "traffic light signals msg is either empty or outdated."; return std::unordered_map<std::string, const TrafficLight*>(); } std::unordered_map<std::string, const TrafficLight*> detected_signals; const auto& signal_msg = AdapterManager::GetTrafficLightDetection()->GetLatestObserved(); for (int j = 0; j < signal_msg.traffic_light_size(); ++j) { const auto& signal = signal_msg.traffic_light(j); detected_signals[signal.id()] = &signal; } return detected_signals; } } // namespace planning } // namespace apollo <commit_msg>Planning: not set default stop type<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/behavior/signal_light_scenario.h" #include <algorithm> #include <limits> #include <string> #include <vector> #include "gflags/gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/common/util/map_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_internal.pb.h" namespace apollo { namespace planning { using apollo::common::adapter::AdapterManager; using apollo::common::util::WithinBound; using apollo::perception::TrafficLight; using apollo::perception::TrafficLightDetection; int SignalLightScenario::ComputeScenarioDecision( Frame* frame, ReferenceLineInfo* const reference_line_info, PlanningTarget* planning_target) { CHECK(frame != nullptr); auto signals_from_map = FindValidSignalLightFromMap(reference_line_info); if (signals_from_map.empty()) { ADEBUG << "No valid signal light along reference line"; return 0; } auto detected_signals = GetPerceptionDetectedSignals(); StopPoint stop_point; stop_point.set_s(std::numeric_limits<double>::max()); for (const auto signal_from_map : signals_from_map) { auto it_signal = detected_signals.find(signal_from_map->object_id); if (it_signal == detected_signals.end()) { AWARN << "Cannot detect signal which is marked on the map; signal id: " << signal_from_map->object_id; continue; } if (signal_from_map->start_s < stop_point.s()) { stop_point.set_s(signal_from_map->start_s); if (it_signal->second->color() == TrafficLight::RED) { stop_point.set_type(StopPoint::HARD); } else if (it_signal->second->color() == TrafficLight::YELLOW) { stop_point.set_type(StopPoint::SOFT); } } } if (stop_point.s() < std::numeric_limits<double>::max() && stop_point.has_type()) { planning_target->mutable_stop_point()->set_s(stop_point.s()); planning_target->mutable_stop_point()->set_type(stop_point.type()); } return 0; } std::vector<const hdmap::PathOverlap*> SignalLightScenario::FindValidSignalLightFromMap( ReferenceLineInfo* const reference_line_info) { const std::vector<hdmap::PathOverlap>& signal_lights = reference_line_info->reference_line().map_path().signal_overlaps(); if (signal_lights.size() == 0) { ADEBUG << "No signal lights from reference line."; return std::vector<const hdmap::PathOverlap*>(); } ADEBUG << "Found signal_lights size=" << signal_lights.size(); std::vector<const hdmap::PathOverlap*> signal_lights_along_reference_line; for (const auto& signal_light : signal_lights) { if (signal_light.start_s + FLAGS_max_stop_distance_buffer > reference_line_info->AdcSlBoundary().end_s()) { signal_lights_along_reference_line.push_back(&signal_light); } } return signal_lights_along_reference_line; } std::unordered_map<std::string, const TrafficLight*> SignalLightScenario::GetPerceptionDetectedSignals() { if (AdapterManager::GetTrafficLightDetection()->Empty() || (AdapterManager::GetTrafficLightDetection()->GetDelaySec() > FLAGS_signal_expire_time_sec)) { ADEBUG << "traffic light signals msg is either empty or outdated."; return std::unordered_map<std::string, const TrafficLight*>(); } std::unordered_map<std::string, const TrafficLight*> detected_signals; const auto& signal_msg = AdapterManager::GetTrafficLightDetection()->GetLatestObserved(); for (int j = 0; j < signal_msg.traffic_light_size(); ++j) { const auto& signal = signal_msg.traffic_light(j); detected_signals[signal.id()] = &signal; } return detected_signals; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search_engines/template_url_model_test_util.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" namespace { // A Task used to coordinate when the database has finished processing // requests. See note in BlockTillServiceProcessesRequests for details. // // When Run() schedules a QuitTask on the message loop it was created with. class QuitTask2 : public Task { public: QuitTask2() : main_loop_(MessageLoop::current()) {} virtual void Run() { main_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } private: MessageLoop* main_loop_; }; // Blocks the caller until thread has finished servicing all pending // requests. static void WaitForThreadToProcessRequests(ChromeThread::ID identifier) { // Schedule a task on the thread that is processed after all // pending requests on the thread. ChromeThread::PostTask(identifier, FROM_HERE, new QuitTask2()); // Run the current message loop. QuitTask2, when run, invokes Quit, // which unblocks this. MessageLoop::current()->Run(); } } // namespace // Subclass the TestingProfile so that it can return a WebDataService. class TemplateURLModelTestingProfile : public TestingProfile { public: TemplateURLModelTestingProfile() : TestingProfile() {} void SetUp(); void TearDown(); virtual WebDataService* GetWebDataService(ServiceAccessType access) { return service_.get(); } private: scoped_refptr<WebDataService> service_; FilePath test_dir_; scoped_ptr<ChromeThread> db_thread_; }; // Trivial subclass of TemplateURLModel that records the last invocation of // SetKeywordSearchTermsForURL. class TestingTemplateURLModel : public TemplateURLModel { public: explicit TestingTemplateURLModel(Profile* profile) : TemplateURLModel(profile) { } std::wstring GetAndClearSearchTerm() { std::wstring search_term; search_term.swap(search_term_); return search_term; } protected: virtual void SetKeywordSearchTermsForURL(const TemplateURL* t_url, const GURL& url, const std::wstring& term) { search_term_ = term; } private: std::wstring search_term_; DISALLOW_COPY_AND_ASSIGN(TestingTemplateURLModel); }; void TemplateURLModelTestingProfile::SetUp() { db_thread_.reset(new ChromeThread(ChromeThread::DB)); db_thread_->Start(); // Name a subdirectory of the temp directory. ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_)); test_dir_ = test_dir_.AppendASCII("TemplateURLModelTest"); // Create a fresh, empty copy of this directory. file_util::Delete(test_dir_, true); file_util::CreateDirectory(test_dir_); FilePath path = test_dir_.AppendASCII("TestDataService.db"); service_ = new WebDataService; EXPECT_TRUE(service_->InitWithPath(path)); } void TemplateURLModelTestingProfile::TearDown() { // Clean up the test directory. service_->Shutdown(); // Note that we must ensure the DB thread is stopped after WDS // shutdown (so it can commit pending transactions) but before // deleting the test profile directory, otherwise we may not be // able to delete it due to an open transaction. db_thread_->Stop(); ASSERT_TRUE(file_util::Delete(test_dir_, true)); ASSERT_FALSE(file_util::PathExists(test_dir_)); } TemplateURLModelTestUtil::TemplateURLModelTestUtil() : ui_thread_(ChromeThread::UI, &message_loop_), changed_count_(0) { } TemplateURLModelTestUtil::~TemplateURLModelTestUtil() { } void TemplateURLModelTestUtil::SetUp() { profile_.reset(new TemplateURLModelTestingProfile()); profile_->SetUp(); model_.reset(new TestingTemplateURLModel(profile_.get())); model_->AddObserver(this); } void TemplateURLModelTestUtil::TearDown() { profile_->TearDown(); TemplateURLRef::SetGoogleBaseURL(NULL); // Flush the message loop to make Purify happy. message_loop_.RunAllPending(); } void TemplateURLModelTestUtil::OnTemplateURLModelChanged() { changed_count_++; } void TemplateURLModelTestUtil::VerifyObserverCount(int expected_changed_count) { ASSERT_EQ(expected_changed_count, changed_count_); changed_count_ = 0; } void TemplateURLModelTestUtil::ResetObserverCount() { changed_count_ = 0; } void TemplateURLModelTestUtil::BlockTillServiceProcessesRequests() { WaitForThreadToProcessRequests(ChromeThread::DB); } void TemplateURLModelTestUtil::BlockTillIOThreadProcessesRequests() { WaitForThreadToProcessRequests(ChromeThread::IO); } void TemplateURLModelTestUtil::VerifyLoad() { ASSERT_FALSE(model_->loaded()); model_->Load(); BlockTillServiceProcessesRequests(); VerifyObserverCount(1); } void TemplateURLModelTestUtil::ChangeModelToLoadState() { model_->ChangeToLoadedState(); // Initialize the web data service so that the database gets updated with // any changes made. model_->service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS); } void TemplateURLModelTestUtil::ClearModel() { model_.reset(NULL); } void TemplateURLModelTestUtil::ResetModel(bool verify_load) { model_.reset(new TestingTemplateURLModel(profile_.get())); model_->AddObserver(this); changed_count_ = 0; if (verify_load) VerifyLoad(); } std::wstring TemplateURLModelTestUtil::GetAndClearSearchTerm() { return model_->GetAndClearSearchTerm(); } void TemplateURLModelTestUtil::SetGoogleBaseURL( const std::string& base_url) const { TemplateURLRef::SetGoogleBaseURL(new std::string(base_url)); } WebDataService* TemplateURLModelTestUtil::GetWebDataService() { return profile_->GetWebDataService(Profile::EXPLICIT_ACCESS); } TemplateURLModel* TemplateURLModelTestUtil::model() const { return model_.get(); } TestingProfile* TemplateURLModelTestUtil::profile() const { return profile_.get(); } <commit_msg>Remove the code that shall not be used in tests: PathService::Get(base::DIR_TEMP<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search_engines/template_url_model_test_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "chrome/browser/search_engines/template_url.h" #include "chrome/browser/search_engines/template_url_model.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" namespace { // A Task used to coordinate when the database has finished processing // requests. See note in BlockTillServiceProcessesRequests for details. // // When Run() schedules a QuitTask on the message loop it was created with. class QuitTask2 : public Task { public: QuitTask2() : main_loop_(MessageLoop::current()) {} virtual void Run() { main_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } private: MessageLoop* main_loop_; }; // Blocks the caller until thread has finished servicing all pending // requests. static void WaitForThreadToProcessRequests(ChromeThread::ID identifier) { // Schedule a task on the thread that is processed after all // pending requests on the thread. ChromeThread::PostTask(identifier, FROM_HERE, new QuitTask2()); // Run the current message loop. QuitTask2, when run, invokes Quit, // which unblocks this. MessageLoop::current()->Run(); } } // namespace // Subclass the TestingProfile so that it can return a WebDataService. class TemplateURLModelTestingProfile : public TestingProfile { public: TemplateURLModelTestingProfile() : TestingProfile() {} void SetUp(); void TearDown(); virtual WebDataService* GetWebDataService(ServiceAccessType access) { return service_.get(); } private: scoped_refptr<WebDataService> service_; ScopedTempDir temp_dir_; scoped_ptr<ChromeThread> db_thread_; }; // Trivial subclass of TemplateURLModel that records the last invocation of // SetKeywordSearchTermsForURL. class TestingTemplateURLModel : public TemplateURLModel { public: explicit TestingTemplateURLModel(Profile* profile) : TemplateURLModel(profile) { } std::wstring GetAndClearSearchTerm() { std::wstring search_term; search_term.swap(search_term_); return search_term; } protected: virtual void SetKeywordSearchTermsForURL(const TemplateURL* t_url, const GURL& url, const std::wstring& term) { search_term_ = term; } private: std::wstring search_term_; DISALLOW_COPY_AND_ASSIGN(TestingTemplateURLModel); }; void TemplateURLModelTestingProfile::SetUp() { db_thread_.reset(new ChromeThread(ChromeThread::DB)); db_thread_->Start(); // Make unique temp directory. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath path = temp_dir_.path().AppendASCII("TestDataService.db"); service_ = new WebDataService; EXPECT_TRUE(service_->InitWithPath(path)); } void TemplateURLModelTestingProfile::TearDown() { // Clean up the test directory. service_->Shutdown(); // Note that we must ensure the DB thread is stopped after WDS // shutdown (so it can commit pending transactions) but before // deleting the test profile directory, otherwise we may not be // able to delete it due to an open transaction. db_thread_->Stop(); } TemplateURLModelTestUtil::TemplateURLModelTestUtil() : ui_thread_(ChromeThread::UI, &message_loop_), changed_count_(0) { } TemplateURLModelTestUtil::~TemplateURLModelTestUtil() { } void TemplateURLModelTestUtil::SetUp() { profile_.reset(new TemplateURLModelTestingProfile()); profile_->SetUp(); model_.reset(new TestingTemplateURLModel(profile_.get())); model_->AddObserver(this); } void TemplateURLModelTestUtil::TearDown() { profile_->TearDown(); TemplateURLRef::SetGoogleBaseURL(NULL); // Flush the message loop to make Purify happy. message_loop_.RunAllPending(); } void TemplateURLModelTestUtil::OnTemplateURLModelChanged() { changed_count_++; } void TemplateURLModelTestUtil::VerifyObserverCount(int expected_changed_count) { ASSERT_EQ(expected_changed_count, changed_count_); changed_count_ = 0; } void TemplateURLModelTestUtil::ResetObserverCount() { changed_count_ = 0; } void TemplateURLModelTestUtil::BlockTillServiceProcessesRequests() { WaitForThreadToProcessRequests(ChromeThread::DB); } void TemplateURLModelTestUtil::BlockTillIOThreadProcessesRequests() { WaitForThreadToProcessRequests(ChromeThread::IO); } void TemplateURLModelTestUtil::VerifyLoad() { ASSERT_FALSE(model_->loaded()); model_->Load(); BlockTillServiceProcessesRequests(); VerifyObserverCount(1); } void TemplateURLModelTestUtil::ChangeModelToLoadState() { model_->ChangeToLoadedState(); // Initialize the web data service so that the database gets updated with // any changes made. model_->service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS); } void TemplateURLModelTestUtil::ClearModel() { model_.reset(NULL); } void TemplateURLModelTestUtil::ResetModel(bool verify_load) { model_.reset(new TestingTemplateURLModel(profile_.get())); model_->AddObserver(this); changed_count_ = 0; if (verify_load) VerifyLoad(); } std::wstring TemplateURLModelTestUtil::GetAndClearSearchTerm() { return model_->GetAndClearSearchTerm(); } void TemplateURLModelTestUtil::SetGoogleBaseURL( const std::string& base_url) const { TemplateURLRef::SetGoogleBaseURL(new std::string(base_url)); } WebDataService* TemplateURLModelTestUtil::GetWebDataService() { return profile_->GetWebDataService(Profile::EXPLICIT_ACCESS); } TemplateURLModel* TemplateURLModelTestUtil::model() const { return model_.get(); } TestingProfile* TemplateURLModelTestUtil::profile() const { return profile_.get(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: convuno.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2006-04-07 16:21:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_CONVUNO_HXX #define SC_CONVUNO_HXX #ifndef INCLUDED_I18NPOOL_LANG_H #include <i18npool/lang.h> #endif #ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_ #include <com/sun/star/table/CellAddress.hpp> #endif #ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_ #include <com/sun/star/table/CellRangeAddress.hpp> #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif class ScUnoConversion { public: static LanguageType GetLanguage( const com::sun::star::lang::Locale& rLocale ); static void FillLocale( com::sun::star::lang::Locale& rLocale, LanguageType eLang ); // CellAddress -> ScAddress static inline void FillScAddress( ScAddress& rScAddress, const ::com::sun::star::table::CellAddress& rApiAddress ); // ScAddress -> CellAddress static inline void FillApiAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ScAddress& rScAddress ); // CellRangeAddress -> ScRange static inline void FillScRange( ScRange& rScRange, const ::com::sun::star::table::CellRangeAddress& rApiRange ); // ScRange -> CellRangeAddress static inline void FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ScRange& rScRange ); // CellAddress -> CellRangeAddress static inline void FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ::com::sun::star::table::CellAddress& rApiAddress ); // CellRangeAddress-Start -> CellAddress static inline void FillApiStartAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ); // CellRangeAddress-End -> CellAddress static inline void FillApiEndAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ); }; inline void ScUnoConversion::FillScAddress( ScAddress& rScAddress, const ::com::sun::star::table::CellAddress& rApiAddress ) { rScAddress.Set( (SCCOL)rApiAddress.Column, (SCROW)rApiAddress.Row, (SCTAB)rApiAddress.Sheet ); } inline void ScUnoConversion::FillApiAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ScAddress& rScAddress ) { rApiAddress.Column = rScAddress.Col(); rApiAddress.Row = rScAddress.Row(); rApiAddress.Sheet = rScAddress.Tab(); } inline void ScUnoConversion::FillScRange( ScRange& rScRange, const ::com::sun::star::table::CellRangeAddress& rApiRange ) { rScRange.aStart.Set( (SCCOL)rApiRange.StartColumn, (SCROW)rApiRange.StartRow, (SCTAB)rApiRange.Sheet ); rScRange.aEnd.Set( (SCCOL)rApiRange.EndColumn, (SCROW)rApiRange.EndRow, (SCTAB)rApiRange.Sheet ); } inline void ScUnoConversion::FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ScRange& rScRange ) { rApiRange.StartColumn = rScRange.aStart.Col(); rApiRange.StartRow = rScRange.aStart.Row(); rApiRange.Sheet = rScRange.aStart.Tab(); rApiRange.EndColumn = rScRange.aEnd.Col(); rApiRange.EndRow = rScRange.aEnd.Row(); } inline void ScUnoConversion::FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ::com::sun::star::table::CellAddress& rApiAddress ) { rApiRange.StartColumn = rApiRange.EndColumn = rApiAddress.Column; rApiRange.StartRow = rApiRange.EndRow = rApiAddress.Row; rApiRange.Sheet = rApiAddress.Sheet; } inline void ScUnoConversion::FillApiStartAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ) { rApiAddress.Column = rApiRange.StartColumn; rApiAddress.Row = rApiRange.StartRow; rApiAddress.Sheet = rApiRange.Sheet; } inline void ScUnoConversion::FillApiEndAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ) { rApiAddress.Column = rApiRange.EndColumn; rApiAddress.Row = rApiRange.EndRow; rApiAddress.Sheet = rApiRange.Sheet; } //___________________________________________________________________ inline sal_Bool operator==( const ::com::sun::star::table::CellAddress& rApiAddress1, const ::com::sun::star::table::CellAddress& rApiAddress2 ) { return (rApiAddress1.Column == rApiAddress2.Column) && (rApiAddress1.Row == rApiAddress2.Row) && (rApiAddress1.Sheet == rApiAddress2.Sheet); } inline sal_Bool operator!=( const ::com::sun::star::table::CellAddress& rApiAddress1, const ::com::sun::star::table::CellAddress& rApiAddress2 ) { return !(rApiAddress1 == rApiAddress2); } inline sal_Bool operator==( const ::com::sun::star::table::CellRangeAddress& rApiRange1, const ::com::sun::star::table::CellRangeAddress& rApiRange2 ) { return (rApiRange1.StartColumn == rApiRange2.StartColumn) && (rApiRange1.StartRow == rApiRange2.StartRow) && (rApiRange1.EndColumn == rApiRange2.EndColumn) && (rApiRange1.EndRow == rApiRange2.EndRow) && (rApiRange1.Sheet == rApiRange2.Sheet); } inline sal_Bool operator!=( const ::com::sun::star::table::CellRangeAddress& rApiRange1, const ::com::sun::star::table::CellRangeAddress& rApiRange2 ) { return !(rApiRange1 == rApiRange2); } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.572); FILE MERGED 2008/04/01 15:29:23 thb 1.6.572.3: #i85898# Stripping all external header guards 2008/04/01 12:35:52 thb 1.6.572.2: #i85898# Stripping all external header guards 2008/03/31 17:13:27 rt 1.6.572.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: convuno.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_CONVUNO_HXX #define SC_CONVUNO_HXX #include <i18npool/lang.h> #include <com/sun/star/table/CellAddress.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <com/sun/star/lang/Locale.hpp> #include "global.hxx" #include "address.hxx" class ScUnoConversion { public: static LanguageType GetLanguage( const com::sun::star::lang::Locale& rLocale ); static void FillLocale( com::sun::star::lang::Locale& rLocale, LanguageType eLang ); // CellAddress -> ScAddress static inline void FillScAddress( ScAddress& rScAddress, const ::com::sun::star::table::CellAddress& rApiAddress ); // ScAddress -> CellAddress static inline void FillApiAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ScAddress& rScAddress ); // CellRangeAddress -> ScRange static inline void FillScRange( ScRange& rScRange, const ::com::sun::star::table::CellRangeAddress& rApiRange ); // ScRange -> CellRangeAddress static inline void FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ScRange& rScRange ); // CellAddress -> CellRangeAddress static inline void FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ::com::sun::star::table::CellAddress& rApiAddress ); // CellRangeAddress-Start -> CellAddress static inline void FillApiStartAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ); // CellRangeAddress-End -> CellAddress static inline void FillApiEndAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ); }; inline void ScUnoConversion::FillScAddress( ScAddress& rScAddress, const ::com::sun::star::table::CellAddress& rApiAddress ) { rScAddress.Set( (SCCOL)rApiAddress.Column, (SCROW)rApiAddress.Row, (SCTAB)rApiAddress.Sheet ); } inline void ScUnoConversion::FillApiAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ScAddress& rScAddress ) { rApiAddress.Column = rScAddress.Col(); rApiAddress.Row = rScAddress.Row(); rApiAddress.Sheet = rScAddress.Tab(); } inline void ScUnoConversion::FillScRange( ScRange& rScRange, const ::com::sun::star::table::CellRangeAddress& rApiRange ) { rScRange.aStart.Set( (SCCOL)rApiRange.StartColumn, (SCROW)rApiRange.StartRow, (SCTAB)rApiRange.Sheet ); rScRange.aEnd.Set( (SCCOL)rApiRange.EndColumn, (SCROW)rApiRange.EndRow, (SCTAB)rApiRange.Sheet ); } inline void ScUnoConversion::FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ScRange& rScRange ) { rApiRange.StartColumn = rScRange.aStart.Col(); rApiRange.StartRow = rScRange.aStart.Row(); rApiRange.Sheet = rScRange.aStart.Tab(); rApiRange.EndColumn = rScRange.aEnd.Col(); rApiRange.EndRow = rScRange.aEnd.Row(); } inline void ScUnoConversion::FillApiRange( ::com::sun::star::table::CellRangeAddress& rApiRange, const ::com::sun::star::table::CellAddress& rApiAddress ) { rApiRange.StartColumn = rApiRange.EndColumn = rApiAddress.Column; rApiRange.StartRow = rApiRange.EndRow = rApiAddress.Row; rApiRange.Sheet = rApiAddress.Sheet; } inline void ScUnoConversion::FillApiStartAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ) { rApiAddress.Column = rApiRange.StartColumn; rApiAddress.Row = rApiRange.StartRow; rApiAddress.Sheet = rApiRange.Sheet; } inline void ScUnoConversion::FillApiEndAddress( ::com::sun::star::table::CellAddress& rApiAddress, const ::com::sun::star::table::CellRangeAddress& rApiRange ) { rApiAddress.Column = rApiRange.EndColumn; rApiAddress.Row = rApiRange.EndRow; rApiAddress.Sheet = rApiRange.Sheet; } //___________________________________________________________________ inline sal_Bool operator==( const ::com::sun::star::table::CellAddress& rApiAddress1, const ::com::sun::star::table::CellAddress& rApiAddress2 ) { return (rApiAddress1.Column == rApiAddress2.Column) && (rApiAddress1.Row == rApiAddress2.Row) && (rApiAddress1.Sheet == rApiAddress2.Sheet); } inline sal_Bool operator!=( const ::com::sun::star::table::CellAddress& rApiAddress1, const ::com::sun::star::table::CellAddress& rApiAddress2 ) { return !(rApiAddress1 == rApiAddress2); } inline sal_Bool operator==( const ::com::sun::star::table::CellRangeAddress& rApiRange1, const ::com::sun::star::table::CellRangeAddress& rApiRange2 ) { return (rApiRange1.StartColumn == rApiRange2.StartColumn) && (rApiRange1.StartRow == rApiRange2.StartRow) && (rApiRange1.EndColumn == rApiRange2.EndColumn) && (rApiRange1.EndRow == rApiRange2.EndRow) && (rApiRange1.Sheet == rApiRange2.Sheet); } inline sal_Bool operator!=( const ::com::sun::star::table::CellRangeAddress& rApiRange1, const ::com::sun::star::table::CellRangeAddress& rApiRange2 ) { return !(rApiRange1 == rApiRange2); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: detfunc.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:41:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_DETFUNC_HXX #define SC_DETFUNC_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif class SdrObject; class SdrPage; class String; class ScCommentData; class ScDetectiveData; class ScDocument; class ScAddress; class ScRange; #define SC_DET_MAXCIRCLE 1000 enum ScDetectiveDelete { SC_DET_ALL, SC_DET_DETECTIVE, SC_DET_CIRCLES, SC_DET_COMMENTS, SC_DET_ARROWS }; enum ScDetectiveObjType { SC_DETOBJ_NONE, SC_DETOBJ_ARROW, SC_DETOBJ_FROMOTHERTAB, SC_DETOBJ_TOOTHERTAB, SC_DETOBJ_CIRCLE }; class ScDetectiveFunc { static ColorData nArrowColor; static ColorData nErrorColor; static ColorData nCommentColor; static BOOL bColorsInitialized; ScDocument* pDoc; SCTAB nTab; BOOL HasArrow( const ScAddress& rStart, SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab ); void DeleteArrowsAt( SCCOL nCol, SCROW nRow, BOOL bDestPnt ); void DeleteBox( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 ); BOOL HasError( const ScRange& rRange, ScAddress& rErrPos ); void FillAttributes( ScDetectiveData& rData ); // called from DrawEntry/DrawAlienEntry and InsertObject BOOL InsertArrow( SCCOL nCol, SCROW nRow, SCCOL nRefStartCol, SCROW nRefStartRow, SCCOL nRefEndCol, SCROW nRefEndRow, BOOL bFromOtherTab, BOOL bRed, ScDetectiveData& rData ); BOOL InsertToOtherTab( SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow, BOOL bRed, ScDetectiveData& rData ); // DrawEntry / DrawAlienEntry check for existing arrows and errors BOOL DrawEntry( SCCOL nCol, SCROW nRow, const ScRange& rRef, ScDetectiveData& rData ); BOOL DrawAlienEntry( const ScRange& rRef, ScDetectiveData& rData ); void DrawCircle( SCCOL nCol, SCROW nRow, ScDetectiveData& rData ); SdrObject* DrawCaption( SCCOL nCol, SCROW nRow, const String& rText, ScCommentData& rData, SdrPage* pDestPage, BOOL bHasUserText, BOOL bLeft, const Rectangle& rVisible ); USHORT InsertPredLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel ); USHORT InsertPredLevelArea( const ScRange& rRef, ScDetectiveData& rData, USHORT nLevel ); USHORT FindPredLevel( SCCOL nCol, SCROW nRow, USHORT nLevel, USHORT nDeleteLevel ); USHORT FindPredLevelArea( const ScRange& rRef, USHORT nLevel, USHORT nDeleteLevel ); USHORT InsertErrorLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel ); USHORT InsertSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2, ScDetectiveData& rData, USHORT nLevel ); USHORT FindSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2, USHORT nLevel, USHORT nDeleteLevel ); BOOL FindFrameForObject( SdrObject* pObject, ScRange& rRange ); public: ScDetectiveFunc(ScDocument* pDocument, SCTAB nTable) : pDoc(pDocument),nTab(nTable) {} Point GetDrawPos( SCCOL nCol, SCROW nRow, BOOL bArrow ); BOOL ShowSucc( SCCOL nCol, SCROW nRow ); BOOL ShowPred( SCCOL nCol, SCROW nRow ); BOOL ShowError( SCCOL nCol, SCROW nRow ); BOOL DeleteSucc( SCCOL nCol, SCROW nRow ); BOOL DeletePred( SCCOL nCol, SCROW nRow ); BOOL DeleteAll( ScDetectiveDelete eWhat ); BOOL MarkInvalid(BOOL& rOverflow); SdrObject* ShowComment( SCCOL nCol, SCROW nRow, BOOL bForce, SdrPage* pDestPage = NULL ); SdrObject* ShowCommentUser( SCCOL nCol, SCROW nRow, const String& rUserText, const Rectangle& rVisible, BOOL bLeft, BOOL bForce, SdrPage* pDestPage ); BOOL HideComment( SCCOL nCol, SCROW nRow ); void UpdateAllComments(); // on all tables void UpdateAllArrowColors(); // on all tables static BOOL IsNonAlienArrow( SdrObject* pObject ); ScDetectiveObjType GetDetectiveObjectType( SdrObject* pObject, ScAddress& rPosition, ScRange& rSource, BOOL& rRedLine ); void InsertObject( ScDetectiveObjType eType, const ScAddress& rPosition, const ScRange& rSource, BOOL bRedLine ); static ColorData GetArrowColor(); static ColorData GetErrorColor(); static ColorData GetCommentColor(); static void InitializeColors(); static BOOL IsColorsInitialized(); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.8.328); FILE MERGED 2005/09/05 15:00:40 rt 1.8.328.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: detfunc.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:32:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_DETFUNC_HXX #define SC_DETFUNC_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif class SdrObject; class SdrPage; class String; class ScCommentData; class ScDetectiveData; class ScDocument; class ScAddress; class ScRange; #define SC_DET_MAXCIRCLE 1000 enum ScDetectiveDelete { SC_DET_ALL, SC_DET_DETECTIVE, SC_DET_CIRCLES, SC_DET_COMMENTS, SC_DET_ARROWS }; enum ScDetectiveObjType { SC_DETOBJ_NONE, SC_DETOBJ_ARROW, SC_DETOBJ_FROMOTHERTAB, SC_DETOBJ_TOOTHERTAB, SC_DETOBJ_CIRCLE }; class ScDetectiveFunc { static ColorData nArrowColor; static ColorData nErrorColor; static ColorData nCommentColor; static BOOL bColorsInitialized; ScDocument* pDoc; SCTAB nTab; BOOL HasArrow( const ScAddress& rStart, SCCOL nEndCol, SCROW nEndRow, SCTAB nEndTab ); void DeleteArrowsAt( SCCOL nCol, SCROW nRow, BOOL bDestPnt ); void DeleteBox( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 ); BOOL HasError( const ScRange& rRange, ScAddress& rErrPos ); void FillAttributes( ScDetectiveData& rData ); // called from DrawEntry/DrawAlienEntry and InsertObject BOOL InsertArrow( SCCOL nCol, SCROW nRow, SCCOL nRefStartCol, SCROW nRefStartRow, SCCOL nRefEndCol, SCROW nRefEndRow, BOOL bFromOtherTab, BOOL bRed, ScDetectiveData& rData ); BOOL InsertToOtherTab( SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow, BOOL bRed, ScDetectiveData& rData ); // DrawEntry / DrawAlienEntry check for existing arrows and errors BOOL DrawEntry( SCCOL nCol, SCROW nRow, const ScRange& rRef, ScDetectiveData& rData ); BOOL DrawAlienEntry( const ScRange& rRef, ScDetectiveData& rData ); void DrawCircle( SCCOL nCol, SCROW nRow, ScDetectiveData& rData ); SdrObject* DrawCaption( SCCOL nCol, SCROW nRow, const String& rText, ScCommentData& rData, SdrPage* pDestPage, BOOL bHasUserText, BOOL bLeft, const Rectangle& rVisible ); USHORT InsertPredLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel ); USHORT InsertPredLevelArea( const ScRange& rRef, ScDetectiveData& rData, USHORT nLevel ); USHORT FindPredLevel( SCCOL nCol, SCROW nRow, USHORT nLevel, USHORT nDeleteLevel ); USHORT FindPredLevelArea( const ScRange& rRef, USHORT nLevel, USHORT nDeleteLevel ); USHORT InsertErrorLevel( SCCOL nCol, SCROW nRow, ScDetectiveData& rData, USHORT nLevel ); USHORT InsertSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2, ScDetectiveData& rData, USHORT nLevel ); USHORT FindSuccLevel( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2, USHORT nLevel, USHORT nDeleteLevel ); BOOL FindFrameForObject( SdrObject* pObject, ScRange& rRange ); public: ScDetectiveFunc(ScDocument* pDocument, SCTAB nTable) : pDoc(pDocument),nTab(nTable) {} Point GetDrawPos( SCCOL nCol, SCROW nRow, BOOL bArrow ); BOOL ShowSucc( SCCOL nCol, SCROW nRow ); BOOL ShowPred( SCCOL nCol, SCROW nRow ); BOOL ShowError( SCCOL nCol, SCROW nRow ); BOOL DeleteSucc( SCCOL nCol, SCROW nRow ); BOOL DeletePred( SCCOL nCol, SCROW nRow ); BOOL DeleteAll( ScDetectiveDelete eWhat ); BOOL MarkInvalid(BOOL& rOverflow); SdrObject* ShowComment( SCCOL nCol, SCROW nRow, BOOL bForce, SdrPage* pDestPage = NULL ); SdrObject* ShowCommentUser( SCCOL nCol, SCROW nRow, const String& rUserText, const Rectangle& rVisible, BOOL bLeft, BOOL bForce, SdrPage* pDestPage ); BOOL HideComment( SCCOL nCol, SCROW nRow ); void UpdateAllComments(); // on all tables void UpdateAllArrowColors(); // on all tables static BOOL IsNonAlienArrow( SdrObject* pObject ); ScDetectiveObjType GetDetectiveObjectType( SdrObject* pObject, ScAddress& rPosition, ScRange& rSource, BOOL& rRedLine ); void InsertObject( ScDetectiveObjType eType, const ScAddress& rPosition, const ScRange& rSource, BOOL bRedLine ); static ColorData GetArrowColor(); static ColorData GetErrorColor(); static ColorData GetCommentColor(); static void InitializeColors(); static BOOL IsColorsInitialized(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: scresid.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:44:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SCRESID_HXX #define SC_SCRESID_HXX #ifndef _TOOLS_RESID_HXX //autogen #include <tools/resid.hxx> #endif //=================================================================== class ScResId : public ResId { public: ScResId( USHORT nId ); // in scdll.cxx }; #endif // SC_SCRESMGR_HXX <commit_msg>INTEGRATION: CWS tune03 (1.1.1.1.530); FILE MERGED 2004/07/08 16:45:01 mhu 1.1.1.1.530.1: #i29979# Added SC_DLLPUBLIC/PRIVATE (see scdllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: scresid.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-08-23 09:26:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SCRESID_HXX #define SC_SCRESID_HXX #ifndef _TOOLS_RESID_HXX //autogen #include <tools/resid.hxx> #endif #ifndef INCLUDED_SCDLLAPI_H #include "scdllapi.h" #endif //=================================================================== class SC_DLLPUBLIC ScResId : public ResId { public: ScResId( USHORT nId ); // in scdll.cxx }; #endif // SC_SCRESMGR_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unowids.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: nn $ $Date: 2001-04-17 19:33:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_UNOWIDS_HXX #define SC_UNOWIDS_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef SC_ITEMS_HXX #include "scitems.hxx" #endif // WIDs for uno property maps, // never stored in files #define SC_WID_UNO_START 1200 #define SC_WID_UNO_CELLSTYL ( SC_WID_UNO_START + 0 ) #define SC_WID_UNO_CHCOLHDR ( SC_WID_UNO_START + 1 ) #define SC_WID_UNO_CHROWHDR ( SC_WID_UNO_START + 2 ) #define SC_WID_UNO_CONDFMT ( SC_WID_UNO_START + 3 ) #define SC_WID_UNO_CONDLOC ( SC_WID_UNO_START + 4 ) #define SC_WID_UNO_CONDXML ( SC_WID_UNO_START + 5 ) #define SC_WID_UNO_TBLBORD ( SC_WID_UNO_START + 6 ) #define SC_WID_UNO_VALIDAT ( SC_WID_UNO_START + 7 ) #define SC_WID_UNO_VALILOC ( SC_WID_UNO_START + 8 ) #define SC_WID_UNO_VALIXML ( SC_WID_UNO_START + 9 ) #define SC_WID_UNO_POS ( SC_WID_UNO_START + 10 ) #define SC_WID_UNO_SIZE ( SC_WID_UNO_START + 11 ) #define SC_WID_UNO_FORMLOC ( SC_WID_UNO_START + 12 ) #define SC_WID_UNO_FORMRT ( SC_WID_UNO_START + 13 ) #define SC_WID_UNO_PAGESTL ( SC_WID_UNO_START + 14 ) #define SC_WID_UNO_CELLVIS ( SC_WID_UNO_START + 15 ) #define SC_WID_UNO_LINKDISPBIT ( SC_WID_UNO_START + 16 ) #define SC_WID_UNO_LINKDISPNAME ( SC_WID_UNO_START + 17 ) #define SC_WID_UNO_CELLWID ( SC_WID_UNO_START + 18 ) #define SC_WID_UNO_OWIDTH ( SC_WID_UNO_START + 19 ) #define SC_WID_UNO_NEWPAGE ( SC_WID_UNO_START + 20 ) #define SC_WID_UNO_MANPAGE ( SC_WID_UNO_START + 21 ) #define SC_WID_UNO_CELLHGT ( SC_WID_UNO_START + 22 ) #define SC_WID_UNO_CELLFILT ( SC_WID_UNO_START + 23 ) #define SC_WID_UNO_OHEIGHT ( SC_WID_UNO_START + 24 ) #define SC_WID_UNO_END ( SC_WID_UNO_START + 24 ) inline BOOL IsScUnoWid( USHORT nWid ) { return nWid >= SC_WID_UNO_START && nWid <= SC_WID_UNO_END; } inline BOOL IsScItemWid( USHORT nWid ) { return nWid >= ATTR_STARTINDEX && nWid <= ATTR_ENDINDEX; // incl. page } #endif <commit_msg>WIDs for style object<commit_after>/************************************************************************* * * $RCSfile: unowids.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: nn $ $Date: 2001-04-25 18:48:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_UNOWIDS_HXX #define SC_UNOWIDS_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef SC_ITEMS_HXX #include "scitems.hxx" #endif // WIDs for uno property maps, // never stored in files #define SC_WID_UNO_START 1200 #define SC_WID_UNO_CELLSTYL ( SC_WID_UNO_START + 0 ) #define SC_WID_UNO_CHCOLHDR ( SC_WID_UNO_START + 1 ) #define SC_WID_UNO_CHROWHDR ( SC_WID_UNO_START + 2 ) #define SC_WID_UNO_CONDFMT ( SC_WID_UNO_START + 3 ) #define SC_WID_UNO_CONDLOC ( SC_WID_UNO_START + 4 ) #define SC_WID_UNO_CONDXML ( SC_WID_UNO_START + 5 ) #define SC_WID_UNO_TBLBORD ( SC_WID_UNO_START + 6 ) #define SC_WID_UNO_VALIDAT ( SC_WID_UNO_START + 7 ) #define SC_WID_UNO_VALILOC ( SC_WID_UNO_START + 8 ) #define SC_WID_UNO_VALIXML ( SC_WID_UNO_START + 9 ) #define SC_WID_UNO_POS ( SC_WID_UNO_START + 10 ) #define SC_WID_UNO_SIZE ( SC_WID_UNO_START + 11 ) #define SC_WID_UNO_FORMLOC ( SC_WID_UNO_START + 12 ) #define SC_WID_UNO_FORMRT ( SC_WID_UNO_START + 13 ) #define SC_WID_UNO_PAGESTL ( SC_WID_UNO_START + 14 ) #define SC_WID_UNO_CELLVIS ( SC_WID_UNO_START + 15 ) #define SC_WID_UNO_LINKDISPBIT ( SC_WID_UNO_START + 16 ) #define SC_WID_UNO_LINKDISPNAME ( SC_WID_UNO_START + 17 ) #define SC_WID_UNO_CELLWID ( SC_WID_UNO_START + 18 ) #define SC_WID_UNO_OWIDTH ( SC_WID_UNO_START + 19 ) #define SC_WID_UNO_NEWPAGE ( SC_WID_UNO_START + 20 ) #define SC_WID_UNO_MANPAGE ( SC_WID_UNO_START + 21 ) #define SC_WID_UNO_CELLHGT ( SC_WID_UNO_START + 22 ) #define SC_WID_UNO_CELLFILT ( SC_WID_UNO_START + 23 ) #define SC_WID_UNO_OHEIGHT ( SC_WID_UNO_START + 24 ) #define SC_WID_UNO_DISPNAME ( SC_WID_UNO_START + 25 ) #define SC_WID_UNO_HEADERSET ( SC_WID_UNO_START + 26 ) #define SC_WID_UNO_FOOTERSET ( SC_WID_UNO_START + 27 ) #define SC_WID_UNO_END ( SC_WID_UNO_START + 27 ) inline BOOL IsScUnoWid( USHORT nWid ) { return nWid >= SC_WID_UNO_START && nWid <= SC_WID_UNO_END; } inline BOOL IsScItemWid( USHORT nWid ) { return nWid >= ATTR_STARTINDEX && nWid <= ATTR_ENDINDEX; // incl. page } #endif <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Widgets/ButtonWidget.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/World.hpp> namespace Ndk { ButtonWidget::ButtonWidget(const WorldHandle& world, BaseWidget* parent) : BaseWidget(world, parent) { m_gradientSprite = Nz::Sprite::New(); m_gradientSprite->SetColor(Nz::Color(74, 74, 74)); m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, Nz::Color(180, 180, 180)); m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, Nz::Color(180, 180, 180)); m_gradientSprite->SetMaterial(Nz::Material::New("Basic2D")); m_gradientEntity = CreateEntity(); m_gradientEntity->AddComponent<NodeComponent>().SetParent(this); m_gradientEntity->AddComponent<GraphicsComponent>().Attach(m_gradientSprite); m_gradientEntity->GetComponent<GraphicsComponent>().Attach(m_borderSprite, Nz::Matrix4f::Translate(Nz::Vector2f(-1.f, -1.f)), -1); m_textSprite = Nz::TextSprite::New(); m_textEntity = CreateEntity(); m_textEntity->AddComponent<NodeComponent>().SetParent(this); m_textEntity->AddComponent<GraphicsComponent>().Attach(m_textSprite, 1); } void ButtonWidget::ResizeToContent() { SetContentSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths())); } void ButtonWidget::Layout() { const Nz::Vector2f& contentSize = GetContentSize(); m_gradientSprite->SetSize(contentSize); Nz::Boxf textBox = m_textEntity->GetComponent<GraphicsComponent>().GetBoundingVolume().aabb; m_textEntity->GetComponent<NodeComponent>().SetPosition(contentSize.x / 2 - textBox.width / 2, contentSize.y / 2 - textBox.height / 2); } } <commit_msg>Sdk/ButtonWidget: Fix compilation<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Widgets/ButtonWidget.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/World.hpp> namespace Ndk { ButtonWidget::ButtonWidget(const WorldHandle& world, BaseWidget* parent) : BaseWidget(world, parent) { m_gradientSprite = Nz::Sprite::New(); m_gradientSprite->SetColor(Nz::Color(74, 74, 74)); m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, Nz::Color(180, 180, 180)); m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, Nz::Color(180, 180, 180)); m_gradientSprite->SetMaterial(Nz::Material::New("Basic2D")); m_gradientEntity = CreateEntity(); m_gradientEntity->AddComponent<NodeComponent>().SetParent(this); m_gradientEntity->AddComponent<GraphicsComponent>().Attach(m_gradientSprite); m_textSprite = Nz::TextSprite::New(); m_textEntity = CreateEntity(); m_textEntity->AddComponent<NodeComponent>().SetParent(this); m_textEntity->AddComponent<GraphicsComponent>().Attach(m_textSprite, 1); } void ButtonWidget::ResizeToContent() { SetContentSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths())); } void ButtonWidget::Layout() { const Nz::Vector2f& contentSize = GetContentSize(); m_gradientSprite->SetSize(contentSize); Nz::Boxf textBox = m_textEntity->GetComponent<GraphicsComponent>().GetBoundingVolume().aabb; m_textEntity->GetComponent<NodeComponent>().SetPosition(contentSize.x / 2 - textBox.width / 2, contentSize.y / 2 - textBox.height / 2); } } <|endoftext|>
<commit_before>#include "PlayerState.h" #include "BuildingCard.h" #include <string> void PlayerState::Render(shared_ptr<Player> &player, std::string character) { player->GetClient()->writeline("You are the: " + character); player->GetClient()->writeline("Gold: " + std::to_string(player->GetGoldAmount())); shared_ptr<CardStack<BuildingCard>> buildings = player->GetBuildings(); player->GetClient()->writeline("\r\nBuildings:"); for (size_t i = 0, blen = buildings->Size(); i < blen; ++i) { std::string name = buildings->ShowCardByIndex(i).GetName(); std::string color = std::to_string(buildings->ShowCardByIndex(i).GetColor()); std::string value = std::to_string(buildings->ShowCardByIndex(i).GetValue()); player->GetClient()->writeline(" - " + name + "(" + color + "," + value + ")"); } shared_ptr<CardStack<BuildingCard>> buildingCards = player->GetBuildingCards(); player->GetClient()->writeline("\r\nCards in hand:"); for (size_t i = 0, blen = buildingCards->Size(); i < blen; ++i) { std::string name = buildingCards->ShowCardByIndex(i).GetName(); std::string color = std::to_string(buildingCards->ShowCardByIndex(i).GetColor()); std::string value = std::to_string(buildingCards->ShowCardByIndex(i).GetValue()); player->GetClient()->writeline(" - " + name + "(" + color + "," + value + ")"); } } void PlayerState::RenderChoices(shared_ptr<Player> &player) { player->GetClient()->writeline("\r\nMake your choice:"); player->GetClient()->writeline(" [0] Show opponent buildings and gold"); player->GetClient()->writeline(" [1] Take 2 gold pieces"); player->GetClient()->writeline(" [2] Take 2 building cards and put 1 away"); player->GetClient()->writeline(" [3] Use character ability"); player->GetClient()->writeline(" [4] End turn"); } int PlayerState::HandleChoice(shared_ptr<Player> &player, shared_ptr<Game> &game, int range) { // Wait for command callback while (!game->HasNextCommand(player)) {} // Get next command for current player ClientCommand command = game->GetNextCommand(player); char choice[] = "X"; choice[0] = command.get_cmd().back(); int index = std::atoi(choice) > 0 ? std::atoi(choice) : 0; if (index < 0 || index > range) { // Invalid index entered return -1; } else { return index; } } void PlayerState::HandleTurn(shared_ptr<Player> &player, shared_ptr<Game> &game, int choice) { switch (choice) { case 0: // Look at opponent cards LookAtOpponent(player, game); break; case 1: // Take 2 gold TakeGold(player, game, 2); break; case 2: // Take 2 building cards TakeBuildingCards(player, game, 2); break; case 3: // Use ability UseAbility(player, game); break; default: break; } } void PlayerState::LookAtOpponent(shared_ptr<Player> &player, shared_ptr<Game> &game) { // Determine opponent shared_ptr<Player> opponent; if (game->GetPlayers()->front() == player) opponent = game->GetPlayers()->back; else opponent = game->GetPlayers()->front; player->GetClient()->writeline("Opponent:"); player->GetClient()->writeline("Gold: " + std::to_string(opponent->GetGoldAmount())); shared_ptr<CardStack<BuildingCard>> buildings = opponent->GetBuildings(); player->GetClient()->writeline("\r\nBuildings:"); for (size_t i = 0, blen = buildings->Size(); i < blen; ++i) { std::string name = buildings->ShowCardByIndex(i).GetName(); std::string color = std::to_string(buildings->ShowCardByIndex(i).GetColor()); std::string value = std::to_string(buildings->ShowCardByIndex(i).GetValue()); player->GetClient()->writeline(" - " + name + "(" + color + "," + value + ")"); } } void PlayerState::TakeGold(shared_ptr<Player> &player, shared_ptr<Game> &game, int amount) { int gold = game->RemoveGold(amount); if (gold != -1) { player->AddGold(gold); player->GetClient()->writeline("You received " + std::to_string(gold) + " gold"); } } void PlayerState::TakeBuildingCards(shared_ptr<Player> &player, shared_ptr<Game> &game, int amount) { for (int i = 0; i < amount; i++) player->AddBuildingCard(game->GetBuildingCards()->GetRandomCard()); }<commit_msg>LookAtOpponent() fix<commit_after>#include "PlayerState.h" #include "BuildingCard.h" #include <string> void PlayerState::Render(shared_ptr<Player> &player, std::string character) { player->GetClient()->writeline("You are the: " + character); player->GetClient()->writeline("Gold: " + std::to_string(player->GetGoldAmount())); shared_ptr<CardStack<BuildingCard>> buildings = player->GetBuildings(); player->GetClient()->writeline("\r\nBuildings:"); for (size_t i = 0, blen = buildings->Size(); i < blen; ++i) { std::string name = buildings->ShowCardByIndex(i).GetName(); std::string color = std::to_string(buildings->ShowCardByIndex(i).GetColor()); std::string value = std::to_string(buildings->ShowCardByIndex(i).GetValue()); player->GetClient()->writeline(" - " + name + "(" + color + "," + value + ")"); } shared_ptr<CardStack<BuildingCard>> buildingCards = player->GetBuildingCards(); player->GetClient()->writeline("\r\nCards in hand:"); for (size_t i = 0, blen = buildingCards->Size(); i < blen; ++i) { std::string name = buildingCards->ShowCardByIndex(i).GetName(); std::string color = std::to_string(buildingCards->ShowCardByIndex(i).GetColor()); std::string value = std::to_string(buildingCards->ShowCardByIndex(i).GetValue()); player->GetClient()->writeline(" - " + name + "(" + color + "," + value + ")"); } } void PlayerState::RenderChoices(shared_ptr<Player> &player) { player->GetClient()->writeline("\r\nMake your choice:"); player->GetClient()->writeline(" [0] Show opponent buildings and gold"); player->GetClient()->writeline(" [1] Take 2 gold pieces"); player->GetClient()->writeline(" [2] Take 2 building cards and put 1 away"); player->GetClient()->writeline(" [3] Use character ability"); player->GetClient()->writeline(" [4] End turn"); } int PlayerState::HandleChoice(shared_ptr<Player> &player, shared_ptr<Game> &game, int range) { // Wait for command callback while (!game->HasNextCommand(player)) {} // Get next command for current player ClientCommand command = game->GetNextCommand(player); char choice[] = "X"; choice[0] = command.get_cmd().back(); int index = std::atoi(choice) > 0 ? std::atoi(choice) : 0; if (index < 0 || index > range) { // Invalid index entered return -1; } else { return index; } } void PlayerState::HandleTurn(shared_ptr<Player> &player, shared_ptr<Game> &game, int choice) { switch (choice) { case 0: // Look at opponent cards LookAtOpponent(player, game); break; case 1: // Take 2 gold TakeGold(player, game, 2); break; case 2: // Take 2 building cards TakeBuildingCards(player, game, 2); break; case 3: // Use ability UseAbility(player, game); break; default: break; } } void PlayerState::LookAtOpponent(shared_ptr<Player> &player, shared_ptr<Game> &game) { // Determine opponent shared_ptr<Player> opponent; if (game->GetPlayers()->front() == player) opponent = game->GetPlayers()->back(); else opponent = game->GetPlayers()->front(); // Show opponent information player->GetClient()->writeline("Opponent:"); player->GetClient()->writeline("Gold: " + std::to_string(opponent->GetGoldAmount())); shared_ptr<CardStack<BuildingCard>> buildings = opponent->GetBuildings(); player->GetClient()->writeline("\r\nBuildings:"); for (size_t i = 0, blen = buildings->Size(); i < blen; ++i) { std::string name = buildings->ShowCardByIndex(i).GetName(); std::string color = std::to_string(buildings->ShowCardByIndex(i).GetColor()); std::string value = std::to_string(buildings->ShowCardByIndex(i).GetValue()); player->GetClient()->writeline(" - " + name + "(" + color + "," + value + ")"); } } void PlayerState::TakeGold(shared_ptr<Player> &player, shared_ptr<Game> &game, int amount) { int gold = game->RemoveGold(amount); if (gold != -1) { player->AddGold(gold); player->GetClient()->writeline("You received " + std::to_string(gold) + " gold"); } } void PlayerState::TakeBuildingCards(shared_ptr<Player> &player, shared_ptr<Game> &game, int amount) { for (int i = 0; i < amount; i++) player->AddBuildingCard(game->GetBuildingCards()->GetRandomCard()); }<|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/user_script_idle_scheduler.h" #include "base/message_loop.h" #include "chrome/renderer/render_view.h" namespace { // The length of time to wait after the DOM is complete to try and run user // scripts. const int kUserScriptIdleTimeoutMs = 200; } UserScriptIdleScheduler::UserScriptIdleScheduler(RenderView* view, WebKit::WebFrame* frame) : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), view_(view), frame_(frame), has_run_(false) { } void UserScriptIdleScheduler::DidFinishDocumentLoad() { MessageLoop::current()->PostDelayedTask(FROM_HERE, method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun), kUserScriptIdleTimeoutMs); } void UserScriptIdleScheduler::DidFinishLoad() { // Ensure that running scripts does not keep any progress UI running. MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun)); } void UserScriptIdleScheduler::Cancel() { view_ = NULL; frame_ = NULL; } void UserScriptIdleScheduler::MaybeRun() { if (!view_) return; DCHECK(frame_); view_->OnUserScriptIdleTriggered(frame_); Cancel(); has_run_ = true; } <commit_msg>Fix a bug where content scripts would get run twice in some cases.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/user_script_idle_scheduler.h" #include "base/message_loop.h" #include "chrome/renderer/render_view.h" namespace { // The length of time to wait after the DOM is complete to try and run user // scripts. const int kUserScriptIdleTimeoutMs = 200; } UserScriptIdleScheduler::UserScriptIdleScheduler(RenderView* view, WebKit::WebFrame* frame) : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), view_(view), frame_(frame), has_run_(false) { } void UserScriptIdleScheduler::DidFinishDocumentLoad() { MessageLoop::current()->PostDelayedTask(FROM_HERE, method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun), kUserScriptIdleTimeoutMs); } void UserScriptIdleScheduler::DidFinishLoad() { // Ensure that running scripts does not keep any progress UI running. MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun)); } void UserScriptIdleScheduler::Cancel() { view_ = NULL; frame_ = NULL; } void UserScriptIdleScheduler::MaybeRun() { if (!view_ || has_run()) return; // Note: we must set this before calling OnUserScriptIdleTriggered, because // that may result in a synchronous call back into MaybeRun if there is a // pending task currently in the queue. // http://code.google.com/p/chromium/issues/detail?id=29644 has_run_ = true; DCHECK(frame_); view_->OnUserScriptIdleTriggered(frame_); Cancel(); } <|endoftext|>
<commit_before>#include "GraphMatRuntime.cpp" #include "common.hpp" #include <limits> #include <omp.h> #include <stdint.h> #include <algorithm> #include <iostream> #ifdef GRANULA #include "granula.hpp" #endif using namespace std; typedef uint32_t depth_type; typedef depth_type msg_type; typedef depth_type reduce_type; struct vertex_value_type { public: depth_type curr; vertex_value_type() { curr = numeric_limits<depth_type>::max(); } vertex_value_type(depth_type d) { curr = d; } bool operator!= (const vertex_value_type& other) const { return !(curr == other.curr); } friend ostream& operator<< (ostream& stream, const vertex_value_type &v) { if (v.curr != numeric_limits<depth_type>::max()) { stream << v.curr; } else { stream << numeric_limits<int64_t>::max(); } return stream; } }; class BreadthFirstSearch: public GraphProgram<msg_type, reduce_type, vertex_value_type> { public: depth_type current_depth; BreadthFirstSearch() { current_depth=1; } edge_direction getOrder() const { return OUT_EDGES; } bool send_message(const vertex_value_type& vertex, msg_type& msg) const { msg = vertex.curr + 1; return (vertex.curr == current_depth-1); } void reduce_function(reduce_type& total, const reduce_type& partial) const { total = min(total, partial); } void process_message(const msg_type& msg, const int edge, const vertex_value_type& vertex, reduce_type& result) const { result = msg; } void apply(const reduce_type& msg, vertex_value_type& vertex) { if(vertex.curr == numeric_limits<depth_type>::max()) { vertex.curr = current_depth; } } void do_every_iteration(int iteration_number) { current_depth++; } }; int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); GraphPad::GB_Init(); if (argc < 3) { cerr << "usage: " << argv[0] << " <graph file> <source vertex> [output file]" << endl; return EXIT_FAILURE; } char *filename = argv[1]; int source_vertex = atoi(argv[2]); char *output = argc > 3 ? argv[3] : NULL; cout << "source vertex: " << source_vertex << endl; nthreads = omp_get_max_threads(); cout << "num. threads: " << nthreads << endl; #ifdef GRANULA granula::operation graphmatJob("GraphMat", "Id.Unique", "Job", "Id.Unique"); cout<<graphmatJob.getOperationInfo("StartTime", graphmatJob.getEpoch())<<endl; granula::operation loadGraph("GraphMat", "Id.Unique", "LoadGraph", "Id.Unique"); cout<<loadGraph.getOperationInfo("StartTime", loadGraph.getEpoch())<<endl; #endif timer_start(); timer_next("load graph"); Graph<vertex_value_type> graph; graph.ReadMTX(filename, nthreads * 4); #ifdef GRANULA cout<<loadGraph.getOperationInfo("EndTime", loadGraph.getEpoch())<<endl; #endif timer_next("initialize engine"); if (source_vertex < 0 || source_vertex >= graph.nvertices) { cerr << "ERROR: invalid source vertex (not in range [0, " << graph.nvertices-1 << "]" << endl; return EXIT_FAILURE; } graph.setAllInactive(); graph.setVertexproperty(source_vertex, vertex_value_type(0)); graph.setActive(source_vertex); BreadthFirstSearch prog; auto ctx = graph_program_init(prog, graph); #ifdef GRANULA granula::operation processGraph("GraphMat", "Id.Unique", "ProcessGraph", "Id.Unique"); cout<<processGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("run algorithm"); run_graph_program(&prog, graph, -1); #ifdef GRANULA cout<<processGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif #ifdef GRANULA granula::operation offloadGraph("GraphMat", "Id.Unique", "OffloadGraph", "Id.Unique"); cout<<offloadGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("print output"); print_graph(output, graph); #ifdef GRANULA cout<<offloadGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif timer_next("deinitialize engine"); graph_program_clear(ctx); timer_end(); #ifdef GRANULA cout<<graphmatJob.getOperationInfo("EndTime", graphmatJob.getEpoch())<<endl; #endif MPI_Finalize(); return EXIT_SUCCESS; } <commit_msg>Fix source vertex ID off by one.<commit_after>#include "GraphMatRuntime.cpp" #include "common.hpp" #include <limits> #include <omp.h> #include <stdint.h> #include <algorithm> #include <iostream> #ifdef GRANULA #include "granula.hpp" #endif using namespace std; typedef uint32_t depth_type; typedef depth_type msg_type; typedef depth_type reduce_type; struct vertex_value_type { public: depth_type curr; vertex_value_type() { curr = numeric_limits<depth_type>::max(); } vertex_value_type(depth_type d) { curr = d; } bool operator!= (const vertex_value_type& other) const { return !(curr == other.curr); } friend ostream& operator<< (ostream& stream, const vertex_value_type &v) { if (v.curr != numeric_limits<depth_type>::max()) { stream << v.curr; } else { stream << numeric_limits<int64_t>::max(); } return stream; } }; class BreadthFirstSearch: public GraphProgram<msg_type, reduce_type, vertex_value_type> { public: depth_type current_depth; BreadthFirstSearch() { current_depth=1; } edge_direction getOrder() const { return OUT_EDGES; } bool send_message(const vertex_value_type& vertex, msg_type& msg) const { msg = vertex.curr + 1; return (vertex.curr == current_depth-1); } void reduce_function(reduce_type& total, const reduce_type& partial) const { total = min(total, partial); } void process_message(const msg_type& msg, const int edge, const vertex_value_type& vertex, reduce_type& result) const { result = msg; } void apply(const reduce_type& msg, vertex_value_type& vertex) { if(vertex.curr == numeric_limits<depth_type>::max()) { vertex.curr = current_depth; } } void do_every_iteration(int iteration_number) { current_depth++; } }; int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); GraphPad::GB_Init(); if (argc < 3) { cerr << "usage: " << argv[0] << " <graph file> <source vertex> [output file]" << endl; return EXIT_FAILURE; } char *filename = argv[1]; int source_vertex = atoi(argv[2]) - 1; char *output = argc > 3 ? argv[3] : NULL; cout << "source vertex: " << source_vertex << endl; nthreads = omp_get_max_threads(); cout << "num. threads: " << nthreads << endl; #ifdef GRANULA granula::operation graphmatJob("GraphMat", "Id.Unique", "Job", "Id.Unique"); cout<<graphmatJob.getOperationInfo("StartTime", graphmatJob.getEpoch())<<endl; granula::operation loadGraph("GraphMat", "Id.Unique", "LoadGraph", "Id.Unique"); cout<<loadGraph.getOperationInfo("StartTime", loadGraph.getEpoch())<<endl; #endif timer_start(); timer_next("load graph"); Graph<vertex_value_type> graph; graph.ReadMTX(filename, nthreads * 4); #ifdef GRANULA cout<<loadGraph.getOperationInfo("EndTime", loadGraph.getEpoch())<<endl; #endif timer_next("initialize engine"); if (source_vertex < 0 || source_vertex >= graph.nvertices) { cerr << "ERROR: invalid source vertex (not in range [0, " << graph.nvertices-1 << "]" << endl; return EXIT_FAILURE; } graph.setAllInactive(); graph.setVertexproperty(source_vertex, vertex_value_type(0)); graph.setActive(source_vertex); BreadthFirstSearch prog; auto ctx = graph_program_init(prog, graph); #ifdef GRANULA granula::operation processGraph("GraphMat", "Id.Unique", "ProcessGraph", "Id.Unique"); cout<<processGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("run algorithm"); run_graph_program(&prog, graph, -1); #ifdef GRANULA cout<<processGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif #ifdef GRANULA granula::operation offloadGraph("GraphMat", "Id.Unique", "OffloadGraph", "Id.Unique"); cout<<offloadGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("print output"); print_graph(output, graph); #ifdef GRANULA cout<<offloadGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif timer_next("deinitialize engine"); graph_program_clear(ctx); timer_end(); #ifdef GRANULA cout<<graphmatJob.getOperationInfo("EndTime", graphmatJob.getEpoch())<<endl; #endif MPI_Finalize(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <BALLTestConfig.h> #include <BALL/CONCEPT/classTest.h> #include <BALL/QSAR/QSARData.h> #include <BALL/QSAR/gpModel.h> using namespace BALL; using namespace BALL::QSAR; START_TEST(GP-model, "$Id: GP_test.C$") PRECISION(1E-3) QSARData data; data.readCSVFile(BALL_TEST_DATA_PATH(Regression_test.csv),1,1,1," ",0,0); CHECK(GP-model) GPModel model(data,2,0.005); model.readTrainingData(); model.train(); const Matrix<double>* res = model.getTrainingResult(); TEST_REAL_EQUAL(res->getRowCount(),5) TEST_REAL_EQUAL((*res)[0],65.3125) TEST_REAL_EQUAL((*res)[1],307.402) TEST_REAL_EQUAL((*res)[2],-478.8941) TEST_REAL_EQUAL((*res)[3],56.16572) TEST_REAL_EQUAL((*res)[4],57.875) RESULT END_TEST <commit_msg>Fixed REAL_EQUAL => EQUAL in GPModel_test<commit_after>#include <BALLTestConfig.h> #include <BALL/CONCEPT/classTest.h> #include <BALL/QSAR/QSARData.h> #include <BALL/QSAR/gpModel.h> using namespace BALL; using namespace BALL::QSAR; START_TEST(GP-model, "$Id: GP_test.C$") PRECISION(1E-3) QSARData data; data.readCSVFile(BALL_TEST_DATA_PATH(Regression_test.csv),1,1,1," ",0,0); CHECK(GP-model) GPModel model(data,2,0.005); model.readTrainingData(); model.train(); const Matrix<double>* res = model.getTrainingResult(); TEST_EQUAL(res->getRowCount(),5) TEST_REAL_EQUAL((*res)[0],65.3125) TEST_REAL_EQUAL((*res)[1],307.402) TEST_REAL_EQUAL((*res)[2],-478.8941) TEST_REAL_EQUAL((*res)[3],56.16572) TEST_REAL_EQUAL((*res)[4],57.875) RESULT END_TEST <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Hernan Saez * 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 <organization> 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 <COPYRIGHT HOLDER> 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 "Components/PathComponent.hpp" #include "Debug/DebugDrawManager.hpp" #include "Mathematics/Matrix4_operators.hpp" #include "Mathematics/Transformation_apply.hpp" #include "Mathematics/ceil.hpp" #include "Mathematics/easing.hpp" #include "Mathematics/floor.hpp" #include "Mathematics/max.hpp" #include "Mathematics/min.hpp" #include "SceneGraph/Group.hpp" using namespace crimild; using namespace crimild::components; Transformation Path::evaluate( float time ) noexcept { auto group = getNode< Group >(); if ( !group->hasNodes() ) { return Transformation::Constants::IDENTITY; } const size_t N = group->getNodeCount() - 1; const size_t idx0 = max( size_t( 0 ), min( size_t( floor( time * N ) ), N ) ); const size_t idx1 = max( size_t( 0 ), min( size_t( ceil( time * N ) ), N ) ); const auto &t0 = group->getNodeAt( idx0 )->getWorld(); const auto &t1 = group->getNodeAt( idx1 )->getWorld(); const auto t = ( time * N ) - floor( time * N ); return Transformation { lerp( t0.mat, t1.mat, t ), lerp( t0.invMat, t1.invMat, t ), }; } void Path::renderDebugInfo( Renderer *, Camera * ) { auto group = getNode< Group >(); const auto N = group->getNodeCount(); for ( auto i = 1; i < N; i++ ) { const auto p0 = location( group->getNodeAt( i )->getWorld() ); const auto p1 = location( group->getNodeAt( i - 1 )->getWorld() ); DebugDrawManager::addLine( p0, p1, ColorRGB { 1, 0, 1 } ); } } <commit_msg>Render normals when drawing paths in debug mode<commit_after>/* * Copyright (c) 2013, Hernan Saez * 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 <organization> 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 <COPYRIGHT HOLDER> 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 "Components/PathComponent.hpp" #include "Debug/DebugDrawManager.hpp" #include "Mathematics/Matrix4_operators.hpp" #include "Mathematics/Point3Ops.hpp" #include "Mathematics/Transformation_apply.hpp" #include "Mathematics/Transformation_easing.hpp" #include "Mathematics/ceil.hpp" #include "Mathematics/easing.hpp" #include "Mathematics/floor.hpp" #include "Mathematics/max.hpp" #include "Mathematics/min.hpp" #include "SceneGraph/Group.hpp" using namespace crimild; using namespace crimild::components; Transformation Path::evaluate( float time ) noexcept { auto group = getNode< Group >(); if ( !group->hasNodes() ) { return Transformation::Constants::IDENTITY; } const size_t N = group->getNodeCount() - 1; const size_t idx0 = max( size_t( 0 ), min( size_t( floor( time * N ) ), N ) ); const size_t idx1 = max( size_t( 0 ), min( size_t( ceil( time * N ) ), N ) ); const auto &t0 = group->getNodeAt( idx0 )->getWorld(); const auto &t1 = group->getNodeAt( idx1 )->getWorld(); const auto t = ( time * N ) - floor( time * N ); return lerp( t0, t1, t ); } void Path::renderDebugInfo( Renderer *, Camera * ) { const auto dt = 0.01f; for ( auto t = 0.0f; t < 1.0f; t += dt ) { const auto T0 = evaluate( t ); const auto T1 = evaluate( t + dt ); const auto P0 = location( T0 ); DebugDrawManager::addLine( P0, location( T1 ), ColorRGB { 1, 0, 1 } ); DebugDrawManager::addLine( P0, P0 + up( T0 ), ColorRGB { 1, 1, 0 } ); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: filelist.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: jp $ $Date: 2001-09-06 13:47:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include<tools/list.hxx> #include<tools/stream.hxx> #include<tools/string.hxx> #include<tools/rtti.hxx> #include<exchange.hxx> #include<filelist.hxx> #pragma hdrstop TYPEINIT1_AUTOFACTORY( FileList, SvDataCopyStream ); // String-Liste zum Speichern der Namen deklarieren DECLARE_LIST( FileStringList, String* ); /************************************************************************* |* |* FileList - Ctor/Dtor |* \*************************************************************************/ FileList::FileList() { pStrList = new FileStringList(); } FileList::~FileList() { ClearAll(); } void FileList::ClearAll( void ) { // Strings in der Liste loeschen ULONG nCount = pStrList->Count(); for( ULONG i = 0 ; i < nCount ; i++ ) delete pStrList->GetObject( i ); // Liste loeschen delete pStrList; } /************************************************************************* |* |* FileList - Zuweisungsoperator |* \*************************************************************************/ FileList& FileList::operator=( const FileList& rFileList ) { // Liste duplizieren *pStrList = *rFileList.pStrList; // Strings in der Liste kopieren ULONG nCount = pStrList->Count(); for( ULONG i = 0 ; i < nCount ; i++ ) pStrList->Replace( new String( *rFileList.pStrList->GetObject( i ) ), i ); return *this; } /************************************************************************* |* |* FileList::GetFormatName() |* \*************************************************************************/ ULONG FileList::GetFormat() { return FORMAT_FILE_LIST; } /****************************************************************************** |* |* virtuelle SvData-Methoden |* \******************************************************************************/ void FileList::Load( SvStream& rIStm ) { rIStm >> *this; } void FileList::Save( SvStream& rOStm ) { rOStm << *this; } void FileList::Assign( const SvDataCopyStream& rCopyStream ) { *this = (const FileList&)rCopyStream; } /****************************************************************************** |* |* Stream-Operatoren |* \******************************************************************************/ // Windows-Struktur nachdefinieren // Typen entsprechend der Groesse der Original-Typen gewaehlt // In den Kommentaren sind jeweils die Original-Typen angegeben. // Hier werden immer die 32-Bit-Varianten der Typen gewaehlt, um // eine einheitliche Struktur fuer alle Plattformen zu erhalten. // Diese Struktor ist zwar nicht Win16-kompatibel, dort kann aber // die Struktur auch nicht direkt per Drag&Drop uebertragen werden. struct Sv_DROPFILES { /*DWORD = unsigned long*/ UINT32 pFiles; // offset of file list /*POINT = { long, long }*/ INT32 pt_x; // drop point INT32 pt_y; /*BOOL = int*/ INT32 fNC; /*BOOL = int*/ INT32 fWide; // wide character-flag // Konstruktor Sv_DROPFILES( void ) { pFiles = 20; // 5 x 4 Bytes, sizeof gefaehrlich wegen alignment pt_x = 0L; pt_y = 0L; fNC = FALSE; fWide = FALSE; // NOTE: Unicode not allowed for Windows 95 !! } }; // Stream-Operatoren fuer Sv_DROPFILES SvStream& operator<<( SvStream& rOStm, const Sv_DROPFILES& r ) { rOStm << r.pFiles << r.pt_x << r.pt_y << r.fNC << r.fWide; return rOStm; } SvStream& operator>>( SvStream& rIStm, Sv_DROPFILES& r ) { rIStm >> r.pFiles >> r.pt_x >> r.pt_y >> r.fNC >> r.fWide; return rIStm; } /* * NOTE: to correctly handle this Protocol with Unicode, native Win32 must be called: * e.g. DropQueryFile */ SvStream& operator<<( SvStream& rOStm, const FileList& rFileList ) { // Windows-kompatible Struktur anlegen und streamen Sv_DROPFILES aSv_DROPFILES; rOStm << aSv_DROPFILES; // String-Liste anhaengen ULONG nCount = rFileList.pStrList->Count(); for( ULONG i = 0 ; i < nCount ; i++ ) { String* pStr = rFileList.pStrList->GetObject( i ); // rOStm << pStr->GetBuffer(); rOStm << "invalid.txt"; // // Noch eine 0 anhaengen rOStm << (char)0; } // Noch eine 0 anhaengen rOStm << (char)0; return rOStm; } SvStream& operator>>( SvStream& rIStm, FileList& rFileList ) { // Windows-kompatible Struktur anlegen und aus Stream lesen Sv_DROPFILES aSv_DROPFILES; rIStm >> aSv_DROPFILES; // Bestehende Liste loeschen und neue anlegen rFileList.ClearAll(); rFileList.pStrList = new FileStringList(); // String-Liste aufbauen // Unicode ? if( aSv_DROPFILES.fWide ) { // no, only ANSI String aStr; sal_uInt16 c; // 1. Zeichen lesen rIStm >> c; do { aStr.Erase(); // String bis '\0' lesen while( c && !rIStm.IsEof() ) { aStr += (sal_Unicode)c; rIStm >> c; } // String in die Liste stopfen rFileList.AppendFile( aStr ); } while( c && !rIStm.IsEof() ); // c == 0 && cLast == 0 -> Ende } else { // no, only ANSI ByteString aStr; sal_Char c; // 1. Zeichen lesen rIStm >> c; do { aStr.Erase(); // String bis '\0' lesen while( c && !rIStm.IsEof() ) { aStr += c; rIStm >> c; } // String in die Liste stopfen rFileList.AppendFile( String(aStr, RTL_TEXTENCODING_ASCII_US)); } while( c && !rIStm.IsEof() ); // c == 0 && cLast == 0 -> Ende } return rIStm; } /****************************************************************************** |* |* Liste fuellen/abfragen |* \******************************************************************************/ void FileList::AppendFile( const String& rStr ) { pStrList->Insert( new String( rStr ) , pStrList->Count() ); } String FileList::GetFile( ULONG i ) const { String aStr; if( i < pStrList->Count() ) aStr = *pStrList->GetObject( i ); return aStr; } ULONG FileList::Count( void ) const { return pStrList->Count(); } <commit_msg>fix: #91670# read filelist from stream fixed<commit_after>/************************************************************************* * * $RCSfile: filelist.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: pb $ $Date: 2001-09-28 12:33:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include<tools/list.hxx> #include<tools/stream.hxx> #include<tools/string.hxx> #include<tools/rtti.hxx> #include<exchange.hxx> #include<filelist.hxx> #pragma hdrstop TYPEINIT1_AUTOFACTORY( FileList, SvDataCopyStream ); // String-Liste zum Speichern der Namen deklarieren DECLARE_LIST( FileStringList, String* ); /************************************************************************* |* |* FileList - Ctor/Dtor |* \*************************************************************************/ FileList::FileList() { pStrList = new FileStringList(); } FileList::~FileList() { ClearAll(); } void FileList::ClearAll( void ) { // Strings in der Liste loeschen ULONG nCount = pStrList->Count(); for( ULONG i = 0 ; i < nCount ; i++ ) delete pStrList->GetObject( i ); // Liste loeschen delete pStrList; } /************************************************************************* |* |* FileList - Zuweisungsoperator |* \*************************************************************************/ FileList& FileList::operator=( const FileList& rFileList ) { // Liste duplizieren *pStrList = *rFileList.pStrList; // Strings in der Liste kopieren ULONG nCount = pStrList->Count(); for( ULONG i = 0 ; i < nCount ; i++ ) pStrList->Replace( new String( *rFileList.pStrList->GetObject( i ) ), i ); return *this; } /************************************************************************* |* |* FileList::GetFormatName() |* \*************************************************************************/ ULONG FileList::GetFormat() { return FORMAT_FILE_LIST; } /****************************************************************************** |* |* virtuelle SvData-Methoden |* \******************************************************************************/ void FileList::Load( SvStream& rIStm ) { rIStm >> *this; } void FileList::Save( SvStream& rOStm ) { rOStm << *this; } void FileList::Assign( const SvDataCopyStream& rCopyStream ) { *this = (const FileList&)rCopyStream; } /****************************************************************************** |* |* Stream-Operatoren |* \******************************************************************************/ // Windows-Struktur nachdefinieren // Typen entsprechend der Groesse der Original-Typen gewaehlt // In den Kommentaren sind jeweils die Original-Typen angegeben. // Hier werden immer die 32-Bit-Varianten der Typen gewaehlt, um // eine einheitliche Struktur fuer alle Plattformen zu erhalten. // Diese Struktor ist zwar nicht Win16-kompatibel, dort kann aber // die Struktur auch nicht direkt per Drag&Drop uebertragen werden. struct Sv_DROPFILES { /*DWORD = unsigned long*/ UINT32 pFiles; // offset of file list /*POINT = { long, long }*/ INT32 pt_x; // drop point INT32 pt_y; /*BOOL = int*/ INT32 fNC; /*BOOL = int*/ INT32 fWide; // wide character-flag // Konstruktor Sv_DROPFILES( void ) { pFiles = 20; // 5 x 4 Bytes, sizeof gefaehrlich wegen alignment pt_x = 0L; pt_y = 0L; fNC = FALSE; fWide = FALSE; // NOTE: Unicode not allowed for Windows 95 !! } }; // Stream-Operatoren fuer Sv_DROPFILES SvStream& operator<<( SvStream& rOStm, const Sv_DROPFILES& r ) { rOStm << r.pFiles << r.pt_x << r.pt_y << r.fNC << r.fWide; return rOStm; } SvStream& operator>>( SvStream& rIStm, Sv_DROPFILES& r ) { rIStm >> r.pFiles >> r.pt_x >> r.pt_y >> r.fNC >> r.fWide; return rIStm; } /* * NOTE: to correctly handle this Protocol with Unicode, native Win32 must be called: * e.g. DropQueryFile */ SvStream& operator<<( SvStream& rOStm, const FileList& rFileList ) { // Windows-kompatible Struktur anlegen und streamen Sv_DROPFILES aSv_DROPFILES; rOStm << aSv_DROPFILES; // String-Liste anhaengen ULONG nCount = rFileList.pStrList->Count(); for( ULONG i = 0 ; i < nCount ; i++ ) { String* pStr = rFileList.pStrList->GetObject( i ); // rOStm << pStr->GetBuffer(); rOStm << "invalid.txt"; // // Noch eine 0 anhaengen rOStm << (char)0; } // Noch eine 0 anhaengen rOStm << (char)0; return rOStm; } SvStream& operator>>( SvStream& rIStm, FileList& rFileList ) { // Windows-kompatible Struktur anlegen und aus Stream lesen Sv_DROPFILES aSv_DROPFILES; rIStm >> aSv_DROPFILES; // Bestehende Liste loeschen und neue anlegen rFileList.ClearAll(); rFileList.pStrList = new FileStringList(); // String-Liste aufbauen // Unicode ? if( aSv_DROPFILES.fWide ) { // yes, Unicode String aStr; sal_uInt16 c; while( !rIStm.IsEof() ) { aStr.Erase(); // read first character of filepath; c==0 > reach end of stream rIStm >> c; if ( !c ) break; // read string till c==0 while( c && !rIStm.IsEof() ) { aStr += (sal_Unicode)c; rIStm >> c; } // append the filepath rFileList.AppendFile( aStr ); } } else { // no, only ANSI ByteString aStr; sal_Char c; while( !rIStm.IsEof() ) { aStr.Erase(); // read first character of filepath; c==0 > reach end of stream rIStm >> c; if ( !c ) break; // read string till c==0 while( c && !rIStm.IsEof() ) { aStr += c; rIStm >> c; } // append the filepath rFileList.AppendFile( String( aStr, RTL_TEXTENCODING_ASCII_US ) ); } } return rIStm; } /****************************************************************************** |* |* Liste fuellen/abfragen |* \******************************************************************************/ void FileList::AppendFile( const String& rStr ) { pStrList->Insert( new String( rStr ) , pStrList->Count() ); } String FileList::GetFile( ULONG i ) const { String aStr; if( i < pStrList->Count() ) aStr = *pStrList->GetObject( i ); return aStr; } ULONG FileList::Count( void ) const { return pStrList->Count(); } <|endoftext|>
<commit_before>/* ** Copyright 2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : [email protected] */ #include <gtest/gtest.h> #include "com/centreon/broker/compression/stream.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" using namespace com::centreon::broker; class CompressionStreamWriteMemoryStream : public io::stream { public: CompressionStreamWriteMemoryStream() : _shutdown(false) {} bool read( misc::shared_ptr<io::data>& d, time_t deadline = (time_t)-1) { (void)deadline; if (_shutdown) throw (exceptions::shutdown() << __FUNCTION__ << " is shutdown"); d = _buffer; _buffer = misc::shared_ptr<io::raw>(); return (true); } int write(misc::shared_ptr<io::data> const& d) { if (d.isNull() || (d->type() != io::raw::static_type())) throw (exceptions::msg() << "invalid data sent to " << __FUNCTION__); io::raw const& e(d.ref_as<io::raw>()); if (_buffer.isNull()) _buffer = new io::raw(e); else _buffer->append(e); return (1); } void shutdown(bool shut_it_down = true) { _shutdown = shut_it_down; return ; } private: misc::shared_ptr<io::raw> _buffer; bool _shutdown; }; class CompressionStreamWrite : public ::testing::Test { public: void SetUp() { _stream = new compression::stream(-1, 20000); _substream = new CompressionStreamWriteMemoryStream(); _stream->set_substream(_substream); return ; } misc::shared_ptr<io::data> new_data() { misc::shared_ptr<io::raw> r(new io::raw); for (int i(0); i < 1000; ++i) r->append(static_cast<char*>(static_cast<void*>(&i)), sizeof(i)); return (r); } protected: misc::shared_ptr<compression::stream> _stream; misc::shared_ptr<CompressionStreamWriteMemoryStream> _substream; }; // Given a compression stream // When write() is called // Then the return value is 1 TEST_F(CompressionStreamWrite, Returns1FirstCall) { // When int retval(_stream->write(new_data())); // Then ASSERT_EQ(retval, 1); } // Given a compression stream // When write() is called multiple times // Then the return value is always 1 TEST_F(CompressionStreamWrite, Returns1AfterMultipleCalls) { // Given for (int i(0); i < 10; ++i) { // When int retval(_stream->write(new_data())); // Then ASSERT_EQ(retval, 1); } } // Given a compression stream // And write() and read() were called multiple times // When write() is called // Then the return value is 1 TEST_F(CompressionStreamWrite, Returns1WithInterleavedRead) { // Given for (int i(0); i < 10; ++i) { for (int j(0); j < 10; ++j) _stream->write(new_data()); misc::shared_ptr<io::data> d; _stream->read(d); } // When int retval(_stream->write(new_data())); // Then ASSERT_EQ(retval, 1); } // Given a compression stream // And write() is called with a data payload // When flush() is called // Then the data written to the substream is smaller than the original size TEST_F(CompressionStreamWrite, Compress) { // Given misc::shared_ptr<io::raw> r(new_data().staticCast<io::raw>()); _stream->write(r); // When _stream->flush(); // Then misc::shared_ptr<io::data> d; _substream->read(d); ASSERT_LT(d.staticCast<io::raw>()->size(), r->size()); } // Given a compression stream // When write() is called with a buffer greater than the maximum allowed size // Then the method throws TEST_F(CompressionStreamWrite, TooMuchData) { // When misc::shared_ptr<io::raw> r(new io::raw); r->resize(compression::stream::max_data_size + 10); // Then ASSERT_THROW(_stream->write(r), exceptions::msg); } // Given a compression stream // And the substream thrown a shutdown exception during a read() call of the compression stream // When write() is called // Then it throws a shutdown exception TEST_F(CompressionStreamWrite, WriteOnShutdown) { // Given _substream->shutdown(true); misc::shared_ptr<io::data> d; ASSERT_THROW(_stream->read(d), exceptions::shutdown); // When, Then ASSERT_THROW(_stream->write(new_data()), exceptions::shutdown); } <commit_msg>core: add more compression::stream unit test.<commit_after>/* ** Copyright 2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : [email protected] */ #include <gtest/gtest.h> #include "com/centreon/broker/compression/stream.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" using namespace com::centreon::broker; class CompressionStreamWriteMemoryStream : public io::stream { public: CompressionStreamWriteMemoryStream() : _shutdown(false) {} bool read( misc::shared_ptr<io::data>& d, time_t deadline = (time_t)-1) { (void)deadline; if (_shutdown) throw (exceptions::shutdown() << __FUNCTION__ << " is shutdown"); d = _buffer; _buffer = misc::shared_ptr<io::raw>(); return (true); } int write(misc::shared_ptr<io::data> const& d) { if (d.isNull() || (d->type() != io::raw::static_type())) throw (exceptions::msg() << "invalid data sent to " << __FUNCTION__); io::raw const& e(d.ref_as<io::raw>()); if (_buffer.isNull()) _buffer = new io::raw(e); else _buffer->append(e); return (1); } void shutdown(bool shut_it_down = true) { _shutdown = shut_it_down; return ; } private: misc::shared_ptr<io::raw> _buffer; bool _shutdown; }; class CompressionStreamWrite : public ::testing::Test { public: void SetUp() { _stream = new compression::stream(-1, 20000); _substream = new CompressionStreamWriteMemoryStream(); _stream->set_substream(_substream); return ; } misc::shared_ptr<io::data> new_data() { misc::shared_ptr<io::raw> r(new io::raw); for (int i(0); i < 1000; ++i) r->append(static_cast<char*>(static_cast<void*>(&i)), sizeof(i)); return (r); } protected: misc::shared_ptr<compression::stream> _stream; misc::shared_ptr<CompressionStreamWriteMemoryStream> _substream; }; // Given a compression stream // When write() is called // Then the return value is 1 TEST_F(CompressionStreamWrite, Returns1FirstCall) { // When int retval(_stream->write(new_data())); // Then ASSERT_EQ(retval, 1); } // Given a compression stream // When write() is called multiple times // Then the return value is always 1 TEST_F(CompressionStreamWrite, Returns1AfterMultipleCalls) { // Given for (int i(0); i < 10; ++i) { // When int retval(_stream->write(new_data())); // Then ASSERT_EQ(retval, 1); } } // Given a compression stream // And write() and read() were called multiple times // When write() is called // Then the return value is 1 TEST_F(CompressionStreamWrite, Returns1WithInterleavedRead) { // Given for (int i(0); i < 10; ++i) { for (int j(0); j < 10; ++j) _stream->write(new_data()); misc::shared_ptr<io::data> d; _stream->read(d); } // When int retval(_stream->write(new_data())); // Then ASSERT_EQ(retval, 1); } // Given a compression stream // And write() is called with a data payload // When flush() is called // Then the data written to the substream is smaller than the original size TEST_F(CompressionStreamWrite, Compress) { // Given misc::shared_ptr<io::raw> r(new_data().staticCast<io::raw>()); _stream->write(r); // When _stream->flush(); // Then misc::shared_ptr<io::data> d; _substream->read(d); ASSERT_LT(d.staticCast<io::raw>()->size(), r->size()); } // Given a compression stream // When write() is called with a buffer greater than the maximum allowed size // Then the method throws TEST_F(CompressionStreamWrite, TooMuchData) { // When misc::shared_ptr<io::raw> r(new io::raw); r->resize(compression::stream::max_data_size + 10); // Then ASSERT_THROW(_stream->write(r), exceptions::msg); } // Given a compression stream // And the substream thrown a shutdown exception during a read() call of the compression stream // When write() is called // Then it throws a shutdown exception TEST_F(CompressionStreamWrite, WriteOnShutdown) { // Given _substream->shutdown(true); misc::shared_ptr<io::data> d; ASSERT_THROW(_stream->read(d), exceptions::shutdown); // When, Then ASSERT_THROW(_stream->write(new_data()), exceptions::shutdown); } // Given a compression stream // And write() was called with a data payload smaller than the buffer size // When flush() is called // Then the return value is 0 // And compressed data is written to the substream TEST_F(CompressionStreamWrite, Flush) { // Given _stream = new compression::stream(-1, 20000); _stream->set_substream(_substream); _stream->write(new_data()); misc::shared_ptr<io::data> d; _stream->read(d); ASSERT_TRUE(d.isNull()); // When int retval(_stream->flush()); // Then ASSERT_EQ(retval, 0); _stream->read(d); ASSERT_TRUE(!d.isNull()); } <|endoftext|>
<commit_before>#include "UIHandler.h" UIHandler::UIHandler() { } UIHandler::~UIHandler() { } void UIHandler::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext) { this->m_maxUIComponents = 10; this->m_nrOfUIComponents = 0; for (int i = 0; i < this->m_maxUIComponents; i++) { UIComponent* newUIComp = new UIComponent; this->m_UIComponents.push_back(newUIComp); } this->m_maxTextComponents = 10; this->m_nrOfTextComponents = 0; for (int i = 0; i < this->m_maxTextComponents; i++) { TextComponent* newTextComp = new TextComponent; this->m_textComponents.push_back(newTextComp); } this->m_spriteBatch = new DirectX::SpriteBatch(deviceContext); this->m_spriteFont = new DirectX::SpriteFont(device, L"consolas.spritefont"); DirectX::CreateWICTextureFromFile(device, L"cat.png", nullptr, &this->m_texture); this->m_UIComponents.at(0)->position = DirectX::XMFLOAT2(10.f, 10.f); this->m_UIComponents.at(0)->layerDepth = 1.f; this->m_UIComponents.at(0)->active = true; this->m_nrOfUIComponents++; this->m_UIComponents.at(1)->position = DirectX::XMFLOAT2(200.f, 100.f); this->m_UIComponents.at(1)->scale = 0.5f; this->m_UIComponents.at(1)->rotation = 2.0f; this->m_UIComponents.at(1)->layerDepth = 0.f; this->m_UIComponents.at(1)->active = true; this->m_nrOfUIComponents++; this->m_textComponents.at(0)->active = true; this->m_textComponents.at(0)->text = L"Hello"; this->m_textComponents.at(0)->layerDepth = 0.5f; this->m_nrOfTextComponents++; this->m_textComponents.at(1)->active = true; this->m_textComponents.at(1)->text = L"Darkness my old friend"; this->m_textComponents.at(1)->position = DirectX::XMFLOAT2(50.f, 85.f); this->m_textComponents.at(1)->scale = DirectX::XMFLOAT2(0.5f, 0.5f); this->m_textComponents.at(1)->layerDepth = 0.5f; this->m_nrOfTextComponents++; } void UIHandler::DrawUI() { UIComponent* tempUIComp = nullptr; TextComponent* tempTextComp = nullptr; this->m_spriteBatch->Begin(DirectX::SpriteSortMode::SpriteSortMode_BackToFront); for (int i = 0; i < this->m_nrOfUIComponents; i++) { tempUIComp = this->m_UIComponents.at(i); if (tempUIComp->active) { this->m_spriteBatch->Draw(this->m_texture, tempUIComp->position, nullptr, DirectX::Colors::White, tempUIComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempUIComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempUIComp->layerDepth); } } for (int i = 0; i < this->m_nrOfTextComponents; i++) { tempTextComp = this->m_textComponents.at(i); if (tempTextComp->active) { this->m_spriteFont->DrawString(this->m_spriteBatch, tempTextComp->text.c_str(), tempTextComp->position, DirectX::Colors::White, tempTextComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempTextComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempTextComp->layerDepth); } } this->m_spriteBatch->End(); } void UIHandler::Shutdown() { for (int i = 0; i < this->m_maxUIComponents; i++) { delete this->m_UIComponents.at(i); } for (int i = 0; i < this->m_maxTextComponents; i++) { delete this->m_textComponents.at(i); } //this->m_spriteBatch.release(); if (this->m_spriteBatch) { delete this->m_spriteBatch; this->m_spriteBatch = nullptr; } if (this->m_spriteFont) { delete this->m_spriteFont; this->m_spriteFont = nullptr; } if (this->m_texture) { this->m_texture->Release(); this->m_texture = nullptr; } } UIComponent* UIHandler::GetNextUIComponent() { if (this->m_nrOfUIComponents < this->m_maxUIComponents) { return this->m_UIComponents.at(this->m_nrOfUIComponents++); } return nullptr; } TextComponent* UIHandler::GetNextTextComponent() { if (this->m_nrOfTextComponents < this->m_maxTextComponents) { return this->m_textComponents.at(this->m_nrOfTextComponents++); } return nullptr; } void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos) { std::vector<UIComponent*>::iterator uiCompIter; for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++) { (*uiCompIter)->UpdateClicked(mousePos); } } void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos, DirectX::XMFLOAT2 windowSize) { std::vector<UIComponent*>::iterator uiCompIter; for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++) { (*uiCompIter)->UpdateClicked(mousePos, windowSize); } } <commit_msg>REMOVE test components from UIHandler<commit_after>#include "UIHandler.h" UIHandler::UIHandler() { } UIHandler::~UIHandler() { } void UIHandler::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext) { this->m_maxUIComponents = 10; this->m_nrOfUIComponents = 0; for (int i = 0; i < this->m_maxUIComponents; i++) { UIComponent* newUIComp = new UIComponent; this->m_UIComponents.push_back(newUIComp); } this->m_maxTextComponents = 10; this->m_nrOfTextComponents = 0; for (int i = 0; i < this->m_maxTextComponents; i++) { TextComponent* newTextComp = new TextComponent; this->m_textComponents.push_back(newTextComp); } this->m_spriteBatch = new DirectX::SpriteBatch(deviceContext); this->m_spriteFont = new DirectX::SpriteFont(device, L"consolas.spritefont"); DirectX::CreateWICTextureFromFile(device, L"cat.png", nullptr, &this->m_texture); } void UIHandler::DrawUI() { UIComponent* tempUIComp = nullptr; TextComponent* tempTextComp = nullptr; this->m_spriteBatch->Begin(DirectX::SpriteSortMode::SpriteSortMode_BackToFront); for (int i = 0; i < this->m_nrOfUIComponents; i++) { tempUIComp = this->m_UIComponents.at(i); if (tempUIComp->active) { this->m_spriteBatch->Draw(this->m_texture, tempUIComp->position, nullptr, DirectX::Colors::White, tempUIComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempUIComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempUIComp->layerDepth); } } for (int i = 0; i < this->m_nrOfTextComponents; i++) { tempTextComp = this->m_textComponents.at(i); if (tempTextComp->active) { this->m_spriteFont->DrawString(this->m_spriteBatch, tempTextComp->text.c_str(), tempTextComp->position, DirectX::Colors::White, tempTextComp->rotation, DirectX::XMFLOAT2(0.f, 0.f), tempTextComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempTextComp->layerDepth); } } this->m_spriteBatch->End(); } void UIHandler::Shutdown() { for (int i = 0; i < this->m_maxUIComponents; i++) { delete this->m_UIComponents.at(i); } for (int i = 0; i < this->m_maxTextComponents; i++) { delete this->m_textComponents.at(i); } //this->m_spriteBatch.release(); if (this->m_spriteBatch) { delete this->m_spriteBatch; this->m_spriteBatch = nullptr; } if (this->m_spriteFont) { delete this->m_spriteFont; this->m_spriteFont = nullptr; } if (this->m_texture) { this->m_texture->Release(); this->m_texture = nullptr; } } UIComponent* UIHandler::GetNextUIComponent() { if (this->m_nrOfUIComponents < this->m_maxUIComponents) { return this->m_UIComponents.at(this->m_nrOfUIComponents++); } return nullptr; } TextComponent* UIHandler::GetNextTextComponent() { if (this->m_nrOfTextComponents < this->m_maxTextComponents) { return this->m_textComponents.at(this->m_nrOfTextComponents++); } return nullptr; } void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos) { std::vector<UIComponent*>::iterator uiCompIter; for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++) { (*uiCompIter)->UpdateClicked(mousePos); } } void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos, DirectX::XMFLOAT2 windowSize) { std::vector<UIComponent*>::iterator uiCompIter; for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++) { (*uiCompIter)->UpdateClicked(mousePos, windowSize); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file. #include "XalanSourceTreeParserLiaison.hpp" #include <algorithm> #include <sax2/XMLReaderFactory.hpp> #include <Include/XalanAutoPtr.hpp> #include <Include/STLHelper.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include "XalanSourceTreeContentHandler.hpp" #include "XalanSourceTreeDOMSupport.hpp" #include "XalanSourceTreeDocument.hpp" // http://xml.org/sax/features/validation const XalanDOMChar XalanSourceTreeParserLiaison::validationString[] = { XalanUnicode::charLetter_h, XalanUnicode::charLetter_t, XalanUnicode::charLetter_t, XalanUnicode::charLetter_p, XalanUnicode::charColon, XalanUnicode::charSolidus, XalanUnicode::charSolidus, XalanUnicode::charLetter_x, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, XalanUnicode::charFullStop, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_g, XalanUnicode::charSolidus, XalanUnicode::charLetter_s, XalanUnicode::charLetter_a, XalanUnicode::charLetter_x, XalanUnicode::charSolidus, XalanUnicode::charLetter_f, XalanUnicode::charLetter_e, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_u, XalanUnicode::charLetter_r, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, XalanUnicode::charSolidus, XalanUnicode::charLetter_v, XalanUnicode::charLetter_a, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 }; XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison(XalanSourceTreeDOMSupport& /* theSupport */) : m_documentNumber(0), m_xercesParserLiaison(), m_documentMap(), m_persistentDocumentMap(), m_poolAllText(true) { } XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison() : m_xercesParserLiaison(), m_documentMap(), m_persistentDocumentMap(), m_poolAllText(true) { } XalanSourceTreeParserLiaison::~XalanSourceTreeParserLiaison() { reset(); #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete any persistent documents. for_each(m_persistentDocumentMap.begin(), m_persistentDocumentMap.end(), makeMapValueDeleteFunctor(m_persistentDocumentMap)); m_persistentDocumentMap.clear(); } void XalanSourceTreeParserLiaison::reset() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete any documents. for_each(m_documentMap.begin(), m_documentMap.end(), makeMapValueDeleteFunctor(m_documentMap)); m_documentMap.clear(); m_xercesParserLiaison.reset(); } ExecutionContext* XalanSourceTreeParserLiaison::getExecutionContext() const { return m_xercesParserLiaison.getExecutionContext(); } void XalanSourceTreeParserLiaison::setExecutionContext(ExecutionContext& theContext) { m_xercesParserLiaison.setExecutionContext(theContext); } void XalanSourceTreeParserLiaison::parseXMLStream( const InputSource& inputSource, DocumentHandler& handler, const XalanDOMString& identifier) { m_xercesParserLiaison.parseXMLStream(inputSource, handler, identifier); } XalanDocument* XalanSourceTreeParserLiaison::parseXMLStream( const InputSource& inputSource, const XalanDOMString& /* identifier */) { XalanSourceTreeContentHandler theContentHandler(createXalanSourceTreeDocument()); XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader()); theReader->setContentHandler(&theContentHandler); theReader->setDTDHandler(&theContentHandler); theReader->setErrorHandler(&m_xercesParserLiaison); theReader->setLexicalHandler(&theContentHandler); EntityResolver* const theResolver = getEntityResolver(); if (theResolver != 0) { theReader->setEntityResolver(theResolver); } theReader->parse(inputSource); return theContentHandler.getDocument(); } XalanDocument* XalanSourceTreeParserLiaison::createDocument() { return createXalanSourceTreeDocument(); } XalanDocument* XalanSourceTreeParserLiaison::createDOMFactory() { return m_xercesParserLiaison.createDocument(); } void XalanSourceTreeParserLiaison::destroyDocument(XalanDocument* theDocument) { if (mapDocument(theDocument) != 0) { m_documentMap.erase(theDocument); delete theDocument; } } unsigned long XalanSourceTreeParserLiaison::getDocumentNumber() { return m_documentNumber++; } int XalanSourceTreeParserLiaison::getIndent() const { return m_xercesParserLiaison.getIndent(); } void XalanSourceTreeParserLiaison::setIndent(int i) { m_xercesParserLiaison.setIndent(i); } bool XalanSourceTreeParserLiaison::getUseValidation() const { return m_xercesParserLiaison.getUseValidation(); } void XalanSourceTreeParserLiaison::setUseValidation(bool b) { m_xercesParserLiaison.setUseValidation(b); } const XalanDOMString XalanSourceTreeParserLiaison::getParserDescription() const { return XALAN_STATIC_UCODE_STRING("XalanSourceTree"); } void XalanSourceTreeParserLiaison::parseXMLStream( const InputSource& theInputSource, ContentHandler& theContentHandler, DTDHandler* theDTDHandler, LexicalHandler* theLexicalHandler, const XalanDOMString& /* theIdentifier */) { XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader()); theReader->setFeature( validationString, m_xercesParserLiaison.getUseValidation()); theReader->setContentHandler(&theContentHandler); theReader->setDTDHandler(theDTDHandler); theReader->setErrorHandler(&m_xercesParserLiaison); theReader->setLexicalHandler(theLexicalHandler); EntityResolver* const theResolver = getEntityResolver(); if (theResolver != 0) { theReader->setEntityResolver(theResolver); } theReader->parse(theInputSource); } bool XalanSourceTreeParserLiaison::getIncludeIgnorableWhitespace() const { return m_xercesParserLiaison.getIncludeIgnorableWhitespace(); } void XalanSourceTreeParserLiaison::setIncludeIgnorableWhitespace(bool include) { m_xercesParserLiaison.setIncludeIgnorableWhitespace(include); } ErrorHandler* XalanSourceTreeParserLiaison::getErrorHandler() { return m_xercesParserLiaison.getErrorHandler(); } const ErrorHandler* XalanSourceTreeParserLiaison::getErrorHandler() const { return m_xercesParserLiaison.getErrorHandler(); } void XalanSourceTreeParserLiaison::setErrorHandler(ErrorHandler* handler) { m_xercesParserLiaison.setErrorHandler(handler); } bool XalanSourceTreeParserLiaison::getDoNamespaces() const { return m_xercesParserLiaison.getDoNamespaces(); } void XalanSourceTreeParserLiaison::setDoNamespaces(bool newState) { m_xercesParserLiaison.setDoNamespaces(newState); } bool XalanSourceTreeParserLiaison::getExitOnFirstFatalError() const { return m_xercesParserLiaison.getExitOnFirstFatalError(); } void XalanSourceTreeParserLiaison::setExitOnFirstFatalError(bool newState) { m_xercesParserLiaison.setExitOnFirstFatalError(newState); } EntityResolver* XalanSourceTreeParserLiaison::getEntityResolver() { return m_xercesParserLiaison.getEntityResolver(); } void XalanSourceTreeParserLiaison::setEntityResolver(EntityResolver* resolver) { m_xercesParserLiaison.setEntityResolver(resolver); } XalanSourceTreeDocument* XalanSourceTreeParserLiaison::mapDocument(const XalanDocument* theDocument) const { DocumentMapType::const_iterator i = m_documentMap.find(theDocument); if (i != m_documentMap.end()) { return (*i).second; } else { i = m_persistentDocumentMap.find(theDocument); if (i != m_persistentDocumentMap.end()) { return (*i).second; } else { return 0; } } } XalanSourceTreeDocument* XalanSourceTreeParserLiaison::createXalanSourceTreeDocument() { XalanSourceTreeDocument* const theNewDocument = new XalanSourceTreeDocument(m_documentNumber++, m_poolAllText); m_documentMap[theNewDocument] = theNewDocument; return theNewDocument; } bool XalanSourceTreeParserLiaison::setPersistent(XalanSourceTreeDocument* theDocument) { const DocumentMapType::iterator i = m_documentMap.find(theDocument); if (i != m_documentMap.end()) { return false; } else { m_persistentDocumentMap[(*i).first] = (*i).second; m_documentMap.erase(i); return true; } } bool XalanSourceTreeParserLiaison::unsetPersistent(XalanSourceTreeDocument* theDocument) { const DocumentMapType::iterator i = m_persistentDocumentMap.find(theDocument); if (i != m_persistentDocumentMap.end()) { return false; } else { m_documentMap[(*i).first] = (*i).second; m_persistentDocumentMap.erase(i); return true; } } <commit_msg>Removed unnecessary code.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ // Class header file. #include "XalanSourceTreeParserLiaison.hpp" #include <algorithm> #include <sax2/XMLReaderFactory.hpp> #include <Include/XalanAutoPtr.hpp> #include <Include/STLHelper.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include "XalanSourceTreeContentHandler.hpp" #include "XalanSourceTreeDOMSupport.hpp" #include "XalanSourceTreeDocument.hpp" // http://xml.org/sax/features/validation const XalanDOMChar XalanSourceTreeParserLiaison::validationString[] = { XalanUnicode::charLetter_h, XalanUnicode::charLetter_t, XalanUnicode::charLetter_t, XalanUnicode::charLetter_p, XalanUnicode::charColon, XalanUnicode::charSolidus, XalanUnicode::charSolidus, XalanUnicode::charLetter_x, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, XalanUnicode::charFullStop, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_g, XalanUnicode::charSolidus, XalanUnicode::charLetter_s, XalanUnicode::charLetter_a, XalanUnicode::charLetter_x, XalanUnicode::charSolidus, XalanUnicode::charLetter_f, XalanUnicode::charLetter_e, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_u, XalanUnicode::charLetter_r, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, XalanUnicode::charSolidus, XalanUnicode::charLetter_v, XalanUnicode::charLetter_a, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 }; XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison(XalanSourceTreeDOMSupport& /* theSupport */) : m_documentNumber(0), m_xercesParserLiaison(), m_documentMap(), m_persistentDocumentMap(), m_poolAllText(true) { } XalanSourceTreeParserLiaison::XalanSourceTreeParserLiaison() : m_xercesParserLiaison(), m_documentMap(), m_persistentDocumentMap(), m_poolAllText(true) { } XalanSourceTreeParserLiaison::~XalanSourceTreeParserLiaison() { reset(); #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete any persistent documents. for_each(m_persistentDocumentMap.begin(), m_persistentDocumentMap.end(), makeMapValueDeleteFunctor(m_persistentDocumentMap)); m_persistentDocumentMap.clear(); } void XalanSourceTreeParserLiaison::reset() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Delete any documents. for_each(m_documentMap.begin(), m_documentMap.end(), makeMapValueDeleteFunctor(m_documentMap)); m_documentMap.clear(); m_xercesParserLiaison.reset(); } ExecutionContext* XalanSourceTreeParserLiaison::getExecutionContext() const { return m_xercesParserLiaison.getExecutionContext(); } void XalanSourceTreeParserLiaison::setExecutionContext(ExecutionContext& theContext) { m_xercesParserLiaison.setExecutionContext(theContext); } void XalanSourceTreeParserLiaison::parseXMLStream( const InputSource& inputSource, DocumentHandler& handler, const XalanDOMString& identifier) { m_xercesParserLiaison.parseXMLStream(inputSource, handler, identifier); } XalanDocument* XalanSourceTreeParserLiaison::parseXMLStream( const InputSource& inputSource, const XalanDOMString& /* identifier */) { XalanSourceTreeContentHandler theContentHandler(createXalanSourceTreeDocument()); XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader()); theReader->setContentHandler(&theContentHandler); theReader->setDTDHandler(&theContentHandler); theReader->setErrorHandler(&m_xercesParserLiaison); theReader->setLexicalHandler(&theContentHandler); theReader->setEntityResolver(getEntityResolver()); theReader->parse(inputSource); return theContentHandler.getDocument(); } XalanDocument* XalanSourceTreeParserLiaison::createDocument() { return createXalanSourceTreeDocument(); } XalanDocument* XalanSourceTreeParserLiaison::createDOMFactory() { return m_xercesParserLiaison.createDocument(); } void XalanSourceTreeParserLiaison::destroyDocument(XalanDocument* theDocument) { if (mapDocument(theDocument) != 0) { m_documentMap.erase(theDocument); delete theDocument; } } unsigned long XalanSourceTreeParserLiaison::getDocumentNumber() { return m_documentNumber++; } int XalanSourceTreeParserLiaison::getIndent() const { return m_xercesParserLiaison.getIndent(); } void XalanSourceTreeParserLiaison::setIndent(int i) { m_xercesParserLiaison.setIndent(i); } bool XalanSourceTreeParserLiaison::getUseValidation() const { return m_xercesParserLiaison.getUseValidation(); } void XalanSourceTreeParserLiaison::setUseValidation(bool b) { m_xercesParserLiaison.setUseValidation(b); } const XalanDOMString XalanSourceTreeParserLiaison::getParserDescription() const { return XALAN_STATIC_UCODE_STRING("XalanSourceTree"); } void XalanSourceTreeParserLiaison::parseXMLStream( const InputSource& theInputSource, ContentHandler& theContentHandler, DTDHandler* theDTDHandler, LexicalHandler* theLexicalHandler, const XalanDOMString& /* theIdentifier */) { XalanAutoPtr<SAX2XMLReader> theReader(XMLReaderFactory::createXMLReader()); theReader->setFeature( validationString, m_xercesParserLiaison.getUseValidation()); theReader->setContentHandler(&theContentHandler); theReader->setDTDHandler(theDTDHandler); theReader->setErrorHandler(&m_xercesParserLiaison); theReader->setLexicalHandler(theLexicalHandler); EntityResolver* const theResolver = getEntityResolver(); if (theResolver != 0) { theReader->setEntityResolver(theResolver); } theReader->parse(theInputSource); } bool XalanSourceTreeParserLiaison::getIncludeIgnorableWhitespace() const { return m_xercesParserLiaison.getIncludeIgnorableWhitespace(); } void XalanSourceTreeParserLiaison::setIncludeIgnorableWhitespace(bool include) { m_xercesParserLiaison.setIncludeIgnorableWhitespace(include); } ErrorHandler* XalanSourceTreeParserLiaison::getErrorHandler() { return m_xercesParserLiaison.getErrorHandler(); } const ErrorHandler* XalanSourceTreeParserLiaison::getErrorHandler() const { return m_xercesParserLiaison.getErrorHandler(); } void XalanSourceTreeParserLiaison::setErrorHandler(ErrorHandler* handler) { m_xercesParserLiaison.setErrorHandler(handler); } bool XalanSourceTreeParserLiaison::getDoNamespaces() const { return m_xercesParserLiaison.getDoNamespaces(); } void XalanSourceTreeParserLiaison::setDoNamespaces(bool newState) { m_xercesParserLiaison.setDoNamespaces(newState); } bool XalanSourceTreeParserLiaison::getExitOnFirstFatalError() const { return m_xercesParserLiaison.getExitOnFirstFatalError(); } void XalanSourceTreeParserLiaison::setExitOnFirstFatalError(bool newState) { m_xercesParserLiaison.setExitOnFirstFatalError(newState); } EntityResolver* XalanSourceTreeParserLiaison::getEntityResolver() { return m_xercesParserLiaison.getEntityResolver(); } void XalanSourceTreeParserLiaison::setEntityResolver(EntityResolver* resolver) { m_xercesParserLiaison.setEntityResolver(resolver); } XalanSourceTreeDocument* XalanSourceTreeParserLiaison::mapDocument(const XalanDocument* theDocument) const { DocumentMapType::const_iterator i = m_documentMap.find(theDocument); if (i != m_documentMap.end()) { return (*i).second; } else { i = m_persistentDocumentMap.find(theDocument); if (i != m_persistentDocumentMap.end()) { return (*i).second; } else { return 0; } } } XalanSourceTreeDocument* XalanSourceTreeParserLiaison::createXalanSourceTreeDocument() { XalanSourceTreeDocument* const theNewDocument = new XalanSourceTreeDocument(m_documentNumber++, m_poolAllText); m_documentMap[theNewDocument] = theNewDocument; return theNewDocument; } bool XalanSourceTreeParserLiaison::setPersistent(XalanSourceTreeDocument* theDocument) { const DocumentMapType::iterator i = m_documentMap.find(theDocument); if (i != m_documentMap.end()) { return false; } else { m_persistentDocumentMap[(*i).first] = (*i).second; m_documentMap.erase(i); return true; } } bool XalanSourceTreeParserLiaison::unsetPersistent(XalanSourceTreeDocument* theDocument) { const DocumentMapType::iterator i = m_persistentDocumentMap.find(theDocument); if (i != m_persistentDocumentMap.end()) { return false; } else { m_documentMap[(*i).first] = (*i).second; m_persistentDocumentMap.erase(i); return true; } } <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <limits> namespace s3d { namespace Math { inline namespace Constants { template <class T> inline constexpr T E_v = T(2.718281828459045235360287471352662498L); template <class T> inline constexpr T Log2E_v = T(1.442695040888963407359924681001892137L); template <class T> inline constexpr T Log10E_v = T(0.434294481903251827651128918916605082L); template <class T> inline constexpr T Pi_v = T(3.141592653589793238462643383279502884L); template <class T> inline constexpr T QuarterPi_v = T(0.785398163397448309615660845819875721L); template <class T> inline constexpr T OneThirdPi_v = T(1.047197551196597746154214461093167628L); template <class T> inline constexpr T HalfPi_v = T(1.570796326794896619231321691639751442L); template <class T> inline constexpr T TwoPi_v = T(6.283185307179586476925286766559005768L); template <class T> inline constexpr T InvTwoPi_v = T(0.159154943091895335768883763372514362L); template <class T> inline constexpr T InvPi_v = T(0.318309886183790671537767526745028724L); template <class T> inline constexpr T InvSqrtPi_v = T(0.564189583547756286948079451560772586L); template <class T> inline constexpr T Ln2_v = T(0.693147180559945309417232121458176568L); template <class T> inline constexpr T Ln10_v = T(2.302585092994045684017991454684364208L); template <class T> inline constexpr T Sqrt2_v = T(1.414213562373095048801688724209698078L); template <class T> inline constexpr T Sqrt3_v = T(1.732050807568877293527446341505872366L); template <class T> inline constexpr T InvSqrt2_v = T(1.570796326794896619231321691639751442L); template <class T> inline constexpr T InvSqrt3_v = T(0.577350269189625764509148780501957456L); template <class T> inline constexpr T EGamma_v = T(0.577215664901532860606512090082402431L); template <class T> inline constexpr T Phi_v = T(1.618033988749894848204586834365638117L); template <class T> inline constexpr T QNaN_v = std::numeric_limits<T>::quiet_NaN(); template <class T> inline constexpr T NaN_v = std::numeric_limits<T>::signaling_NaN(); template <class T> inline constexpr T Inf_v = std::numeric_limits<T>::infinity(); /// <summary> /// (float) π /// </summary> inline constexpr float PiF = Pi_v<float>; /// <summary> /// (float) π/4 /// </summary> inline constexpr float QuarterPiF = QuarterPi_v<float>; /// <summary> /// (float) π/3 /// </summary> inline constexpr float OneThirdPiF = OneThirdPi_v<float>; /// <summary> /// (float) π/2 /// </summary> inline constexpr float HalfPiF = HalfPi_v<float>; /// <summary> /// (float) 2 * π /// </summary> inline constexpr float TwoPiF = TwoPi_v<float>; /// <summary> /// 自然対数の底 /// Euler's number /// </summary> inline constexpr double E = E_v<double>; /// <summary> /// 2 を底とする e の対数 /// </summary> inline constexpr double Log2E = Log2E_v<double>; /// <summary> /// 10 を底とする e の対数 /// </summary> inline constexpr double Log10E = Log10E_v<double>; /// <summary> /// π /// </summary> inline constexpr double Pi = Pi_v<double>; /// <summary> /// π/4 /// </summary> inline constexpr double QuarterPi = QuarterPi_v<double>; /// <summary> /// π/3 /// </summary> inline constexpr double OneThirdPi = OneThirdPi_v<double>; /// <summary> /// π/2 /// </summary> inline constexpr double HalfPi = HalfPi_v<double>; /// <summary> /// 2 * π /// </summary> inline constexpr double TwoPi = TwoPi_v<double>; /// <summary> /// 1 / (2π) /// </summary> inline constexpr double InvTwoPi = InvTwoPi_v<double>; /// <summary> /// 1 / π /// </summary> inline constexpr double InvPi = InvPi_v<double>; /// <summary> /// 1 / √π /// </summary> inline constexpr double InvSqrtPi = InvSqrtPi_v<double>; /// <summary> /// 2 の自然対数 /// </summary> inline constexpr double Ln2 = Ln2_v<double>; /// <summary> /// 10 の自然対数 /// </summary> inline constexpr double Ln10 = Ln10_v<double>; /// <summary> /// √2 /// </summary> inline constexpr double Sqrt2 = Sqrt2_v<double>; /// <summary> /// √3 /// </summary> inline constexpr double Sqrt3 = Sqrt3_v<double>; /// <summary> /// 1 / √2 /// </summary> inline constexpr double InvSqrt2 = InvSqrt2_v<double>; /// <summary> /// 1 / √3 /// </summary> inline constexpr double InvSqrt3 = InvSqrt3_v<double>; /// <summary> /// オイラーの定数 /// </summary> inline constexpr double EGamma = EGamma_v<double>; /// <summary> /// 黄金数 (φ) /// Golden Ratio /// </summary> inline constexpr double Phi = Phi_v<double>; /// <summary> /// Quiet NaN /// </summary> inline constexpr double QNaN = QNaN_v<double>; /// <summary> /// Signaling NaN /// </summary> inline constexpr double NaN = NaN_v<double>; /// <summary> /// +Inf /// </summary> inline constexpr double Inf = Inf_v<double>; } } inline namespace Literals { inline namespace MathLiterals { [[nodiscard]] inline constexpr double operator ""_pi(long double x) { return static_cast<double>(x * Math::Constants::Pi); } [[nodiscard]] inline constexpr double operator ""_pi(unsigned long long x) { return static_cast<double>(x * Math::Constants::Pi); } [[nodiscard]] inline constexpr double operator ""_deg(long double deg) { return static_cast<double>(deg * Math::Constants::Pi / 180); } [[nodiscard]] inline constexpr double operator ""_deg(unsigned long long deg) { return static_cast<double>(deg * Math::Constants::Pi / 180); } } } } <commit_msg>fix #493<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <limits> namespace s3d { namespace Math { inline namespace Constants { template <class T> inline constexpr T E_v = T(2.718281828459045235360287471352662498L); template <class T> inline constexpr T Log2E_v = T(1.442695040888963407359924681001892137L); template <class T> inline constexpr T Log10E_v = T(0.434294481903251827651128918916605082L); template <class T> inline constexpr T Pi_v = T(3.141592653589793238462643383279502884L); template <class T> inline constexpr T QuarterPi_v = T(0.785398163397448309615660845819875721L); template <class T> inline constexpr T OneThirdPi_v = T(1.047197551196597746154214461093167628L); template <class T> inline constexpr T HalfPi_v = T(1.570796326794896619231321691639751442L); template <class T> inline constexpr T TwoPi_v = T(6.283185307179586476925286766559005768L); template <class T> inline constexpr T InvTwoPi_v = T(0.159154943091895335768883763372514362L); template <class T> inline constexpr T InvPi_v = T(0.318309886183790671537767526745028724L); template <class T> inline constexpr T InvSqrtPi_v = T(0.564189583547756286948079451560772586L); template <class T> inline constexpr T Ln2_v = T(0.693147180559945309417232121458176568L); template <class T> inline constexpr T Ln10_v = T(2.302585092994045684017991454684364208L); template <class T> inline constexpr T Sqrt2_v = T(1.414213562373095048801688724209698078L); template <class T> inline constexpr T Sqrt3_v = T(1.732050807568877293527446341505872366L); template <class T> inline constexpr T InvSqrt2_v = T(0.707106781186547524400844362104849039L); template <class T> inline constexpr T InvSqrt3_v = T(0.577350269189625764509148780501957456L); template <class T> inline constexpr T EGamma_v = T(0.577215664901532860606512090082402431L); template <class T> inline constexpr T Phi_v = T(1.618033988749894848204586834365638117L); template <class T> inline constexpr T QNaN_v = std::numeric_limits<T>::quiet_NaN(); template <class T> inline constexpr T NaN_v = std::numeric_limits<T>::signaling_NaN(); template <class T> inline constexpr T Inf_v = std::numeric_limits<T>::infinity(); /// <summary> /// (float) π /// </summary> inline constexpr float PiF = Pi_v<float>; /// <summary> /// (float) π/4 /// </summary> inline constexpr float QuarterPiF = QuarterPi_v<float>; /// <summary> /// (float) π/3 /// </summary> inline constexpr float OneThirdPiF = OneThirdPi_v<float>; /// <summary> /// (float) π/2 /// </summary> inline constexpr float HalfPiF = HalfPi_v<float>; /// <summary> /// (float) 2 * π /// </summary> inline constexpr float TwoPiF = TwoPi_v<float>; /// <summary> /// 自然対数の底 /// Euler's number /// </summary> inline constexpr double E = E_v<double>; /// <summary> /// 2 を底とする e の対数 /// </summary> inline constexpr double Log2E = Log2E_v<double>; /// <summary> /// 10 を底とする e の対数 /// </summary> inline constexpr double Log10E = Log10E_v<double>; /// <summary> /// π /// </summary> inline constexpr double Pi = Pi_v<double>; /// <summary> /// π/4 /// </summary> inline constexpr double QuarterPi = QuarterPi_v<double>; /// <summary> /// π/3 /// </summary> inline constexpr double OneThirdPi = OneThirdPi_v<double>; /// <summary> /// π/2 /// </summary> inline constexpr double HalfPi = HalfPi_v<double>; /// <summary> /// 2 * π /// </summary> inline constexpr double TwoPi = TwoPi_v<double>; /// <summary> /// 1 / (2π) /// </summary> inline constexpr double InvTwoPi = InvTwoPi_v<double>; /// <summary> /// 1 / π /// </summary> inline constexpr double InvPi = InvPi_v<double>; /// <summary> /// 1 / √π /// </summary> inline constexpr double InvSqrtPi = InvSqrtPi_v<double>; /// <summary> /// 2 の自然対数 /// </summary> inline constexpr double Ln2 = Ln2_v<double>; /// <summary> /// 10 の自然対数 /// </summary> inline constexpr double Ln10 = Ln10_v<double>; /// <summary> /// √2 /// </summary> inline constexpr double Sqrt2 = Sqrt2_v<double>; /// <summary> /// √3 /// </summary> inline constexpr double Sqrt3 = Sqrt3_v<double>; /// <summary> /// 1 / √2 /// </summary> inline constexpr double InvSqrt2 = InvSqrt2_v<double>; /// <summary> /// 1 / √3 /// </summary> inline constexpr double InvSqrt3 = InvSqrt3_v<double>; /// <summary> /// オイラーの定数 /// </summary> inline constexpr double EGamma = EGamma_v<double>; /// <summary> /// 黄金数 (φ) /// Golden Ratio /// </summary> inline constexpr double Phi = Phi_v<double>; /// <summary> /// Quiet NaN /// </summary> inline constexpr double QNaN = QNaN_v<double>; /// <summary> /// Signaling NaN /// </summary> inline constexpr double NaN = NaN_v<double>; /// <summary> /// +Inf /// </summary> inline constexpr double Inf = Inf_v<double>; } } inline namespace Literals { inline namespace MathLiterals { [[nodiscard]] inline constexpr double operator ""_pi(long double x) { return static_cast<double>(x * Math::Constants::Pi); } [[nodiscard]] inline constexpr double operator ""_pi(unsigned long long x) { return static_cast<double>(x * Math::Constants::Pi); } [[nodiscard]] inline constexpr double operator ""_deg(long double deg) { return static_cast<double>(deg * Math::Constants::Pi / 180); } [[nodiscard]] inline constexpr double operator ""_deg(unsigned long long deg) { return static_cast<double>(deg * Math::Constants::Pi / 180); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <map> #include <vector> #include "base/string_util.h" #include "build/build_config.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/pepper_devices.h" #include "chrome/renderer/webplugin_delegate_pepper.h" #include "chrome/test/render_view_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/npapi/bindings/npapi.h" #include "third_party/npapi/bindings/npruntime.h" #include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" #include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h" #include "third_party/WebKit/WebKit/chromium/public/WebRect.h" #include "webkit/glue/plugins/plugin_instance.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/webplugin_impl.h" class PepperDeviceTest; namespace { const char kTestPluginMimeType[] = "chrome-test/pepper-device-test"; // This maps the NPP instances to the test object so our C callbacks can easily // get back to the object. There will normally be only one item in this map. static std::map<NPP, PepperDeviceTest*> active_tests; NPError NPP_New(NPMIMEType plugin_type, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { // Watch out: active_tests won't contain the NPP pointer until after this // call is complete, so don't use it. return NPERR_NO_ERROR; } NPError NPP_Destroy(NPP instance, NPSavedData** saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; return NPERR_NO_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void* event) { return 0; } NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; switch (variable) { case NPPVpluginNeedsXEmbed: *static_cast<NPBool*>(value) = 1; return NPERR_NO_ERROR; default: return NPERR_INVALID_PARAM; } } NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) { return NPERR_NO_ERROR; } NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) { plugin_funcs->newp = NPP_New; plugin_funcs->destroy = NPP_Destroy; plugin_funcs->setwindow = NPP_SetWindow; plugin_funcs->event = NPP_HandleEvent; plugin_funcs->getvalue = NPP_GetValue; plugin_funcs->setvalue = NPP_SetValue; return NPERR_NO_ERROR; } #if defined(OS_MACOSX) || defined(OS_WIN) NPError API_CALL NP_Initialize(NPNetscapeFuncs* browser_funcs) { return NPERR_NO_ERROR; } #else NPError API_CALL NP_Initialize(NPNetscapeFuncs* browser_funcs, NPPluginFuncs* plugin_funcs) { NP_GetEntryPoints(plugin_funcs); return NPERR_NO_ERROR; } #endif NPError API_CALL NP_Shutdown() { return NPERR_NO_ERROR; } } // namespace // PepperDeviceTest ------------------------------------------------------------ class PepperDeviceTest : public RenderViewTest { public: PepperDeviceTest(); ~PepperDeviceTest(); const FilePath& plugin_path() const { return version_info_.path; } WebPluginDelegatePepper* pepper_plugin() const { return pepper_plugin_; } NPP npp() const { return pepper_plugin_->instance()->npp(); } protected: // Logs that the given flush command was called in flush_calls. static void FlushCalled(NPP instance, NPDeviceContext* context, NPError err, NPUserData* user_data); // A log of flush commands we can use to check the async callbacks. struct FlushData { NPP instance; NPDeviceContext* context; NPError err; NPUserData* user_data; }; std::vector<FlushData> flush_calls_; private: // testing::Test implementation. virtual void SetUp(); virtual void TearDown(); NPAPI::PluginVersionInfo version_info_; scoped_ptr<webkit_glue::WebPluginImpl> plugin_; WebPluginDelegatePepper* pepper_plugin_; // FIXME(brettw): check lifetime. }; PepperDeviceTest::PepperDeviceTest() { version_info_.path = FilePath(FILE_PATH_LITERAL("pepper-device-tester")); version_info_.product_name = ASCIIToWide("Pepper device test plugin"); version_info_.file_description = ASCIIToWide("Pepper device test plugin"); version_info_.file_version = ASCIIToWide("1"); version_info_.mime_types = ASCIIToWide(kTestPluginMimeType); NPAPI::PluginEntryPoints entry_points = { #if !defined(OS_POSIX) || defined(OS_MACOSX) NP_GetEntryPoints, #endif NP_Initialize, NP_Shutdown }; version_info_.entry_points = entry_points; } PepperDeviceTest::~PepperDeviceTest() { } void PepperDeviceTest::SetUp() { RenderViewTest::SetUp(); NPAPI::PluginList::Singleton()->RegisterInternalPlugin(version_info_); // Create the WebKit plugin with no delegates (this seems to work // sufficiently for the test). WebKit::WebPluginParams params; plugin_.reset(new webkit_glue::WebPluginImpl( NULL, params, base::WeakPtr<webkit_glue::WebPluginPageDelegate>())); // Create a pepper plugin for the RenderView. pepper_plugin_ = WebPluginDelegatePepper::Create( plugin_path(), kTestPluginMimeType, view_->AsWeakPtr()); ASSERT_TRUE(pepper_plugin_); ASSERT_TRUE(pepper_plugin_->Initialize(GURL(), std::vector<std::string>(), std::vector<std::string>(), plugin_.get(), false)); // Normally the RenderView creates the pepper plugin and registers it with // its internal list. Since we're creating it manually, we have to reach in // and register it to prevent tear-down from asserting. view_->current_pepper_plugins_.insert(pepper_plugin_); active_tests[npp()] = this; // Need to specify a window size or graphics calls will fail on the 0x0 // bitmap. gfx::Rect rect(0, 0, 100, 100); view_->OnResize(rect.size(), gfx::Rect()); pepper_plugin_->UpdateGeometry(rect, rect); } void PepperDeviceTest::TearDown() { active_tests.erase(active_tests.find(npp())); plugin_.reset(); if (pepper_plugin_) pepper_plugin_->PluginDestroyed(); NPAPI::PluginList::Singleton()->UnregisterInternalPlugin(version_info_.path); RenderViewTest::TearDown(); } // static void PepperDeviceTest::FlushCalled(NPP instance, NPDeviceContext* context, NPError err, NPUserData* user_data) { if (active_tests.find(instance) == active_tests.end()) return; PepperDeviceTest* that = active_tests[instance]; FlushData flush_data; flush_data.instance = instance; flush_data.context = context; flush_data.err = err; flush_data.user_data = user_data; that->flush_calls_.push_back(flush_data); } // ----------------------------------------------------------------------------- TEST_F(PepperDeviceTest, Flush) { // Create a 2D device. NPDeviceContext2DConfig config; NPDeviceContext2D context; EXPECT_EQ(NPERR_NO_ERROR, pepper_plugin()->Device2DInitializeContext(&config, &context)); // Flush the bitmap. Here we fake the invalidate call to the RenderView since // there isn't an actual visible web page that would otherwise get painted. // The callback should not get called synchronously. pepper_plugin()->Device2DFlushContext(npp(), &context, &FlushCalled, NULL); view_->didInvalidateRect(WebKit::WebRect(0, 0, 100, 100)); EXPECT_TRUE(flush_calls_.empty()); // Run the message loop which should process the pending paints, there should // still be no callbacks since the stuff hasn't been copied to the screen, // but there should be a paint message sent to the browser. MessageLoop::current()->RunAllPending(); EXPECT_TRUE(flush_calls_.empty()); EXPECT_TRUE(render_thread_.sink().GetFirstMessageMatching( ViewHostMsg_UpdateRect::ID)); // Send a paint ACK, this should trigger the callback. view_->OnMessageReceived(ViewMsg_UpdateRect_ACK(view_->routing_id())); EXPECT_EQ(1u, flush_calls_.size()); } <commit_msg>Fix bustage from pepper flush fix by commenting out the new test on Mac.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <map> #include <vector> #include "base/string_util.h" #include "build/build_config.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/pepper_devices.h" #include "chrome/renderer/webplugin_delegate_pepper.h" #include "chrome/test/render_view_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/npapi/bindings/npapi.h" #include "third_party/npapi/bindings/npruntime.h" #include "third_party/WebKit/WebKit/chromium/public/WebPlugin.h" #include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h" #include "third_party/WebKit/WebKit/chromium/public/WebRect.h" #include "webkit/glue/plugins/plugin_instance.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/webplugin_impl.h" class PepperDeviceTest; namespace { const char kTestPluginMimeType[] = "chrome-test/pepper-device-test"; // This maps the NPP instances to the test object so our C callbacks can easily // get back to the object. There will normally be only one item in this map. static std::map<NPP, PepperDeviceTest*> active_tests; NPError NPP_New(NPMIMEType plugin_type, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { // Watch out: active_tests won't contain the NPP pointer until after this // call is complete, so don't use it. return NPERR_NO_ERROR; } NPError NPP_Destroy(NPP instance, NPSavedData** saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; return NPERR_NO_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void* event) { return 0; } NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; switch (variable) { case NPPVpluginNeedsXEmbed: *static_cast<NPBool*>(value) = 1; return NPERR_NO_ERROR; default: return NPERR_INVALID_PARAM; } } NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) { return NPERR_NO_ERROR; } NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) { plugin_funcs->newp = NPP_New; plugin_funcs->destroy = NPP_Destroy; plugin_funcs->setwindow = NPP_SetWindow; plugin_funcs->event = NPP_HandleEvent; plugin_funcs->getvalue = NPP_GetValue; plugin_funcs->setvalue = NPP_SetValue; return NPERR_NO_ERROR; } #if defined(OS_MACOSX) || defined(OS_WIN) NPError API_CALL NP_Initialize(NPNetscapeFuncs* browser_funcs) { return NPERR_NO_ERROR; } #else NPError API_CALL NP_Initialize(NPNetscapeFuncs* browser_funcs, NPPluginFuncs* plugin_funcs) { NP_GetEntryPoints(plugin_funcs); return NPERR_NO_ERROR; } #endif NPError API_CALL NP_Shutdown() { return NPERR_NO_ERROR; } } // namespace // PepperDeviceTest ------------------------------------------------------------ class PepperDeviceTest : public RenderViewTest { public: PepperDeviceTest(); ~PepperDeviceTest(); const FilePath& plugin_path() const { return version_info_.path; } WebPluginDelegatePepper* pepper_plugin() const { return pepper_plugin_; } NPP npp() const { return pepper_plugin_->instance()->npp(); } protected: // Logs that the given flush command was called in flush_calls. static void FlushCalled(NPP instance, NPDeviceContext* context, NPError err, NPUserData* user_data); // A log of flush commands we can use to check the async callbacks. struct FlushData { NPP instance; NPDeviceContext* context; NPError err; NPUserData* user_data; }; std::vector<FlushData> flush_calls_; private: // testing::Test implementation. virtual void SetUp(); virtual void TearDown(); NPAPI::PluginVersionInfo version_info_; scoped_ptr<webkit_glue::WebPluginImpl> plugin_; WebPluginDelegatePepper* pepper_plugin_; // FIXME(brettw): check lifetime. }; PepperDeviceTest::PepperDeviceTest() { version_info_.path = FilePath(FILE_PATH_LITERAL("pepper-device-tester")); version_info_.product_name = ASCIIToWide("Pepper device test plugin"); version_info_.file_description = ASCIIToWide("Pepper device test plugin"); version_info_.file_version = ASCIIToWide("1"); version_info_.mime_types = ASCIIToWide(kTestPluginMimeType); NPAPI::PluginEntryPoints entry_points = { #if !defined(OS_POSIX) || defined(OS_MACOSX) NP_GetEntryPoints, #endif NP_Initialize, NP_Shutdown }; version_info_.entry_points = entry_points; } PepperDeviceTest::~PepperDeviceTest() { } void PepperDeviceTest::SetUp() { RenderViewTest::SetUp(); NPAPI::PluginList::Singleton()->RegisterInternalPlugin(version_info_); // Create the WebKit plugin with no delegates (this seems to work // sufficiently for the test). WebKit::WebPluginParams params; plugin_.reset(new webkit_glue::WebPluginImpl( NULL, params, base::WeakPtr<webkit_glue::WebPluginPageDelegate>())); // Create a pepper plugin for the RenderView. pepper_plugin_ = WebPluginDelegatePepper::Create( plugin_path(), kTestPluginMimeType, view_->AsWeakPtr()); ASSERT_TRUE(pepper_plugin_); ASSERT_TRUE(pepper_plugin_->Initialize(GURL(), std::vector<std::string>(), std::vector<std::string>(), plugin_.get(), false)); // Normally the RenderView creates the pepper plugin and registers it with // its internal list. Since we're creating it manually, we have to reach in // and register it to prevent tear-down from asserting. view_->current_pepper_plugins_.insert(pepper_plugin_); active_tests[npp()] = this; // Need to specify a window size or graphics calls will fail on the 0x0 // bitmap. gfx::Rect rect(0, 0, 100, 100); view_->OnResize(rect.size(), gfx::Rect()); pepper_plugin_->UpdateGeometry(rect, rect); } void PepperDeviceTest::TearDown() { active_tests.erase(active_tests.find(npp())); plugin_.reset(); if (pepper_plugin_) pepper_plugin_->PluginDestroyed(); NPAPI::PluginList::Singleton()->UnregisterInternalPlugin(version_info_.path); RenderViewTest::TearDown(); } // static void PepperDeviceTest::FlushCalled(NPP instance, NPDeviceContext* context, NPError err, NPUserData* user_data) { if (active_tests.find(instance) == active_tests.end()) return; PepperDeviceTest* that = active_tests[instance]; FlushData flush_data; flush_data.instance = instance; flush_data.context = context; flush_data.err = err; flush_data.user_data = user_data; that->flush_calls_.push_back(flush_data); } // ----------------------------------------------------------------------------- // TODO(brettw) this crashes on Mac. Figure out why and enable. #if !defined(OS_MACOSX) TEST_F(PepperDeviceTest, Flush) { // Create a 2D device. NPDeviceContext2DConfig config; NPDeviceContext2D context; EXPECT_EQ(NPERR_NO_ERROR, pepper_plugin()->Device2DInitializeContext(&config, &context)); // Flush the bitmap. Here we fake the invalidate call to the RenderView since // there isn't an actual visible web page that would otherwise get painted. // The callback should not get called synchronously. pepper_plugin()->Device2DFlushContext(npp(), &context, &FlushCalled, NULL); view_->didInvalidateRect(WebKit::WebRect(0, 0, 100, 100)); EXPECT_TRUE(flush_calls_.empty()); // Run the message loop which should process the pending paints, there should // still be no callbacks since the stuff hasn't been copied to the screen, // but there should be a paint message sent to the browser. MessageLoop::current()->RunAllPending(); EXPECT_TRUE(flush_calls_.empty()); EXPECT_TRUE(render_thread_.sink().GetFirstMessageMatching( ViewHostMsg_UpdateRect::ID)); // Send a paint ACK, this should trigger the callback. view_->OnMessageReceived(ViewMsg_UpdateRect_ACK(view_->routing_id())); EXPECT_EQ(1u, flush_calls_.size()); } #endif <|endoftext|>
<commit_before>#include "OccTest.hpp" #include <MechanicsFwd.hpp> #include "OccContactShape.hpp" #include <TopoDS_Shape.hxx> #include <BRepPrimAPI_MakeSphere.hxx> #include <BRepTools.hxx> void OccTest::setUp() { } void OccTest::tearDown() { } void OccTest::t1() { BRepPrimAPI_MakeSphere mksphere(1.0); OccContactShape sphere(mksphere.Shape()); std::string s1 = sphere.exportBRepAsString(); std::stringstream out; BRepTools::Write(mksphere.Shape(), out); CPPUNIT_ASSERT(out.str() == s1); } void OccTest::t2() { } <commit_msg>[Mechanics] OccTest fix tests discovery + add computeUVBound test<commit_after>#include "OccTest.hpp" #include <MechanicsFwd.hpp> #include "OccContactShape.hpp" #include <TopoDS_Shape.hxx> #include <BRepPrimAPI_MakeSphere.hxx> #include <BRepTools.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <cmath> CPPUNIT_TEST_SUITE_REGISTRATION(OccTest); void OccTest::setUp() { } void OccTest::tearDown() { } void OccTest::t1() { BRepPrimAPI_MakeSphere mksphere(1.0); OccContactShape sphere(mksphere.Shape()); std::string s1 = sphere.exportBRepAsString(); std::stringstream out; BRepTools::Write(mksphere.Shape(), out); CPPUNIT_ASSERT(out.str() == s1); } void OccTest::t2() { BRepPrimAPI_MakeSphere mksphere(1.0); TopExp_Explorer exp; exp.Init(mksphere.Shape(), TopAbs_SHELL); TopoDS_Shell shell = TopoDS::Shell(exp.Current().Composed(mksphere.Shape().Orientation())); exp.Init(shell, TopAbs_FACE); TopoDS_Face face = TopoDS::Face(exp.Current().Composed(shell.Orientation())); OccContactShape sphere(face); sphere.computeUVBounds(); CPPUNIT_ASSERT(std::abs(sphere.bsup1[0] - 6.28319) < 1e-4); CPPUNIT_ASSERT(std::abs(sphere.bsup1[1] - 1.5708) < 1e-4); CPPUNIT_ASSERT(std::abs(sphere.binf1[0] - 0.) < 1e-4); CPPUNIT_ASSERT(std::abs(sphere.binf1[1] + 1.5708) < 1e-4); std::cout << sphere.bsup1[0] << "," << sphere.bsup1[1] << std::endl; std::cout << sphere.binf1[0] << "," << sphere.binf1[1] << std::endl; } <|endoftext|>
<commit_before>// // ClockReceiver.hpp // Clock Signal // // Created by Thomas Harte on 22/07/2017. // Copyright 2017 Thomas Harte. All rights reserved. // #ifndef ClockReceiver_hpp #define ClockReceiver_hpp /* Informal pattern for all classes that run from a clock cycle: Each will implement either or both of run_for(Cycles) and run_for(HalfCycles), as is appropriate. Callers that are accumulating HalfCycles but want to talk to receivers that implement only run_for(Cycles) can use HalfCycle.flush_cycles if they have appropriate storage, or can wrap the receiver in HalfClockReceiver in order automatically to bind half-cycle storage to it. Alignment rule: run_for(Cycles) may be called only after an even number of half cycles. E.g. the following sequence will have undefined results: run_for(HalfCycles(1)) run_for(Cycles(1)) An easy way to ensure this as a caller is to pick only one of run_for(Cycles) and run_for(HalfCycles) to use. Reasoning: Users of this template may with to implement run_for(Cycles) and run_for(HalfCycles) where there is a need to implement at half-cycle precision but a faster execution path can be offered for full-cycle precision. Those users are permitted to assume phase in run_for(Cycles) and should do so to be compatible with callers that use only run_for(Cycles). Corollary: Starting from nothing, the first run_for(HalfCycles(1)) will do the **first** half of a full cycle. The second will do the second half. Etc. */ /*! Provides a class that wraps a plain int, providing most of the basic arithmetic and Boolean operators, but forcing callers and receivers to be explicit as to usage. */ template <class T> class WrappedInt { public: constexpr WrappedInt(int l) : length_(l) {} constexpr WrappedInt() : length_(0) {} constexpr T &operator =(const T &rhs) { length_ = rhs.length_; return *this; } constexpr T &operator +=(const T &rhs) { length_ += rhs.length_; return *static_cast<T *>(this); } constexpr T &operator -=(const T &rhs) { length_ -= rhs.length_; return *static_cast<T *>(this); } T &operator ++() { ++ length_; return *static_cast<T *>(this); } T &operator ++(int) { length_ ++; return *static_cast<T *>(this); } T &operator --() { -- length_; return *static_cast<T *>(this); } T &operator --(int) { length_ --; return *static_cast<T *>(this); } T &operator %=(const T &rhs) { length_ %= rhs.length_; return *static_cast<T *>(this); } T &operator &=(const T &rhs) { length_ &= rhs.length_; return *static_cast<T *>(this); } constexpr T operator +(const T &rhs) const { return T(length_ + rhs.length_); } constexpr T operator -(const T &rhs) const { return T(length_ - rhs.length_); } constexpr T operator %(const T &rhs) const { return T(length_ % rhs.length_); } constexpr T operator &(const T &rhs) const { return T(length_ & rhs.length_); } constexpr T operator -() const { return T(- length_); } constexpr bool operator <(const T &rhs) const { return length_ < rhs.length_; } constexpr bool operator >(const T &rhs) const { return length_ > rhs.length_; } constexpr bool operator <=(const T &rhs) const { return length_ <= rhs.length_; } constexpr bool operator >=(const T &rhs) const { return length_ >= rhs.length_; } constexpr bool operator ==(const T &rhs) const { return length_ == rhs.length_; } constexpr bool operator !=(const T &rhs) const { return length_ != rhs.length_; } constexpr bool operator !() const { return !length_; } // bool operator () is not supported because it offers an implicit cast to int, which is prone silently to permit misuse constexpr int as_int() const { return length_; } /*! Severs from @c this the effect of dividing by @c divisor; @c this will end up with the value of @c this modulo @c divisor and @c divided by @c divisor is returned. */ T divide(const T &divisor) { T result(length_ / divisor.length_); length_ %= divisor.length_; return result; } /*! Flushes the value in @c this. The current value is returned, and the internal value is reset to zero. */ T flush() { T result(length_); length_ = 0; return result; } // operator int() is deliberately not provided, to avoid accidental subtitution of // classes that use this template. protected: int length_; }; /// Describes an integer number of whole cycles: pairs of clock signal transitions. class Cycles: public WrappedInt<Cycles> { public: constexpr Cycles(int l) : WrappedInt<Cycles>(l) {} constexpr Cycles() : WrappedInt<Cycles>() {} constexpr Cycles(const Cycles &cycles) : WrappedInt<Cycles>(cycles.length_) {} }; /// Describes an integer number of half cycles: single clock signal transitions. class HalfCycles: public WrappedInt<HalfCycles> { public: constexpr HalfCycles(int l) : WrappedInt<HalfCycles>(l) {} constexpr HalfCycles() : WrappedInt<HalfCycles>() {} constexpr HalfCycles(const Cycles cycles) : WrappedInt<HalfCycles>(cycles.as_int() * 2) {} constexpr HalfCycles(const HalfCycles &half_cycles) : WrappedInt<HalfCycles>(half_cycles.length_) {} /// @returns The number of whole cycles completely covered by this span of half cycles. constexpr Cycles cycles() { return Cycles(length_ >> 1); } /// Flushes the whole cycles in @c this, subtracting that many from the total stored here. Cycles flush_cycles() { Cycles result(length_ >> 1); length_ &= 1; return result; } /// Flushes the half cycles in @c this, returning the number stored and setting this total to zero. HalfCycles flush() { HalfCycles result(length_); length_ = 0; return result; } /*! Severs from @c this the effect of dividing by @c divisor; @c this will end up with the value of @c this modulo @c divisor and @c divided by @c divisor is returned. */ Cycles divide_cycles(const Cycles &divisor) { HalfCycles half_divisor = HalfCycles(divisor); Cycles result(length_ / half_divisor.length_); length_ %= half_divisor.length_; return result; } }; /*! If a component implements only run_for(Cycles), an owner can wrap it in HalfClockReceiver automatically to gain run_for(HalfCycles). */ template <class T> class HalfClockReceiver: public T { public: using T::T; inline void run_for(const HalfCycles half_cycles) { half_cycles_ += half_cycles; T::run_for(half_cycles_.flush_cycles()); } private: HalfCycles half_cycles_; }; #endif /* ClockReceiver_hpp */ <commit_msg>Strips further improper `constexpr`s.<commit_after>// // ClockReceiver.hpp // Clock Signal // // Created by Thomas Harte on 22/07/2017. // Copyright 2017 Thomas Harte. All rights reserved. // #ifndef ClockReceiver_hpp #define ClockReceiver_hpp /* Informal pattern for all classes that run from a clock cycle: Each will implement either or both of run_for(Cycles) and run_for(HalfCycles), as is appropriate. Callers that are accumulating HalfCycles but want to talk to receivers that implement only run_for(Cycles) can use HalfCycle.flush_cycles if they have appropriate storage, or can wrap the receiver in HalfClockReceiver in order automatically to bind half-cycle storage to it. Alignment rule: run_for(Cycles) may be called only after an even number of half cycles. E.g. the following sequence will have undefined results: run_for(HalfCycles(1)) run_for(Cycles(1)) An easy way to ensure this as a caller is to pick only one of run_for(Cycles) and run_for(HalfCycles) to use. Reasoning: Users of this template may with to implement run_for(Cycles) and run_for(HalfCycles) where there is a need to implement at half-cycle precision but a faster execution path can be offered for full-cycle precision. Those users are permitted to assume phase in run_for(Cycles) and should do so to be compatible with callers that use only run_for(Cycles). Corollary: Starting from nothing, the first run_for(HalfCycles(1)) will do the **first** half of a full cycle. The second will do the second half. Etc. */ /*! Provides a class that wraps a plain int, providing most of the basic arithmetic and Boolean operators, but forcing callers and receivers to be explicit as to usage. */ template <class T> class WrappedInt { public: constexpr WrappedInt(int l) : length_(l) {} constexpr WrappedInt() : length_(0) {} T &operator =(const T &rhs) { length_ = rhs.length_; return *this; } T &operator +=(const T &rhs) { length_ += rhs.length_; return *static_cast<T *>(this); } T &operator -=(const T &rhs) { length_ -= rhs.length_; return *static_cast<T *>(this); } T &operator ++() { ++ length_; return *static_cast<T *>(this); } T &operator ++(int) { length_ ++; return *static_cast<T *>(this); } T &operator --() { -- length_; return *static_cast<T *>(this); } T &operator --(int) { length_ --; return *static_cast<T *>(this); } T &operator %=(const T &rhs) { length_ %= rhs.length_; return *static_cast<T *>(this); } T &operator &=(const T &rhs) { length_ &= rhs.length_; return *static_cast<T *>(this); } constexpr T operator +(const T &rhs) const { return T(length_ + rhs.length_); } constexpr T operator -(const T &rhs) const { return T(length_ - rhs.length_); } constexpr T operator %(const T &rhs) const { return T(length_ % rhs.length_); } constexpr T operator &(const T &rhs) const { return T(length_ & rhs.length_); } constexpr T operator -() const { return T(- length_); } constexpr bool operator <(const T &rhs) const { return length_ < rhs.length_; } constexpr bool operator >(const T &rhs) const { return length_ > rhs.length_; } constexpr bool operator <=(const T &rhs) const { return length_ <= rhs.length_; } constexpr bool operator >=(const T &rhs) const { return length_ >= rhs.length_; } constexpr bool operator ==(const T &rhs) const { return length_ == rhs.length_; } constexpr bool operator !=(const T &rhs) const { return length_ != rhs.length_; } constexpr bool operator !() const { return !length_; } // bool operator () is not supported because it offers an implicit cast to int, which is prone silently to permit misuse constexpr int as_int() const { return length_; } /*! Severs from @c this the effect of dividing by @c divisor; @c this will end up with the value of @c this modulo @c divisor and @c divided by @c divisor is returned. */ T divide(const T &divisor) { T result(length_ / divisor.length_); length_ %= divisor.length_; return result; } /*! Flushes the value in @c this. The current value is returned, and the internal value is reset to zero. */ T flush() { T result(length_); length_ = 0; return result; } // operator int() is deliberately not provided, to avoid accidental subtitution of // classes that use this template. protected: int length_; }; /// Describes an integer number of whole cycles: pairs of clock signal transitions. class Cycles: public WrappedInt<Cycles> { public: constexpr Cycles(int l) : WrappedInt<Cycles>(l) {} constexpr Cycles() : WrappedInt<Cycles>() {} constexpr Cycles(const Cycles &cycles) : WrappedInt<Cycles>(cycles.length_) {} }; /// Describes an integer number of half cycles: single clock signal transitions. class HalfCycles: public WrappedInt<HalfCycles> { public: constexpr HalfCycles(int l) : WrappedInt<HalfCycles>(l) {} constexpr HalfCycles() : WrappedInt<HalfCycles>() {} constexpr HalfCycles(const Cycles cycles) : WrappedInt<HalfCycles>(cycles.as_int() * 2) {} constexpr HalfCycles(const HalfCycles &half_cycles) : WrappedInt<HalfCycles>(half_cycles.length_) {} /// @returns The number of whole cycles completely covered by this span of half cycles. constexpr Cycles cycles() { return Cycles(length_ >> 1); } /// Flushes the whole cycles in @c this, subtracting that many from the total stored here. Cycles flush_cycles() { Cycles result(length_ >> 1); length_ &= 1; return result; } /// Flushes the half cycles in @c this, returning the number stored and setting this total to zero. HalfCycles flush() { HalfCycles result(length_); length_ = 0; return result; } /*! Severs from @c this the effect of dividing by @c divisor; @c this will end up with the value of @c this modulo @c divisor and @c divided by @c divisor is returned. */ Cycles divide_cycles(const Cycles &divisor) { HalfCycles half_divisor = HalfCycles(divisor); Cycles result(length_ / half_divisor.length_); length_ %= half_divisor.length_; return result; } }; /*! If a component implements only run_for(Cycles), an owner can wrap it in HalfClockReceiver automatically to gain run_for(HalfCycles). */ template <class T> class HalfClockReceiver: public T { public: using T::T; inline void run_for(const HalfCycles half_cycles) { half_cycles_ += half_cycles; T::run_for(half_cycles_.flush_cycles()); } private: HalfCycles half_cycles_; }; #endif /* ClockReceiver_hpp */ <|endoftext|>
<commit_before>/*! \file path.cpp \brief Filesystem path wrapper implementation \author Ivan Shynkarenka \date 11.08.2016 \copyright MIT License */ #include "filesystem/path.h" #include "errors/exceptions.h" #include <algorithm> #include <vector> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #elif defined(unix) || defined(__unix) || defined(__unix__) #include <unistd.h> #endif namespace CppCommon { //! @cond namespace Internals { std::pair<Path, size_t> root(const std::string& path) { bool root_found = false; size_t root_length = 0; // Unix case 1: "/" or "/foo" if (((path.size() == 1) && ((path[0] == '\\') || (path[0] == '/'))) || ((path.size() > 1) && ((path[0] == '\\') || (path[0] == '/')) && ((path[1] != '\\') && (path[1] != '/')))) { root_found = true; root_length = 1; return std::make_pair(Path("/"), root_length); } // Unix case 2: "///foo" if ((path.size() > 2) && ((path[0] == '\\') || (path[0] == '/')) && ((path[1] == '\\') || (path[1] == '/')) && ((path[2] == '\\') || (path[2] == '/'))) { root_found = true; root_length = 3; // Find root position while (root_length < path.size()) { if ((path[root_length] != '\\') && (path[root_length] != '/')) break; ++root_length; } return std::make_pair(Path("/"), root_length); } // Windows case 1: "\\net" or "//net" if ((path.size() > 2) && ((path[0] == '\\') || (path[0] == '/')) && ((path[1] == '\\') || (path[1] == '/')) && ((path[2] != '\\') && (path[2] != '/') && (path[2] != '?'))) { root_found = true; root_length = 3; // Find root position while (root_length < path.size()) { if ((path[root_length] == '\\') || (path[root_length] == '/')) { ++root_length; break; } ++root_length; } return std::make_pair(Path(path.substr(0, root_length)), root_length); } // Windows case 2: "\\?\" if ((path.size() > 3) && ((path[0] == '\\') && (path[1] == '\\') && (path[2] == '?') && (path[3] == '\\'))) { root_found = true; root_length = 4; } // Windows case 3: "C:" or "C:\" while (root_length < path.size()) { if (path[root_length] == ':') { root_found = true; ++root_length; while (root_length < path.size()) { if ((path[root_length] != '\\') && (path[root_length] != '/')) break; ++root_length; } break; } ++root_length; } return (root_found && (root_length > 0)) ? std::make_pair(Path(path.substr(0, root_length)), root_length) : std::make_pair(Path(), 0u); } } // namespace Internals //! @endcond Path Path::root() const { return Internals::root(_path).first; } Path Path::relative() const { size_t root_length = Internals::root(_path).second; size_t relative_length = _path.size() - root_length; return Path(_path.substr(root_length, relative_length)); } Path Path::parent() const { bool parent_found = false; size_t parent_length = _path.size(); // Find parent path position while (parent_length > 0) { --parent_length; if ((_path[parent_length] == '\\') || (_path[parent_length] == '/')) { parent_found = true; // Windows case 1: "\\net" or "//net" if ((parent_length == 1) && ((_path[parent_length - 1] == '\\') || (_path[parent_length - 1] == '/'))) parent_found = false; // Windows case 2: "\\?\" if ((parent_length > 0) && (_path[parent_length - 1] == '?')) parent_found = false; // Skip multiple path separators while (parent_length > 0) { --parent_length; if ((_path[parent_length] != '\\') && (_path[parent_length] != '/')) { ++parent_length; break; } } // Unix case 1: "/foo" -> "/", but "/" -> "" if ((parent_length == 0) && (_path.size() > 1)) ++parent_length; break; } } return (parent_found && (parent_length > 0)) ? Path(_path.substr(0, parent_length)) : Path(); } Path Path::filename() const { bool filename_found = false; size_t filename_begin = _path.size(); size_t filename_end = _path.size(); // Find filename position while (filename_begin > 0) { --filename_begin; if ((_path[filename_begin] == '\\') || (_path[filename_begin] == '/') || (_path[filename_begin] == ':')) { filename_found = ((_path[filename_begin] == '\\') || (_path[filename_begin] == '/')); ++filename_begin; break; } } size_t filename_length = (filename_end - filename_begin); return (filename_length > 0) ? Path(_path.substr(filename_begin, filename_length)) : (filename_found ? Path(".") : Path()); } Path Path::stem() const { bool ext_found = false; size_t ext_begin = _path.size(); size_t ext_end = _path.size(); // Find extension position while (ext_begin > 0) { --ext_begin; if (_path[ext_begin] == '.') { ext_found = true; if ((ext_begin > 0) && (_path[ext_begin - 1] == '.')) ext_end = ext_begin; break; } if ((_path[ext_begin] == '\\') || (_path[ext_begin] == '/') || (_path[ext_begin] == ':')) { ++ext_begin; ext_end = ext_begin; break; } } size_t ext_length = ext_end - ext_begin; bool stem_found = false; size_t stem_begin = ext_begin; size_t stem_end = (ext_found && (ext_length > 1)) ? ext_begin : _path.size(); // Find stem position while (stem_begin > 0) { --stem_begin; if ((_path[stem_begin] == '\\') || (_path[stem_begin] == '/') || (_path[stem_begin] == ':')) { stem_found = ((_path[stem_begin] == '\\') || (_path[stem_begin] == '/')); ++stem_begin; break; } } size_t stem_length = (stem_end - stem_begin); return (stem_length > 0) ? Path(_path.substr(stem_begin, stem_length)) : (stem_found ? Path(".") : Path()); } Path Path::extension() const { bool ext_found = false; size_t ext_begin = _path.size(); size_t ext_end = _path.size(); // Find extension position while (ext_begin > 0) { --ext_begin; if (_path[ext_begin] == '.') { ext_found = true; if ((ext_begin > 0) && (_path[ext_begin - 1] == '.')) ext_end = ext_begin; break; } if ((_path[ext_begin] == '\\') || (_path[ext_begin] == '/') || (_path[ext_begin] == ':')) { ++ext_begin; ext_end = ext_begin; break; } } size_t ext_length = ext_end - ext_begin; return (ext_found && (ext_length > 1)) ? Path(_path.substr(ext_begin, ext_length)) : Path(); } Path& Path::Append(const Path& path) { if (_path.empty()) _path = path._path; else { char last = _path[_path.size() - 1]; if ((last == '\\') || (last == '/')) _path += path._path; else { _path += separator(); _path += path._path; } } return *this; } Path& Path::MakePreferred() { #if defined(_WIN32) || defined(_WIN64) std::replace(_path.begin(), _path.end(), '/', '\\'); #elif defined(unix) || defined(__unix) || defined(__unix__) std::replace(_path.begin(), _path.end(), '\\', '/'); #endif return *this; } Path& Path::ReplaceFilename(const Path& filename) { if (_path.empty()) _path.append(filename._path); else { size_t index = _path.size(); // Find filename position while (index > 0) { --index; if ((_path[index] == '\\') || (_path[index] == '/') || (_path[index] == ':')) { if (!filename.empty()) ++index; break; } } _path.resize(index); _path.append(filename._path); } return *this; } Path& Path::ReplaceExtension(const Path& extension) { bool dot_required = (!extension._path.empty() && (extension._path[0] != '.')); if (_path.empty()) { if (dot_required) _path.append("."); _path.append(extension._path); } else { size_t dot = _path.size(); size_t index = _path.size(); // Find extension position while (index > 0) { --index; if (_path[index] == '.') { if ((index > 0) && (_path[index - 1] == '.')) dot = index - 1; else dot = index; break; } if ((_path[index] == '\\') || (_path[index] == '/') || (_path[index] == ':')) { if (!extension.empty()) ++index; break; } } _path.resize(dot); if (dot_required) _path.append("."); _path.append(extension._path); } return *this; } Path& Path::RemoveTrailingSeparators() { size_t index = _path.size(); while (index > 0) { --index; if (((_path[index] != '\\') && (_path[index] != '/')) || ((index > 0) && (_path[index - 1] == ':'))) { ++index; break; } } _path.resize(index); return *this; } Path Path::executable() { #if defined(_WIN32) || defined(_WIN64) std::vector<wchar_t> path(MAX_PATH); DWORD result; while ((result = GetModuleFileNameW(nullptr, path.data(), (DWORD)path.size())) == path.size()) path.resize(path.size() * 2); if (result == 0) throwex SystemException("Cannot executable path of the current process!"); return Path(std::wstring(path.begin(), path.end())); #elif defined(unix) || defined(__unix) || defined(__unix__) std::vector<char> path(PATH_MAX); ssize_t result; while ((result = readlink("/proc/self/exe", path.data(), path.size())) == (ssize_t)path.size()) path.resize(path.size() * 2); if (result == -1) throwex SystemException("Cannot executable path of the current process!"); return Path(std::string(path.begin(), path.end())); #endif } } // namespace CppCommon <commit_msg>Bugfix<commit_after>/*! \file path.cpp \brief Filesystem path wrapper implementation \author Ivan Shynkarenka \date 11.08.2016 \copyright MIT License */ #include "filesystem/path.h" #include "errors/exceptions.h" #include <algorithm> #include <vector> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #elif defined(unix) || defined(__unix) || defined(__unix__) #include <limits.h> #include <unistd.h> #endif namespace CppCommon { //! @cond namespace Internals { std::pair<Path, size_t> root(const std::string& path) { bool root_found = false; size_t root_length = 0; // Unix case 1: "/" or "/foo" if (((path.size() == 1) && ((path[0] == '\\') || (path[0] == '/'))) || ((path.size() > 1) && ((path[0] == '\\') || (path[0] == '/')) && ((path[1] != '\\') && (path[1] != '/')))) { root_found = true; root_length = 1; return std::make_pair(Path("/"), root_length); } // Unix case 2: "///foo" if ((path.size() > 2) && ((path[0] == '\\') || (path[0] == '/')) && ((path[1] == '\\') || (path[1] == '/')) && ((path[2] == '\\') || (path[2] == '/'))) { root_found = true; root_length = 3; // Find root position while (root_length < path.size()) { if ((path[root_length] != '\\') && (path[root_length] != '/')) break; ++root_length; } return std::make_pair(Path("/"), root_length); } // Windows case 1: "\\net" or "//net" if ((path.size() > 2) && ((path[0] == '\\') || (path[0] == '/')) && ((path[1] == '\\') || (path[1] == '/')) && ((path[2] != '\\') && (path[2] != '/') && (path[2] != '?'))) { root_found = true; root_length = 3; // Find root position while (root_length < path.size()) { if ((path[root_length] == '\\') || (path[root_length] == '/')) { ++root_length; break; } ++root_length; } return std::make_pair(Path(path.substr(0, root_length)), root_length); } // Windows case 2: "\\?\" if ((path.size() > 3) && ((path[0] == '\\') && (path[1] == '\\') && (path[2] == '?') && (path[3] == '\\'))) { root_found = true; root_length = 4; } // Windows case 3: "C:" or "C:\" while (root_length < path.size()) { if (path[root_length] == ':') { root_found = true; ++root_length; while (root_length < path.size()) { if ((path[root_length] != '\\') && (path[root_length] != '/')) break; ++root_length; } break; } ++root_length; } return (root_found && (root_length > 0)) ? std::make_pair(Path(path.substr(0, root_length)), root_length) : std::make_pair<Path, size_t>(Path(), 0); } } // namespace Internals //! @endcond Path Path::root() const { return Internals::root(_path).first; } Path Path::relative() const { size_t root_length = Internals::root(_path).second; size_t relative_length = _path.size() - root_length; return Path(_path.substr(root_length, relative_length)); } Path Path::parent() const { bool parent_found = false; size_t parent_length = _path.size(); // Find parent path position while (parent_length > 0) { --parent_length; if ((_path[parent_length] == '\\') || (_path[parent_length] == '/')) { parent_found = true; // Windows case 1: "\\net" or "//net" if ((parent_length == 1) && ((_path[parent_length - 1] == '\\') || (_path[parent_length - 1] == '/'))) parent_found = false; // Windows case 2: "\\?\" if ((parent_length > 0) && (_path[parent_length - 1] == '?')) parent_found = false; // Skip multiple path separators while (parent_length > 0) { --parent_length; if ((_path[parent_length] != '\\') && (_path[parent_length] != '/')) { ++parent_length; break; } } // Unix case 1: "/foo" -> "/", but "/" -> "" if ((parent_length == 0) && (_path.size() > 1)) ++parent_length; break; } } return (parent_found && (parent_length > 0)) ? Path(_path.substr(0, parent_length)) : Path(); } Path Path::filename() const { bool filename_found = false; size_t filename_begin = _path.size(); size_t filename_end = _path.size(); // Find filename position while (filename_begin > 0) { --filename_begin; if ((_path[filename_begin] == '\\') || (_path[filename_begin] == '/') || (_path[filename_begin] == ':')) { filename_found = ((_path[filename_begin] == '\\') || (_path[filename_begin] == '/')); ++filename_begin; break; } } size_t filename_length = (filename_end - filename_begin); return (filename_length > 0) ? Path(_path.substr(filename_begin, filename_length)) : (filename_found ? Path(".") : Path()); } Path Path::stem() const { bool ext_found = false; size_t ext_begin = _path.size(); size_t ext_end = _path.size(); // Find extension position while (ext_begin > 0) { --ext_begin; if (_path[ext_begin] == '.') { ext_found = true; if ((ext_begin > 0) && (_path[ext_begin - 1] == '.')) ext_end = ext_begin; break; } if ((_path[ext_begin] == '\\') || (_path[ext_begin] == '/') || (_path[ext_begin] == ':')) { ++ext_begin; ext_end = ext_begin; break; } } size_t ext_length = ext_end - ext_begin; bool stem_found = false; size_t stem_begin = ext_begin; size_t stem_end = (ext_found && (ext_length > 1)) ? ext_begin : _path.size(); // Find stem position while (stem_begin > 0) { --stem_begin; if ((_path[stem_begin] == '\\') || (_path[stem_begin] == '/') || (_path[stem_begin] == ':')) { stem_found = ((_path[stem_begin] == '\\') || (_path[stem_begin] == '/')); ++stem_begin; break; } } size_t stem_length = (stem_end - stem_begin); return (stem_length > 0) ? Path(_path.substr(stem_begin, stem_length)) : (stem_found ? Path(".") : Path()); } Path Path::extension() const { bool ext_found = false; size_t ext_begin = _path.size(); size_t ext_end = _path.size(); // Find extension position while (ext_begin > 0) { --ext_begin; if (_path[ext_begin] == '.') { ext_found = true; if ((ext_begin > 0) && (_path[ext_begin - 1] == '.')) ext_end = ext_begin; break; } if ((_path[ext_begin] == '\\') || (_path[ext_begin] == '/') || (_path[ext_begin] == ':')) { ++ext_begin; ext_end = ext_begin; break; } } size_t ext_length = ext_end - ext_begin; return (ext_found && (ext_length > 1)) ? Path(_path.substr(ext_begin, ext_length)) : Path(); } Path& Path::Append(const Path& path) { if (_path.empty()) _path = path._path; else { char last = _path[_path.size() - 1]; if ((last == '\\') || (last == '/')) _path += path._path; else { _path += separator(); _path += path._path; } } return *this; } Path& Path::MakePreferred() { #if defined(_WIN32) || defined(_WIN64) std::replace(_path.begin(), _path.end(), '/', '\\'); #elif defined(unix) || defined(__unix) || defined(__unix__) std::replace(_path.begin(), _path.end(), '\\', '/'); #endif return *this; } Path& Path::ReplaceFilename(const Path& filename) { if (_path.empty()) _path.append(filename._path); else { size_t index = _path.size(); // Find filename position while (index > 0) { --index; if ((_path[index] == '\\') || (_path[index] == '/') || (_path[index] == ':')) { if (!filename.empty()) ++index; break; } } _path.resize(index); _path.append(filename._path); } return *this; } Path& Path::ReplaceExtension(const Path& extension) { bool dot_required = (!extension._path.empty() && (extension._path[0] != '.')); if (_path.empty()) { if (dot_required) _path.append("."); _path.append(extension._path); } else { size_t dot = _path.size(); size_t index = _path.size(); // Find extension position while (index > 0) { --index; if (_path[index] == '.') { if ((index > 0) && (_path[index - 1] == '.')) dot = index - 1; else dot = index; break; } if ((_path[index] == '\\') || (_path[index] == '/') || (_path[index] == ':')) { if (!extension.empty()) ++index; break; } } _path.resize(dot); if (dot_required) _path.append("."); _path.append(extension._path); } return *this; } Path& Path::RemoveTrailingSeparators() { size_t index = _path.size(); while (index > 0) { --index; if (((_path[index] != '\\') && (_path[index] != '/')) || ((index > 0) && (_path[index - 1] == ':'))) { ++index; break; } } _path.resize(index); return *this; } Path Path::executable() { #if defined(_WIN32) || defined(_WIN64) std::vector<wchar_t> path(MAX_PATH); DWORD result; while ((result = GetModuleFileNameW(nullptr, path.data(), (DWORD)path.size())) == path.size()) path.resize(path.size() * 2); if (result == 0) throwex SystemException("Cannot executable path of the current process!"); return Path(std::wstring(path.begin(), path.end())); #elif defined(unix) || defined(__unix) || defined(__unix__) std::vector<char> path(PATH_MAX); ssize_t result; while ((result = readlink("/proc/self/exe", path.data(), path.size())) == (ssize_t)path.size()) path.resize(path.size() * 2); if (result == -1) throwex SystemException("Cannot executable path of the current process!"); return Path(std::string(path.begin(), path.end())); #endif } } // namespace CppCommon <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Nicholas Corgan ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "CalculationOutput.hpp" using namespace pkmnsim; using namespace std; CalculationOutput::CalculationOutput(QWidget* parent, int gen): QWidget(parent) { generation = gen; QVBoxLayout* mainLayout = new QVBoxLayout(); QGroupBox* hpGroupBox = new QGroupBox(tr("HP"),this); hpGroupBox->setObjectName("hpGroupBox"); QHBoxLayout* hpLayout = new QHBoxLayout(hpGroupBox); QLabel* hpEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); hpLayout->addWidget(hpEmptyLabel); hpLayout->setAlignment(Qt::AlignCenter); QGroupBox* attackGroupBox = new QGroupBox(tr("Attack"),this); attackGroupBox->setObjectName("attackGroupBox"); QHBoxLayout* attackLayout = new QHBoxLayout(attackGroupBox); QLabel* attackEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); attackLayout->addWidget(attackEmptyLabel); attackLayout->setAlignment(Qt::AlignCenter); QGroupBox* defenseGroupBox = new QGroupBox(tr("Defense"),this); defenseGroupBox->setObjectName("defenseGroupBox"); QHBoxLayout* defenseLayout = new QHBoxLayout(defenseGroupBox); QLabel* defenseEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); defenseLayout->addWidget(defenseEmptyLabel); defenseLayout->setAlignment(Qt::AlignCenter); QGroupBox* speedGroupBox = new QGroupBox(tr("Speed"),this); speedGroupBox->setObjectName("defenseGroupBox"); QHBoxLayout* speedLayout = new QHBoxLayout(speedGroupBox); QLabel* speedEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); speedLayout->addWidget(speedEmptyLabel); speedLayout->setAlignment(Qt::AlignCenter); hpGroupBox->setLayout(hpLayout); attackGroupBox->setLayout(attackLayout); defenseGroupBox->setLayout(defenseLayout); speedGroupBox->setLayout(speedLayout); mainLayout->addWidget(hpGroupBox); mainLayout->addWidget(attackGroupBox); mainLayout->addWidget(defenseGroupBox); mainLayout->addWidget(speedGroupBox); if(gen == 1) { QGroupBox* specialGroupBox = new QGroupBox(tr("Special"),this); specialGroupBox->setObjectName("specialGroupBox"); QHBoxLayout* specialLayout = new QHBoxLayout(specialGroupBox); specialGroupBox->setLayout(specialLayout); QLabel* specialEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); specialLayout->addWidget(specialEmptyLabel); specialLayout->setAlignment(Qt::AlignCenter); mainLayout->addWidget(specialGroupBox); } else { QGroupBox* specialAttackGroupBox = new QGroupBox(tr("Special Attack"),this); specialAttackGroupBox->setObjectName("specialAttackGroupBox"); QHBoxLayout* specialAttackLayout = new QHBoxLayout(specialAttackGroupBox); specialAttackGroupBox->setLayout(specialAttackLayout); QLabel* specialAttackEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); specialAttackLayout->addWidget(specialAttackEmptyLabel); specialAttackLayout->setAlignment(Qt::AlignCenter); mainLayout->addWidget(specialAttackGroupBox); QGroupBox* specialDefenseGroupBox = new QGroupBox(tr("Special Defense"),this); specialDefenseGroupBox->setObjectName("specialDefenseGroupBox"); QHBoxLayout* specialDefenseLayout = new QHBoxLayout(specialDefenseGroupBox); specialDefenseGroupBox->setLayout(specialDefenseLayout); QLabel* specialDefenseEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); specialDefenseLayout->addWidget(specialDefenseEmptyLabel); specialDefenseLayout->setAlignment(Qt::AlignCenter); mainLayout->addWidget(specialDefenseGroupBox); } setLayout(mainLayout); } //Slot to call when results are calculated by OptionsGroupBox void CalculationOutput::getAndShowResults(vector<vector<stat_st> > highest_stats_vecs, vector<vector<stat_st> > lowest_stats_vecs, vector<int> errcodes, string type1, string type2) { vector<stat_st> high_vec = highest_stats_vecs[generation-1]; vector<stat_st> low_vec = lowest_stats_vecs[generation-1]; QList<QGroupBox*> groupBoxQList = this->findChildren<QGroupBox*>(); for(int i = 0; i < groupBoxQList.count(); i++) { //Delete all widgets in QGroupBox QList<QLabel*> labelQList = groupBoxQList.at(i)->findChildren<QLabel*>(); for(int j = 0; j < labelQList.count(); j++) delete labelQList.at(j); QList<BasePkmnDisplayWidget*> basePkmnQList = groupBoxQList.at(i)->findChildren<BasePkmnDisplayWidget*>(); for(int j = 0; j < basePkmnQList.count(); j++) delete basePkmnQList.at(j); QFrame* delVertLine = groupBoxQList.at(i)->findChild<QFrame*>(QString("vertLine")); if(delVertLine) delete delVertLine; if(errcodes[generation-1] or high_vec[i].pkmn_name == "Missingno." or low_vec[i].pkmn_name == "Missingno.") { QLabel* noPkmnLabel = new QLabel(QString("No Pokemon of specified type combination in Generation %1").arg( QString::number(generation) )); groupBoxQList.at(i)->layout()->addWidget(noPkmnLabel); } else { //Add appropriate Pokemon base_pkmn::sptr highPkmn = base_pkmn::make(high_vec[i].pkmn_name, generation, false); base_pkmn::sptr lowPkmn = base_pkmn::make(low_vec[i].pkmn_name, generation, false); //Manually set Castform form if necessary if(highPkmn->get_display_name() == "Castform") set_castform_type(highPkmn, type1); if(lowPkmn->get_display_name() == "Castform") set_castform_type(lowPkmn, type1); //Create BasePkmnDisplayWidgets BasePkmnDisplayWidget* highWidget = new BasePkmnDisplayWidget(groupBoxQList.at(i),highPkmn); BasePkmnDisplayWidget* lowWidget = new BasePkmnDisplayWidget(groupBoxQList.at(i),lowPkmn); //Create QLabels with BasePkmnDisplayWidgets QLabel* highLabel = new QLabel(tr("High:"), highWidget); QLabel* lowLabel = new QLabel(tr("Low:"), lowWidget); //Create stat number labels (PROBABLY WILL CHANGE LATER) QLabel* highStat = new QLabel(QString("(%1)").arg(QString::number(high_vec[i].stat_value))); QLabel* lowStat = new QLabel(QString("(%1)").arg(QString::number(low_vec[i].stat_value))); //Separator and calculate button QFrame* vertLine = new QFrame(groupBoxQList.at(i)); vertLine->setObjectName("vertLine"); vertLine->setFrameShape(QFrame::VLine); //Add widgets to QGroupBoxes groupBoxQList.at(i)->layout()->addWidget(highWidget); groupBoxQList.at(i)->layout()->addWidget(highStat); groupBoxQList.at(i)->layout()->addWidget(vertLine); groupBoxQList.at(i)->layout()->addWidget(lowWidget); groupBoxQList.at(i)->layout()->addWidget(lowStat); } } update(); } <commit_msg>get_type_stats_gui: layout improvement<commit_after>/* * Copyright (c) 2013 Nicholas Corgan ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "CalculationOutput.hpp" using namespace pkmnsim; using namespace std; CalculationOutput::CalculationOutput(QWidget* parent, int gen): QWidget(parent) { generation = gen; QVBoxLayout* mainLayout = new QVBoxLayout(); QGroupBox* hpGroupBox = new QGroupBox(tr("HP"),this); hpGroupBox->setObjectName("hpGroupBox"); QHBoxLayout* hpLayout = new QHBoxLayout(hpGroupBox); QLabel* hpEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); hpLayout->addWidget(hpEmptyLabel); hpLayout->setAlignment(Qt::AlignCenter); QGroupBox* attackGroupBox = new QGroupBox(tr("Attack"),this); attackGroupBox->setObjectName("attackGroupBox"); QHBoxLayout* attackLayout = new QHBoxLayout(attackGroupBox); QLabel* attackEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); attackLayout->addWidget(attackEmptyLabel); attackLayout->setAlignment(Qt::AlignCenter); QGroupBox* defenseGroupBox = new QGroupBox(tr("Defense"),this); defenseGroupBox->setObjectName("defenseGroupBox"); QHBoxLayout* defenseLayout = new QHBoxLayout(defenseGroupBox); QLabel* defenseEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); defenseLayout->addWidget(defenseEmptyLabel); defenseLayout->setAlignment(Qt::AlignCenter); QGroupBox* speedGroupBox = new QGroupBox(tr("Speed"),this); speedGroupBox->setObjectName("defenseGroupBox"); QHBoxLayout* speedLayout = new QHBoxLayout(speedGroupBox); QLabel* speedEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); speedLayout->addWidget(speedEmptyLabel); speedLayout->setAlignment(Qt::AlignCenter); hpGroupBox->setLayout(hpLayout); attackGroupBox->setLayout(attackLayout); defenseGroupBox->setLayout(defenseLayout); speedGroupBox->setLayout(speedLayout); mainLayout->addWidget(hpGroupBox); mainLayout->addWidget(attackGroupBox); mainLayout->addWidget(defenseGroupBox); mainLayout->addWidget(speedGroupBox); if(gen == 1) { QGroupBox* specialGroupBox = new QGroupBox(tr("Special"),this); specialGroupBox->setObjectName("specialGroupBox"); QHBoxLayout* specialLayout = new QHBoxLayout(specialGroupBox); specialGroupBox->setLayout(specialLayout); QLabel* specialEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); specialLayout->addWidget(specialEmptyLabel); specialLayout->setAlignment(Qt::AlignCenter); mainLayout->addWidget(specialGroupBox); } else { QGroupBox* specialAttackGroupBox = new QGroupBox(tr("Special Attack"),this); specialAttackGroupBox->setObjectName("specialAttackGroupBox"); QHBoxLayout* specialAttackLayout = new QHBoxLayout(specialAttackGroupBox); specialAttackGroupBox->setLayout(specialAttackLayout); QLabel* specialAttackEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); specialAttackLayout->addWidget(specialAttackEmptyLabel); specialAttackLayout->setAlignment(Qt::AlignCenter); mainLayout->addWidget(specialAttackGroupBox); QGroupBox* specialDefenseGroupBox = new QGroupBox(tr("Special Defense"),this); specialDefenseGroupBox->setObjectName("specialDefenseGroupBox"); QHBoxLayout* specialDefenseLayout = new QHBoxLayout(specialDefenseGroupBox); specialDefenseGroupBox->setLayout(specialDefenseLayout); QLabel* specialDefenseEmptyLabel = new QLabel(tr("Press the Calculate button to show results.")); specialDefenseLayout->addWidget(specialDefenseEmptyLabel); specialDefenseLayout->setAlignment(Qt::AlignCenter); mainLayout->addWidget(specialDefenseGroupBox); } setLayout(mainLayout); } //Slot to call when results are calculated by OptionsGroupBox void CalculationOutput::getAndShowResults(vector<vector<stat_st> > highest_stats_vecs, vector<vector<stat_st> > lowest_stats_vecs, vector<int> errcodes, string type1, string type2) { vector<stat_st> high_vec = highest_stats_vecs[generation-1]; vector<stat_st> low_vec = lowest_stats_vecs[generation-1]; QList<QGroupBox*> groupBoxQList = this->findChildren<QGroupBox*>(); for(int i = 0; i < groupBoxQList.count(); i++) { //Delete all widgets in QGroupBox QList<QLabel*> labelQList = groupBoxQList.at(i)->findChildren<QLabel*>(); for(int j = 0; j < labelQList.count(); j++) delete labelQList.at(j); QList<BasePkmnDisplayWidget*> basePkmnQList = groupBoxQList.at(i)->findChildren<BasePkmnDisplayWidget*>(); for(int j = 0; j < basePkmnQList.count(); j++) delete basePkmnQList.at(j); QFrame* delVertLine = groupBoxQList.at(i)->findChild<QFrame*>(QString("vertLine")); if(delVertLine) delete delVertLine; if(errcodes[generation-1] or high_vec[i].pkmn_name == "Missingno." or low_vec[i].pkmn_name == "Missingno.") { QLabel* noPkmnLabel = new QLabel(QString("No Pokemon of specified type combination in Generation %1").arg( QString::number(generation) )); groupBoxQList.at(i)->layout()->addWidget(noPkmnLabel); } else { //Add appropriate Pokemon base_pkmn::sptr highPkmn = base_pkmn::make(high_vec[i].pkmn_name, generation, false); base_pkmn::sptr lowPkmn = base_pkmn::make(low_vec[i].pkmn_name, generation, false); //Manually set Castform form if necessary if(highPkmn->get_display_name() == "Castform") set_castform_type(highPkmn, type1); if(lowPkmn->get_display_name() == "Castform") set_castform_type(lowPkmn, type1); //Create BasePkmnDisplayWidgets BasePkmnDisplayWidget* highWidget = new BasePkmnDisplayWidget(groupBoxQList.at(i),highPkmn); BasePkmnDisplayWidget* lowWidget = new BasePkmnDisplayWidget(groupBoxQList.at(i),lowPkmn); //Create QLabels with BasePkmnDisplayWidgets QLabel* highLabel = new QLabel(tr("High:")); QLabel* lowLabel = new QLabel(tr("Low:")); //Create stat number labels (PROBABLY WILL CHANGE LATER) QLabel* highStat = new QLabel(QString("(%1)").arg(QString::number(high_vec[i].stat_value))); QLabel* lowStat = new QLabel(QString("(%1)").arg(QString::number(low_vec[i].stat_value))); //Separator and calculate button QFrame* vertLine = new QFrame(groupBoxQList.at(i)); vertLine->setObjectName("vertLine"); vertLine->setFrameShape(QFrame::VLine); //Add widgets to QGroupBoxes groupBoxQList.at(i)->layout()->addWidget(highLabel); groupBoxQList.at(i)->layout()->addWidget(highWidget); groupBoxQList.at(i)->layout()->addWidget(highStat); groupBoxQList.at(i)->layout()->addWidget(vertLine); groupBoxQList.at(i)->layout()->addWidget(lowLabel); groupBoxQList.at(i)->layout()->addWidget(lowWidget); groupBoxQList.at(i)->layout()->addWidget(lowStat); groupBoxQList.at(i)->layout()->setSpacing(10); groupBoxQList.at(i)->layout()->setMargin(5); } } update(); } <|endoftext|>
<commit_before>/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /****************************************************************************************************/ #include <GG/adobe/future/widgets/headers/platform_window.hpp> #include <GG/adobe/future/modal_dialog_interface.hpp> #include <GG/adobe/future/widgets/headers/display.hpp> #include <GG/adobe/future/widgets/headers/widget_utils.hpp> #include <GG/adobe/future/widgets/headers/platform_label.hpp> #include <GG/adobe/future/widgets/headers/platform_metrics.hpp> #include <GG/adobe/future/widgets/headers/platform_widget_utils.hpp> #include <GG/adobe/keyboard.hpp> #include <GG/EveGlue.h> #include <GG/GUI.h> #include <GG/StyleFactory.h> /****************************************************************************************************/ namespace adobe { /****************************************************************************************************/ window_t::window_t(const std::string& name, GG::Flags<GG::WndFlag> flags, GG::Clr color, GG::Clr text_color) : window_m(0), flags_m(flags), name_m(name), color_m(color), text_color_m(text_color), debounce_m(false), placed_once_m(false) { } /****************************************************************************************************/ window_t::~window_t() { delete window_m; } /****************************************************************************************************/ void window_t::measure(extents_t& result) { assert(window_m); if (name_m.empty()) { result.height() = 15; result.width() = 15; return; } // REVISIT (fbrereto) : A lot of static metrics values added here boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory(); result = metrics::measure_text(name_m, style->DefaultFont()); result.width() = static_cast<long>(result.width() * 1.5); } /****************************************************************************************************/ void window_t::place(const place_data_t& place_data) { assert(window_m); if (placed_once_m) { set_size(point_2d_t(width(place_data), height(place_data))); } else { placed_once_m = true; place_data_m = place_data; GG::Pt ul(GG::X(left(place_data)), GG::Y(top(place_data))); GG::Pt size( GG::Pt(GG::X(width(place_data)), GG::Y(height(place_data))) + implementation::NonClientSize(*window_m) ); window_m->SetMinSize(size); window_m->SizeMove(ul, ul + size); } } /****************************************************************************************************/ void window_t::set_size(const point_2d_t& size) { assert(window_m); if (debounce_m) return; debounce_m = true; width(place_data_m) = size.x_m; height(place_data_m) = size.y_m; window_m->Resize( GG::Pt(GG::X(width(place_data_m)), GG::Y(height(place_data_m))) + implementation::NonClientSize(*window_m) ); debounce_m = false; } /****************************************************************************************************/ void window_t::reposition() { assert(window_m); const GG::X width(window_m->Width()); const GG::Y height(window_m->Height()); GG::X app_width(GG::GUI::GetGUI()->AppWidth()); GG::Y app_height(GG::GUI::GetGUI()->AppHeight()); GG::X left(std::max(GG::X(10), (app_width - width) / 2)); GG::Y top(std::max(GG::Y(10), (app_height - height) / 2)); window_m->MoveTo(GG::Pt(left, top)); } /****************************************************************************************************/ void window_t::set_visible(bool make_visible) { assert(window_m); if (!window_m->Visible()) reposition(); set_control_visible(window_m, make_visible); } /****************************************************************************************************/ void window_t::monitor_resize(const window_resize_proc_t& proc) { resize_proc_m = proc; } /****************************************************************************************************/ any_regular_t window_t::underlying_handler() { return any_regular_t(window_m); } /****************************************************************************************************/ bool window_t::handle_key(key_type key, bool pressed, modifiers_t modifiers) { return false; } /****************************************************************************************************/ template <> platform_display_type insert<window_t>(display_t& display, platform_display_type& parent, window_t& element) { assert(!element.window_m); assert(!parent); element.window_m = new GG::EveDialog(element, element.color_m, element.text_color_m); return display.insert(parent, element.window_m); } /****************************************************************************************************/ } // namespace adobe /****************************************************************************************************/ <commit_msg>Removed window_t's deletion of its window_m member in its dtor. This prevents double deletion of EveDialogs.<commit_after>/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /****************************************************************************************************/ #include <GG/adobe/future/widgets/headers/platform_window.hpp> #include <GG/adobe/future/modal_dialog_interface.hpp> #include <GG/adobe/future/widgets/headers/display.hpp> #include <GG/adobe/future/widgets/headers/widget_utils.hpp> #include <GG/adobe/future/widgets/headers/platform_label.hpp> #include <GG/adobe/future/widgets/headers/platform_metrics.hpp> #include <GG/adobe/future/widgets/headers/platform_widget_utils.hpp> #include <GG/adobe/keyboard.hpp> #include <GG/EveGlue.h> #include <GG/GUI.h> #include <GG/StyleFactory.h> /****************************************************************************************************/ namespace adobe { /****************************************************************************************************/ window_t::window_t(const std::string& name, GG::Flags<GG::WndFlag> flags, GG::Clr color, GG::Clr text_color) : window_m(0), flags_m(flags), name_m(name), color_m(color), text_color_m(text_color), debounce_m(false), placed_once_m(false) { } /****************************************************************************************************/ window_t::~window_t() { } /****************************************************************************************************/ void window_t::measure(extents_t& result) { assert(window_m); if (name_m.empty()) { result.height() = 15; result.width() = 15; return; } // REVISIT (fbrereto) : A lot of static metrics values added here boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory(); result = metrics::measure_text(name_m, style->DefaultFont()); result.width() = static_cast<long>(result.width() * 1.5); } /****************************************************************************************************/ void window_t::place(const place_data_t& place_data) { assert(window_m); if (placed_once_m) { set_size(point_2d_t(width(place_data), height(place_data))); } else { placed_once_m = true; place_data_m = place_data; GG::Pt ul(GG::X(left(place_data)), GG::Y(top(place_data))); GG::Pt size( GG::Pt(GG::X(width(place_data)), GG::Y(height(place_data))) + implementation::NonClientSize(*window_m) ); window_m->SetMinSize(size); window_m->SizeMove(ul, ul + size); } } /****************************************************************************************************/ void window_t::set_size(const point_2d_t& size) { assert(window_m); if (debounce_m) return; debounce_m = true; width(place_data_m) = size.x_m; height(place_data_m) = size.y_m; window_m->Resize( GG::Pt(GG::X(width(place_data_m)), GG::Y(height(place_data_m))) + implementation::NonClientSize(*window_m) ); debounce_m = false; } /****************************************************************************************************/ void window_t::reposition() { assert(window_m); const GG::X width(window_m->Width()); const GG::Y height(window_m->Height()); GG::X app_width(GG::GUI::GetGUI()->AppWidth()); GG::Y app_height(GG::GUI::GetGUI()->AppHeight()); GG::X left(std::max(GG::X(10), (app_width - width) / 2)); GG::Y top(std::max(GG::Y(10), (app_height - height) / 2)); window_m->MoveTo(GG::Pt(left, top)); } /****************************************************************************************************/ void window_t::set_visible(bool make_visible) { assert(window_m); if (!window_m->Visible()) reposition(); set_control_visible(window_m, make_visible); } /****************************************************************************************************/ void window_t::monitor_resize(const window_resize_proc_t& proc) { resize_proc_m = proc; } /****************************************************************************************************/ any_regular_t window_t::underlying_handler() { return any_regular_t(window_m); } /****************************************************************************************************/ bool window_t::handle_key(key_type key, bool pressed, modifiers_t modifiers) { return false; } /****************************************************************************************************/ template <> platform_display_type insert<window_t>(display_t& display, platform_display_type& parent, window_t& element) { assert(!element.window_m); assert(!parent); element.window_m = new GG::EveDialog(element, element.color_m, element.text_color_m); return display.insert(parent, element.window_m); } /****************************************************************************************************/ } // namespace adobe /****************************************************************************************************/ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Hugh Bailey <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ #pragma once namespace DShow { #define COMMON_ENCODED_CX 720 #define COMMON_ENCODED_CY 480 #define COMMON_ENCODED_INTERVAL (10010000000LL/60000LL) #define COMMON_ENCODED_VFORMAT VideoFormat::H264 #define COMMON_ENCODED_SAMPLERATE 48000 static const EncodedDevice HD_PVR1 = { COMMON_ENCODED_VFORMAT, 0x1011UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AC3, 0x1100UL, COMMON_ENCODED_SAMPLERATE }; static const EncodedDevice HD_PVR2 = { COMMON_ENCODED_VFORMAT, 0x1011UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AAC, 0x1100UL, COMMON_ENCODED_SAMPLERATE }; static const EncodedDevice Roxio = { COMMON_ENCODED_VFORMAT, 0x1011UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AAC, 0x010FUL, COMMON_ENCODED_SAMPLERATE, }; static const EncodedDevice HD_PVR_Rocket = { COMMON_ENCODED_VFORMAT, 0x07D1UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::MPGA, 0x07D2UL, COMMON_ENCODED_SAMPLERATE }; }; /* namespace DShow */ <commit_msg>Change HD-PVR Rocket default audio encoder to AAC<commit_after>/* * Copyright (C) 2014 Hugh Bailey <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ #pragma once namespace DShow { #define COMMON_ENCODED_CX 720 #define COMMON_ENCODED_CY 480 #define COMMON_ENCODED_INTERVAL (10010000000LL/60000LL) #define COMMON_ENCODED_VFORMAT VideoFormat::H264 #define COMMON_ENCODED_SAMPLERATE 48000 static const EncodedDevice HD_PVR1 = { COMMON_ENCODED_VFORMAT, 0x1011UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AC3, 0x1100UL, COMMON_ENCODED_SAMPLERATE }; static const EncodedDevice HD_PVR2 = { COMMON_ENCODED_VFORMAT, 0x1011UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AAC, 0x1100UL, COMMON_ENCODED_SAMPLERATE }; static const EncodedDevice Roxio = { COMMON_ENCODED_VFORMAT, 0x1011UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AAC, 0x010FUL, COMMON_ENCODED_SAMPLERATE, }; static const EncodedDevice HD_PVR_Rocket = { COMMON_ENCODED_VFORMAT, 0x07D1UL, COMMON_ENCODED_CX, COMMON_ENCODED_CY, COMMON_ENCODED_INTERVAL, AudioFormat::AAC, 0x07D2UL, COMMON_ENCODED_SAMPLERATE }; }; /* namespace DShow */ <|endoftext|>
<commit_before>/*============================================================================= MYPROJECT: A software package for whatever. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <mpMyFunctions.h> #include <iostream> #ifdef BUILD_Eigen #include <Eigen/Dense> #endif #ifdef BUILD_Boost #include <boost/math/special_functions/round.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem/path.hpp> #endif #ifdef BUILD_OpenCV #include <cv.h> #endif /** * \brief Demo file to check that #includes and library linkage is correct. */ int main(int argc, char** argv) { #ifdef BUILD_Eigen Eigen::MatrixXd m(2,2); std::cout << "Printing 2x2 matrix ..." << m << std::endl; #endif #ifdef BUILD_Boost std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl; boost::posix_time::ptime startTime = boost::posix_time::second_clock::local_time(); boost::filesystem::path pathname( "/tmp/tmp.txt" ); #endif #ifdef BUILD_OpenCV cv::Matx44d matrix = cv::Matx44d::eye(); std::cout << "Printing 4x4 matrix ..." << matrix << std::endl; #endif std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl; return 0; } <commit_msg>Issue #1: Include some gflags and glog statements to check includes and linkage.<commit_after>/*============================================================================= MYPROJECT: A software package for whatever. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <mpMyFunctions.h> #include <iostream> #ifdef BUILD_gflags #include "gflags/gflags.h" #endif #ifdef BUILD_glog #include <glog/logging.h> #endif #ifdef BUILD_Eigen #include <Eigen/Dense> #endif #ifdef BUILD_Boost #include <boost/math/special_functions/round.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem/path.hpp> #endif #ifdef BUILD_OpenCV #include <cv.h> #endif /** * \brief Demo file to check that #includes and library linkage is correct. */ int main(int argc, char** argv) { #ifdef BUILD_glog google::InitGoogleLogging(argv[0]); #endif #ifdef BUILD_gflags gflags::SetVersionString("1.0.0"); #endif #ifdef BUILD_Eigen Eigen::MatrixXd m(2,2); std::cout << "Printing 2x2 matrix ..." << m << std::endl; #endif #ifdef BUILD_Boost std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl; boost::posix_time::ptime startTime = boost::posix_time::second_clock::local_time(); boost::filesystem::path pathname( "/tmp/tmp.txt" ); #endif #ifdef BUILD_OpenCV cv::Matx44d matrix = cv::Matx44d::eye(); std::cout << "Printing 4x4 matrix ..." << matrix << std::endl; #endif std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl; return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "robot_interface/robot_interface.h" using namespace std; // Declare a test TEST(RobotInterfaceTest, testConstructorDefaultValues) { RobotInterface ri("robot", "left"); EXPECT_FALSE(ri.isCtrlRunning()); EXPECT_EQ(START, int(ri.getState())); EXPECT_EQ("robot", ri.getName()); EXPECT_EQ( "left", ri.getLimb()); EXPECT_TRUE(ri.isRobotUsed()); EXPECT_EQ( 100.0, ri.getCtrlFreq()); EXPECT_TRUE(ri.useForces()); EXPECT_TRUE(ri.useTracIK()); EXPECT_TRUE(ri.useCartCtrl()); EXPECT_FALSE(ri.isExperimental()); ri.setTracIK(false); EXPECT_FALSE(ri.useTracIK()); } TEST(RobotInterfaceTest, testConstructorCustomValues) { string name = "robot"; string limb = "left"; bool use_robot = false; double ctrl_freq = 50.0; bool use_forces = false; bool use_trac_ik = false; bool use_cart_ctrl = false; bool is_experimental = false; RobotInterface ri(name, limb, use_robot, ctrl_freq, use_forces, use_trac_ik, use_cart_ctrl, is_experimental); EXPECT_FALSE(ri.isCtrlRunning()); EXPECT_EQ(START, int(ri.getState())); EXPECT_EQ( name, ri.getName()); EXPECT_EQ( limb, ri.getLimb()); EXPECT_EQ( use_robot, ri.isRobotUsed()); EXPECT_EQ( ctrl_freq, ri.getCtrlFreq()); EXPECT_EQ( use_forces, ri.useForces()); EXPECT_EQ( use_trac_ik, ri.useTracIK()); EXPECT_EQ( use_cart_ctrl, ri.useCartCtrl()); EXPECT_EQ(is_experimental, ri.isExperimental()); use_trac_ik = true; ri.setTracIK(use_trac_ik); EXPECT_EQ(use_trac_ik, ri.useTracIK()); } TEST(RobotInterfaceTest, testPrivateMethods) { string name = "robot"; string limb = "left"; bool use_robot = false; double ctrl_freq = 50.0; bool use_forces = false; bool use_trac_ik = false; bool use_cart_ctrl = false; bool is_experimental = false; RobotInterface ri(name, limb, use_robot, ctrl_freq, use_forces, use_trac_ik, use_cart_ctrl, is_experimental); EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "loose", "sdf")); EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "strict", "sdf")); EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "sdf", "pose")); EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "sdf", "position")); EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "sdf", "orientation")); std::string type = "pose"; EXPECT_FALSE(ri.setCtrlType("")); EXPECT_EQ(ri.getCtrlType(), type); EXPECT_FALSE(ri.setCtrlType(" ")); EXPECT_EQ(ri.getCtrlType(), type); EXPECT_FALSE(ri.setCtrlType("asdfa")); EXPECT_EQ(ri.getCtrlType(), type); EXPECT_TRUE(ri.setCtrlType(type)); EXPECT_EQ(ri.getCtrlType(), type); type = "position"; EXPECT_TRUE(ri.setCtrlType(type)); EXPECT_EQ(ri.getCtrlType(), type); type = "orientation"; EXPECT_TRUE(ri.setCtrlType(type)); EXPECT_EQ(ri.getCtrlType(), type); } TEST(RobotInterfaceTest, testCallbacks) { ros::NodeHandle nh; RobotInterface ri("robot", "left"); EXPECT_EQ(ri.getCurrRange(), 0.0); EXPECT_EQ(ri.getCurrMinRange(), 0.0); EXPECT_EQ(ri.getCurrMaxRange(), 0.0); // Create publisher ros::Publisher ir_pub = nh.advertise<sensor_msgs::Range>("/robot/range/" + ri.getLimb() + "_hand_range/state", SUBSCRIBER_BUFFER); // Publish stuff sensor_msgs::Range msg; msg.range = 1.0; msg.min_range = 2.0; msg.max_range = 3.0; ros::Rate loop_rate(10); while(ros::ok() && (ri.getCurrRange() == 0.0)) { ir_pub.publish(msg); //ROS_INFO("%s", msg.range); ros::spinOnce(); loop_rate.sleep(); } // Check that the stuff has beeen correctly parsed by a robot interface object EXPECT_EQ(ri.getCurrRange(), 1.0); EXPECT_EQ(ri.getCurrMinRange(), 2.0); EXPECT_EQ(ri.getCurrMaxRange(), 3.0); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { ros::init(argc, argv, "robot_interface_test"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>endpoint, cuffLower, cuffUpper, and jointStates callback tests<commit_after>#include <gtest/gtest.h> #include <tf/transform_datatypes.h> #include "robot_interface/robot_interface.h" using namespace std; // Declare a test // TEST(RobotInterfaceTest, testConstructorDefaultValues) // { // RobotInterface ri("robot", "left"); // EXPECT_FALSE(ri.isCtrlRunning()); // EXPECT_EQ(START, int(ri.getState())); // EXPECT_EQ("robot", ri.getName()); // EXPECT_EQ( "left", ri.getLimb()); // EXPECT_TRUE(ri.isRobotUsed()); // EXPECT_EQ( 100.0, ri.getCtrlFreq()); // EXPECT_TRUE(ri.useForces()); // EXPECT_TRUE(ri.useTracIK()); // EXPECT_TRUE(ri.useCartCtrl()); // EXPECT_FALSE(ri.isExperimental()); // ri.setTracIK(false); // EXPECT_FALSE(ri.useTracIK()); // } // TEST(RobotInterfaceTest, testConstructorCustomValues) // { // string name = "robot"; // string limb = "left"; // bool use_robot = false; // double ctrl_freq = 50.0; // bool use_forces = false; // bool use_trac_ik = false; // bool use_cart_ctrl = false; // bool is_experimental = false; // RobotInterface ri(name, limb, use_robot, ctrl_freq, use_forces, // use_trac_ik, use_cart_ctrl, is_experimental); // EXPECT_FALSE(ri.isCtrlRunning()); // EXPECT_EQ(START, int(ri.getState())); // EXPECT_EQ( name, ri.getName()); // EXPECT_EQ( limb, ri.getLimb()); // EXPECT_EQ( use_robot, ri.isRobotUsed()); // EXPECT_EQ( ctrl_freq, ri.getCtrlFreq()); // EXPECT_EQ( use_forces, ri.useForces()); // EXPECT_EQ( use_trac_ik, ri.useTracIK()); // EXPECT_EQ( use_cart_ctrl, ri.useCartCtrl()); // EXPECT_EQ(is_experimental, ri.isExperimental()); // use_trac_ik = true; // ri.setTracIK(use_trac_ik); // EXPECT_EQ(use_trac_ik, ri.useTracIK()); // } // TEST(RobotInterfaceTest, testPrivateMethods) // { // string name = "robot"; // string limb = "left"; // bool use_robot = false; // double ctrl_freq = 50.0; // bool use_forces = false; // bool use_trac_ik = false; // bool use_cart_ctrl = false; // bool is_experimental = false; // RobotInterface ri(name, limb, use_robot, ctrl_freq, use_forces, // use_trac_ik, use_cart_ctrl, is_experimental); // EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "loose", "sdf")); // EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "strict", "sdf")); // EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "sdf", "pose")); // EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "sdf", "position")); // EXPECT_FALSE(ri.isPoseReached(geometry_msgs::Pose(), "sdf", "orientation")); // std::string type = "pose"; // EXPECT_FALSE(ri.setCtrlType("")); // EXPECT_EQ(ri.getCtrlType(), type); // EXPECT_FALSE(ri.setCtrlType(" ")); // EXPECT_EQ(ri.getCtrlType(), type); // EXPECT_FALSE(ri.setCtrlType("asdfa")); // EXPECT_EQ(ri.getCtrlType(), type); // EXPECT_TRUE(ri.setCtrlType(type)); // EXPECT_EQ(ri.getCtrlType(), type); // type = "position"; // EXPECT_TRUE(ri.setCtrlType(type)); // EXPECT_EQ(ri.getCtrlType(), type); // type = "orientation"; // EXPECT_TRUE(ri.setCtrlType(type)); // EXPECT_EQ(ri.getCtrlType(), type); // } TEST(RobotInterfaceTest, testJointStatesCallback) { ros::NodeHandle nh; RobotInterface ri("robot", "left"); ros::Publisher jointStates_pub = nh.advertise<sensor_msgs::JointState> ("/robot/joint_states", SUBSCRIBER_BUFFER); sensor_msgs::JointState msg; msg.name = {"_s0", "_s1", "_e0", "_e1", "_w0", "_w1", "_w2"}; for(size_t i = 0; i < msg.name.size(); ++i) { msg.name[i] = ri.getLimb() + msg.name[i].c_str(); } msg.position = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}; msg.velocity = {1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7}; ros::Rate loop_rate(10); while(ros::ok() && (ri.getJointStates().name.size() == 0)) { jointStates_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } EXPECT_EQ(ri.getJointStates().name[0], ri.getLimb() + "_s0"); EXPECT_EQ(ri.getJointStates().name[1], ri.getLimb() + "_s1"); EXPECT_EQ(ri.getJointStates().name[2], ri.getLimb() + "_e0"); EXPECT_EQ(ri.getJointStates().name[3], ri.getLimb() + "_e1"); EXPECT_EQ(ri.getJointStates().name[4], ri.getLimb() + "_w0"); EXPECT_EQ(ri.getJointStates().name[5], ri.getLimb() + "_w1"); EXPECT_EQ(ri.getJointStates().name[6], ri.getLimb() + "_w2"); EXPECT_EQ(ri.getJointStates().position[0], 0.1); EXPECT_EQ(ri.getJointStates().position[1], 0.2); EXPECT_EQ(ri.getJointStates().position[2], 0.3); EXPECT_EQ(ri.getJointStates().position[3], 0.4); EXPECT_EQ(ri.getJointStates().position[4], 0.5); EXPECT_EQ(ri.getJointStates().position[5], 0.6); EXPECT_EQ(ri.getJointStates().position[6], 0.7); EXPECT_EQ(ri.getJointStates().velocity[0], 1.1); EXPECT_EQ(ri.getJointStates().velocity[1], 1.2); EXPECT_EQ(ri.getJointStates().velocity[2], 1.3); EXPECT_EQ(ri.getJointStates().velocity[3], 1.4); EXPECT_EQ(ri.getJointStates().velocity[4], 1.5); EXPECT_EQ(ri.getJointStates().velocity[5], 1.6); EXPECT_EQ(ri.getJointStates().velocity[6], 1.7); } // TEST(RobotInterfaceTest, testCuffLowerCallback) // { // ros::NodeHandle nh; // RobotInterface ri("robot", "left"); // ros::Publisher cuffLower_pub = // nh.advertise<baxter_core_msgs::DigitalIOState> // ("/robot/digital_io/" + ri.getLimb() + "_lower_button/state", SUBSCRIBER_BUFFER); // baxter_core_msgs::DigitalIOState msg; // msg.state = baxter_core_msgs::DigitalIOState::PRESSED; // ros::Rate loop_rate(10); // while(ros::ok() && ri.getState() == START) // { // cuffLower_pub.publish(msg); // ros::spinOnce(); // loop_rate.sleep(); // } // EXPECT_EQ(int(ri.getState()), KILLED); // } // TEST(RobotInterfaceTest, testCuffUpperCallback) // { // ros::NodeHandle nh; // RobotInterface ri("robot", "left"); // ros::Publisher cuffUpper_pub = // nh.advertise<baxter_core_msgs::DigitalIOState> // ("/robot/digital_io/" + ri.getLimb() + "_upper_button/state", SUBSCRIBER_BUFFER); // baxter_core_msgs::DigitalIOState msg; // msg.state = baxter_core_msgs::DigitalIOState::PRESSED; // ros::Rate loop_rate(10); // while(ros::ok() && ri.getState() == START) // { // cuffUpper_pub.publish(msg); // ros::spinOnce(); // loop_rate.sleep(); // } // EXPECT_EQ(int(ri.getState()), KILLED); // } // TEST(RobotInterfaceTest, testEndpointCallback) // { // ros::NodeHandle nh; // RobotInterface ri("robot", "left"); // ros::Publisher endpoint_pub = // nh.advertise<baxter_core_msgs::EndpointState> // ("/robot/limb/" + ri.getLimb() + "/endpoint_state", SUBSCRIBER_BUFFER); // typename geometry_msgs::Point point; // point.x = 0.1; // point.y = 0.2; // point.z = 0.3; // typename geometry_msgs::Quaternion ori; // ori.x = 0.4; // ori.y = 0.5; // ori.z = 0.6; // ori.w = 0.7; // typename baxter_core_msgs::EndpointState msg; // msg.pose.position = point; // msg.pose.orientation = ori; // if(ri.useForces()) // { // typename geometry_msgs::Wrench wrench; // typename geometry_msgs::Vector3 force; // typename geometry_msgs::Vector3 torque; // force.x = 0.1; // force.y = 0.2; // force.z = 0.3; // wrench.force = force; // torque.x = 0.1; // torque.y = 0.2; // torque.z = 0.3; // wrench.torque = torque; // msg.wrench = wrench; // } // ros::Rate loop_rate(10); // while(ros::ok() && ri.getWrench().torque.z == 0.0) // { // endpoint_pub.publish(msg); // ros::spinOnce(); // loop_rate.sleep(); // } // EXPECT_EQ(ri.getPos().x, 0.1); // EXPECT_EQ(ri.getPos().y, 0.2); // EXPECT_EQ(ri.getPos().z, 0.3); // EXPECT_EQ(ri.getOri().x, 0.4); // EXPECT_EQ(ri.getOri().y, 0.5); // EXPECT_EQ(ri.getOri().z, 0.6); // EXPECT_EQ(ri.getOri().w, 0.7); // EXPECT_TRUE(ri.useForces()); // if(ri.useForces()) // { // EXPECT_EQ(ri.getWrench().force.x, 0.1); // EXPECT_EQ(ri.getWrench().force.y, 0.2); // EXPECT_EQ(ri.getWrench().force.z, 0.3); // EXPECT_EQ(ri.getWrench().torque.x, 0.1); // EXPECT_EQ(ri.getWrench().torque.y, 0.2); // EXPECT_EQ(ri.getWrench().torque.z, 0.3); // } // //filterForces() ************************************ // } // TEST(RobotInterfaceTest, testIRCallback) // { // ros::NodeHandle nh; // RobotInterface ri("robot", "left"); // EXPECT_EQ(ri.getCurrRange(), 0.0); // EXPECT_EQ(ri.getCurrMinRange(), 0.0); // EXPECT_EQ(ri.getCurrMaxRange(), 0.0); // // Create publisher // ros::Publisher ir_pub = // nh.advertise<sensor_msgs::Range>("/robot/range/" + ri.getLimb() + "_hand_range/state", SUBSCRIBER_BUFFER); // // Publish stuff // sensor_msgs::Range msg; // msg.range = 1.0; // msg.min_range = 2.0; // msg.max_range = 3.0; // ros::Rate loop_rate(10); // while(ros::ok() && (ri.getCurrRange() == 0.0)) // { // ir_pub.publish(msg); // ros::spinOnce(); // loop_rate.sleep(); // } // // Check that the stuff has beeen correctly parsed by a robot interface object // EXPECT_EQ(ri.getCurrRange(), 1.0); // EXPECT_EQ(ri.getCurrMinRange(), 2.0); // EXPECT_EQ(ri.getCurrMaxRange(), 3.0); // } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { ros::init(argc, argv, "robot_interface_test"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "gui/element/label.h++" #include <graphics/color.h++> #include <graphics/shape/text.h++> #include <graphics/canvas.h++> #include "graphics/shape/ellipse.h++" #include "graphics/shape/rectangle.h++" #include "graphics/gradient/sweep_gradient.h++" namespace skui { namespace gui { namespace { graphics::text make_text(const core::string& text, const graphics::style::fill& fill, const graphics::style::border& outline, const graphics::style::font& font) { graphics::text result(text); result.fill = fill; result.border = outline; result.font = font; return result; } } label::label(core::string text) : text{text} , fill{} {} label::~label() = default; void label::draw(graphics::canvas& canvas, const graphics::scalar_position& position) const { auto graphics_text = make_text(text, fill, outline, font); graphics::rectangle rectangle{canvas.measure_text(graphics_text)}; rectangle.border = border; //rectangle.fill = background; element::draw(canvas, {&rectangle, &graphics_text}, {position, position + graphics::scalar_position{border.thickness, border.thickness}}); } graphics::scalar_size label::implicit_size(const graphics::canvas& canvas) const { auto graphics_text = make_text(text, fill, outline, font); const auto text_size = canvas.measure_text(graphics_text); core::debug_print(border.thickness, '\n'); return text_size + 2.f*graphics::scalar_size{border.thickness, border.thickness}; } } } <commit_msg>Small fixes for gui::label<commit_after>/** * The MIT License (MIT) * * Copyright © 2017-2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "gui/element/label.h++" #include <graphics/color.h++> #include <graphics/shape/text.h++> #include <graphics/canvas.h++> #include "graphics/shape/ellipse.h++" #include "graphics/shape/rectangle.h++" #include "graphics/gradient/sweep_gradient.h++" namespace skui { namespace gui { namespace { graphics::text make_text(const core::string& text, const graphics::style::fill& fill, const graphics::style::border& outline, const graphics::style::font& font) { graphics::text result(text); result.fill = fill; result.border = outline; result.font = font; return result; } } label::label(core::string text) : text{text} , fill{} {} label::~label() = default; void label::draw(graphics::canvas& canvas, const graphics::scalar_position& position) const { auto graphics_text = make_text(text, fill, outline, font); graphics::rectangle rectangle{canvas.measure_text(graphics_text)}; rectangle.border = border; rectangle.fill = background; element::draw(canvas, {&rectangle, &graphics_text}, {position, position + graphics::scalar_position{border.thickness, border.thickness}}); } graphics::scalar_size label::implicit_size(const graphics::canvas& canvas) const { auto graphics_text = make_text(text, fill, outline, font); const auto text_size = canvas.measure_text(graphics_text); return text_size + 2.f*graphics::scalar_size{border.thickness, border.thickness}; } } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Magician.h" #include "FireballSkill.h" Magician::Magician() { } Magician::Magician(int playerId, HeroType heroType, b2Vec2 pos) { m_HeroType = HERO_MAGICIAN; m_Qskill = new FireballSkill(m_PlayerID); } Magician::~Magician() { } void Magician::UseSkill(SkillKey skillKey, b2Vec2 heroPos, b2Vec2 targetPos) { //broadcast skill id , unit pos... //skill id == missile unit id switch (skillKey) { case SKILL_NONE: break; case SKILL_Q: m_Qskill->ShootSkill(m_UnitID,heroPos,targetPos); break; case SKILL_W: break; case SKILL_E: break; case SKILL_R: break; } } <commit_msg>[S]잔수정 commit을 늘리겠다<commit_after>#include "stdafx.h" #include "Magician.h" #include "FireballSkill.h" Magician::Magician() { } Magician::Magician(int playerId, HeroType heroType, b2Vec2 pos) { m_HeroType = HERO_MAGICIAN; m_Qskill = new FireballSkill(m_PlayerID, m_Body->GetFixtureList()->GetShape()->m_radius); } Magician::~Magician() { } void Magician::UseSkill(SkillKey skillKey, b2Vec2 heroPos, b2Vec2 targetPos) { //broadcast skill id , unit pos... //skill id == missile unit id switch (skillKey) { case SKILL_NONE: break; case SKILL_Q: m_Qskill->ShootSkill(m_UnitID,heroPos,targetPos); break; case SKILL_W: break; case SKILL_E: break; case SKILL_R: break; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2014 ZNC, see the NOTICE file for details. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <znc/IRCNetwork.h> class CPerform : public CModule { void Add(const CString& sCommand) { CString sPerf = sCommand.Token(1, true); if (sPerf.empty()) { PutModule("Usage: add <command>"); return; } m_vPerform.push_back(ParsePerform(sPerf)); PutModule("Added!"); Save(); } void Del(const CString& sCommand) { u_int iNum = sCommand.Token(1, true).ToUInt(); if (iNum > m_vPerform.size() || iNum <= 0) { PutModule("Illegal # Requested"); return; } else { m_vPerform.erase(m_vPerform.begin() + iNum - 1); PutModule("Command Erased."); } Save(); } void List(const CString& sCommand) { CTable Table; unsigned int index = 1; Table.AddColumn("Id"); Table.AddColumn("Perform"); Table.AddColumn("Expanded"); for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it, index++) { Table.AddRow(); Table.SetCell("Id", CString(index)); Table.SetCell("Perform", *it); CString sExpanded = ExpandString(*it); if (sExpanded != *it) { Table.SetCell("Expanded", sExpanded); } } if (PutModule(Table) == 0) { PutModule("No commands in your perform list."); } } void Execute(const CString& sCommand) { OnIRCConnected(); PutModule("perform commands sent"); } void Swap(const CString& sCommand) { u_int iNumA = sCommand.Token(1).ToUInt(); u_int iNumB = sCommand.Token(2).ToUInt(); if (iNumA > m_vPerform.size() || iNumA <= 0 || iNumB > m_vPerform.size() || iNumB <= 0) { PutModule("Illegal # Requested"); } else { std::iter_swap(m_vPerform.begin() + (iNumA - 1), m_vPerform.begin() + (iNumB - 1)); PutModule("Commands Swapped."); Save(); } } public: MODCONSTRUCTOR(CPerform) { AddHelpCommand(); AddCommand("Add", static_cast<CModCommand::ModCmdFunc>(&CPerform::Add), "<command>"); AddCommand("Del", static_cast<CModCommand::ModCmdFunc>(&CPerform::Del), "<nr>"); AddCommand("List", static_cast<CModCommand::ModCmdFunc>(&CPerform::List)); AddCommand("Execute", static_cast<CModCommand::ModCmdFunc>(&CPerform::Execute)); AddCommand("Swap", static_cast<CModCommand::ModCmdFunc>(&CPerform::Swap), "<nr> <nr>"); } virtual ~CPerform() {} CString ParsePerform(const CString& sArg) const { CString sPerf = sArg; if (sPerf.Left(1) == "/") sPerf.LeftChomp(); if (sPerf.Token(0).Equals("MSG")) { sPerf = "PRIVMSG " + sPerf.Token(1, true); } if ((sPerf.Token(0).Equals("PRIVMSG") || sPerf.Token(0).Equals("NOTICE")) && sPerf.Token(2).Left(1) != ":") { sPerf = sPerf.Token(0) + " " + sPerf.Token(1) + " :" + sPerf.Token(2, true); } return sPerf; } virtual bool OnLoad(const CString& sArgs, CString& sMessage) { GetNV("Perform").Split("\n", m_vPerform, false); return true; } virtual void OnIRCConnected() { for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { PutIRC(ExpandString(*it)); } } virtual CString GetWebMenuTitle() { return "Perform"; } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName != "index") { // only accept requests to index return false; } if (WebSock.IsPost()) { VCString vsPerf; WebSock.GetRawParam("perform", true).Split("\n", vsPerf, false); m_vPerform.clear(); for (VCString::const_iterator it = vsPerf.begin(); it != vsPerf.end(); ++it) m_vPerform.push_back(ParsePerform(*it)); Save(); } for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { CTemplate& Row = Tmpl.AddRow("PerformLoop"); Row["Perform"] = *it; } return true; } private: void Save() { CString sBuffer = ""; for (VCString::const_iterator it = m_vPerform.begin(); it != m_vPerform.end(); ++it) { sBuffer += *it + "\n"; } SetNV("Perform", sBuffer); } VCString m_vPerform; }; template<> void TModInfo<CPerform>(CModInfo& Info) { Info.AddType(CModInfo::UserModule); Info.SetWikiPage("perform"); } NETWORKMODULEDEFS(CPerform, "Keeps a list of commands to be executed when ZNC connects to IRC.") <commit_msg>removed perform.cpp<commit_after><|endoftext|>
<commit_before>#include "persons.h" Persons::Persons() { name = ""; birthYear = 1980; deathYear = 0; alive = true; } <commit_msg>breytti kyn í char<commit_after>#include "persons.h" Persons::Persons() { name = ""; birthYear = 1980; deathYear = 0; alive = true; gender = 'M'; } <|endoftext|>
<commit_before>#include "persons.h" #include <iomanip> Persons::Persons() { name = " "; gender = ' '; birthYear = 1980; deathYear = 0; alive = true; } Persons::Persons(string n, char g, int bY, int dY) { name = n; birthYear = bY; deathYear = dY; gender = g; if (dY == 0) { alive = true; } else { alive = false; } } string Persons::getName() const{ return name; } int Persons::getBirthYear() const{ return birthYear; } int Persons::getDeathYear() const{ return deathYear; } char Persons::getGender() const{ return gender; } bool Persons::getAlive() const{ return alive; } ostream& operator << (ostream& out, const Persons& p) { out.width(16); out << left << p.getName() << ";\t" << p.getGender() << "\t" << p.getBirthYear() << "\t"; if (!p.getAlive()) { out << "\t" << "Died " << p.getDeathYear(); } else { out << "\t" << "Alive " << p.getDeathYear(); } return out; } istream& operator >> (istream& in, Persons& p) { string a = " "; getline(in, p.name, ';'); in >> p.gender >> p.birthYear >> a; if (a == "Alive") { p.alive = true; } else if (a == "Died"){ p.alive = false; } in >> p.deathYear; return in; } <commit_msg>persons in lagað<commit_after>#include "persons.h" #include <iomanip> Persons::Persons() { name = " "; gender = ' '; birthYear = 1980; deathYear = 0; alive = true; } Persons::Persons(string n, char g, int bY, int dY) { name = n; birthYear = bY; deathYear = dY; gender = g; if (dY == 0) { alive = true; } else { alive = false; } } string Persons::getName() const{ return name; } int Persons::getBirthYear() const{ return birthYear; } int Persons::getDeathYear() const{ return deathYear; } char Persons::getGender() const{ return gender; } bool Persons::getAlive() const{ return alive; } ostream& operator << (ostream& out, const Persons& p) { out.width(16); out << left << p.getName() << ";\t" << p.getGender() << "\t" << p.getBirthYear() << "\t"; if (!p.getAlive()) { out << "\t" << "Died " << p.getDeathYear(); } else { out << "\t" << "Alive " << p.getDeathYear(); } return out; } istream& operator >> (istream& in, Persons& p) { string a = " "; getline(in, p.name, ';'); in >> p.gender >> p.birthYear >> a; if (a == "Alive") { p.alive = true; <<<<<<< HEAD ======= in >> p.deathYear; >>>>>>> 34a878318004ce91cb9ea5b203bfc0ea790d21a7 } else if (a == "Died"){ p.alive = false; } in >> p.deathYear; return in; } <|endoftext|>
<commit_before>#include "notendaui.h" #include <iostream> #include <string> #include <utility> #include <algorithm> using namespace std; NotendaUI::NotendaUI() { } bool check = true; void NotendaUI::keyra() { _service.writeTolvufolk(tolvufolk("Charles Babbage", "kk", 1990, 1991)); _service.appendTolvufolk(tolvufolk("Ada Lovelace", "kvk", 1880, 1890)); _service.appendTolvufolk(tolvufolk("zllan Turing", "kk", 1918, 1948)); vector<tolvufolk> data = _service.getTolvufolk(true); skrifaUt(); do { check = true; string skipun; cin >> skipun; if (skipun == "list" || skipun == "l") { system("cls"); cout << "List of computer scientists: " << endl; printList(); continueUI(); } else if (skipun == "sort"|| skipun == "so") { skrifaUt(); sortOptions(); continueUI(); } else if (skipun == "add" || skipun == "a") { system("cls"); cout << "Adding computer scientist: " << endl; addPerson(); printList(); continueUI(); } else if (skipun == "delete" || skipun == "d") { deletePerson(); continueUI(); } else if (skipun == "update" || skipun == "u") { skrifaUt(); updatePerson(data); continueUI(); } else if (skipun == "search" || skipun == "s") { skrifaUt(); searchName(data); continueUI(); } else if (skipun == "purge" || skipun == "p") { skrifaUt(); purgeList(data); } else if (skipun == "quit" || skipun == "q") { check = true; } else { skrifaUt(); cerr << "Input not valid, try again: "; check = false; } } while (check == false); } void NotendaUI::skrifaUt() { system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following commands ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||list - Shows a list of all known entries in the database. ||*" << endl; cout << "*||add - Add a new entry into the database. ||*" << endl; cout << "*||delete - Removes an entry from the database. ||*" << endl; cout << "*||update - Updates an entry from the database. ||*" << endl; cout << "*||search - Search for an entry from the database. ||*" << endl; cout << "*||purge - Removes every entry from the database. ||*" << endl; cout << "*||quit - Exits/quits the program. ||*" << endl; cout << "*==================================================================*" << endl; } void NotendaUI::updatePerson(vector<tolvufolk>& data) { system("cls"); printList(); int persNR; string skipunin; cout << "Update scientist number: "; cin >> persNR; persNR --; cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command* ||*" << endl; cout << "*=================================================================*" << endl; cout << "*||name - update name, please write 'name' ||*" << endl; cout << "*||gender - update gender, please write 'gender' ||*" << endl; cout << "*||birth - update year of birth, please write 'birth' ||*" << endl; cout << "*||death - update year of death, please write 'deat' ||*" << endl; cout << "*==================================================================*" << endl; cin >> skipunin; if (skipunin == "name" || skipunin == "n") { string nafn; cout << "Enter updated name for " << data[persNR].getNafn() << ": "; cin.ignore(); getline(cin,nafn); data[persNR].updNafn(nafn); } else if (skipunin == "gender" || skipunin == "g") { string newgend; cout << "Enter updated gender for " << data[persNR].getNafn() << ": "; cin >> newgend; while (newgend != "kk" && newgend != "kvk") { cerr << "Input not valid, try again: "; cin >> newgend; } data[persNR].updGender(newgend); } else if (skipunin == "birth" || skipunin == "b") { int nytt; cout << "Enter updated year of birth for " << data[persNR].getNafn() << ": "; cin >> nytt; data[persNR].updFaedingarar(nytt); } else if (skipunin == "death" || skipunin == "d") { int nytt; cout << "Enter updated year of death for " << data[persNR].getNafn() << ": "; cin >> nytt; data[persNR].updDanarar(nytt); } refreshTxtFile(data); } void NotendaUI::searchOptions() { system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||name - Search by name, please write 'name' ||*" << endl; cout << "*||age - Search by age, please write 'age' ||*" << endl; cout << "*||birth - Search by year of birth, please write 'birth' ||*" << endl; cout << "*||death - Search by year of death, please write 'death' ||*" << endl; cout << "*==================================================================*" << endl; } void NotendaUI::printList() { cout << "----------------------------------------------------------------------------------------------------------" << endl; cout << "|Scientist ID \t |Name \t\t\t\t |Gender \t |Year of Birth |Year of death |Age \t |" << endl; cout << "----------------------------------------------------------------------------------------------------------" << endl; vector<tolvufolk> data = _service.getTolvufolk(false); for (size_t i = 0; i < data.size(); i++) { cout << "|" << i + 1 << " \t\t "; cout << data[i]; /* cout << "Scientist number: " << i + 1 << endl; cout << data[i] << endl; */ } cout << "----------------------------------------------------------------------------------------------------------" << endl; } void NotendaUI::searchName(const vector<tolvufolk>& data) { searchOptions(); string skipunin; cin >> skipunin; if (skipunin == "name" || skipunin == "n") { searchOptions(); string nafn; cout << "Name to search: "; cin.ignore(); getline(cin,nafn); cout << endl; for(size_t i = 0; i < data.size(); i++) { if (nafn == data[i].getNafn() ) { cout << data[i]; } } cout << endl; } else if (skipunin == "age" || skipunin == "a") { searchOptions(); int age; cout << "Age to search: "; cin >> age; cout << endl; for(size_t i = 0; i < data.size(); i++) { if (age == (data[i].getDanarar() - data[i].getFaedingarar() ) ) { cout << data[i]; } } cout << endl; } else if (skipunin == "birth" || skipunin == "b") { searchOptions(); int birth; cout << "Year of birth to search: "; cin >> birth; cout << endl; for(size_t i = 0; i < data.size(); i++) { if (birth == data[i].getFaedingarar() ) { cout << data[i]; } } cout << endl; } else if (skipunin == "death" || skipunin == "d") { searchOptions(); int death; cout << "Year of birth to search: "; cin >> death; cout << endl; for(size_t i = 0; i < data.size(); i++) { if (death == data[i].getDanarar() ) { cout << data[i]; } } cout << endl; } } void NotendaUI::sortOptions() { string skipunin; system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||name - Sort by name, please write 'name' ||*" << endl; cout << "*||age - Sort by age, please write 'age' ||*" << endl; cout << "*||birth - Sort by year of birth, please write 'birth' ||*" << endl; cout << "*||death - Sort by year of death, please write 'death' ||*" << endl; cout << "*==================================================================*" << endl; cin >> skipunin; if (skipunin == "name" || skipunin == "n") { system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||ascending - Sort names by ascending order ||*" << endl; cout << "*||descending - Sort names by descending order ||*" << endl; cout << "*==================================================================*" << endl; cin >> skipunin; if(skipunin == "ascending" || skipunin == "a") { _service.sortByAscending(); printList(); } else if(skipunin == "descending" || skipunin == "d") { _service.sortByDescending(); printList(); } } } void NotendaUI::addPerson() { string firstName; string lastName; string gGender; int bYear; int dYear; cout << "Enter firstname: "; cin >> firstName; cout << "Enter lastname: "; cin >> lastName; cout << "Enter gender(kk/kvk) [lowercase]: "; cin >> gGender; while (gGender != "kk" && gGender != "kvk") { cerr << "Input not valid, try again: "; cin >> gGender; } cout << "Enter year of birth: "; cin >> bYear; while (0 > bYear) { cerr << "Input not valid, try again: "; cin >> bYear; } cout << "Enter year of death(-1 if still alive): "; cin >> dYear; while (-1 > dYear) { cerr << "Input not valid, try again: "; cin >> dYear; cout << endl; } cout << endl; _service.addTolvufolk(tolvufolk(firstName + " " + lastName, gGender, bYear, dYear)); } void NotendaUI::deletePerson() { system("cls"); printList(); int persNR; cout << "Delete scientist number: "; cin >> persNR; persNR--; _service.deleteSingleTolvufolk(persNR); } void NotendaUI::purgeList(vector<tolvufolk> &data) { string skipun; cout << "By the Emperor, are you sure? (Y/N): "; cin >> skipun; if (skipun == "Y" || skipun == "y") { cout << "Are you really sure? This will EXTERMINATE ALL ENTRIES. (Y/N): "; cin >> skipun; if (skipun == "Y" || skipun == "y") { cout << "Acknowledged, by your will, all ENTRIES will be EXTERMINATED." << endl; data.clear(); refreshTxtFile(data); continueUI(); } else { cout << "Purge canceled." << endl; continueUI(); } } else { cout << "Purge canceled." << endl; continueUI(); } } void NotendaUI::refreshTxtFile(const vector<tolvufolk>& data) { _service.deleteTolvufolk(); for(size_t i = 0; i < data.size(); i++) { _service.appendTolvufolk(data[i]); } } void NotendaUI::continueUI() { string answer; cout << "Continue? (Y/N): "; cin >> answer; if (answer == "Y" || answer == "y") { skrifaUt(); check = false; } else { check = true; } } <commit_msg>litid fix vid continue fallid<commit_after>#include "notendaui.h" #include <iostream> #include <string> #include <utility> #include <algorithm> using namespace std; NotendaUI::NotendaUI() { } bool check = true; void NotendaUI::keyra() { _service.writeTolvufolk(tolvufolk("Charles Babbage", "kk", 1990, 1991)); _service.appendTolvufolk(tolvufolk("Ada Lovelace", "kvk", 1880, 1890)); _service.appendTolvufolk(tolvufolk("zllan Turing", "kk", 1918, 1948)); vector<tolvufolk> data = _service.getTolvufolk(true); skrifaUt(); do { check = true; string skipun; cin >> skipun; if (skipun == "list" || skipun == "l") { system("cls"); cout << "List of computer scientists: " << endl; printList(); continueUI(); } else if (skipun == "sort"|| skipun == "so") { skrifaUt(); sortOptions(); continueUI(); } else if (skipun == "add" || skipun == "a") { system("cls"); cout << "Adding computer scientist: " << endl; addPerson(); printList(); continueUI(); } else if (skipun == "delete" || skipun == "d") { deletePerson(); continueUI(); } else if (skipun == "update" || skipun == "u") { skrifaUt(); updatePerson(data); continueUI(); } else if (skipun == "search" || skipun == "s") { skrifaUt(); searchName(data); continueUI(); } else if (skipun == "purge" || skipun == "p") { skrifaUt(); purgeList(data); } else if (skipun == "quit" || skipun == "q") { check = true; } else { skrifaUt(); cerr << "Input not valid, try again: "; check = false; } } while (check == false); } void NotendaUI::skrifaUt() { system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following commands ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||list - Shows a list of all known entries in the database. ||*" << endl; cout << "*||add - Add a new entry into the database. ||*" << endl; cout << "*||delete - Removes an entry from the database. ||*" << endl; cout << "*||update - Updates an entry from the database. ||*" << endl; cout << "*||search - Search for an entry from the database. ||*" << endl; cout << "*||purge - Removes every entry from the database. ||*" << endl; cout << "*||quit - Exits/quits the program. ||*" << endl; cout << "*==================================================================*" << endl; } void NotendaUI::updatePerson(vector<tolvufolk>& data) { system("cls"); printList(); int persNR; string skipunin; cout << "Update scientist number: "; cin >> persNR; persNR --; cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command* ||*" << endl; cout << "*=================================================================*" << endl; cout << "*||name - update name, please write 'name' ||*" << endl; cout << "*||gender - update gender, please write 'gender' ||*" << endl; cout << "*||birth - update year of birth, please write 'birth' ||*" << endl; cout << "*||death - update year of death, please write 'deat' ||*" << endl; cout << "*==================================================================*" << endl; cin >> skipunin; if (skipunin == "name" || skipunin == "n") { string nafn; cout << "Enter updated name for " << data[persNR].getNafn() << ": "; cin.ignore(); getline(cin,nafn); data[persNR].updNafn(nafn); } else if (skipunin == "gender" || skipunin == "g") { string newgend; cout << "Enter updated gender for " << data[persNR].getNafn() << ": "; cin >> newgend; while (newgend != "kk" && newgend != "kvk") { cerr << "Input not valid, try again: "; cin >> newgend; } data[persNR].updGender(newgend); } else if (skipunin == "birth" || skipunin == "b") { int nytt; cout << "Enter updated year of birth for " << data[persNR].getNafn() << ": "; cin >> nytt; data[persNR].updFaedingarar(nytt); } else if (skipunin == "death" || skipunin == "d") { int nytt; cout << "Enter updated year of death for " << data[persNR].getNafn() << ": "; cin >> nytt; data[persNR].updDanarar(nytt); } refreshTxtFile(data); } void NotendaUI::searchOptions() { system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||name - Search by name, please write 'name' ||*" << endl; cout << "*||age - Search by age, please write 'age' ||*" << endl; cout << "*||birth - Search by year of birth, please write 'birth' ||*" << endl; cout << "*||death - Search by year of death, please write 'death' ||*" << endl; cout << "*==================================================================*" << endl; } void NotendaUI::printList() { cout << "----------------------------------------------------------------------------------------------------------" << endl; cout << "|Scientist ID \t |Name \t\t\t\t |Gender \t |Year of Birth |Year of death |Age \t |" << endl; cout << "----------------------------------------------------------------------------------------------------------" << endl; vector<tolvufolk> data = _service.getTolvufolk(false); for (size_t i = 0; i < data.size(); i++) { cout << "|" << i + 1 << " \t\t "; cout << data[i]; /* cout << "Scientist number: " << i + 1 << endl; cout << data[i] << endl; */ } cout << "----------------------------------------------------------------------------------------------------------" << endl; } void NotendaUI::searchName(const vector<tolvufolk>& data) { searchOptions(); string skipunin; cin >> skipunin; if (skipunin == "name" || skipunin == "n") { searchOptions(); string nafn; cout << "Name to search: "; cin.ignore(); getline(cin,nafn); cout << endl; for(size_t i = 0; i < data.size(); i++) { if (nafn == data[i].getNafn() ) { cout << data[i]; } } cout << endl; } else if (skipunin == "age" || skipunin == "a") { searchOptions(); int age; cout << "Age to search: "; cin >> age; cout << endl; for(size_t i = 0; i < data.size(); i++) { if (age == (data[i].getDanarar() - data[i].getFaedingarar() ) ) { cout << data[i]; } } cout << endl; } else if (skipunin == "birth" || skipunin == "b") { searchOptions(); int birth; cout << "Year of birth to search: "; cin >> birth; cout << endl; for(size_t i = 0; i < data.size(); i++) { if (birth == data[i].getFaedingarar() ) { cout << data[i]; } } cout << endl; } else if (skipunin == "death" || skipunin == "d") { searchOptions(); int death; cout << "Year of birth to search: "; cin >> death; cout << endl; for(size_t i = 0; i < data.size(); i++) { if (death == data[i].getDanarar() ) { cout << data[i]; } } cout << endl; } } void NotendaUI::sortOptions() { string skipunin; system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||name - Sort by name, please write 'name' ||*" << endl; cout << "*||age - Sort by age, please write 'age' ||*" << endl; cout << "*||birth - Sort by year of birth, please write 'birth' ||*" << endl; cout << "*||death - Sort by year of death, please write 'death' ||*" << endl; cout << "*==================================================================*" << endl; cin >> skipunin; if (skipunin == "name" || skipunin == "n") { system("cls"); cout << "*==================================================================*" << endl; cout << "*||Please enter one the following command ||*" << endl; cout << "*==================================================================*" << endl; cout << "*||ascending - Sort names by ascending order ||*" << endl; cout << "*||descending - Sort names by descending order ||*" << endl; cout << "*==================================================================*" << endl; cin >> skipunin; if(skipunin == "ascending" || skipunin == "a") { _service.sortByAscending(); printList(); } else if(skipunin == "descending" || skipunin == "d") { _service.sortByDescending(); printList(); } } } void NotendaUI::addPerson() { string firstName; string lastName; string gGender; int bYear; int dYear; cout << "Enter firstname: "; cin >> firstName; cout << "Enter lastname: "; cin >> lastName; cout << "Enter gender(kk/kvk) [lowercase]: "; cin >> gGender; while (gGender != "kk" && gGender != "kvk") { cerr << "Input not valid, try again: "; cin >> gGender; } cout << "Enter year of birth: "; cin >> bYear; while (0 > bYear) { cerr << "Input not valid, try again: "; cin >> bYear; } cout << "Enter year of death(-1 if still alive): "; cin >> dYear; while (-1 > dYear) { cerr << "Input not valid, try again: "; cin >> dYear; cout << endl; } cout << endl; _service.addTolvufolk(tolvufolk(firstName + " " + lastName, gGender, bYear, dYear)); } void NotendaUI::deletePerson() { system("cls"); printList(); int persNR; cout << "Delete scientist number: "; cin >> persNR; persNR--; _service.deleteSingleTolvufolk(persNR); } void NotendaUI::purgeList(vector<tolvufolk> &data) { string skipun; cout << "By the Emperor, are you sure? (Y/N): "; cin >> skipun; if (skipun == "Y" || skipun == "y") { cout << "Are you really sure? This will EXTERMINATE ALL ENTRIES. (Y/N): "; cin >> skipun; if (skipun == "Y" || skipun == "y") { cout << "Acknowledged, by your will, all ENTRIES will be EXTERMINATED." << endl; data.clear(); refreshTxtFile(data); continueUI(); } else { cout << "Purge canceled." << endl; continueUI(); } } else { cout << "Purge canceled." << endl; continueUI(); } } void NotendaUI::refreshTxtFile(const vector<tolvufolk>& data) { _service.deleteTolvufolk(); for(size_t i = 0; i < data.size(); i++) { _service.appendTolvufolk(data[i]); } } void NotendaUI::continueUI() { string answer; cout << "Continue? (Y/N): "; cin >> answer; while (answer != "Y" || answer != "y" || answer != "N" || answer != "n") if (answer == "Y" || answer == "y") { skrifaUt(); check = false; } else if(answer == "N" || answer == "n") { check = true; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "poll_manager.h" #include "de_web_plugin_private.h" /*! Constructor. */ PollManager::PollManager(QObject *parent) : QObject(parent) { pollState = StateIdle; timer = new QTimer(this); timer->setSingleShot(true); connect(timer, SIGNAL(timeout()), this, SLOT(pollTimerFired())); plugin = qobject_cast<DeRestPluginPrivate*>(parent); } /*! Queues polling of the node. \param restNode - the node to poll */ void PollManager::poll(RestNodeBase *restNode, const QDateTime &tStart) { Resource *r = dynamic_cast<Resource*>(restNode); DBG_Assert(r); if (!r || !restNode->node()) { return; } PollItem pitem; if (!restNode->node()->nodeDescriptor().receiverOnWhenIdle()) { return; } LightNode *lightNode = nullptr; Sensor *sensor = nullptr; if (r->prefix() == RLights) { lightNode = static_cast<LightNode*>(restNode); DBG_Assert(lightNode); pitem.endpoint = lightNode->haEndpoint().endpoint(); DBG_Printf(DBG_INFO_L2, ">>>> Poll light node %s\n", qPrintable(lightNode->name())); } else if (r->prefix() == RSensors) { sensor = static_cast<Sensor*>(restNode); DBG_Assert(sensor); pitem.endpoint = sensor->fingerPrint().endpoint; DBG_Printf(DBG_INFO_L2, ">>>> Poll %s sensor node %s\n", qPrintable(sensor->type()), qPrintable(sensor->name())); } else { return; } pitem.id = restNode->id(); pitem.prefix = r->prefix(); pitem.address = restNode->address(); pitem.tStart = tStart; for (int i = 0; i < r->itemCount(); i++) { const ResourceItem *item = r->itemForIndex(i); const char *suffix = item ? item->descriptor().suffix : nullptr; if (suffix == RStateOn || suffix == RStateBri || suffix == RStateColorMode || (suffix == RStateConsumption && sensor && sensor->type() == QLatin1String("ZHAConsumption")) || (suffix == RStatePower && sensor && sensor->type() == QLatin1String("ZHAPower")) || (suffix == RStatePresence && sensor && sensor->type() == QLatin1String("ZHAPresence")) || (suffix == RStateLightLevel && sensor && sensor->type() == QLatin1String("ZHALightLevel")) || suffix == RAttrModelId || suffix == RAttrSwVersion) { // DBG_Printf(DBG_INFO_L2, " attribute %s\n", suffix); pitem.items.push_back(suffix); } } for (PollItem &i : items) { if (i.prefix == r->prefix() && i.id == restNode->id()) { i.items = pitem.items; // update if (tStart.isValid()) { i.tStart = tStart; } return; } } items.push_back(pitem); if (!timer->isActive()) { timer->start(1); } } /*! Delays polling for \p ms milliseconds. */ void PollManager::delay(int ms) { timer->stop(); timer->start(ms); } /*! Handle APS confirm if related to polling. */ void PollManager::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf) { if (pollState != StateWait) { return; } if (apsReqId != conf.id()) { return; } if (dstAddr.hasExt() && conf.dstAddress().hasExt() && dstAddr.ext() != conf.dstAddress().ext()) { } else if (dstAddr.hasNwk() && conf.dstAddress().hasNwk() && dstAddr.nwk() != conf.dstAddress().nwk()) { } DBG_Printf(DBG_INFO_L2, "Poll APS confirm %u status: 0x%02X\n", conf.id(), conf.status()); pollState = StateIdle; timer->stop(); timer->start(1); } /*! Timer callback to proceed polling. */ void PollManager::pollTimerFired() { if (pollState == StateWait) { DBG_Printf(DBG_INFO, "timeout on poll APS confirm\n"); pollState = StateIdle; } DBG_Assert(pollState == StateIdle); if (items.empty()) { return; } QDateTime now = QDateTime::currentDateTime(); PollItem &pitem = items.front(); Resource *r = plugin->getResource(pitem.prefix, pitem.id); ResourceItem *item = nullptr; RestNodeBase *restNode = nullptr; const LightNode *lightNode = nullptr; if (r && r->prefix() == RLights) { restNode = plugin->getLightNodeForId(pitem.id); lightNode = static_cast<LightNode*>(restNode); item = r->item(RStateReachable); } else if (r && r->prefix() == RSensors) { restNode = plugin->getSensorNodeForId(pitem.id); item = r->item(RConfigReachable); } if (pitem.tStart.isValid() && pitem.tStart > now) { if (items.size() > 1) { PollItem tmp = pitem; items.front() = items.back(); items.back() = tmp; } timer->start(1); return; } if (!r || pitem.items.empty() || !restNode || //!restNode->lastRx().isValid() || !item || !item->toBool()) // not reachable { items.front() = items.back(); items.pop_back(); timer->start(1); return; } const auto dtReachable = item->lastSet().secsTo(now); quint16 clusterId = 0xffff; // invalid std::vector<quint16> attributes; item = r->item(RStateOn); bool isOn = item ? item->toBool() : false; const char *&suffix = pitem.items[0]; for (size_t i = 0; pitem.items[0] == nullptr && i < pitem.items.size(); i++) { if (pitem.items[i] != nullptr) { pitem.items[0] = pitem.items[i]; // move to front pitem.items[i] = nullptr; // clear break; } } if (!suffix) { pitem.items.clear(); // all done } if (suffix == RStateOn) { if (lightNode && lightNode->manufacturerCode() != VENDOR_115F) // reports { clusterId = ONOFF_CLUSTER_ID; attributes.push_back(0x0000); // onOff } } else if (suffix == RStateBri && isOn) { NodeValue &val = restNode->getZclValue(LEVEL_CLUSTER_ID, 0x0000); if (isOn || !val.timestamp.isValid()) { clusterId = LEVEL_CLUSTER_ID; attributes.push_back(0x0000); // current level } } else if (suffix == RStateColorMode && lightNode) { clusterId = COLOR_CLUSTER_ID; item = r->item(RConfigColorCapabilities); if (!item || item->toNumber() <= 0) { attributes.push_back(0x0008); // color mode attributes.push_back(0x4001); // enhanced color mode attributes.push_back(0x400a); // color capabilities attributes.push_back(0x400b); // color temperature min attributes.push_back(0x400c); // color temperature max } else { quint16 cap = item->toNumber(); std::vector<quint16> toCheck; if (cap & 0x0002) // enhanced hue supported { toCheck.push_back(0x4001); // enhanced color mode toCheck.push_back(0x4000); // enhanced hue toCheck.push_back(0x0001); // saturation } else if (cap & 0x0001) { toCheck.push_back(0x0000); // hue toCheck.push_back(0x0001); // saturation toCheck.push_back(0x0008); // color mode } else { toCheck.push_back(0x0008); // color mode } if (cap & 0x0004) { toCheck.push_back(0x4002); // Color loop active } if (cap & 0x0008) { toCheck.push_back(0x0003); // currentX toCheck.push_back(0x0004); // currentY } if (cap & 0x0010) { toCheck.push_back(0x0007); // color temperature } for (const deCONZ::ZclCluster &cl : lightNode->haEndpoint().inClusters()) { if (cl.id() != COLOR_CLUSTER_ID) { continue; } for (const deCONZ::ZclAttribute &attr : cl.attributes()) { for (quint16 attrId : toCheck) { // discard attributes which are not be available if (attrId == attr.id() && attr.isAvailable()) { NodeValue &val = restNode->getZclValue(clusterId, attrId); if (isOn || !val.timestamp.isValid()) { attributes.push_back(attrId); } } } } break; } } } else if (suffix == RStatePresence) { clusterId = OCCUPANCY_SENSING_CLUSTER_ID; attributes.push_back(0x0000); // Occupancy attributes.push_back(0x0010); // PIR Occupied To Unoccupied Delay } else if (suffix == RStateLightLevel) { clusterId = ILLUMINANCE_MEASUREMENT_CLUSTER_ID; attributes.push_back(0x0000); // Measured Value } else if (suffix == RStateConsumption) { clusterId = METERING_CLUSTER_ID; attributes.push_back(0x0000); // Curent Summation Delivered attributes.push_back(0x0400); // Instantaneous Demand } else if (suffix == RStatePower) { clusterId = ELECTRICAL_MEASUREMENT_CLUSTER_ID; attributes.push_back(0x050b); // Active Power item = r->item(RAttrModelId); if (! item->toString().startsWith(QLatin1String("Plug"))) // OSRAM plug { attributes.push_back(0x0505); // RMS Voltage attributes.push_back(0x0508); // RMS Current } } else if (suffix == RAttrModelId) { item = r->item(RAttrModelId); if (item && (item->toString().isEmpty() || item->toString() == QLatin1String("unknown") || (item->lastSet().secsTo(now) > READ_MODEL_ID_INTERVAL && item->toString().startsWith("FLS-A")) // dynamic model ids )) { clusterId = BASIC_CLUSTER_ID; //attributes.push_back(0x0004); // manufacturer attributes.push_back(0x0005); // model id } } else if (suffix == RAttrSwVersion && lightNode) { item = r->item(RAttrSwVersion); if (item && (item->toString().isEmpty() || (item->lastSet().secsTo(now) > READ_SWBUILD_ID_INTERVAL))) // dynamic { clusterId = BASIC_CLUSTER_ID; if (lightNode->manufacturerCode() == VENDOR_UBISYS || lightNode->manufacturerCode() == VENDOR_EMBER || lightNode->manufacturerCode() == VENDOR_120B || lightNode->manufacturerCode() == VENDOR_115F || lightNode->manufacturer().startsWith(QLatin1String("Climax"))) { attributes.push_back(0x0006); // date code } else { attributes.push_back(0x4000); // sw build id } } } size_t fresh = 0; const int reportWaitTime = 360; for (quint16 attrId : attributes) { // force polling after node becomes reachable, since reporting might not be active if (dtReachable < reportWaitTime) { break; } NodeValue &val = restNode->getZclValue(clusterId, attrId); if (val.timestampLastReport.isValid() && val.timestampLastReport.secsTo(now) < reportWaitTime) { fresh++; } } // check that cluster exists on endpoint if (clusterId != 0xffff) { bool found = false; deCONZ::SimpleDescriptor sd; if (restNode->node()->copySimpleDescriptor(pitem.endpoint, &sd) == 0) { for (const auto &cl : sd.inClusters()) { if (cl.id() == clusterId) { found = true; break; } } } if (!found) { DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped, cluster doesn't exist\n", pitem.address.ext(), clusterId); clusterId = 0xffff; } } if (clusterId != 0xffff && fresh > 0 && fresh == attributes.size()) { DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped, values are fresh enough\n", pitem.address.ext(), clusterId); suffix = nullptr; // clear timer->start(100); } else if (!attributes.empty() && clusterId != 0xffff && plugin->readAttributes(restNode, pitem.endpoint, clusterId, attributes)) { pollState = StateWait; // TODO this hack to get aps request id DBG_Assert(plugin->tasks.back().taskType == TaskReadAttributes); apsReqId = plugin->tasks.back().req.id(); dstAddr = pitem.address; timer->start(60 * 1000); // wait for confirm suffix = nullptr; // clear DBG_Printf(DBG_INFO_L2, "Poll APS request %u to 0x%016llX cluster: 0x%04X\n", apsReqId, dstAddr.ext(), clusterId); } else if (suffix) { suffix = nullptr; // clear timer->start(100); } else { if (clusterId != 0xffff) { DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped\n", pitem.address.ext(), clusterId); } timer->start(100); items.front() = items.back(); items.pop_back(); } } <commit_msg>Don't repeadedly static datecode and sw build id<commit_after>/* * Copyright (c) 2017-2018 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "poll_manager.h" #include "de_web_plugin_private.h" /*! Constructor. */ PollManager::PollManager(QObject *parent) : QObject(parent) { pollState = StateIdle; timer = new QTimer(this); timer->setSingleShot(true); connect(timer, SIGNAL(timeout()), this, SLOT(pollTimerFired())); plugin = qobject_cast<DeRestPluginPrivate*>(parent); } /*! Queues polling of the node. \param restNode - the node to poll */ void PollManager::poll(RestNodeBase *restNode, const QDateTime &tStart) { Resource *r = dynamic_cast<Resource*>(restNode); DBG_Assert(r); if (!r || !restNode->node()) { return; } PollItem pitem; if (!restNode->node()->nodeDescriptor().receiverOnWhenIdle()) { return; } LightNode *lightNode = nullptr; Sensor *sensor = nullptr; if (r->prefix() == RLights) { lightNode = static_cast<LightNode*>(restNode); DBG_Assert(lightNode); pitem.endpoint = lightNode->haEndpoint().endpoint(); DBG_Printf(DBG_INFO_L2, ">>>> Poll light node %s\n", qPrintable(lightNode->name())); } else if (r->prefix() == RSensors) { sensor = static_cast<Sensor*>(restNode); DBG_Assert(sensor); pitem.endpoint = sensor->fingerPrint().endpoint; DBG_Printf(DBG_INFO_L2, ">>>> Poll %s sensor node %s\n", qPrintable(sensor->type()), qPrintable(sensor->name())); } else { return; } pitem.id = restNode->id(); pitem.prefix = r->prefix(); pitem.address = restNode->address(); pitem.tStart = tStart; for (int i = 0; i < r->itemCount(); i++) { const ResourceItem *item = r->itemForIndex(i); const char *suffix = item ? item->descriptor().suffix : nullptr; if (suffix == RStateOn || suffix == RStateBri || suffix == RStateColorMode || (suffix == RStateConsumption && sensor && sensor->type() == QLatin1String("ZHAConsumption")) || (suffix == RStatePower && sensor && sensor->type() == QLatin1String("ZHAPower")) || (suffix == RStatePresence && sensor && sensor->type() == QLatin1String("ZHAPresence")) || (suffix == RStateLightLevel && sensor && sensor->type() == QLatin1String("ZHALightLevel")) || suffix == RAttrModelId || suffix == RAttrSwVersion) { // DBG_Printf(DBG_INFO_L2, " attribute %s\n", suffix); pitem.items.push_back(suffix); } } for (PollItem &i : items) { if (i.prefix == r->prefix() && i.id == restNode->id()) { i.items = pitem.items; // update if (tStart.isValid()) { i.tStart = tStart; } return; } } items.push_back(pitem); if (!timer->isActive()) { timer->start(1); } } /*! Delays polling for \p ms milliseconds. */ void PollManager::delay(int ms) { timer->stop(); timer->start(ms); } /*! Handle APS confirm if related to polling. */ void PollManager::apsdeDataConfirm(const deCONZ::ApsDataConfirm &conf) { if (pollState != StateWait) { return; } if (apsReqId != conf.id()) { return; } if (dstAddr.hasExt() && conf.dstAddress().hasExt() && dstAddr.ext() != conf.dstAddress().ext()) { } else if (dstAddr.hasNwk() && conf.dstAddress().hasNwk() && dstAddr.nwk() != conf.dstAddress().nwk()) { } DBG_Printf(DBG_INFO_L2, "Poll APS confirm %u status: 0x%02X\n", conf.id(), conf.status()); pollState = StateIdle; timer->stop(); timer->start(1); } /*! Timer callback to proceed polling. */ void PollManager::pollTimerFired() { if (pollState == StateWait) { DBG_Printf(DBG_INFO, "timeout on poll APS confirm\n"); pollState = StateIdle; } DBG_Assert(pollState == StateIdle); if (items.empty()) { return; } QDateTime now = QDateTime::currentDateTime(); PollItem &pitem = items.front(); Resource *r = plugin->getResource(pitem.prefix, pitem.id); ResourceItem *item = nullptr; RestNodeBase *restNode = nullptr; const LightNode *lightNode = nullptr; if (r && r->prefix() == RLights) { restNode = plugin->getLightNodeForId(pitem.id); lightNode = static_cast<LightNode*>(restNode); item = r->item(RStateReachable); } else if (r && r->prefix() == RSensors) { restNode = plugin->getSensorNodeForId(pitem.id); item = r->item(RConfigReachable); } if (pitem.tStart.isValid() && pitem.tStart > now) { if (items.size() > 1) { PollItem tmp = pitem; items.front() = items.back(); items.back() = tmp; } timer->start(1); return; } if (!r || pitem.items.empty() || !restNode || //!restNode->lastRx().isValid() || !item || !item->toBool()) // not reachable { items.front() = items.back(); items.pop_back(); timer->start(1); return; } const auto dtReachable = item->lastSet().secsTo(now); quint16 clusterId = 0xffff; // invalid std::vector<quint16> attributes; item = r->item(RStateOn); bool isOn = item ? item->toBool() : false; const char *&suffix = pitem.items[0]; for (size_t i = 0; pitem.items[0] == nullptr && i < pitem.items.size(); i++) { if (pitem.items[i] != nullptr) { pitem.items[0] = pitem.items[i]; // move to front pitem.items[i] = nullptr; // clear break; } } if (!suffix) { pitem.items.clear(); // all done } if (suffix == RStateOn) { if (lightNode && lightNode->manufacturerCode() != VENDOR_115F) // reports { clusterId = ONOFF_CLUSTER_ID; attributes.push_back(0x0000); // onOff } } else if (suffix == RStateBri && isOn) { NodeValue &val = restNode->getZclValue(LEVEL_CLUSTER_ID, 0x0000); if (isOn || !val.timestamp.isValid()) { clusterId = LEVEL_CLUSTER_ID; attributes.push_back(0x0000); // current level } } else if (suffix == RStateColorMode && lightNode) { clusterId = COLOR_CLUSTER_ID; item = r->item(RConfigColorCapabilities); if (!item || item->toNumber() <= 0) { attributes.push_back(0x0008); // color mode attributes.push_back(0x4001); // enhanced color mode attributes.push_back(0x400a); // color capabilities attributes.push_back(0x400b); // color temperature min attributes.push_back(0x400c); // color temperature max } else { quint16 cap = item->toNumber(); std::vector<quint16> toCheck; if (cap & 0x0002) // enhanced hue supported { toCheck.push_back(0x4001); // enhanced color mode toCheck.push_back(0x4000); // enhanced hue toCheck.push_back(0x0001); // saturation } else if (cap & 0x0001) { toCheck.push_back(0x0000); // hue toCheck.push_back(0x0001); // saturation toCheck.push_back(0x0008); // color mode } else { toCheck.push_back(0x0008); // color mode } if (cap & 0x0004) { toCheck.push_back(0x4002); // Color loop active } if (cap & 0x0008) { toCheck.push_back(0x0003); // currentX toCheck.push_back(0x0004); // currentY } if (cap & 0x0010) { toCheck.push_back(0x0007); // color temperature } for (const deCONZ::ZclCluster &cl : lightNode->haEndpoint().inClusters()) { if (cl.id() != COLOR_CLUSTER_ID) { continue; } for (const deCONZ::ZclAttribute &attr : cl.attributes()) { for (quint16 attrId : toCheck) { // discard attributes which are not be available if (attrId == attr.id() && attr.isAvailable()) { NodeValue &val = restNode->getZclValue(clusterId, attrId); if (isOn || !val.timestamp.isValid()) { attributes.push_back(attrId); } } } } break; } } } else if (suffix == RStatePresence) { clusterId = OCCUPANCY_SENSING_CLUSTER_ID; attributes.push_back(0x0000); // Occupancy attributes.push_back(0x0010); // PIR Occupied To Unoccupied Delay } else if (suffix == RStateLightLevel) { clusterId = ILLUMINANCE_MEASUREMENT_CLUSTER_ID; attributes.push_back(0x0000); // Measured Value } else if (suffix == RStateConsumption) { clusterId = METERING_CLUSTER_ID; attributes.push_back(0x0000); // Curent Summation Delivered attributes.push_back(0x0400); // Instantaneous Demand } else if (suffix == RStatePower) { clusterId = ELECTRICAL_MEASUREMENT_CLUSTER_ID; attributes.push_back(0x050b); // Active Power item = r->item(RAttrModelId); if (! item->toString().startsWith(QLatin1String("Plug"))) // OSRAM plug { attributes.push_back(0x0505); // RMS Voltage attributes.push_back(0x0508); // RMS Current } } else if (suffix == RAttrModelId) { item = r->item(RAttrModelId); if (item && (item->toString().isEmpty() || item->toString() == QLatin1String("unknown") || (item->lastSet().secsTo(now) > READ_MODEL_ID_INTERVAL && item->toString().startsWith("FLS-A")) // dynamic model ids )) { clusterId = BASIC_CLUSTER_ID; //attributes.push_back(0x0004); // manufacturer attributes.push_back(0x0005); // model id } } else if (suffix == RAttrSwVersion && lightNode) { item = r->item(RAttrSwVersion); if (item && (item->toString().isEmpty() || (item->lastSet().secsTo(now) > READ_SWBUILD_ID_INTERVAL))) // dynamic { if (lightNode->manufacturerCode() == VENDOR_UBISYS || lightNode->manufacturerCode() == VENDOR_EMBER || lightNode->manufacturerCode() == VENDOR_120B || lightNode->manufacturerCode() == VENDOR_115F || lightNode->manufacturer().startsWith(QLatin1String("Climax"))) { if (item->toString().isEmpty()) { attributes.push_back(0x0006); // date code clusterId = BASIC_CLUSTER_ID; } } else { if (item->toString().isEmpty() || lightNode->manufacturerCode() == VENDOR_XAL || lightNode->manufacturerCode() == VENDOR_DDEL) { attributes.push_back(0x4000); // sw build id clusterId = BASIC_CLUSTER_ID; } } } } size_t fresh = 0; const int reportWaitTime = 360; for (quint16 attrId : attributes) { // force polling after node becomes reachable, since reporting might not be active if (dtReachable < reportWaitTime) { break; } NodeValue &val = restNode->getZclValue(clusterId, attrId); if (val.timestampLastReport.isValid() && val.timestampLastReport.secsTo(now) < reportWaitTime) { fresh++; } } // check that cluster exists on endpoint if (clusterId != 0xffff) { bool found = false; deCONZ::SimpleDescriptor sd; if (restNode->node()->copySimpleDescriptor(pitem.endpoint, &sd) == 0) { for (const auto &cl : sd.inClusters()) { if (cl.id() == clusterId) { found = true; break; } } } if (!found) { DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped, cluster doesn't exist\n", pitem.address.ext(), clusterId); clusterId = 0xffff; } } if (clusterId != 0xffff && fresh > 0 && fresh == attributes.size()) { DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped, values are fresh enough\n", pitem.address.ext(), clusterId); suffix = nullptr; // clear timer->start(100); } else if (!attributes.empty() && clusterId != 0xffff && plugin->readAttributes(restNode, pitem.endpoint, clusterId, attributes)) { pollState = StateWait; // TODO this hack to get aps request id DBG_Assert(plugin->tasks.back().taskType == TaskReadAttributes); apsReqId = plugin->tasks.back().req.id(); dstAddr = pitem.address; timer->start(60 * 1000); // wait for confirm suffix = nullptr; // clear DBG_Printf(DBG_INFO_L2, "Poll APS request %u to 0x%016llX cluster: 0x%04X\n", apsReqId, dstAddr.ext(), clusterId); } else if (suffix) { suffix = nullptr; // clear timer->start(100); } else { if (clusterId != 0xffff) { DBG_Printf(DBG_INFO, "Poll APS request to 0x%016llX cluster: 0x%04X dropped\n", pitem.address.ext(), clusterId); } timer->start(100); items.front() = items.back(); items.pop_back(); } } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUITreeItem.cpp created: 5-13-07 author: Jonathan Welch (Based on Code by David Durant) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/widgets/Tree.h" #include "CEGUI/widgets/TreeItem.h" #include "CEGUI/System.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Image.h" #include "CEGUI/FontManager.h" #include "CEGUI/Font.h" #include "CEGUI/Window.h" #include <algorithm> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUI/FribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUI/MinibidiVisualMapping.h" #else #include "CEGUI/BidiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// BasicRenderedStringParser TreeItem::d_stringParser; /************************************************************************* Constants *************************************************************************/ const Colour TreeItem::DefaultSelectionColour = 0xFF4444AA; const Colour TreeItem::DefaultTextColour = 0xFFFFFFFF; /************************************************************************* Base class constructor *************************************************************************/ TreeItem::TreeItem(const String& text, uint item_id, void* item_data, bool disabled, bool auto_delete) : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_itemID(item_id), d_itemData(item_data), d_selected(false), d_disabled(disabled), d_autoDelete(auto_delete), d_buttonLocation(Rectf(0, 0, 0, 0)), d_owner(0), d_selectCols(DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour), d_selectBrush(0), d_textCols(DefaultTextColour, DefaultTextColour, DefaultTextColour, DefaultTextColour), d_font(0), d_iconImage(0), d_isOpen(false), d_renderedStringValid(false) { setText(text); } //----------------------------------------------------------------------------// TreeItem::~TreeItem(void) { CEGUI_DELETE_AO d_bidiVisualMapping; } /************************************************************************* Set the selection highlighting brush image. *************************************************************************/ void TreeItem::setSelectionBrushImage(const String& name) { setSelectionBrushImage( &ImageManager::getSingleton().get(name)); } /************************************************************************* Return a ColourRect object describing the colours in 'cols' after having their alpha component modulated by the value 'alpha'. *************************************************************************/ ColourRect TreeItem::getModulateAlphaColourRect(const ColourRect& cols, float alpha) const { return ColourRect ( calculateModulatedAlphaColour(cols.d_top_left, alpha), calculateModulatedAlphaColour(cols.d_top_right, alpha), calculateModulatedAlphaColour(cols.d_bottom_left, alpha), calculateModulatedAlphaColour(cols.d_bottom_right, alpha) ); } /************************************************************************* Return a colour value describing the colour specified by 'col' after having its alpha component modulated by the value 'alpha'. *************************************************************************/ Colour TreeItem::calculateModulatedAlphaColour(Colour col, float alpha) const { Colour temp(col); temp.setAlpha(temp.getAlpha() * alpha); return temp; } /************************************************************************* Return a pointer to the font being used by this TreeItem *************************************************************************/ const Font* TreeItem::getFont(void) const { // prefer out own font if (d_font != 0) return d_font; // try our owner window's font setting // (may be null if owner uses non existant default font) else if (d_owner != 0) return d_owner->getFont(); // no owner, just use the default (which may be NULL anyway) else return System::getSingleton().getDefaultFont(); } /************************************************************************* Set the font to be used by this TreeItem *************************************************************************/ void TreeItem::setFont(const String& font_name) { setFont(&FontManager::getSingleton().get(font_name)); } //----------------------------------------------------------------------------// void TreeItem::setFont(const Font* font) { d_font = font; d_renderedStringValid = false; } //----------------------------------------------------------------------------// /************************************************************************* Return the rendered pixel size of this tree item. *************************************************************************/ Sizef TreeItem::getPixelSize(void) const { const Font* fnt = getFont(); if (!fnt) return Sizef(0, 0); if (!d_renderedStringValid) parseTextString(); Sizef sz(0.0f, 0.0f); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { const Sizef line_sz(d_renderedString.getPixelSize(i)); sz.d_height += line_sz.d_height; if (line_sz.d_width > sz.d_width) sz.d_width = line_sz.d_width; } return sz; } /************************************************************************* Add the given TreeItem to this item's list. *************************************************************************/ void TreeItem::addItem(TreeItem* item) { if (item != 0) { Tree* parentWindow = (Tree*)getOwnerWindow(); // establish ownership item->setOwnerWindow(parentWindow); // if sorting is enabled, re-sort the tree if (parentWindow->isSortEnabled()) { d_listItems.insert( std::upper_bound(d_listItems.begin(), d_listItems.end(), item, &lbi_less), item); } // not sorted, just stick it on the end. else { d_listItems.push_back(item); } WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } /************************************************************************* Remove the given TreeItem from this item's list. *************************************************************************/ void TreeItem::removeItem(const TreeItem* item) { if (item) { Tree* parentWindow = (Tree*)getOwnerWindow(); LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); if (pos != d_listItems.end()) { (*pos)->setOwnerWindow(0); d_listItems.erase(pos); if (item == parentWindow->d_lastSelected) parentWindow->d_lastSelected = 0; if (item->isAutoDeleted()) CEGUI_DELETE_AO item; WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } } TreeItem *TreeItem::getTreeItemFromIndex(size_t itemIndex) { if (itemIndex > d_listItems.size()) return 0; return d_listItems[itemIndex]; } /************************************************************************* Draw the tree item in its current state. *************************************************************************/ void TreeItem::draw(GeometryBuffer& buffer, const Rectf& targetRect, float alpha, const Rectf* clipper) const { Rectf finalRect(targetRect); if (d_iconImage != 0) { Rectf finalPos(finalRect); finalPos.setWidth(targetRect.getHeight()); finalPos.setHeight(targetRect.getHeight()); d_iconImage->render(buffer, finalPos, clipper, ColourRect(Colour(1,1,1,alpha))); finalRect.d_min.d_x += targetRect.getHeight(); } if (d_selected && d_selectBrush != 0) d_selectBrush->render(buffer, finalRect, clipper, getModulateAlphaColourRect(d_selectCols, alpha)); const Font* font = getFont(); if (!font) return; Vector2f draw_pos(finalRect.getPosition()); draw_pos.d_y -= (font->getLineSpacing() - font->getBaseline()) * 0.5f; if (!d_renderedStringValid) parseTextString(); const ColourRect final_colours( getModulateAlphaColourRect(ColourRect(0xFFFFFFFF), alpha)); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { d_renderedString.draw(i, buffer, draw_pos, &final_colours, clipper, 0.0f); draw_pos.d_y += d_renderedString.getPixelSize(i).d_height; } } /************************************************************************* Set the colours used for selection highlighting. *************************************************************************/ void TreeItem::setSelectionColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_selectCols.d_top_left = top_left_colour; d_selectCols.d_top_right = top_right_colour; d_selectCols.d_bottom_left = bottom_left_colour; d_selectCols.d_bottom_right = bottom_right_colour; } /************************************************************************* Set the colours used for text rendering. *************************************************************************/ void TreeItem::setTextColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_textCols.d_top_left = top_left_colour; d_textCols.d_top_right = top_right_colour; d_textCols.d_bottom_left = bottom_left_colour; d_textCols.d_bottom_right = bottom_right_colour; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::setText( const String& text ) { d_textLogical = text; d_bidiDataValid = false; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::parseTextString() const { d_renderedString = d_stringParser.parse(getTextVisual(), const_cast<Font*>(getFont()), &d_textCols); d_renderedStringValid = true; } //----------------------------------------------------------------------------// const String& TreeItem::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>Auto delete tree item's children upon destruction<commit_after>/*********************************************************************** filename: CEGUITreeItem.cpp created: 5-13-07 author: Jonathan Welch (Based on Code by David Durant) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/widgets/Tree.h" #include "CEGUI/widgets/TreeItem.h" #include "CEGUI/System.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Image.h" #include "CEGUI/FontManager.h" #include "CEGUI/Font.h" #include "CEGUI/Window.h" #include <algorithm> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUI/FribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUI/MinibidiVisualMapping.h" #else #include "CEGUI/BidiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// BasicRenderedStringParser TreeItem::d_stringParser; /************************************************************************* Constants *************************************************************************/ const Colour TreeItem::DefaultSelectionColour = 0xFF4444AA; const Colour TreeItem::DefaultTextColour = 0xFFFFFFFF; /************************************************************************* Base class constructor *************************************************************************/ TreeItem::TreeItem(const String& text, uint item_id, void* item_data, bool disabled, bool auto_delete) : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_itemID(item_id), d_itemData(item_data), d_selected(false), d_disabled(disabled), d_autoDelete(auto_delete), d_buttonLocation(Rectf(0, 0, 0, 0)), d_owner(0), d_selectCols(DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour), d_selectBrush(0), d_textCols(DefaultTextColour, DefaultTextColour, DefaultTextColour, DefaultTextColour), d_font(0), d_iconImage(0), d_isOpen(false), d_renderedStringValid(false) { setText(text); } //----------------------------------------------------------------------------// TreeItem::~TreeItem(void) { // delete any items we are supposed to for (size_t i = 0; i < getItemCount(); ++i) { // if item is supposed to be deleted by us if (d_listItems[i]->isAutoDeleted()) { // clean up this item. CEGUI_DELETE_AO d_listItems[i]; } } CEGUI_DELETE_AO d_bidiVisualMapping; } /************************************************************************* Set the selection highlighting brush image. *************************************************************************/ void TreeItem::setSelectionBrushImage(const String& name) { setSelectionBrushImage( &ImageManager::getSingleton().get(name)); } /************************************************************************* Return a ColourRect object describing the colours in 'cols' after having their alpha component modulated by the value 'alpha'. *************************************************************************/ ColourRect TreeItem::getModulateAlphaColourRect(const ColourRect& cols, float alpha) const { return ColourRect ( calculateModulatedAlphaColour(cols.d_top_left, alpha), calculateModulatedAlphaColour(cols.d_top_right, alpha), calculateModulatedAlphaColour(cols.d_bottom_left, alpha), calculateModulatedAlphaColour(cols.d_bottom_right, alpha) ); } /************************************************************************* Return a colour value describing the colour specified by 'col' after having its alpha component modulated by the value 'alpha'. *************************************************************************/ Colour TreeItem::calculateModulatedAlphaColour(Colour col, float alpha) const { Colour temp(col); temp.setAlpha(temp.getAlpha() * alpha); return temp; } /************************************************************************* Return a pointer to the font being used by this TreeItem *************************************************************************/ const Font* TreeItem::getFont(void) const { // prefer out own font if (d_font != 0) return d_font; // try our owner window's font setting // (may be null if owner uses non existant default font) else if (d_owner != 0) return d_owner->getFont(); // no owner, just use the default (which may be NULL anyway) else return System::getSingleton().getDefaultFont(); } /************************************************************************* Set the font to be used by this TreeItem *************************************************************************/ void TreeItem::setFont(const String& font_name) { setFont(&FontManager::getSingleton().get(font_name)); } //----------------------------------------------------------------------------// void TreeItem::setFont(const Font* font) { d_font = font; d_renderedStringValid = false; } //----------------------------------------------------------------------------// /************************************************************************* Return the rendered pixel size of this tree item. *************************************************************************/ Sizef TreeItem::getPixelSize(void) const { const Font* fnt = getFont(); if (!fnt) return Sizef(0, 0); if (!d_renderedStringValid) parseTextString(); Sizef sz(0.0f, 0.0f); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { const Sizef line_sz(d_renderedString.getPixelSize(i)); sz.d_height += line_sz.d_height; if (line_sz.d_width > sz.d_width) sz.d_width = line_sz.d_width; } return sz; } /************************************************************************* Add the given TreeItem to this item's list. *************************************************************************/ void TreeItem::addItem(TreeItem* item) { if (item != 0) { Tree* parentWindow = (Tree*)getOwnerWindow(); // establish ownership item->setOwnerWindow(parentWindow); // if sorting is enabled, re-sort the tree if (parentWindow->isSortEnabled()) { d_listItems.insert( std::upper_bound(d_listItems.begin(), d_listItems.end(), item, &lbi_less), item); } // not sorted, just stick it on the end. else { d_listItems.push_back(item); } WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } /************************************************************************* Remove the given TreeItem from this item's list. *************************************************************************/ void TreeItem::removeItem(const TreeItem* item) { if (item) { Tree* parentWindow = (Tree*)getOwnerWindow(); LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); if (pos != d_listItems.end()) { (*pos)->setOwnerWindow(0); d_listItems.erase(pos); if (item == parentWindow->d_lastSelected) parentWindow->d_lastSelected = 0; if (item->isAutoDeleted()) CEGUI_DELETE_AO item; WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } } TreeItem *TreeItem::getTreeItemFromIndex(size_t itemIndex) { if (itemIndex > d_listItems.size()) return 0; return d_listItems[itemIndex]; } /************************************************************************* Draw the tree item in its current state. *************************************************************************/ void TreeItem::draw(GeometryBuffer& buffer, const Rectf& targetRect, float alpha, const Rectf* clipper) const { Rectf finalRect(targetRect); if (d_iconImage != 0) { Rectf finalPos(finalRect); finalPos.setWidth(targetRect.getHeight()); finalPos.setHeight(targetRect.getHeight()); d_iconImage->render(buffer, finalPos, clipper, ColourRect(Colour(1,1,1,alpha))); finalRect.d_min.d_x += targetRect.getHeight(); } if (d_selected && d_selectBrush != 0) d_selectBrush->render(buffer, finalRect, clipper, getModulateAlphaColourRect(d_selectCols, alpha)); const Font* font = getFont(); if (!font) return; Vector2f draw_pos(finalRect.getPosition()); draw_pos.d_y -= (font->getLineSpacing() - font->getBaseline()) * 0.5f; if (!d_renderedStringValid) parseTextString(); const ColourRect final_colours( getModulateAlphaColourRect(ColourRect(0xFFFFFFFF), alpha)); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { d_renderedString.draw(i, buffer, draw_pos, &final_colours, clipper, 0.0f); draw_pos.d_y += d_renderedString.getPixelSize(i).d_height; } } /************************************************************************* Set the colours used for selection highlighting. *************************************************************************/ void TreeItem::setSelectionColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_selectCols.d_top_left = top_left_colour; d_selectCols.d_top_right = top_right_colour; d_selectCols.d_bottom_left = bottom_left_colour; d_selectCols.d_bottom_right = bottom_right_colour; } /************************************************************************* Set the colours used for text rendering. *************************************************************************/ void TreeItem::setTextColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_textCols.d_top_left = top_left_colour; d_textCols.d_top_right = top_right_colour; d_textCols.d_bottom_left = bottom_left_colour; d_textCols.d_bottom_right = bottom_right_colour; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::setText( const String& text ) { d_textLogical = text; d_bidiDataValid = false; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::parseTextString() const { d_renderedString = d_stringParser.parse(getTextVisual(), const_cast<Font*>(getFont()), &d_textCols); d_renderedStringValid = true; } //----------------------------------------------------------------------------// const String& TreeItem::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/* * --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Our own set object, to beat Python, at least when computing intersection. */ #ifndef NTA_MATH_SET_HPP #define NTA_MATH_SET_HPP #include <vector> namespace nta { //-------------------------------------------------------------------------------- // SET // // Represents the set with an indicator function stored in a bit array. // // T is an unsigned integral type. // T_byte has the size of a byte. // // Test from Python: // Mac PowerBook 2.8 GHz Core 2 Duo, 10.6.3, -O3 -DNDEBUG, gcc 4.2.1 (Apple 5659) // m = 50000, n1 = 40, n2 = 10000: 0.00274658203125 0.00162267684937 1.69262415516 // m = 50000, n1 = 80, n2 = 10000: 0.00458002090454 0.00179862976074 2.54639448568 // m = 50000, n1 = 200, n2 = 10000: 0.0124213695526 0.00241708755493 5.13898204774 // m = 50000, n1 = 500, n2 = 10000: 0.0339875221252 0.00330281257629 10.2904785967 // m = 50000, n1 = 1000, n2 = 10000: 0.0573344230652 0.00443959236145 12.9143440202 // m = 50000, n1 = 2500, n2 = 10000: 0.155576944351 0.00838160514832 18.5617124164 // m = 50000, n1 = 5000, n2 = 10000: 0.256726026535 0.0143656730652 17.8707969595 //-------------------------------------------------------------------------------- template <typename T =size_t, typename T_byte =unsigned char> class Set { private: T m; // max value of non-zero indices T n; // number of non-zeros in s std::vector<T_byte> s; // indicator of the non-zeros public: // For Python binding inline Set() {} /** * Constructs from a list of n element indices ss, each element being * in the interval [0,m[. */ inline Set(T _m, T _n, T* ss) : m(_m), n(_n), s(m/8 + (m % 8 == 0 ? 0 : 1)) { construct(m, n, ss); } inline void construct(T _m, T _n, T* ss) { m = _m; n = _n; s.resize(m/8 + (m % 8 == 0 ? 0 : 1)); for (T i = 0; i != n; ++i) s[ss[i] / 8] |= 1 << (ss[i] % 8); } inline Set(const Set& o) : s(o.s) {} inline Set& operator=(const Set& o) { s = o.s; return *this; } inline T n_elements() const { return n; } inline T max_index() const { return m; } inline T n_bytes() const { return s.size(); } /** * Computes the intersection between this and another set (n2, s2). * n2 is the number of element in the second s, s2 is a pointer to * the first element, which needs to be stored contiguously. s2 needs * to store the indices of the elements: (2,7,11) is the set of those * 3 elements. * r is the result set, and is also a list of element indices. * This method also returns an integer, which is the number of elements * in the intersection (so that r can be allocated once, and its first * few positions reused over and over again). * * NOTE: for best performance, have n2 << n */ inline T intersection(T n2, T* s2, T* r) const { /* if (n < n2) { std::cout << "Calling nta::Set::intersection " << "with small set: for best performance, " << "call with smaller set as argument" << std::endl; } */ T* rr = r; for (T* i = s2, *i_end = s2 + n2; i != i_end; ++i) { *r = *i; r += (s[*i >> 3] & (1 << (*i % 8))) / (1 << (*i % 8)); } return (T) (r - rr); } }; } // end namespace nta //-------------------------------------------------------------------------------- #endif //NTA_MATH_SET_HPP <commit_msg>add note of deprecation, write tests to decide<commit_after>/* * --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Our own set object, to beat Python, at least when computing intersection. * TODO: this file is currently superceded by built-in python set(), keeping as a reference, * and we should test which is faster for intersection workload, which is heavily used. */ #ifndef NTA_MATH_SET_HPP #define NTA_MATH_SET_HPP #include <vector> namespace nta { //-------------------------------------------------------------------------------- // SET // // Represents the set with an indicator function stored in a bit array. // // T is an unsigned integral type. // T_byte has the size of a byte. // // Test from Python: // Mac PowerBook 2.8 GHz Core 2 Duo, 10.6.3, -O3 -DNDEBUG, gcc 4.2.1 (Apple 5659) // m = 50000, n1 = 40, n2 = 10000: 0.00274658203125 0.00162267684937 1.69262415516 // m = 50000, n1 = 80, n2 = 10000: 0.00458002090454 0.00179862976074 2.54639448568 // m = 50000, n1 = 200, n2 = 10000: 0.0124213695526 0.00241708755493 5.13898204774 // m = 50000, n1 = 500, n2 = 10000: 0.0339875221252 0.00330281257629 10.2904785967 // m = 50000, n1 = 1000, n2 = 10000: 0.0573344230652 0.00443959236145 12.9143440202 // m = 50000, n1 = 2500, n2 = 10000: 0.155576944351 0.00838160514832 18.5617124164 // m = 50000, n1 = 5000, n2 = 10000: 0.256726026535 0.0143656730652 17.8707969595 //-------------------------------------------------------------------------------- template <typename T =size_t, typename T_byte =unsigned char> class Set { private: T m; // max value of non-zero indices T n; // number of non-zeros in s std::vector<T_byte> s; // indicator of the non-zeros public: // For Python binding inline Set() {} /** * Constructs from a list of n element indices ss, each element being * in the interval [0,m[. */ inline Set(T _m, T _n, T* ss) : m(_m), n(_n), s(m/8 + (m % 8 == 0 ? 0 : 1)) { construct(m, n, ss); } inline void construct(T _m, T _n, T* ss) { m = _m; n = _n; s.resize(m/8 + (m % 8 == 0 ? 0 : 1)); for (T i = 0; i != n; ++i) s[ss[i] / 8] |= 1 << (ss[i] % 8); } inline Set(const Set& o) : s(o.s) {} inline Set& operator=(const Set& o) { s = o.s; return *this; } inline T n_elements() const { return n; } inline T max_index() const { return m; } inline T n_bytes() const { return s.size(); } /** * Computes the intersection between this and another set (n2, s2). * n2 is the number of element in the second s, s2 is a pointer to * the first element, which needs to be stored contiguously. s2 needs * to store the indices of the elements: (2,7,11) is the set of those * 3 elements. * r is the result set, and is also a list of element indices. * This method also returns an integer, which is the number of elements * in the intersection (so that r can be allocated once, and its first * few positions reused over and over again). * * NOTE: for best performance, have n2 << n */ inline T intersection(T n2, T* s2, T* r) const { /* if (n < n2) { std::cout << "Calling nta::Set::intersection " << "with small set: for best performance, " << "call with smaller set as argument" << std::endl; } */ T* rr = r; for (T* i = s2, *i_end = s2 + n2; i != i_end; ++i) { *r = *i; r += (s[*i >> 3] & (1 << (*i % 8))) / (1 << (*i % 8)); } return (T) (r - rr); } }; } // end namespace nta //-------------------------------------------------------------------------------- #endif //NTA_MATH_SET_HPP <|endoftext|>
<commit_before>/* This file is part of CanFestival, a library implementing CanOpen Stack. Copyright (C): Edouard TISSERANT and Francis DUPIN Copyright (C) Win32 Port Leonid Tochinski See COPYING file for copyrights details. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <windows.h> #include <stdlib.h> extern "C" { #include "applicfg.h" #include "can_driver.h" #include "timer.h" #include "timers_driver.h" }; // --------------- Synchronization Object Implementation --------------- class ccritical_section { public: ccritical_section() { ::InitializeCriticalSection(&m_cs); } ~ccritical_section() { ::DeleteCriticalSection(&m_cs); } void enter() { ::EnterCriticalSection(&m_cs); } void leave() { ::LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION m_cs; }; static ccritical_section g_cs; void EnterMutex(void) { g_cs.enter(); } void LeaveMutex(void) { g_cs.leave(); } // --------------- Synchronization Object Implementation --------------- // --------------- CAN Receive Thread Implementation --------------- void CreateReceiveTask(CAN_HANDLE fd0, TASK_HANDLE* Thread, void* ReceiveLoopPtr) { unsigned long thread_id = 0; *Thread = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReceiveLoopPtr, fd0, 0, &thread_id); } void WaitReceiveTaskEnd(TASK_HANDLE Thread) { ::WaitForSingleObject(Thread, INFINITE); ::CloseHandle(Thread); //*Thread = NULL; } // --------------- CAN Receive Thread Implementation --------------- // --------------- Timer Thread Implementation --------------- class class_timers { public: class_timers(); ~class_timers(); void start_timer_thread(); void resume_timer_thread(); void stop_timer_thread(); void set_timer(TIMEVAL value); TIMEVAL get_elapsed_time(); private: TIMEVAL get_timer() const; static DWORD WINAPI timer_loop_thread_proc(void* arg); private: TIMEVAL m_last_occured_alarm_time; volatile TIMEVAL m_last_alarm_set_time; HANDLE m_timer_thread; volatile bool m_continue_timer_loop; bool m_use_hi_res_timer; double m_counts_per_usec; }; class_timers::class_timers() : m_last_occured_alarm_time(TIMEVAL_MAX), m_last_alarm_set_time(TIMEVAL_MAX), m_timer_thread(0), m_continue_timer_loop(false), m_use_hi_res_timer(false), m_counts_per_usec(0.) { // initialize hi resolution timer LARGE_INTEGER counts_per_sec = {0, 0}; if (::QueryPerformanceFrequency(&counts_per_sec) && counts_per_sec.QuadPart > 0) { m_use_hi_res_timer = true; m_counts_per_usec = counts_per_sec.QuadPart / 1000000.; } m_use_hi_res_timer = true; } class_timers::~class_timers() { stop_timer_thread(); } // time is in micro seconds TIMEVAL class_timers::get_timer() const { if (m_use_hi_res_timer) { LARGE_INTEGER performance_count = {0, 0}; ::QueryPerformanceCounter(&performance_count); return (TIMEVAL)(performance_count.QuadPart / m_counts_per_usec); } // hi-res timer is unavailable return 1000 * ::GetTickCount(); } DWORD WINAPI class_timers::timer_loop_thread_proc(void* arg) { class_timers* This = reinterpret_cast<class_timers*>(arg); while (This->m_continue_timer_loop) { TIMEVAL cur_time = This->get_timer(); if (cur_time >= This->m_last_alarm_set_time) { This->m_last_occured_alarm_time = cur_time; This->m_last_alarm_set_time = TIMEVAL_MAX; EnterMutex(); TimeDispatch(); LeaveMutex(); } else { ::Sleep(1); } } return 0; } void class_timers::start_timer_thread() { if (m_timer_thread == 0) { unsigned long thread_id = 0; m_timer_thread = ::CreateThread(NULL, 0, &timer_loop_thread_proc, this, CREATE_SUSPENDED, &thread_id); m_last_alarm_set_time = TIMEVAL_MAX; m_last_occured_alarm_time = get_timer(); } } void class_timers::resume_timer_thread() { if (m_timer_thread) { m_continue_timer_loop = true; ::ResumeThread(m_timer_thread); } } void class_timers::stop_timer_thread() { if (m_timer_thread) { m_continue_timer_loop = false; ::WaitForSingleObject(m_timer_thread, INFINITE); ::CloseHandle(m_timer_thread); m_timer_thread = 0; } } void class_timers::set_timer(TIMEVAL value) { m_last_alarm_set_time = (value == TIMEVAL_MAX) ? TIMEVAL_MAX : get_timer() + value; } // elapsed time since last occured alarm TIMEVAL class_timers::get_elapsed_time() { return get_timer() - m_last_occured_alarm_time; } // ---------------------------------------------------------- static class_timers s_timers; void StartTimerLoop(TimerCallback_t init_callback) { s_timers.start_timer_thread(); // At first, TimeDispatch will call init_callback. if (init_callback != NULL) SetAlarm(NULL, 0, init_callback, (TIMEVAL)0, (TIMEVAL)0); s_timers.resume_timer_thread(); } void StopTimerLoop(void) { s_timers.stop_timer_thread(); } void setTimer(TIMEVAL value) { s_timers.set_timer(value); } TIMEVAL getElapsedTime(void) { return s_timers.get_elapsed_time(); } <commit_msg>Repercutions of parameter type change in waitReceiveTaskEnd in win32<commit_after>/* This file is part of CanFestival, a library implementing CanOpen Stack. Copyright (C): Edouard TISSERANT and Francis DUPIN Copyright (C) Win32 Port Leonid Tochinski See COPYING file for copyrights details. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <windows.h> #include <stdlib.h> extern "C" { #include "applicfg.h" #include "can_driver.h" #include "timer.h" #include "timers_driver.h" }; // --------------- Synchronization Object Implementation --------------- class ccritical_section { public: ccritical_section() { ::InitializeCriticalSection(&m_cs); } ~ccritical_section() { ::DeleteCriticalSection(&m_cs); } void enter() { ::EnterCriticalSection(&m_cs); } void leave() { ::LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION m_cs; }; static ccritical_section g_cs; void EnterMutex(void) { g_cs.enter(); } void LeaveMutex(void) { g_cs.leave(); } // --------------- Synchronization Object Implementation --------------- // --------------- CAN Receive Thread Implementation --------------- void CreateReceiveTask(CAN_HANDLE fd0, TASK_HANDLE* Thread, void* ReceiveLoopPtr) { unsigned long thread_id = 0; *Thread = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReceiveLoopPtr, fd0, 0, &thread_id); } void WaitReceiveTaskEnd(TASK_HANDLE *Thread) { ::WaitForSingleObject(*Thread, INFINITE); ::CloseHandle(*Thread); //*Thread = NULL; } // --------------- CAN Receive Thread Implementation --------------- // --------------- Timer Thread Implementation --------------- class class_timers { public: class_timers(); ~class_timers(); void start_timer_thread(); void resume_timer_thread(); void stop_timer_thread(); void set_timer(TIMEVAL value); TIMEVAL get_elapsed_time(); private: TIMEVAL get_timer() const; static DWORD WINAPI timer_loop_thread_proc(void* arg); private: TIMEVAL m_last_occured_alarm_time; volatile TIMEVAL m_last_alarm_set_time; HANDLE m_timer_thread; volatile bool m_continue_timer_loop; bool m_use_hi_res_timer; double m_counts_per_usec; }; class_timers::class_timers() : m_last_occured_alarm_time(TIMEVAL_MAX), m_last_alarm_set_time(TIMEVAL_MAX), m_timer_thread(0), m_continue_timer_loop(false), m_use_hi_res_timer(false), m_counts_per_usec(0.) { // initialize hi resolution timer LARGE_INTEGER counts_per_sec = {0, 0}; if (::QueryPerformanceFrequency(&counts_per_sec) && counts_per_sec.QuadPart > 0) { m_use_hi_res_timer = true; m_counts_per_usec = counts_per_sec.QuadPart / 1000000.; } m_use_hi_res_timer = true; } class_timers::~class_timers() { stop_timer_thread(); } // time is in micro seconds TIMEVAL class_timers::get_timer() const { if (m_use_hi_res_timer) { LARGE_INTEGER performance_count = {0, 0}; ::QueryPerformanceCounter(&performance_count); return (TIMEVAL)(performance_count.QuadPart / m_counts_per_usec); } // hi-res timer is unavailable return 1000 * ::GetTickCount(); } DWORD WINAPI class_timers::timer_loop_thread_proc(void* arg) { class_timers* This = reinterpret_cast<class_timers*>(arg); while (This->m_continue_timer_loop) { TIMEVAL cur_time = This->get_timer(); if (cur_time >= This->m_last_alarm_set_time) { This->m_last_occured_alarm_time = cur_time; This->m_last_alarm_set_time = TIMEVAL_MAX; EnterMutex(); TimeDispatch(); LeaveMutex(); } else { ::Sleep(1); } } return 0; } void class_timers::start_timer_thread() { if (m_timer_thread == 0) { unsigned long thread_id = 0; m_timer_thread = ::CreateThread(NULL, 0, &timer_loop_thread_proc, this, CREATE_SUSPENDED, &thread_id); m_last_alarm_set_time = TIMEVAL_MAX; m_last_occured_alarm_time = get_timer(); } } void class_timers::resume_timer_thread() { if (m_timer_thread) { m_continue_timer_loop = true; ::ResumeThread(m_timer_thread); } } void class_timers::stop_timer_thread() { if (m_timer_thread) { m_continue_timer_loop = false; ::WaitForSingleObject(m_timer_thread, INFINITE); ::CloseHandle(m_timer_thread); m_timer_thread = 0; } } void class_timers::set_timer(TIMEVAL value) { m_last_alarm_set_time = (value == TIMEVAL_MAX) ? TIMEVAL_MAX : get_timer() + value; } // elapsed time since last occured alarm TIMEVAL class_timers::get_elapsed_time() { return get_timer() - m_last_occured_alarm_time; } // ---------------------------------------------------------- static class_timers s_timers; void StartTimerLoop(TimerCallback_t init_callback) { s_timers.start_timer_thread(); // At first, TimeDispatch will call init_callback. if (init_callback != NULL) SetAlarm(NULL, 0, init_callback, (TIMEVAL)0, (TIMEVAL)0); s_timers.resume_timer_thread(); } void StopTimerLoop(void) { s_timers.stop_timer_thread(); } void setTimer(TIMEVAL value) { s_timers.set_timer(value); } TIMEVAL getElapsedTime(void) { return s_timers.get_elapsed_time(); } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/arena_planner.h" #include <algorithm> #include <cstdint> #include <limits> #include <set> #include <type_traits> #include <utility> namespace tflite { namespace { constexpr int32_t kNodeNotAssigned = std::numeric_limits<int32_t>::max(); } // namespace ArenaPlanner::ArenaPlanner(TfLiteContext* context, std::unique_ptr<GraphInfo> graph_info, bool preserve_inputs, bool preserve_intermediates, int tensor_alignment) : context_(context), graph_info_(std::move(graph_info)), arena_(kDefaultArenaAlignment), persistent_arena_(kDefaultArenaAlignment), preserve_inputs_(preserve_inputs), preserve_intermediates_(preserve_intermediates), tensor_alignment_(tensor_alignment) {} ArenaPlanner::~ArenaPlanner() {} std::intptr_t ArenaPlanner::BasePointer(TfLiteAllocationType type) { if (type == kTfLiteArenaRwPersistent) { return persistent_arena_.BasePointer(); } if (type == kTfLiteArenaRw) { return arena_.BasePointer(); } return 0; } TfLiteStatus ArenaPlanner::ResetAllocations() { TF_LITE_ENSURE_STATUS(arena_.ClearPlan()); TF_LITE_ENSURE_STATUS(persistent_arena_.ClearPlan()); allocs_.clear(); allocs_.resize(graph_info_->num_tensors()); return kTfLiteOk; } TfLiteStatus ArenaPlanner::ResetAllocationsAfter(int node) { for (int i = 0; i < static_cast<int>(allocs_.size()); ++i) { if (allocs_[i].first_node > node && allocs_[i].size > 0) { TfLiteTensor& tensor = *graph_info_->tensor(i); if (tensor.allocation_type == kTfLiteArenaRw) { TF_LITE_ENSURE_STATUS(arena_.Deallocate(context_, allocs_[i])); allocs_[i].reset(); tensor.data.raw = nullptr; } } } return kTfLiteOk; } TfLiteStatus ArenaPlanner::PlanAllocations() { // Invalidate any existing data. TF_LITE_ENSURE_STATUS(ResetAllocations()); // Maybe other verb instead of 'Assigned' alloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned); dealloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned); // Keeps track of references to each tensor. std::vector<int> refcounts(graph_info_->num_tensors(), 0); auto allocate = [this](int node, int tensor) -> TfLiteStatus { if (alloc_node_[tensor] != kNodeNotAssigned) { // Tensor has already been allocated. return kTfLiteOk; } TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned); alloc_node_[tensor] = node; return kTfLiteOk; }; auto deallocate = [this](int node, int tensor) -> TfLiteStatus { if (alloc_node_[tensor] == kNodeNotAssigned) { // We don't need to deallocate the tensor, that is never allocated. // This happened with the constant tensors. return kTfLiteOk; } TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned); dealloc_node_[tensor] = node; return kTfLiteOk; }; // We must make sure the output tensors are never overwritten. We do that by // artificially adding one to their ref-counts so they are never selected // for deallocation. for (int tensor_index : graph_info_->outputs()) { refcounts[tensor_index]++; } // Variable tensors also should be ensured to be never overwritten and need to // be alive all the time. for (int tensor_index : graph_info_->variables()) { refcounts[tensor_index]++; } // Queue all graph inputs for allocation. If preserve_inputs_ is true, make // sure they never be overwritten. for (int tensor_index : graph_info_->inputs()) { if (tensor_index != kTfLiteOptionalTensor) { if (preserve_inputs_) { refcounts[tensor_index]++; } TF_LITE_ENSURE_STATUS(allocate(0, tensor_index)); } } // Queue all graph variable tensors for allocation. for (int tensor_index : graph_info_->variables()) { if (tensor_index != kTfLiteOptionalTensor) { // Increase the reference count for input tensors by one, so it will // never be deallocated. TF_LITE_ENSURE_STATUS(allocate(0, tensor_index)); } } // Count references to node input tensors. for (size_t i = 0; i < graph_info_->num_nodes(); ++i) { const TfLiteNode& node = graph_info_->node(i); TfLiteIntArray* node_inputs = node.inputs; for (int j = 0; j < node_inputs->size; ++j) { int tensor_index = node_inputs->data[j]; if (tensor_index != kTfLiteOptionalTensor) { refcounts[tensor_index]++; } } } // Queue all graph inputs for allocation. for (int tensor_index : graph_info_->inputs()) { if (tensor_index != kTfLiteOptionalTensor) { TF_LITE_ENSURE_STATUS(allocate(0, tensor_index)); } } // Go through the graph in execution order. for (size_t i = 0; i < graph_info_->num_nodes(); ++i) { const TfLiteNode& node = graph_info_->node(i); // First queue output tensors for allocation. TfLiteIntArray* node_outputs = node.outputs; for (int j = 0; j < node_outputs->size; ++j) { int tensor_index = node_outputs->data[j]; TF_LITE_ENSURE_STATUS(allocate(i, tensor_index)); } // Then update the ref-counts of the node's inputs, and if necessary queue // them for deallocation. if (!preserve_intermediates_) { TfLiteIntArray* node_inputs = node.inputs; for (int j = 0; j < node_inputs->size; ++j) { int tensor_index = node_inputs->data[j]; if (tensor_index != kTfLiteOptionalTensor) { refcounts[tensor_index]--; if (refcounts[tensor_index] == 0) { TF_LITE_ENSURE_STATUS(deallocate(i, tensor_index)); } } } } } // Note that graph outputs will never be scheduled for deallocation. We // could do that here for completeness, but it won't have any effect. return kTfLiteOk; } TfLiteStatus ArenaPlanner::ExecuteAllocations(int first_node, int last_node) { // Grow the size of `allocs_` if necessary. This allows allocating temporary // tensors in op's `prepare` function. TF_LITE_ENSURE(context_, graph_info_->num_tensors() >= allocs_.size()); alloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned); dealloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned); allocs_.resize(graph_info_->num_tensors()); // Set allocation and deallocation for temporary tensors. for (size_t i = first_node; i <= last_node && i < graph_info_->num_nodes(); ++i) { const TfLiteNode& node = graph_info_->node(i); TfLiteIntArray* node_temporaries = node.temporaries; for (int j = 0; j < node_temporaries->size; ++j) { int tensor_index = node_temporaries->data[j]; alloc_node_[tensor_index] = i; dealloc_node_[tensor_index] = i; } } TF_LITE_ENSURE_STATUS(CalculateAllocations(first_node, last_node)); TF_LITE_ENSURE_STATUS(Commit()); for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { // TODO(ahentz): we could do this only for the tensors that were modified // in CalculateAllocations(), instead of redoing it for tensors that // already had proper pointers. However we must be very careful, because // SimpleMemoryArena::Commit() could move the base pointer. TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i)); } return kTfLiteOk; } TfLiteStatus ArenaPlanner::ReleaseNonPersistentMemory() { // Clear non-persistent arena's buffer. TF_LITE_ENSURE_STATUS(arena_.ReleaseBuffer()); // Set data pointers for all non-persistent tensors to nullptr. for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { TfLiteTensor& tensor = *graph_info_->tensor(i); if (tensor.allocation_type == kTfLiteArenaRw) { tensor.data.raw = nullptr; } } return kTfLiteOk; } TfLiteStatus ArenaPlanner::AcquireNonPersistentMemory() { // First commit arena_ to allocate underlying buffer. TF_LITE_ENSURE_STATUS(arena_.Commit(context_)); // Resolve allocations for all tensors not on the persistent arena. for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { TfLiteTensor& tensor = *graph_info_->tensor(i); if (tensor.allocation_type == kTfLiteArenaRw) { TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i)); } } return kTfLiteOk; } bool ArenaPlanner::HasNonPersistentMemory() { return arena_.GetBufferSize() != 0; } TfLiteStatus ArenaPlanner::Commit() { TF_LITE_ENSURE_STATUS(arena_.Commit(context_)); TF_LITE_ENSURE_STATUS(persistent_arena_.Commit(context_)); return kTfLiteOk; } std::vector<int32_t> ArenaPlanner::CreateTensorAllocationVector(int first_node, int last_node) { auto tensor_compare = [this](int idx1, int idx2) { // Tensors that have lifespan through the whole model inference time are // allocated at the beginning of memory slice. Their respective order // doesn't matter in fact, so here they are sorted by index. if (this->alloc_node_[idx1] == 0 && this->dealloc_node_[idx1] == kNodeNotAssigned) { if (this->alloc_node_[idx2] == 0 && this->dealloc_node_[idx2] == kNodeNotAssigned) { return idx1 < idx2; } return true; } if (this->alloc_node_[idx2] == 0 && this->dealloc_node_[idx2] == kNodeNotAssigned) { return false; } // All other tensors are sorted in non-increasing order of their size. auto size1 = this->graph_info_->tensor(idx1)->bytes; auto size2 = this->graph_info_->tensor(idx2)->bytes; if (size1 != size2) { return size1 > size2; } // Tensors with equal size are sorted in order of their allocation time. return this->alloc_node_[idx1] < this->alloc_node_[idx2]; }; std::set<int32_t> tensors_set; for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { if (alloc_node_[i] >= first_node && alloc_node_[i] <= last_node) { tensors_set.insert(i); } } // Indices of tensors in order their allocation offsets will be calculated. std::vector<int32_t> tensor_order(tensors_set.begin(), tensors_set.end()); std::sort(tensor_order.begin(), tensor_order.end(), tensor_compare); return tensor_order; } TfLiteStatus ArenaPlanner::CalculateAllocations(int first_node, int last_node) { // Indices of tensors in order their allocation offsets will be calculated. const std::vector<int32_t> tensor_order = CreateTensorAllocationVector(first_node, last_node); // Deallocate if the tensor was already allocated. for (const auto& tensor_index : tensor_order) { TfLiteTensor& tensor = *graph_info_->tensor(tensor_index); if (tensor.allocation_type == kTfLiteArenaRw && allocs_[tensor_index].size != 0) { TF_LITE_ENSURE_STATUS(arena_.Deallocate(context_, allocs_[tensor_index])); } } // Vector of ids of already allocated tensors, ordered by offset. for (const auto& tensor_index : tensor_order) { TfLiteTensor& tensor = *graph_info_->tensor(tensor_index); if (tensor.allocation_type == kTfLiteArenaRw) { TF_LITE_ENSURE_STATUS( arena_.Allocate(context_, tensor_alignment_, tensor.bytes, tensor_index, alloc_node_[tensor_index], dealloc_node_[tensor_index], &allocs_[tensor_index])); } if (tensor.allocation_type == kTfLiteArenaRwPersistent) { TF_LITE_ENSURE_STATUS(persistent_arena_.Allocate( context_, tensor_alignment_, tensor.bytes, tensor_index, /*first_node=*/alloc_node_[tensor_index], /*last_node=*/std::numeric_limits<int32_t>::max(), &allocs_[tensor_index])); } } return kTfLiteOk; } TfLiteStatus ArenaPlanner::ResolveTensorAllocation(int tensor_index) { TfLiteTensor& tensor = *graph_info_->tensor(tensor_index); if (tensor.allocation_type == kTfLiteArenaRw) { // Skip resolution if the size of the tensor is zero, leaving it as a // nullptr. if (allocs_[tensor_index].size != 0) { TF_LITE_ENSURE_STATUS(arena_.ResolveAlloc(context_, allocs_[tensor_index], &tensor.data.raw)); } } if (tensor.allocation_type == kTfLiteArenaRwPersistent) { TF_LITE_ENSURE_STATUS(persistent_arena_.ResolveAlloc( context_, allocs_[tensor_index], &tensor.data.raw)); } return kTfLiteOk; } } // namespace tflite <commit_msg>arena_planner: Create tensor_order vector directly instead of using tensors_set<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/arena_planner.h" #include <algorithm> #include <cstdint> #include <limits> #include <set> #include <type_traits> #include <utility> namespace tflite { namespace { constexpr int32_t kNodeNotAssigned = std::numeric_limits<int32_t>::max(); } // namespace ArenaPlanner::ArenaPlanner(TfLiteContext* context, std::unique_ptr<GraphInfo> graph_info, bool preserve_inputs, bool preserve_intermediates, int tensor_alignment) : context_(context), graph_info_(std::move(graph_info)), arena_(kDefaultArenaAlignment), persistent_arena_(kDefaultArenaAlignment), preserve_inputs_(preserve_inputs), preserve_intermediates_(preserve_intermediates), tensor_alignment_(tensor_alignment) {} ArenaPlanner::~ArenaPlanner() {} std::intptr_t ArenaPlanner::BasePointer(TfLiteAllocationType type) { if (type == kTfLiteArenaRwPersistent) { return persistent_arena_.BasePointer(); } if (type == kTfLiteArenaRw) { return arena_.BasePointer(); } return 0; } TfLiteStatus ArenaPlanner::ResetAllocations() { TF_LITE_ENSURE_STATUS(arena_.ClearPlan()); TF_LITE_ENSURE_STATUS(persistent_arena_.ClearPlan()); allocs_.clear(); allocs_.resize(graph_info_->num_tensors()); return kTfLiteOk; } TfLiteStatus ArenaPlanner::ResetAllocationsAfter(int node) { for (int i = 0; i < static_cast<int>(allocs_.size()); ++i) { if (allocs_[i].first_node > node && allocs_[i].size > 0) { TfLiteTensor& tensor = *graph_info_->tensor(i); if (tensor.allocation_type == kTfLiteArenaRw) { TF_LITE_ENSURE_STATUS(arena_.Deallocate(context_, allocs_[i])); allocs_[i].reset(); tensor.data.raw = nullptr; } } } return kTfLiteOk; } TfLiteStatus ArenaPlanner::PlanAllocations() { // Invalidate any existing data. TF_LITE_ENSURE_STATUS(ResetAllocations()); // Maybe other verb instead of 'Assigned' alloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned); dealloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned); // Keeps track of references to each tensor. std::vector<int> refcounts(graph_info_->num_tensors(), 0); auto allocate = [this](int node, int tensor) -> TfLiteStatus { if (alloc_node_[tensor] != kNodeNotAssigned) { // Tensor has already been allocated. return kTfLiteOk; } TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned); alloc_node_[tensor] = node; return kTfLiteOk; }; auto deallocate = [this](int node, int tensor) -> TfLiteStatus { if (alloc_node_[tensor] == kNodeNotAssigned) { // We don't need to deallocate the tensor, that is never allocated. // This happened with the constant tensors. return kTfLiteOk; } TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned); dealloc_node_[tensor] = node; return kTfLiteOk; }; // We must make sure the output tensors are never overwritten. We do that by // artificially adding one to their ref-counts so they are never selected // for deallocation. for (int tensor_index : graph_info_->outputs()) { refcounts[tensor_index]++; } // Variable tensors also should be ensured to be never overwritten and need to // be alive all the time. for (int tensor_index : graph_info_->variables()) { refcounts[tensor_index]++; } // Queue all graph inputs for allocation. If preserve_inputs_ is true, make // sure they never be overwritten. for (int tensor_index : graph_info_->inputs()) { if (tensor_index != kTfLiteOptionalTensor) { if (preserve_inputs_) { refcounts[tensor_index]++; } TF_LITE_ENSURE_STATUS(allocate(0, tensor_index)); } } // Queue all graph variable tensors for allocation. for (int tensor_index : graph_info_->variables()) { if (tensor_index != kTfLiteOptionalTensor) { // Increase the reference count for input tensors by one, so it will // never be deallocated. TF_LITE_ENSURE_STATUS(allocate(0, tensor_index)); } } // Count references to node input tensors. for (size_t i = 0; i < graph_info_->num_nodes(); ++i) { const TfLiteNode& node = graph_info_->node(i); TfLiteIntArray* node_inputs = node.inputs; for (int j = 0; j < node_inputs->size; ++j) { int tensor_index = node_inputs->data[j]; if (tensor_index != kTfLiteOptionalTensor) { refcounts[tensor_index]++; } } } // Queue all graph inputs for allocation. for (int tensor_index : graph_info_->inputs()) { if (tensor_index != kTfLiteOptionalTensor) { TF_LITE_ENSURE_STATUS(allocate(0, tensor_index)); } } // Go through the graph in execution order. for (size_t i = 0; i < graph_info_->num_nodes(); ++i) { const TfLiteNode& node = graph_info_->node(i); // First queue output tensors for allocation. TfLiteIntArray* node_outputs = node.outputs; for (int j = 0; j < node_outputs->size; ++j) { int tensor_index = node_outputs->data[j]; TF_LITE_ENSURE_STATUS(allocate(i, tensor_index)); } // Then update the ref-counts of the node's inputs, and if necessary queue // them for deallocation. if (!preserve_intermediates_) { TfLiteIntArray* node_inputs = node.inputs; for (int j = 0; j < node_inputs->size; ++j) { int tensor_index = node_inputs->data[j]; if (tensor_index != kTfLiteOptionalTensor) { refcounts[tensor_index]--; if (refcounts[tensor_index] == 0) { TF_LITE_ENSURE_STATUS(deallocate(i, tensor_index)); } } } } } // Note that graph outputs will never be scheduled for deallocation. We // could do that here for completeness, but it won't have any effect. return kTfLiteOk; } TfLiteStatus ArenaPlanner::ExecuteAllocations(int first_node, int last_node) { // Grow the size of `allocs_` if necessary. This allows allocating temporary // tensors in op's `prepare` function. TF_LITE_ENSURE(context_, graph_info_->num_tensors() >= allocs_.size()); alloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned); dealloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned); allocs_.resize(graph_info_->num_tensors()); // Set allocation and deallocation for temporary tensors. for (size_t i = first_node; i <= last_node && i < graph_info_->num_nodes(); ++i) { const TfLiteNode& node = graph_info_->node(i); TfLiteIntArray* node_temporaries = node.temporaries; for (int j = 0; j < node_temporaries->size; ++j) { int tensor_index = node_temporaries->data[j]; alloc_node_[tensor_index] = i; dealloc_node_[tensor_index] = i; } } TF_LITE_ENSURE_STATUS(CalculateAllocations(first_node, last_node)); TF_LITE_ENSURE_STATUS(Commit()); for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { // TODO(ahentz): we could do this only for the tensors that were modified // in CalculateAllocations(), instead of redoing it for tensors that // already had proper pointers. However we must be very careful, because // SimpleMemoryArena::Commit() could move the base pointer. TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i)); } return kTfLiteOk; } TfLiteStatus ArenaPlanner::ReleaseNonPersistentMemory() { // Clear non-persistent arena's buffer. TF_LITE_ENSURE_STATUS(arena_.ReleaseBuffer()); // Set data pointers for all non-persistent tensors to nullptr. for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { TfLiteTensor& tensor = *graph_info_->tensor(i); if (tensor.allocation_type == kTfLiteArenaRw) { tensor.data.raw = nullptr; } } return kTfLiteOk; } TfLiteStatus ArenaPlanner::AcquireNonPersistentMemory() { // First commit arena_ to allocate underlying buffer. TF_LITE_ENSURE_STATUS(arena_.Commit(context_)); // Resolve allocations for all tensors not on the persistent arena. for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { TfLiteTensor& tensor = *graph_info_->tensor(i); if (tensor.allocation_type == kTfLiteArenaRw) { TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i)); } } return kTfLiteOk; } bool ArenaPlanner::HasNonPersistentMemory() { return arena_.GetBufferSize() != 0; } TfLiteStatus ArenaPlanner::Commit() { TF_LITE_ENSURE_STATUS(arena_.Commit(context_)); TF_LITE_ENSURE_STATUS(persistent_arena_.Commit(context_)); return kTfLiteOk; } std::vector<int32_t> ArenaPlanner::CreateTensorAllocationVector(int first_node, int last_node) { auto tensor_compare = [this](int idx1, int idx2) { // Tensors that have lifespan through the whole model inference time are // allocated at the beginning of memory slice. Their respective order // doesn't matter in fact, so here they are sorted by index. if (this->alloc_node_[idx1] == 0 && this->dealloc_node_[idx1] == kNodeNotAssigned) { if (this->alloc_node_[idx2] == 0 && this->dealloc_node_[idx2] == kNodeNotAssigned) { return idx1 < idx2; } return true; } if (this->alloc_node_[idx2] == 0 && this->dealloc_node_[idx2] == kNodeNotAssigned) { return false; } // All other tensors are sorted in non-increasing order of their size. auto size1 = this->graph_info_->tensor(idx1)->bytes; auto size2 = this->graph_info_->tensor(idx2)->bytes; if (size1 != size2) { return size1 > size2; } // Tensors with equal size are sorted in order of their allocation time. return this->alloc_node_[idx1] < this->alloc_node_[idx2]; }; std::vector<int32_t> tensor_order; for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) { if (alloc_node_[i] >= first_node && alloc_node_[i] <= last_node) { tensor_order.push_back(i); } } // Indices of tensors in order their allocation offsets will be calculated. std::sort(tensor_order.begin(), tensor_order.end(), tensor_compare); return tensor_order; } TfLiteStatus ArenaPlanner::CalculateAllocations(int first_node, int last_node) { // Indices of tensors in order their allocation offsets will be calculated. const std::vector<int32_t> tensor_order = CreateTensorAllocationVector(first_node, last_node); // Deallocate if the tensor was already allocated. for (const auto& tensor_index : tensor_order) { TfLiteTensor& tensor = *graph_info_->tensor(tensor_index); if (tensor.allocation_type == kTfLiteArenaRw && allocs_[tensor_index].size != 0) { TF_LITE_ENSURE_STATUS(arena_.Deallocate(context_, allocs_[tensor_index])); } } // Vector of ids of already allocated tensors, ordered by offset. for (const auto& tensor_index : tensor_order) { TfLiteTensor& tensor = *graph_info_->tensor(tensor_index); if (tensor.allocation_type == kTfLiteArenaRw) { TF_LITE_ENSURE_STATUS( arena_.Allocate(context_, tensor_alignment_, tensor.bytes, tensor_index, alloc_node_[tensor_index], dealloc_node_[tensor_index], &allocs_[tensor_index])); } if (tensor.allocation_type == kTfLiteArenaRwPersistent) { TF_LITE_ENSURE_STATUS(persistent_arena_.Allocate( context_, tensor_alignment_, tensor.bytes, tensor_index, /*first_node=*/alloc_node_[tensor_index], /*last_node=*/std::numeric_limits<int32_t>::max(), &allocs_[tensor_index])); } } return kTfLiteOk; } TfLiteStatus ArenaPlanner::ResolveTensorAllocation(int tensor_index) { TfLiteTensor& tensor = *graph_info_->tensor(tensor_index); if (tensor.allocation_type == kTfLiteArenaRw) { // Skip resolution if the size of the tensor is zero, leaving it as a // nullptr. if (allocs_[tensor_index].size != 0) { TF_LITE_ENSURE_STATUS(arena_.ResolveAlloc(context_, allocs_[tensor_index], &tensor.data.raw)); } } if (tensor.allocation_type == kTfLiteArenaRwPersistent) { TF_LITE_ENSURE_STATUS(persistent_arena_.ResolveAlloc( context_, allocs_[tensor_index], &tensor.data.raw)); } return kTfLiteOk; } } // namespace tflite <|endoftext|>
<commit_before>#include "LRLayersPack.h" #include "check_params.h" #include <lr/dataset/Grids.h> #include <lr/dataset/CharacterFileName.h> #include <easyshape.h> namespace edb { std::string LRLayersPack::Command() const { return "lr-pack"; } std::string LRLayersPack::Description() const { return "create shape table from lr file"; } std::string LRLayersPack::Usage() const { // lr-pack e:/test2/test_lr.json std::string usage = Command() + " [filepath]"; return usage; } void LRLayersPack::Run(int argc, char *argv[]) { if (!check_number(this, argc, 3)) return; if (!check_file(argv[2])) return; Run(argv[2]); } void LRLayersPack::Run(const std::string& filepath) { Json::Value lr_val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, lr_val); fin.close(); m_dir = d2d::FilenameTools::getFileDir(filepath) + "\\"; Json::Value out_val; out_val["width"] = lr_val["size"]["width"]; out_val["height"] = lr_val["size"]["height"]; out_val["view width"] = lr_val["size"]["view width"]; out_val["view height"] = lr_val["size"]["view height"]; lr::Grids grids; int w = lr_val["size"]["width"].asUInt(), h = lr_val["size"]["height"].asUInt(); grids.Build(w, h); int col, row; grids.GetGridSize(col, row); out_val["col"] = col; out_val["row"] = row; ParserSpecial(lr_val, out_val); ParserCharacter(lr_val, 2, "character", out_val); ParserPoint(lr_val, 3, "point", out_val); ParserShapeLayer(lr_val, grids, false, 4, "path", out_val); ParserShapeLayer(lr_val, grids, true, 5, "region", out_val); ParserShapeLayer(lr_val, grids, true, 6, "collision region", out_val); ParserCamera(lr_val, 7, "camera", out_val); std::string outfile = filepath.substr(0, filepath.find_last_of('_')) + ".json"; Json::StyledStreamWriter writer; std::locale::global(std::locale("")); std::ofstream fout(outfile.c_str()); std::locale::global(std::locale("C")); writer.write(fout, out_val); fout.close(); } void LRLayersPack::ParserShape(d2d::IShape* shape, const d2d::Vector& offset, const lr::Grids& grids, bool force_grids, Json::Value& out_val) { if (libshape::PolygonShape* poly = dynamic_cast<libshape::PolygonShape*>(shape)) { std::vector<int> grid_idx; std::vector<d2d::Vector> bound = poly->GetVertices(); for (int i = 0, n = bound.size(); i < n; ++i) { bound[i] += offset; } grid_idx = grids.IntersectPolygon(bound); for (int i = 0, n = grid_idx.size(); i < n; ++i) { int sz = out_val["grid"].size(); out_val["grid"][sz] = grid_idx[i]; } } else if (libshape::ChainShape* chain = dynamic_cast<libshape::ChainShape*>(shape)) { std::vector<d2d::Vector> bound = chain->GetVertices(); for (int i = 0, n = bound.size(); i < n; ++i) { bound[i] += offset; } if (force_grids) { std::vector<int> grid_idx; grid_idx = grids.IntersectPolyline(bound); for (int i = 0, n = grid_idx.size(); i < n; ++i) { int sz = out_val["grid"].size(); out_val["grid"][sz] = grid_idx[i]; } } else { d2d::JsonIO::Store(bound, out_val["pos"]); } } else { throw d2d::Exception("LRLayersPack::ParserPolyLayer error shape type"); } } void LRLayersPack::ParserShapeLayer(const Json::Value& src_val, const lr::Grids& grids, bool force_grids, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!src_spr_val.isNull()) { std::string spr_path = d2d::SymbolSearcher::GetSymbolPath(m_dir, src_spr_val); d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->FetchSymbol(spr_path); assert(symbol); Json::Value dst_val; dst_val["name"] = src_spr_val["name"]; d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol); sprite->Load(src_spr_val); libshape::Sprite* shape_spr = dynamic_cast<libshape::Sprite*>(sprite); assert(shape_spr); const std::vector<d2d::IShape*>& shapes = shape_spr->GetSymbol().GetShapes(); for (int i = 0, n = shapes.size(); i < n; ++i) { ParserShape(shapes[i], sprite->GetPosition(), grids, force_grids, dst_val); } int sz = out_val[name].size(); out_val[name][sz] = dst_val; sprite->Release(); symbol->Release(); src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } idx = 0; Json::Value src_shape_val = src_val["layer"][layer_idx]["shape"][idx++]; while (!src_shape_val.isNull()) { d2d::IShape* shape = libshape::ShapeFactory::CreateShapeFromFile(src_shape_val, m_dir); Json::Value dst_val; dst_val["name"] = src_shape_val["name"]; ParserShape(shape, d2d::Vector(0, 0), grids, force_grids, dst_val); int sz = out_val[name].size(); out_val[name][sz] = dst_val; shape->Release(); src_shape_val = src_val["layer"][layer_idx]["shape"][idx++]; } } void LRLayersPack::ParserPoint(const Json::Value& src_val, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { std::string spr_path = d2d::SymbolSearcher::GetSymbolPath(m_dir, spr_val); d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->FetchSymbol(spr_path); if (!symbol) { std::string filepath = spr_val["filepath"].asString(); throw d2d::Exception("Symbol doesn't exist, [dir]:%s, [file]:%s !", m_dir.c_str(), filepath.c_str()); } Json::Value shape_val; shape_val["name"] = spr_val["name"]; d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol); sprite->Load(spr_val); shape_val["x"] = sprite->GetPosition().x; shape_val["y"] = sprite->GetPosition().y; int sz = out_val[name].size(); out_val[name][sz] = shape_val; sprite->Release(); symbol->Release(); spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } void LRLayersPack::ParserCamera(const Json::Value& src_val, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { Json::Value cam_val; cam_val["name"] = spr_val["name"]; cam_val["x"] = spr_val["position"]["x"]; cam_val["y"] = spr_val["position"]["y"]; cam_val["scale"] = spr_val["x scale"]; int sz = out_val[name].size(); out_val[name][sz] = cam_val; spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } void LRLayersPack::ParserCharacter(const Json::Value& src_val, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { std::string filename = d2d::FilenameTools::getFilename(spr_val["filepath"].asString()); if (d2d::FileNameParser::isType(filename, d2d::FileNameParser::e_particle3d)) { spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; continue; } Json::Value char_val; char_val["name"] = spr_val["name"]; char_val["x"] = spr_val["position"]["x"]; char_val["y"] = spr_val["position"]["y"]; // tags std::string tag = spr_val["tag"].asString(); std::vector<std::string> tags; int pos = tag.find_first_of(';'); tags.push_back(tag.substr(0, pos)); do { int next_pos = tag.find_first_of(';', pos + 1); tags.push_back(tag.substr(pos + 1, next_pos - pos - 1)); pos = next_pos; } while (pos != std::string::npos); for (int i = 0, n = tags.size(); i < n; ++i) { const std::string& str = tags[i]; int pos = str.find_first_of('='); std::string key = str.substr(0, pos); std::string val = str.substr(pos+1); char_val["tag"][key] = val; } // filename lr::CharacterFileName out_name(filename); char_val["filename"] = out_name.GetOutputName(); // angle int dir = 1 + (out_name.GetField(lr::CharacterFileName::FT_DIRECTION)[0] - '1'); if (spr_val["x mirror"].asBool()) { dir = 10 - dir; } dir = (dir + 7) % 8; char_val["angle"] = dir + 1; int sz = out_val[name].size(); out_val[name][sz] = char_val; spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } void LRLayersPack::ParserSpecial(const Json::Value& src_val, Json::Value& out_val) { for (int layer_idx = 0; layer_idx < 3; ++layer_idx) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { std::string filepath = spr_val["filepath"].asString(); std::string tag = spr_val["tag"].asString(); if (d2d::FileNameParser::isType(filepath, d2d::FileNameParser::e_particle3d)) { ParserParticleLayer(spr_val, out_val); } else if (tag.find("layer=cover") != std::string::npos) { ParserSpecialLayer(spr_val, "cover", out_val); } else if (tag.find("layer=top") != std::string::npos) { ParserSpecialLayer(spr_val, "top", out_val); } spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } } void LRLayersPack::ParserSpecialLayer(const Json::Value& spr_val, const std::string& name, Json::Value& out_val) { Json::Value dec_val; float px = spr_val["position"]["x"].asDouble(), py = spr_val["position"]["y"].asDouble(); std::string export_name = ""; wxString spr_path = d2d::SymbolSearcher::GetSymbolPath(m_dir, spr_val); if (spr_path.Contains(".json")) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(spr_path.fn_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); export_name = val["name"].asString(); int idx = 0; const Json::Value& spr_val = val["sprite"][idx]; float cx = spr_val["position"]["x"].asDouble(), cy = spr_val["position"]["y"].asDouble(); px += cx; py += cy; } dec_val["export"] = export_name; dec_val["x"] = px; dec_val["y"] = py; int sz = out_val[name].size(); out_val[name][sz] = dec_val; } void LRLayersPack::ParserParticleLayer(const Json::Value& spr_val, Json::Value& out_val) { Json::Value dec_val; dec_val["x"] = spr_val["position"]["x"].asDouble(); dec_val["y"] = spr_val["position"]["y"].asDouble(); std::string sym_path = spr_val["filepath"].asString(); Json::Value sym_val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(sym_path.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, sym_val); fin.close(); dec_val["export"] = sym_val["name"].asString(); Json::Value dir_val; dir_val["x"] = 0; dir_val["y"] = 0; dir_val["z"] = 1; dec_val["dir"] = dir_val; int sz = out_val["particle"].size(); out_val["particle"][sz] = dec_val; } }<commit_msg>[FIXED] lr打包角色层数据<commit_after>#include "LRLayersPack.h" #include "check_params.h" #include <lr/dataset/Grids.h> #include <lr/dataset/CharacterFileName.h> #include <easyshape.h> namespace edb { std::string LRLayersPack::Command() const { return "lr-pack"; } std::string LRLayersPack::Description() const { return "create shape table from lr file"; } std::string LRLayersPack::Usage() const { // lr-pack e:/test2/test_lr.json std::string usage = Command() + " [filepath]"; return usage; } void LRLayersPack::Run(int argc, char *argv[]) { if (!check_number(this, argc, 3)) return; if (!check_file(argv[2])) return; Run(argv[2]); } void LRLayersPack::Run(const std::string& filepath) { Json::Value lr_val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, lr_val); fin.close(); m_dir = d2d::FilenameTools::getFileDir(filepath) + "\\"; Json::Value out_val; out_val["width"] = lr_val["size"]["width"]; out_val["height"] = lr_val["size"]["height"]; out_val["view width"] = lr_val["size"]["view width"]; out_val["view height"] = lr_val["size"]["view height"]; lr::Grids grids; int w = lr_val["size"]["width"].asUInt(), h = lr_val["size"]["height"].asUInt(); grids.Build(w, h); int col, row; grids.GetGridSize(col, row); out_val["col"] = col; out_val["row"] = row; ParserSpecial(lr_val, out_val); ParserCharacter(lr_val, 2, "character", out_val); ParserPoint(lr_val, 3, "point", out_val); ParserShapeLayer(lr_val, grids, false, 4, "path", out_val); ParserShapeLayer(lr_val, grids, true, 5, "region", out_val); ParserShapeLayer(lr_val, grids, true, 6, "collision region", out_val); ParserCamera(lr_val, 7, "camera", out_val); std::string outfile = filepath.substr(0, filepath.find_last_of('_')) + ".json"; Json::StyledStreamWriter writer; std::locale::global(std::locale("")); std::ofstream fout(outfile.c_str()); std::locale::global(std::locale("C")); writer.write(fout, out_val); fout.close(); } void LRLayersPack::ParserShape(d2d::IShape* shape, const d2d::Vector& offset, const lr::Grids& grids, bool force_grids, Json::Value& out_val) { if (libshape::PolygonShape* poly = dynamic_cast<libshape::PolygonShape*>(shape)) { std::vector<int> grid_idx; std::vector<d2d::Vector> bound = poly->GetVertices(); for (int i = 0, n = bound.size(); i < n; ++i) { bound[i] += offset; } grid_idx = grids.IntersectPolygon(bound); for (int i = 0, n = grid_idx.size(); i < n; ++i) { int sz = out_val["grid"].size(); out_val["grid"][sz] = grid_idx[i]; } } else if (libshape::ChainShape* chain = dynamic_cast<libshape::ChainShape*>(shape)) { std::vector<d2d::Vector> bound = chain->GetVertices(); for (int i = 0, n = bound.size(); i < n; ++i) { bound[i] += offset; } if (force_grids) { std::vector<int> grid_idx; grid_idx = grids.IntersectPolyline(bound); for (int i = 0, n = grid_idx.size(); i < n; ++i) { int sz = out_val["grid"].size(); out_val["grid"][sz] = grid_idx[i]; } } else { d2d::JsonIO::Store(bound, out_val["pos"]); } } else { throw d2d::Exception("LRLayersPack::ParserPolyLayer error shape type"); } } void LRLayersPack::ParserShapeLayer(const Json::Value& src_val, const lr::Grids& grids, bool force_grids, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!src_spr_val.isNull()) { std::string spr_path = d2d::SymbolSearcher::GetSymbolPath(m_dir, src_spr_val); d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->FetchSymbol(spr_path); assert(symbol); Json::Value dst_val; dst_val["name"] = src_spr_val["name"]; d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol); sprite->Load(src_spr_val); libshape::Sprite* shape_spr = dynamic_cast<libshape::Sprite*>(sprite); assert(shape_spr); const std::vector<d2d::IShape*>& shapes = shape_spr->GetSymbol().GetShapes(); for (int i = 0, n = shapes.size(); i < n; ++i) { ParserShape(shapes[i], sprite->GetPosition(), grids, force_grids, dst_val); } int sz = out_val[name].size(); out_val[name][sz] = dst_val; sprite->Release(); symbol->Release(); src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } idx = 0; Json::Value src_shape_val = src_val["layer"][layer_idx]["shape"][idx++]; while (!src_shape_val.isNull()) { d2d::IShape* shape = libshape::ShapeFactory::CreateShapeFromFile(src_shape_val, m_dir); Json::Value dst_val; dst_val["name"] = src_shape_val["name"]; ParserShape(shape, d2d::Vector(0, 0), grids, force_grids, dst_val); int sz = out_val[name].size(); out_val[name][sz] = dst_val; shape->Release(); src_shape_val = src_val["layer"][layer_idx]["shape"][idx++]; } } void LRLayersPack::ParserPoint(const Json::Value& src_val, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { std::string spr_path = d2d::SymbolSearcher::GetSymbolPath(m_dir, spr_val); d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->FetchSymbol(spr_path); if (!symbol) { std::string filepath = spr_val["filepath"].asString(); throw d2d::Exception("Symbol doesn't exist, [dir]:%s, [file]:%s !", m_dir.c_str(), filepath.c_str()); } Json::Value shape_val; shape_val["name"] = spr_val["name"]; d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol); sprite->Load(spr_val); shape_val["x"] = sprite->GetPosition().x; shape_val["y"] = sprite->GetPosition().y; int sz = out_val[name].size(); out_val[name][sz] = shape_val; sprite->Release(); symbol->Release(); spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } void LRLayersPack::ParserCamera(const Json::Value& src_val, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { Json::Value cam_val; cam_val["name"] = spr_val["name"]; cam_val["x"] = spr_val["position"]["x"]; cam_val["y"] = spr_val["position"]["y"]; cam_val["scale"] = spr_val["x scale"]; int sz = out_val[name].size(); out_val[name][sz] = cam_val; spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } void LRLayersPack::ParserCharacter(const Json::Value& src_val, int layer_idx, const char* name, Json::Value& out_val) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { std::string filepath = spr_val["filepath"].asString(); if (d2d::FileNameParser::isType(filepath, d2d::FileNameParser::e_particle3d)) { spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; continue; } Json::Value char_val; char_val["name"] = spr_val["name"]; char_val["x"] = spr_val["position"]["x"]; char_val["y"] = spr_val["position"]["y"]; // tags std::string tag = spr_val["tag"].asString(); std::vector<std::string> tags; int pos = tag.find_first_of(';'); tags.push_back(tag.substr(0, pos)); do { int next_pos = tag.find_first_of(';', pos + 1); tags.push_back(tag.substr(pos + 1, next_pos - pos - 1)); pos = next_pos; } while (pos != std::string::npos); for (int i = 0, n = tags.size(); i < n; ++i) { const std::string& str = tags[i]; int pos = str.find_first_of('='); std::string key = str.substr(0, pos); std::string val = str.substr(pos+1); char_val["tag"][key] = val; } // filename std::string filename = d2d::FilenameTools::getFilename(filepath); lr::CharacterFileName out_name(filename); char_val["filename"] = out_name.GetOutputName(); // angle int dir = 1 + (out_name.GetField(lr::CharacterFileName::FT_DIRECTION)[0] - '1'); if (spr_val["x mirror"].asBool()) { dir = 10 - dir; } dir = (dir + 7) % 8; char_val["angle"] = dir + 1; int sz = out_val[name].size(); out_val[name][sz] = char_val; spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } void LRLayersPack::ParserSpecial(const Json::Value& src_val, Json::Value& out_val) { for (int layer_idx = 0; layer_idx < 3; ++layer_idx) { int idx = 0; Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; while (!spr_val.isNull()) { std::string filepath = spr_val["filepath"].asString(); std::string tag = spr_val["tag"].asString(); if (d2d::FileNameParser::isType(filepath, d2d::FileNameParser::e_particle3d)) { ParserParticleLayer(spr_val, out_val); } else if (tag.find("layer=cover") != std::string::npos) { ParserSpecialLayer(spr_val, "cover", out_val); } else if (tag.find("layer=top") != std::string::npos) { ParserSpecialLayer(spr_val, "top", out_val); } spr_val = src_val["layer"][layer_idx]["sprite"][idx++]; } } } void LRLayersPack::ParserSpecialLayer(const Json::Value& spr_val, const std::string& name, Json::Value& out_val) { Json::Value dec_val; float px = spr_val["position"]["x"].asDouble(), py = spr_val["position"]["y"].asDouble(); std::string export_name = ""; wxString spr_path = d2d::SymbolSearcher::GetSymbolPath(m_dir, spr_val); if (spr_path.Contains(".json")) { Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(spr_path.fn_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); export_name = val["name"].asString(); int idx = 0; const Json::Value& spr_val = val["sprite"][idx]; float cx = spr_val["position"]["x"].asDouble(), cy = spr_val["position"]["y"].asDouble(); px += cx; py += cy; } dec_val["export"] = export_name; dec_val["x"] = px; dec_val["y"] = py; int sz = out_val[name].size(); out_val[name][sz] = dec_val; } void LRLayersPack::ParserParticleLayer(const Json::Value& spr_val, Json::Value& out_val) { Json::Value dec_val; dec_val["x"] = spr_val["position"]["x"].asDouble(); dec_val["y"] = spr_val["position"]["y"].asDouble(); std::string sym_path = spr_val["filepath"].asString(); Json::Value sym_val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(sym_path.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, sym_val); fin.close(); dec_val["export"] = sym_val["name"].asString(); Json::Value dir_val; dir_val["x"] = 0; dir_val["y"] = 0; dir_val["z"] = 1; dec_val["dir"] = dir_val; int sz = out_val["particle"].size(); out_val["particle"][sz] = dec_val; } }<|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Ruben Dörfel <[email protected]>; * @version dev * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Example for cHPI fitting on raw data with SSP. The result is written to a .txt file for comparison with MaxFilter's .pos file. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <vector> #include <fiff/fiff.h> #include <fiff/fiff_info.h> #include <fiff/fiff_dig_point_set.h> #include <inverse/hpiFit/hpifit.h> #include <utils/ioutils.h> #include <utils/generics/applicationlogger.h> #include <utils/mnemath.h> #include <fwd/fwd_coil_set.h> //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QFile> #include <QCommandLineParser> #include <QDebug> #include <QGenericMatrix> #include <QElapsedTimer> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace INVERSELIB; using namespace FIFFLIB; using namespace UTILSLIB; using namespace Eigen; //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { qInstallMessageHandler(ApplicationLogger::customLogWriter); QElapsedTimer timer; QCoreApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("hpiFit Example"); parser.addHelpOption(); qInfo() << "Please download the mne-cpp-test-data folder from Github (mne-tools) into mne-cpp/bin."; QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/raw/data_with_movement_chpi_raw.fif"); parser.addOption(inputOption); parser.process(a); // Init data loading and writing QFile t_fileIn(parser.value(inputOption)); FiffRawData raw(t_fileIn); QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(raw.info)); // Setup comparison of transformation matrices FiffCoordTrans transDevHead = pFiffInfo->dev_head_t; // transformation that only updates after big head movements float fThreshRot = 5; // in degree float fThreshTrans = 0.005; // in m // Set up the reading parameters RowVectorXi vPicks = pFiffInfo->pick_types(true, false, false); MatrixXd mData, mTimes; fiff_int_t from, to; fiff_int_t first = raw.first_samp; fiff_int_t last = raw.last_samp; float dTSec = 0.1; // time between hpi fits float fQuantumSec = 0.2f; // read and write in 200 ms junks fiff_int_t iQuantum = ceil(fQuantumSec*pFiffInfo->sfreq); // // create time vector that specifies when to fit // int iN = ceil((last-first)/iQuantum); // RowVectorXf vTime = RowVectorXf::LinSpaced(iN, 0, iN-1) * dTSec; // To fit at specific times outcommend the following block // Read Quaternion File MatrixXd pos; qInfo() << "Specify the path to your Position file (.txt)"; IOUtils::read_eigen_matrix(pos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/pos/posMax_data_with_movement_chpi.txt"); RowVectorXd vTime = pos.col(0); MatrixXd mPosition; // mPosition matrix to save quaternions etc. // setup informations for HPI fit (VectorView) QVector<int> vFreqs {154,158,161,166}; QVector<double> vError; VectorXd vGoF; FiffDigPointSet fittedPointSet; // Use SSP + SGM + calibration MatrixXd mProjectors = MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size()); //Do a copy here because we are going to change the activity flags of the SSP's FiffInfo infoTemp = *(pFiffInfo.data()); //Turn on all SSP for(int i = 0; i < infoTemp.projs.size(); ++i) { infoTemp.projs[i].active = true; } //Create the projector for all SSP's on infoTemp.make_projector(mProjectors); //set columns of matrix to zero depending on bad channels indexes for(qint32 j = 0; j < infoTemp.bads.size(); ++j) { mProjectors.col(infoTemp.ch_names.indexOf(infoTemp.bads.at(j))).setZero(); } // if debugging files are necessary set bDoDebug = true; QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug"; bool bDoDebug = false; HPIFit HPI = HPIFit(pFiffInfo); // ordering of frequencies from = first + vTime(0)*pFiffInfo->sfreq; to = from + iQuantum; if(!raw.read_raw_segment(mData, mTimes, from, to)) { qCritical("error during read_raw_segment"); return -1; } qInfo() << "[done]"; // order frequencies qInfo() << "Find Order..."; timer.start(); HPI.findOrder(mData, mProjectors, pFiffInfo->dev_head_t, vFreqs, vError, vGoF, fittedPointSet, pFiffInfo); qInfo() << "Ordered Frequencies: "; qInfo() << "findOrder() took" << timer.elapsed() << "milliseconds"; qInfo() << "[done]"; float fTimer = 0.0; // read and fit for(int i = 0; i < vTime.size(); i++) { from = first + vTime(i)*pFiffInfo->sfreq; to = from + iQuantum; if (to > last) { to = last; qWarning() << "Block size < iQuantum " << iQuantum; } // Reading if(!raw.read_raw_segment(mData, mTimes, from, to)) { qCritical("error during read_raw_segment"); return -1; } qInfo() << "[done]"; qInfo() << "HPI-Fit..."; timer.start(); HPI.fitHPI(mData, mProjectors, pFiffInfo->dev_head_t, vFreqs, vError, vGoF, fittedPointSet, pFiffInfo, bDoDebug, sHPIResourceDir); fTimer = timer.elapsed(); qInfo() << "The HPI-Fit took" << fTimer << "milliseconds"; qInfo() << "[done]"; HPIFit::storeHeadPosition(vTime(i), pFiffInfo->dev_head_t.trans, mPosition, vGoF, vError); mPosition(i,9) = fTimer; // if big head displacement occures, update debHeadTrans if(MNEMath::compareTransformation(transDevHead.trans, pFiffInfo->dev_head_t.trans, fThreshRot, fThreshTrans)) { transDevHead = pFiffInfo->dev_head_t; qInfo() << "dev_head_t has been updated."; } } IOUtils::write_eigen_matrix(mPosition, QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/pos/pos_01_Faster_MEG.txt"); } <commit_msg>Temp: change file path in example<commit_after>//============================================================================================================= /** * @file main.cpp * @author Ruben Dörfel <[email protected]>; * @version dev * @date January, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Example for cHPI fitting on raw data with SSP. The result is written to a .txt file for comparison with MaxFilter's .pos file. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include <iostream> #include <vector> #include <fiff/fiff.h> #include <fiff/fiff_info.h> #include <fiff/fiff_dig_point_set.h> #include <inverse/hpiFit/hpifit.h> #include <utils/ioutils.h> #include <utils/generics/applicationlogger.h> #include <utils/mnemath.h> #include <fwd/fwd_coil_set.h> //============================================================================================================= // Qt INCLUDES //============================================================================================================= #include <QtCore/QCoreApplication> #include <QFile> #include <QCommandLineParser> #include <QDebug> #include <QGenericMatrix> #include <QElapsedTimer> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace INVERSELIB; using namespace FIFFLIB; using namespace UTILSLIB; using namespace Eigen; //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { qInstallMessageHandler(ApplicationLogger::customLogWriter); QElapsedTimer timer; QCoreApplication a(argc, argv); // Command Line Parser QCommandLineParser parser; parser.setApplicationDescription("hpiFit Example"); parser.addHelpOption(); qInfo() << "Please download the mne-cpp-test-data folder from Github (mne-tools) into mne-cpp/bin."; QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/raw/data_with_movement_chpi_raw.fif"); parser.addOption(inputOption); parser.process(a); // Init data loading and writing QFile t_fileIn(parser.value(inputOption)); FiffRawData raw(t_fileIn); QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(raw.info)); // Setup comparison of transformation matrices FiffCoordTrans transDevHead = pFiffInfo->dev_head_t; // transformation that only updates after big head movements float fThreshRot = 5; // in degree float fThreshTrans = 0.005; // in m // Set up the reading parameters RowVectorXi vPicks = pFiffInfo->pick_types(true, false, false); MatrixXd mData, mTimes; fiff_int_t from, to; fiff_int_t first = raw.first_samp; fiff_int_t last = raw.last_samp; float dTSec = 0.1; // time between hpi fits float fQuantumSec = 0.2f; // read and write in 200 ms junks fiff_int_t iQuantum = ceil(fQuantumSec*pFiffInfo->sfreq); // // create time vector that specifies when to fit // int iN = ceil((last-first)/iQuantum); // RowVectorXf vTime = RowVectorXf::LinSpaced(iN, 0, iN-1) * dTSec; // To fit at specific times outcommend the following block // Read Quaternion File MatrixXd pos; qInfo() << "Specify the path to your Position file (.txt)"; IOUtils::read_eigen_matrix(pos, QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/pos/posMax_data_with_movement_chpi.txt"); RowVectorXd vTime = pos.col(0); MatrixXd mPosition; // mPosition matrix to save quaternions etc. // setup informations for HPI fit (VectorView) QVector<int> vFreqs {154,158,161,166}; QVector<double> vError; VectorXd vGoF; FiffDigPointSet fittedPointSet; // Use SSP + SGM + calibration MatrixXd mProjectors = MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size()); //Do a copy here because we are going to change the activity flags of the SSP's FiffInfo infoTemp = *(pFiffInfo.data()); //Turn on all SSP for(int i = 0; i < infoTemp.projs.size(); ++i) { infoTemp.projs[i].active = true; } //Create the projector for all SSP's on infoTemp.make_projector(mProjectors); //set columns of matrix to zero depending on bad channels indexes for(qint32 j = 0; j < infoTemp.bads.size(); ++j) { mProjectors.col(infoTemp.ch_names.indexOf(infoTemp.bads.at(j))).setZero(); } // if debugging files are necessary set bDoDebug = true; QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug"; bool bDoDebug = false; HPIFit HPI = HPIFit(pFiffInfo); // ordering of frequencies from = first + vTime(0)*pFiffInfo->sfreq; to = from + iQuantum; if(!raw.read_raw_segment(mData, mTimes, from, to)) { qCritical("error during read_raw_segment"); return -1; } qInfo() << "[done]"; // order frequencies qInfo() << "Find Order..."; timer.start(); HPI.findOrder(mData, mProjectors, pFiffInfo->dev_head_t, vFreqs, vError, vGoF, fittedPointSet, pFiffInfo); qInfo() << "Ordered Frequencies: "; qInfo() << "findOrder() took" << timer.elapsed() << "milliseconds"; qInfo() << "[done]"; float fTimer = 0.0; // read and fit for(int i = 0; i < vTime.size(); i++) { from = first + vTime(i)*pFiffInfo->sfreq; to = from + iQuantum; if (to > last) { to = last; qWarning() << "Block size < iQuantum " << iQuantum; } // Reading if(!raw.read_raw_segment(mData, mTimes, from, to)) { qCritical("error during read_raw_segment"); return -1; } qInfo() << "[done]"; qInfo() << "HPI-Fit..."; timer.start(); HPI.fitHPI(mData, mProjectors, pFiffInfo->dev_head_t, vFreqs, vError, vGoF, fittedPointSet, pFiffInfo, bDoDebug, sHPIResourceDir); fTimer = timer.elapsed(); qInfo() << "The HPI-Fit took" << fTimer << "milliseconds"; qInfo() << "[done]"; HPIFit::storeHeadPosition(vTime(i), pFiffInfo->dev_head_t.trans, mPosition, vGoF, vError); mPosition(i,9) = fTimer; // if big head displacement occures, update debHeadTrans if(MNEMath::compareTransformation(transDevHead.trans, pFiffInfo->dev_head_t.trans, fThreshRot, fThreshTrans)) { transDevHead = pFiffInfo->dev_head_t; qInfo() << "dev_head_t has been updated."; } } IOUtils::write_eigen_matrix(mPosition, QCoreApplication::applicationDirPath() + "/MNE-sample-data/chpi/pos/pos_02_Faster_MEG.txt"); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 #if defined(OS_LINUX) #define MAYBE_Instance FLAKY_Instance #else #define MAYBE_Instance Instance #endif TEST_PPAPI_OUT_OF_PROCESS(MAYBE_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) TEST_PPAPI_OUT_OF_PROCESS(PostMessage) TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(QueryPolicy) //TEST_PPAPI_OUT_OF_PROCESS(QueryPolicy) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/90040 TEST_F(OutOfProcessPPAPITest, FLAKY_FileSystem) { RunTestViaHTTP("FileSystem"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84295 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } TEST_PPAPI_IN_PROCESS(VideoDecoder) // There is no proxy yet (vrk is adding it). TEST_F(OutOfProcessPPAPITest, FAILS_VideoDecoder) { RunTest("VideoDecoder"); } <commit_msg>Revert 95540 - Marked OutOfProcessPPAPITest.Instance flaky.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // First wait for the "starting" signal. This cookie is set at the start // of every test. Waiting for this separately allows us to avoid a single // long timeout. Instead, we can have two timeouts which allow startup + // test execution time to take a while on a loaded computer, while also // making sure we're making forward progress. std::string startup_cookie = WaitUntilCookieNonEmpty(tab.get(), test_url, "STARTUP_COOKIE", TestTimeouts::action_max_timeout_ms()); // If this fails, the plugin couldn't be loaded in the given amount of // time. This may mean the plugin was not found or possibly the system // can't load it due to missing symbols, etc. ASSERT_STREQ("STARTED", startup_cookie.c_str()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", TestTimeouts::large_test_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) TEST_PPAPI_OUT_OF_PROCESS(Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) TEST_PPAPI_OUT_OF_PROCESS(PostMessage) TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(QueryPolicy) //TEST_PPAPI_OUT_OF_PROCESS(QueryPolicy) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_F(OutOfProcessPPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/90040 TEST_F(OutOfProcessPPAPITest, FLAKY_FileSystem) { RunTestViaHTTP("FileSystem"); } #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84295 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } TEST_PPAPI_IN_PROCESS(VideoDecoder) // There is no proxy yet (vrk is adding it). TEST_F(OutOfProcessPPAPITest, FAILS_VideoDecoder) { RunTest("VideoDecoder"); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // Flakey, http:L//crbug.com/57053 TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } // TODO(dumi): figure out why this test is flaky on Mac and fix it. #if defined(OS_MACOSX) #define DISABLED_ON_MAC(test_name) DISABLED_##test_name #else #define DISABLED_ON_MAC(test_name) test_name #endif TEST_F(PPAPITest, DISABLED_ON_MAC(FileIO)) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } <commit_msg>Looks like PPAPITest.FileIO fails on Win XP (dbg) too, disable for now...<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/glue/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Give unlimited quota for files to Pepper tests. // TODO(dumi): remove this switch once we have a quota management // system in place. launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; replacements.SetQuery(test_case.c_str(), url_parse::Component(0, test_case.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL(test_server.GetURL("files/test_case.html?" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; TEST_F(PPAPITest, FAILS_Instance) { RunTest("Instance"); } TEST_F(PPAPITest, Graphics2D) { RunTest("Graphics2D"); } // TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating. // Possibly all the image allocations slow things down on a loaded bot too much. TEST_F(PPAPITest, FLAKY_ImageData) { RunTest("ImageData"); } TEST_F(PPAPITest, Buffer) { RunTest("Buffer"); } // Flakey, http:L//crbug.com/57053 TEST_F(PPAPITest, FLAKY_URLLoader) { RunTestViaHTTP("URLLoader"); } // Flaky, http://crbug.com/51012 TEST_F(PPAPITest, FLAKY_PaintAggregator) { RunTestViaHTTP("PaintAggregator"); } // Flaky, http://crbug.com/48544. TEST_F(PPAPITest, FLAKY_Scrollbar) { RunTest("Scrollbar"); } TEST_F(PPAPITest, UrlUtil) { RunTest("UrlUtil"); } TEST_F(PPAPITest, CharSet) { RunTest("CharSet"); } TEST_F(PPAPITest, Var) { RunTest("Var"); } // TODO(dumi): figure out why this test is flaky on Mac and Win XP (dbg). #if defined(OS_MACOSX) || defined(OS_WIN) #define DISABLED_ON_MAC_AND_WIN(test_name) DISABLED_##test_name #else #define DISABLED_ON_MAC_AND_WIN(test_name) test_name #endif TEST_F(PPAPITest, DISABLED_ON_MAC_AND_WIN(FileIO)) { RunTestViaHTTP("FileIO"); } TEST_F(PPAPITest, FileRef) { RunTestViaHTTP("FileRef"); } TEST_F(PPAPITest, DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/worker_host/worker_service.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_layout_test.h" static const char kTestCompleteCookie[] = "status"; static const char kTestCompleteSuccess[] = "OK"; class WorkerTest : public UILayoutTest { protected: virtual ~WorkerTest() { } void RunTest(const std::wstring& test_case) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url = GetTestUrl(L"workers", test_case); ASSERT_TRUE(tab->NavigateToURL(url)); std::string value = WaitUntilCookieNonEmpty(tab.get(), url, kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs); ASSERT_STREQ(kTestCompleteSuccess, value.c_str()); } }; TEST_F(WorkerTest, SingleWorker) { RunTest(L"single_worker.html"); } TEST_F(WorkerTest, MultipleWorkers) { RunTest(L"multi_worker.html"); } TEST_F(WorkerTest, WorkerFastLayoutTests) { static const char* kLayoutTestFiles[] = { "stress-js-execution.html", "use-machine-stack.html", "worker-call.html", //"worker-close.html", "worker-constructor.html", "worker-context-gc.html", "worker-event-listener.html", "worker-gc.html", "worker-location.html", "worker-messageport.html", "worker-navigator.html", "worker-replace-global-constructor.html", "worker-replace-self.html", "worker-script-error.html", "worker-terminate.html", "worker-timeout.html" }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } TEST_F(WorkerTest, WorkerHttpLayoutTests) { static const char* kLayoutTestFiles[] = { // flakey? BUG 16934 "text-encoding.html", "worker-importScripts.html", "worker-redirect.html", }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) { static const char* kLayoutTestFiles[] = { "abort-exception-assert.html", "close.html", //"methods-async.html", //"methods.html", "xmlhttprequest-file-not-found.html" }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest"); worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, MessagePorts) { static const char* kLayoutTestFiles[] = { "message-channel-gc.html", "message-channel-gc-2.html", "message-channel-gc-3.html", "message-channel-gc-4.html", "message-port.html", "message-port-clone.html", "message-port-constructor-for-deleted-document.html", "message-port-deleted-document.html", "message-port-deleted-frame.html", "message-port-inactive-document.html", "message-port-no-wrapper.html", // Only works with run-webkit-tests --leaks. //"message-channel-listener-circular-ownership.html", }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("events"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } TEST_F(WorkerTest, LimitPerPage) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1), UITest::GetBrowserProcessCount()); } TEST_F(WorkerTest, LimitTotal) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; int total_workers = WorkerService::kMaxWorkersWhenSeparate; int tab_count = (total_workers / max_workers_per_tab) + 1; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); for (int i = 1; i < tab_count; ++i) window->AppendTab(url); // Check that we didn't create more than the max number of workers. EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count), UITest::GetBrowserProcessCount()); // Now close the first tab and check that the queued workers were started. tab->Close(true); tab->NavigateToURL(GetTestUrl(L"google", L"google.html")); EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count), UITest::GetBrowserProcessCount()); } <commit_msg>Disable WorkerTest::WorkerFastLayoutTests<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/worker_host/worker_service.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_layout_test.h" static const char kTestCompleteCookie[] = "status"; static const char kTestCompleteSuccess[] = "OK"; class WorkerTest : public UILayoutTest { protected: virtual ~WorkerTest() { } void RunTest(const std::wstring& test_case) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url = GetTestUrl(L"workers", test_case); ASSERT_TRUE(tab->NavigateToURL(url)); std::string value = WaitUntilCookieNonEmpty(tab.get(), url, kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs); ASSERT_STREQ(kTestCompleteSuccess, value.c_str()); } }; TEST_F(WorkerTest, SingleWorker) { RunTest(L"single_worker.html"); } TEST_F(WorkerTest, MultipleWorkers) { RunTest(L"multi_worker.html"); } TEST_F(WorkerTest, DISABLED_WorkerFastLayoutTests) { static const char* kLayoutTestFiles[] = { "stress-js-execution.html", "use-machine-stack.html", "worker-call.html", //"worker-close.html", "worker-constructor.html", "worker-context-gc.html", "worker-event-listener.html", "worker-gc.html", "worker-location.html", "worker-messageport.html", "worker-navigator.html", "worker-replace-global-constructor.html", "worker-replace-self.html", "worker-script-error.html", "worker-terminate.html", "worker-timeout.html" }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } TEST_F(WorkerTest, WorkerHttpLayoutTests) { static const char* kLayoutTestFiles[] = { // flakey? BUG 16934 "text-encoding.html", "worker-importScripts.html", "worker-redirect.html", }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) { static const char* kLayoutTestFiles[] = { "abort-exception-assert.html", "close.html", //"methods-async.html", //"methods.html", "xmlhttprequest-file-not-found.html" }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest"); worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, MessagePorts) { static const char* kLayoutTestFiles[] = { "message-channel-gc.html", "message-channel-gc-2.html", "message-channel-gc-3.html", "message-channel-gc-4.html", "message-port.html", "message-port-clone.html", "message-port-constructor-for-deleted-document.html", "message-port-deleted-document.html", "message-port-deleted-frame.html", "message-port-inactive-document.html", "message-port-no-wrapper.html", // Only works with run-webkit-tests --leaks. //"message-channel-listener-circular-ownership.html", }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("events"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } TEST_F(WorkerTest, LimitPerPage) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1), UITest::GetBrowserProcessCount()); } TEST_F(WorkerTest, LimitTotal) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; int total_workers = WorkerService::kMaxWorkersWhenSeparate; int tab_count = (total_workers / max_workers_per_tab) + 1; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); for (int i = 1; i < tab_count; ++i) window->AppendTab(url); // Check that we didn't create more than the max number of workers. EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count), UITest::GetBrowserProcessCount()); // Now close the first tab and check that the queued workers were started. tab->Close(true); tab->NavigateToURL(GetTestUrl(L"google", L"google.html")); EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count), UITest::GetBrowserProcessCount()); } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright 2016 Davide Faconti * 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 Willow Garage, Inc. 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. ********************************************************************/ #include <boost/algorithm/string.hpp> #include <boost/utility/string_ref.hpp> #include "ros_type_introspection/renamer.hpp" #include "ros_type_introspection/ros_introspection.hpp" namespace RosIntrospection{ inline bool isNumberPlaceholder( const SString& s) { return s.size() == 1 && s.at(0) == '#'; } inline bool isSubstitutionPlaceholder( const SString& s) { return s.size() == 1 && s.at(0) == '@'; } // given a leaf of the tree, that can have multiple index_array, // find the only index which corresponds to the # in the pattern int PatternMatchAndIndexPosition(const StringTreeLeaf& leaf, const StringTreeNode* pattern_head ) { const StringTreeNode* node_ptr = leaf.node_ptr; int pos = leaf.array_size-1; while( node_ptr ) { if( node_ptr != pattern_head ) { if( isNumberPlaceholder( node_ptr->value() )) { pos--; } } else{ return pos; } node_ptr = node_ptr->parent(); } // end while return -1; } void Parser::applyNameTransform(const std::string& msg_identifier, const ROSTypeFlat& container, RenamedValues *renamed_value ) { const std::vector<RulesCache>& rules_cache = _registered_rules[msg_identifier]; const size_t num_values = container.value.size(); const size_t num_names = container.name.size(); renamed_value->resize( container.value.size() ); //DO NOT clear() renamed_value static std::vector<int> alias_array_pos; static std::vector<SString> formatted_string; static std::vector<int8_t> substituted; alias_array_pos.reserve( num_names ); alias_array_pos.clear(); formatted_string.reserve( num_values ); formatted_string.clear(); substituted.resize( num_values ); for(size_t i=0; i<num_values; i++) { substituted[i] = false; } size_t renamed_index = 0; for(const RulesCache& cache: rules_cache) { const SubstitutionRule& rule = cache.rule; const StringTreeNode* pattern_head = cache.pattern_head; const StringTreeNode* alias_head = cache.alias_head; if( !pattern_head ) continue; if( !alias_head ) continue; for (size_t n=0; n<num_names; n++) { const StringTreeLeaf& alias_leaf = container.name[n].first; alias_array_pos[n] = PatternMatchAndIndexPosition(alias_leaf, alias_head); } for(size_t i=0; i<num_values; i++) { if( substituted[i]) continue; const auto& value_leaf = container.value[i]; const StringTreeLeaf& leaf = value_leaf.first; int pattern_array_pos = PatternMatchAndIndexPosition(leaf, pattern_head); if( pattern_array_pos>= 0) // -1 if pattern doesn't match { const SString* new_name = nullptr; for (size_t n=0; n < num_names; n++) { const auto & it = container.name[n]; const StringTreeLeaf& alias_leaf = it.first; if( alias_array_pos[n] >= 0 ) // -1 if pattern doesn't match { if( alias_leaf.index_array[ alias_array_pos[n] ] == leaf.index_array[ pattern_array_pos] ) { new_name = &(it.second); break; } } } //-------------------------- if( new_name ) { int char_count = 0; static std::vector<const SString*> concatenated_name; concatenated_name.reserve( 10 ); concatenated_name.clear(); const StringTreeNode* node_ptr = leaf.node_ptr; int position = leaf.array_size - 1; while( node_ptr != pattern_head) { const SString* value = &node_ptr->value(); if( isNumberPlaceholder( *value) ){ char buffer[16]; int str_size = print_number( buffer, leaf.index_array[position--] ); formatted_string.push_back( SString(buffer, str_size) ); value = &formatted_string.back(); } char_count += value->size(); concatenated_name.push_back( value ); node_ptr = node_ptr->parent(); } for (int s = rule.substitution().size()-1; s >= 0; s--) { const SString* value = &rule.substitution()[s]; if( isSubstitutionPlaceholder( *value) ) { value = new_name; position--; } char_count += value->size(); concatenated_name.push_back( value ); } for (size_t p = 0; p < rule.pattern().size() && node_ptr; p++) { node_ptr = node_ptr->parent(); } while( node_ptr ) { const SString* value = &node_ptr->value(); if( isNumberPlaceholder( *value) ){ char buffer[16]; int str_size = print_number( buffer, leaf.index_array[position--] ); formatted_string.push_back( SString(buffer, str_size) ); value = &formatted_string.back(); } char_count += value->size(); concatenated_name.push_back( value ); node_ptr = node_ptr->parent(); } //------------------------ std::string& new_identifier = (*renamed_value)[renamed_index].first; new_identifier.clear(); for (int c = concatenated_name.size()-1; c >= 0; c--) { new_identifier.append( concatenated_name[c]->data(), concatenated_name[c]->size() ); if( c>0 ) new_identifier.append("/",1); } (*renamed_value)[renamed_index].second = value_leaf.second ; renamed_index++; substituted[i] = true; }// end if( new_name ) else { } }// end if( PatternMatching ) else { } } // end for values } // end for rules for(size_t i=0; i< container.value.size(); i++) { if( !substituted[i] ) { const std::pair<StringTreeLeaf, Variant> & value_leaf = container.value[i]; std::string& destination = (*renamed_value)[renamed_index].first; value_leaf.first.toStr( destination ); (*renamed_value)[renamed_index].second = value_leaf.second ; renamed_index++; } } } SubstitutionRule::SubstitutionRule(const char *pattern, const char *alias, const char *substitution) { std::vector<std::string> split_text; boost::split(split_text, pattern, boost::is_any_of("./")); _pattern.reserve(split_text.size()); for (const auto& part: split_text){ if(part.size()>0) _pattern.push_back( part ); } boost::split(split_text, alias, boost::is_any_of("./")); _alias.reserve(split_text.size()); for (const auto& part: split_text){ if(part.size()>0) _alias.push_back( part ); } boost::split(split_text, substitution, boost::is_any_of("./")); _substitution.reserve(split_text.size()); for (const auto& part: split_text){ if(part.size()>0) _substitution.push_back( part ); } size_t h1 = std::hash<std::string>{}(pattern); size_t h2 = std::hash<std::string>{}(alias); size_t h3 = std::hash<std::string>{}(substitution); _hash = (h1 ^ (h2 << 1)) ^ (h3 << 1 ); } inline bool FindPattern(const std::vector<SString> &pattern, size_t index, const StringTreeNode *tail, const StringTreeNode **head) { if( tail->value() == pattern[index]) { index++; } else{ // mismatch if( index > 0 ){ // reset counter; FindPattern( pattern, 0, tail, head); return false; } index = 0; } if( index == pattern.size()){ *head = ( tail ); return true; } bool found = false; for (auto& child: tail->children() ) { found = FindPattern( pattern, index, &child, head); if( found) break; } return found; } void Parser::registerRenamingRules(const ROSType &type, const std::vector<SubstitutionRule> &rules) { for(const auto& it: _registred_messages) { const std::string& msg_identifier = it.first; const ROSMessageInfo& msg_info = it.second; if( getMessageByType(type, msg_info) ) { std::vector<RulesCache>& cache_vector = _registered_rules[msg_identifier]; for(const auto& rule: rules ) { RulesCache cache(rule); FindPattern( cache.rule.pattern(), 0, msg_info.string_tree.croot(), &cache.pattern_head ); FindPattern( cache.rule.alias(), 0, msg_info.string_tree.croot(), &cache.alias_head ); if( cache.pattern_head && cache.alias_head && std::find( cache_vector.begin(), cache_vector.end(), cache) == cache_vector.end() ) { cache_vector.push_back( std::move(cache) ); } } } } _block_register_message = true; } } //end namespace <commit_msg>according to Valgrind, this is much faster<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright 2016 Davide Faconti * 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 Willow Garage, Inc. 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. ********************************************************************/ #include <boost/algorithm/string.hpp> #include <boost/utility/string_ref.hpp> #include "ros_type_introspection/renamer.hpp" #include "ros_type_introspection/ros_introspection.hpp" namespace RosIntrospection{ inline bool isNumberPlaceholder( const SString& s) { return s.size() == 1 && s.at(0) == '#'; } inline bool isSubstitutionPlaceholder( const SString& s) { return s.size() == 1 && s.at(0) == '@'; } // given a leaf of the tree, that can have multiple index_array, // find the only index which corresponds to the # in the pattern int PatternMatchAndIndexPosition(const StringTreeLeaf& leaf, const StringTreeNode* pattern_head ) { const StringTreeNode* node_ptr = leaf.node_ptr; int pos = leaf.array_size-1; while( node_ptr ) { if( node_ptr != pattern_head ) { if( isNumberPlaceholder( node_ptr->value() )) { pos--; } } else{ return pos; } node_ptr = node_ptr->parent(); } // end while return -1; } void Parser::applyNameTransform(const std::string& msg_identifier, const ROSTypeFlat& container, RenamedValues *renamed_value ) { const std::vector<RulesCache>& rules_cache = _registered_rules[msg_identifier]; const size_t num_values = container.value.size(); const size_t num_names = container.name.size(); renamed_value->resize( container.value.size() ); //DO NOT clear() renamed_value static std::vector<int> alias_array_pos; static std::vector<SString> formatted_string; static std::vector<int8_t> substituted; alias_array_pos.reserve( num_names ); alias_array_pos.clear(); formatted_string.reserve( num_values ); formatted_string.clear(); substituted.resize( num_values ); for(size_t i=0; i<num_values; i++) { substituted[i] = false; } size_t renamed_index = 0; for(const RulesCache& cache: rules_cache) { const SubstitutionRule& rule = cache.rule; const StringTreeNode* pattern_head = cache.pattern_head; const StringTreeNode* alias_head = cache.alias_head; if( !pattern_head ) continue; if( !alias_head ) continue; for (size_t n=0; n<num_names; n++) { const StringTreeLeaf& alias_leaf = container.name[n].first; alias_array_pos[n] = PatternMatchAndIndexPosition(alias_leaf, alias_head); } for(size_t i=0; i<num_values; i++) { if( substituted[i]) continue; const auto& value_leaf = container.value[i]; const StringTreeLeaf& leaf = value_leaf.first; int pattern_array_pos = PatternMatchAndIndexPosition(leaf, pattern_head); if( pattern_array_pos>= 0) // -1 if pattern doesn't match { const SString* new_name = nullptr; for (size_t n=0; n < num_names; n++) { const auto & it = container.name[n]; const StringTreeLeaf& alias_leaf = it.first; if( alias_array_pos[n] >= 0 ) // -1 if pattern doesn't match { if( alias_leaf.index_array[ alias_array_pos[n] ] == leaf.index_array[ pattern_array_pos] ) { new_name = &(it.second); break; } } } //-------------------------- if( new_name ) { int char_count = 0; static std::vector<const SString*> concatenated_name; concatenated_name.reserve( 10 ); concatenated_name.clear(); const StringTreeNode* node_ptr = leaf.node_ptr; int position = leaf.array_size - 1; while( node_ptr != pattern_head) { const SString* value = &node_ptr->value(); if( isNumberPlaceholder( *value) ){ char buffer[16]; int str_size = print_number( buffer, leaf.index_array[position--] ); formatted_string.push_back( SString(buffer, str_size) ); value = &formatted_string.back(); } char_count += value->size(); concatenated_name.push_back( value ); node_ptr = node_ptr->parent(); } for (int s = rule.substitution().size()-1; s >= 0; s--) { const SString* value = &rule.substitution()[s]; if( isSubstitutionPlaceholder( *value) ) { value = new_name; position--; } char_count += value->size(); concatenated_name.push_back( value ); } for (size_t p = 0; p < rule.pattern().size() && node_ptr; p++) { node_ptr = node_ptr->parent(); } while( node_ptr ) { const SString* value = &node_ptr->value(); if( isNumberPlaceholder( *value) ){ char buffer[16]; int str_size = print_number( buffer, leaf.index_array[position--] ); formatted_string.push_back( SString(buffer, str_size) ); value = &formatted_string.back(); } char_count += value->size(); concatenated_name.push_back( value ); node_ptr = node_ptr->parent(); } //------------------------ std::string& new_identifier = (*renamed_value)[renamed_index].first; new_identifier.clear(); for (int c = concatenated_name.size()-1; c >= 0; c--) { new_identifier.append( concatenated_name[c]->data(), concatenated_name[c]->size() ); if( c>0 ) new_identifier += '/'; } (*renamed_value)[renamed_index].second = value_leaf.second ; renamed_index++; substituted[i] = true; }// end if( new_name ) else { } }// end if( PatternMatching ) else { } } // end for values } // end for rules for(size_t i=0; i< container.value.size(); i++) { if( !substituted[i] ) { const std::pair<StringTreeLeaf, Variant> & value_leaf = container.value[i]; std::string& destination = (*renamed_value)[renamed_index].first; value_leaf.first.toStr( destination ); (*renamed_value)[renamed_index].second = value_leaf.second ; renamed_index++; } } } SubstitutionRule::SubstitutionRule(const char *pattern, const char *alias, const char *substitution) { std::vector<std::string> split_text; boost::split(split_text, pattern, boost::is_any_of("./")); _pattern.reserve(split_text.size()); for (const auto& part: split_text){ if(part.size()>0) _pattern.push_back( part ); } boost::split(split_text, alias, boost::is_any_of("./")); _alias.reserve(split_text.size()); for (const auto& part: split_text){ if(part.size()>0) _alias.push_back( part ); } boost::split(split_text, substitution, boost::is_any_of("./")); _substitution.reserve(split_text.size()); for (const auto& part: split_text){ if(part.size()>0) _substitution.push_back( part ); } size_t h1 = std::hash<std::string>{}(pattern); size_t h2 = std::hash<std::string>{}(alias); size_t h3 = std::hash<std::string>{}(substitution); _hash = (h1 ^ (h2 << 1)) ^ (h3 << 1 ); } inline bool FindPattern(const std::vector<SString> &pattern, size_t index, const StringTreeNode *tail, const StringTreeNode **head) { if( tail->value() == pattern[index]) { index++; } else{ // mismatch if( index > 0 ){ // reset counter; FindPattern( pattern, 0, tail, head); return false; } index = 0; } if( index == pattern.size()){ *head = ( tail ); return true; } bool found = false; for (auto& child: tail->children() ) { found = FindPattern( pattern, index, &child, head); if( found) break; } return found; } void Parser::registerRenamingRules(const ROSType &type, const std::vector<SubstitutionRule> &rules) { for(const auto& it: _registred_messages) { const std::string& msg_identifier = it.first; const ROSMessageInfo& msg_info = it.second; if( getMessageByType(type, msg_info) ) { std::vector<RulesCache>& cache_vector = _registered_rules[msg_identifier]; for(const auto& rule: rules ) { RulesCache cache(rule); FindPattern( cache.rule.pattern(), 0, msg_info.string_tree.croot(), &cache.pattern_head ); FindPattern( cache.rule.alias(), 0, msg_info.string_tree.croot(), &cache.alias_head ); if( cache.pattern_head && cache.alias_head && std::find( cache_vector.begin(), cache_vector.end(), cache) == cache_vector.end() ) { cache_vector.push_back( std::move(cache) ); } } } } _block_register_message = true; } } //end namespace <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author ([email protected]) \authors ([email protected]) \date 10.05.2009 \brief common- \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdocommon.h" #include "utils/rdofile.h" #include "utils/rdotime.h" #include "utils/test/utils_common_test/resource.h" // -------------------------------------------------------------------------------- const tstring s_testFileName(_T("test_file")); const tstring s_resourceStr1(_T("test_101")); const tstring s_resourceStr2(_T("test_102 22")); const tstring s_resourceStr3(_T("test_103 test_101 33 test_102 22")); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_ResourceFormat) { tstring str1 = rdo::format(IDS_STRING101); BOOST_CHECK(str1 == s_resourceStr1); tstring str2 = rdo::format(IDS_STRING102, 22); BOOST_CHECK(str2 == s_resourceStr2); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); BOOST_CHECK(str3 == s_resourceStr3); } #endif // OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { tstring file(_T("/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr2")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { tstring file(_T("/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { tstring file(_T(":/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { tstring file(_T(":/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { tstring file(_T(":\\rdo\\ \\files\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\rdo\\ \\files\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { tstring file(_T(":\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<tstring> name_set; for(int i = 0; i < 15; ++i) { tstring file_name = rdo::File::getTempFileName(); BOOST_CHECK(name_set.find(file_name) == name_set.end()); name_set.insert(file_name); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::cout << _T("Today: ") << timeValue.asString() << _T(" is not it?"); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <commit_msg>* reverted changes from rev.6842<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author ([email protected]) \authors ([email protected]) \date 10.05.2009 \brief common- \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdocommon.h" #include "utils/rdofile.h" #include "utils/rdotime.h" #include "utils/test/utils_common_test/resource.h" // -------------------------------------------------------------------------------- const tstring s_testFileName(_T("test_file")); const tstring s_resourceStr1(_T("test_101")); const tstring s_resourceStr2(_T("test_102 22")); const tstring s_resourceStr3(_T("test_103 test_101 33 test_102 22")); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_ResourceFormat) { tstring str1 = rdo::format(IDS_STRING101); BOOST_CHECK(str1 == s_resourceStr1); tstring str2 = rdo::format(IDS_STRING102, 22); BOOST_CHECK(str2 == s_resourceStr2); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); BOOST_CHECK(str3 == s_resourceStr3); } #endif // OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { tstring file(_T("/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { tstring file(_T("/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { tstring file(_T(":/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { tstring file(_T(":/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { tstring file(_T(":\\rdo\\ \\files\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\rdo\\ \\files\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { tstring file(_T(":\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<tstring> name_set; for(int i = 0; i < 15; ++i) { tstring file_name = rdo::File::getTempFileName(); BOOST_CHECK(name_set.find(file_name) == name_set.end()); name_set.insert(file_name); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::cout << _T("Today: ") << timeValue.asString() << _T(" is not it?"); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_mem_startclocks.C /// /// @brief Start clocks on MBA/MCAs //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : Sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : HB //------------------------------------------------------------------------------ //## auto_generated #include "p9_mem_startclocks.H" #include "p9_const_common.H" #include "p9_misc_scom_addresses_fld.H" #include "p9_perv_scom_addresses.H" #include "p9_perv_scom_addresses_fld.H" #include "p9_quad_scom_addresses_fld.H" #include "p9_sbe_common.H" enum P9_MEM_STARTCLOCKS_Private_Constants { CLOCK_CMD = 0x1, STARTSLAVE = 0x1, STARTMASTER = 0x1, REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE, CLOCK_TYPES = 0x7, DONT_STARTMASTER = 0x0, DONT_STARTSLAVE = 0x0 }; static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet, const fapi2::buffer<uint64_t> i_pg_vector); static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet); static fapi2::ReturnCode p9_mem_startclocks_flushmode( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet); fapi2::ReturnCode p9_mem_startclocks(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip) { uint8_t l_sync_mode = 0; fapi2::buffer<uint64_t> l_pg_vector; FAPI_DBG("Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode), "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)"); for (auto l_target_cplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV> (static_cast<fapi2::TargetFilter>(fapi2::TARGET_FILTER_ALL_NEST | fapi2::TARGET_FILTER_TP), fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(p9_sbe_common_get_pg_vector(l_target_cplt, l_pg_vector)); FAPI_DBG("pg targets vector: %#018lX", l_pg_vector); } if (!l_sync_mode) { for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV> (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets"); FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt)); FAPI_INF("Call module align chiplets for Mc chiplets"); FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt)); FAPI_INF("Call module clock start stop for MC01, MC23."); FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD, DONT_STARTSLAVE, DONT_STARTMASTER, REGIONS_ALL_EXCEPT_VITAL_NESTPLL, CLOCK_TYPES)); FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets "); FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector)); FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets"); FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt)); } } FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief --drop chiplet fence /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet, const fapi2::buffer<uint64_t> i_pg_vector) { uint8_t l_read_attrunitpos = 0; fapi2::buffer<uint64_t> l_data64; FAPI_DBG("Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet, l_read_attrunitpos)); if ( l_read_attrunitpos == 0x07 ) { if ( i_pg_vector.getBit<4>() == 1 ) { FAPI_DBG("Drop chiplet fence"); //Setting NET_CTRL0 register value l_data64.flush<1>(); l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0 FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64)); } } if ( l_read_attrunitpos == 0x08 ) { if ( i_pg_vector.getBit<2>() == 1 ) { FAPI_DBG("Drop chiplet fence"); //Setting NET_CTRL0 register value l_data64.flush<1>(); l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0 FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64)); } } FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief --drop vital fence /// --reset abstclk muxsel and syncclk muxsel /// /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet) { fapi2::buffer<uint64_t> l_data64; FAPI_DBG("Entering ..."); // Local variable and constant definition fapi2::buffer <uint32_t> l_attr_pg; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg)); l_attr_pg.invert(); FAPI_INF("Drop partial good fences"); //Setting CPLT_CTRL1 register value l_data64.flush<0>(); //CPLT_CTRL1.TC_VITL_REGION_FENCE = l_attr_pg.getBit<19>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<19>()); //CPLT_CTRL1.TC_PERV_REGION_FENCE = l_attr_pg.getBit<20>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_PERV_REGION_FENCE>(l_attr_pg.getBit<20>()); //CPLT_CTRL1.TC_REGION1_FENCE = l_attr_pg.getBit<21>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_REGION1_FENCE>(l_attr_pg.getBit<21>()); //CPLT_CTRL1.TC_REGION2_FENCE = l_attr_pg.getBit<22>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_REGION2_FENCE>(l_attr_pg.getBit<22>()); //CPLT_CTRL1.TC_REGION3_FENCE = l_attr_pg.getBit<23>() l_data64.writeBit<PERV_1_CPLT_CTRL1_TC_REGION3_FENCE>(l_attr_pg.getBit<23>()); //CPLT_CTRL1.TC_REGION4_FENCE = l_attr_pg.getBit<24>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION4_FENCE>(l_attr_pg.getBit<24>()); //CPLT_CTRL1.TC_REGION5_FENCE = l_attr_pg.getBit<25>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION5_FENCE>(l_attr_pg.getBit<25>()); //CPLT_CTRL1.TC_REGION6_FENCE = l_attr_pg.getBit<26>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION6_FENCE>(l_attr_pg.getBit<26>()); //CPLT_CTRL1.TC_REGION7_FENCE = l_attr_pg.getBit<27>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION7_FENCE>(l_attr_pg.getBit<27>()); //CPLT_CTRL1.UNUSED_12B = l_attr_pg.getBit<28>() l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_12B>(l_attr_pg.getBit<28>()); //CPLT_CTRL1.UNUSED_13B = l_attr_pg.getBit<29>() l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_13B>(l_attr_pg.getBit<29>()); //CPLT_CTRL1.UNUSED_14B = l_attr_pg.getBit<30>() l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_14B>(l_attr_pg.getBit<30>()); FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64)); FAPI_INF("reset abistclk_muxsel and syncclk_muxsel"); //Setting CPLT_CTRL0 register value l_data64.flush<0>(); //CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1 l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1); //CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1 l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1); FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64)); FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief will force all chiplets out of flush /// /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p9_mem_startclocks_flushmode( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet) { fapi2::buffer<uint64_t> l_data64; FAPI_DBG("Entering ..."); FAPI_INF("Clear flush_inhibit to go in to flush mode"); //Setting CPLT_CTRL0 register value l_data64.flush<0>(); //CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0 l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>(); FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64)); FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>Changing ATTR_PG from 32 to 16 bit<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_startclocks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_mem_startclocks.C /// /// @brief Start clocks on MBA/MCAs //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <[email protected]> // *HWP HW Backup Owner : Srinivas V Naga <[email protected]> // *HWP FW Owner : Sunil kumar <[email protected]> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : HB //------------------------------------------------------------------------------ //## auto_generated #include "p9_mem_startclocks.H" #include "p9_const_common.H" #include "p9_misc_scom_addresses_fld.H" #include "p9_perv_scom_addresses.H" #include "p9_perv_scom_addresses_fld.H" #include "p9_quad_scom_addresses_fld.H" #include "p9_sbe_common.H" enum P9_MEM_STARTCLOCKS_Private_Constants { CLOCK_CMD = 0x1, STARTSLAVE = 0x1, STARTMASTER = 0x1, REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE, CLOCK_TYPES = 0x7, DONT_STARTMASTER = 0x0, DONT_STARTSLAVE = 0x0 }; static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet, const fapi2::buffer<uint64_t> i_pg_vector); static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet); static fapi2::ReturnCode p9_mem_startclocks_flushmode( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet); fapi2::ReturnCode p9_mem_startclocks(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip) { uint8_t l_sync_mode = 0; fapi2::buffer<uint64_t> l_pg_vector; FAPI_DBG("Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode), "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)"); for (auto l_target_cplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV> (static_cast<fapi2::TargetFilter>(fapi2::TARGET_FILTER_ALL_NEST | fapi2::TARGET_FILTER_TP), fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(p9_sbe_common_get_pg_vector(l_target_cplt, l_pg_vector)); FAPI_DBG("pg targets vector: %#018lX", l_pg_vector); } if (!l_sync_mode) { for (auto l_trgt_chplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV> (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_INF("Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets"); FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt)); FAPI_INF("Call module align chiplets for Mc chiplets"); FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt)); FAPI_INF("Call module clock start stop for MC01, MC23."); FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD, DONT_STARTSLAVE, DONT_STARTMASTER, REGIONS_ALL_EXCEPT_VITAL_NESTPLL, CLOCK_TYPES)); FAPI_INF("Call p9_mem_startclocks_fence_setup_function for Mc chiplets "); FAPI_TRY(p9_mem_startclocks_fence_setup_function(l_trgt_chplt, l_pg_vector)); FAPI_INF("Call p9_mem_startclocks_flushmode for Mc chiplets"); FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt)); } } FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief --drop chiplet fence /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p9_mem_startclocks_fence_setup_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet, const fapi2::buffer<uint64_t> i_pg_vector) { uint8_t l_read_attrunitpos = 0; fapi2::buffer<uint64_t> l_data64; FAPI_DBG("Entering ..."); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target_chiplet, l_read_attrunitpos)); if ( l_read_attrunitpos == 0x07 ) { if ( i_pg_vector.getBit<4>() == 1 ) { FAPI_DBG("Drop chiplet fence"); //Setting NET_CTRL0 register value l_data64.flush<1>(); l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0 FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64)); } } if ( l_read_attrunitpos == 0x08 ) { if ( i_pg_vector.getBit<2>() == 1 ) { FAPI_DBG("Drop chiplet fence"); //Setting NET_CTRL0 register value l_data64.flush<1>(); l_data64.clearBit<PERV_1_NET_CTRL0_FENCE_EN>(); //NET_CTRL0.FENCE_EN = 0 FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64)); } } FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief --drop vital fence /// --reset abstclk muxsel and syncclk muxsel /// /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet) { fapi2::buffer<uint64_t> l_data64; FAPI_DBG("Entering ..."); // Local variable and constant definition fapi2::buffer <uint16_t> l_attr_pg; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg)); l_attr_pg.invert(); FAPI_INF("Drop partial good fences"); //Setting CPLT_CTRL1 register value l_data64.flush<0>(); //CPLT_CTRL1.TC_VITL_REGION_FENCE = l_attr_pg.getBit<19>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_VITL_REGION_FENCE>(l_attr_pg.getBit<3>()); //CPLT_CTRL1.TC_PERV_REGION_FENCE = l_attr_pg.getBit<20>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_PERV_REGION_FENCE>(l_attr_pg.getBit<4>()); //CPLT_CTRL1.TC_REGION1_FENCE = l_attr_pg.getBit<21>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_REGION1_FENCE>(l_attr_pg.getBit<5>()); //CPLT_CTRL1.TC_REGION2_FENCE = l_attr_pg.getBit<22>() l_data64.writeBit<PEC_CPLT_CTRL1_TC_REGION2_FENCE>(l_attr_pg.getBit<6>()); //CPLT_CTRL1.TC_REGION3_FENCE = l_attr_pg.getBit<23>() l_data64.writeBit<PERV_1_CPLT_CTRL1_TC_REGION3_FENCE>(l_attr_pg.getBit<7>()); //CPLT_CTRL1.TC_REGION4_FENCE = l_attr_pg.getBit<24>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION4_FENCE>(l_attr_pg.getBit<8>()); //CPLT_CTRL1.TC_REGION5_FENCE = l_attr_pg.getBit<25>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION5_FENCE>(l_attr_pg.getBit<9>()); //CPLT_CTRL1.TC_REGION6_FENCE = l_attr_pg.getBit<26>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION6_FENCE>(l_attr_pg.getBit<10>()); //CPLT_CTRL1.TC_REGION7_FENCE = l_attr_pg.getBit<27>() l_data64.writeBit<EQ_CPLT_CTRL1_TC_REGION7_FENCE>(l_attr_pg.getBit<11>()); //CPLT_CTRL1.UNUSED_12B = l_attr_pg.getBit<28>() l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_12B>(l_attr_pg.getBit<12>()); //CPLT_CTRL1.UNUSED_13B = l_attr_pg.getBit<29>() l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_13B>(l_attr_pg.getBit<13>()); //CPLT_CTRL1.UNUSED_14B = l_attr_pg.getBit<30>() l_data64.writeBit<PEC_CPLT_CTRL1_UNUSED_14B>(l_attr_pg.getBit<14>()); FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64)); FAPI_INF("reset abistclk_muxsel and syncclk_muxsel"); //Setting CPLT_CTRL0 register value l_data64.flush<0>(); //CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1 l_data64.writeBit<PEC_CPLT_CTRL0_CTRL_CC_ABSTCLK_MUXSEL_DC>(1); //CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1 l_data64.writeBit<PEC_CPLT_CTRL0_TC_UNIT_SYNCCLK_MUXSEL_DC>(1); FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64)); FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } /// @brief will force all chiplets out of flush /// /// @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target /// @return FAPI2_RC_SUCCESS if success, else error code. static fapi2::ReturnCode p9_mem_startclocks_flushmode( const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet) { fapi2::buffer<uint64_t> l_data64; FAPI_DBG("Entering ..."); FAPI_INF("Clear flush_inhibit to go in to flush mode"); //Setting CPLT_CTRL0 register value l_data64.flush<0>(); //CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0 l_data64.setBit<PEC_CPLT_CTRL0_CTRL_CC_FLUSHMODE_INH_DC>(); FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64)); FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file eegosportssetupstimuluswidget.cpp * @author Viktor Klüber <[email protected]>; * Lorenz Esch <[email protected]>; * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date April 2016 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Contains the implementation of the EEGoSportsSetupStimulusWidget class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "eegosportssetupstimuluswidget.h" #include "ui_eegosportssetupstimuluswidget.h" #include "../flashobject.h" #include "../eegosports.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace EEGoSportsPlugin; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= EEGoSportsSetupStimulusWidget::EEGoSportsSetupStimulusWidget(EEGoSports* pEEGoSports, QWidget *parent) : QDialog(parent), ui(new Ui::EEGoSportsSetupStimulusWidget), m_pEEGoSports(pEEGoSports), m_bIsRunning(false), m_bReadFreq(false) { ui->setupUi(this); //create QGraphicsView with QGraphcisScene in a new Widget for the Test Screen m_pTestScreen = new QWidget; m_pLayout = new QVBoxLayout(); m_pView = new QGraphicsView(); m_pScene = new QGraphicsScene(m_pView); //setup the Widget for the test-screen m_pLayout->setSpacing(0); m_pLayout->setMargin(0); m_pLayout->setContentsMargins(0,0,0,0); m_pLayout->addWidget(m_pView); m_pTestScreen->setLayout(m_pLayout); m_pTestScreen->setStyleSheet("QWidget { border-style: none; }"); //setting full-screen on second monitor QScreen *screen = QGuiApplication::screens()[1]; // specify which screen to use m_pTestScreen->move(screen->geometry().x(), screen->geometry().y()); //connecting View with Scene m_pView->setScene(m_pScene); m_pView->setStyleSheet("QGraphicsView { border-style: none; }"); //Setup a Timer for a continous refresh of the Test Screen (60 Hz) m_pTimer = new QTimer(); connect(m_pTimer,SIGNAL(timeout()),this,SLOT(ScreenTrigger())); m_pTimer->setTimerType(Qt::PreciseTimer); m_pTimer->start(16.67); //connect the changedView slot to the Scene for refreshing function of the test screen view connect(m_pScene,SIGNAL(changed(QList<QRectF>)),this,SLOT(changeView())); m_pView->installEventFilter(this); //set Black as scene background color and show Test Screen m_pView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern)); m_pTestScreen->showFullScreen(); } //************************************************************************************************************* EEGoSportsSetupStimulusWidget::~EEGoSportsSetupStimulusWidget() { delete ui; delete m_pTestScreen; delete m_pLayout; delete m_pView; delete m_pScene; } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::ScreenTrigger(){ //m_pView->viewport()->repaint(); m_pView->viewport()->update(); } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::changeView(){ //Calculates and returns the bounding rect of all items on the scene. //This function works by iterating over all items, and because if this, it can be slow for large scenes. QRectF rect = m_pScene->itemsBoundingRect(); m_pScene->setSceneRect(rect); } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::closeEvent(QCloseEvent *event) { Q_UNUSED(event) m_pTestScreen->close(); } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::clear() { m_bIsRunning = false; QList <QGraphicsItem*> itemList = getTopLevelItems(); while(!itemList.isEmpty()){ delete itemList.first(); itemList = m_pScene->items(); } } //************************************************************************************************************* QList<QGraphicsItem*> EEGoSportsSetupStimulusWidget::getTopLevelItems() { int numItems, iItem; QList<QGraphicsItem*> topLevel; QList<QGraphicsItem*> itemList = m_pScene->items(); numItems = itemList.size(); for (iItem = 0; iItem < numItems; iItem++) { QGraphicsItem *item = itemList.at(iItem); if (item->parentItem() == NULL) topLevel.append(item); } return topLevel; } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::changeComboBox(QList<QGraphicsItem*> &List) { //clear ComboBox ui->comboBox->clear(); //refresh Items on the QList m_pItems.clear(); m_pItems = getTopLevelItems(); //create new comobBox list for(int i = 1; i <= List.size(); i++ ) ui->comboBox->addItem(QString().number(i)); m_bIsRunning = true; on_comboBox_currentIndexChanged(0); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_clicked() { m_pTestScreen->showFullScreen(); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_2_clicked() { clear(); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_3_clicked() { m_pTestScreen->close(); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_4_clicked() { //clear Items from screen clear(); m_pFlashList.clear(); //define dimensions of items int dimx_x = (0.33*double(m_pView->width())); int dimx_y = int(0.2*double(m_pView->height())); int dimy_x = int(0.125*double(m_pView->width())); int dimy_y = int(0.4*double(m_pView->height())); //create new flashing objects QPointer<FlashObject> obj_1 = new FlashObject(); QPointer<FlashObject> obj_2 = new FlashObject(); QPointer<FlashObject> obj_3 = new FlashObject(); QPointer<FlashObject> obj_4 = new FlashObject(); QPointer<FlashObject> obj_5 = new FlashObject(); //set starting-flashing frequencies obj_1->setFreq(6); obj_2->setFreq(7.5); obj_3->setFreq(10); obj_4->setFreq(15); obj_5->setFreq(30); //set item dimesnions obj_1->setDim(dimx_x,dimx_y); obj_2->setDim(dimy_x,dimy_y); obj_3->setDim(dimx_x,dimx_y); obj_4->setDim(dimy_x,dimy_y); obj_5->setDim(dimx_x,dimy_y); //set postitions of flashing object obj_1->setPos(0.5*m_pView->width() - 0.5*dimx_x , 0); obj_2->setPos(m_pView->width() - dimy_x , +0.5*m_pView->height() - 0.5*dimy_y ); obj_3->setPos(0.5*m_pView->width() - 0.5*dimx_x , +m_pView->height() - dimx_y); obj_4->setPos(0 , +0.5*m_pView->height() - 0.5*dimy_y); obj_5->setPos(0.5*m_pView->width() - 0.5*dimx_x , +0.5*m_pView->height() - 0.5*dimy_y); //add items to scene and to FlashList m_pScene->addItem(obj_1);m_pFlashList.append(obj_1); m_pScene->addItem(obj_2);m_pFlashList.append(obj_2); m_pScene->addItem(obj_3);m_pFlashList.append(obj_3); m_pScene->addItem(obj_4);m_pFlashList.append(obj_4); m_pScene->addItem(obj_5);m_pFlashList.append(obj_5); //add Items to ComboBox changeComboBox(m_pItems); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_5_clicked() { //clear Items from screen clear(); m_pFlashList.clear(); QPointer<FlashObject> obj_1 = new FlashObject(); obj_1->setFreq(1); obj_1->setDim(m_pView->width(),m_pView->height()); m_pScene->addItem(obj_1);m_pFlashList.append(obj_1); obj_1->setFreq(15); //add Items to ComboBox changeComboBox(m_pItems); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_6_clicked() { //clear Items from screen clear(); m_pFlashList.clear(); QPointer<FlashObject> obj_1 = new FlashObject; QPointer<FlashObject> obj_2 = new FlashObject; //set Frequencies obj_1->setFreq(3); obj_2->setFreq(3.75); //set dimensions obj_1->setDim(0.3*m_pView->width(),0.8*m_pView->height()); obj_2->setDim(0.3*m_pView->width(),0.8*m_pView->height()); //set positions obj_1->setPos(0,(0.5-0.8/2)*m_pView->height()); obj_2->setPos((1-0.3)*m_pView->width(), (0.5-0.8/2)*m_pView->height()); //ad Items to scene m_pScene->addItem(obj_1);m_pFlashList.append(obj_1); m_pScene->addItem(obj_2);m_pFlashList.append(obj_2); //add Items to ComboBox changeComboBox(m_pItems); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_doubleSpinBox_valueChanged(double arg) { if(m_bReadFreq) m_bReadFreq=false; else{ //get selected Item from comboBox int ItemSelect = ui->comboBox->currentIndex(); //adjust the Frequency of the selected Plugin m_pFlashList.at(ItemSelect)->setFreq(arg); } } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_comboBox_currentIndexChanged(int index) { if(m_bIsRunning){ m_bReadFreq = true; ui->doubleSpinBox->setValue(m_pFlashList.at(index)->getFreq()); } } <commit_msg>[MX-96] adapt stimulation feature<commit_after>//============================================================================================================= /** * @file eegosportssetupstimuluswidget.cpp * @author Viktor Klüber <[email protected]>; * Lorenz Esch <[email protected]>; * Christoph Dinh <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date April 2016 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Contains the implementation of the EEGoSportsSetupStimulusWidget class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "eegosportssetupstimuluswidget.h" #include "ui_eegosportssetupstimuluswidget.h" #include "../flashobject.h" #include "../eegosports.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace EEGoSportsPlugin; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= EEGoSportsSetupStimulusWidget::EEGoSportsSetupStimulusWidget(EEGoSports* pEEGoSports, QWidget *parent) : QDialog(parent), ui(new Ui::EEGoSportsSetupStimulusWidget), m_pEEGoSports(pEEGoSports), m_bIsRunning(false), m_bReadFreq(false) { ui->setupUi(this); //create QGraphicsView with QGraphcisScene in a new Widget for the Test Screen m_pTestScreen = new QWidget; m_pLayout = new QVBoxLayout(); m_pView = new QGraphicsView(); m_pScene = new QGraphicsScene(m_pView); //setup the Widget for the test-screen m_pLayout->setSpacing(0); m_pLayout->setMargin(0); m_pLayout->setContentsMargins(0,0,0,0); m_pLayout->addWidget(m_pView); m_pTestScreen->setLayout(m_pLayout); m_pTestScreen->setStyleSheet("QWidget { border-style: none; }"); //setting full-screen on second monitor QScreen *screen = QGuiApplication::screens()[1]; // specify which screen to use m_pTestScreen->move(screen->geometry().x(), screen->geometry().y()); //connecting View with Scene m_pView->setScene(m_pScene); m_pView->setStyleSheet("QGraphicsView { border-style: none; }"); //Setup a Timer for a continous refresh of the Test Screen (60 Hz) m_pTimer = new QTimer(); connect(m_pTimer,SIGNAL(timeout()),this,SLOT(ScreenTrigger())); m_pTimer->setTimerType(Qt::PreciseTimer); m_pTimer->start(16.67); //connect the changedView slot to the Scene for refreshing function of the test screen view connect(m_pScene,SIGNAL(changed(QList<QRectF>)),this,SLOT(changeView())); m_pView->installEventFilter(this); //set Black as scene background color and show Test Screen m_pView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern)); m_pTestScreen->showFullScreen(); } //************************************************************************************************************* EEGoSportsSetupStimulusWidget::~EEGoSportsSetupStimulusWidget() { delete ui; delete m_pTestScreen; delete m_pLayout; delete m_pView; delete m_pScene; } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::ScreenTrigger(){ //m_pView->viewport()->repaint(); m_pView->viewport()->update(); } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::changeView(){ //Calculates and returns the bounding rect of all items on the scene. //This function works by iterating over all items, and because if this, it can be slow for large scenes. QRectF rect = m_pScene->itemsBoundingRect(); m_pScene->setSceneRect(rect); } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::closeEvent(QCloseEvent *event) { Q_UNUSED(event) m_pTestScreen->close(); } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::clear() { m_bIsRunning = false; QList <QGraphicsItem*> itemList = getTopLevelItems(); while(!itemList.isEmpty()){ delete itemList.first(); itemList = m_pScene->items(); } } //************************************************************************************************************* QList<QGraphicsItem*> EEGoSportsSetupStimulusWidget::getTopLevelItems() { int numItems, iItem; QList<QGraphicsItem*> topLevel; QList<QGraphicsItem*> itemList = m_pScene->items(); numItems = itemList.size(); for (iItem = 0; iItem < numItems; iItem++) { QGraphicsItem *item = itemList.at(iItem); if (item->parentItem() == NULL) topLevel.append(item); } return topLevel; } //************************************************************************************************************* void EEGoSportsSetupStimulusWidget::changeComboBox(QList<QGraphicsItem*> &List) { //clear ComboBox ui->comboBox->clear(); //refresh Items on the QList m_pItems.clear(); m_pItems = getTopLevelItems(); //create new comobBox list for(int i = 1; i <= List.size(); i++ ) ui->comboBox->addItem(QString().number(i)); m_bIsRunning = true; on_comboBox_currentIndexChanged(0); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_clicked() { m_pTestScreen->showFullScreen(); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_2_clicked() { clear(); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_3_clicked() { m_pTestScreen->close(); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_4_clicked() { //clear Items from screen clear(); m_pFlashList.clear(); //define dimensions of items int dimx_x = (0.33*double(m_pView->width())); int dimx_y = int(0.2*double(m_pView->height())); int dimy_x = int(0.125*double(m_pView->width())); int dimy_y = int(0.4*double(m_pView->height())); //create new flashing objects QPointer<FlashObject> obj_1 = new FlashObject(); QPointer<FlashObject> obj_2 = new FlashObject(); QPointer<FlashObject> obj_3 = new FlashObject(); QPointer<FlashObject> obj_4 = new FlashObject(); QPointer<FlashObject> obj_5 = new FlashObject(); //set starting-flashing frequencies obj_1->setFreq(6); obj_2->setFreq(7.5); obj_3->setFreq(10); obj_4->setFreq(15); obj_5->setFreq(30); //set item dimesnions obj_1->setDim(dimx_x,dimx_y); obj_2->setDim(dimy_x,dimy_y); obj_3->setDim(dimx_x,dimx_y); obj_4->setDim(dimy_x,dimy_y); obj_5->setDim(dimx_x,dimy_y); //set postitions of flashing object obj_1->setPos(0.5*m_pView->width() - 0.5*dimx_x , 0); obj_2->setPos(m_pView->width() - dimy_x , +0.5*m_pView->height() - 0.5*dimy_y ); obj_3->setPos(0.5*m_pView->width() - 0.5*dimx_x , +m_pView->height() - dimx_y); obj_4->setPos(0 , +0.5*m_pView->height() - 0.5*dimy_y); obj_5->setPos(0.5*m_pView->width() - 0.5*dimx_x , +0.5*m_pView->height() - 0.5*dimy_y); //add items to scene and to FlashList m_pScene->addItem(obj_1);m_pFlashList.append(obj_1); m_pScene->addItem(obj_2);m_pFlashList.append(obj_2); m_pScene->addItem(obj_3);m_pFlashList.append(obj_3); m_pScene->addItem(obj_4);m_pFlashList.append(obj_4); m_pScene->addItem(obj_5);m_pFlashList.append(obj_5); //add Items to ComboBox changeComboBox(m_pItems); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_5_clicked() { //clear Items from screen clear(); m_pFlashList.clear(); QPointer<FlashObject> obj_1 = new FlashObject(); obj_1->setFreq(1); obj_1->setDim(m_pView->width(),m_pView->height()); m_pScene->addItem(obj_1);m_pFlashList.append(obj_1); obj_1->setFreq(15); //add Items to ComboBox changeComboBox(m_pItems); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_pushButton_6_clicked() { //clear Items from screen clear(); m_pFlashList.clear(); QPointer<FlashObject> obj_1 = new FlashObject; QPointer<FlashObject> obj_2 = new FlashObject; //set Frequencies obj_1->setFreq(3); obj_2->setFreq(3.75); //set dimensions obj_1->setDim(0.2*m_pView->width(),0.2*m_pView->height()); obj_2->setDim(0.2*m_pView->width(),0.2*m_pView->height()); //set positions obj_1->setPos(0.2*m_pView->width(),(0.5-0.2/2)*m_pView->height()); obj_2->setPos((1-0.5)*m_pView->width(), (0.5-0.2/2)*m_pView->height()); //ad Items to scene m_pScene->addItem(obj_1);m_pFlashList.append(obj_1); m_pScene->addItem(obj_2);m_pFlashList.append(obj_2); //add Items to ComboBox changeComboBox(m_pItems); } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_doubleSpinBox_valueChanged(double arg) { if(m_bReadFreq) m_bReadFreq=false; else{ //get selected Item from comboBox int ItemSelect = ui->comboBox->currentIndex(); //adjust the Frequency of the selected Plugin m_pFlashList.at(ItemSelect)->setFreq(arg); } } //************************************************************************************************************* void EEGoSportsPlugin::EEGoSportsSetupStimulusWidget::on_comboBox_currentIndexChanged(int index) { if(m_bIsRunning){ m_bReadFreq = true; ui->doubleSpinBox->setValue(m_pFlashList.at(index)->getFreq()); } } <|endoftext|>
<commit_before>#include "Client.h" #include <GL/glew.h> #include <GL/glut.h> #include <math.h> #include <unistd.h> #include <iostream> #include <fstream> #include <cassert> #include <ctime> #ifdef WIN32 #include <conio.h> // For _kbhit() #include <cstdio> // For getchar() #include <windows.h> // For Sleep() #endif // WIN32 #include <time.h> using namespace ViconDataStreamSDK::CPP; // Make a new client Client MyClient; std::string HostName = "141.219.28.17:801"; //std::string HostName = "localhost:801"; // screen width/height indicate the size of the window on our screen (not the size of the display wall). The aspect ratio must match the actual display wall. const GLdouble SCREEN_WIDTH = (1920*6)/8.0; const GLdouble SCREEN_HEIGHT = (1080.0*4)/8.0; const float screenAspectRatio = SCREEN_WIDTH/SCREEN_HEIGHT; float player1Xpos=0, player2Xpos=0; float player1Color1[3] = {87/255.0, 159/255.0, 210/255.0}; // blue float player1Color2[3] = {19/255.0,119/255.0,189/255.0}; float player2Color1[3] = {225/255.0,95/255.0,93/255.0}; // red float player2Color2[3] = {220/255.0,50/255.0,47/255.0}; float ballPos[2] = { 0,0 }; float ballDir[2] = { 0,1 }; float ballColor[3] = { 0,0,0 }; const float ballGreenColor[3] = { 146/255.0, 158/255.0, 64/255.0 }; int ballBouncesTillSpeedup = 4; // number of paddle hits before we speed up. int ballBounceCount = 0; // counter of paddle hits so far float ballSpeed = 70; // speed of ball (larger=slower) const float ballSpeedSlowest = 70; time_t startTime = time(NULL); bool startedFlag = false; bool hasAlreadyMissed = false; // ball went past paddle. float paddleWidth1 = .1; float paddleWidth2 = .1; const float paddleWidthIncrement = .02; const float paddleThickness = .04; const float player2Ypos = -.9; const float player1Ypos = -player2Ypos; const float ballRadius = 0.02; namespace { std::string Adapt( const bool i_Value ) { return i_Value ? "True" : "False"; } std::string Adapt( const Direction::Enum i_Direction ) { switch( i_Direction ) { case Direction::Forward: return "Forward"; case Direction::Backward: return "Backward"; case Direction::Left: return "Left"; case Direction::Right: return "Right"; case Direction::Up: return "Up"; case Direction::Down: return "Down"; default: return "Unknown"; } } std::string Adapt( const DeviceType::Enum i_DeviceType ) { switch( i_DeviceType ) { case DeviceType::ForcePlate: return "ForcePlate"; case DeviceType::Unknown: default: return "Unknown"; } } std::string Adapt( const Unit::Enum i_Unit ) { switch( i_Unit ) { case Unit::Meter: return "Meter"; case Unit::Volt: return "Volt"; case Unit::NewtonMeter: return "NewtonMeter"; case Unit::Newton: return "Newton"; case Unit::Kilogram: return "Kilogram"; case Unit::Second: return "Second"; case Unit::Ampere: return "Ampere"; case Unit::Kelvin: return "Kelvin"; case Unit::Mole: return "Mole"; case Unit::Candela: return "Candela"; case Unit::Radian: return "Radian"; case Unit::Steradian: return "Steradian"; case Unit::MeterSquared: return "MeterSquared"; case Unit::MeterCubed: return "MeterCubed"; case Unit::MeterPerSecond: return "MeterPerSecond"; case Unit::MeterPerSecondSquared: return "MeterPerSecondSquared"; case Unit::RadianPerSecond: return "RadianPerSecond"; case Unit::RadianPerSecondSquared: return "RadianPerSecondSquared"; case Unit::Hertz: return "Hertz"; case Unit::Joule: return "Joule"; case Unit::Watt: return "Watt"; case Unit::Pascal: return "Pascal"; case Unit::Lumen: return "Lumen"; case Unit::Lux: return "Lux"; case Unit::Coulomb: return "Coulomb"; case Unit::Ohm: return "Ohm"; case Unit::Farad: return "Farad"; case Unit::Weber: return "Weber"; case Unit::Tesla: return "Tesla"; case Unit::Henry: return "Henry"; case Unit::Siemens: return "Siemens"; case Unit::Becquerel: return "Becquerel"; case Unit::Gray: return "Gray"; case Unit::Sievert: return "Sievert"; case Unit::Katal: return "Katal"; case Unit::Unknown: default: return "Unknown"; } } } void viconExit() { MyClient.DisableSegmentData(); // MyClient.DisableMarkerData(); // MyClient.DisableUnlabeledMarkerData(); // MyClient.DisableDeviceData(); // TODO: Disconnect seems to cause a hang. -Scott Kuhl // Disconnect and dispose int t = clock(); std::cout << " Disconnecting..." << std::endl; MyClient.Disconnect(); int dt = clock() - t; double secs = (double) (dt)/(double)CLOCKS_PER_SEC; std::cout << " Disconnect time = " << secs << " secs" << std::endl; } void viconInit() { // Connect to a server std::cout << "Connecting to " << HostName << " ..." << std::flush; int attemptConnectCount = 0; const int MAX_CONNECT_ATTEMPTS=2; while( !MyClient.IsConnected().Connected && attemptConnectCount < MAX_CONNECT_ATTEMPTS) { attemptConnectCount++; bool ok = false; ok =( MyClient.Connect( HostName ).Result == Result::Success ); if(!ok) std::cout << "Warning - connect failed..." << std::endl; std::cout << "."; sleep(1); } if(attemptConnectCount == MAX_CONNECT_ATTEMPTS) { printf("Giving up making connection to Vicon system\n"); return; } std::cout << std::endl; // Enable some different data types MyClient.EnableSegmentData(); //MyClient.EnableMarkerData(); //MyClient.EnableUnlabeledMarkerData(); //MyClient.EnableDeviceData(); std::cout << "Segment Data Enabled: " << Adapt( MyClient.IsSegmentDataEnabled().Enabled ) << std::endl; std::cout << "Marker Data Enabled: " << Adapt( MyClient.IsMarkerDataEnabled().Enabled ) << std::endl; std::cout << "Unlabeled Marker Data Enabled: " << Adapt( MyClient.IsUnlabeledMarkerDataEnabled().Enabled ) << std::endl; std::cout << "Device Data Enabled: " << Adapt( MyClient.IsDeviceDataEnabled().Enabled ) << std::endl; // Set the streaming mode //MyClient.SetStreamMode( ViconDataStreamSDK::CPP::StreamMode::ClientPull ); // MyClient.SetStreamMode( ViconDataStreamSDK::CPP::StreamMode::ClientPullPreFetch ); MyClient.SetStreamMode( ViconDataStreamSDK::CPP::StreamMode::ServerPush ); // Set the global up axis MyClient.SetAxisMapping( Direction::Forward, Direction::Left, Direction::Up ); // Z-up // MyClient.SetGlobalUpAxis( Direction::Forward, // Direction::Up, // Direction::Right ); // Y-up Output_GetAxisMapping _Output_GetAxisMapping = MyClient.GetAxisMapping(); std::cout << "Axis Mapping: X-" << Adapt( _Output_GetAxisMapping.XAxis ) << " Y-" << Adapt( _Output_GetAxisMapping.YAxis ) << " Z-" << Adapt( _Output_GetAxisMapping.ZAxis ) << std::endl; // Discover the version number Output_GetVersion _Output_GetVersion = MyClient.GetVersion(); std::cout << "Version: " << _Output_GetVersion.Major << "." << _Output_GetVersion.Minor << "." << _Output_GetVersion.Point << std::endl; } // an atexit() callback: void exitCallback() { viconExit(); return; } void clampPaddles() { // left screen boundary if(player1Xpos < -1+paddleWidth1/2) player1Xpos = -1+paddleWidth1/2; if(player2Xpos < -1+paddleWidth2/2) player2Xpos = -1+paddleWidth2/2; // right screen boundary if(player1Xpos > 1-paddleWidth1/2) player1Xpos = 1-paddleWidth1/2; if(player2Xpos > 1-paddleWidth2/2) player2Xpos = 1-paddleWidth2/2; } void bounceBall() { if(ballSpeed > ballSpeedSlowest) { ballSpeed = ballSpeedSlowest; } bool isBounce = false; if(ballPos[0]+ballRadius > 1) // right wall { ballPos[0] = 1-ballRadius; ballDir[0] = -ballDir[0]; isBounce = true; } if(ballPos[1] > 1+ballRadius*screenAspectRatio*1.1) // top wall { #if 0 ballPos[1] = 1; ballDir[1] = -ballDir[1]; isBounce = true; #endif ballBounceCount = 0; paddleWidth1 -= paddleWidthIncrement; paddleWidth2 += paddleWidthIncrement; if(paddleWidth1 < 0.001) { printf("player 1 (top) loses\n"); exit(1); } else // missed paddle and didn't lose { sleep(1); ballPos[0] = 0; ballPos[1] = 0; ballSpeed /= .7; ballBouncesTillSpeedup--; hasAlreadyMissed = false; } } if(ballPos[0]-ballRadius < -1) // left wall { ballPos[0] = -1+ballRadius; ballDir[0] = -ballDir[0]; isBounce = true; } if(ballPos[1] < -1-ballRadius*screenAspectRatio*1.1) // bottom wall { #if 0 ballPos[1] = -1; ballDir[1] = -ballDir[1]; isBounce = true; #endif ballBounceCount = 0; paddleWidth1 += paddleWidthIncrement; paddleWidth2 -= paddleWidthIncrement; if(paddleWidth2 < 0.001) { printf("player 2 (bottom) loses\n"); exit(1); } else // missed paddle and didn't lose { sleep(1); ballPos[0] = 0; ballPos[1] = 0; ballSpeed /= .7; ballBouncesTillSpeedup--; hasAlreadyMissed = false; } } if(!hasAlreadyMissed) { // check for player 1 (top) paddle hit if(ballPos[1] > player1Ypos-ballRadius*screenAspectRatio && ballDir[1] > 0) { // if we hit paddle if(ballPos[0]+ballRadius*.9 > player1Xpos-paddleWidth1/2 && ballPos[0]-ballRadius*.9 < player1Xpos+paddleWidth1/2) { ballPos[1] = player1Ypos-ballRadius*screenAspectRatio; ballDir[1] = -ballDir[1]; isBounce = true; ballBounceCount++; } else // missed paddle { hasAlreadyMissed = true; } } // check for player 2 (bottom) paddle hit if(ballPos[1] < player2Ypos+ballRadius*screenAspectRatio && ballDir[1] < 0) { // if we hit paddle if(ballPos[0]+ballRadius*.9 > player2Xpos-paddleWidth2/2 && ballPos[0]-ballRadius*.9 < player2Xpos+paddleWidth2/2) { ballPos[1] = player2Ypos+ballRadius*screenAspectRatio; ballDir[1] = -ballDir[1]; isBounce = true; ballBounceCount++; } else { hasAlreadyMissed = true; } } } // speedup the ball periodically if(ballBounceCount == ballBouncesTillSpeedup) { ballBounceCount = 0; ballSpeed = ballSpeed * .7; ballBouncesTillSpeedup++; ballColor[0] = ballGreenColor[0]; ballColor[1] = ballGreenColor[1]; ballColor[2] = ballGreenColor[2]; } // add noise to bounces so they don't bounce perfectly. if(isBounce) { double noise = drand48()/30.0-(1/30.0/2); ballDir[0] += noise; ballDir[1] -= noise; const float minYdir = .2; if(fabs(ballDir[1]) < minYdir) { printf("too little vertical movement\n"); float diff = minYdir-ballDir[1]; ballDir[0] -= diff; ballDir[1] += diff; } } } void keyboard(unsigned char key, int x, int y) { if (key == 27 || key == 'q') // escape key, exit program exit(0); if(key == 'a') { player1Xpos -= .01; player2Xpos += .01; clampPaddles(); } if(key == 'd') { player1Xpos += .01; player2Xpos -= .01; clampPaddles(); } } void display() { // usleep(10000); if(!startedFlag) { if(time(NULL)-startTime < 5) { ballDir[0] = 0; ballDir[1] = 0; } else { srand48(startTime); startedFlag = true; ballDir[1] = 1; if(drand48() < .5) ballDir[1] = -1; ballColor[0] = ballGreenColor[0]; ballColor[1] = ballGreenColor[1]; ballColor[2] = ballGreenColor[2]; } } glEnable(GL_LIGHTING) ; glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glColor3f(1,1,1); // Get a frame if(MyClient.GetFrame().Result != Result::Success ) printf("WARNING: Inside display() and there is no data from Vicon...\n"); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1,1,-1,1,-1,1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // units are in millimeters, lets switch to meters Output_GetSegmentGlobalTranslation globalTranslate1 = MyClient.GetSegmentGlobalTranslation("HandL", "HandL"); Output_GetSegmentGlobalTranslation globalTranslate2 = MyClient.GetSegmentGlobalTranslation("HandR", "HandR"); // divide by 1000 to convert from mm to meters. Screen coordinates // range from -1 to 1 so we need to divide by ~3 to make the // paddle movement on screen approximately match the movement in // the room. player1Xpos = globalTranslate1.Translation[0]/1000/2; player2Xpos = globalTranslate2.Translation[0]/1000/2; glDisable(GL_LIGHTING); // background quad glBegin(GL_QUADS); glColor3f(.2,.2,.2); glVertex3f(1, 1, -.1); // top left glVertex3f(-1,1, -.1); glColor3f(1,1,1); glVertex3f(-1,-1,-.1); glVertex3f( 1,-1,-.1); glEnd(); // top player (player 1) paddle glPushMatrix(); glTranslatef(player1Xpos,0,0); glBegin(GL_QUADS); glColor3fv(player1Color1); glVertex3f( paddleWidth1/2, player1Ypos+paddleThickness, 0); // top left glVertex3f(-paddleWidth1/2, player1Ypos+paddleThickness, 0); glColor3fv(player1Color2); glVertex3f(-paddleWidth1/2, player1Ypos, 0); glVertex3f( paddleWidth1/2, player1Ypos, 0); glEnd(); glPopMatrix(); // bottom player (player 2) paddle glPushMatrix(); glTranslatef(player2Xpos,0,0); glBegin(GL_QUADS); glColor3fv(player2Color1); glVertex3f( paddleWidth2/2, player2Ypos, 0); // top left glVertex3f(-paddleWidth2/2, player2Ypos, 0); glColor3fv(player2Color2); glVertex3f(-paddleWidth2/2, player2Ypos-paddleThickness, 0); glVertex3f( paddleWidth2/2, player2Ypos-paddleThickness, 0); glEnd(); glPopMatrix(); // ball glColor3fv(ballColor); glEnable(GL_LIGHTING); glPushMatrix(); glTranslatef(ballPos[0], ballPos[1],0); // make ball round even though screen is stretched horizontally glScalef(1,screenAspectRatio,1); glutSolidSphere(ballRadius, 100, 100); glPopMatrix(); ballPos[0]+=ballDir[0]/ballSpeed; ballPos[1]+=ballDir[1]/ballSpeed; ballColor[0] = ballColor[0] - .005; ballColor[1] = ballColor[1] - .005; ballColor[2] = ballColor[2] - .005; if(ballColor[0] < 0) ballColor[0] = 0; if(ballColor[1] < 0) ballColor[1] = 0; if(ballColor[2] < 0) ballColor[2] = 0; bounceBall(); glFlush(); glutSwapBuffers(); glutPostRedisplay(); // call display() repeatedly } int main( int argc, char* argv[] ) { glutInit(&argc, argv); //initialize the toolkit glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); //set display mode glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT); //set window size glutInitWindowPosition(0, 0); //set window position on screen glutCreateWindow(argv[0]); //open the screen window int glew_err = glewInit(); if(glew_err != GLEW_OK) fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(glew_err)); glutDisplayFunc(display); glutKeyboardFunc(keyboard); atexit(exitCallback); viconInit(); glutMainLoop(); } <commit_msg>Removed pong.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>remove boolean parameter default from ScTable::SetDirty()<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSocketCommunicator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkSocketCommunicator.h" #include "vtkSocketController.h" #include "vtkObjectFactory.h" #if defined(_WIN32) && !defined(__CYGWIN__) #define WSA_VERSION MAKEWORD(1,1) #define vtkCloseSocketMacro(sock) (closesocket(sock)) #else #define vtkCloseSocketMacro(sock) (close(sock)) #endif // These macros are used to decrease the number of lines // not covered during testing (macros count as one line) #define vtkSCCheckForError \ if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) \ { \ return 0; \ } #define vtkSCSendError \ if (sent == -1) \ { \ vtkGenericWarningMacro("Could not send message."); \ return 0; \ } #define vtkSCReceiveError \ if (received == -1) \ { \ vtkErrorMacro("Could not receive message."); \ return 0; \ } //------------------------------------------------------------------------------ vtkSocketCommunicator* vtkSocketCommunicator::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSocketCommunicator"); if(ret) { return (vtkSocketCommunicator*)ret; } // If the factory was unable to create the object, then create it here. return new vtkSocketCommunicator; } //---------------------------------------------------------------------------- vtkSocketCommunicator::vtkSocketCommunicator() { this->Socket = -1; this->IsConnected = 0; this->NumberOfProcesses = 2; this->SwapBytesInReceivedData = 0; } //---------------------------------------------------------------------------- vtkSocketCommunicator::~vtkSocketCommunicator() { if (this->IsConnected) { vtkCloseSocketMacro(this->Socket); } } //---------------------------------------------------------------------------- void vtkSocketCommunicator::PrintSelf(ostream& os, vtkIndent indent) { vtkCommunicator::PrintSelf(os,indent); os << indent << "SwapBytesInReceivedData: " << this->SwapBytesInReceivedData << endl; } static inline int checkForError(int id, int maxId) { if ( id == 0 ) { vtkGenericWarningMacro("Can not connect to myself!"); return 1; } else if ( id >= maxId ) { vtkGenericWarningMacro("No port for process " << id << " exists."); return 1; } return 0; } static int SendMessage(char* data, int length, int tag, int sock) { int sent, total = 0; total = send(sock, (char *)&tag, sizeof(int), 0); if (total == -1) { vtkGenericWarningMacro("Could not send tag."); return 0; } while ( total < sizeof(int) ) { sent = send ( sock, (char*)data + total, sizeof(int) - total, 0 ); vtkSCSendError; total += sent; } total = send(sock, (char*)data, length, 0); if (total == -1) { vtkGenericWarningMacro("Could not send message."); return 0; } while ( total < length ) { sent = send ( sock, (char*)data + total, length - total, 0 ); vtkSCSendError; total += sent; } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(int *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(int), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned long *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data),length*sizeof(unsigned long), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(float *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(float), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(double *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(double), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(vtkIdType *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(vtkIdType), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::ReceiveMessage( char *data, int size, int length, int tag ) { int totalLength = length * size; int received, total; int recvTag = -1; char* charTag = (char*)&recvTag; total = recv( this->Socket, charTag, sizeof(int), MSG_PEEK ); if ( total == -1 ) { vtkErrorMacro("Could not receive tag."); return 0; } while ( total < sizeof(int) ) { cout << total << endl; received = recv( this->Socket, &(charTag[total]), sizeof(int) - total, 0 ); vtkSCReceiveError; total += received; } if ( this->SwapBytesInReceivedData ) { vtkSwap4( charTag ); } if ( recvTag != tag ) { return 0; } // Since we've already peeked at the entire tag, it must all be here, so // we should be able to get all of it in one try. if (recv( this->Socket, charTag, sizeof(int), 0 ) == -1) { vtkErrorMacro("Could not receive tag (even though it's already here)."); return 0; } total = recv( this->Socket, data, totalLength, 0 ); if (total == -1) { vtkErrorMacro("Could not receive message."); return 0; } while ( total < totalLength ) { received = recv( this->Socket, &(data[total]), totalLength - total, 0 ); vtkSCReceiveError; total += received; } // Unless we're dealing with chars, then check byte ordering // This is really bad and should probably use some enum for types if (this->SwapBytesInReceivedData) { if (size == 4) { vtkSwap4Range(data, length); } else { vtkSwap8Range(data, length); } } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(int *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; int retval = ReceiveMessage( (char *)data, sizeof(int), length, tag ); if ( tag == vtkMultiProcessController::RMI_TAG ) { data[2] = 1; } return retval; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned long *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(unsigned long), length, tag ); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( data, sizeof(char), length, tag); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(char), length, tag); } int vtkSocketCommunicator::Receive(float *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(float), length, tag); } int vtkSocketCommunicator::Receive(double *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(double), length, tag); } int vtkSocketCommunicator::Receive(vtkIdType *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(vtkIdType), length, tag); } int vtkSocketCommunicator::WaitForConnection(int port) { if ( this->IsConnected ) { vtkErrorMacro("Port " << 1 << " is occupied."); return 0; } int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(port); if ( bind(sock, (sockaddr *)&server, sizeof(server)) ) { vtkErrorMacro("Can not bind socket to port " << port); return 0; } listen(sock,1); this->Socket = accept(sock, 0, 0); if ( this->Socket == -1 ) { vtkErrorMacro("Error in accept."); return 0; } vtkCloseSocketMacro(sock); this->IsConnected = 1; // Handshake to determine if the client machine has the same endianness char clientIsBE; if ( !ReceiveMessage( &clientIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Client is " << ( clientIsBE ? "big" : "little" ) << "-endian"); #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); if ( clientIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } void vtkSocketCommunicator::CloseConnection() { if ( this->IsConnected ) { vtkCloseSocketMacro(this->Socket); this->IsConnected = 0; } } int vtkSocketCommunicator::ConnectTo ( char* hostName, int port ) { if ( this->IsConnected ) { vtkErrorMacro("Communicator port " << 1 << " is occupied."); return 0; } struct hostent* hp; hp = gethostbyname(hostName); if (!hp) { unsigned long addr = inet_addr(hostName); hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); } if (!hp) { vtkErrorMacro("Unknown host: " << hostName); return 0; } this->Socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in name; name.sin_family = AF_INET; memcpy(&name.sin_addr, hp->h_addr, hp->h_length); name.sin_port = htons(port); if( connect(this->Socket, (sockaddr *)&name, sizeof(name)) < 0) { vtkErrorMacro("Can not connect to " << hostName << " on port " << port); return 0; } vtkDebugMacro("Connected to " << hostName << " on port " << port); this->IsConnected = 1; // Handshake to determine if the server machine has the same endianness #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); char serverIsBE; if ( !ReceiveMessage( &serverIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG ) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Server is " << ( serverIsBE ? "big" : "little" ) << "-endian"); if ( serverIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } <commit_msg>Fixed warnings.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSocketCommunicator.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkSocketCommunicator.h" #include "vtkSocketController.h" #include "vtkObjectFactory.h" #if defined(_WIN32) && !defined(__CYGWIN__) #define WSA_VERSION MAKEWORD(1,1) #define vtkCloseSocketMacro(sock) (closesocket(sock)) #else #define vtkCloseSocketMacro(sock) (close(sock)) #endif // These macros are used to decrease the number of lines // not covered during testing (macros count as one line) #define vtkSCCheckForError \ if ( checkForError(remoteProcessId, this->NumberOfProcesses) ) \ { \ return 0; \ } #define vtkSCSendError \ if (sent == -1) \ { \ vtkGenericWarningMacro("Could not send message."); \ return 0; \ } #define vtkSCReceiveError \ if (received == -1) \ { \ vtkErrorMacro("Could not receive message."); \ return 0; \ } //------------------------------------------------------------------------------ vtkSocketCommunicator* vtkSocketCommunicator::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSocketCommunicator"); if(ret) { return (vtkSocketCommunicator*)ret; } // If the factory was unable to create the object, then create it here. return new vtkSocketCommunicator; } //---------------------------------------------------------------------------- vtkSocketCommunicator::vtkSocketCommunicator() { this->Socket = -1; this->IsConnected = 0; this->NumberOfProcesses = 2; this->SwapBytesInReceivedData = 0; } //---------------------------------------------------------------------------- vtkSocketCommunicator::~vtkSocketCommunicator() { if (this->IsConnected) { vtkCloseSocketMacro(this->Socket); } } //---------------------------------------------------------------------------- void vtkSocketCommunicator::PrintSelf(ostream& os, vtkIndent indent) { vtkCommunicator::PrintSelf(os,indent); os << indent << "SwapBytesInReceivedData: " << this->SwapBytesInReceivedData << endl; } static inline int checkForError(int id, int maxId) { if ( id == 0 ) { vtkGenericWarningMacro("Can not connect to myself!"); return 1; } else if ( id >= maxId ) { vtkGenericWarningMacro("No port for process " << id << " exists."); return 1; } return 0; } static int SendMessage(char* data, int length, int tag, int sock) { int sent, total = 0; total = send(sock, (char *)&tag, sizeof(int), 0); if (total == -1) { vtkGenericWarningMacro("Could not send tag."); return 0; } while ( total < (int)sizeof(int) ) { sent = send ( sock, (char*)data + total, sizeof(int) - total, 0 ); vtkSCSendError; total += sent; } total = send(sock, (char*)data, length, 0); if (total == -1) { vtkGenericWarningMacro("Could not send message."); return 0; } while ( total < length ) { sent = send ( sock, (char*)data + total, length - total, 0 ); vtkSCSendError; total += sent; } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(int *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(int), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned long *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data),length*sizeof(unsigned long), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(unsigned char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length, tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(float *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(float), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(double *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(double), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Send(vtkIdType *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return SendMessage(reinterpret_cast<char*>(data), length*sizeof(vtkIdType), tag, this->Socket); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::ReceiveMessage( char *data, int size, int length, int tag ) { int totalLength = length * size; int received, total; int recvTag = -1; char* charTag = (char*)&recvTag; total = recv( this->Socket, charTag, sizeof(int), MSG_PEEK ); if ( total == -1 ) { vtkErrorMacro("Could not receive tag."); return 0; } while ( total < (int)sizeof(int) ) { cout << total << endl; received = recv( this->Socket, &(charTag[total]), sizeof(int) - total, 0 ); vtkSCReceiveError; total += received; } if ( this->SwapBytesInReceivedData ) { vtkSwap4( charTag ); } if ( recvTag != tag ) { return 0; } // Since we've already peeked at the entire tag, it must all be here, so // we should be able to get all of it in one try. if (recv( this->Socket, charTag, sizeof(int), 0 ) == -1) { vtkErrorMacro("Could not receive tag (even though it's already here)."); return 0; } total = recv( this->Socket, data, totalLength, 0 ); if (total == -1) { vtkErrorMacro("Could not receive message."); return 0; } while ( total < totalLength ) { received = recv( this->Socket, &(data[total]), totalLength - total, 0 ); vtkSCReceiveError; total += received; } // Unless we're dealing with chars, then check byte ordering // This is really bad and should probably use some enum for types if (this->SwapBytesInReceivedData) { if (size == 4) { vtkSwap4Range(data, length); } else { vtkSwap8Range(data, length); } } return 1; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(int *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; int retval = ReceiveMessage( (char *)data, sizeof(int), length, tag ); if ( tag == vtkMultiProcessController::RMI_TAG ) { data[2] = 1; } return retval; } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned long *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(unsigned long), length, tag ); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( data, sizeof(char), length, tag); } //---------------------------------------------------------------------------- int vtkSocketCommunicator::Receive(unsigned char *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(char), length, tag); } int vtkSocketCommunicator::Receive(float *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(float), length, tag); } int vtkSocketCommunicator::Receive(double *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(double), length, tag); } int vtkSocketCommunicator::Receive(vtkIdType *data, int length, int remoteProcessId, int tag) { vtkSCCheckForError; return ReceiveMessage( (char *)data, sizeof(vtkIdType), length, tag); } int vtkSocketCommunicator::WaitForConnection(int port) { if ( this->IsConnected ) { vtkErrorMacro("Port " << 1 << " is occupied."); return 0; } int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(port); if ( bind(sock, (sockaddr *)&server, sizeof(server)) ) { vtkErrorMacro("Can not bind socket to port " << port); return 0; } listen(sock,1); this->Socket = accept(sock, 0, 0); if ( this->Socket == -1 ) { vtkErrorMacro("Error in accept."); return 0; } vtkCloseSocketMacro(sock); this->IsConnected = 1; // Handshake to determine if the client machine has the same endianness char clientIsBE; if ( !ReceiveMessage( &clientIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Client is " << ( clientIsBE ? "big" : "little" ) << "-endian"); #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); if ( clientIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } void vtkSocketCommunicator::CloseConnection() { if ( this->IsConnected ) { vtkCloseSocketMacro(this->Socket); this->IsConnected = 0; } } int vtkSocketCommunicator::ConnectTo ( char* hostName, int port ) { if ( this->IsConnected ) { vtkErrorMacro("Communicator port " << 1 << " is occupied."); return 0; } struct hostent* hp; hp = gethostbyname(hostName); if (!hp) { unsigned long addr = inet_addr(hostName); hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET); } if (!hp) { vtkErrorMacro("Unknown host: " << hostName); return 0; } this->Socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in name; name.sin_family = AF_INET; memcpy(&name.sin_addr, hp->h_addr, hp->h_length); name.sin_port = htons(port); if( connect(this->Socket, (sockaddr *)&name, sizeof(name)) < 0) { vtkErrorMacro("Can not connect to " << hostName << " on port " << port); return 0; } vtkDebugMacro("Connected to " << hostName << " on port " << port); this->IsConnected = 1; // Handshake to determine if the server machine has the same endianness #ifdef VTK_WORDS_BIGENDIAN char IAmBE = 1; #else char IAmBE = 0; #endif vtkDebugMacro(<< "I am " << ( IAmBE ? "big" : "little" ) << "-endian"); SendMessage( &IAmBE, 1, vtkSocketController::ENDIAN_TAG, this->Socket ); char serverIsBE; if ( !ReceiveMessage( &serverIsBE, sizeof(char), 1, vtkSocketController::ENDIAN_TAG ) ) { vtkErrorMacro("Endian handshake failed."); return 0; } vtkDebugMacro(<< "Server is " << ( serverIsBE ? "big" : "little" ) << "-endian"); if ( serverIsBE != IAmBE ) { this->SwapBytesInReceivedData = 1; } return 1; } <|endoftext|>
<commit_before> //snippet-sourcedescription:[create_bucket.cpp demonstrates how to create an Amazon S3 bucket.] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon S3] //snippet-service:[s3] //snippet-sourcetype:[full-example] //snippet-sourcedate:[] //snippet-sourceauthor:[AWS] /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //snippet-start:[s3.cpp.create_bucket.inc] #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/CreateBucketRequest.h> //snippet-end:[s3.cpp.create_bucket.inc] /** * Create an Amazon S3 bucket. */ int main(int argc, char** argv) { if (argc < 2) { std::cout << "create_bucket - create an S3 bucket" << std::endl << "\nUsage:" << std::endl << " create_bucket <bucket>" << std::endl << "\nWhere:" << std::endl << " bucket - the bucket to create" << std::endl << "\nExample:" << std::endl << " create_bucket testbucket\n" << std::endl << std::endl; exit(1); } Aws::SDKOptions options; Aws::InitAPI(options); { const Aws::String bucket_name = argv[1]; std::cout << "Creating S3 bucket: " << bucket_name << std::endl; // snippet-start:[s3.cpp.create_bucket.code] Aws::S3::S3Client s3_client; Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucket_name); auto outcome = s3_client.CreateBucket(request); if (outcome.IsSuccess()) { std::cout << "Done!" << std::endl; } else { std::cout << "CreateBucket error: " << outcome.GetError().GetExceptionName() << std::endl << outcome.GetError().GetMessage() << std::endl; } // snippet-end:[s3.cpp.create_bucket.code] } Aws::ShutdownAPI(options); } <commit_msg>Add support for regions in C++ S3 CreateBucket example<commit_after> //snippet-sourcedescription:[create_bucket.cpp demonstrates how to create an Amazon S3 bucket.] //snippet-service:[s3] //snippet-keyword:[Amazon S3] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-sourcetype:[snippet] //snippet-sourcedate:[2019-06-20] //snippet-sourceauthor:[AWS] /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //snippet-start:[s3.cpp.create_bucket.inc] #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/CreateBucketRequest.h> //snippet-end:[s3.cpp.create_bucket.inc] /** * Create an Amazon S3 bucket in a specified region */ // snippet-start:[s3.cpp.create_bucket.code] bool create_bucket(const Aws::String &bucket_name, const Aws::S3::Model::BucketLocationConstraint &region = Aws::S3::Model::BucketLocationConstraint::us_east_1) { // Set up the request Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucket_name); // Is the region other than us-east-1 (N. Virginia)? if (region != Aws::S3::Model::BucketLocationConstraint::us_east_1) { // Specify the region as a location constraint Aws::S3::Model::CreateBucketConfiguration bucket_config; bucket_config.SetLocationConstraint(region); request.SetCreateBucketConfiguration(bucket_config); } // Create the bucket Aws::S3::S3Client s3_client; auto outcome = s3_client.CreateBucket(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cout << "ERROR: CreateBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; return false; } return true; } // snippet-end:[s3.cpp.create_bucket.code] /** * Exercise create_bucket() */ int main() { // Set these values before compiling and running the program const Aws::String bucket_name_in_default_region = "BUCKET_NAME"; const Aws::String bucket_name_in_specified_region = "BUCKET_NAME"; const Aws::S3::Model::BucketLocationConstraint region = Aws::S3::Model::BucketLocationConstraint::us_west_2; Aws::SDKOptions options; Aws::InitAPI(options); { // Create a bucket in the S3 default region (us-east-1) if (create_bucket(bucket_name_in_default_region)) { std::cout << "Created bucket " << bucket_name_in_default_region << " in the S3 default region (us-east-1)\n"; } // Create a bucket in a specified region if (create_bucket(bucket_name_in_specified_region, region)) { std::cout << "Created bucket " << bucket_name_in_specified_region << " in the specified region" << std::endl; } } Aws::ShutdownAPI(options); } <|endoftext|>
<commit_before>#include "merkletree/compact_merkle_tree.h" #include <assert.h> #include <stddef.h> #include <string> #include <vector> #include "merkletree/merkle_tree_math.h" using cert_trans::MerkleTreeInterface; using std::string; CompactMerkleTree::CompactMerkleTree(SerialHasher* hasher) : MerkleTreeInterface(), treehasher_(hasher), leaf_count_(0), leaves_processed_(0), level_count_(0), root_(treehasher_.HashEmpty()) { } CompactMerkleTree::CompactMerkleTree(MerkleTree& model, SerialHasher* hasher) : MerkleTreeInterface(), tree_(std::max<int64_t>(0, model.LevelCount() - 1)), treehasher_(hasher), leaf_count_(model.LeafCount()), leaves_processed_(0), level_count_(model.LevelCount()), root_(treehasher_.HashEmpty()) { if (model.LeafCount() == 0) { return; } // Get the inclusion proof path to the last entry in the tree, which by // definition must consist purely of left-hand nodes. std::vector<string> path(model.PathToCurrentRoot(model.LeafCount())); if (path.size() > 0) { /* We have to do some juggling here as tree_[] differs from our MerkleTree // structure in that incomplete right-hand subtrees 'fall-through' to lower // levels: // // MerkleTree structure for 3 leaves: // R // / \ // / \ // AB c // / \ // a b // // Compact tree represents this as: // R // / \ // / \ // AB . // | // c // or: // tree_[1] = AB // tree_[0] = c // (c) has "fallen-through" to the lowest level // // The inclusion proof path for the right-most entry effectively // describes the state of the tree immediately before the right-most // entry was added. // Since the inclusion proof path consists exclusively of left-hand // nodes and each entry in the path covers the maximum sub-tree possible, // we can use this to directly construct the Compact respresentation of // the tree before the newest entry was added. */ // index into tree_, starting at the leaf level: int level(0); std::vector<string>::const_iterator i = path.begin(); size_t size_of_previous_tree(model.LeafCount() - 1); for (; size_of_previous_tree != 0; size_of_previous_tree >>= 1) { if ((size_of_previous_tree & 1) != 0) { // if the level'th bit in the previous tree size is set, then we have // a proof path entry for this level (because proof entries cover the // maximum possible sub-tree.) tree_[level] = *i; i++; } level++; } assert(i == path.end()); } // Now tree_ should contain a representation of the tree state just before // the last entry was added, so we PushBack the final right-hand entry // here, which will perform any recalculations necessary to reach the final // tree. PushBack(0, model.LeafHash(model.LeafCount())); assert(model.CurrentRoot() == CurrentRoot()); assert(model.LeafCount() == LeafCount()); assert(model.LevelCount() == LevelCount()); } CompactMerkleTree::CompactMerkleTree(const CompactMerkleTree& other, SerialHasher* hasher) : tree_(other.tree_), treehasher_(hasher), leaf_count_(other.leaf_count_), leaves_processed_(other.leaves_processed_), level_count_(other.level_count_), root_(other.root_) { } CompactMerkleTree::~CompactMerkleTree() { } size_t CompactMerkleTree::AddLeaf(const string& data) { return AddLeafHash(treehasher_.HashLeaf(data)); } size_t CompactMerkleTree::AddLeafHash(const string& hash) { PushBack(0, hash); // Update level count: a k-level tree can hold 2^{k-1} leaves, // so increment level count every time we overflow a power of two. // Do not update the root; we evaluate the tree lazily. if (MerkleTreeMath::IsPowerOfTwoPlusOne(++leaf_count_)) ++level_count_; return leaf_count_; } string CompactMerkleTree::CurrentRoot() { UpdateRoot(); return root_; } void CompactMerkleTree::PushBack(size_t level, string node) { assert(node.size() == treehasher_.DigestSize()); if (tree_.size() <= level) { // First node at a new level. tree_.push_back(node); } else if (tree_[level].empty()) { // Lone left sibling. tree_[level] = node; } else { // Left sibling waiting: hash together and propagate up. PushBack(level + 1, treehasher_.HashChildren(tree_[level], node)); tree_[level].clear(); } } void CompactMerkleTree::UpdateRoot() { if (leaves_processed_ == LeafCount()) return; string right_sibling; for (size_t level = 0; level < tree_.size(); ++level) { if (!tree_[level].empty()) { // A lonely left sibling gets pulled up as a right sibling. if (right_sibling.empty()) right_sibling = tree_[level]; else right_sibling = treehasher_.HashChildren(tree_[level], right_sibling); } } root_ = right_sibling; leaves_processed_ = LeafCount(); } <commit_msg>Use the empty() method instead of "size() > 0".<commit_after>#include "merkletree/compact_merkle_tree.h" #include <assert.h> #include <stddef.h> #include <string> #include <vector> #include "merkletree/merkle_tree_math.h" using cert_trans::MerkleTreeInterface; using std::string; CompactMerkleTree::CompactMerkleTree(SerialHasher* hasher) : MerkleTreeInterface(), treehasher_(hasher), leaf_count_(0), leaves_processed_(0), level_count_(0), root_(treehasher_.HashEmpty()) { } CompactMerkleTree::CompactMerkleTree(MerkleTree& model, SerialHasher* hasher) : MerkleTreeInterface(), tree_(std::max<int64_t>(0, model.LevelCount() - 1)), treehasher_(hasher), leaf_count_(model.LeafCount()), leaves_processed_(0), level_count_(model.LevelCount()), root_(treehasher_.HashEmpty()) { if (model.LeafCount() == 0) { return; } // Get the inclusion proof path to the last entry in the tree, which by // definition must consist purely of left-hand nodes. std::vector<string> path(model.PathToCurrentRoot(model.LeafCount())); if (!path.empty()) { /* We have to do some juggling here as tree_[] differs from our MerkleTree // structure in that incomplete right-hand subtrees 'fall-through' to lower // levels: // // MerkleTree structure for 3 leaves: // R // / \ // / \ // AB c // / \ // a b // // Compact tree represents this as: // R // / \ // / \ // AB . // | // c // or: // tree_[1] = AB // tree_[0] = c // (c) has "fallen-through" to the lowest level // // The inclusion proof path for the right-most entry effectively // describes the state of the tree immediately before the right-most // entry was added. // Since the inclusion proof path consists exclusively of left-hand // nodes and each entry in the path covers the maximum sub-tree possible, // we can use this to directly construct the Compact respresentation of // the tree before the newest entry was added. */ // index into tree_, starting at the leaf level: int level(0); std::vector<string>::const_iterator i = path.begin(); size_t size_of_previous_tree(model.LeafCount() - 1); for (; size_of_previous_tree != 0; size_of_previous_tree >>= 1) { if ((size_of_previous_tree & 1) != 0) { // if the level'th bit in the previous tree size is set, then we have // a proof path entry for this level (because proof entries cover the // maximum possible sub-tree.) tree_[level] = *i; i++; } level++; } assert(i == path.end()); } // Now tree_ should contain a representation of the tree state just before // the last entry was added, so we PushBack the final right-hand entry // here, which will perform any recalculations necessary to reach the final // tree. PushBack(0, model.LeafHash(model.LeafCount())); assert(model.CurrentRoot() == CurrentRoot()); assert(model.LeafCount() == LeafCount()); assert(model.LevelCount() == LevelCount()); } CompactMerkleTree::CompactMerkleTree(const CompactMerkleTree& other, SerialHasher* hasher) : tree_(other.tree_), treehasher_(hasher), leaf_count_(other.leaf_count_), leaves_processed_(other.leaves_processed_), level_count_(other.level_count_), root_(other.root_) { } CompactMerkleTree::~CompactMerkleTree() { } size_t CompactMerkleTree::AddLeaf(const string& data) { return AddLeafHash(treehasher_.HashLeaf(data)); } size_t CompactMerkleTree::AddLeafHash(const string& hash) { PushBack(0, hash); // Update level count: a k-level tree can hold 2^{k-1} leaves, // so increment level count every time we overflow a power of two. // Do not update the root; we evaluate the tree lazily. if (MerkleTreeMath::IsPowerOfTwoPlusOne(++leaf_count_)) ++level_count_; return leaf_count_; } string CompactMerkleTree::CurrentRoot() { UpdateRoot(); return root_; } void CompactMerkleTree::PushBack(size_t level, string node) { assert(node.size() == treehasher_.DigestSize()); if (tree_.size() <= level) { // First node at a new level. tree_.push_back(node); } else if (tree_[level].empty()) { // Lone left sibling. tree_[level] = node; } else { // Left sibling waiting: hash together and propagate up. PushBack(level + 1, treehasher_.HashChildren(tree_[level], node)); tree_[level].clear(); } } void CompactMerkleTree::UpdateRoot() { if (leaves_processed_ == LeafCount()) return; string right_sibling; for (size_t level = 0; level < tree_.size(); ++level) { if (!tree_[level].empty()) { // A lonely left sibling gets pulled up as a right sibling. if (right_sibling.empty()) right_sibling = tree_[level]; else right_sibling = treehasher_.HashChildren(tree_[level], right_sibling); } } root_ = right_sibling; leaves_processed_ = LeafCount(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: implrenderer.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: thb $ $Date: 2004-03-18 10:41:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CPPCANVAS_IMPLRENDERER_HXX #define _CPPCANVAS_IMPLRENDERER_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef BOOST_SHARED_PTR_HPP_INCLUDED #include <external/boost/shared_ptr.hpp> #endif #ifndef _CPPCANVAS_RENDERER_HXX #include <cppcanvas/renderer.hxx> #endif #ifndef _CPPCANVAS_CANVAS_HXX #include <cppcanvas/canvas.hxx> #endif #include "canvasgraphichelper.hxx" #include "action.hxx" #include <vector> class GDIMetaFile; class BitmapEx; class VirtualDevice; class Gradient; namespace cppcanvas { namespace internal { struct OutDevState; // state stack of OutputDevice, to correctly handle // push/pop actions typedef ::std::vector< OutDevState > VectorOfOutDevStates; class ImplRenderer : public virtual Renderer, protected CanvasGraphicHelper { public: ImplRenderer( const CanvasSharedPtr& rCanvas, const GDIMetaFile& rMtf ); ImplRenderer( const CanvasSharedPtr& rCanvas, const BitmapEx& rBmpEx ); virtual ~ImplRenderer(); virtual bool draw() const; virtual bool drawSubset( int nStartIndex, int nEndIndex ) const; // element of the Renderer's action vector. Need to be // public, since some functors need it, too. struct MtfAction { MtfAction( const ActionSharedPtr& rAction, int nOrigIndex ) : mpAction( rAction ), mnOrigIndex( nOrigIndex ) { } ActionSharedPtr mpAction; int mnOrigIndex; }; private: // default: disabled copy/assignment ImplRenderer(const ImplRenderer&); ImplRenderer& operator=( const ImplRenderer& ); bool createActions( const CanvasSharedPtr& rCanvas, VirtualDevice& rVDev, GDIMetaFile& rMtf, VectorOfOutDevStates& rStates ); bool createFillAndStroke( const ::PolyPolygon& rPolyPoly, const CanvasSharedPtr& rCanvas, int rActionIndex, VectorOfOutDevStates& rStates ); void skipContent( GDIMetaFile& rMtf, const char& rCommentString ) const; void createGradientAction( const Rectangle& rRect, const Gradient& rGradient, VirtualDevice& rVDev, const CanvasSharedPtr& rCanvas, VectorOfOutDevStates& rStates ); // prefetched and prepared canvas actions // (externally not visible) typedef ::std::vector< MtfAction > ActionVector; ActionVector maActions; }; } } #endif /* _CPPCANVAS_IMPLRENDERER_HXX */ <commit_msg>INTEGRATION: CWS ooo20040704 (1.2.10); FILE MERGED 2004/06/28 12:12:42 cmc 1.2.10.1: #i30801 no need to prepend external before boost<commit_after>/************************************************************************* * * $RCSfile: implrenderer.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-09-08 16:59:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CPPCANVAS_IMPLRENDERER_HXX #define _CPPCANVAS_IMPLRENDERER_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef BOOST_SHARED_PTR_HPP_INCLUDED #include <boost/shared_ptr.hpp> #endif #ifndef _CPPCANVAS_RENDERER_HXX #include <cppcanvas/renderer.hxx> #endif #ifndef _CPPCANVAS_CANVAS_HXX #include <cppcanvas/canvas.hxx> #endif #include "canvasgraphichelper.hxx" #include "action.hxx" #include <vector> class GDIMetaFile; class BitmapEx; class VirtualDevice; class Gradient; namespace cppcanvas { namespace internal { struct OutDevState; // state stack of OutputDevice, to correctly handle // push/pop actions typedef ::std::vector< OutDevState > VectorOfOutDevStates; class ImplRenderer : public virtual Renderer, protected CanvasGraphicHelper { public: ImplRenderer( const CanvasSharedPtr& rCanvas, const GDIMetaFile& rMtf ); ImplRenderer( const CanvasSharedPtr& rCanvas, const BitmapEx& rBmpEx ); virtual ~ImplRenderer(); virtual bool draw() const; virtual bool drawSubset( int nStartIndex, int nEndIndex ) const; // element of the Renderer's action vector. Need to be // public, since some functors need it, too. struct MtfAction { MtfAction( const ActionSharedPtr& rAction, int nOrigIndex ) : mpAction( rAction ), mnOrigIndex( nOrigIndex ) { } ActionSharedPtr mpAction; int mnOrigIndex; }; private: // default: disabled copy/assignment ImplRenderer(const ImplRenderer&); ImplRenderer& operator=( const ImplRenderer& ); bool createActions( const CanvasSharedPtr& rCanvas, VirtualDevice& rVDev, GDIMetaFile& rMtf, VectorOfOutDevStates& rStates ); bool createFillAndStroke( const ::PolyPolygon& rPolyPoly, const CanvasSharedPtr& rCanvas, int rActionIndex, VectorOfOutDevStates& rStates ); void skipContent( GDIMetaFile& rMtf, const char& rCommentString ) const; void createGradientAction( const Rectangle& rRect, const Gradient& rGradient, VirtualDevice& rVDev, const CanvasSharedPtr& rCanvas, VectorOfOutDevStates& rStates ); // prefetched and prepared canvas actions // (externally not visible) typedef ::std::vector< MtfAction > ActionVector; ActionVector maActions; }; } } #endif /* _CPPCANVAS_IMPLRENDERER_HXX */ <|endoftext|>
<commit_before>// // file : xQGanttListView.C // date : 23 nov 2000 // changed : // author : jh // #include "xQGanttListView.h" #include <qcolor.h> xQGanttListView::xQGanttListView(KGanttItem* toplevelitem, QWidget* parent, const char * name, WFlags f) : QScrollView(parent,name,f) ///////////////////////////////////////////////////////// { _toplevelitem = toplevelitem; setFrameStyle(QFrame::Sunken); setLineWidth(1); _headerBackBrush = QBrush(QColor(230,230,230)); setMargins( 1, TOPMARGIN , 1, 1 ); setVScrollBarMode( AlwaysOff ); _viewport = new xQGanttListViewPort(toplevelitem,viewport()); addChild(_viewport); viewport()->setBackgroundColor(QColor(white)); } xQGanttListView::~xQGanttListView() /////////////////////////////////// { } void xQGanttListView::drawHeader() /////////////////////////////// { // printf("xQGanttListView::drawHeader()\n"); QPainter p(this); p.setPen( QPen(QColor(black)) ); p.fillRect(0,0,width(),TOPMARGIN, _headerBackBrush ); p.drawText(5, (0.8 * TOPMARGIN), i18n("Items")); } void xQGanttListView::contentsMoved(int x, int y) //////////////////////////////////////////// { printf("xQGanttListView::contentsMoved(%d,%d)\n", x, y); setContentsPos( 0, y ); } void xQGanttListView::paintEvent(QPaintEvent * e) { drawHeader(); } #include "xQGanttListView.moc" <commit_msg>fix compilation<commit_after>// // file : xQGanttListView.C // date : 23 nov 2000 // changed : // author : jh // #include "xQGanttListView.h" #include <qcolor.h> #include <klocale.h> xQGanttListView::xQGanttListView(KGanttItem* toplevelitem, QWidget* parent, const char * name, WFlags f) : QScrollView(parent,name,f) ///////////////////////////////////////////////////////// { _toplevelitem = toplevelitem; setFrameStyle(QFrame::Sunken); setLineWidth(1); _headerBackBrush = QBrush(QColor(230,230,230)); setMargins( 1, TOPMARGIN , 1, 1 ); setVScrollBarMode( AlwaysOff ); _viewport = new xQGanttListViewPort(toplevelitem,viewport()); addChild(_viewport); viewport()->setBackgroundColor(QColor(white)); } xQGanttListView::~xQGanttListView() /////////////////////////////////// { } void xQGanttListView::drawHeader() /////////////////////////////// { // printf("xQGanttListView::drawHeader()\n"); QPainter p(this); p.setPen( QPen(QColor(black)) ); p.fillRect(0,0,width(),TOPMARGIN, _headerBackBrush ); p.drawText(5, (0.8 * TOPMARGIN), i18n("Items")); } void xQGanttListView::contentsMoved(int x, int y) //////////////////////////////////////////// { printf("xQGanttListView::contentsMoved(%d,%d)\n", x, y); setContentsPos( 0, y ); } void xQGanttListView::paintEvent(QPaintEvent * e) { drawHeader(); } #include "xQGanttListView.moc" <|endoftext|>
<commit_before>#include "idletimedetector.h" #include <qdatetime.h> #include <qmessagebox.h> #include <qtimer.h> #include <kdialog.h> #include <kglobal.h> #include <klocale.h> // i18n #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #ifdef Q_WS_X11 #include <QX11Info> #endif IdleTimeDetector::IdleTimeDetector(int maxIdle) { _maxIdle = maxIdle; #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) int event_base, error_base; if(XScreenSaverQueryExtension(QX11Info::display(), &event_base, &error_base)) { _idleDetectionPossible = true; } else { _idleDetectionPossible = false; } _timer = new QTimer(this); connect(_timer, SIGNAL(timeout()), this, SLOT(check())); #else _idleDetectionPossible = false; #endif // HAVE_LIBXSS } bool IdleTimeDetector::isIdleDetectionPossible() { return _idleDetectionPossible; } void IdleTimeDetector::check() { #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) if (_idleDetectionPossible) { _mit_info = XScreenSaverAllocInfo (); XScreenSaverQueryInfo(QX11Info::display(), QX11Info::appRootWindow(), _mit_info); idleminutes = (_mit_info->idle/1000)/secsPerMinute; if (idleminutes >= _maxIdle) informOverrun(); } #endif // HAVE_LIBXSS } void IdleTimeDetector::setMaxIdle(int maxIdle) { _maxIdle = maxIdle; } void IdleTimeDetector::revert() { // revert and stop kDebug(5970) << "Entering IdleTimeDetector::revert" << endl; QDateTime end = QDateTime::currentDateTime(); int diff = start.secsTo(end)/secsPerMinute; emit(extractTime(idleminutes+diff)); emit(stopAllTimers()); } #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) void IdleTimeDetector::informOverrun() { if (!_overAllIdleDetect) return; // In the preferences the user has indicated that he do not // want idle detection. _timer->stop(); start = QDateTime::currentDateTime(); QDateTime idleStart = start.addSecs(-60 * _maxIdle); QString backThen = KGlobal::locale()->formatTime(idleStart.time()); // Create dialog KDialog *dialog=new KDialog( 0 ); QWidget* wid=new QWidget(dialog); dialog->setMainWidget( wid ); QVBoxLayout *lay1 = new QVBoxLayout(wid); QHBoxLayout *lay2 = new QHBoxLayout(); lay1->addLayout(lay2); QString idlemsg=QString( "Desktop has been idle since %1. What do you want to do ?" ).arg(backThen); QLabel *label = new QLabel( idlemsg, wid ); lay2->addWidget( label ); connect( dialog , SIGNAL(cancelClicked()) , this , SLOT(revert()) ); connect( wid , SIGNAL(changed(bool)) , wid , SLOT(enabledButtonApply(bool)) ); QString explanation=i18n(QString("Continue timing. Timing has started at %1").arg(backThen).toAscii()); QString explanationrevert=i18n(QString( "Stop timing and revert back to the time at %1." ).arg(backThen).toAscii()); dialog->setButtonText(KDialog::Ok, i18n("Continue timing.")); dialog->setButtonText(KDialog::Cancel, i18n("Revert timing")); dialog->setButtonWhatsThis(KDialog::Ok, explanation); dialog->setButtonWhatsThis(KDialog::Cancel, explanationrevert); dialog->show(); /* else { // Continue _timer->start(testInterval); } */ } #endif // HAVE_LIBXSS void IdleTimeDetector::startIdleDetection() { #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) if (!_timer->isActive()) _timer->start(testInterval); #endif //HAVE_LIBXSS } void IdleTimeDetector::stopIdleDetection() { #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) if (_timer->isActive()) _timer->stop(); #endif // HAVE_LIBXSS } void IdleTimeDetector::toggleOverAllIdleDetection(bool on) { _overAllIdleDetect = on; } #include "idletimedetector.moc" <commit_msg>confusion--<commit_after>#include "idletimedetector.h" #include <qdatetime.h> #include <qmessagebox.h> #include <qtimer.h> #include <kdialog.h> #include <kglobal.h> #include <klocale.h> // i18n #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #ifdef Q_WS_X11 #include <QX11Info> #endif IdleTimeDetector::IdleTimeDetector(int maxIdle) { _maxIdle = maxIdle; #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) int event_base, error_base; if(XScreenSaverQueryExtension(QX11Info::display(), &event_base, &error_base)) { _idleDetectionPossible = true; } else { _idleDetectionPossible = false; } _timer = new QTimer(this); connect(_timer, SIGNAL(timeout()), this, SLOT(check())); #else _idleDetectionPossible = false; #endif // HAVE_LIBXSS } bool IdleTimeDetector::isIdleDetectionPossible() { return _idleDetectionPossible; } void IdleTimeDetector::check() { #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) if (_idleDetectionPossible) { _mit_info = XScreenSaverAllocInfo (); XScreenSaverQueryInfo(QX11Info::display(), QX11Info::appRootWindow(), _mit_info); idleminutes = (_mit_info->idle/1000)/secsPerMinute; if (idleminutes >= _maxIdle) informOverrun(); } #endif // HAVE_LIBXSS } void IdleTimeDetector::setMaxIdle(int maxIdle) { _maxIdle = maxIdle; } void IdleTimeDetector::revert() { // revert and stop kDebug(5970) << "Entering IdleTimeDetector::revert" << endl; QDateTime end = QDateTime::currentDateTime(); int diff = start.secsTo(end)/secsPerMinute; emit(extractTime(idleminutes+diff)); emit(stopAllTimers()); } #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) void IdleTimeDetector::informOverrun() { if (!_overAllIdleDetect) return; // In the preferences the user has indicated that he do not // want idle detection. _timer->stop(); start = QDateTime::currentDateTime(); idlestart = start.addSecs(-60 * _maxIdle); QString backThen = KGlobal::locale()->formatTime(idlestart.time()); // Create dialog KDialog *dialog=new KDialog( 0 ); QWidget* wid=new QWidget(dialog); dialog->setMainWidget( wid ); QVBoxLayout *lay1 = new QVBoxLayout(wid); QHBoxLayout *lay2 = new QHBoxLayout(); lay1->addLayout(lay2); QString idlemsg=QString( "Desktop has been idle since %1. What do you want to do ?" ).arg(backThen); QLabel *label = new QLabel( idlemsg, wid ); lay2->addWidget( label ); connect( dialog , SIGNAL(cancelClicked()) , this , SLOT(revert()) ); connect( wid , SIGNAL(changed(bool)) , wid , SLOT(enabledButtonApply(bool)) ); QString explanation=i18n(QString("Continue timing. Timing has started at %1").arg(backThen).toAscii()); QString explanationrevert=i18n(QString( "Stop timing and revert back to the time at %1." ).arg(backThen).toAscii()); dialog->setButtonText(KDialog::Ok, i18n("Continue timing.")); dialog->setButtonText(KDialog::Cancel, i18n("Revert timing")); dialog->setButtonWhatsThis(KDialog::Ok, explanation); dialog->setButtonWhatsThis(KDialog::Cancel, explanationrevert); dialog->show(); /* else { // Continue _timer->start(testInterval); } */ } #endif // HAVE_LIBXSS void IdleTimeDetector::startIdleDetection() { #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) if (!_timer->isActive()) _timer->start(testInterval); #endif //HAVE_LIBXSS } void IdleTimeDetector::stopIdleDetection() { #if defined(HAVE_LIBXSS) && defined(Q_WS_X11) if (_timer->isActive()) _timer->stop(); #endif // HAVE_LIBXSS } void IdleTimeDetector::toggleOverAllIdleDetection(bool on) { _overAllIdleDetect = on; } #include "idletimedetector.moc" <|endoftext|>
<commit_before>// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s // PR36992 namespace Implicit { struct A { char c; A(const A&); }; struct B { int n; char c[3]; ~B(); }; struct C : B, virtual A {}; static_assert(sizeof(C) == sizeof(void*) + 8); C f(C c) { return c; } // CHECK: define {{.*}} @_ZN8Implicit1CC1EOS0_ // CHECK: call {{.*}} @_ZN8Implicit1AC2ERKS0_( // Note: this must memcpy 7 bytes, not 8, to avoid trampling over the virtual base class. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 7, i1 false) // CHECK: store i32 {{.*}} @_ZTVN8Implicit1CE } namespace InitWithinNVSize { // This is the same as the previous test, except that the A base lies // entirely within the nvsize of C. This makes it valid to copy at the // full width. struct A { char c; A(const A&); }; struct B { int n; char c[3]; ~B(); }; struct C : B, virtual A { char x; }; static_assert(sizeof(C) > sizeof(void*) + 8); C f(C c) { return c; } // CHECK: define {{.*}} @_ZN16InitWithinNVSize1CC1EOS0_ // CHECK: call {{.*}} @_ZN16InitWithinNVSize1AC2ERKS0_( // This copies over the 'C::x' member, but that's OK because we've not initialized it yet. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 8, i1 false) // CHECK: store i32 {{.*}} @_ZTVN16InitWithinNVSize1CE // CHECK: store i8 } namespace NoUniqueAddr { struct A { char c; A(const A&); }; struct B { int n; char c[3]; ~B(); }; struct C : virtual A { B b; }; struct D : virtual A { [[no_unique_address]] B b; }; struct E : virtual A { [[no_unique_address]] B b; char x; }; static_assert(sizeof(C) == sizeof(void*) + 8 + alignof(void*)); static_assert(sizeof(D) == sizeof(void*) + 8); static_assert(sizeof(E) == sizeof(void*) + 8 + alignof(void*)); // CHECK: define {{.*}} @_ZN12NoUniqueAddr1CC1EOS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1CE // Copy the full size of B. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 8, i1 false) C f(C c) { return c; } // CHECK: define {{.*}} @_ZN12NoUniqueAddr1DC1EOS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1DE // Copy just the data size of B, to avoid overwriting the A base class. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 7, i1 false) D f(D d) { return d; } // CHECK: define {{.*}} @_ZN12NoUniqueAddr1EC1EOS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1EE // We can copy the full size of B here. (As it happens, we fold the copy of 'x' into // this memcpy, so we're copying 8 bytes either way.) // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 8, i1 false) E f(E e) { return e; } struct F : virtual A { F(const F &o) : A(o), b(o.b) {} [[no_unique_address]] B b; }; // CHECK: define {{.*}} @_ZN12NoUniqueAddr1FC1ERKS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1FE // CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 7, i1 false) F f(F x) { return x; } } <commit_msg>Fix test for 32-bit targets.<commit_after>// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s // PR36992 namespace Implicit { struct A { char c; A(const A&); }; struct B { int n; char c[3]; ~B(); }; struct C : B, virtual A {}; static_assert(sizeof(C) == sizeof(void*) + 8); C f(C c) { return c; } // CHECK: define {{.*}} @_ZN8Implicit1CC1EOS0_ // CHECK: call {{.*}} @_ZN8Implicit1AC2ERKS0_( // Note: this must memcpy 7 bytes, not 8, to avoid trampling over the virtual base class. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 7, i1 false) // CHECK: store i32 {{.*}} @_ZTVN8Implicit1CE } namespace InitWithinNVSize { // This is the same as the previous test, except that the A base lies // entirely within the nvsize of C. This makes it valid to copy at the // full width. struct A { char c; A(const A&); }; struct B { int n; char c[3]; ~B(); }; struct C : B, virtual A { char x; }; static_assert(sizeof(C) > sizeof(void*) + 8); C f(C c) { return c; } // CHECK: define {{.*}} @_ZN16InitWithinNVSize1CC1EOS0_ // CHECK: call {{.*}} @_ZN16InitWithinNVSize1AC2ERKS0_( // This copies over the 'C::x' member, but that's OK because we've not initialized it yet. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 8, i1 false) // CHECK: store i32 {{.*}} @_ZTVN16InitWithinNVSize1CE // CHECK: store i8 } namespace NoUniqueAddr { struct A { char c; A(const A&); }; struct B { int n; char c[3]; ~B(); }; struct C : virtual A { B b; }; struct D : virtual A { [[no_unique_address]] B b; }; struct E : virtual A { [[no_unique_address]] B b; char x; }; static_assert(sizeof(C) == sizeof(void*) + 8 + alignof(void*)); static_assert(sizeof(D) == sizeof(void*) + 8); static_assert(sizeof(E) == sizeof(void*) + 8 + alignof(void*)); // CHECK: define {{.*}} @_ZN12NoUniqueAddr1CC1EOS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1CE // Copy the full size of B. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 8, i1 false) C f(C c) { return c; } // CHECK: define {{.*}} @_ZN12NoUniqueAddr1DC1EOS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1DE // Copy just the data size of B, to avoid overwriting the A base class. // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 7, i1 false) D f(D d) { return d; } // CHECK: define {{.*}} @_ZN12NoUniqueAddr1EC1EOS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1EE // We can copy the full size of B here. (As it happens, we fold the copy of 'x' into // this memcpy, so we're copying 8 bytes either way.) // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 8, i1 false) E f(E e) { return e; } struct F : virtual A { F(const F &o) : A(o), b(o.b) {} [[no_unique_address]] B b; }; // CHECK: define {{.*}} @_ZN12NoUniqueAddr1FC1ERKS0_ // CHECK: call {{.*}} @_ZN12NoUniqueAddr1AC2ERKS0_( // CHECK: store i32 {{.*}} @_ZTVN12NoUniqueAddr1FE // CHECK: call void @llvm.memcpy.p0i8.p0i8.i{{32|64}}(i8* {{.*}}, i8* {{.*}}, i{{32|64}} 7, i1 false) F f(F x) { return x; } } <|endoftext|>
<commit_before>// @(#)root/g3d:$Name: $:$Id: TPARA.cxx,v 1.2 2004/08/03 16:01:18 brun Exp $ // Author: Nenad Buncic 19/09/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TPARA.h" #include "TNode.h" ClassImp(TPARA) //______________________________________________________________________________ // Begin_Html <P ALIGN=CENTER> <IMG SRC="gif/para.gif"> </P> End_Html // PARA is a parallelepiped. It has 9 parameters: // // - name name of the shape // - title shape's title // - material (see TMaterial) // - dx half-length in x // - dy half-length in y // - dz half-length in z // - alpha angle formed by the y axis and by the plane joining the // centre of the faces parallel to the z-x plane at -DY and +DY // - theta polar angle of the line joining the centres of the faces // at -DZ and +DZ in z // - phi azimuthal angle of the line joining the centres of the // faces at -DZ and +DZ in z //______________________________________________________________________________ TPARA::TPARA() { // PARA shape default constructor } //______________________________________________________________________________ TPARA::TPARA(const char *name, const char *title, const char *material, Float_t dx, Float_t dy, Float_t dz, Float_t alpha, Float_t theta, Float_t phi) : TBRIK(name, title,material, dx, dy, dz) { // PARA shape normal constructor fAlpha = alpha; fTheta = theta; fPhi = phi; } //______________________________________________________________________________ TPARA::~TPARA() { // PARA shape default destructor } //______________________________________________________________________________ void TPARA::SetPoints(Double_t *buff) { // Create PARA points if (!buff) return; Float_t dx, dy, dz, theta, phi, alpha; const Float_t PI = Float_t (TMath::Pi()); alpha = fAlpha * PI/180.0; theta = fTheta * PI/180.0; phi = fPhi * PI/180.0; dx = TBRIK::fDx; dy = TBRIK::fDy; dz = TBRIK::fDz; // Parallelepiped change angles to tangents (by Pavel Nevski 12/04/99) Double_t TXY = TMath::Tan(alpha); Double_t TTH = TMath::Tan(theta); Double_t TXZ = TTH*TMath::Cos(phi); Double_t TYZ = TTH*TMath::Sin(phi); Double_t * rep = buff; *buff++ = -dz*TXZ-TXY*dy-dx ; *buff++ = -dy-dz*TYZ ; *buff++ = -dz; *buff++ = -dz*TXZ+TXY*dy-dx ; *buff++ = +dy-dz*TYZ ; *buff++ = -dz; //3 *buff++ = -dz*TXZ+TXY*dy+dx ; *buff++ = +dy-dz*TYZ ; *buff++ = -dz; *buff++ = -dz*TXZ-TXY*dy+dx ; *buff++ = -dy-dz*TYZ ; *buff++ = -dz;//1 *buff++ = +dz*TXZ-TXY*dy-dx ; *buff++ = -dy+dz*TYZ ; *buff++ = +dz; *buff++ = +dz*TXZ+TXY*dy-dx ; *buff++ = +dy+dz*TYZ ; *buff++ = +dz;//7 *buff++ = +dz*TXZ+TXY*dy+dx ; *buff++ = +dy+dz*TYZ ; *buff++ = +dz; *buff++ = +dz*TXZ-TXY*dy+dx ; *buff++ = -dy+dz*TYZ ; *buff++ = +dz;//5 } <commit_msg>remove unused variable "rep".<commit_after>// @(#)root/g3d:$Name: $:$Id: TPARA.cxx,v 1.3 2004/08/09 15:22:28 brun Exp $ // Author: Nenad Buncic 19/09/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TPARA.h" #include "TNode.h" ClassImp(TPARA) //______________________________________________________________________________ // Begin_Html <P ALIGN=CENTER> <IMG SRC="gif/para.gif"> </P> End_Html // PARA is a parallelepiped. It has 9 parameters: // // - name name of the shape // - title shape's title // - material (see TMaterial) // - dx half-length in x // - dy half-length in y // - dz half-length in z // - alpha angle formed by the y axis and by the plane joining the // centre of the faces parallel to the z-x plane at -DY and +DY // - theta polar angle of the line joining the centres of the faces // at -DZ and +DZ in z // - phi azimuthal angle of the line joining the centres of the // faces at -DZ and +DZ in z //______________________________________________________________________________ TPARA::TPARA() { // PARA shape default constructor } //______________________________________________________________________________ TPARA::TPARA(const char *name, const char *title, const char *material, Float_t dx, Float_t dy, Float_t dz, Float_t alpha, Float_t theta, Float_t phi) : TBRIK(name, title,material, dx, dy, dz) { // PARA shape normal constructor fAlpha = alpha; fTheta = theta; fPhi = phi; } //______________________________________________________________________________ TPARA::~TPARA() { // PARA shape default destructor } //______________________________________________________________________________ void TPARA::SetPoints(Double_t *buff) { // Create PARA points if (!buff) return; Float_t dx, dy, dz, theta, phi, alpha; const Float_t PI = Float_t (TMath::Pi()); alpha = fAlpha * PI/180.0; theta = fTheta * PI/180.0; phi = fPhi * PI/180.0; dx = TBRIK::fDx; dy = TBRIK::fDy; dz = TBRIK::fDz; // Parallelepiped change angles to tangents (by Pavel Nevski 12/04/99) Double_t TXY = TMath::Tan(alpha); Double_t TTH = TMath::Tan(theta); Double_t TXZ = TTH*TMath::Cos(phi); Double_t TYZ = TTH*TMath::Sin(phi); *buff++ = -dz*TXZ-TXY*dy-dx ; *buff++ = -dy-dz*TYZ ; *buff++ = -dz; *buff++ = -dz*TXZ+TXY*dy-dx ; *buff++ = +dy-dz*TYZ ; *buff++ = -dz; //3 *buff++ = -dz*TXZ+TXY*dy+dx ; *buff++ = +dy-dz*TYZ ; *buff++ = -dz; *buff++ = -dz*TXZ-TXY*dy+dx ; *buff++ = -dy-dz*TYZ ; *buff++ = -dz;//1 *buff++ = +dz*TXZ-TXY*dy-dx ; *buff++ = -dy+dz*TYZ ; *buff++ = +dz; *buff++ = +dz*TXZ+TXY*dy-dx ; *buff++ = +dy+dz*TYZ ; *buff++ = +dz;//7 *buff++ = +dz*TXZ+TXY*dy+dx ; *buff++ = +dy+dz*TYZ ; *buff++ = +dz; *buff++ = +dz*TXZ-TXY*dy+dx ; *buff++ = -dy+dz*TYZ ; *buff++ = +dz;//5 } <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Compiler engine class //============================================================================== #include "compilerengine.h" #include "compilermath.h" #include "corecliutils.h" //============================================================================== #include "llvmdisablewarnings.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Host.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvmenablewarnings.h" //============================================================================== #include <string> //============================================================================== namespace OpenCOR { namespace Compiler { //============================================================================== CompilerEngine::CompilerEngine() : mExecutionEngine(std::unique_ptr<llvm::ExecutionEngine>()), mError(QString()) { } //============================================================================== CompilerEngine::~CompilerEngine() { // Reset ourselves reset(); } //============================================================================== void CompilerEngine::reset(const bool &pResetError) { // Reset some internal objects delete mExecutionEngine.release(); mExecutionEngine = std::unique_ptr<llvm::ExecutionEngine>(); if (pResetError) mError = QString(); } //============================================================================== bool CompilerEngine::hasError() const { // Return whether an error occurred return mError.size(); } //============================================================================== QString CompilerEngine::error() const { // Return the compiler engine's error return mError; } //============================================================================== bool CompilerEngine::compileCode(const QString &pCode) { // Reset our compiler engine reset(); // Determine our target triple // Note: normally, we would call llvm::sys::getProcessTriple(), but this // returns the information about the system on which LLVM was built. // In most cases it is fine, but on OS X it may be a problem. Indeed, // with OS X 10.9, Apple decided to extend the C standard by adding // some functions (e.g. __exp10()). So, if the given code needs one of // those functions, then OpenCOR will crash if run on an 'old' version // of OS X. So, to avoid this issue, we set the target triple // ourselves, based on the system on which OpenCOR is being used... std::string targetTriple; #if defined(Q_OS_WIN) targetTriple = (sizeof(void *) == 4)?"i686-pc-windows-msvc-elf":"x86_64-pc-windows-msvc-elf"; // Note: MCJIT currently works only through the ELF object format, hence we // are appending "-elf"... #elif defined(Q_OS_LINUX) targetTriple = (sizeof(void *) == 4)?"i686-pc-linux-gnu":"x86_64-pc-linux-gnu"; #elif defined(Q_OS_MAC) targetTriple = "x86_64-apple-darwin"+std::to_string(QSysInfo::MacintoshVersion+2); #else #error Unsupported platform #endif // Get a driver to compile our code #ifdef QT_DEBUG llvm::raw_ostream &outputStream = llvm::outs(); #else llvm::raw_ostream &outputStream = llvm::nulls(); #endif llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnosticOptions = new clang::DiagnosticOptions(); clang::DiagnosticsEngine diagnosticsEngine(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()), &*diagnosticOptions, new clang::TextDiagnosticPrinter(outputStream, &*diagnosticOptions)); clang::driver::Driver driver("clang", targetTriple, diagnosticsEngine); driver.setCheckInputsExist(false); // Get a compilation object to which we pass some arguments llvm::StringRef dummyFileName("dummyFile.c"); llvm::SmallVector<const char *, 16> compilationArguments; compilationArguments.push_back("clang"); compilationArguments.push_back("-fsyntax-only"); compilationArguments.push_back("-O3"); compilationArguments.push_back("-ffast-math"); compilationArguments.push_back("-Werror"); compilationArguments.push_back(dummyFileName.data()); std::unique_ptr<clang::driver::Compilation> compilation(driver.BuildCompilation(compilationArguments)); if (!compilation) { mError = tr("the compilation object could not be created"); return false; } // The compilation object should have only one command, so if it doesn't // then something went wrong const clang::driver::JobList &jobList = compilation->getJobs(); if ( (jobList.size() != 1) || !llvm::isa<clang::driver::Command>(*jobList.begin())) { mError = tr("the compilation object must contain only one command"); return false; } // Retrieve the command job const clang::driver::Command &command = llvm::cast<clang::driver::Command>(*jobList.begin()); QString commandName = command.getCreator().getName(); if (commandName.compare("clang")) { mError = tr("a <strong>clang</strong> command was expected, but a <strong>%1</strong> command was found instead").arg(commandName); return false; } // Create a compiler invocation using our command's arguments const clang::driver::ArgStringList &commandArguments = command.getArguments(); std::unique_ptr<clang::CompilerInvocation> compilerInvocation(new clang::CompilerInvocation()); clang::CompilerInvocation::CreateFromArgs(*compilerInvocation, commandArguments.data(), commandArguments.data()+commandArguments.size(), diagnosticsEngine); // Map our dummy file to a memory buffer QByteArray codeByteArray = pCode.toUtf8(); compilerInvocation->getPreprocessorOpts().addRemappedFile(dummyFileName, llvm::MemoryBuffer::getMemBuffer(codeByteArray.constData()).release()); // Create a compiler instance to handle the actual work clang::CompilerInstance compilerInstance; compilerInstance.setInvocation(compilerInvocation.release()); // Create the compiler instance's diagnostics engine compilerInstance.createDiagnostics(); if (!compilerInstance.hasDiagnostics()) { mError = tr("the diagnostics engine could not be created"); return false; } // Create and execute the frontend to generate an LLVM bitcode module // Note: the LLVM team has been meaning to modify // CompilerInstance::ExecuteAction() so that we could specify the // output stream we want to use (rather than always use llvm::errs()), // but they have yet to actually do it, so we modified it ourselves... std::unique_ptr<clang::CodeGenAction> codeGenerationAction(new clang::EmitLLVMOnlyAction(&llvm::getGlobalContext())); if (!compilerInstance.ExecuteAction(*codeGenerationAction, outputStream)) { mError = tr("the code could not be compiled"); reset(false); return false; } // Retrieve the LLVM bitcode module std::unique_ptr<llvm::Module> module = codeGenerationAction->takeModule(); // Initialise the native target (and its ASM printer), so not only can we // then create an execution engine, but more importantly its data layout // will match that of our target platform llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); // Create and keep track of an execution engine mExecutionEngine = std::unique_ptr<llvm::ExecutionEngine>(llvm::EngineBuilder(std::move(module)).setEngineKind(llvm::EngineKind::JIT).create()); if (!mExecutionEngine) { mError = tr("the execution engine could not be created"); delete module.release(); return false; } return true; } //============================================================================== void * CompilerEngine::getFunction(const QString &pFunctionName) { // Return the address of the requested function if (mExecutionEngine) return (void *) mExecutionEngine->getFunctionAddress(qPrintable(pFunctionName)); else return 0; } //============================================================================== } // namespace Compiler } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Compiler engine class //============================================================================== #include "compilerengine.h" #include "compilermath.h" #include "corecliutils.h" //============================================================================== #include "llvmdisablewarnings.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/Host.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvmenablewarnings.h" //============================================================================== #include <string> //============================================================================== namespace OpenCOR { namespace Compiler { //============================================================================== CompilerEngine::CompilerEngine() : mExecutionEngine(std::unique_ptr<llvm::ExecutionEngine>()), mError(QString()) { } //============================================================================== CompilerEngine::~CompilerEngine() { // Reset ourselves reset(); } //============================================================================== void CompilerEngine::reset(const bool &pResetError) { // Reset some internal objects delete mExecutionEngine.release(); mExecutionEngine = std::unique_ptr<llvm::ExecutionEngine>(); if (pResetError) mError = QString(); } //============================================================================== bool CompilerEngine::hasError() const { // Return whether an error occurred return mError.size(); } //============================================================================== QString CompilerEngine::error() const { // Return the compiler engine's error return mError; } //============================================================================== bool CompilerEngine::compileCode(const QString &pCode) { // Reset our compiler engine reset(); // Determine our target triple // Note: normally, we would call llvm::sys::getProcessTriple(), but this // returns the information about the system on which LLVM was built. // In most cases it is fine, but on OS X it may be a problem. Indeed, // with OS X 10.9, Apple decided to extend the C standard by adding // some functions (e.g. __exp10()). So, if the given code needs one of // those functions, then OpenCOR will crash if run on an 'old' version // of OS X. So, to avoid this issue, we set the target triple // ourselves, based on the system on which OpenCOR is being used... std::string targetTriple; #if defined(Q_OS_WIN) targetTriple = (sizeof(void *) == 4)?"i686-pc-windows-msvc-elf":"x86_64-pc-windows-msvc-elf"; // Note: MCJIT currently works only through the ELF object format, hence we // are appending "-elf"... #elif defined(Q_OS_LINUX) targetTriple = (sizeof(void *) == 4)?"i686-pc-linux-gnu":"x86_64-pc-linux-gnu"; #elif defined(Q_OS_MAC) targetTriple = "x86_64-apple-darwin"+std::to_string(QSysInfo::MacintoshVersion+2); #else #error Unsupported platform #endif // Get a driver to compile our code llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnosticOptions = new clang::DiagnosticOptions(); clang::DiagnosticsEngine diagnosticsEngine(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()), &*diagnosticOptions); clang::driver::Driver driver("clang", targetTriple, diagnosticsEngine); driver.setCheckInputsExist(false); // Get a compilation object to which we pass some arguments llvm::StringRef dummyFileName("dummyFile.c"); llvm::SmallVector<const char *, 16> compilationArguments; compilationArguments.push_back("clang"); compilationArguments.push_back("-fsyntax-only"); compilationArguments.push_back("-O3"); compilationArguments.push_back("-ffast-math"); compilationArguments.push_back("-Werror"); compilationArguments.push_back(dummyFileName.data()); std::unique_ptr<clang::driver::Compilation> compilation(driver.BuildCompilation(compilationArguments)); if (!compilation) { mError = tr("the compilation object could not be created"); return false; } // The compilation object should have only one command, so if it doesn't // then something went wrong const clang::driver::JobList &jobList = compilation->getJobs(); if ( (jobList.size() != 1) || !llvm::isa<clang::driver::Command>(*jobList.begin())) { mError = tr("the compilation object must contain only one command"); return false; } // Retrieve the command job const clang::driver::Command &command = llvm::cast<clang::driver::Command>(*jobList.begin()); QString commandName = command.getCreator().getName(); if (commandName.compare("clang")) { mError = tr("a <strong>clang</strong> command was expected, but a <strong>%1</strong> command was found instead").arg(commandName); return false; } // Create a compiler invocation using our command's arguments const clang::driver::ArgStringList &commandArguments = command.getArguments(); std::unique_ptr<clang::CompilerInvocation> compilerInvocation(new clang::CompilerInvocation()); clang::CompilerInvocation::CreateFromArgs(*compilerInvocation, commandArguments.data(), commandArguments.data()+commandArguments.size(), diagnosticsEngine); // Map our dummy file to a memory buffer QByteArray codeByteArray = pCode.toUtf8(); compilerInvocation->getPreprocessorOpts().addRemappedFile(dummyFileName, llvm::MemoryBuffer::getMemBuffer(codeByteArray.constData()).release()); // Create a compiler instance to handle the actual work clang::CompilerInstance compilerInstance; compilerInstance.setInvocation(compilerInvocation.release()); // Create the compiler instance's diagnostics engine compilerInstance.createDiagnostics(); if (!compilerInstance.hasDiagnostics()) { mError = tr("the diagnostics engine could not be created"); return false; } // Create and execute the frontend to generate an LLVM bitcode module // Note: the LLVM team has been meaning to modify // CompilerInstance::ExecuteAction() so that we could specify the // output stream we want to use (rather than always use llvm::errs()), // but they have yet to actually do it, so we modified it ourselves... std::unique_ptr<clang::CodeGenAction> codeGenerationAction(new clang::EmitLLVMOnlyAction(&llvm::getGlobalContext())); if (!compilerInstance.ExecuteAction(*codeGenerationAction, llvm::outs())) { mError = tr("the code could not be compiled"); reset(false); return false; } // Retrieve the LLVM bitcode module std::unique_ptr<llvm::Module> module = codeGenerationAction->takeModule(); // Initialise the native target (and its ASM printer), so not only can we // then create an execution engine, but more importantly its data layout // will match that of our target platform llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); // Create and keep track of an execution engine mExecutionEngine = std::unique_ptr<llvm::ExecutionEngine>(llvm::EngineBuilder(std::move(module)).setEngineKind(llvm::EngineKind::JIT).create()); if (!mExecutionEngine) { mError = tr("the execution engine could not be created"); delete module.release(); return false; } return true; } //============================================================================== void * CompilerEngine::getFunction(const QString &pFunctionName) { // Return the address of the requested function if (mExecutionEngine) return (void *) mExecutionEngine->getFunctionAddress(qPrintable(pFunctionName)); else return 0; } //============================================================================== } // namespace Compiler } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include "common/RhoPort.h" extern "C" void Init_System(); extern "C" void Init_Network(); extern "C" void Init_SQLite3(); extern "C" void Init_Log(); extern "C" void Init_WebView(); extern "C" void Init_WebView_extension(); extern "C" void Init_Application(); extern "C" void Init_NativeToolbar(); extern "C" void Init_NativeToolbar_extension(); extern "C" void Init_NativeTabbar(); extern "C" void Init_NativeTabbar_extension(); extern "C" void Init_Navbar(); extern "C" void Init_Notification(); extern "C" void Init_RhoFile(); extern "C" void Init_NativeMenuBar(); extern "C" void Init_Led(); extern "C" void Init_Push(); extern "C" void Init_NewORM_extension(); extern "C" void Init_Intent(); extern "C" void Init_CoreAPI_Extension() { Init_System(); Init_Application(); Init_Network(); Init_SQLite3(); //#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(OS_WINCE) Init_NewORM_extension(); //#endif Init_Log(); #if defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(OS_ANDROID) Init_WebView(); #elif defined(OS_WP8) Init_WebView_extension(); #endif #if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || (defined(OS_MACOSX) && defined(RHODES_EMULATOR)) || defined(OS_ANDROID) || defined(OS_MACOSX) Init_NativeToolbar(); Init_NativeTabbar(); #elif defined(OS_WP8) Init_NativeToolbar_extension(); Init_NativeTabbar_extension(); #endif #if defined(OS_MACOSX) || defined(RHODES_EMULATOR) Init_Navbar(); #endif #if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_ANDROID) Init_Notification(); #endif #if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(WINDOWS_PLATFORM) Init_RhoFile(); #endif #if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(RHODES_EMULATOR) Init_NativeMenuBar(); #endif #if defined(OS_WINCE) || defined(OS_ANDROID) //Init_Led(); #endif #if defined(OS_ANDROID) || defined(OS_WINCE) || defined(OS_MACOSX) || (defined(OS_WINDOWS_DESKTOP) && !defined(RHODES_EMULATOR)) Init_Push(); #endif #if defined(OS_ANDROID) || (defined(OS_MACOSX) && !defined(RHODES_EMULATOR)) || defined(OS_WINCE) Init_Intent(); #endif } <commit_msg>fix config api<commit_after>#include "common/RhoPort.h" extern "C" void Init_System(); extern "C" void Init_Network(); extern "C" void Init_SQLite3(); extern "C" void Init_Log(); extern "C" void Init_WebView(); extern "C" void Init_WebView_extension(); extern "C" void Init_Application(); extern "C" void Init_NativeToolbar(); extern "C" void Init_NativeToolbar_extension(); extern "C" void Init_NativeTabbar(); extern "C" void Init_NativeTabbar_extension(); extern "C" void Init_Navbar(); extern "C" void Init_Notification(); extern "C" void Init_RhoFile(); extern "C" void Init_NativeMenuBar(); extern "C" void Init_Led(); extern "C" void Init_Push(); extern "C" void Init_NewORM_extension(); extern "C" void Init_Intent(); extern "C" void Init_Config_extension(); extern "C" void Init_CoreAPI_Extension() { Init_System(); Init_Application(); Init_Network(); Init_SQLite3(); //#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(OS_WINCE) Init_NewORM_extension(); //#endif Init_Log(); #if defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(OS_ANDROID) Init_WebView(); #elif defined(OS_WP8) Init_WebView_extension(); #endif #if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || (defined(OS_MACOSX) && defined(RHODES_EMULATOR)) || defined(OS_ANDROID) || defined(OS_MACOSX) Init_NativeToolbar(); Init_NativeTabbar(); #elif defined(OS_WP8) Init_NativeToolbar_extension(); Init_NativeTabbar_extension(); #endif #if defined(OS_MACOSX) || defined(RHODES_EMULATOR) Init_Navbar(); #endif #if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_ANDROID) Init_Notification(); #endif #if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(WINDOWS_PLATFORM) Init_RhoFile(); #endif #if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(RHODES_EMULATOR) Init_NativeMenuBar(); #endif #if defined(OS_WINCE) || defined(OS_ANDROID) //Init_Led(); #endif #if defined(OS_ANDROID) || defined(OS_WINCE) || defined(OS_MACOSX) || (defined(OS_WINDOWS_DESKTOP) && !defined(RHODES_EMULATOR)) Init_Push(); #endif #if defined(OS_ANDROID) || (defined(OS_MACOSX) && !defined(RHODES_EMULATOR)) || defined(OS_WINCE) Init_Intent(); #endif #if defined(OS_WP8) Init_Config_extension(); #endif } <|endoftext|>
<commit_before>#include <fstream> #include <dirent.h> #include <errno.h> #include "pixelboost/data/json/reader.h" #include "pixelboost/file/fileHelpers.h" #include "pixelboost/network/networkMessage.h" #include "pixelboost/network/networkServer.h" #include "project/project.h" #include "project/record.h" #include "project/schema.h" #include "core.h" using namespace pixeleditor; bool GetDirectoryListing(const std::string& directory, std::vector<std::string>& files) { DIR* dir; dirent* entry; dir = opendir(directory.c_str()); if (!dir) // TODO: Log to error, use errno for error number return false; while ((entry = readdir(dir))) { if (entry->d_type == DT_REG) files.push_back(std::string(entry->d_name)); } closedir(dir); return true; } Project::Project() : _IsOpen(false) , _Location("") , _Schema(0) { _Name = "Project"; _Schema = new Schema(); } Project::~Project() { Close(); } bool Project::Open(const std::string& directory) { if (_IsOpen) Close(); pb::FileSystem::Instance()->OverrideWriteDirectory(directory); pb::FileSystem::Instance()->MountReadLocation(directory, "editor_project", true); _Location = directory; if (_Location.length() == 0) return false; if (_Location[_Location.length()-1] != '/') _Location += "/"; OpenConfig("editor_project/project.prj"); if (!_Schema->Open(_Config.commonSchema, "editor_project/schema/main.txt")) return false; _IsOpen = true; projectOpened(this); std::vector<std::string> files; GetDirectoryListing(_Location + "records/", files); for (std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it) { if (it->length() > 0 && it->at(0) == '.') continue; if (it->length() < 4 || it->substr(it->length()-4, 4) != ".txt") continue; LoadRecord("editor_project/records/" + *it); } return true; } bool Project::OpenConfig(const std::string& filename) { pb::File* file = pb::FileSystem::Instance()->OpenFile(filename); std::string contents; if (file) { file->ReadAll(contents); delete file; } json::Object config; json::Reader::Read(config, contents); json::String& projectRoot = config["project_root"]; _Config.projectRoot = projectRoot; json::String& commonSchema = config["common_schema"]; _Config.commonSchema = commonSchema; // Image roots json::Array& imageRoots = config["image_roots"]; for (json::Array::iterator it = imageRoots.Begin(); it != imageRoots.End(); ++it) { json::String imageRoot = *it; _Config.imageRoots.push_back(_Location + imageRoot.Value()); } // Model roots json::Array& modelRoots = config["model_roots"]; for (json::Array::iterator it = modelRoots.Begin(); it != modelRoots.End(); ++it) { json::String modelRoot = *it; _Config.modelRoots.push_back(_Location + modelRoot.Value()); } // Export directory json::String& exportDir = config["export_dir"]; _Config.exportDir = _Location + exportDir.Value(); // Pixel unit (How many pixels in 1m) json::Number& pixelUnit = config["pixel_unit"]; _Config.pixelUnit = pixelUnit.Value(); json::Object& assets = config["assets"]; _Config.assets = assets; for (auto it = _Config.imageRoots.begin(); it != _Config.imageRoots.end(); ++it) { pb::FileSystem::Instance()->MountReadLocation(_Location + *it, "editor_images", true); } for (auto it = _Config.modelRoots.begin(); it != _Config.modelRoots.end(); ++it) { pb::FileSystem::Instance()->MountReadLocation(_Location + *it, "editor_models", true); } pb::FileSystem::Instance()->MountReadLocation(_Location + _Config.projectRoot, "/", true); return true; } bool Project::Close() { if (!_IsOpen) return false; _Location = ""; for (RecordMap::iterator it = _Records.begin(); it != _Records.end(); ++it) { it->second->Close(); recordRemoved(this, it->second); delete it->second; } _Records.clear(); _Schema->Close(); _Uids.clear(); _IsOpen = false; projectClosed(this); return true; } bool Project::Save() { for (RecordMap::iterator it = _Records.begin(); it != _Records.end(); ++it) it->second->Save(); projectSaved(this); return true; } bool Project::Export(bool networkExport) { // TODO: Make OS independant char cmd[2048]; std::string outputDir = GetConfig().exportDir; sprintf(cmd, "mkdir -p %s", outputDir.c_str()); system(cmd); std::string location = outputDir + "main.lua"; std::fstream file(location.c_str(), std::fstream::out | std::fstream::trunc); file << "records = {" << std::endl; for (RecordMap::iterator it = _Records.begin(); it != _Records.end();) { it->second->ExportLua(); char recordString[32]; sprintf(recordString, "{ name = \"%s\", type = %u, uid = %u }", it->second->GetName().c_str(), it->second->GetTypeHash(), it->second->GetUid()); file << recordString; ++it; if (it != _Records.end()) file << ","; file << std::endl; } file << "}" << std::endl; file.close(); projectExported(this); if (networkExport) { if (!Core::Instance()->GetNetworkManager()->GetClientConnection().IsOpen()) return false; pb::File* file; pb::NetworkMessage message; message.SetProtocol('DBDG'); message.WriteString("main.lua"); file = pb::FileSystem::Instance()->OpenFile(outputDir+"main.lua"); std::string main; if (file) { file->ReadAll(main); delete file; file = 0; } message.WriteString(main.c_str()); Core::Instance()->GetNetworkManager()->GetClientConnection().Send(message); for (RecordMap::iterator it = _Records.begin(); it != _Records.end(); ++it) { char recordName[1024]; sprintf(recordName, "records/%X.lua", it->second->GetUid()); pb::NetworkMessage message; message.SetProtocol('DBDG'); message.WriteString(recordName); file = pb::FileSystem::Instance()->OpenFile(outputDir+recordName); std::string main; if (file) { file->ReadAll(main); delete file; file = 0; } message.WriteString(main.c_str()); Core::Instance()->GetNetworkManager()->GetClientConnection().Send(message); } } return true; } bool Project::IsOpen() { return _IsOpen; } const std::string& Project::GetName() const { return _Name; } ProjectEntity* Project::GetEntity(Uid uid) const { for (RecordMap::const_iterator it = _Records.begin(); it != _Records.end(); ++it) { ProjectEntity* entity = it->second->GetEntity(uid); if (entity) return entity; } return 0; } ProjectRecord* Project::GetRecord(Uid uid) const { RecordMap::const_iterator it = _Records.find(uid); if (it != _Records.end()) return it->second; return 0; } ProjectRecord* Project::GetRecordByName(const std::string& recordName) const { for (RecordMap::const_iterator it = _Records.begin(); it != _Records.end(); ++it) { if (recordName == it->second->GetName()) return it->second; } return 0; } Uid Project::CalculateUid(Uid min, Uid max) { for (int i=0; i<128; i++) { unsigned long id = (rand() % max-min)+min; UidSet::iterator it = _Uids.find(id); if (id > min && id < max && it == _Uids.end()) { _Uids.insert(id); return id; } } // TODO : Assert here! return 0; } bool Project::RegisterUid(Uid uid) { if (_Uids.find(uid) != _Uids.end()) return false; _Uids.insert(uid); return true; } bool Project::ReleaseUid(Uid uid) { UidSet::iterator it = _Uids.find(uid); if (it == _Uids.end()) return false; _Uids.erase(it); return true; } const Project::ProjectConfig& Project::GetConfig() const { return _Config; } const Project::RecordMap& Project::GetRecords() const { return _Records; } bool Project::AddRecord(const std::string& name, const std::string& type) { if (GetRecordByName(name)) return false; const SchemaRecord* schemaRecord = GetSchema()->GetRecordByName(type); ProjectRecord* record = new ProjectRecord(this, schemaRecord, name); _Records[record->GetUid()] = record; recordAdded(this, record); return true; } bool Project::LoadRecord(const std::string& filename) { ProjectRecord* record = new ProjectRecord(this); record->Open(filename); std::string name = record->GetName(); ProjectRecord* existing = GetRecordByName(name); if (existing) { delete record; return false; } _Records[record->GetUid()] = record; recordAdded(this, record); return true; } bool Project::RemoveRecord(std::string const &name, bool erase) { ProjectRecord* record = GetRecordByName(name); if (!record) return false; RecordMap::iterator it = _Records.find(record->GetUid()); _Records.erase(it); recordRemoved(this, record); if (erase) delete record; return true; } Schema* Project::GetSchema() { return _Schema; } <commit_msg>Fix buffer overrun<commit_after>#include <fstream> #include <dirent.h> #include <errno.h> #include "pixelboost/data/json/reader.h" #include "pixelboost/file/fileHelpers.h" #include "pixelboost/network/networkMessage.h" #include "pixelboost/network/networkServer.h" #include "project/project.h" #include "project/record.h" #include "project/schema.h" #include "core.h" using namespace pixeleditor; bool GetDirectoryListing(const std::string& directory, std::vector<std::string>& files) { DIR* dir; dirent* entry; dir = opendir(directory.c_str()); if (!dir) // TODO: Log to error, use errno for error number return false; while ((entry = readdir(dir))) { if (entry->d_type == DT_REG) files.push_back(std::string(entry->d_name)); } closedir(dir); return true; } Project::Project() : _IsOpen(false) , _Location("") , _Schema(0) { _Name = "Project"; _Schema = new Schema(); } Project::~Project() { Close(); } bool Project::Open(const std::string& directory) { if (_IsOpen) Close(); pb::FileSystem::Instance()->OverrideWriteDirectory(directory); pb::FileSystem::Instance()->MountReadLocation(directory, "editor_project", true); _Location = directory; if (_Location.length() == 0) return false; if (_Location[_Location.length()-1] != '/') _Location += "/"; OpenConfig("editor_project/project.prj"); if (!_Schema->Open(_Config.commonSchema, "editor_project/schema/main.txt")) return false; _IsOpen = true; projectOpened(this); std::vector<std::string> files; GetDirectoryListing(_Location + "records/", files); for (std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it) { if (it->length() > 0 && it->at(0) == '.') continue; if (it->length() < 4 || it->substr(it->length()-4, 4) != ".txt") continue; LoadRecord("editor_project/records/" + *it); } return true; } bool Project::OpenConfig(const std::string& filename) { pb::File* file = pb::FileSystem::Instance()->OpenFile(filename); std::string contents; if (file) { file->ReadAll(contents); delete file; } json::Object config; json::Reader::Read(config, contents); json::String& projectRoot = config["project_root"]; _Config.projectRoot = projectRoot; json::String& commonSchema = config["common_schema"]; _Config.commonSchema = commonSchema; // Image roots json::Array& imageRoots = config["image_roots"]; for (json::Array::iterator it = imageRoots.Begin(); it != imageRoots.End(); ++it) { json::String imageRoot = *it; _Config.imageRoots.push_back(_Location + imageRoot.Value()); } // Model roots json::Array& modelRoots = config["model_roots"]; for (json::Array::iterator it = modelRoots.Begin(); it != modelRoots.End(); ++it) { json::String modelRoot = *it; _Config.modelRoots.push_back(_Location + modelRoot.Value()); } // Export directory json::String& exportDir = config["export_dir"]; _Config.exportDir = _Location + exportDir.Value(); // Pixel unit (How many pixels in 1m) json::Number& pixelUnit = config["pixel_unit"]; _Config.pixelUnit = pixelUnit.Value(); json::Object& assets = config["assets"]; _Config.assets = assets; for (auto it = _Config.imageRoots.begin(); it != _Config.imageRoots.end(); ++it) { pb::FileSystem::Instance()->MountReadLocation(_Location + *it, "editor_images", true); } for (auto it = _Config.modelRoots.begin(); it != _Config.modelRoots.end(); ++it) { pb::FileSystem::Instance()->MountReadLocation(_Location + *it, "editor_models", true); } pb::FileSystem::Instance()->MountReadLocation(_Location + _Config.projectRoot, "/", true); return true; } bool Project::Close() { if (!_IsOpen) return false; _Location = ""; for (RecordMap::iterator it = _Records.begin(); it != _Records.end(); ++it) { it->second->Close(); recordRemoved(this, it->second); delete it->second; } _Records.clear(); _Schema->Close(); _Uids.clear(); _IsOpen = false; projectClosed(this); return true; } bool Project::Save() { for (RecordMap::iterator it = _Records.begin(); it != _Records.end(); ++it) it->second->Save(); projectSaved(this); return true; } bool Project::Export(bool networkExport) { // TODO: Make OS independant char cmd[2048]; std::string outputDir = GetConfig().exportDir; sprintf(cmd, "mkdir -p %s", outputDir.c_str()); system(cmd); std::string location = outputDir + "main.lua"; std::fstream file(location.c_str(), std::fstream::out | std::fstream::trunc); file << "records = {" << std::endl; for (RecordMap::iterator it = _Records.begin(); it != _Records.end();) { it->second->ExportLua(); char recordString[1024]; snprintf(recordString, 1024, "{ name = \"%s\", type = %u, uid = %u }", it->second->GetName().c_str(), it->second->GetTypeHash(), it->second->GetUid()); file << recordString; ++it; if (it != _Records.end()) file << ","; file << std::endl; } file << "}" << std::endl; file.close(); projectExported(this); if (networkExport) { if (!Core::Instance()->GetNetworkManager()->GetClientConnection().IsOpen()) return false; pb::File* file; pb::NetworkMessage message; message.SetProtocol('DBDG'); message.WriteString("main.lua"); file = pb::FileSystem::Instance()->OpenFile(outputDir+"main.lua"); std::string main; if (file) { file->ReadAll(main); delete file; file = 0; } message.WriteString(main.c_str()); Core::Instance()->GetNetworkManager()->GetClientConnection().Send(message); for (RecordMap::iterator it = _Records.begin(); it != _Records.end(); ++it) { char recordName[1024]; sprintf(recordName, "records/%X.lua", it->second->GetUid()); pb::NetworkMessage message; message.SetProtocol('DBDG'); message.WriteString(recordName); file = pb::FileSystem::Instance()->OpenFile(outputDir+recordName); std::string main; if (file) { file->ReadAll(main); delete file; file = 0; } message.WriteString(main.c_str()); Core::Instance()->GetNetworkManager()->GetClientConnection().Send(message); } } return true; } bool Project::IsOpen() { return _IsOpen; } const std::string& Project::GetName() const { return _Name; } ProjectEntity* Project::GetEntity(Uid uid) const { for (RecordMap::const_iterator it = _Records.begin(); it != _Records.end(); ++it) { ProjectEntity* entity = it->second->GetEntity(uid); if (entity) return entity; } return 0; } ProjectRecord* Project::GetRecord(Uid uid) const { RecordMap::const_iterator it = _Records.find(uid); if (it != _Records.end()) return it->second; return 0; } ProjectRecord* Project::GetRecordByName(const std::string& recordName) const { for (RecordMap::const_iterator it = _Records.begin(); it != _Records.end(); ++it) { if (recordName == it->second->GetName()) return it->second; } return 0; } Uid Project::CalculateUid(Uid min, Uid max) { for (int i=0; i<128; i++) { unsigned long id = (rand() % max-min)+min; UidSet::iterator it = _Uids.find(id); if (id > min && id < max && it == _Uids.end()) { _Uids.insert(id); return id; } } // TODO : Assert here! return 0; } bool Project::RegisterUid(Uid uid) { if (_Uids.find(uid) != _Uids.end()) return false; _Uids.insert(uid); return true; } bool Project::ReleaseUid(Uid uid) { UidSet::iterator it = _Uids.find(uid); if (it == _Uids.end()) return false; _Uids.erase(it); return true; } const Project::ProjectConfig& Project::GetConfig() const { return _Config; } const Project::RecordMap& Project::GetRecords() const { return _Records; } bool Project::AddRecord(const std::string& name, const std::string& type) { if (GetRecordByName(name)) return false; const SchemaRecord* schemaRecord = GetSchema()->GetRecordByName(type); ProjectRecord* record = new ProjectRecord(this, schemaRecord, name); _Records[record->GetUid()] = record; recordAdded(this, record); return true; } bool Project::LoadRecord(const std::string& filename) { ProjectRecord* record = new ProjectRecord(this); record->Open(filename); std::string name = record->GetName(); ProjectRecord* existing = GetRecordByName(name); if (existing) { delete record; return false; } _Records[record->GetUid()] = record; recordAdded(this, record); return true; } bool Project::RemoveRecord(std::string const &name, bool erase) { ProjectRecord* record = GetRecordByName(name); if (!record) return false; RecordMap::iterator it = _Records.find(record->GetUid()); _Records.erase(it); recordRemoved(this, record); if (erase) delete record; return true; } Schema* Project::GetSchema() { return _Schema; } <|endoftext|>
<commit_before>#ifndef K3_RUNTIME_BASESTRING_H #define K3_RUNTIME_BASESTRING_H #include <cstring> #include <memory> #include <vector> #include "yaml-cpp/yaml.h" #include "rapidjson/document.h" #include "boost/serialization/array.hpp" #include "boost/functional/hash.hpp" #include "Common.hpp" #include "dataspace/Dataspace.hpp" char* dupstr(const char*) throw (); namespace K3 { class base_string { public: // Constructors/Destructors/Assignment. base_string(): buffer(nullptr) {} base_string(const base_string& other): buffer(dupstr(other.buffer)) {} base_string(base_string&& other): base_string() { swap(*this, other); } base_string(const char* b): buffer(dupstr(b)) {} base_string(const std::string& s) : buffer(dupstr(s.c_str())) {} base_string(const char* from, std::size_t count): base_string() { if (from && count) { buffer = new char[count + 1]; strncpy(buffer, from, count); buffer[count] = 0; } } ~base_string() { if (buffer) { delete [] buffer; } buffer = 0; } base_string operator +(const base_string& other) const { return base_string(std::string(buffer) + std::string(other.buffer)); } base_string operator +(base_string&& other) { return base_string(std::string(buffer) + std::string(other.buffer)); } base_string& operator =(const base_string& other) { base_string temp(other); swap(*this, temp); return *this; } base_string& operator =(base_string&& other) { swap(*this, other); return *this; } friend void swap(base_string& first, base_string& second) { using std::swap; swap(first.buffer, second.buffer); } // Conversions operator std::string() const { return std::string(buffer ? buffer : ""); } // Accessors std::size_t length() const { if (buffer) { return strlen(buffer); } return 0; } const char* c_str() const { return buffer; } // Comparisons bool operator ==(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") == 0; } bool operator !=(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") != 0; } bool operator <=(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") <= 0; } bool operator <(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") < 0; } bool operator >=(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") >= 0; } bool operator >(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") > 0; } // Operations base_string substr(std::size_t from, std::size_t to) const { if (!buffer) { return base_string(); } auto n = length(); if (from > n) { from = n; } if (to > n) { to = n; } return base_string(buffer + from, to - from); } // Modifies this string. Seq<R_elem<string_impl>> splitString(const string_impl& splitter) { Seq<R_elem<string_impl>> results; if (!buffer) { return results; } R_elem<string_impl> rec; char * pch; pch = strtok (buffer, splitter.c_str()); while (pch != NULL) { rec.elem = string_impl(pch); results.insert(rec); pch = strtok (NULL, splitter.c_str()); } return results; } // Stream Operators friend std::ostream& operator <<(std::ostream& out, const K3::base_string& s) { if (s.buffer) { return out << s.c_str(); } return out; } char* begin() const { return buffer; } char* end() const { return buffer + length(); } template <class archive> void serialize(archive& a, const unsigned int) { std::size_t len; if (archive::is_saving::value) { len = length(); } a & len; if (archive::is_loading::value) { // Possibly extraneous: // Buffer might always be null when loading // since this base_str was just constructed if(buffer) { delete [] buffer; buffer = 0; } if (len) { buffer = new char[len + 1]; buffer[len] = 0; } else { buffer = 0; } } if (buffer) { a & boost::serialization::make_array(buffer, len); } } private: char* buffer; }; } // namespace K3 namespace JSON { template <> struct convert<K3::base_string> { template <class Allocator> static rapidjson::Value encode(const K3::base_string& from, Allocator& al) { Value v; if (from.c_str()) { v.SetString(from.c_str(), al); } else { v.SetString("", al); } return v; } }; } namespace YAML { template <> struct convert<K3::base_string> { static Node encode(const K3::base_string& s) { Node node; node = std::string(s.c_str()); return node; } static bool decode(const Node& node, K3::base_string& s) { try { auto t = node.as<std::string>(); s = K3::base_string(t); return true; } catch (YAML::TypedBadConversion<std::string> e) { return false; } } }; } #endif <commit_msg>Add out-of-line +operator for base_strings.<commit_after>#ifndef K3_RUNTIME_BASESTRING_H #define K3_RUNTIME_BASESTRING_H #include <cstring> #include <memory> #include <vector> #include "yaml-cpp/yaml.h" #include "rapidjson/document.h" #include "boost/serialization/array.hpp" #include "boost/functional/hash.hpp" #include "Common.hpp" #include "dataspace/Dataspace.hpp" char* dupstr(const char*) throw (); namespace K3 { class base_string { public: // Constructors/Destructors/Assignment. base_string(): buffer(nullptr) {} base_string(const base_string& other): buffer(dupstr(other.buffer)) {} base_string(base_string&& other): base_string() { swap(*this, other); } base_string(const char* b): buffer(dupstr(b)) {} base_string(const std::string& s) : buffer(dupstr(s.c_str())) {} base_string(const char* from, std::size_t count): base_string() { if (from && count) { buffer = new char[count + 1]; strncpy(buffer, from, count); buffer[count] = 0; } } ~base_string() { if (buffer) { delete [] buffer; } buffer = 0; } base_string& operator += (const base_string& other) { auto new_string = std::string(buffer) + std::string(other.buffer); buffer = dupstr(new_string.c_str()); return *this; } base_string& operator += (const char* other) { return *this += base_string(other); } base_string& operator =(const base_string& other) { base_string temp(other); swap(*this, temp); return *this; } base_string& operator =(base_string&& other) { swap(*this, other); return *this; } friend void swap(base_string& first, base_string& second) { using std::swap; swap(first.buffer, second.buffer); } // Conversions operator std::string() const { return std::string(buffer ? buffer : ""); } // Accessors std::size_t length() const { if (buffer) { return strlen(buffer); } return 0; } const char* c_str() const { return buffer; } // Comparisons bool operator ==(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") == 0; } bool operator !=(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") != 0; } bool operator <=(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") <= 0; } bool operator <(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") < 0; } bool operator >=(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") >= 0; } bool operator >(const base_string& other) const { return strcmp(buffer ? buffer : "", other.buffer ? other.buffer : "") > 0; } // Operations base_string substr(std::size_t from, std::size_t to) const { if (!buffer) { return base_string(); } auto n = length(); if (from > n) { from = n; } if (to > n) { to = n; } return base_string(buffer + from, to - from); } // Modifies this string. Seq<R_elem<string_impl>> splitString(const string_impl& splitter) { Seq<R_elem<string_impl>> results; if (!buffer) { return results; } R_elem<string_impl> rec; char * pch; pch = strtok (buffer, splitter.c_str()); while (pch != NULL) { rec.elem = string_impl(pch); results.insert(rec); pch = strtok (NULL, splitter.c_str()); } return results; } // Stream Operators friend std::ostream& operator <<(std::ostream& out, const K3::base_string& s) { if (s.buffer) { return out << s.c_str(); } return out; } char* begin() const { return buffer; } char* end() const { return buffer + length(); } template <class archive> void serialize(archive& a, const unsigned int) { std::size_t len; if (archive::is_saving::value) { len = length(); } a & len; if (archive::is_loading::value) { // Possibly extraneous: // Buffer might always be null when loading // since this base_str was just constructed if(buffer) { delete [] buffer; buffer = 0; } if (len) { buffer = new char[len + 1]; buffer[len] = 0; } else { buffer = 0; } } if (buffer) { a & boost::serialization::make_array(buffer, len); } } private: char* buffer; }; inline base_string operator + (base_string s, char const* t) { return s += t; } inline base_string operator + (char const* t, base_string s) { auto new_string = base_string(t); return new_string += s; } } // namespace K3 namespace JSON { template <> struct convert<K3::base_string> { template <class Allocator> static rapidjson::Value encode(const K3::base_string& from, Allocator& al) { Value v; if (from.c_str()) { v.SetString(from.c_str(), al); } else { v.SetString("", al); } return v; } }; } namespace YAML { template <> struct convert<K3::base_string> { static Node encode(const K3::base_string& s) { Node node; node = std::string(s.c_str()); return node; } static bool decode(const Node& node, K3::base_string& s) { try { auto t = node.as<std::string>(); s = K3::base_string(t); return true; } catch (YAML::TypedBadConversion<std::string> e) { return false; } } }; } #endif <|endoftext|>
<commit_before>#include "System.h" System::System() { this->m_inputHandler = NULL; this->m_window = NULL; } System::~System() { } int System::Shutdown() { int result = 0; //Destroy the display window SDL_DestroyWindow(m_window); //Quit SDL subsystems SDL_Quit(); this->m_graphicsHandler->Shutdown(); delete this->m_graphicsHandler; delete this->m_camera; this->m_inputHandler->Shutdown(); delete this->m_inputHandler; return result; } int System::Initialize() { int result = 1; this->m_fullscreen = false; this->m_running = true; this->m_window = NULL; //Get the instance if this application this->m_hinstance = GetModuleHandle(NULL); if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError()); } else { printf("SDL succeeded in initializing the window!\n"); } m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (m_window == NULL) { printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError()); } else { printf("Window creation succeeded!\n"); SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(m_window, &wmInfo); m_hwnd = wmInfo.info.win.window; } this->m_graphicsHandler = new GraphicsHandler(); if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT))) { printf("GraphicsHandler did not work. RIP!\n"); } this->m_camera = new Camera(); this->m_camera->Initialize(); Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera); delete oldCam; oldCam = nullptr; //Initialize the PhysicsHandler //this->m_physicsHandler.Initialize(); //Initialize the InputHandler this->m_inputHandler = new InputHandler(); this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT); return result; } //Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method int System::Run() { int result = 0; LARGE_INTEGER frequency, currTime, prevTime, elapsedTime; QueryPerformanceFrequency(&frequency); //QueryPerformanceCounter(&prevTime); QueryPerformanceCounter(&currTime); while (this->m_running) { prevTime = currTime; QueryPerformanceCounter(&currTime); elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= frequency.QuadPart; this->m_physicsHandler.Update(); //Prepare the InputHandler this->m_inputHandler->Update(); //Handle events and update inputhandler through said events result = this->HandleEvents(); SDL_PumpEvents(); //Update game if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE)) { this->m_running = false; } if (!this->Update((float)elapsedTime.QuadPart)) { this->m_running = false; } if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F)) { this->FullscreenToggle(); } //std::cout << int(totalTime) << "\n"; //Render this->m_graphicsHandler->Render(); } if (this->m_fullscreen) this->FullscreenToggle(); return result; } int System::Update(float deltaTime) { int result = 1; int translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0; int rotateCameraY = 0; if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W)) { translateCameraZ++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S)) { translateCameraZ--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_SPACE)) { translateCameraY++; if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT)) { translateCameraY *= -1; } } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D)) { translateCameraX++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A)) { translateCameraX--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E)) { rotateCameraY++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q)) { rotateCameraY--; } if (translateCameraY || translateCameraX || translateCameraZ || rotateCameraY) { DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), float(translateCameraZ) * (deltaTime / 1000000.0f)); this->m_camera->AddToCameraPos(posTranslation); this->m_camera->AddToLookAt(posTranslation); float rotationAmount = DirectX::XM_PI / 8; rotationAmount *= deltaTime / 1000000.0f; DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f)); this->m_camera->SetRotation(newRotation); this->m_camera->Update(); } // return result; } int System::HandleEvents() { SDL_Event m_event; while (SDL_PollEvent(&m_event)) { switch (m_event.type) { #pragma region case SDL_WINDOWEVENT: { switch (m_event.window.event) { case SDL_WINDOWEVENT_ENTER: { //OnMouseFocus(); break; } case SDL_WINDOWEVENT_LEAVE: { //OnMouseBlur(); break; } case SDL_WINDOWEVENT_FOCUS_GAINED: { //OnInputFocus(); break; } case SDL_WINDOWEVENT_FOCUS_LOST: { //OnInputBlur(); break; } case SDL_WINDOWEVENT_SHOWN: { break; } case SDL_WINDOWEVENT_HIDDEN: { break; } case SDL_WINDOWEVENT_EXPOSED: { break; } case SDL_WINDOWEVENT_MOVED: { break; } case SDL_WINDOWEVENT_RESIZED: { break; } case SDL_WINDOWEVENT_SIZE_CHANGED: { break; } case SDL_WINDOWEVENT_MINIMIZED: { break; } case SDL_WINDOWEVENT_MAXIMIZED: { break; } case SDL_WINDOWEVENT_RESTORED: { break; } case SDL_WINDOWEVENT_CLOSE: { break; } } break; } #pragma endregion window events case SDL_MOUSEMOTION: { break; } case SDL_QUIT: { //The big X in the corner this->m_running = false; break; } #pragma region case SDL_KEYDOWN: { //OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true); break; } case SDL_KEYUP: { //OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false); break; } case SDL_MOUSEBUTTONDOWN: { this->m_inputHandler->SetMouseState(m_event.button.button, true); break; } case SDL_MOUSEBUTTONUP: { this->m_inputHandler->SetMouseState(m_event.button.button, false); break; } #pragma endregion Key / Button events case SDL_MOUSEWHEEL: { this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y); break; } } } return 1; } int System::FullscreenToggle() { int result = 0; this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN); this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; return result; } <commit_msg>UPDATE init physics no longer commented out<commit_after>#include "System.h" System::System() { this->m_inputHandler = NULL; this->m_window = NULL; } System::~System() { } int System::Shutdown() { int result = 0; //Destroy the display window SDL_DestroyWindow(m_window); //Quit SDL subsystems SDL_Quit(); this->m_graphicsHandler->Shutdown(); delete this->m_graphicsHandler; delete this->m_camera; this->m_inputHandler->Shutdown(); delete this->m_inputHandler; return result; } int System::Initialize() { int result = 1; this->m_fullscreen = false; this->m_running = true; this->m_window = NULL; //Get the instance if this application this->m_hinstance = GetModuleHandle(NULL); if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError()); } else { printf("SDL succeeded in initializing the window!\n"); } m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (m_window == NULL) { printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError()); } else { printf("Window creation succeeded!\n"); SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(m_window, &wmInfo); m_hwnd = wmInfo.info.win.window; } this->m_graphicsHandler = new GraphicsHandler(); if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT))) { printf("GraphicsHandler did not work. RIP!\n"); } this->m_camera = new Camera(); this->m_camera->Initialize(); Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera); delete oldCam; oldCam = nullptr; //Initialize the PhysicsHandler this->m_physicsHandler.Initialize(); //Initialize the InputHandler this->m_inputHandler = new InputHandler(); this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT); return result; } //Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method int System::Run() { int result = 0; LARGE_INTEGER frequency, currTime, prevTime, elapsedTime; QueryPerformanceFrequency(&frequency); //QueryPerformanceCounter(&prevTime); QueryPerformanceCounter(&currTime); while (this->m_running) { prevTime = currTime; QueryPerformanceCounter(&currTime); elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= frequency.QuadPart; this->m_physicsHandler.Update(); //Prepare the InputHandler this->m_inputHandler->Update(); //Handle events and update inputhandler through said events result = this->HandleEvents(); SDL_PumpEvents(); //Update game if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE)) { this->m_running = false; } if (!this->Update((float)elapsedTime.QuadPart)) { this->m_running = false; } if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F)) { this->FullscreenToggle(); } //std::cout << int(totalTime) << "\n"; //Render this->m_graphicsHandler->Render(); } if (this->m_fullscreen) this->FullscreenToggle(); return result; } int System::Update(float deltaTime) { int result = 1; int translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0; int rotateCameraY = 0; if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W)) { translateCameraZ++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S)) { translateCameraZ--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_SPACE)) { translateCameraY++; if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT)) { translateCameraY *= -1; } } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D)) { translateCameraX++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A)) { translateCameraX--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E)) { rotateCameraY++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q)) { rotateCameraY--; } if (translateCameraY || translateCameraX || translateCameraZ || rotateCameraY) { DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), float(translateCameraZ) * (deltaTime / 1000000.0f)); this->m_camera->AddToCameraPos(posTranslation); this->m_camera->AddToLookAt(posTranslation); float rotationAmount = DirectX::XM_PI / 8; rotationAmount *= deltaTime / 1000000.0f; DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f)); this->m_camera->SetRotation(newRotation); this->m_camera->Update(); } // return result; } int System::HandleEvents() { SDL_Event m_event; while (SDL_PollEvent(&m_event)) { switch (m_event.type) { #pragma region case SDL_WINDOWEVENT: { switch (m_event.window.event) { case SDL_WINDOWEVENT_ENTER: { //OnMouseFocus(); break; } case SDL_WINDOWEVENT_LEAVE: { //OnMouseBlur(); break; } case SDL_WINDOWEVENT_FOCUS_GAINED: { //OnInputFocus(); break; } case SDL_WINDOWEVENT_FOCUS_LOST: { //OnInputBlur(); break; } case SDL_WINDOWEVENT_SHOWN: { break; } case SDL_WINDOWEVENT_HIDDEN: { break; } case SDL_WINDOWEVENT_EXPOSED: { break; } case SDL_WINDOWEVENT_MOVED: { break; } case SDL_WINDOWEVENT_RESIZED: { break; } case SDL_WINDOWEVENT_SIZE_CHANGED: { break; } case SDL_WINDOWEVENT_MINIMIZED: { break; } case SDL_WINDOWEVENT_MAXIMIZED: { break; } case SDL_WINDOWEVENT_RESTORED: { break; } case SDL_WINDOWEVENT_CLOSE: { break; } } break; } #pragma endregion window events case SDL_MOUSEMOTION: { break; } case SDL_QUIT: { //The big X in the corner this->m_running = false; break; } #pragma region case SDL_KEYDOWN: { //OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true); break; } case SDL_KEYUP: { //OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false); break; } case SDL_MOUSEBUTTONDOWN: { this->m_inputHandler->SetMouseState(m_event.button.button, true); break; } case SDL_MOUSEBUTTONUP: { this->m_inputHandler->SetMouseState(m_event.button.button, false); break; } #pragma endregion Key / Button events case SDL_MOUSEWHEEL: { this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y); break; } } } return 1; } int System::FullscreenToggle() { int result = 0; this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN); this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; return result; } <|endoftext|>
<commit_before>// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> using namespace std; #define BOOST_ERROR_CODE_HEADER_ONLY #define BOOST_CHRONO_HEADER_ONLY #define BOOST_CHRONO_EXTENSIONS #include <boost/chrono.hpp> using namespace boost; using namespace boost::chrono; ////////////////////////////////////////// typedef duration<long, ratio<30>> half_min; typedef duration<int, ratio<60*15>> quater; typedef duration<double, ratio<3600*24>> day; //typedef duration<int,60*60> my_hour; //typedef duration<int,ratio<-10, 1000>> my_ms; void case1() { seconds s(10); minutes m(5); hours h(1); milliseconds ms(100); assert(s.count() == 10); assert(ms.count() == 100); s *= 3; s += seconds(30); s = s - seconds(20); assert(s < seconds(50)); cout << s << endl; } ////////////////////////////////////////// void case2() { seconds s(10); minutes m(5); s += m; cout << s << endl; //m+= s; { seconds s(10); typedef duration<double, ratio<60>> my_min; my_min m(5); m += s; cout << m << endl; } { seconds s(40); auto m = duration_cast<minutes>(s); cout << m << endl; seconds s2(301); cout << duration_cast<minutes>(s2) << endl; } { seconds s(3600 + 50); cout << floor<minutes>(s) << endl; cout << ceil<minutes>(s) << endl; cout << round<minutes>(s) << endl; cout << round<hours>(s) << endl; } } ////////////////////////////////////////// template<typename T> using clock_desc = clock_string<T, char>; void case3() { cout << clock_desc<system_clock>::name() << endl; cout << clock_desc<system_clock>::since() << endl; cout << clock_desc<steady_clock>::name() << endl; cout << clock_desc<steady_clock>::since() << endl; cout << clock_desc<process_real_cpu_clock>::name() << endl; cout << clock_desc<process_real_cpu_clock>::since() << endl; } ////////////////////////////////////////// void case4() { auto tp1 = system_clock::now(); cout << tp1 << endl; auto d = tp1.time_since_epoch(); cout << duration_cast<hours>(d) << endl; cout << duration_cast<day>(d) << endl; auto tp2 = tp1 +minutes(1); cout << tp2 << endl; { auto tp = steady_clock::now(); cout << tp << endl; auto d = tp.time_since_epoch(); cout << round<minutes>(d) << endl; cout << round<hours>(d) << endl; } } ////////////////////////////////////////// hours operator"" _h(unsigned long long n) { return hours(n); } seconds operator"" _s(unsigned long long n) { return seconds(n); } milliseconds operator"" _ms(unsigned long long n) { return milliseconds(n); } void case5() { auto h = 5_h; auto s = 45_s; auto ms = 200_ms; cout << h << s << ms << endl; } ////////////////////////////////////////// void case6() { auto tp = system_clock::now(); auto t = system_clock::to_time_t(tp); cout << std::ctime(&t) << endl; } ////////////////////////////////////////// class steady_timer final { private: typedef boost::chrono::steady_clock clock_type; //typedef clock_type::duration duration_type; typedef clock_type::time_point time_point_type; typedef boost::chrono::microseconds duration_type; time_point_type m_start = clock_type::now(); public: steady_timer() = default; ~steady_timer() = default; public: void restart() { m_start = clock_type::now(); } duration_type elapsed() const { return round<duration_type>( clock_type::now() - m_start); } }; ////////////////////////////////////////// int main() { steady_timer t; case1(); case2(); case3(); case4(); case5(); case6(); cout << t.elapsed() << endl; } <commit_msg>chrono in 171<commit_after>// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> //using namespace std; using std::cout; using std::endl; #define BOOST_ERROR_CODE_HEADER_ONLY #define BOOST_CHRONO_HEADER_ONLY #define BOOST_CHRONO_EXTENSIONS #include <boost/chrono.hpp> using namespace boost; using namespace boost::chrono; ////////////////////////////////////////// typedef duration<long, ratio<30>> half_min; typedef duration<int, ratio<60*15>> quater; typedef duration<double, ratio<3600*24>> day; //typedef duration<int,60*60> my_hour; //typedef duration<int,ratio<-10, 1000>> my_ms; void case1() { seconds s(10); minutes m(5); hours h(1); milliseconds ms(100); assert(s.count() == 10); assert(ms.count() == 100); s *= 3; s += seconds(30); s = s - seconds(20); assert(s < seconds(50)); cout << s << endl; } ////////////////////////////////////////// void case2() { seconds s(10); minutes m(5); s += m; cout << s << endl; //m+= s; { seconds s(10); typedef duration<double, ratio<60>> my_min; my_min m(5); m += s; cout << m << endl; } { seconds s(40); auto m = duration_cast<minutes>(s); cout << m << endl; seconds s2(301); cout << duration_cast<minutes>(s2) << endl; } { seconds s(3600 + 50); cout << floor<minutes>(s) << endl; cout << ceil<minutes>(s) << endl; cout << round<minutes>(s) << endl; cout << round<hours>(s) << endl; } } ////////////////////////////////////////// template<typename T> using clock_desc = clock_string<T, char>; void case3() { cout << clock_desc<system_clock>::name() << endl; cout << clock_desc<system_clock>::since() << endl; cout << clock_desc<steady_clock>::name() << endl; cout << clock_desc<steady_clock>::since() << endl; cout << clock_desc<process_real_cpu_clock>::name() << endl; cout << clock_desc<process_real_cpu_clock>::since() << endl; } ////////////////////////////////////////// void case4() { auto tp1 = system_clock::now(); cout << tp1 << endl; auto d = tp1.time_since_epoch(); cout << duration_cast<hours>(d) << endl; cout << duration_cast<day>(d) << endl; auto tp2 = tp1 +minutes(1); cout << tp2 << endl; { auto tp = steady_clock::now(); cout << tp << endl; auto d = tp.time_since_epoch(); cout << round<minutes>(d) << endl; cout << round<hours>(d) << endl; } } ////////////////////////////////////////// hours operator"" _h(unsigned long long n) { return hours(n); } seconds operator"" _s(unsigned long long n) { return seconds(n); } milliseconds operator"" _ms(unsigned long long n) { return milliseconds(n); } void case5() { auto h = 5_h; auto s = 45_s; auto ms = 200_ms; cout << h << s << ms << endl; } ////////////////////////////////////////// void case6() { auto tp = system_clock::now(); auto t = system_clock::to_time_t(tp); cout << std::ctime(&t) << endl; } ////////////////////////////////////////// class steady_timer final { private: typedef boost::chrono::steady_clock clock_type; //typedef clock_type::duration duration_type; typedef clock_type::time_point time_point_type; typedef boost::chrono::microseconds duration_type; time_point_type m_start = clock_type::now(); public: steady_timer() = default; ~steady_timer() = default; public: void restart() { m_start = clock_type::now(); } duration_type elapsed() const { return round<duration_type>( clock_type::now() - m_start); } }; ////////////////////////////////////////// int main() { steady_timer t; case1(); case2(); case3(); case4(); case5(); case6(); cout << t.elapsed() << endl; } <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1754 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1130397 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/03/13 03:00:13<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1755 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#define AODSelector_cxx // The class definition in AODSelector.h has been generated automatically // by the ROOT utility TTree::MakeSelector(). This class is derived // from the ROOT class TSelector. For more information on the TSelector // framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual. // The following methods are defined in this file: // Begin(): called every time a loop on the tree starts, // a convenient place to create your histograms. // SlaveBegin(): called after Begin(), when on PROOF called only on the // slave servers. // Process(): called for each event, in this function you decide what // to read and fill your histograms. // SlaveTerminate: called at the end of the loop on the tree, when on PROOF // called only on the slave servers. // Terminate(): called at the end of the loop on the tree, // a convenient place to draw/fit your histograms. // // To use this file, try the following session on your Tree T: // // Root > T->Process("AODSelector.cxx") // Root > T->Process("AODSelector.cxx","some options") // Root > T->Process("AODSelector.cxx+") // #include "AODSelector.h" #include <TH2.h> #include <TStyle.h> #include <TMath.h> #include <TAxis.h> #include <TH2F.h> #include <TH3F.h> #include <TH1F.h> #include <TF1.h> #include <TCanvas.h> #include <TRandom3.h> static void BinLogAxis(const TH1 *h) { // // Method for the correct logarithmic binning of histograms // TAxis *axis = const_cast<TAxis*>(h->GetXaxis()); const Int_t bins = axis->GetNbins(); const Double_t from = axis->GetXmin(); const Double_t to = axis->GetXmax(); Double_t *newBins = new Double_t[bins + 1]; newBins[0] = from; Double_t factor = pow(to / from, 1. / bins); for (Int_t i = 1; i <= bins; i++) { newBins[i] = factor * newBins[i - 1]; } axis->Set(bins, newBins); delete [] newBins; } Double_t BetheBlochAleph(Double_t bg, Double_t kp1, Double_t kp2, Double_t kp3, Double_t kp4, Double_t kp5) { Double_t beta = bg / TMath::Sqrt(1. + bg * bg); Double_t aa = TMath::Power(beta,kp4); Double_t bb = TMath::Power(1. / bg,kp5); bb = TMath::Log(kp3 + bb); return (kp2 - aa - bb) * kp1 / aa; } Double_t DeuteronTPC(Double_t *x, Double_t *) { // Deuteron expected signal in TPC, taken from AntiHe4 task return BetheBlochAleph(x[0] / MD ,4.69637,7.51827,0.0183746,2.60,2.7); } unsigned int Log2Int(const unsigned int v) { // Taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 0xFF00FF00, 0xFFFF0000}; unsigned int r = (v & b[0]) != 0; r |= ((v & b[4]) != 0) << 4; r |= ((v & b[3]) != 0) << 3; r |= ((v & b[2]) != 0) << 2; r |= ((v & b[1]) != 0) << 1; return r; } void AODSelector::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } Int_t AODSelector::GetCentBin(float cent) { if (cent < fCentralityBins[0]) return -1; for (int i = 0; i < kNCent; ++i) if (cent <= fCentralityBins[i + 1]) return i; return -1; } Int_t AODSelector::GetPtBin(float pt) { for (int i = 0; i < kNBins; ++i) { if (pt < fBins[i+1] && pt >= fBins[i]) { return i; } } return -1; } Bool_t AODSelector::Flatten(float cent) { float prob[13] = { 0.855566,0.846964,0.829618,0.829259,0.830984, 0.85094,0.844346,0.851818,0.874758,1, 0.374767,0.650491,0.946963 }; return gRandom->Rndm() > prob[int(cent)]; } void AODSelector::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); const Int_t nPtBins = kNBins; const Int_t nCentBins = kNCent; const Double_t *pTbins = fBins; const Double_t *centBins = fCentralityBins; const Int_t nDCAbins = 80; const Float_t range = 0.5; Double_t dcaBins[nDCAbins+1]; for (int i = 0; i <= nDCAbins; ++i) dcaBins[i] = i * range * 2 / nDCAbins - range; fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.); fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins); fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.); GetOutputList()->Add(fCentrality); GetOutputList()->Add(fCentralityClasses); GetOutputList()->Add(fFlattenedCentrality); const int tofNbins = 75; const float tofLowBoundary = -2.4,tofHighBoundary = 3.6; Double_t tofBins[tofNbins + 1]; const float deltaTOF = (tofHighBoundary - tofLowBoundary) / tofNbins; for (int i = 0; i <= tofNbins; ++i) tofBins[i] = i * deltaTOF + tofLowBoundary; const int dcaZnBins = 400; const float dcaZlimit = 10.; Double_t dcazBins[dcaZnBins + 1]; const float deltaDCAz = 2.f * dcaZlimit / dcaZnBins; for (int i = 0; i <= dcaZnBins; ++i) dcazBins[i] = i * deltaDCAz - dcaZlimit; const int nTpcBins = 500; Double_t tpcBins[nTpcBins + 1]; for (int i = 0; i <= nTpcBins; ++i) { tpcBins[i] = i * 5; } fTPCSignal = new TH2F("fTPCSignal","p_{T} (GeV/c);dE/dx (a.u.)",nPtBins,pTbins,500,0,2500); fATOFsignal = new TH3F("fATOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)", nCentBins,centBins,nPtBins,pTbins,dcaZnBins,dcazBins); fMTOFsignal = new TH3F("fMTOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); GetOutputList()->Add(fATOFsignal); GetOutputList()->Add(fATPCcounts); GetOutputList()->Add(fMDCAxy); GetOutputList()->Add(fMDCAz); GetOutputList()->Add(fMTOFsignal); GetOutputList()->Add(fMTPCcounts); GetOutputList()->Add(fTPCSignal); fDeutBB = new TF1("fDeutBB",DeuteronTPC,0.3,6,0); } Bool_t AODSelector::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either AODSelector::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. GetEntry(entry); if (centrality < 0) { fSkipEvent = kFALSE; if (-centrality < 13.f) fSkipEvent = Flatten(-centrality); if (!fSkipEvent) { fFlattenedCentrality->Fill(-centrality); fCentralityClasses->Fill(-centrality); } fCentrality->Fill(-centrality); } if (fSkipEvent) return kTRUE; const int cent = GetCentBin(TMath::Abs(centrality)); if (cent < 0) return kTRUE; if (TMath::Abs(eta) > 0.8) return kTRUE; if (TMath::Abs(chi2NDF) > kChi2Cut) return kTRUE; Double_t pz = TMath::Sqrt(p * p - pT * pT); Double_t e = TMath::Sqrt(p * p + M2D); Double_t y = 0.5 * TMath::Log((e + pz) / (e - pz)); if (TMath::Abs(y) > 0.5) { return kTRUE; } if (TPCnSignal < kTPCsig) return kTRUE; if (ITSnClust - ITSnSignal <= 0) return kTRUE; if (TMath::Abs(DCAz) > kDCAz) return kTRUE; if (TMath::Abs(DCAxy) > 0.5f) return kTRUE; Float_t c_pT = pT; if (c_pT > 0) { c_pT -= fCorrectionD(c_pT); } else { c_pT += fCorrectionAD(-c_pT); } fTPCSignal->Fill(pTPC, TPCsignal); if (TPCsignal > 0.7f * fDeutBB->Eval(pTPC) && TPCsignal < 1.3f * fDeutBB->Eval(pTPC)) { if(c_pT > 0.) { fMTPCcounts->Fill(centrality,c_pT,TPCsignal); fMDCAxy->Fill(centrality,c_pT,DCAxy); fMDCAz->Fill(centrality,c_pT,DCAz); } else { fATPCcounts->Fill(centrality,-c_pT,TPCsignal); } if (TOFtime > 0.f && length > 350.f) { Float_t beta = length / (2.99792457999999984e-02f * TOFtime); if (beta < (1.f - EPSILON)) { Float_t gamma = 1. / TMath::Sqrt(1.f - (beta * beta)); const float dm = p * p / (beta * beta * gamma * gamma) - M2D; if(c_pT > 0.) { fMTOFsignal->Fill(centrality,c_pT,dm); } else { fATOFsignal->Fill(centrality,-c_pT,dm); } } } } return kTRUE; } void AODSelector::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void AODSelector::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. TFile f("nuclei.root","update"); f.mkdir(kName.Data()); f.cd(kName.Data()); ((TH1F*)GetOutputList()->FindObject("fCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fFlattenCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fCentralityClasses"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATPCcounts"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAxy"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAz"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTPCcounts"))->Write(); f.Close(); fTPCSignal = (TH2F*)GetOutputList()->FindObject("fTPCSignal"); fTPCSignal->Draw("colz"); fDeutBB = new TF1("deutTPC",DeuteronTPC,0.4,6,0); fDeutBB->Draw("same"); } <commit_msg>Tighter cut on TPC PID<commit_after>#define AODSelector_cxx // The class definition in AODSelector.h has been generated automatically // by the ROOT utility TTree::MakeSelector(). This class is derived // from the ROOT class TSelector. For more information on the TSelector // framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual. // The following methods are defined in this file: // Begin(): called every time a loop on the tree starts, // a convenient place to create your histograms. // SlaveBegin(): called after Begin(), when on PROOF called only on the // slave servers. // Process(): called for each event, in this function you decide what // to read and fill your histograms. // SlaveTerminate: called at the end of the loop on the tree, when on PROOF // called only on the slave servers. // Terminate(): called at the end of the loop on the tree, // a convenient place to draw/fit your histograms. // // To use this file, try the following session on your Tree T: // // Root > T->Process("AODSelector.cxx") // Root > T->Process("AODSelector.cxx","some options") // Root > T->Process("AODSelector.cxx+") // #include "AODSelector.h" #include <TH2.h> #include <TStyle.h> #include <TMath.h> #include <TAxis.h> #include <TH2F.h> #include <TH3F.h> #include <TH1F.h> #include <TF1.h> #include <TCanvas.h> #include <TRandom3.h> static void BinLogAxis(const TH1 *h) { // // Method for the correct logarithmic binning of histograms // TAxis *axis = const_cast<TAxis*>(h->GetXaxis()); const Int_t bins = axis->GetNbins(); const Double_t from = axis->GetXmin(); const Double_t to = axis->GetXmax(); Double_t *newBins = new Double_t[bins + 1]; newBins[0] = from; Double_t factor = pow(to / from, 1. / bins); for (Int_t i = 1; i <= bins; i++) { newBins[i] = factor * newBins[i - 1]; } axis->Set(bins, newBins); delete [] newBins; } Double_t BetheBlochAleph(Double_t bg, Double_t kp1, Double_t kp2, Double_t kp3, Double_t kp4, Double_t kp5) { Double_t beta = bg / TMath::Sqrt(1. + bg * bg); Double_t aa = TMath::Power(beta,kp4); Double_t bb = TMath::Power(1. / bg,kp5); bb = TMath::Log(kp3 + bb); return (kp2 - aa - bb) * kp1 / aa; } Double_t DeuteronTPC(Double_t *x, Double_t *) { // Deuteron expected signal in TPC, taken from AntiHe4 task return BetheBlochAleph(x[0] / MD ,4.69637,7.51827,0.0183746,2.60,2.7); } unsigned int Log2Int(const unsigned int v) { // Taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 0xFF00FF00, 0xFFFF0000}; unsigned int r = (v & b[0]) != 0; r |= ((v & b[4]) != 0) << 4; r |= ((v & b[3]) != 0) << 3; r |= ((v & b[2]) != 0) << 2; r |= ((v & b[1]) != 0) << 1; return r; } void AODSelector::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } Int_t AODSelector::GetCentBin(float cent) { if (cent < fCentralityBins[0]) return -1; for (int i = 0; i < kNCent; ++i) if (cent <= fCentralityBins[i + 1]) return i; return -1; } Int_t AODSelector::GetPtBin(float pt) { for (int i = 0; i < kNBins; ++i) { if (pt < fBins[i+1] && pt >= fBins[i]) { return i; } } return -1; } Bool_t AODSelector::Flatten(float cent) { float prob[13] = { 0.855566,0.846964,0.829618,0.829259,0.830984, 0.85094,0.844346,0.851818,0.874758,1, 0.374767,0.650491,0.946963 }; return gRandom->Rndm() > prob[int(cent)]; } void AODSelector::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); const Int_t nPtBins = kNBins; const Int_t nCentBins = kNCent; const Double_t *pTbins = fBins; const Double_t *centBins = fCentralityBins; const Int_t nDCAbins = 80; const Float_t range = 0.5; Double_t dcaBins[nDCAbins+1]; for (int i = 0; i <= nDCAbins; ++i) dcaBins[i] = i * range * 2 / nDCAbins - range; fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.); fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins); fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.); GetOutputList()->Add(fCentrality); GetOutputList()->Add(fCentralityClasses); GetOutputList()->Add(fFlattenedCentrality); const int tofNbins = 75; const float tofLowBoundary = -2.4,tofHighBoundary = 3.6; Double_t tofBins[tofNbins + 1]; const float deltaTOF = (tofHighBoundary - tofLowBoundary) / tofNbins; for (int i = 0; i <= tofNbins; ++i) tofBins[i] = i * deltaTOF + tofLowBoundary; const int dcaZnBins = 400; const float dcaZlimit = 10.; Double_t dcazBins[dcaZnBins + 1]; const float deltaDCAz = 2.f * dcaZlimit / dcaZnBins; for (int i = 0; i <= dcaZnBins; ++i) dcazBins[i] = i * deltaDCAz - dcaZlimit; const int nTpcBins = 500; Double_t tpcBins[nTpcBins + 1]; for (int i = 0; i <= nTpcBins; ++i) { tpcBins[i] = i * 5; } fTPCSignal = new TH2F("fTPCSignal","p_{T} (GeV/c);dE/dx (a.u.)",nPtBins,pTbins,500,0,2500); fATOFsignal = new TH3F("fATOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)", nCentBins,centBins,nPtBins,pTbins,dcaZnBins,dcazBins); fMTOFsignal = new TH3F("fMTOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); GetOutputList()->Add(fATOFsignal); GetOutputList()->Add(fATPCcounts); GetOutputList()->Add(fMDCAxy); GetOutputList()->Add(fMDCAz); GetOutputList()->Add(fMTOFsignal); GetOutputList()->Add(fMTPCcounts); GetOutputList()->Add(fTPCSignal); fDeutBB = new TF1("fDeutBB",DeuteronTPC,0.3,6,0); } Bool_t AODSelector::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either AODSelector::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. GetEntry(entry); if (centrality < 0) { fSkipEvent = kFALSE; if (-centrality < 13.f) fSkipEvent = Flatten(-centrality); if (!fSkipEvent) { fFlattenedCentrality->Fill(-centrality); fCentralityClasses->Fill(-centrality); } fCentrality->Fill(-centrality); } if (fSkipEvent) return kTRUE; const int cent = GetCentBin(TMath::Abs(centrality)); if (cent < 0) return kTRUE; if (TMath::Abs(eta) > 0.8) return kTRUE; if (TMath::Abs(chi2NDF) > kChi2Cut) return kTRUE; Double_t pz = TMath::Sqrt(p * p - pT * pT); Double_t e = TMath::Sqrt(p * p + M2D); Double_t y = 0.5 * TMath::Log((e + pz) / (e - pz)); if (TMath::Abs(y) > 0.5) { return kTRUE; } if (TPCnSignal < kTPCsig) return kTRUE; if (ITSnClust - ITSnSignal <= 0) return kTRUE; if (TMath::Abs(DCAz) > kDCAz) return kTRUE; if (TMath::Abs(DCAxy) > 0.5f) return kTRUE; Float_t c_pT = pT; if (c_pT > 0) { c_pT -= fCorrectionD(c_pT); } else { c_pT += fCorrectionAD(-c_pT); } fTPCSignal->Fill(pTPC, TPCsignal); if (TPCsignal > 0.76f * fDeutBB->Eval(pTPC) && TPCsignal < 1.24f * fDeutBB->Eval(pTPC)) { if(c_pT > 0.) { fMTPCcounts->Fill(centrality,c_pT,TPCsignal); fMDCAxy->Fill(centrality,c_pT,DCAxy); fMDCAz->Fill(centrality,c_pT,DCAz); } else { fATPCcounts->Fill(centrality,-c_pT,TPCsignal); } if (TOFtime > 0.f && length > 350.f) { Float_t beta = length / (2.99792457999999984e-02f * TOFtime); if (beta < (1.f - EPSILON)) { Float_t gamma = 1. / TMath::Sqrt(1.f - (beta * beta)); const float dm = p * p / (beta * beta * gamma * gamma) - M2D; if(c_pT > 0.) { fMTOFsignal->Fill(centrality,c_pT,dm); } else { fATOFsignal->Fill(centrality,-c_pT,dm); } } } } return kTRUE; } void AODSelector::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void AODSelector::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. TFile f("nuclei.root","update"); f.mkdir(kName.Data()); f.cd(kName.Data()); ((TH1F*)GetOutputList()->FindObject("fCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fFlattenCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fCentralityClasses"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATPCcounts"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAxy"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAz"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTPCcounts"))->Write(); f.Close(); fTPCSignal = (TH2F*)GetOutputList()->FindObject("fTPCSignal"); fTPCSignal->Draw("colz"); fDeutBB = new TF1("deutTPC",DeuteronTPC,0.4,6,0); fDeutBB->Draw("same"); } <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1985 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1223585 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/12/26 03:00:09<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1986 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1689 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1099664 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/11/22 03:00:11<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1690 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2035 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1237301 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/02/16 03:00:11<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2036 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// @(#)root/mathcore:$Id$ // Authors: L. Moneta, J.T. Offermann, E.G.P. Bos 2013-2018 // /********************************************************************** * * * Copyright (c) 2013 , LCG ROOT MathLib Team * * * **********************************************************************/ /* * NumericalDerivatorMinuit2.cxx * * Original version (NumericalDerivator) created on: Aug 14, 2013 * Authors: L. Moneta, J. T. Offermann * Modified version (NumericalDerivatorMinuit2) created on: Sep 27, 2017 * Author: E. G. P. Bos * * NumericalDerivator was essentially a slightly modified copy of code * written by M. Winkler, F. James, L. Moneta, and A. Zsenei for Minuit2, * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT. Original version: * https://github.com/lmoneta/root/blob/lvmini/math/mathcore/src/NumericalDerivator.cxx * * This class attempts to more closely follow the Minuit2 implementation. * Modified things (w.r.t. NumericalDerivator) are indicated by MODIFIED. */ #include "NumericalDerivatorMinuit2.h" #include <cmath> #include <algorithm> #include <Math/IFunction.h> #include <iostream> #include <TMath.h> #include <cassert> #include "Fit/ParameterSettings.h" #include <Math/Minimizer.h> // needed here because in Fitter is only a forward declaration #include <RooMsgService.h> namespace RooFit { NumericalDerivatorMinuit2::NumericalDerivatorMinuit2(bool always_exactly_mimic_minuit2) : _always_exactly_mimic_minuit2(always_exactly_mimic_minuit2) { } NumericalDerivatorMinuit2::NumericalDerivatorMinuit2(double step_tolerance, double grad_tolerance, unsigned int ncycles, double error_level, bool always_exactly_mimic_minuit2) : fStepTolerance(step_tolerance), fGradTolerance(grad_tolerance), fNCycles(ncycles), Up(error_level), _always_exactly_mimic_minuit2(always_exactly_mimic_minuit2) { } // deep copy constructor NumericalDerivatorMinuit2::NumericalDerivatorMinuit2(const RooFit::NumericalDerivatorMinuit2 &other) : fStepTolerance(other.fStepTolerance), fGradTolerance(other.fGradTolerance), fNCycles(other.fNCycles), Up(other.Up), fVal(other.fVal), vx(other.vx), vx_external(other.vx_external), dfmin(other.dfmin), vrysml(other.vrysml), precision(other.precision), _always_exactly_mimic_minuit2(other._always_exactly_mimic_minuit2), vx_fVal_cache(other.vx_fVal_cache) { } void NumericalDerivatorMinuit2::SetStepTolerance(double value) { fStepTolerance = value; } void NumericalDerivatorMinuit2::SetGradTolerance(double value) { fGradTolerance = value; } void NumericalDerivatorMinuit2::SetNCycles(int value) { fNCycles = value; } NumericalDerivatorMinuit2::~NumericalDerivatorMinuit2() { // TODO Auto-generated destructor stub } // This function sets internal state based on input parameters. This state // setup is used in the actual (partial) derivative calculations. void NumericalDerivatorMinuit2::setup_differentiate(const ROOT::Math::IBaseFunctionMultiDim *function, const double *cx, const std::vector<ROOT::Fit::ParameterSettings> &parameters) { assert(function != nullptr && "function is a nullptr"); auto get_time = []() { return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); }; decltype(get_time()) t1, t2, t3, t4, t5, t6, t7, t8; t1 = get_time(); if (vx.size() != function->NDim()) { vx.resize(function->NDim()); } t2 = get_time(); if (vx_external.size() != function->NDim()) { vx_external.resize(function->NDim()); } t3 = get_time(); if (vx_fVal_cache.size() != function->NDim()) { vx_fVal_cache.resize(function->NDim()); } t4 = get_time(); std::copy(cx, cx + function->NDim(), vx.data()); t5 = get_time(); // convert to Minuit external parameters for (unsigned i = 0; i < function->NDim(); i++) { vx_external[i] = Int2ext(parameters[i], vx[i]); } t6 = get_time(); if (vx != vx_fVal_cache) { vx_fVal_cache = vx; fVal = (*function)(vx_external.data()); // value of function at given points } t7 = get_time(); dfmin = 8. * precision.Eps2() * (std::abs(fVal) + Up); vrysml = 8. * precision.Eps() * precision.Eps(); t8 = get_time(); } MinuitDerivatorElement NumericalDerivatorMinuit2::partial_derivative(const ROOT::Math::IBaseFunctionMultiDim *function, const double *x, const std::vector<ROOT::Fit::ParameterSettings> &parameters, unsigned int i_component, MinuitDerivatorElement previous) { setup_differentiate(function, x, parameters); return fast_partial_derivative(function, parameters, i_component, previous); } // leaves the parameter setup to the caller MinuitDerivatorElement NumericalDerivatorMinuit2::fast_partial_derivative(const ROOT::Math::IBaseFunctionMultiDim *function, const std::vector<ROOT::Fit::ParameterSettings> &parameters, unsigned int ix, const MinuitDerivatorElement& previous) { MinuitDerivatorElement deriv {previous}; double xtf = vx[ix]; double epspri = precision.Eps2() + std::abs(deriv.derivative * precision.Eps2()); double step_old = 0.; for (unsigned int j = 0; j < fNCycles; ++j) { double optstp = std::sqrt(dfmin / (std::abs(deriv.second_derivative) + epspri)); double step = std::max(optstp, std::abs(0.1 * deriv.step_size)); if (parameters[ix].IsBound()) { if (step > 0.5) step = 0.5; } double stpmax = 10. * std::abs(deriv.step_size); if (step > stpmax) step = stpmax; double stpmin = std::max(vrysml, 8. * std::abs(precision.Eps2() * vx[ix])); if (step < stpmin) step = stpmin; if (std::abs((step - step_old) / step) < fStepTolerance) { break; } deriv.step_size = step; step_old = step; vx[ix] = xtf + step; vx_external[ix] = Int2ext(parameters[ix], vx[ix]); double fs1 = (*function)(vx_external.data()); vx[ix] = xtf - step; vx_external[ix] = Int2ext(parameters[ix], vx[ix]); double fs2 = (*function)(vx_external.data()); vx[ix] = xtf; vx_external[ix] = Int2ext(parameters[ix], vx[ix]); double fGrd_old = deriv.derivative; deriv.derivative = 0.5 * (fs1 - fs2) / step; deriv.second_derivative = (fs1 + fs2 - 2. * fVal) / step / step; if (std::abs(fGrd_old - deriv.derivative) / (std::abs(deriv.derivative) + dfmin / step) < fGradTolerance) { break; } } return deriv; } MinuitDerivatorElement NumericalDerivatorMinuit2::operator()(const ROOT::Math::IBaseFunctionMultiDim *function, const double *x, const std::vector<ROOT::Fit::ParameterSettings> &parameters, unsigned int i_component, const MinuitDerivatorElement& previous) { return partial_derivative(function, x, parameters, i_component, previous); } std::vector<MinuitDerivatorElement> NumericalDerivatorMinuit2::Differentiate(const ROOT::Math::IBaseFunctionMultiDim *function, const double *cx, const std::vector<ROOT::Fit::ParameterSettings> &parameters, const std::vector<MinuitDerivatorElement>& previous_gradient) { setup_differentiate(function, cx, parameters); std::vector<MinuitDerivatorElement> gradient; gradient.reserve(function->NDim()); for (unsigned int ix = 0; ix < function->NDim(); ++ix) { gradient.emplace_back(fast_partial_derivative(function, parameters, ix, previous_gradient[ix])); } return gradient; } double NumericalDerivatorMinuit2::Int2ext(const ROOT::Fit::ParameterSettings &parameter, double val) const { // return external value from internal value for parameter i if (parameter.IsBound()) { if (parameter.IsDoubleBound()) { return fDoubleLimTrafo.Int2ext(val, parameter.UpperLimit(), parameter.LowerLimit()); } else if (parameter.HasUpperLimit() && !parameter.HasLowerLimit()) { return fUpperLimTrafo.Int2ext(val, parameter.UpperLimit()); } else { return fLowerLimTrafo.Int2ext(val, parameter.LowerLimit()); } } return val; } double NumericalDerivatorMinuit2::Ext2int(const ROOT::Fit::ParameterSettings &parameter, double val) const { // return the internal value for parameter i with external value val if (parameter.IsBound()) { if (parameter.IsDoubleBound()) { return fDoubleLimTrafo.Ext2int(val, parameter.UpperLimit(), parameter.LowerLimit(), precision); } else if (parameter.HasUpperLimit() && !parameter.HasLowerLimit()) { return fUpperLimTrafo.Ext2int(val, parameter.UpperLimit(), precision); } else { return fLowerLimTrafo.Ext2int(val, parameter.LowerLimit(), precision); } } return val; } double NumericalDerivatorMinuit2::DInt2Ext(const ROOT::Fit::ParameterSettings &parameter, double val) const { // return the derivative of the int->ext transformation: dPext(i) / dPint(i) // for the parameter i with value val double dd = 1.; if (parameter.IsBound()) { if (parameter.IsDoubleBound()) { dd = fDoubleLimTrafo.DInt2Ext(val, parameter.UpperLimit(), parameter.LowerLimit()); } else if (parameter.HasUpperLimit() && !parameter.HasLowerLimit()) { dd = fUpperLimTrafo.DInt2Ext(val, parameter.UpperLimit()); } else { dd = fLowerLimTrafo.DInt2Ext(val, parameter.LowerLimit()); } } return dd; } // MODIFIED: // This function was not implemented as in Minuit2. Now it copies the behavior // of InitialGradientCalculator. See https://github.com/roofit-dev/root/issues/10 void NumericalDerivatorMinuit2::SetInitialGradient(const ROOT::Math::IBaseFunctionMultiDim *function, const std::vector<ROOT::Fit::ParameterSettings> &parameters, std::vector<MinuitDerivatorElement>& gradient) { // set an initial gradient using some given steps // (used in the first iteration) auto get_time = []() { return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); }; decltype(get_time()) t1, t2; t1 = get_time(); assert(function != nullptr && "function is a nullptr"); double eps2 = precision.Eps2(); unsigned ix = 0; for (auto parameter = parameters.begin(); parameter != parameters.end(); ++parameter, ++ix) { // What Minuit2 calls "Error" is stepsize on the ROOT side. double werr = parameter->StepSize(); // Actually, sav in Minuit2 is the external parameter value, so that is // what we called var before and var is unnecessary here. double sav = parameter->Value(); // However, we do need var below, so let's calculate it using Ext2int: double var = Ext2int(*parameter, sav); if (_always_exactly_mimic_minuit2) { // this transformation can lose a few bits, but Minuit2 does it too sav = Int2ext(*parameter, var); } double sav2 = sav + werr; if (parameter->HasUpperLimit() && sav2 > parameter->UpperLimit()) { sav2 = parameter->UpperLimit(); } double var2 = Ext2int(*parameter, sav2); double vplu = var2 - var; sav2 = sav - werr; if (parameter->HasLowerLimit() && sav2 < parameter->LowerLimit()) { sav2 = parameter->LowerLimit(); } var2 = Ext2int(*parameter, sav2); double vmin = var2 - var; double gsmin = 8. * eps2 * (fabs(var) + eps2); // protect against very small step sizes which can cause dirin to zero and then nan values in grd double dirin = std::max(0.5 * (fabs(vplu) + fabs(vmin)), gsmin); double g2 = 2.0 * Up / (dirin * dirin); double gstep = std::max(gsmin, 0.1 * dirin); double grd = g2 * dirin; if (parameter->IsBound()) { if (gstep > 0.5) gstep = 0.5; } gradient[ix].derivative = grd; gradient[ix].second_derivative = g2; gradient[ix].step_size = gstep; } t2 = get_time(); } bool NumericalDerivatorMinuit2::always_exactly_mimic_minuit2() const { return _always_exactly_mimic_minuit2; }; void NumericalDerivatorMinuit2::set_always_exactly_mimic_minuit2(bool flag) { _always_exactly_mimic_minuit2 = flag; } void NumericalDerivatorMinuit2::set_step_tolerance(double step_tolerance) { fStepTolerance = step_tolerance; } void NumericalDerivatorMinuit2::set_grad_tolerance(double grad_tolerance) { fGradTolerance = grad_tolerance; } void NumericalDerivatorMinuit2::set_ncycles(unsigned int ncycles) { fNCycles = ncycles; } void NumericalDerivatorMinuit2::set_error_level(double error_level) { Up = error_level; } std::ostream& operator<<(std::ostream& out, const MinuitDerivatorElement value){ return out << "(derivative: " << value.derivative << ", second_derivative: " << value.second_derivative << ", step_size: " << value.step_size << ")"; } } // namespace RooFit <commit_msg>Remove timing code<commit_after>// @(#)root/mathcore:$Id$ // Authors: L. Moneta, J.T. Offermann, E.G.P. Bos 2013-2018 // /********************************************************************** * * * Copyright (c) 2013 , LCG ROOT MathLib Team * * * **********************************************************************/ /* * NumericalDerivatorMinuit2.cxx * * Original version (NumericalDerivator) created on: Aug 14, 2013 * Authors: L. Moneta, J. T. Offermann * Modified version (NumericalDerivatorMinuit2) created on: Sep 27, 2017 * Author: E. G. P. Bos * * NumericalDerivator was essentially a slightly modified copy of code * written by M. Winkler, F. James, L. Moneta, and A. Zsenei for Minuit2, * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT. Original version: * https://github.com/lmoneta/root/blob/lvmini/math/mathcore/src/NumericalDerivator.cxx * * This class attempts to more closely follow the Minuit2 implementation. * Modified things (w.r.t. NumericalDerivator) are indicated by MODIFIED. */ #include "NumericalDerivatorMinuit2.h" #include <cmath> #include <algorithm> #include <Math/IFunction.h> #include <iostream> #include <TMath.h> #include <cassert> #include "Fit/ParameterSettings.h" #include <Math/Minimizer.h> // needed here because in Fitter is only a forward declaration #include <RooMsgService.h> namespace RooFit { NumericalDerivatorMinuit2::NumericalDerivatorMinuit2(bool always_exactly_mimic_minuit2) : _always_exactly_mimic_minuit2(always_exactly_mimic_minuit2) { } NumericalDerivatorMinuit2::NumericalDerivatorMinuit2(double step_tolerance, double grad_tolerance, unsigned int ncycles, double error_level, bool always_exactly_mimic_minuit2) : fStepTolerance(step_tolerance), fGradTolerance(grad_tolerance), fNCycles(ncycles), Up(error_level), _always_exactly_mimic_minuit2(always_exactly_mimic_minuit2) { } // deep copy constructor NumericalDerivatorMinuit2::NumericalDerivatorMinuit2(const RooFit::NumericalDerivatorMinuit2 &other) : fStepTolerance(other.fStepTolerance), fGradTolerance(other.fGradTolerance), fNCycles(other.fNCycles), Up(other.Up), fVal(other.fVal), vx(other.vx), vx_external(other.vx_external), dfmin(other.dfmin), vrysml(other.vrysml), precision(other.precision), _always_exactly_mimic_minuit2(other._always_exactly_mimic_minuit2), vx_fVal_cache(other.vx_fVal_cache) { } void NumericalDerivatorMinuit2::SetStepTolerance(double value) { fStepTolerance = value; } void NumericalDerivatorMinuit2::SetGradTolerance(double value) { fGradTolerance = value; } void NumericalDerivatorMinuit2::SetNCycles(int value) { fNCycles = value; } NumericalDerivatorMinuit2::~NumericalDerivatorMinuit2() { // TODO Auto-generated destructor stub } // This function sets internal state based on input parameters. This state // setup is used in the actual (partial) derivative calculations. void NumericalDerivatorMinuit2::setup_differentiate(const ROOT::Math::IBaseFunctionMultiDim *function, const double *cx, const std::vector<ROOT::Fit::ParameterSettings> &parameters) { assert(function != nullptr && "function is a nullptr"); if (vx.size() != function->NDim()) { vx.resize(function->NDim()); } if (vx_external.size() != function->NDim()) { vx_external.resize(function->NDim()); } if (vx_fVal_cache.size() != function->NDim()) { vx_fVal_cache.resize(function->NDim()); } std::copy(cx, cx + function->NDim(), vx.data()); // convert to Minuit external parameters for (unsigned i = 0; i < function->NDim(); i++) { vx_external[i] = Int2ext(parameters[i], vx[i]); } if (vx != vx_fVal_cache) { vx_fVal_cache = vx; fVal = (*function)(vx_external.data()); // value of function at given points } dfmin = 8. * precision.Eps2() * (std::abs(fVal) + Up); vrysml = 8. * precision.Eps() * precision.Eps(); } MinuitDerivatorElement NumericalDerivatorMinuit2::partial_derivative(const ROOT::Math::IBaseFunctionMultiDim *function, const double *x, const std::vector<ROOT::Fit::ParameterSettings> &parameters, unsigned int i_component, MinuitDerivatorElement previous) { setup_differentiate(function, x, parameters); return fast_partial_derivative(function, parameters, i_component, previous); } // leaves the parameter setup to the caller MinuitDerivatorElement NumericalDerivatorMinuit2::fast_partial_derivative(const ROOT::Math::IBaseFunctionMultiDim *function, const std::vector<ROOT::Fit::ParameterSettings> &parameters, unsigned int ix, const MinuitDerivatorElement& previous) { MinuitDerivatorElement deriv {previous}; double xtf = vx[ix]; double epspri = precision.Eps2() + std::abs(deriv.derivative * precision.Eps2()); double step_old = 0.; for (unsigned int j = 0; j < fNCycles; ++j) { double optstp = std::sqrt(dfmin / (std::abs(deriv.second_derivative) + epspri)); double step = std::max(optstp, std::abs(0.1 * deriv.step_size)); if (parameters[ix].IsBound()) { if (step > 0.5) step = 0.5; } double stpmax = 10. * std::abs(deriv.step_size); if (step > stpmax) step = stpmax; double stpmin = std::max(vrysml, 8. * std::abs(precision.Eps2() * vx[ix])); if (step < stpmin) step = stpmin; if (std::abs((step - step_old) / step) < fStepTolerance) { break; } deriv.step_size = step; step_old = step; vx[ix] = xtf + step; vx_external[ix] = Int2ext(parameters[ix], vx[ix]); double fs1 = (*function)(vx_external.data()); vx[ix] = xtf - step; vx_external[ix] = Int2ext(parameters[ix], vx[ix]); double fs2 = (*function)(vx_external.data()); vx[ix] = xtf; vx_external[ix] = Int2ext(parameters[ix], vx[ix]); double fGrd_old = deriv.derivative; deriv.derivative = 0.5 * (fs1 - fs2) / step; deriv.second_derivative = (fs1 + fs2 - 2. * fVal) / step / step; if (std::abs(fGrd_old - deriv.derivative) / (std::abs(deriv.derivative) + dfmin / step) < fGradTolerance) { break; } } return deriv; } MinuitDerivatorElement NumericalDerivatorMinuit2::operator()(const ROOT::Math::IBaseFunctionMultiDim *function, const double *x, const std::vector<ROOT::Fit::ParameterSettings> &parameters, unsigned int i_component, const MinuitDerivatorElement& previous) { return partial_derivative(function, x, parameters, i_component, previous); } std::vector<MinuitDerivatorElement> NumericalDerivatorMinuit2::Differentiate(const ROOT::Math::IBaseFunctionMultiDim *function, const double *cx, const std::vector<ROOT::Fit::ParameterSettings> &parameters, const std::vector<MinuitDerivatorElement>& previous_gradient) { setup_differentiate(function, cx, parameters); std::vector<MinuitDerivatorElement> gradient; gradient.reserve(function->NDim()); for (unsigned int ix = 0; ix < function->NDim(); ++ix) { gradient.emplace_back(fast_partial_derivative(function, parameters, ix, previous_gradient[ix])); } return gradient; } double NumericalDerivatorMinuit2::Int2ext(const ROOT::Fit::ParameterSettings &parameter, double val) const { // return external value from internal value for parameter i if (parameter.IsBound()) { if (parameter.IsDoubleBound()) { return fDoubleLimTrafo.Int2ext(val, parameter.UpperLimit(), parameter.LowerLimit()); } else if (parameter.HasUpperLimit() && !parameter.HasLowerLimit()) { return fUpperLimTrafo.Int2ext(val, parameter.UpperLimit()); } else { return fLowerLimTrafo.Int2ext(val, parameter.LowerLimit()); } } return val; } double NumericalDerivatorMinuit2::Ext2int(const ROOT::Fit::ParameterSettings &parameter, double val) const { // return the internal value for parameter i with external value val if (parameter.IsBound()) { if (parameter.IsDoubleBound()) { return fDoubleLimTrafo.Ext2int(val, parameter.UpperLimit(), parameter.LowerLimit(), precision); } else if (parameter.HasUpperLimit() && !parameter.HasLowerLimit()) { return fUpperLimTrafo.Ext2int(val, parameter.UpperLimit(), precision); } else { return fLowerLimTrafo.Ext2int(val, parameter.LowerLimit(), precision); } } return val; } double NumericalDerivatorMinuit2::DInt2Ext(const ROOT::Fit::ParameterSettings &parameter, double val) const { // return the derivative of the int->ext transformation: dPext(i) / dPint(i) // for the parameter i with value val double dd = 1.; if (parameter.IsBound()) { if (parameter.IsDoubleBound()) { dd = fDoubleLimTrafo.DInt2Ext(val, parameter.UpperLimit(), parameter.LowerLimit()); } else if (parameter.HasUpperLimit() && !parameter.HasLowerLimit()) { dd = fUpperLimTrafo.DInt2Ext(val, parameter.UpperLimit()); } else { dd = fLowerLimTrafo.DInt2Ext(val, parameter.LowerLimit()); } } return dd; } // MODIFIED: // This function was not implemented as in Minuit2. Now it copies the behavior // of InitialGradientCalculator. See https://github.com/roofit-dev/root/issues/10 void NumericalDerivatorMinuit2::SetInitialGradient(const ROOT::Math::IBaseFunctionMultiDim *function, const std::vector<ROOT::Fit::ParameterSettings> &parameters, std::vector<MinuitDerivatorElement>& gradient) { // set an initial gradient using some given steps // (used in the first iteration) assert(function != nullptr && "function is a nullptr"); double eps2 = precision.Eps2(); unsigned ix = 0; for (auto parameter = parameters.begin(); parameter != parameters.end(); ++parameter, ++ix) { // What Minuit2 calls "Error" is stepsize on the ROOT side. double werr = parameter->StepSize(); // Actually, sav in Minuit2 is the external parameter value, so that is // what we called var before and var is unnecessary here. double sav = parameter->Value(); // However, we do need var below, so let's calculate it using Ext2int: double var = Ext2int(*parameter, sav); if (_always_exactly_mimic_minuit2) { // this transformation can lose a few bits, but Minuit2 does it too sav = Int2ext(*parameter, var); } double sav2 = sav + werr; if (parameter->HasUpperLimit() && sav2 > parameter->UpperLimit()) { sav2 = parameter->UpperLimit(); } double var2 = Ext2int(*parameter, sav2); double vplu = var2 - var; sav2 = sav - werr; if (parameter->HasLowerLimit() && sav2 < parameter->LowerLimit()) { sav2 = parameter->LowerLimit(); } var2 = Ext2int(*parameter, sav2); double vmin = var2 - var; double gsmin = 8. * eps2 * (fabs(var) + eps2); // protect against very small step sizes which can cause dirin to zero and then nan values in grd double dirin = std::max(0.5 * (fabs(vplu) + fabs(vmin)), gsmin); double g2 = 2.0 * Up / (dirin * dirin); double gstep = std::max(gsmin, 0.1 * dirin); double grd = g2 * dirin; if (parameter->IsBound()) { if (gstep > 0.5) gstep = 0.5; } gradient[ix].derivative = grd; gradient[ix].second_derivative = g2; gradient[ix].step_size = gstep; } } bool NumericalDerivatorMinuit2::always_exactly_mimic_minuit2() const { return _always_exactly_mimic_minuit2; }; void NumericalDerivatorMinuit2::set_always_exactly_mimic_minuit2(bool flag) { _always_exactly_mimic_minuit2 = flag; } void NumericalDerivatorMinuit2::set_step_tolerance(double step_tolerance) { fStepTolerance = step_tolerance; } void NumericalDerivatorMinuit2::set_grad_tolerance(double grad_tolerance) { fGradTolerance = grad_tolerance; } void NumericalDerivatorMinuit2::set_ncycles(unsigned int ncycles) { fNCycles = ncycles; } void NumericalDerivatorMinuit2::set_error_level(double error_level) { Up = error_level; } std::ostream& operator<<(std::ostream& out, const MinuitDerivatorElement value){ return out << "(derivative: " << value.derivative << ", second_derivative: " << value.second_derivative << ", step_size: " << value.step_size << ")"; } } // namespace RooFit <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2675 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1569377 by johtaylo@johtaylo-jtincrementor2-increment on 2018/06/17 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2676 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2596 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1518662 by johtaylo@johtaylo-jtincrementor2-increment on 2018/02/23 03:00:05<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2597 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2765 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1624840 by chui@ocl-promo-incrementor on 2018/10/27 03:00:36<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2766 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>#include <assert.h> #include <errno.h> #include <iostream> #include <new> #include <sstream> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <core/CHIPError.h> #include <inet/InetLayer.h> #include <inet/UDPEndPoint.h> #include <support/CHIPLogging.h> #include <support/CodeUtils.h> #include <support/ErrorStr.h> #include <controller/CHIPDeviceController.h> extern "C" { #include "chip-zcl/chip-zcl.h" #include "gen/gen-cluster-id.h" #include "gen/gen-command-id.h" #include "gen/gen-types.h" } // extern "C" // Delay, in seconds, between sends for the echo case. #define SEND_DELAY 5 using namespace ::chip; using namespace ::chip::Inet; static const char * PAYLOAD = "Message from Standalone CHIP echo client!"; // Device Manager Callbacks static void EchoResponse(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState, System::PacketBuffer * buffer, const IPPacketInfo * packet_info) { char src_addr[INET_ADDRSTRLEN]; char dest_addr[INET_ADDRSTRLEN]; size_t data_len = buffer->DataLength(); packet_info->SrcAddress.ToString(src_addr, sizeof(src_addr)); packet_info->DestAddress.ToString(dest_addr, sizeof(dest_addr)); printf("UDP packet received from %s:%u to %s:%u (%zu bytes)\n", src_addr, packet_info->SrcPort, dest_addr, packet_info->DestPort, static_cast<size_t>(buffer->DataLength())); // attempt to print the incoming message char msg_buffer[data_len]; msg_buffer[data_len] = 0; // Null-terminate whatever we received and treat like a string... memcpy(msg_buffer, buffer->Start(), data_len); int compare = strncmp(msg_buffer, PAYLOAD, data_len); if (compare == 0) { printf("Got expected Message...\n"); } else { printf("Didn't get the expected Echo. Compare: %d\n", compare); printf("\nSend: %s \nRecv: %s\n", PAYLOAD, msg_buffer); } System::PacketBuffer::Free(buffer); } static void ReceiveError(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState, CHIP_ERROR error, const IPPacketInfo * pi) { printf("ERROR: %s\n Got UDP error\n", ErrorStr(error)); } void ShowUsage(const char * executable) { fprintf(stderr, "Usage: \n" " %s device-ip-address device-port echo|off|on|toggle\n", executable); } bool DetermineAddress(int argc, char * argv[], IPAddress * hostAddr, uint16_t * port) { if (argc < 3) { return false; } if (!IPAddress::FromString(argv[1], *hostAddr)) { fputs("Error: Invalid device IP address", stderr); return false; } std::string port_str(argv[2]); std::stringstream ss(port_str); ss >> *port; if (ss.fail() || !ss.eof()) { fputs("Error: Invalid device port", stderr); return false; } return true; } enum class Command { Off, On, Toggle, Echo, }; template <int N> bool EqualsLiteral(const char * str, const char (&literal)[N]) { return strncmp(str, literal, N) == 0; } bool DetermineCommand(int argc, char * argv[], Command * command) { if (argc < 4) { return false; } if (EqualsLiteral(argv[3], "off")) { *command = Command::Off; return true; } if (EqualsLiteral(argv[3], "on")) { *command = Command::On; return true; } if (EqualsLiteral(argv[3], "toggle")) { *command = Command::Toggle; return true; } if (EqualsLiteral(argv[3], "echo")) { *command = Command::Echo; return true; } fprintf(stderr, "Unknown command: %s\n", argv[3]); return false; } // Handle the echo case, where we just send a string and expect to get it back. void DoEcho(DeviceController::ChipDeviceController * controller, const IPAddress & host_addr, uint16_t port) { size_t payload_len = strlen(PAYLOAD); auto * buffer = System::PacketBuffer::NewWithAvailableSize(payload_len); snprintf((char *) buffer->Start(), payload_len + 1, "%s", PAYLOAD); buffer->SetDataLength(payload_len); // Run the client char host_ip_str[40]; host_addr.ToString(host_ip_str, sizeof(host_ip_str)); while (1) { // Send calls release on this buffer, so bump up the ref because we want to reuse it buffer->AddRef(); controller->SendMessage(NULL, buffer); printf("Msg sent to server at %s:%d\n", host_ip_str, port); controller->ServiceEvents(); sleep(SEND_DELAY); } } // Handle the on/off/toggle case, where we are sending a ZCL command and not // expecting a response at all. void DoOnOff(DeviceController::ChipDeviceController * controller, Command command) { ChipZclCommandId_t zclCommand; switch (command) { case Command::Off: zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_OFF; break; case Command::On: zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_ON; break; case Command::Toggle: zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_TOGGLE; break; default: fprintf(stderr, "Unknown command: %d\n", command); return; } // Make sure our buffer is big enough, but this will need a better setup! static const size_t bufferSize = 1024; auto * buffer = System::PacketBuffer::NewWithAvailableSize(bufferSize); ChipZclBuffer_t * zcl_buffer = (ChipZclBuffer_t *) buffer; ChipZclCommandContext_t ctx = { 1, // endpointId CHIP_ZCL_CLUSTER_ON_OFF, // clusterId true, // clusterSpecific false, // mfgSpecific 0, // mfgCode zclCommand, // commandId ZCL_DIRECTION_CLIENT_TO_SERVER, // direction 0, // payloadStartIndex nullptr, // request nullptr // response }; chipZclEncodeZclHeader(zcl_buffer, &ctx); const size_t data_len = chipZclBufferDataLength(zcl_buffer); #ifdef DEBUG fprintf(stderr, "SENDING: %zu ", data_len); for (size_t i = 0; i < data_len; ++i) { fprintf(stderr, "%d ", chipZclBufferPointer(zcl_buffer)[i]); } fprintf(stderr, "\n"); #endif controller->SendMessage(NULL, buffer); controller->ServiceEvents(); } // ================================================================================ // Main Code // ================================================================================ int main(int argc, char * argv[]) { IPAddress host_addr; uint16_t port; Command command; if (!DetermineAddress(argc, argv, &host_addr, &port) || !DetermineCommand(argc, argv, &command)) { ShowUsage(argv[0]); return -1; } auto * controller = new DeviceController::ChipDeviceController(); controller->Init(); controller->ConnectDevice(1, host_addr, NULL, EchoResponse, ReceiveError, port); if (command == Command::Echo) { DoEcho(controller, host_addr, port); } else { DoOnOff(controller, command); } controller->Shutdown(); delete controller; return 0; } extern "C" { // We have to have this empty callback, because the ZCL code links against it. void chipZclPostAttributeChangeCallback(uint8_t endpoint, ChipZclClusterId clusterId, ChipZclAttributeId attributeId, uint8_t mask, uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value) {} } // extern "C" <commit_msg>Only grab the buffer length if we will use it. (#972)<commit_after>#include <assert.h> #include <errno.h> #include <iostream> #include <new> #include <sstream> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <core/CHIPError.h> #include <inet/InetLayer.h> #include <inet/UDPEndPoint.h> #include <support/CHIPLogging.h> #include <support/CodeUtils.h> #include <support/ErrorStr.h> #include <controller/CHIPDeviceController.h> extern "C" { #include "chip-zcl/chip-zcl.h" #include "gen/gen-cluster-id.h" #include "gen/gen-command-id.h" #include "gen/gen-types.h" } // extern "C" // Delay, in seconds, between sends for the echo case. #define SEND_DELAY 5 using namespace ::chip; using namespace ::chip::Inet; static const char * PAYLOAD = "Message from Standalone CHIP echo client!"; // Device Manager Callbacks static void EchoResponse(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState, System::PacketBuffer * buffer, const IPPacketInfo * packet_info) { char src_addr[INET_ADDRSTRLEN]; char dest_addr[INET_ADDRSTRLEN]; size_t data_len = buffer->DataLength(); packet_info->SrcAddress.ToString(src_addr, sizeof(src_addr)); packet_info->DestAddress.ToString(dest_addr, sizeof(dest_addr)); printf("UDP packet received from %s:%u to %s:%u (%zu bytes)\n", src_addr, packet_info->SrcPort, dest_addr, packet_info->DestPort, static_cast<size_t>(buffer->DataLength())); // attempt to print the incoming message char msg_buffer[data_len]; msg_buffer[data_len] = 0; // Null-terminate whatever we received and treat like a string... memcpy(msg_buffer, buffer->Start(), data_len); int compare = strncmp(msg_buffer, PAYLOAD, data_len); if (compare == 0) { printf("Got expected Message...\n"); } else { printf("Didn't get the expected Echo. Compare: %d\n", compare); printf("\nSend: %s \nRecv: %s\n", PAYLOAD, msg_buffer); } System::PacketBuffer::Free(buffer); } static void ReceiveError(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState, CHIP_ERROR error, const IPPacketInfo * pi) { printf("ERROR: %s\n Got UDP error\n", ErrorStr(error)); } void ShowUsage(const char * executable) { fprintf(stderr, "Usage: \n" " %s device-ip-address device-port echo|off|on|toggle\n", executable); } bool DetermineAddress(int argc, char * argv[], IPAddress * hostAddr, uint16_t * port) { if (argc < 3) { return false; } if (!IPAddress::FromString(argv[1], *hostAddr)) { fputs("Error: Invalid device IP address", stderr); return false; } std::string port_str(argv[2]); std::stringstream ss(port_str); ss >> *port; if (ss.fail() || !ss.eof()) { fputs("Error: Invalid device port", stderr); return false; } return true; } enum class Command { Off, On, Toggle, Echo, }; template <int N> bool EqualsLiteral(const char * str, const char (&literal)[N]) { return strncmp(str, literal, N) == 0; } bool DetermineCommand(int argc, char * argv[], Command * command) { if (argc < 4) { return false; } if (EqualsLiteral(argv[3], "off")) { *command = Command::Off; return true; } if (EqualsLiteral(argv[3], "on")) { *command = Command::On; return true; } if (EqualsLiteral(argv[3], "toggle")) { *command = Command::Toggle; return true; } if (EqualsLiteral(argv[3], "echo")) { *command = Command::Echo; return true; } fprintf(stderr, "Unknown command: %s\n", argv[3]); return false; } // Handle the echo case, where we just send a string and expect to get it back. void DoEcho(DeviceController::ChipDeviceController * controller, const IPAddress & host_addr, uint16_t port) { size_t payload_len = strlen(PAYLOAD); auto * buffer = System::PacketBuffer::NewWithAvailableSize(payload_len); snprintf((char *) buffer->Start(), payload_len + 1, "%s", PAYLOAD); buffer->SetDataLength(payload_len); // Run the client char host_ip_str[40]; host_addr.ToString(host_ip_str, sizeof(host_ip_str)); while (1) { // Send calls release on this buffer, so bump up the ref because we want to reuse it buffer->AddRef(); controller->SendMessage(NULL, buffer); printf("Msg sent to server at %s:%d\n", host_ip_str, port); controller->ServiceEvents(); sleep(SEND_DELAY); } } // Handle the on/off/toggle case, where we are sending a ZCL command and not // expecting a response at all. void DoOnOff(DeviceController::ChipDeviceController * controller, Command command) { ChipZclCommandId_t zclCommand; switch (command) { case Command::Off: zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_OFF; break; case Command::On: zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_ON; break; case Command::Toggle: zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_TOGGLE; break; default: fprintf(stderr, "Unknown command: %d\n", command); return; } // Make sure our buffer is big enough, but this will need a better setup! static const size_t bufferSize = 1024; auto * buffer = System::PacketBuffer::NewWithAvailableSize(bufferSize); ChipZclBuffer_t * zcl_buffer = (ChipZclBuffer_t *) buffer; ChipZclCommandContext_t ctx = { 1, // endpointId CHIP_ZCL_CLUSTER_ON_OFF, // clusterId true, // clusterSpecific false, // mfgSpecific 0, // mfgCode zclCommand, // commandId ZCL_DIRECTION_CLIENT_TO_SERVER, // direction 0, // payloadStartIndex nullptr, // request nullptr // response }; chipZclEncodeZclHeader(zcl_buffer, &ctx); #ifdef DEBUG const size_t data_len = chipZclBufferDataLength(zcl_buffer); fprintf(stderr, "SENDING: %zu ", data_len); for (size_t i = 0; i < data_len; ++i) { fprintf(stderr, "%d ", chipZclBufferPointer(zcl_buffer)[i]); } fprintf(stderr, "\n"); #endif controller->SendMessage(NULL, buffer); controller->ServiceEvents(); } // ================================================================================ // Main Code // ================================================================================ int main(int argc, char * argv[]) { IPAddress host_addr; uint16_t port; Command command; if (!DetermineAddress(argc, argv, &host_addr, &port) || !DetermineCommand(argc, argv, &command)) { ShowUsage(argv[0]); return -1; } auto * controller = new DeviceController::ChipDeviceController(); controller->Init(); controller->ConnectDevice(1, host_addr, NULL, EchoResponse, ReceiveError, port); if (command == Command::Echo) { DoEcho(controller, host_addr, port); } else { DoOnOff(controller, command); } controller->Shutdown(); delete controller; return 0; } extern "C" { // We have to have this empty callback, because the ZCL code links against it. void chipZclPostAttributeChangeCallback(uint8_t endpoint, ChipZclClusterId clusterId, ChipZclAttributeId attributeId, uint8_t mask, uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value) {} } // extern "C" <|endoftext|>
<commit_before>#include <windows.h> #include <OvRender.h> #include <sloverlay.h> #include <overlay.h> SlOverlayMenu* MnuMenu; MenuVars MnuOsd[20]; MenuVars MnuCache[10]; WCHAR* GroupOpt[] = {L"", L""}; WCHAR* ItemOpt[] = {L"Off", L"On"}; BOOLEAN MnuInitialized; //Add menu items to menu VOID AddItems() { MnuMenu->AddGroup(L"OSD", GroupOpt, &MnuOsd[0].Var); if (MnuOsd[0].Var) { MnuMenu->AddItem(L"GPU Core utilization", ItemOpt, &MnuOsd[1].Var); MnuMenu->AddItem(L"GPU Core temperature", ItemOpt, &MnuOsd[2].Var); MnuMenu->AddItem(L"GPU Engine Clock", ItemOpt, &MnuOsd[3].Var); MnuMenu->AddItem(L"GPU Memory Clock", ItemOpt, &MnuOsd[4].Var); MnuMenu->AddItem(L"GPU VRAM usage", ItemOpt, &MnuOsd[5].Var); MnuMenu->AddItem(L"CPU utilization", ItemOpt, &MnuOsd[6].Var); MnuMenu->AddItem(L"CPU temperature", ItemOpt, &MnuOsd[7].Var); MnuMenu->AddItem(L"RAM usage", ItemOpt, &MnuOsd[8].Var); MnuMenu->AddItem(L"Max core usage", ItemOpt, &MnuOsd[9].Var); MnuMenu->AddItem(L"Max thread usage", ItemOpt, &MnuOsd[10].Var); MnuMenu->AddItem(L"Disk read-write rate", ItemOpt, &MnuOsd[11].Var); MnuMenu->AddItem(L"Disk response time", ItemOpt, &MnuOsd[12].Var); MnuMenu->AddItem(L"Frame Buffer count", ItemOpt, &MnuOsd[13].Var); MnuMenu->AddItem(L"Show Time", ItemOpt, &MnuOsd[14].Var); } MnuMenu->AddGroup(L"CACHE", GroupOpt, &MnuCache[0].Var); if (MnuCache[0].Var) { MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[1].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[2].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[3].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[4].Var); } } VOID ProcessOptions() { if (MnuOsd[1].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_LOAD; /*else PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/ //this needs to be fixed, if it was enable by main gui //checkbox then it'll get disabled. too lazy... if (MnuOsd[2].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_TEMP; if (MnuOsd[3].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; if (MnuOsd[4].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; if (MnuOsd[9].Var > 0) PushSharedMemory->OSDFlags |= OSD_MCU; if (MnuOsd[10].Var > 0) PushSharedMemory->OSDFlags |= OSD_MTU; if (MnuOsd[14].Var > 0) PushSharedMemory->OSDFlags |= OSD_TIME; } VOID MnuRender( OvOverlay* Overlay ) { if (!MnuInitialized) { MnuMenu = new SlOverlayMenu(300); MnuInitialized = TRUE; } if( MnuMenu->mSet.MaxItems == 0 ) AddItems(); //Call drawing and navigation functions MnuMenu->Render(100, 200, Overlay); ProcessOptions(); } <commit_msg>fixed in-game cpu temp toggling<commit_after>#include <windows.h> #include <OvRender.h> #include <sloverlay.h> #include <overlay.h> SlOverlayMenu* MnuMenu; MenuVars MnuOsd[20]; MenuVars MnuCache[10]; WCHAR* GroupOpt[] = {L"", L""}; WCHAR* ItemOpt[] = {L"Off", L"On"}; BOOLEAN MnuInitialized; //Add menu items to menu VOID AddItems() { MnuMenu->AddGroup(L"OSD", GroupOpt, &MnuOsd[0].Var); if (MnuOsd[0].Var) { MnuMenu->AddItem(L"GPU Core utilization", ItemOpt, &MnuOsd[1].Var); MnuMenu->AddItem(L"GPU Core temperature", ItemOpt, &MnuOsd[2].Var); MnuMenu->AddItem(L"GPU Engine Clock", ItemOpt, &MnuOsd[3].Var); MnuMenu->AddItem(L"GPU Memory Clock", ItemOpt, &MnuOsd[4].Var); MnuMenu->AddItem(L"GPU VRAM usage", ItemOpt, &MnuOsd[5].Var); MnuMenu->AddItem(L"CPU utilization", ItemOpt, &MnuOsd[6].Var); MnuMenu->AddItem(L"CPU temperature", ItemOpt, &MnuOsd[7].Var); MnuMenu->AddItem(L"RAM usage", ItemOpt, &MnuOsd[8].Var); MnuMenu->AddItem(L"Max core usage", ItemOpt, &MnuOsd[9].Var); MnuMenu->AddItem(L"Max thread usage", ItemOpt, &MnuOsd[10].Var); MnuMenu->AddItem(L"Disk read-write rate", ItemOpt, &MnuOsd[11].Var); MnuMenu->AddItem(L"Disk response time", ItemOpt, &MnuOsd[12].Var); MnuMenu->AddItem(L"Frame Buffer count", ItemOpt, &MnuOsd[13].Var); MnuMenu->AddItem(L"Show Time", ItemOpt, &MnuOsd[14].Var); } MnuMenu->AddGroup(L"CACHE", GroupOpt, &MnuCache[0].Var); if (MnuCache[0].Var) { MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[1].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[2].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[3].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MnuCache[4].Var); } } VOID ProcessOptions() { if (MnuOsd[1].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_LOAD; /*else PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/ //this needs to be fixed, if it was enable by main gui //checkbox then it'll get disabled. too lazy... if (MnuOsd[2].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_TEMP; if (MnuOsd[3].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; if (MnuOsd[4].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; if (MnuOsd[7].Var > 0) PushSharedMemory->OSDFlags |= OSD_CPU_TEMP; if (MnuOsd[9].Var > 0) PushSharedMemory->OSDFlags |= OSD_MCU; if (MnuOsd[10].Var > 0) PushSharedMemory->OSDFlags |= OSD_MTU; if (MnuOsd[14].Var > 0) PushSharedMemory->OSDFlags |= OSD_TIME; } VOID MnuRender( OvOverlay* Overlay ) { if (!MnuInitialized) { MnuMenu = new SlOverlayMenu(300); MnuInitialized = TRUE; } if( MnuMenu->mSet.MaxItems == 0 ) AddItems(); //Call drawing and navigation functions MnuMenu->Render(100, 200, Overlay); ProcessOptions(); } <|endoftext|>
<commit_before>#include <windows.h> #include <OvRender.h> #include <sloverlay.h> #include <overlay.h> SlOverlayMenu* MnuMenu; MenuVars MenuOsd[20]; MenuVars MenuGpu[10]; WCHAR* GroupOpt[] = {L"", L""}; WCHAR* ItemOpt[] = {L"Off", L"On"}; BOOLEAN MnuInitialized; HANDLE MenuProcessHeap; //Add menu items to menu VOID AddItems() { MnuMenu->AddGroup(L"OSD", GroupOpt, &MenuOsd[0].Var); if (MenuOsd[0].Var) { MnuMenu->AddItem(L"GPU Core utilization", ItemOpt, &MenuOsd[1].Var); MnuMenu->AddItem(L"GPU Core temperature", ItemOpt, &MenuOsd[2].Var); MnuMenu->AddItem(L"GPU Engine Clock", ItemOpt, &MenuOsd[3].Var); MnuMenu->AddItem(L"GPU Memory Clock", ItemOpt, &MenuOsd[4].Var); MnuMenu->AddItem(L"GPU VRAM usage", ItemOpt, &MenuOsd[5].Var); MnuMenu->AddItem(L"CPU utilization", ItemOpt, &MenuOsd[6].Var); MnuMenu->AddItem(L"CPU temperature", ItemOpt, &MenuOsd[7].Var); MnuMenu->AddItem(L"RAM usage", ItemOpt, &MenuOsd[8].Var); MnuMenu->AddItem(L"Max core usage", ItemOpt, &MenuOsd[9].Var); MnuMenu->AddItem(L"Max thread usage", ItemOpt, &MenuOsd[10].Var); MnuMenu->AddItem(L"Disk read-write rate", ItemOpt, &MenuOsd[11].Var); MnuMenu->AddItem(L"Disk response time", ItemOpt, &MenuOsd[12].Var); MnuMenu->AddItem(L"Frame Buffer count", ItemOpt, &MenuOsd[13].Var); MnuMenu->AddItem(L"Show Time", ItemOpt, &MenuOsd[14].Var); } MnuMenu->AddGroup(L"GPU", GroupOpt, &MenuGpu[0].Var); if (MenuGpu[0].Var) { MnuMenu->AddItem(L"Force Max Clocks", ItemOpt, &MenuGpu[1].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MenuGpu[2].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MenuGpu[3].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MenuGpu[4].Var); } } VOID ProcessOptions() { if (MenuOsd[1].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_LOAD; /*else PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/ //this needs to be fixed, if it was enable by main gui //checkbox then it'll get disabled. too lazy... if (MenuOsd[2].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_TEMP; if (MenuOsd[3].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; if (MenuOsd[4].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; if (MenuOsd[7].Var > 0) PushSharedMemory->OSDFlags |= OSD_CPU_TEMP; if (MenuOsd[8].Var > 0) PushSharedMemory->OSDFlags |= OSD_RAM; if (MenuOsd[9].Var > 0) PushSharedMemory->OSDFlags |= OSD_MCU; if (MenuOsd[10].Var > 0) PushSharedMemory->OSDFlags |= OSD_MTU; if (MenuOsd[11].Var > 0) PushSharedMemory->OSDFlags |= OSD_DISK_RWRATE; if (MenuOsd[12].Var > 0) PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE; if (MenuOsd[14].Var > 0) PushSharedMemory->OSDFlags |= OSD_TIME; if (MenuGpu[1].Var > 0) { HANDLE hPipe; DWORD dwWritten; WCHAR command[] = L"ForceMaxClocks"; hPipe = CreateFile(TEXT("\\\\.\\pipe\\Push"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe != INVALID_HANDLE_VALUE) { WriteFile(hPipe, command, sizeof(command), &dwWritten, NULL); CloseHandle(hPipe); } } } VOID MnuRender( OvOverlay* Overlay ) { if (!MnuInitialized) { MnuMenu = new SlOverlayMenu(300); MnuInitialized = TRUE; } if( MnuMenu->mSet.MaxItems == 0 ) AddItems(); //Call drawing and navigation functions MnuMenu->Render(100, 200, Overlay); } #define GROUP 1 #define ITEM 2 #define HEIGHT 16 DWORD LightBlue = 0xFF4DD0EB; DWORD Green = 0xFF33FF00; DWORD White = 0xFFE6E6E6; DWORD Blue = 0xFF00A4C5; WNDPROC OldWNDPROC; SlOverlayMenu* OvmMenu; VOID MenuKeyboardHook( WPARAM Key ) { if (!OvmMenu) return; if (Key == VK_INSERT || Key == VK_UP || Key == VK_DOWN || Key == VK_LEFT || Key == VK_RIGHT) { switch (Key) { case VK_INSERT: OvmMenu->mSet.Show = !OvmMenu->mSet.Show; break; case VK_UP: { if (!OvmMenu->mSet.Show) break; OvmMenu->mSet.SeletedIndex--; if (OvmMenu->mSet.SeletedIndex < 0) OvmMenu->mSet.SeletedIndex = OvmMenu->mSet.MaxItems - 1; } break; case VK_DOWN: { if (!OvmMenu->mSet.Show) break; OvmMenu->mSet.SeletedIndex++; if (OvmMenu->mSet.SeletedIndex == OvmMenu->mSet.MaxItems) OvmMenu->mSet.SeletedIndex = 0; } break; case VK_LEFT: { if (!OvmMenu->mSet.Show) break; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var > 0) { *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += -1; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP) OvmMenu->mSet.MaxItems = 0; } } break; case VK_RIGHT: { if (!OvmMenu->mSet.Show) break; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var < (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].MaxValue - 1)) { *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += 1; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP) OvmMenu->mSet.MaxItems = 0; } } break; } // Update osd items. ProcessOptions(); } } SlOverlayMenu::SlOverlayMenu( int OptionsX ) { OpX = OptionsX; mSet.Show = FALSE; mSet.MaxItems = 0; mSet.SeletedIndex = 0; OvmMenu = this; MenuProcessHeap = GetProcessHeap(); } void SlOverlayMenu::AddItemToMenu(WCHAR* Title, WCHAR** Options, int* Var, int MaxValue, int Type) { Items[mSet.MaxItems].Title = Title; Items[mSet.MaxItems].Options= Options; Items[mSet.MaxItems].Var = Var; Items[mSet.MaxItems].MaxValue = MaxValue; Items[mSet.MaxItems].Type = Type; mSet.MaxItems++; } VOID SlOverlayMenu::Render( int X, int Y, OvOverlay* Overlay ) { DWORD ColorOne, ColorTwo; int ValueOne, ValueTwo; if (!mSet.Show) return; for (int i = 0; i < mSet.MaxItems; i++) { ValueOne = (Items[i].Var) ? (*Items[i].Var) : 0; ValueTwo = (Items[i].Var) ? (*Items[i].Var) : 0; if (i == mSet.SeletedIndex) { ColorOne = LightBlue; ColorTwo = (ValueTwo) ? Green : White; } else if (Items[i].Type == GROUP) { ColorOne = Blue; ColorTwo = Blue; } else { ColorOne = (ValueOne) ? White : White; ColorTwo = (ValueTwo) ? Green : White; } if (Items[i].Type == GROUP) Overlay->DrawText(Items[i].Title, X, Y, ColorOne); if (Items[i].Type == ITEM) Overlay->DrawText(Items[i].Title, X + 20, Y, ColorOne); if (Items[i].Options) Overlay->DrawText(Items[i].Options[ValueTwo], OpX, Y, ColorTwo); Y += HEIGHT; } } <commit_msg>do some magic<commit_after>#include <windows.h> #include <OvRender.h> #include <sloverlay.h> #include <overlay.h> SlOverlayMenu* MnuMenu; MenuVars MenuOsd[20]; MenuVars MenuGpu[10]; WCHAR* GroupOpt[] = {L"", L""}; WCHAR* ItemOpt[] = {L"Off", L"On"}; BOOLEAN MnuInitialized; HANDLE MenuProcessHeap; //Add menu items to menu VOID AddItems() { MnuMenu->AddGroup(L"OSD", GroupOpt, &MenuOsd[0].Var); if (MenuOsd[0].Var) { MnuMenu->AddItem(L"GPU Core utilization", ItemOpt, &MenuOsd[1].Var); MnuMenu->AddItem(L"GPU Core temperature", ItemOpt, &MenuOsd[2].Var); MnuMenu->AddItem(L"GPU Engine Clock", ItemOpt, &MenuOsd[3].Var); MnuMenu->AddItem(L"GPU Memory Clock", ItemOpt, &MenuOsd[4].Var); MnuMenu->AddItem(L"GPU VRAM usage", ItemOpt, &MenuOsd[5].Var); MnuMenu->AddItem(L"CPU utilization", ItemOpt, &MenuOsd[6].Var); MnuMenu->AddItem(L"CPU temperature", ItemOpt, &MenuOsd[7].Var); MnuMenu->AddItem(L"RAM usage", ItemOpt, &MenuOsd[8].Var); MnuMenu->AddItem(L"Max core usage", ItemOpt, &MenuOsd[9].Var); MnuMenu->AddItem(L"Max thread usage", ItemOpt, &MenuOsd[10].Var); MnuMenu->AddItem(L"Disk read-write rate", ItemOpt, &MenuOsd[11].Var); MnuMenu->AddItem(L"Disk response time", ItemOpt, &MenuOsd[12].Var); MnuMenu->AddItem(L"Frame Buffer count", ItemOpt, &MenuOsd[13].Var); MnuMenu->AddItem(L"Show Time", ItemOpt, &MenuOsd[14].Var); } MnuMenu->AddGroup(L"GPU", GroupOpt, &MenuGpu[0].Var); if (MenuGpu[0].Var) { MnuMenu->AddItem(L"Force Max Clocks", ItemOpt, &MenuGpu[1].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MenuGpu[2].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MenuGpu[3].Var); MnuMenu->AddItem(L"NULL", ItemOpt, &MenuGpu[4].Var); } } VOID ProcessOptions() { if (MenuOsd[1].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_LOAD; /*else PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*/ //this needs to be fixed, if it was enable by main gui //checkbox then it'll get disabled. too lazy... if (MenuOsd[2].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_TEMP; if (MenuOsd[3].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; if (MenuOsd[4].Var > 0) PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; if (MenuOsd[7].Var > 0) PushSharedMemory->OSDFlags |= OSD_CPU_TEMP; if (MenuOsd[8].Var > 0) PushSharedMemory->OSDFlags |= OSD_RAM; if (MenuOsd[9].Var > 0) PushSharedMemory->OSDFlags |= OSD_MCU; if (MenuOsd[10].Var > 0) PushSharedMemory->OSDFlags |= OSD_MTU; if (MenuOsd[11].Var > 0) PushSharedMemory->OSDFlags |= OSD_DISK_RWRATE; if (MenuOsd[12].Var > 0) PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE; if (MenuOsd[14].Var > 0) PushSharedMemory->OSDFlags |= OSD_TIME; if (MenuGpu[1].Var > 0) { HANDLE hPipe; DWORD dwWritten; WCHAR command[] = L"ForceMaxClocks"; hPipe = CreateFile(TEXT("\\\\.\\pipe\\Push"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe != INVALID_HANDLE_VALUE) { WriteFile(hPipe, command, sizeof(command), &dwWritten, NULL); CloseHandle(hPipe); } PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; PushSharedMemory->Overloads &= ~OSD_GPU_E_CLK; PushSharedMemory->Overloads &= ~OSD_GPU_M_CLK; } } VOID MnuRender( OvOverlay* Overlay ) { if (!MnuInitialized) { MnuMenu = new SlOverlayMenu(300); MnuInitialized = TRUE; } if( MnuMenu->mSet.MaxItems == 0 ) AddItems(); //Call drawing and navigation functions MnuMenu->Render(100, 200, Overlay); } #define GROUP 1 #define ITEM 2 #define HEIGHT 16 DWORD LightBlue = 0xFF4DD0EB; DWORD Green = 0xFF33FF00; DWORD White = 0xFFE6E6E6; DWORD Blue = 0xFF00A4C5; WNDPROC OldWNDPROC; SlOverlayMenu* OvmMenu; VOID MenuKeyboardHook( WPARAM Key ) { if (!OvmMenu) return; if (Key == VK_INSERT || Key == VK_UP || Key == VK_DOWN || Key == VK_LEFT || Key == VK_RIGHT) { switch (Key) { case VK_INSERT: OvmMenu->mSet.Show = !OvmMenu->mSet.Show; break; case VK_UP: { if (!OvmMenu->mSet.Show) break; OvmMenu->mSet.SeletedIndex--; if (OvmMenu->mSet.SeletedIndex < 0) OvmMenu->mSet.SeletedIndex = OvmMenu->mSet.MaxItems - 1; } break; case VK_DOWN: { if (!OvmMenu->mSet.Show) break; OvmMenu->mSet.SeletedIndex++; if (OvmMenu->mSet.SeletedIndex == OvmMenu->mSet.MaxItems) OvmMenu->mSet.SeletedIndex = 0; } break; case VK_LEFT: { if (!OvmMenu->mSet.Show) break; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var > 0) { *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += -1; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP) OvmMenu->mSet.MaxItems = 0; } } break; case VK_RIGHT: { if (!OvmMenu->mSet.Show) break; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var < (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].MaxValue - 1)) { *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += 1; if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP) OvmMenu->mSet.MaxItems = 0; } } break; } // Update osd items. ProcessOptions(); } } SlOverlayMenu::SlOverlayMenu( int OptionsX ) { OpX = OptionsX; mSet.Show = FALSE; mSet.MaxItems = 0; mSet.SeletedIndex = 0; OvmMenu = this; MenuProcessHeap = GetProcessHeap(); } void SlOverlayMenu::AddItemToMenu(WCHAR* Title, WCHAR** Options, int* Var, int MaxValue, int Type) { Items[mSet.MaxItems].Title = Title; Items[mSet.MaxItems].Options= Options; Items[mSet.MaxItems].Var = Var; Items[mSet.MaxItems].MaxValue = MaxValue; Items[mSet.MaxItems].Type = Type; mSet.MaxItems++; } VOID SlOverlayMenu::Render( int X, int Y, OvOverlay* Overlay ) { DWORD ColorOne, ColorTwo; int ValueOne, ValueTwo; if (!mSet.Show) return; for (int i = 0; i < mSet.MaxItems; i++) { ValueOne = (Items[i].Var) ? (*Items[i].Var) : 0; ValueTwo = (Items[i].Var) ? (*Items[i].Var) : 0; if (i == mSet.SeletedIndex) { ColorOne = LightBlue; ColorTwo = (ValueTwo) ? Green : White; } else if (Items[i].Type == GROUP) { ColorOne = Blue; ColorTwo = Blue; } else { ColorOne = (ValueOne) ? White : White; ColorTwo = (ValueTwo) ? Green : White; } if (Items[i].Type == GROUP) Overlay->DrawText(Items[i].Title, X, Y, ColorOne); if (Items[i].Type == ITEM) Overlay->DrawText(Items[i].Title, X + 20, Y, ColorOne); if (Items[i].Options) Overlay->DrawText(Items[i].Options[ValueTwo], OpX, Y, ColorTwo); Y += HEIGHT; } } <|endoftext|>
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include <granary/granary.h> using namespace granary; GRANARY_DEFINE_bool(count_execs, false, "Count the number of times each block is executed. This option is only " "meaningful for static instrumentation. By default, `count_bbs` does not " "count the number of executions of each basic block."); namespace { // Runtime block execution counter. class BlockCounter : public MutableMetaData<BlockCounter> { public: BlockCounter(void) : count(0) {} uint64_t count; }; // Records the static number of basic blocks. This could be an underestimation // of the total number of basic blocks in the instrumented binary, but an // overestimate of the total number of *distinct* basic blocks instrumented // (because of race conditions when two threads simultaneously instrument the // same basic block). static std::atomic<uint64_t> NUM_BBS(ATOMIC_VAR_INIT(0)); // Simple tool for static and dynamic basic block counting. class BBCount : public Tool { public: BBCount(void) { if (FLAG_count_execs) { RegisterMetaData<BlockCounter>(); } } virtual ~BBCount(void) = default; virtual void InstrumentBlock(DecodedBasicBlock *bb) { NUM_BBS.fetch_add(1); if (!FLAG_count_execs) { return; } Instruction *insert_instr = bb->FirstInstruction(); // Try to find a good place to insert this instruction such that the // placement is before an instruction that kills the flags (but doesn't // read them). for (auto instr : bb->ReversedAppInstructions()) { if (!IsA<ControlFlowInstruction *>(instr) && instr->WritesConditionCodes() && !instr->ReadsConditionCodes()) { insert_instr = instr; break; } } auto meta = GetMetaData<BlockCounter>(bb); MemoryOperand counter_addr(&(meta->count)); BeginInlineAssembly({&counter_addr}); InlineBefore(insert_instr, "INC m64 %0;"_x86_64); InlineBefore(insert_instr, "MOV r64 %1, m64 %0;" "MOV r64 %2, r64 %1;" "ADD r64 %2, r64 %1;"_x86_64); EndInlineAssembly(); } }; } // namespace // Initialize the `count_bbs` tool. GRANARY_CLIENT_INIT({ RegisterTool<BBCount>("count_bbs"); }) <commit_msg>Removed the fake changes to bbcount that were there for testing frag-local virtual regs. Now switching focus back to watchpoints tool for generalized virtual registers.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */ #include <granary/granary.h> using namespace granary; GRANARY_DEFINE_bool(count_execs, false, "Count the number of times each block is executed. This option is only " "meaningful for static instrumentation. By default, `count_bbs` does not " "count the number of executions of each basic block."); namespace { // Runtime block execution counter. class BlockCounter : public MutableMetaData<BlockCounter> { public: BlockCounter(void) : count(0) {} uint64_t count; }; // Records the static number of basic blocks. This could be an underestimation // of the total number of basic blocks in the instrumented binary, but an // overestimate of the total number of *distinct* basic blocks instrumented // (because of race conditions when two threads simultaneously instrument the // same basic block). static std::atomic<uint64_t> NUM_BBS(ATOMIC_VAR_INIT(0)); // Simple tool for static and dynamic basic block counting. class BBCount : public Tool { public: BBCount(void) { if (FLAG_count_execs) { RegisterMetaData<BlockCounter>(); } } virtual ~BBCount(void) = default; virtual void InstrumentBlock(DecodedBasicBlock *bb) { NUM_BBS.fetch_add(1); if (!FLAG_count_execs) { return; } Instruction *insert_instr = bb->FirstInstruction(); // Try to find a good place to insert this instruction such that the // placement is before an instruction that kills the flags (but doesn't // read them). for (auto instr : bb->ReversedAppInstructions()) { if (!IsA<ControlFlowInstruction *>(instr) && instr->WritesConditionCodes() && !instr->ReadsConditionCodes()) { insert_instr = instr; break; } } // Now that we have an insertion spot (either first instruction, or before // and instruction that kills the flags), go and insert the increment to // the block-specific execution counter. auto meta = GetMetaData<BlockCounter>(bb); MemoryOperand counter_addr(&(meta->count)); BeginInlineAssembly({&counter_addr}); InlineBefore(insert_instr, "INC m64 %0;"_x86_64); EndInlineAssembly(); } }; } // namespace // Initialize the `count_bbs` tool. GRANARY_CLIENT_INIT({ RegisterTool<BBCount>("count_bbs"); }) <|endoftext|>
<commit_before>/* wx_twitter_notebook - An GUI widgets for Twitter * * Copyright (C) 2015 Hiroyuki Nagata * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program 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 General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Contributor: * Hiroyuki Nagata <[email protected]> */ #include <fstream> #include <wx/dir.h> #include <wx/textdlg.h> #include "wx/wx_twitter_notebook.hpp" // バージョン static const std::string THIS_VERSION = "PACKAGE_VERSION"; // 設定ファイル保存先 static const wxString DEFAULT_AUTH_FILE = wxT(".authkey_"); static const wxString APP_DIR = wxT(".ctw"); static const wxString DEFAULT_SETTING_FILE = wxT("ctwrc"); wxString wxTwitterNotebook::AP_COMSUMER_KEY = wxEmptyString; wxString wxTwitterNotebook::AP_COMSUMER_SECRET = wxEmptyString; /** * ログ出力用に使用するウィジェットを登録する * * @param wxTextCtrl* ログ出力ウィジェット */ void wxTwitterNotebook::SetLoggingTextCtrl(wxTextCtrl* logging) { this->log = logging; } /** * cmdline_twitterが出力するファイルを格納するディレクトリを指定する * "指定したディレクトリ" / .ctw 以下が対象となる * * @param const wxString& ファイルを格納するディレクトリ */ void wxTwitterNotebook::SetAppDir(const wxString& dir) { // dir = "~/" なので、その内部に ".ctw" というディレクトリを作成する this->appDir = dir + wxFILE_SEP_PATH + APP_DIR; } void wxTwitterNotebook::SetComsumerPair(const wxString& key,const wxString& sec) { AP_COMSUMER_KEY = key; AP_COMSUMER_SECRET = sec; } /** * cmdline_twitterが出力するファイルを格納するディレクトリを取得する * ディレクトリが存在しなければ作成する * * @return const wxString ファイルを格納するディレクトリ */ const wxString wxTwitterNotebook::GetAppDir() { if ( !this->appDir.IsEmpty() && !wxDir::Exists(this->appDir) ) { ::wxMkdir(this->appDir); } return this->appDir; } /** * 初期化処理 */ void wxTwitterNotebook::Initialize() { // このアプリのコンシューマキーなどを設定 client.setComsumerPair(std::string(AP_COMSUMER_KEY.mb_str()), std::string(AP_COMSUMER_SECRET.mb_str())); // 認証 DoAuthentication(); // 設定読み込み ReadSetting(); // ここから先はユーザのアクセスキーが必要 if(!ReadAccessKey()) { return; } //DoWxWidgetsUIMode(); return; } /** * 一連の認証動作を行う */ void wxTwitterNotebook::DoAuthentication() { *log << wxT("Twitterにつなぐ準備中...\n"); std::string rurl, pincode; *log << wxT("認証手続きをしています...\n"); if(!client.Authentication_GetURL(rurl)) { return; } wxString message = wxT("以下のURLにアクセスして認証後、ダイアログにPINを入力してください\n"); message << wxT("(※デフォルトのブラウザを開きます)\n"); message << wxString((const char*)rurl.c_str(), wxConvUTF8); // デフォルトのブラウザを開く ::wxLaunchDefaultBrowser(wxString((const char*)rurl.c_str(), wxConvUTF8)); // PIN 入力用ダイアログ wxTextEntryDialog dlg(this, message, wxT("Twitter - PINコード認証")); dlg.ShowModal(); pincode = std::string(dlg.GetValue().mb_str()); *log << wxT("認証中です...\n"); if(dlg.GetValue().IsEmpty() || !client.Authentication_Finish(pincode)){ *log << wxT("認証に失敗しました。再度認証しなおしてください\n"); return; } *log << wxT("認証に成功しました\n"); wxString fname; std::string key,sec; std::ofstream fout; // ~/.ctw/以下に保存する if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); return; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_AUTH_FILE; client.getUserAccessPair(key,sec); fout.open(fname.mb_str(), std::ios::out); if(! fout.is_open()){ *log << wxT("設定ファイルを開けませんでした。\n"); *log << wxT("再度認証しなおしてください\n"); return; } fout << key; fout << sec; fout.close(); return; } /** * 保存している認証コードを読みこむ */ bool wxTwitterNotebook::ReadAccessKey() { wxString fname; std::string key,sec; std::ifstream fin; // ~/.ctw/以下から読み込みする if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); return false; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_AUTH_FILE; fin.open(fname.mb_str()); if(! fin.is_open()) { *log << wxT("設定ファイルを開けませんでした。\n"); *log << wxT("指定されたエイリアス名が間違っているかもしれません。\n"); return false; } fin >> key; fin >> sec; fin.close(); if(key.empty() || sec.empty()) { *log << wxT("設定ファイルが壊れています。再度認証してください\n"); return false; } client.setUserAccessPair(key,sec); return true; } void wxTwitterNotebook::InitSetting() { setting["READHOME_COUNT"] = minisetting::value(200); setting["READHOME_VIEWRT"] = minisetting::value(true); setting["READHOME_VIEWMENTION"] = minisetting::value(true); setting["READUSER_COUNT"] = minisetting::value(200); setting["READUSER_VIEWRT"] = minisetting::value(true); setting["READUSER_VIEWMENTION"] = minisetting::value(true); setting["READDM_COUNT"] = minisetting::value(200); setting["READLIST_COUNT"] = minisetting::value(200); setting["READLIST_VIEWRT"] = minisetting::value(true); setting["VIEW_SHORT"] = minisetting::value(false); setting["VIEW_SHORT_NAMEONLY"] = minisetting::value(true); setting["VIEW_STATUSID"] = minisetting::value(true); } /** * 設定ファイルの読み込み */ void wxTwitterNotebook::ReadSetting() { using namespace minisetting; wxString fname; std::ifstream fin; InitSetting(); // ~/.ctw/以下から読み込みする if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); *log << wxT("設定ファイルを読み込めませんでした。 \n"); *log << wxT("デフォルトの設定を使用します \n"); return; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_SETTING_FILE; fin.open(fname.mb_str()); if(! fin.is_open()) { *log << wxT("設定ファイルを開けませんでした。\n"); *log << wxT("デフォルトの設定を使用します \n"); WriteSetting(); return; } parse(fin,setting); fin.close(); } /** * 設定ファイルが存在しない場合に新規に作成する */ void wxTwitterNotebook::WriteSetting() { using namespace minisetting; wxString fname; std::ofstream fout; // ~/.ctw/以下に保存する if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); return; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_SETTING_FILE; fout.open(fname.mb_str(),ios::out); if(! fout.is_open()) { return; } // "ホームタイムライン読み込み設定" // "ホームタイムラインの読み込み件数(20-200)" putval(fout,setting,"READHOME_COUNT"); // "ホームタイムラインでRTを表示するかどうか(true false)" putval(fout,setting,"READHOME_VIEWRT"); // "ホームタイムラインで@を表示するかどうか(true false)" putval(fout,setting,"READHOME_VIEWMENTION"); // "ユーザタイムライン読み込み設定" // "ユーザタイムラインの読み込み件数(20-200)" putval(fout,setting,"READUSER_COUNT"); // "ユーザタイムラインでRTを表示するかどうか(true false)" putval(fout,setting,"READUSER_VIEWRT"); // "ユーザタイムラインで@を表示するかどうか(true false)" putval(fout,setting,"READUSER_VIEWMENTION"); // "ダイレクトメッセージ読み込み設定" // "ダイレクトメッセージの読み込み件数(20-200)" putval(fout,setting,"READDM_COUNT"); // "リスト読み込み設定" // "リストタイムラインの読み込み件数(20-200)" putval(fout,setting,"READLIST_COUNT"); // "リストタイムラインでRTを表示するかどうか(true false)" putval(fout,setting,"READLIST_VIEWRT"); // "表示設定" // "短縮表示をおこなうかどうか(true false)" putval(fout,setting,"VIEW_SHORT"); // "短縮表示のとき、名前を登録名(スクリーンネーム以外)にする(true false)" putval(fout,setting,"VIEW_SHORT_NAMEONLY"); // "発言IDの表示をおこなうかどうか(true false)" putval(fout,setting,"VIEW_STATUSID"); fout.close(); } <commit_msg>Some bug fix [skip ci]<commit_after>/* wx_twitter_notebook - An GUI widgets for Twitter * * Copyright (C) 2015 Hiroyuki Nagata * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program 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 General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Contributor: * Hiroyuki Nagata <[email protected]> */ #include <fstream> #include <wx/dir.h> #include <wx/textdlg.h> #include "wx/wx_twitter_notebook.hpp" // バージョン static const std::string THIS_VERSION = "PACKAGE_VERSION"; // 設定ファイル保存先 static const wxString DEFAULT_AUTH_FILE = wxT(".authkey_"); static const wxString APP_DIR = wxT(".ctw"); static const wxString DEFAULT_SETTING_FILE = wxT("ctwrc"); wxString wxTwitterNotebook::AP_COMSUMER_KEY = wxEmptyString; wxString wxTwitterNotebook::AP_COMSUMER_SECRET = wxEmptyString; /** * ログ出力用に使用するウィジェットを登録する * * @param wxTextCtrl* ログ出力ウィジェット */ void wxTwitterNotebook::SetLoggingTextCtrl(wxTextCtrl* logging) { this->log = logging; } /** * cmdline_twitterが出力するファイルを格納するディレクトリを指定する * "指定したディレクトリ" / .ctw 以下が対象となる * * @param const wxString& ファイルを格納するディレクトリ */ void wxTwitterNotebook::SetAppDir(const wxString& dir) { // dir = "~/" なので、その内部に ".ctw" というディレクトリを作成する this->appDir = dir + wxFILE_SEP_PATH + APP_DIR; } void wxTwitterNotebook::SetComsumerPair(const wxString& key,const wxString& sec) { AP_COMSUMER_KEY = key; AP_COMSUMER_SECRET = sec; } /** * cmdline_twitterが出力するファイルを格納するディレクトリを取得する * ディレクトリが存在しなければ作成する * * @return const wxString ファイルを格納するディレクトリ */ const wxString wxTwitterNotebook::GetAppDir() { if ( !this->appDir.IsEmpty() && !wxDir::Exists(this->appDir) ) { ::wxMkdir(this->appDir); } return this->appDir; } /** * 初期化処理 */ void wxTwitterNotebook::Initialize() { // このアプリのコンシューマキーなどを設定 client.setComsumerPair(std::string(AP_COMSUMER_KEY.mb_str()), std::string(AP_COMSUMER_SECRET.mb_str())); // 認証 DoAuthentication(); // 設定読み込み ReadSetting(); // ここから先はユーザのアクセスキーが必要 if(!ReadAccessKey()) { return; } //DoWxWidgetsUIMode(); return; } /** * 一連の認証動作を行う */ void wxTwitterNotebook::DoAuthentication() { *log << wxT("Twitterにつなぐ準備中...\n"); std::string rurl, pincode; *log << wxT("認証手続きをしています...\n"); if(!client.Authentication_GetURL(rurl)) { return; } wxString message = wxT("以下のURLにアクセスして認証後、ダイアログにPINを入力してください\n"); message << wxT("(※デフォルトのブラウザを開きます)\n"); message << wxString((const char*)rurl.c_str(), wxConvUTF8); // デフォルトのブラウザを開く ::wxLaunchDefaultBrowser(wxString((const char*)rurl.c_str(), wxConvUTF8)); // PIN 入力用ダイアログ wxTextEntryDialog dlg(this, message, wxT("Twitter - PINコード認証")); dlg.ShowModal(); pincode = std::string(dlg.GetValue().mb_str()); *log << wxT("認証中です...\n"); if(dlg.GetValue().IsEmpty() || !client.Authentication_Finish(pincode)){ *log << wxT("認証に失敗しました。再度認証しなおしてください\n"); return; } *log << wxT("認証に成功しました\n"); wxString fname; std::string key,sec; std::ofstream fout; // ~/.ctw/以下に保存する if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); return; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_AUTH_FILE; client.getUserAccessPair(key,sec); fout.open(fname.mb_str(), std::ios::out); if(! fout.is_open()){ *log << wxT("設定ファイルを開けませんでした。\n"); *log << wxT("再度認証しなおしてください\n"); return; } fout << key << std::endl; fout << sec << std::endl; fout.close(); return; } /** * 保存している認証コードを読みこむ */ bool wxTwitterNotebook::ReadAccessKey() { wxString fname; std::string key,sec; std::ifstream fin; // ~/.ctw/以下から読み込みする if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); return false; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_AUTH_FILE; fin.open(fname.mb_str()); if(! fin.is_open()) { *log << wxT("設定ファイルを開けませんでした。\n"); *log << wxT("指定されたエイリアス名が間違っているかもしれません。\n"); return false; } fin >> key; fin >> sec; fin.close(); if(key.empty() || sec.empty()) { *log << wxT("設定ファイルが壊れています。再度認証してください\n"); return false; } client.setUserAccessPair(key,sec); return true; } void wxTwitterNotebook::InitSetting() { setting["READHOME_COUNT"] = minisetting::value(200); setting["READHOME_VIEWRT"] = minisetting::value(true); setting["READHOME_VIEWMENTION"] = minisetting::value(true); setting["READUSER_COUNT"] = minisetting::value(200); setting["READUSER_VIEWRT"] = minisetting::value(true); setting["READUSER_VIEWMENTION"] = minisetting::value(true); setting["READDM_COUNT"] = minisetting::value(200); setting["READLIST_COUNT"] = minisetting::value(200); setting["READLIST_VIEWRT"] = minisetting::value(true); setting["VIEW_SHORT"] = minisetting::value(false); setting["VIEW_SHORT_NAMEONLY"] = minisetting::value(true); setting["VIEW_STATUSID"] = minisetting::value(true); } /** * 設定ファイルの読み込み */ void wxTwitterNotebook::ReadSetting() { using namespace minisetting; wxString fname; std::ifstream fin; InitSetting(); // ~/.ctw/以下から読み込みする if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); *log << wxT("設定ファイルを読み込めませんでした。 \n"); *log << wxT("デフォルトの設定を使用します \n"); return; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_SETTING_FILE; fin.open(fname.mb_str()); if(! fin.is_open()) { *log << wxT("設定ファイルを開けませんでした。\n"); *log << wxT("デフォルトの設定を使用します \n"); WriteSetting(); return; } parse(fin,setting); fin.close(); } /** * 設定ファイルが存在しない場合に新規に作成する */ void wxTwitterNotebook::WriteSetting() { using namespace minisetting; wxString fname; std::ofstream fout; // ~/.ctw/以下に保存する if(GetAppDir().IsEmpty() || !wxDir::Exists(GetAppDir()) ) { *log << wxT("HOME/.ctw/ ディレクトリを作成できません。\n"); return; } fname << GetAppDir(); fname << wxFILE_SEP_PATH; fname << DEFAULT_SETTING_FILE; fout.open(fname.mb_str(),ios::out); if(! fout.is_open()) { return; } // "ホームタイムライン読み込み設定" // "ホームタイムラインの読み込み件数(20-200)" putval(fout,setting,"READHOME_COUNT"); // "ホームタイムラインでRTを表示するかどうか(true false)" putval(fout,setting,"READHOME_VIEWRT"); // "ホームタイムラインで@を表示するかどうか(true false)" putval(fout,setting,"READHOME_VIEWMENTION"); // "ユーザタイムライン読み込み設定" // "ユーザタイムラインの読み込み件数(20-200)" putval(fout,setting,"READUSER_COUNT"); // "ユーザタイムラインでRTを表示するかどうか(true false)" putval(fout,setting,"READUSER_VIEWRT"); // "ユーザタイムラインで@を表示するかどうか(true false)" putval(fout,setting,"READUSER_VIEWMENTION"); // "ダイレクトメッセージ読み込み設定" // "ダイレクトメッセージの読み込み件数(20-200)" putval(fout,setting,"READDM_COUNT"); // "リスト読み込み設定" // "リストタイムラインの読み込み件数(20-200)" putval(fout,setting,"READLIST_COUNT"); // "リストタイムラインでRTを表示するかどうか(true false)" putval(fout,setting,"READLIST_VIEWRT"); // "表示設定" // "短縮表示をおこなうかどうか(true false)" putval(fout,setting,"VIEW_SHORT"); // "短縮表示のとき、名前を登録名(スクリーンネーム以外)にする(true false)" putval(fout,setting,"VIEW_SHORT_NAMEONLY"); // "発言IDの表示をおこなうかどうか(true false)" putval(fout,setting,"VIEW_STATUSID"); fout.close(); } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ // This is a wrapper program that we use for things we launch via glexec, // in order to get around glexec's inability to pass environment variables. // The basic procedure is: // 1) Condor sets up a UNIX domain socket pair // 2) Condor invokes this wrapper via glexec, passing one of the sockets // to the wrapper as it's standard input stream. // 3) A stream of environment variables is sent over the socket pair and // merged into the environment that will be used for the job. // 4) The job's "real" standard input FD is sent over the socket pair. The // wrapper's socket end is dup'ed and FD 0 is then set to use the // received FD. // 5) The wrapper's socket end is set close-on-exec, and the wrapper then // exec's the job. #include "condor_common.h" #include "MyString.h" #include "env.h" #include "condor_blkng_full_disk_io.h" #include "fdpass.h" static void fatal_error(); static char* read_env(); static void get_std_fd(int, char*); static MyString err; static int sock_fd; int main(int argc, char* argv[]) { // dup FD 0 since we will later replace FD 0 with the job's stdin // sock_fd = dup(0); if (sock_fd == -1) { err.sprintf("dup error on FD 0: %s", strerror(errno)); sock_fd = 0; fatal_error(); } // deal with our arguments // if (argc < 5) { err.sprintf("usage: %s <in> <out> <err> <cmd> [<arg> ...]", argv[0]); fatal_error(); } char* job_stdin = argv[1]; char* job_stdout = argv[2]; char* job_stderr = argv[3]; char** job_argv = &argv[4]; // set up an Env object that we'll use for the job. we'll initialize // it with the environment that Condor sends us then merge on top of // that the environment that glexec prepared for us // // Why? I don't understand why we are overriding job environment // set by condor with the environment set by glexec. For now, we // must make one exception: X509_USER_PROXY. We want the job to // use the proxy that is managed by Condor, not a copy of the // proxy created by glexec or the proxy used by condor itself. Env env; char* env_buf = read_env(); MyString merge_err; if (!env.MergeFromV2Raw(env_buf, &merge_err)) { err.sprintf("Env::MergeFromV2Raw error: %s", merge_err.Value()); fatal_error(); } MyString user_proxy; bool override_glexec_proxy_env = false; if( env.GetEnv("X509_USER_PROXY",user_proxy) && getenv("X509_USER_PROXY") ) { override_glexec_proxy_env = true; } env.MergeFrom(environ); delete[] env_buf; if( override_glexec_proxy_env ) { env.SetEnv("X509_USER_PROXY",user_proxy.Value()); } // now prepare the job's standard FDs // get_std_fd(0, job_stdin); get_std_fd(1, job_stdout); get_std_fd(2, job_stderr); // Now we do a little dance to replace the socketpair that we // have been using to communicate with the starter with a new // one. Why? Because, as of glexec 0.8, when glexec is // configured with linger=on, some persistent process // (glexec?, procd?) is keeping a handle to the wrapper's end // of the socket open, so the starter hangs waiting for the // socket to close when the job is executed. int new_sock_fd = fdpass_recv(sock_fd); if (new_sock_fd == -1) { err = "fdpass_recv error on new_sock_fd"; fatal_error(); } if (dup2(new_sock_fd,sock_fd) == -1 ) { err = "dup2 error on new_sock_fd"; fatal_error(); } close(new_sock_fd); // set our UNIX domain socket end close-on-exec; if the Starter // sees it close without seeing an error message first, it assumes // that the job has begun execution // if (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) { err.sprintf("fcntl error setting close-on-exec: %s", strerror(errno)); fatal_error(); } // now we can exec the job. for arguments, we shift this wrapper's // arguments by one. similarly, the job's executable path is taken // as our argv[1] // char** envp = env.getStringArray(); execve(job_argv[0], &job_argv[0], envp); err.sprintf("execve error: %s", strerror(errno)); fatal_error(); } static void fatal_error() { write(sock_fd, err.Value(), err.Length() + 1); exit(1); } static char* read_env() { int bytes; int env_len; bytes = full_read(0, &env_len, sizeof(env_len)); if (bytes != sizeof(env_len)) { if (bytes == -1) { err.sprintf("read error getting env size: %s", strerror(errno)); } else { err.sprintf("short read of env size: %d of %d bytes", bytes, sizeof(env_len)); } fatal_error(); } if (env_len <= 0) { err.sprintf("invalid env size %d read from stdin", env_len); fatal_error(); } char* env_buf = new char[env_len]; if (env_buf == NULL) { err.sprintf("failure to allocate %d bytes", env_len); fatal_error(); } bytes = full_read(0, env_buf, env_len); if (bytes != env_len) { if (bytes == -1) { err.sprintf("read error getting env: %s", strerror(errno)); } else { err.sprintf("short read of env: %d of %d bytes", bytes, env_len); } fatal_error(); } return env_buf; } static void get_std_fd(int std_fd, char* name) { int new_fd = std_fd; if (strcmp(name, "-") == 0) { if (std_fd == 0) { // stdin is handled specially, since its "default" // (if we were passed "-" on the command line) is // to get passed the FD to use from the Starter // new_fd = fdpass_recv(sock_fd); if (new_fd == -1) { err = "fdpass_recv error"; fatal_error(); } } } else { int flags; if (std_fd == 0) { flags = O_RDONLY; } else { flags = O_WRONLY | O_CREAT | O_TRUNC; } new_fd = safe_open_wrapper(name, flags, 0600); if (new_fd == -1) { err.sprintf("safe_open_wrapper error on %s: %s", name, strerror(errno)); fatal_error(); } } if (new_fd != std_fd) { if (dup2(new_fd, std_fd) == -1) { err.sprintf("dup2 error (%d to %d): %s", new_fd, std_fd, strerror(errno)); fatal_error(); } close(new_fd); } } <commit_msg>Prevent glexec from overriding the job's PATH environment variable.<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ // This is a wrapper program that we use for things we launch via glexec, // in order to get around glexec's inability to pass environment variables. // The basic procedure is: // 1) Condor sets up a UNIX domain socket pair // 2) Condor invokes this wrapper via glexec, passing one of the sockets // to the wrapper as it's standard input stream. // 3) A stream of environment variables is sent over the socket pair and // merged into the environment that will be used for the job. // 4) The job's "real" standard input FD is sent over the socket pair. The // wrapper's socket end is dup'ed and FD 0 is then set to use the // received FD. // 5) The wrapper's socket end is set close-on-exec, and the wrapper then // exec's the job. #include "condor_common.h" #include "MyString.h" #include "env.h" #include "condor_blkng_full_disk_io.h" #include "fdpass.h" static void fatal_error(); static char* read_env(); static void get_std_fd(int, char*); static MyString err; static int sock_fd; int main(int argc, char* argv[]) { // dup FD 0 since we will later replace FD 0 with the job's stdin // sock_fd = dup(0); if (sock_fd == -1) { err.sprintf("dup error on FD 0: %s", strerror(errno)); sock_fd = 0; fatal_error(); } // deal with our arguments // if (argc < 5) { err.sprintf("usage: %s <in> <out> <err> <cmd> [<arg> ...]", argv[0]); fatal_error(); } char* job_stdin = argv[1]; char* job_stdout = argv[2]; char* job_stderr = argv[3]; char** job_argv = &argv[4]; // set up an Env object that we'll use for the job. we'll initialize // it with the environment that Condor sends us then merge on top of // that the environment that glexec prepared for us // // Why? I don't understand why we are overriding job environment // set by condor with the environment set by glexec. For now, we // must make two exceptions: X509_USER_PROXY and PATH. We want the job to // use the proxy that is managed by Condor, not a copy of the // proxy created by glexec or the proxy used by condor itself. // The overriding of PATH by glexec has also been probematic. Env env; char* env_buf = read_env(); MyString merge_err; if (!env.MergeFromV2Raw(env_buf, &merge_err)) { err.sprintf("Env::MergeFromV2Raw error: %s", merge_err.Value()); fatal_error(); } MyString user_proxy; bool override_glexec_proxy_env = false; if( env.GetEnv("X509_USER_PROXY",user_proxy) && getenv("X509_USER_PROXY") ) { override_glexec_proxy_env = true; } MyString path; bool override_path = false; if( env.GetEnv("PATH",path) && getenv("PATH") ) { override_path = true; } env.MergeFrom(environ); delete[] env_buf; if( override_glexec_proxy_env ) { env.SetEnv("X509_USER_PROXY",user_proxy.Value()); } if( override_path ) { env.SetEnv("PATH",path.Value()); } // now prepare the job's standard FDs // get_std_fd(0, job_stdin); get_std_fd(1, job_stdout); get_std_fd(2, job_stderr); // Now we do a little dance to replace the socketpair that we // have been using to communicate with the starter with a new // one. Why? Because, as of glexec 0.8, when glexec is // configured with linger=on, some persistent process // (glexec?, procd?) is keeping a handle to the wrapper's end // of the socket open, so the starter hangs waiting for the // socket to close when the job is executed. int new_sock_fd = fdpass_recv(sock_fd); if (new_sock_fd == -1) { err = "fdpass_recv error on new_sock_fd"; fatal_error(); } if (dup2(new_sock_fd,sock_fd) == -1 ) { err = "dup2 error on new_sock_fd"; fatal_error(); } close(new_sock_fd); // set our UNIX domain socket end close-on-exec; if the Starter // sees it close without seeing an error message first, it assumes // that the job has begun execution // if (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) { err.sprintf("fcntl error setting close-on-exec: %s", strerror(errno)); fatal_error(); } // now we can exec the job. for arguments, we shift this wrapper's // arguments by one. similarly, the job's executable path is taken // as our argv[1] // char** envp = env.getStringArray(); execve(job_argv[0], &job_argv[0], envp); err.sprintf("execve error: %s", strerror(errno)); fatal_error(); } static void fatal_error() { write(sock_fd, err.Value(), err.Length() + 1); exit(1); } static char* read_env() { int bytes; int env_len; bytes = full_read(0, &env_len, sizeof(env_len)); if (bytes != sizeof(env_len)) { if (bytes == -1) { err.sprintf("read error getting env size: %s", strerror(errno)); } else { err.sprintf("short read of env size: %d of %d bytes", bytes, sizeof(env_len)); } fatal_error(); } if (env_len <= 0) { err.sprintf("invalid env size %d read from stdin", env_len); fatal_error(); } char* env_buf = new char[env_len]; if (env_buf == NULL) { err.sprintf("failure to allocate %d bytes", env_len); fatal_error(); } bytes = full_read(0, env_buf, env_len); if (bytes != env_len) { if (bytes == -1) { err.sprintf("read error getting env: %s", strerror(errno)); } else { err.sprintf("short read of env: %d of %d bytes", bytes, env_len); } fatal_error(); } return env_buf; } static void get_std_fd(int std_fd, char* name) { int new_fd = std_fd; if (strcmp(name, "-") == 0) { if (std_fd == 0) { // stdin is handled specially, since its "default" // (if we were passed "-" on the command line) is // to get passed the FD to use from the Starter // new_fd = fdpass_recv(sock_fd); if (new_fd == -1) { err = "fdpass_recv error"; fatal_error(); } } } else { int flags; if (std_fd == 0) { flags = O_RDONLY; } else { flags = O_WRONLY | O_CREAT | O_TRUNC; } new_fd = safe_open_wrapper(name, flags, 0600); if (new_fd == -1) { err.sprintf("safe_open_wrapper error on %s: %s", name, strerror(errno)); fatal_error(); } } if (new_fd != std_fd) { if (dup2(new_fd, std_fd) == -1) { err.sprintf("dup2 error (%d to %d): %s", new_fd, std_fd, strerror(errno)); fatal_error(); } close(new_fd); } } <|endoftext|>
<commit_before>#include <iostream> #include <string.h> #include <istream> #include <cstring> #include <unistd.h> using namespace std; #include <cstdio> #include <stdio.h> #include <string.h> /* int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," ,.-"); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " ,.-"); } return 0; } */ //need to figure out how to parse!! //see boost library's TOKENIZER !!!!! int main() { string input; //taking input as a c++ string; will convert to c_str later cout << "$ "; //command prompt getline (cin,input); cout << endl << "outputting input: " << endl << input << endl; //these will be the arguments to my shell after parsing int argc = 0; // no arguments (yet) char* argv[99999]; argv[0] = new char[9999]; char * tmp; //cstring to not deal with memory management for now char delims[] = " &&||;-"; // connectors we are looking out for. //FIXME: may not be exactly what we want since may have //to be arguments too char input2[9999]; strcpy(input2, input.c_str() ); cout << "about to run strtok 1st time" << endl; tmp = strtok(input2,delims) ; strcpy( argv[argc] , tmp ); //copying first token cout << "about to run strtok In while loop." << endl; while (tmp != NULL) { argc +=1; // argument count increases. printf ("%s\n",tmp) ; tmp = strtok (NULL,delims); argv[argc] = tmp; // copying tokens into argv one at a time } /* cerr << "copying tmp into argv..." << endl; strcpy(*argv,tmp ); cout << "strcpy successful!! (maybe LOL)" << endl; */ //checking everything was read in cout << "argc: " << argc << " " << endl; cout << " argv:" << endl; for(unsigned i = 0; argv[i]!='\0'; ++i){ cout << i << ": " << argv[i] << endl; } //need to figure out a way to read in commands with ';' in between //and white space in between if (argv[1]=='\0'){ cout << "Null man. " << endl; } //execvp(argv); cout << "||" << endl; return 0; } <commit_msg>didn't change anything.<commit_after>#include <iostream> #include <string.h> #include <istream> #include <cstring> #include <unistd.h> using namespace std; #include <cstdio> #include <stdio.h> #include <string.h> int main() { string input; //taking input as a c++ string; will convert to c_str later cout << "$ "; //command prompt getline (cin,input); cout << endl << "outputting input: " << endl << input << endl; //these will be the arguments to my shell after parsing int argc = 0; // no arguments (yet) char* argv[99999]; argv[0] = new char[9999]; char * tmp; //cstring to not deal with memory management for now char delims[] = " &&||;-"; // connectors we are looking out for. //FIXME: may not be exactly what we want since may have //to be arguments too char input2[9999]; //will take copy of input from std::string input strcpy(input2, input.c_str() ); cout << "about to run strtok 1st time" << endl; tmp = strtok(input2,delims) ; strcpy( argv[argc] , tmp ); //copying first token cout << "about to run strtok In while loop." << endl; while (tmp != NULL) { argc +=1; // argument count increases. printf ("%s\n",tmp) ; tmp = strtok (NULL,delims); argv[argc] = tmp; // copying tokens into argv one at a time } /* cerr << "copying tmp into argv..." << endl; strcpy(*argv,tmp ); cout << "strcpy successful!! (maybe LOL)" << endl; */ //checking everything was read in cout << "argc: " << argc << " " << endl; cout << " argv:" << endl; for(unsigned i = 0; argv[i]!='\0'; ++i){ cout << i << ": " << argv[i] << endl; } //need to figure out a way to read in commands with ';' in between //and white space in between if (argv[1]=='\0'){ cout << "Null man. " << endl; } //execvp(argv); cout << "||" << endl; return 0; } <|endoftext|>
<commit_before>/* * SessionAsyncCompletions.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_ASYNC_R_COMPLETIONS_HPP #define SESSION_ASYNC_R_COMPLETIONS_HPP #include <core/r_util/RSourceIndex.hpp> #include <session/SessionAsyncRProcess.hpp> namespace rstudio { namespace session { namespace modules { namespace r_completions { class AsyncRCompletions : public async_r::AsyncRProcess { public: static void update(); friend class CompleteUpdateOnExit; protected: void onStdout(const std::string& output) { stdOut_ << output; } void onStderr(const std::string& output) { LOG_ERROR_MESSAGE(output); } void onCompleted(int exitStatus); private: static bool s_isUpdating_; static std::vector<std::string> s_pkgsToUpdate_; std::stringstream stdOut_; }; } // end namespace r_completions } // end namesapce modules } // end namespace session } #endif <commit_msg>suppress error logging for async r completions<commit_after>/* * SessionAsyncCompletions.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_ASYNC_R_COMPLETIONS_HPP #define SESSION_ASYNC_R_COMPLETIONS_HPP #include <core/r_util/RSourceIndex.hpp> #include <session/SessionAsyncRProcess.hpp> namespace rstudio { namespace session { namespace modules { namespace r_completions { class AsyncRCompletions : public async_r::AsyncRProcess { public: static void update(); friend class CompleteUpdateOnExit; protected: void onStdout(const std::string& output) { stdOut_ << output; } void onStderr(const std::string& output) { // since package load can fail for a myriad of reasons, and these reasons // are almost never actionable, we don't log errors } void onCompleted(int exitStatus); private: static bool s_isUpdating_; static std::vector<std::string> s_pkgsToUpdate_; std::stringstream stdOut_; }; } // end namespace r_completions } // end namesapce modules } // end namespace session } #endif <|endoftext|>
<commit_before>#include <fhe/FHEContext.h> #include <fhe/FHE.h> #include <fhe/NumbTh.h> #include <fhe/EncryptedArray.h> #include <utils/FileUtils.hpp> #include <utils/timer.hpp> #include <algebra/NDSS.h> #include <thread> #include <atomic> #include <vector> #ifdef FHE_THREADS long WORKER_NR = 8; #else // ifdef FHE_THREADS long WORKER_NR = 1; #endif // ifdef FHE_THREAD std::vector<MDL::EncVector>encrypt(const MDL::Matrix<long>& data, const FHEPubKey & pk, const EncryptedArray & ea, long from = 0, long to = 0) { MDL::Timer timer; std::vector<MDL::EncVector> ctxts(to - from, pk); std::vector<std::thread> workers; std::atomic<size_t> counter(from); to = to == 0 ? data.rows() : to; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&data, &ea, &to, &counter, &ctxts]() { size_t next; while ((next = counter.fetch_add(1)) < to) { ctxts[next - from].pack(data[next], ea); } }))); } for (auto && wr : workers) wr.join(); timer.end(); printf("Encrypt %ld data with %ld workers costed %f sec\n", to - from, WORKER_NR, timer.second()); return ctxts; } MDL::EncVector mean(const std::vector<MDL::EncVector>& ctxts) { std::vector<std::thread> workers; std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey()); std::atomic<size_t> counter(WORKER_NR); MDL::Timer timer; timer.start(); for (long i = 0; i < WORKER_NR; i++) { partials[i] = ctxts[i]; workers.push_back(std::move(std::thread([&counter, &ctxts] (MDL::EncVector& ct) { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ct += ctxts[next]; } }, std::ref(partials[i])))); } for (auto && wr : workers) { wr.join(); } for (long i = 1; i < WORKER_NR; i++) { partials[0] += partials[i]; } timer.end(); printf("Sum %zd data with %ld workers costed %f sec\n", ctxts.size(), WORKER_NR, timer.second()); return partials[0]; } MDL::EncVector squareSum(std::vector<MDL::EncVector>& ctxts) { MDL::Timer timer; std::atomic<size_t> counter(0); std::vector<std::thread> workers; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&ctxts, &counter]() { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ctxts[next].square(); } }))); } for (auto && wr : workers) wr.join(); auto sq_sum = mean(ctxts); timer.end(); printf("Square Sum costed %f sec\n", timer.second()); return sq_sum; } MDL::EncVector variance(const MDL::Matrix<long>& data, const EncryptedArray & ea, const FHEPubKey & pk) { MDL::EncVector square_sum(pk), sum_square(pk); NTL::ZZX N(data.rows()); const long BATCH_SIZE = 5000; MDL::Timer totalTimer, encTimer, evalTimer; totalTimer.start(); for (long part = 0; part *BATCH_SIZE < data.rows(); part++) { long from = std::min<long>(part * BATCH_SIZE, data.rows()); long to = std::min<long>(from + BATCH_SIZE, data.rows()); encTimer.start(); auto ctxts = encrypt(data, pk, ea, from, to); encTimer.end(); evalTimer.start(); if (part > 0) { sum_square += mean(ctxts); square_sum += squareSum(ctxts); } else { sum_square = mean(ctxts); square_sum = squareSum(ctxts); } evalTimer.end(); } evalTimer.start(); sum_square.square(); square_sum.multByConstant(N); square_sum -= sum_square; evalTimer.end(); totalTimer.end(); printf("Varaice of %zd data with %ld workers used %f(%f/%f)\n", data.rows(), WORKER_NR, totalTimer.second(), encTimer.second(), evalTimer.second()); return square_sum; } int main(int argc, char *argv[]) { long m, p, r, L; ArgMapping argmap; argmap.arg("m", m, "m"); argmap.arg("L", L, "L"); argmap.arg("p", p, "p"); argmap.arg("r", r, "r"); argmap.parse(argc, argv); FHEcontext context(m, p, r); buildModChain(context, L); FHESecKey sk(context); sk.GenSecKey(64); addSome1DMatrices(sk); FHEPubKey pk = sk; auto G = context.alMod.getFactorsOverZZ()[0]; EncryptedArray ea(context, G); auto data = load_csv("adult.data"); auto result = load_csv("adult_result"); // auto ctxts = encrypt(data, pk, ea); // { // MDL::Vector<long> ret; // auto summaiton = mean(ctxts); // summaiton.unpack(ret, sk, ea); // std::cout << ret << std::endl; // std::cout << result[0] << std::endl; // } { MDL::Vector<long> ret; auto var = variance(data, ea, pk); var.unpack(ret, sk, ea); std::cout << ret << std::endl; std::cout << result[1] << std::endl; } return 0; } <commit_msg>Bugfix, to capture 'from' in the lambda<commit_after>#include <fhe/FHEContext.h> #include <fhe/FHE.h> #include <fhe/NumbTh.h> #include <fhe/EncryptedArray.h> #include <utils/FileUtils.hpp> #include <utils/timer.hpp> #include <algebra/NDSS.h> #include <thread> #include <atomic> #include <vector> #ifdef FHE_THREADS long WORKER_NR = 8; #else // ifdef FHE_THREADS long WORKER_NR = 1; #endif // ifdef FHE_THREAD std::vector<MDL::EncVector>encrypt(const MDL::Matrix<long>& data, const FHEPubKey & pk, const EncryptedArray & ea, long from = 0, long to = 0) { MDL::Timer timer; std::vector<MDL::EncVector> ctxts(to - from, pk); std::vector<std::thread> workers; std::atomic<size_t> counter(from); to = to == 0 ? data.rows() : to; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&data, &ea, &to, &from, &counter, &ctxts]() { size_t next; while ((next = counter.fetch_add(1)) < to) { ctxts[next - from].pack(data[next], ea); } }))); } for (auto && wr : workers) wr.join(); timer.end(); printf("Encrypt %ld data with %ld workers costed %f sec\n", to - from, WORKER_NR, timer.second()); return ctxts; } MDL::EncVector mean(const std::vector<MDL::EncVector>& ctxts) { std::vector<std::thread> workers; std::vector<MDL::EncVector> partials(WORKER_NR, ctxts[0].getPubKey()); std::atomic<size_t> counter(WORKER_NR); MDL::Timer timer; timer.start(); for (long i = 0; i < WORKER_NR; i++) { partials[i] = ctxts[i]; workers.push_back(std::move(std::thread([&counter, &ctxts] (MDL::EncVector& ct) { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ct += ctxts[next]; } }, std::ref(partials[i])))); } for (auto && wr : workers) { wr.join(); } for (long i = 1; i < WORKER_NR; i++) { partials[0] += partials[i]; } timer.end(); printf("Sum %zd data with %ld workers costed %f sec\n", ctxts.size(), WORKER_NR, timer.second()); return partials[0]; } MDL::EncVector squareSum(std::vector<MDL::EncVector>& ctxts) { MDL::Timer timer; std::atomic<size_t> counter(0); std::vector<std::thread> workers; timer.start(); for (long wr = 0; wr < WORKER_NR; wr++) { workers.push_back(std::move(std::thread([&ctxts, &counter]() { size_t next; while ((next = counter.fetch_add(1)) < ctxts.size()) { ctxts[next].square(); } }))); } for (auto && wr : workers) wr.join(); auto sq_sum = mean(ctxts); timer.end(); printf("Square Sum costed %f sec\n", timer.second()); return sq_sum; } MDL::EncVector variance(const MDL::Matrix<long>& data, const EncryptedArray & ea, const FHEPubKey & pk) { MDL::EncVector square_sum(pk), sum_square(pk); NTL::ZZX N(data.rows()); const long BATCH_SIZE = 5000; MDL::Timer totalTimer, encTimer, evalTimer; totalTimer.start(); for (long part = 0; part *BATCH_SIZE < data.rows(); part++) { long from = std::min<long>(part * BATCH_SIZE, data.rows()); long to = std::min<long>(from + BATCH_SIZE, data.rows()); encTimer.start(); auto ctxts = encrypt(data, pk, ea, from, to); encTimer.end(); evalTimer.start(); if (part > 0) { sum_square += mean(ctxts); square_sum += squareSum(ctxts); } else { sum_square = mean(ctxts); square_sum = squareSum(ctxts); } evalTimer.end(); } evalTimer.start(); sum_square.square(); square_sum.multByConstant(N); square_sum -= sum_square; evalTimer.end(); totalTimer.end(); printf("Varaice of %zd data with %ld workers used %f(%f/%f)\n", data.rows(), WORKER_NR, totalTimer.second(), encTimer.second(), evalTimer.second()); return square_sum; } int main(int argc, char *argv[]) { long m, p, r, L; ArgMapping argmap; argmap.arg("m", m, "m"); argmap.arg("L", L, "L"); argmap.arg("p", p, "p"); argmap.arg("r", r, "r"); argmap.parse(argc, argv); FHEcontext context(m, p, r); buildModChain(context, L); FHESecKey sk(context); sk.GenSecKey(64); addSome1DMatrices(sk); FHEPubKey pk = sk; auto G = context.alMod.getFactorsOverZZ()[0]; EncryptedArray ea(context, G); auto data = load_csv("adult.data"); auto result = load_csv("adult_result"); // auto ctxts = encrypt(data, pk, ea); // { // MDL::Vector<long> ret; // auto summaiton = mean(ctxts); // summaiton.unpack(ret, sk, ea); // std::cout << ret << std::endl; // std::cout << result[0] << std::endl; // } { MDL::Vector<long> ret; auto var = variance(data, ea, pk); var.unpack(ret, sk, ea); std::cout << ret << std::endl; std::cout << result[1] << std::endl; } return 0; } <|endoftext|>
<commit_before>#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<sstream> #include<iomanip> #include"sandbox.h" using namespace std; int sandboxExec(int boxid, const sandboxOptions &opt, const string &comm) { ostringstream sout; sout << "isolate --box-id=" << boxid; if(opt.cgroup) sout << " --cg"; if(opt.preserve_env) sout << " --full-env"; for(int i = 0; i < opt.dirs.size(); ++i) sout << " --dir=" << opt.dirs[i]; if(!opt.input.empty()) sout << " --stdin=" << opt.input; if(!opt.output.empty()) sout << " --stdout=" << opt.output; if(!opt.errout.empty()) sout << " --stderr=" << opt.errout; if(!opt.meta.empty()) sout << " --meta=" << opt.meta; if(opt.mem != 0) sout << " --mem=" << opt.mem sout << " --processes=" << opt.procs; double timeout = opt.timeout * 0.001; if(opt.timeout != 0){ sout << " --time=" << fixed << setprecision(3) << timeout; sout << " --wall-time=" << fixed << setprecision(3) << timeout * 2; } sout << " --extra-time=0.2"; sout << " --run -- " << comm; cerr << "[debug] box-" << boxid << " execute command : " << sout.str() << endl; system(sout.str().c_str()); return 0; } int sandboxInit(int boxid) { ostringstream sout; sout << "isolate --box-id=" << boxid; sout << " --cg"; sout << " --init 2>/dev/null >/dev/null"; cerr << "[debug] box-" << boxid << " inited" << endl; system(sout.str().c_str()); return 0; } int sandboxDele(int boxid) { ostringstream sout; sout << "isolate --box-id=" << boxid; sout << " --cg"; sout << " --cleanup 2>/dev/null >/dev/null"; cerr << "[debug] box-" << boxid << " cleaned" << endl; system(sout.str().c_str()); return 0; } <commit_msg>try mem limit<commit_after>#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<sstream> #include<iomanip> #include"sandbox.h" using namespace std; int sandboxExec(int boxid, const sandboxOptions &opt, const string &comm) { ostringstream sout; sout << "isolate --box-id=" << boxid; if(opt.cgroup) sout << " --cg"; if(opt.preserve_env) sout << " --full-env"; for(int i = 0; i < opt.dirs.size(); ++i) sout << " --dir=" << opt.dirs[i]; if(!opt.input.empty()) sout << " --stdin=" << opt.input; if(!opt.output.empty()) sout << " --stdout=" << opt.output; if(!opt.errout.empty()) sout << " --stderr=" << opt.errout; if(!opt.meta.empty()) sout << " --meta=" << opt.meta; if(opt.mem != 0) sout << " --mem=" << opt.mem; sout << " --processes=" << opt.procs; double timeout = opt.timeout * 0.001; if(opt.timeout != 0){ sout << " --time=" << fixed << setprecision(3) << timeout; sout << " --wall-time=" << fixed << setprecision(3) << timeout * 2; } sout << " --extra-time=0.2"; sout << " --run -- " << comm; cerr << "[debug] box-" << boxid << " execute command : " << sout.str() << endl; system(sout.str().c_str()); return 0; } int sandboxInit(int boxid) { ostringstream sout; sout << "isolate --box-id=" << boxid; sout << " --cg"; sout << " --init 2>/dev/null >/dev/null"; cerr << "[debug] box-" << boxid << " inited" << endl; system(sout.str().c_str()); return 0; } int sandboxDele(int boxid) { ostringstream sout; sout << "isolate --box-id=" << boxid; sout << " --cg"; sout << " --cleanup 2>/dev/null >/dev/null"; cerr << "[debug] box-" << boxid << " cleaned" << endl; system(sout.str().c_str()); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b2dhompoint.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:25:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _BGFX_POINT_B2DHOMPOINT_HXX #define _BGFX_POINT_B2DHOMPOINT_HXX #ifndef _BGFX_POINT_B2DPOINT_HXX #include <basegfx/point/b2dpoint.hxx> #endif namespace basegfx { /** Basic homogen Point class with two double values and one homogen factor This class provides access to homogen coordinates in 2D. For this purpose all the operators which need to do specific action due to their homogenity are implemented here. The only caveat are member methods which are declared as const but do change the content. These are documented for that reason. The class is designed to provide homogenous coordinates without direct access to the homogen part (mfW). This is also the reason for leaving out the [] operators which return references to members. @see B2DTuple */ class B2DHomPoint { protected: /// This member contains the coordinate part of the point ::basegfx::B2DTuple maTuple; /// This Member holds the homogenous part of the point double mfW; /** Test if this homogen point does have a homogenous part @return Returns true if this point has no homogenous part */ bool implIsHomogenized() const; /** Remove homogenous part of this Point This method does necessary calculations to remove the evtl. homogenous part of this Point. This may change all members. */ void implHomogenize(); /** Test and on demand remove homogenous part This method tests if this Point does have a homogenous part and then evtl. takes actions to remove that part. @attention Even when this method is const it may change all members of this instance. This is due to the fact that changing the homogenous part of a homogenous point does from a mathematical point of view not change the point at all. */ void implTestAndHomogenize() const; public: /** Create a homogen point The point is initialized to (0.0, 0.0) */ B2DHomPoint() : maTuple(), mfW(1.0) {} /** Create a homogen point @param fX This parameter is used to initialize the X-coordinate of the Point. The homogenous part is initialized to 1.0. @param fY This parameter is used to initialize the Y-coordinate of the Point. The homogenous part is initialized to 1.0. */ B2DHomPoint(double fX, double fY) : maTuple(fX, fY), mfW(1.0) {} /** Create a copy of a 2D Point @param rVec The 2D point which will be copied. The homogenous part is initialized to 1.0. */ B2DHomPoint(const B2DPoint& rVec) : maTuple(rVec), mfW(1.0) {} /** Create a copy of a homogen point @param rVec The homogen point which will be copied. The homogenous part is copied, too. */ B2DHomPoint(const B2DHomPoint& rVec) : maTuple(rVec.maTuple.getX(), rVec.maTuple.getY()), mfW(rVec.mfW) {} ~B2DHomPoint() {} /** Get a 2D point from this homogenous point This method normalizes this homogen point if necessary and returns the corresponding 2D point for this homogen point. @attention Even when this method is const it may change all members of this instance. */ B2DPoint getB2DPoint() const; /** Get X-coordinate This method normalizes this homogen point if necessary and returns the corresponding X-coordinate for this homogen point. @attention Even when this method is const it may change all members of this instance. */ double getX() const; /** Get Y-coordinate This method normalizes this homogen point if necessary and returns the corresponding Y-coordinate for this homogen point. @attention Even when this method is const it may change all members of this instance. */ double getY() const; /** Set X-coordinate of the homogen point. This method sets the X-coordinate of the homogen point. If the point does have a homogenous part this is taken into account. @param fX The to-be-set X-coordinate without homogenous part. */ void setX(double fX); /** Set Y-coordinate of the homogen point. This method sets the Y-coordinate of the homogen point. If the point does have a homogenous part this is taken into account. @param fY The to-be-set Y-coordinate without homogenous part. */ void setY(double fY); // operators ////////////////////////////////////////////////////////////////////// B2DHomPoint& operator+=( const B2DHomPoint& rPnt ); B2DHomPoint& operator-=( const B2DHomPoint& rPnt ); B2DHomPoint& operator*=(double t); B2DHomPoint& operator*=( const B2DHomMatrix& rMat ); B2DHomPoint& operator/=(double t); B2DHomPoint& operator-(void); bool operator==( const B2DHomPoint& rPnt ) const; bool operator!=( const B2DHomPoint& rPnt ) const; B2DHomPoint& operator=( const B2DHomPoint& rPnt ); }; // external operators ////////////////////////////////////////////////////////////////////////// B2DHomPoint minimum(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint maximum(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint absolute(const B2DHomPoint& rVec); B2DHomPoint interpolate(B2DHomPoint& rOld1, B2DHomPoint& rOld2, double t); B2DHomPoint average(B2DHomPoint& rOld1, B2DHomPoint& rOld2); B2DHomPoint average(B2DHomPoint& rOld1, B2DHomPoint& rOld2, B2DHomPoint& rOld3); B2DHomPoint operator+(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint operator-(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint operator*(const B2DHomPoint& rVec, double t); B2DHomPoint operator*(double t, const B2DHomPoint& rVec); B2DHomPoint operator*( const B2DHomMatrix& rMat, const B2DHomPoint& rPoint ); B2DHomPoint operator/(const B2DHomPoint& rVec, double t); B2DHomPoint operator/(double t, const B2DHomPoint& rVec); } // end of namespace basegfx #endif /* _BGFX_POINT_B2DHOMPOINT_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.9.88); FILE MERGED 2008/04/01 10:48:07 thb 1.9.88.2: #i85898# Stripping all external header guards 2008/03/28 16:05:39 rt 1.9.88.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b2dhompoint.hxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _BGFX_POINT_B2DHOMPOINT_HXX #define _BGFX_POINT_B2DHOMPOINT_HXX #include <basegfx/point/b2dpoint.hxx> namespace basegfx { /** Basic homogen Point class with two double values and one homogen factor This class provides access to homogen coordinates in 2D. For this purpose all the operators which need to do specific action due to their homogenity are implemented here. The only caveat are member methods which are declared as const but do change the content. These are documented for that reason. The class is designed to provide homogenous coordinates without direct access to the homogen part (mfW). This is also the reason for leaving out the [] operators which return references to members. @see B2DTuple */ class B2DHomPoint { protected: /// This member contains the coordinate part of the point ::basegfx::B2DTuple maTuple; /// This Member holds the homogenous part of the point double mfW; /** Test if this homogen point does have a homogenous part @return Returns true if this point has no homogenous part */ bool implIsHomogenized() const; /** Remove homogenous part of this Point This method does necessary calculations to remove the evtl. homogenous part of this Point. This may change all members. */ void implHomogenize(); /** Test and on demand remove homogenous part This method tests if this Point does have a homogenous part and then evtl. takes actions to remove that part. @attention Even when this method is const it may change all members of this instance. This is due to the fact that changing the homogenous part of a homogenous point does from a mathematical point of view not change the point at all. */ void implTestAndHomogenize() const; public: /** Create a homogen point The point is initialized to (0.0, 0.0) */ B2DHomPoint() : maTuple(), mfW(1.0) {} /** Create a homogen point @param fX This parameter is used to initialize the X-coordinate of the Point. The homogenous part is initialized to 1.0. @param fY This parameter is used to initialize the Y-coordinate of the Point. The homogenous part is initialized to 1.0. */ B2DHomPoint(double fX, double fY) : maTuple(fX, fY), mfW(1.0) {} /** Create a copy of a 2D Point @param rVec The 2D point which will be copied. The homogenous part is initialized to 1.0. */ B2DHomPoint(const B2DPoint& rVec) : maTuple(rVec), mfW(1.0) {} /** Create a copy of a homogen point @param rVec The homogen point which will be copied. The homogenous part is copied, too. */ B2DHomPoint(const B2DHomPoint& rVec) : maTuple(rVec.maTuple.getX(), rVec.maTuple.getY()), mfW(rVec.mfW) {} ~B2DHomPoint() {} /** Get a 2D point from this homogenous point This method normalizes this homogen point if necessary and returns the corresponding 2D point for this homogen point. @attention Even when this method is const it may change all members of this instance. */ B2DPoint getB2DPoint() const; /** Get X-coordinate This method normalizes this homogen point if necessary and returns the corresponding X-coordinate for this homogen point. @attention Even when this method is const it may change all members of this instance. */ double getX() const; /** Get Y-coordinate This method normalizes this homogen point if necessary and returns the corresponding Y-coordinate for this homogen point. @attention Even when this method is const it may change all members of this instance. */ double getY() const; /** Set X-coordinate of the homogen point. This method sets the X-coordinate of the homogen point. If the point does have a homogenous part this is taken into account. @param fX The to-be-set X-coordinate without homogenous part. */ void setX(double fX); /** Set Y-coordinate of the homogen point. This method sets the Y-coordinate of the homogen point. If the point does have a homogenous part this is taken into account. @param fY The to-be-set Y-coordinate without homogenous part. */ void setY(double fY); // operators ////////////////////////////////////////////////////////////////////// B2DHomPoint& operator+=( const B2DHomPoint& rPnt ); B2DHomPoint& operator-=( const B2DHomPoint& rPnt ); B2DHomPoint& operator*=(double t); B2DHomPoint& operator*=( const B2DHomMatrix& rMat ); B2DHomPoint& operator/=(double t); B2DHomPoint& operator-(void); bool operator==( const B2DHomPoint& rPnt ) const; bool operator!=( const B2DHomPoint& rPnt ) const; B2DHomPoint& operator=( const B2DHomPoint& rPnt ); }; // external operators ////////////////////////////////////////////////////////////////////////// B2DHomPoint minimum(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint maximum(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint absolute(const B2DHomPoint& rVec); B2DHomPoint interpolate(B2DHomPoint& rOld1, B2DHomPoint& rOld2, double t); B2DHomPoint average(B2DHomPoint& rOld1, B2DHomPoint& rOld2); B2DHomPoint average(B2DHomPoint& rOld1, B2DHomPoint& rOld2, B2DHomPoint& rOld3); B2DHomPoint operator+(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint operator-(const B2DHomPoint& rVecA, const B2DHomPoint& rVecB); B2DHomPoint operator*(const B2DHomPoint& rVec, double t); B2DHomPoint operator*(double t, const B2DHomPoint& rVec); B2DHomPoint operator*( const B2DHomMatrix& rMat, const B2DHomPoint& rPoint ); B2DHomPoint operator/(const B2DHomPoint& rVec, double t); B2DHomPoint operator/(double t, const B2DHomPoint& rVec); } // end of namespace basegfx #endif /* _BGFX_POINT_B2DHOMPOINT_HXX */ <|endoftext|>