{"text":"\n#include \"ros\/ros.h\"\n#include \"geometry_msgs\/PoseStamped.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\ntypedef pcl::PointCloud PointCloud;\n\nsensor_msgs::ImageConstPtr image; \n\nstruct my_pose {\n float x; \n float y;\n} m, a1, b1, c1, d1, a2, b2, c2, d2; \n\n\/*\n a b\n m\n c d\n -------------\n1, board near conference room\n2, board near 400\/500 doors\n*\/\n \/\/ M of coordinates(x,y) is inside the rectangle iff, \n \/\/ (0 < AM dot AB < AB dot AB) AND (0 < AM dot AC < AC dot AC)\n\nbool inRectangle(my_pose* m, my_pose* a, my_pose* b, my_pose* c) \n{\n \n float am_ab, ab_ab, am_ad, ad_ad;\n am_ab = (m->x - a->x) * (b->x - a->x) + (m->y - a->y) * (b->y - a->y);\n ab_ab = (b->x - a->x) * (b->x - a->x) + (b->y - a->y) * (b->y - a->y);\n am_ac = (m->x - a->x) * (c->x - a->x) + (m->y - a->y) * (c->y - a->y);\n ac_ac = (c->x - a->x) * (c->x - a->x) + (c->y - a->y) * (c->y - a->y);\n\n if (0 < am_ab && am_ab < ab_ab && 0 < am_ac && am_ac < ac_ac)\n return true;\n else\n return false;\n}\n\nvoid callback(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n a1.x = 62.67;\n a1.y = 9.89;\n b1.x = 62.27;\n b1.y = 4.27;\n c1.x = 60.85;\n c1.y = 9.36;\n \n a2.x = 39.73;\n a2.y = 17.12;\n b2.x = 39.80;\n b2.y = 11.17;\n c2.x = 38.24;\n c2.y = 16.94;\n \n geometry_msgs::PoseStampedConstPtr poseStamped = msg; \n\n m.x = poseStamped->pose.position.x;\n m.y = poseStamped->pose.position.y; \n\n\n if (inRectangle(&m, &a1, &b1, &c1) || inRectangle(&m, &a2, &b2, &c2)) \n {\n std::time_t rawtime;\n std::tm* timeinfo;\n char buffer [80];\n\n std::time(&rawtime);\n timeinfo = std::localtime(&rawtime);\n std::strftime(buffer, 80, \"%Y-%m-%d-%H-%M-%S\", timeinfo);\n std::puts(buffer);\n std::string str(buffer);\n\n ROS_INFO(\"People detected in frout of a white board, picture saved.\");\n\n cv_bridge::CvImageConstPtr cv_ptr;\n try \n {\n cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);\n cv::imwrite(\"\/home\/bwi\/Desktop\/whiteboard_\" + str + \".jpg\",\n cv_ptr->image);\n }\n catch (cv_bridge::Exception& e) \n {\n ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n return;\n }\n }\n}\n\n\/\/ keep saving the most recent image\nvoid callback_image_saver(const sensor_msgs::ImageConstPtr& msg)\n{\n image = msg; \n}\n\n\/\/ main function of the node\nint main(int argc, char ** argv)\n{\n ros::init(argc, argv, \"white_board\");\n ros::NodeHandle nh;\n ros::Subscriber sub1 = nh.subscribe(\n \"\/segbot_pcl_person_detector\/human_poses\", 100, callback); \n\n image_transport::ImageTransport it(nh);\n image_transport::Subscriber sub2 = it.subscribe(\n \"\/nav_kinect\/rgb\/image_color\", 1, callback_image_saver);\n\n ros::spin(); \n\n return 0; \n}\n\nminor\n#include \"ros\/ros.h\"\n#include \"geometry_msgs\/PoseStamped.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\ntypedef pcl::PointCloud PointCloud;\n\nsensor_msgs::ImageConstPtr image; \n\nstruct my_pose {\n float x; \n float y;\n} m, a1, b1, c1, d1, a2, b2, c2, d2; \n\n\/*\n a b\n m\n c d\n -------------\n1, board near conference room\n2, board near 400\/500 doors\n*\/\n \/\/ M of coordinates(x,y) is inside the rectangle iff, \n \/\/ (0 < AM dot AB < AB dot AB) AND (0 < AM dot AC < AC dot AC)\n\nbool inRectangle(my_pose* m, my_pose* a, my_pose* b, my_pose* c) \n{\n \n float am_ab, ab_ab, am_ac, ac_ac;\n am_ab = (m->x - a->x) * (b->x - a->x) + (m->y - a->y) * (b->y - a->y);\n ab_ab = (b->x - a->x) * (b->x - a->x) + (b->y - a->y) * (b->y - a->y);\n am_ac = (m->x - a->x) * (c->x - a->x) + (m->y - a->y) * (c->y - a->y);\n ac_ac = (c->x - a->x) * (c->x - a->x) + (c->y - a->y) * (c->y - a->y);\n\n if (0 < am_ab && am_ab < ab_ab && 0 < am_ac && am_ac < ac_ac)\n return true;\n else\n return false;\n}\n\nvoid callback(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n a1.x = 62.67;\n a1.y = 9.89;\n b1.x = 62.27;\n b1.y = 4.27;\n c1.x = 60.85;\n c1.y = 9.36;\n \n a2.x = 39.73;\n a2.y = 17.12;\n b2.x = 39.80;\n b2.y = 11.17;\n c2.x = 38.24;\n c2.y = 16.94;\n \n geometry_msgs::PoseStampedConstPtr poseStamped = msg; \n\n m.x = poseStamped->pose.position.x;\n m.y = poseStamped->pose.position.y; \n\n\n if (inRectangle(&m, &a1, &b1, &c1) || inRectangle(&m, &a2, &b2, &c2)) \n {\n std::time_t rawtime;\n std::tm* timeinfo;\n char buffer [80];\n\n std::time(&rawtime);\n timeinfo = std::localtime(&rawtime);\n std::strftime(buffer, 80, \"%Y-%m-%d-%H-%M-%S\", timeinfo);\n std::puts(buffer);\n std::string str(buffer);\n\n ROS_INFO(\"People detected in frout of a white board, picture saved.\");\n\n cv_bridge::CvImageConstPtr cv_ptr;\n try \n {\n cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);\n cv::imwrite(\"\/home\/bwi\/Desktop\/whiteboard_\" + str + \".jpg\",\n cv_ptr->image);\n }\n catch (cv_bridge::Exception& e) \n {\n ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n return;\n }\n }\n}\n\n\/\/ keep saving the most recent image\nvoid callback_image_saver(const sensor_msgs::ImageConstPtr& msg)\n{\n image = msg; \n}\n\n\/\/ main function of the node\nint main(int argc, char ** argv)\n{\n ros::init(argc, argv, \"white_board\");\n ros::NodeHandle nh;\n ros::Subscriber sub1 = nh.subscribe(\n \"\/segbot_pcl_person_detector\/human_poses\", 100, callback); \n\n image_transport::ImageTransport it(nh);\n image_transport::Subscriber sub2 = it.subscribe(\n \"\/nav_kinect\/rgb\/image_color\", 1, callback_image_saver);\n\n ros::spin(); \n\n return 0; \n}\n\n<|endoftext|>"} {"text":"#if !defined(__CINT__) || defined(__MAKECINT__)\n #include \n #include \n #include \n #include \n\n #include \n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#endif\n \nextern TROOT *gROOT;\n\/\/extern TFile *gFile;\n\n\nvoid PostProcessCTau(Int_t corrType=1) {\n \/\/-----------------------------------------------------------------\n \/\/ PostProcess the histograms produced by AliAnalysisTaskCTau* \n \/\/ Produce:\n \/\/ -- V0 particle spectra (not corrected for the feeddown)\n \/\/ -- Estimated (anti)Lambda feed-down spectra (from Xi's only)\n \/\/ -- V0 particle c*tau distributions (feeddown corrected) \n \/\/-----------------------------------------------------------------\n\n TString name(\"cTau_0090\"); \/\/centrality\n \/\/TString name(\"cTau_0005\"); \/\/centrality\n \/\/TString name(\"cTau_2040\"); \/\/centrality\n \/\/TString name(\"cTau_4060\"); \/\/centrality\n \/\/TString name(\"cTau_6080\"); \/\/centrality\n \/\/TString name(\"cTau_8090\"); \/\/centrality\n\n\n \/\/+++++ Real data histograms\n TFile::Open(\"new\/real\/all\/\" + name + \".root\");\n TList *list=(TList *)gFile->Get(name); \n\n TH2F *fK0sSi=(TH2F*)list->FindObject(\"fK0sSi\");fK0sSi->Sumw2();\n TH2F *fLambdaSi=(TH2F*)list->FindObject(\"fLambdaSi\");fLambdaSi->Sumw2();\n TH1F *fXiSiP=(TH1F*)list->FindObject(\"fXiSiP\"); fXiSiP->Sumw2();\n TH2F *fLambdaBarSi=\n (TH2F*)list->FindObject(\"fLambdaBarSi\"); fLambdaBarSi->Sumw2();\n TH1F *fXiBarSiP=(TH1F*)list->FindObject(\"fXiBarSiP\"); fXiBarSiP->Sumw2();\n\n TH1F *fMult=(TH1F*)list->FindObject(\"fMult\");\n \/\/+++++\n\n const Double_t nEvents=fMult->Integral();\n\n \/\/+++++ MC histograms\n TFile::Open(\"new\/mc_b_plus\/all\/\" + name + \"_mc.root\");\n TList *listmc=(TList *)gFile->Get(name+\"_mc\"); \n\n TH2F *fK0sMC=(TH2F*)listmc->FindObject(\"fK0sMC\"); fK0sMC->Sumw2();\n TH2F *fK0sAs=(TH2F*)listmc->FindObject(\"fK0sAs\"); fK0sAs->Sumw2();\n\n TH2F *fLambdaMC=(TH2F*)listmc->FindObject(\"fLambdaMC\"); fLambdaMC->Sumw2();\n TH2F *fLambdaAs=(TH2F*)listmc->FindObject(\"fLambdaAs\"); fLambdaAs->Sumw2();\n\n TH2F *fLambdaBarMC=\n (TH2F*)listmc->FindObject(\"fLambdaBarMC\"); fLambdaBarMC->Sumw2();\n TH2F *fLambdaBarAs=\n (TH2F*)listmc->FindObject(\"fLambdaBarAs\"); fLambdaBarAs->Sumw2();\n\n TH1F *fXiSiPMC=(TH1F*)listmc->FindObject(\"fXiSiP\");fXiSiPMC->Sumw2();\n TH3F *fLambdaFromXi=(TH3F*)listmc->FindObject(\"fLambdaFromXi\");\n fLambdaFromXi->Sumw2();\n\n TH1F *fXiBarSiPMC=(TH1F*)listmc->FindObject(\"fXiBarSiP\");fXiBarSiPMC->Sumw2();\n TH3F *fLambdaBarFromXiBar=(TH3F*)listmc->FindObject(\"fLambdaBarFromXiBar\");\n fLambdaBarFromXiBar->Sumw2();\n \/\/+++++\n\n\n Double_t myExp2(Double_t *v, Double_t *p);\n void Correct(TH1 *rw, const TH1 *as, const TH1 *mc);\n void Normalise(Double_t, Double_t, Double_t, Double_t, TH1 *h);\n\n const Int_t iMax=3; \/\/ Number of V0 particles\n const TString pnam[]={\"K^{0}_{S}\", \"#Lambda\", \"#bar{#Lambda}\"};\n const Double_t brch[]={0.69, 0.64, 0.64};\n const Double_t mass[]={0.4977, 1.115, 1.115};\n const Double_t ctau[]={2.68, 7.89, 7.89};\n const Double_t yWin=2*0.5; \/\/ rapidity window\n const Double_t wbx=fK0sSi->GetBinWidth(3);\n const Int_t nbx=fLambdaFromXi->GetNbinsX();\n const Int_t nby=fLambdaFromXi->GetNbinsY();\n const Int_t nbz=fLambdaFromXi->GetNbinsZ();\n\n const TH2 *in[]={\n fK0sSi,fK0sAs,fK0sMC,\n fLambdaSi,fLambdaAs,fLambdaMC,\n fLambdaBarSi,fLambdaBarAs,fLambdaBarMC\n };\n TH1 *fd[]={\n 0,0,0,\n fLambdaFromXi,fXiSiP,fXiSiPMC,\n fLambdaBarFromXiBar,fXiBarSiP,fXiBarSiPMC\n };\n \n for (Int_t i=0; iClone();\n Correct(cr, ptAs, ptMc);\n\n \/\/++++ pT spectrum\n if (corrType==1) {\n pt =ptRw->ProjectionX(\"_px\",0,-1,\"e\"); \n ptAsPx=ptAs->ProjectionX(\"_px\",0,-1,\"e\"); \n ptMcPx=ptMc->ProjectionX(\"_px\",0,-1,\"e\"); \n Correct(pt, ptAsPx, ptMcPx);\n\t \/*\n TString effName = \"Efficiency for \" + pnam[i] + \" (\" + name + \")\";\n TH1 *eff = (TH1*)ptAsPx->Clone();\n eff->SetTitle(effName.Data());\n eff->Divide(ptAsPx,ptMcPx,1,1,\"b\");\n eff->SetName(\"eff\");\n eff->Scale(brch[i]);\n new TCanvas; eff->Draw();\n\t *\/\n } else {\n pt=cr->ProjectionX(\"_px\",0,-1,\"e\");\n }\n TString ptName = pnam[i] + \" p_{T} spectrum\";\n pt->SetTitle(ptName.Data());\n Normalise(brch[i], yWin, wbx, nEvents, pt); \n\n new TCanvas; \n pt->Draw(); \n\n if (i>0) {\n \/\/++++ feeddown\n\t TH3 *fd3=(TH3*)fd[3*i + 0];\n\t TH1 *rl =(TH1*)fd[3*i + 1];\n\t TH1 *mc =(TH1*)fd[3*i + 2];\n\n Double_t nLambdaFromXiMc=fd3->Integral();\n Double_t nXiMc=mc->Integral();\n Double_t nXiRl=rl->Integral();\n Double_t f=(nLambdaFromXiMc*nXiRl\/nXiMc)\/ptRw->Integral();\n Double_t ef=f*TMath::Sqrt(nXiMc)\/nXiMc;\n cout<Divide(mc);\n \n for (Int_t k=1; k<=nbx; k++) {\n for (Int_t l=1; l<=nby; l++) {\n for (Int_t m=1; m<=nbz; m++) {\n Float_t c=fd3->GetBinContent(k,l,m);\n c *= rl->GetBinContent(m);\n fd3->SetBinContent(k,l,m,c);\n\t\t }\n\t }\n\t }\n\n TH2 *fd2=(TH2*)fd3->Project3D(\"yxe\");\n Correct(fd2, ptAs, ptMc);\n\n TH1 *fd1=0;\n if (corrType==1) {\n fd1=(TH1*)fd3->Project3D(\"x\");\n Correct(fd1, ptAsPx, ptMcPx);\n } else {\n fd1=fd2->ProjectionX(\"_px\",0,-1,\"e\");\n\t }\n Normalise(brch[i], yWin, wbx, nEvents, fd1);\n\n \/\/new TCanvas();\n fd1->Draw(\"same\");\n\n cr->Add(fd2,-1);\n } \n \/\/continue;\n \n \/\/++++ c*tau\n TF2 *f2=new TF2(\"myexpo2\",myExp2,0.,10.,0.,100.,1+1+1+nbx);\n f2->SetParameter(0, ctau[i]);\n f2->FixParameter(1, ctau[i]);\n f2->FixParameter(2, mass[i]);\n for (Int_t p=1+1+1; p<=nbx+1+1; p++) \n f2->SetParameter(p,fK0sSi->GetBinContent(p,1));\n\n new TCanvas; \n TFitResultPtr r=cr->Fit(f2,\"SQ\");\n\n Int_t status = r;\n Double_t chi2 = r->Chi2()\/r->Ndf(); \n Double_t slope = r->Parameter(0); \n Double_t error = r->ParError(0); \n cout< 2.5*ctau)) {\n TF1::RejectPoint();\n return 0; \n }\n\n Int_t i=pt\/0.1 + 1 + 1;\n return p[i]*TMath::Exp(-ct\/p[0]);\n}\n\nvoid Correct(TH1 *rw, const TH1 *as, const TH1 *mc) {\n TH1 *eff = (TH1*)as->Clone();\n eff->Divide(as,mc,1,1,\"b\");\n rw->Divide(eff);\n delete eff;\n} \n\nvoid Normalise(Double_t br, Double_t yw, Double_t bw, Double_t ne, TH1 *pt) {\n pt->Scale(1\/br); \/\/ branching ratio\n pt->Scale(1\/yw); \/\/ rapidity window\n pt->Scale(1\/bw); \/\/ bin width \n pt->Scale(1\/ne); \/\/ number of events\n}\nBranching is now included in efficiency#if !defined(__CINT__) || defined(__MAKECINT__)\n #include \n #include \n #include \n #include \n\n #include \n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#endif\n \nextern TROOT *gROOT;\n\/\/extern TFile *gFile;\n\n\nvoid PostProcessCTau(Int_t corrType=1) {\n \/\/-----------------------------------------------------------------\n \/\/ PostProcess the histograms produced by AliAnalysisTaskCTau* \n \/\/ Produce:\n \/\/ -- V0 particle spectra (not corrected for the feeddown)\n \/\/ -- Estimated (anti)Lambda feed-down spectra (from Xi's only)\n \/\/ -- V0 particle c*tau distributions (feeddown corrected) \n \/\/-----------------------------------------------------------------\n\n TString name(\"cTau_0090\"); \/\/centrality\n \/\/TString name(\"cTau_0005\"); \/\/centrality\n \/\/TString name(\"cTau_2040\"); \/\/centrality\n \/\/TString name(\"cTau_4060\"); \/\/centrality\n \/\/TString name(\"cTau_6080\"); \/\/centrality\n \/\/TString name(\"cTau_8090\"); \/\/centrality\n\n\n \/\/+++++ Real data histograms\n TFile::Open(\"new\/real\/all\/\" + name + \".root\");\n TList *list=(TList *)gFile->Get(name); \n\n TH2F *fK0sSi=(TH2F*)list->FindObject(\"fK0sSi\");fK0sSi->Sumw2();\n TH2F *fLambdaSi=(TH2F*)list->FindObject(\"fLambdaSi\");fLambdaSi->Sumw2();\n TH1F *fXiSiP=(TH1F*)list->FindObject(\"fXiSiP\"); fXiSiP->Sumw2();\n TH2F *fLambdaBarSi=\n (TH2F*)list->FindObject(\"fLambdaBarSi\"); fLambdaBarSi->Sumw2();\n TH1F *fXiBarSiP=(TH1F*)list->FindObject(\"fXiBarSiP\"); fXiBarSiP->Sumw2();\n\n TH1F *fMult=(TH1F*)list->FindObject(\"fMult\");\n \/\/+++++\n\n const Double_t nEvents=fMult->Integral();\n\n \/\/+++++ MC histograms\n TFile::Open(\"new\/mc_b_plus\/all\/\" + name + \"_mc.root\");\n TList *listmc=(TList *)gFile->Get(name+\"_mc\"); \n\n TH2F *fK0sMC=(TH2F*)listmc->FindObject(\"fK0sMC\"); fK0sMC->Sumw2();\n TH2F *fK0sAs=(TH2F*)listmc->FindObject(\"fK0sAs\"); fK0sAs->Sumw2();\n\n TH2F *fLambdaMC=(TH2F*)listmc->FindObject(\"fLambdaMC\"); fLambdaMC->Sumw2();\n TH2F *fLambdaAs=(TH2F*)listmc->FindObject(\"fLambdaAs\"); fLambdaAs->Sumw2();\n\n TH2F *fLambdaBarMC=\n (TH2F*)listmc->FindObject(\"fLambdaBarMC\"); fLambdaBarMC->Sumw2();\n TH2F *fLambdaBarAs=\n (TH2F*)listmc->FindObject(\"fLambdaBarAs\"); fLambdaBarAs->Sumw2();\n\n TH1F *fXiSiPMC=(TH1F*)listmc->FindObject(\"fXiSiP\");fXiSiPMC->Sumw2();\n TH3F *fLambdaFromXi=(TH3F*)listmc->FindObject(\"fLambdaFromXi\");\n fLambdaFromXi->Sumw2();\n\n TH1F *fXiBarSiPMC=(TH1F*)listmc->FindObject(\"fXiBarSiP\");fXiBarSiPMC->Sumw2();\n TH3F *fLambdaBarFromXiBar=(TH3F*)listmc->FindObject(\"fLambdaBarFromXiBar\");\n fLambdaBarFromXiBar->Sumw2();\n \/\/+++++\n\n\n Double_t myExp2(Double_t *v, Double_t *p);\n void Correct(TH1 *rw, const TH1 *as, const TH1 *mc);\n void Normalise(Double_t, Double_t, Double_t, TH1 *h);\n\n const Int_t iMax=3; \/\/ Number of V0 particles\n const TString pnam[]={\"K^{0}_{S}\", \"#Lambda\", \"#bar{#Lambda}\"};\n const Double_t brch[]={0.69, 0.64, 0.64};\n const Double_t mass[]={0.4977, 1.115, 1.115};\n const Double_t ctau[]={2.68, 7.89, 7.89};\n const Double_t yWin=2*0.5; \/\/ rapidity window\n const Double_t wbx=fK0sSi->GetBinWidth(3);\n const Int_t nbx=fLambdaFromXi->GetNbinsX();\n const Int_t nby=fLambdaFromXi->GetNbinsY();\n const Int_t nbz=fLambdaFromXi->GetNbinsZ();\n\n fK0sMC->Scale(1\/brch[0]);\n fLambdaMC->Scale(1\/brch[1]);\n fLambdaBarMC->Scale(1\/brch[2]);\n\n const TH2 *in[]={\n fK0sSi,fK0sAs,fK0sMC,\n fLambdaSi,fLambdaAs,fLambdaMC,\n fLambdaBarSi,fLambdaBarAs,fLambdaBarMC\n };\n TH1 *fd[]={\n 0,0,0,\n fLambdaFromXi,fXiSiP,fXiSiPMC,\n fLambdaBarFromXiBar,fXiBarSiP,fXiBarSiPMC\n };\n \n for (Int_t i=0; iClone();\n Correct(cr, ptAs, ptMc);\n\n \/\/++++ pT spectrum\n if (corrType==1) {\n pt =ptRw->ProjectionX(\"_px\",0,-1,\"e\"); \n ptAsPx=ptAs->ProjectionX(\"_px\",0,-1,\"e\"); \n ptMcPx=ptMc->ProjectionX(\"_px\",0,-1,\"e\"); \n Correct(pt, ptAsPx, ptMcPx);\n\t \n TString effName = \"Efficiency for \" + pnam[i] + \" (\" + name + \")\";\n TH1 *eff = (TH1*)ptAsPx->Clone();\n eff->SetTitle(effName.Data());\n eff->Divide(ptAsPx,ptMcPx,1,1,\"b\");\n eff->SetName(\"eff\");\n new TCanvas; eff->Draw();\n } else {\n pt=cr->ProjectionX(\"_px\",0,-1,\"e\");\n }\n TString ptName = pnam[i] + \" p_{T} spectrum\";\n pt->SetTitle(ptName.Data());\n Normalise(yWin, wbx, nEvents, pt); \n\n new TCanvas; \n pt->Draw(); \n\n if (i>0) {\n \/\/++++ feeddown\n\t TH3 *fd3=(TH3*)fd[3*i + 0];\n\t TH1 *rl =(TH1*)fd[3*i + 1];\n\t TH1 *mc =(TH1*)fd[3*i + 2];\n\n Double_t nLambdaFromXiMc=fd3->Integral();\n Double_t nXiMc=mc->Integral();\n Double_t nXiRl=rl->Integral();\n Double_t f=(nLambdaFromXiMc*nXiRl\/nXiMc)\/ptRw->Integral();\n Double_t ef=f*TMath::Sqrt(nXiMc)\/nXiMc;\n cout<Divide(mc);\n \n for (Int_t k=1; k<=nbx; k++) {\n for (Int_t l=1; l<=nby; l++) {\n for (Int_t m=1; m<=nbz; m++) {\n Float_t c=fd3->GetBinContent(k,l,m);\n c *= rl->GetBinContent(m);\n fd3->SetBinContent(k,l,m,c);\n\t\t }\n\t }\n\t }\n\n TH2 *fd2=(TH2*)fd3->Project3D(\"yxe\");\n Correct(fd2, ptAs, ptMc);\n\n TH1 *fd1=0;\n if (corrType==1) {\n fd1=(TH1*)fd3->Project3D(\"x\");\n Correct(fd1, ptAsPx, ptMcPx);\n } else {\n fd1=fd2->ProjectionX(\"_px\",0,-1,\"e\");\n\t }\n Normalise(yWin, wbx, nEvents, fd1);\n\n \/\/new TCanvas();\n fd1->Draw(\"same\");\n\n cr->Add(fd2,-1);\n } \n continue;\n \n \/\/++++ c*tau\n TF2 *f2=new TF2(\"myexpo2\",myExp2,0.,10.,0.,100.,1+1+1+nbx);\n f2->SetParameter(0, ctau[i]);\n f2->FixParameter(1, ctau[i]);\n f2->FixParameter(2, mass[i]);\n for (Int_t p=1+1+1; p<=nbx+1+1; p++) \n f2->SetParameter(p,fK0sSi->GetBinContent(p,1));\n\n new TCanvas; \n TFitResultPtr r=cr->Fit(f2,\"SQ\");\n\n Int_t status = r;\n Double_t chi2 = r->Chi2()\/r->Ndf(); \n Double_t slope = r->Parameter(0); \n Double_t error = r->ParError(0); \n cout< 2.5*ctau)) {\n TF1::RejectPoint();\n return 0; \n }\n\n Int_t i=pt\/0.1 + 1 + 1;\n return p[i]*TMath::Exp(-ct\/p[0]);\n}\n\nvoid Correct(TH1 *rw, const TH1 *as, const TH1 *mc) {\n TH1 *eff = (TH1*)as->Clone();\n eff->Divide(as,mc,1,1,\"b\");\n rw->Divide(eff);\n delete eff;\n} \n\nvoid Normalise(Double_t yw, Double_t bw, Double_t ne, TH1 *pt) {\n pt->Scale(1\/yw); \/\/ rapidity window\n pt->Scale(1\/bw); \/\/ bin width \n pt->Scale(1\/ne); \/\/ number of events\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * Copyright (c) 2013 Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Kevin Lim\n *\/\n\n#include \n\n#include \"cpu\/o3\/rename_map.hh\"\n#include \"debug\/Rename.hh\"\n\nusing namespace std;\n\n\/**** SimpleRenameMap methods ****\/\n\nSimpleRenameMap::SimpleRenameMap()\n : freeList(NULL), zeroReg(0)\n{\n}\n\n\nvoid\nSimpleRenameMap::init(unsigned size, SimpleFreeList *_freeList,\n RegIndex _zeroReg)\n{\n assert(freeList == NULL);\n assert(map.empty());\n\n map.resize(size);\n freeList = _freeList;\n zeroReg = _zeroReg;\n}\n\nSimpleRenameMap::RenameInfo\nSimpleRenameMap::rename(RegIndex arch_reg)\n{\n PhysRegIndex renamed_reg;\n\n \/\/ Record the current physical register that is renamed to the\n \/\/ requested architected register.\n PhysRegIndex prev_reg = map[arch_reg];\n\n \/\/ If it's not referencing the zero register, then rename the\n \/\/ register.\n if (arch_reg != zeroReg) {\n renamed_reg = freeList->getReg();\n\n map[arch_reg] = renamed_reg;\n } else {\n \/\/ Otherwise return the zero register so nothing bad happens.\n assert(prev_reg == zeroReg);\n renamed_reg = zeroReg;\n }\n\n DPRINTF(Rename, \"Renamed reg %d to physical reg %d old mapping was %d\\n\",\n arch_reg, renamed_reg, prev_reg);\n\n return RenameInfo(renamed_reg, prev_reg);\n}\n\n\n\/**** UnifiedRenameMap methods ****\/\n\nvoid\nUnifiedRenameMap::init(PhysRegFile *_regFile,\n RegIndex _intZeroReg,\n RegIndex _floatZeroReg,\n UnifiedFreeList *freeList)\n{\n regFile = _regFile;\n\n intMap.init(TheISA::NumIntRegs, &(freeList->intList), _intZeroReg);\n\n floatMap.init(TheISA::NumFloatRegs, &(freeList->floatList), _floatZeroReg);\n\n ccMap.init(TheISA::NumFloatRegs, &(freeList->ccList), (RegIndex)-1);\n}\n\n\nUnifiedRenameMap::RenameInfo\nUnifiedRenameMap::rename(RegIndex arch_reg)\n{\n RegIndex rel_arch_reg;\n\n switch (regIdxToClass(arch_reg, &rel_arch_reg)) {\n case IntRegClass:\n return renameInt(rel_arch_reg);\n\n case FloatRegClass:\n return renameFloat(rel_arch_reg);\n\n case CCRegClass:\n return renameCC(rel_arch_reg);\n\n case MiscRegClass:\n return renameMisc(rel_arch_reg);\n\n default:\n panic(\"rename rename(): unknown reg class %s\\n\",\n RegClassStrings[regIdxToClass(arch_reg)]);\n }\n}\n\n\nPhysRegIndex\nUnifiedRenameMap::lookup(RegIndex arch_reg) const\n{\n RegIndex rel_arch_reg;\n\n switch (regIdxToClass(arch_reg, &rel_arch_reg)) {\n case IntRegClass:\n return lookupInt(rel_arch_reg);\n\n case FloatRegClass:\n return lookupFloat(rel_arch_reg);\n\n case CCRegClass:\n return lookupCC(rel_arch_reg);\n\n case MiscRegClass:\n return lookupMisc(rel_arch_reg);\n\n default:\n panic(\"rename lookup(): unknown reg class %s\\n\",\n RegClassStrings[regIdxToClass(arch_reg)]);\n }\n}\n\nvoid\nUnifiedRenameMap::setEntry(RegIndex arch_reg, PhysRegIndex phys_reg)\n{\n RegIndex rel_arch_reg;\n\n switch (regIdxToClass(arch_reg, &rel_arch_reg)) {\n case IntRegClass:\n return setIntEntry(rel_arch_reg, phys_reg);\n\n case FloatRegClass:\n return setFloatEntry(rel_arch_reg, phys_reg);\n\n case CCRegClass:\n return setCCEntry(rel_arch_reg, phys_reg);\n\n case MiscRegClass:\n \/\/ Misc registers do not actually rename, so don't change\n \/\/ their mappings. We end up here when a commit or squash\n \/\/ tries to update or undo a hardwired misc reg nmapping,\n \/\/ which should always be setting it to what it already is.\n assert(phys_reg == lookupMisc(rel_arch_reg));\n return;\n\n default:\n panic(\"rename setEntry(): unknown reg class %s\\n\",\n RegClassStrings[regIdxToClass(arch_reg)]);\n }\n}\no3: correct the number of cc registers in rename map\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * Copyright (c) 2013 Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Kevin Lim\n *\/\n\n#include \n\n#include \"cpu\/o3\/rename_map.hh\"\n#include \"debug\/Rename.hh\"\n\nusing namespace std;\n\n\/**** SimpleRenameMap methods ****\/\n\nSimpleRenameMap::SimpleRenameMap()\n : freeList(NULL), zeroReg(0)\n{\n}\n\n\nvoid\nSimpleRenameMap::init(unsigned size, SimpleFreeList *_freeList,\n RegIndex _zeroReg)\n{\n assert(freeList == NULL);\n assert(map.empty());\n\n map.resize(size);\n freeList = _freeList;\n zeroReg = _zeroReg;\n}\n\nSimpleRenameMap::RenameInfo\nSimpleRenameMap::rename(RegIndex arch_reg)\n{\n PhysRegIndex renamed_reg;\n\n \/\/ Record the current physical register that is renamed to the\n \/\/ requested architected register.\n PhysRegIndex prev_reg = map[arch_reg];\n\n \/\/ If it's not referencing the zero register, then rename the\n \/\/ register.\n if (arch_reg != zeroReg) {\n renamed_reg = freeList->getReg();\n\n map[arch_reg] = renamed_reg;\n } else {\n \/\/ Otherwise return the zero register so nothing bad happens.\n assert(prev_reg == zeroReg);\n renamed_reg = zeroReg;\n }\n\n DPRINTF(Rename, \"Renamed reg %d to physical reg %d old mapping was %d\\n\",\n arch_reg, renamed_reg, prev_reg);\n\n return RenameInfo(renamed_reg, prev_reg);\n}\n\n\n\/**** UnifiedRenameMap methods ****\/\n\nvoid\nUnifiedRenameMap::init(PhysRegFile *_regFile,\n RegIndex _intZeroReg,\n RegIndex _floatZeroReg,\n UnifiedFreeList *freeList)\n{\n regFile = _regFile;\n\n intMap.init(TheISA::NumIntRegs, &(freeList->intList), _intZeroReg);\n\n floatMap.init(TheISA::NumFloatRegs, &(freeList->floatList), _floatZeroReg);\n\n ccMap.init(TheISA::NumCCRegs, &(freeList->ccList), (RegIndex)-1);\n}\n\n\nUnifiedRenameMap::RenameInfo\nUnifiedRenameMap::rename(RegIndex arch_reg)\n{\n RegIndex rel_arch_reg;\n\n switch (regIdxToClass(arch_reg, &rel_arch_reg)) {\n case IntRegClass:\n return renameInt(rel_arch_reg);\n\n case FloatRegClass:\n return renameFloat(rel_arch_reg);\n\n case CCRegClass:\n return renameCC(rel_arch_reg);\n\n case MiscRegClass:\n return renameMisc(rel_arch_reg);\n\n default:\n panic(\"rename rename(): unknown reg class %s\\n\",\n RegClassStrings[regIdxToClass(arch_reg)]);\n }\n}\n\n\nPhysRegIndex\nUnifiedRenameMap::lookup(RegIndex arch_reg) const\n{\n RegIndex rel_arch_reg;\n\n switch (regIdxToClass(arch_reg, &rel_arch_reg)) {\n case IntRegClass:\n return lookupInt(rel_arch_reg);\n\n case FloatRegClass:\n return lookupFloat(rel_arch_reg);\n\n case CCRegClass:\n return lookupCC(rel_arch_reg);\n\n case MiscRegClass:\n return lookupMisc(rel_arch_reg);\n\n default:\n panic(\"rename lookup(): unknown reg class %s\\n\",\n RegClassStrings[regIdxToClass(arch_reg)]);\n }\n}\n\nvoid\nUnifiedRenameMap::setEntry(RegIndex arch_reg, PhysRegIndex phys_reg)\n{\n RegIndex rel_arch_reg;\n\n switch (regIdxToClass(arch_reg, &rel_arch_reg)) {\n case IntRegClass:\n return setIntEntry(rel_arch_reg, phys_reg);\n\n case FloatRegClass:\n return setFloatEntry(rel_arch_reg, phys_reg);\n\n case CCRegClass:\n return setCCEntry(rel_arch_reg, phys_reg);\n\n case MiscRegClass:\n \/\/ Misc registers do not actually rename, so don't change\n \/\/ their mappings. We end up here when a commit or squash\n \/\/ tries to update or undo a hardwired misc reg nmapping,\n \/\/ which should always be setting it to what it already is.\n assert(phys_reg == lookupMisc(rel_arch_reg));\n return;\n\n default:\n panic(\"rename setEntry(): unknown reg class %s\\n\",\n RegClassStrings[regIdxToClass(arch_reg)]);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/modest\/ModuleLoader.h\"\n#include \"db\/modest\/ModuleApi.h\"\n#include \"db\/rt\/DynamicLibrary.h\"\n\n#include \n\nusing namespace db::modest;\nusing namespace db::rt;\n\nModuleLoader::ModuleLoader()\n{\n}\n\nModuleLoader::~ModuleLoader()\n{\n}\n\nModuleInfo* ModuleLoader::loadModule(const char* filename)\n{\n ModuleInfo* rval = NULL;\n \n \/\/ open library\n void* handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);\n if(handle != NULL)\n {\n CreateModestModuleFn create;\n FreeModestModuleFn free;\n \n \/\/ clear error\n char* error = dlerror();\n \n \/\/ try to get create module function\n create = (CreateModestModuleFn)dlsym(handle, \"createModestModule\");\n if((error = dlerror()) == NULL)\n {\n \/\/ clear error\n error = dlerror();\n \n \/\/ try to get free module function\n free = (FreeModestModuleFn)dlsym(handle, \"freeModestModule\");\n error = dlerror();\n }\n \n if(error == NULL)\n {\n \/\/ create ModuleInfo\n rval = new ModuleInfo();\n rval->handle = handle;\n rval->module = create();\n rval->freeModule = free;\n }\n else\n {\n \/\/ could not load create or free functions\n char temp[100 + strlen(filename) + strlen(error)];\n sprintf(temp, \"Could not load module '%s', error=%s\", filename, error);\n ExceptionRef e = new Exception(temp, \"db.modest.BadModule\");\n Exception::setLast(e, false);\n }\n }\n else\n {\n \/\/ failed to open module\n char* error = dlerror();\n char temp[100 + strlen(filename) + strlen(error)];\n sprintf(temp,\n \"Could not load module '%s', could not open module file, error=%s\",\n filename, error);\n ExceptionRef e = new Exception(temp, \"db.modest.BadModuleFile\");\n Exception::setLast(e, false);\n }\n \n return rval;\n}\n\nvoid ModuleLoader::unloadModule(ModuleInfo* mi)\n{\n \/\/ free module\n mi->freeModule(mi->module);\n \n \/\/ close handle\n dlclose(mi->handle);\n \n \/\/ delete module info\n delete mi;\n}\nCleaned up exception code.\/*\n * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/modest\/ModuleLoader.h\"\n\n#include \"db\/modest\/ModuleApi.h\"\n#include \"db\/rt\/DynamicLibrary.h\"\n#include \"db\/rt\/DynamicObject.h\"\n\n#include \n\nusing namespace db::modest;\nusing namespace db::rt;\n\nModuleLoader::ModuleLoader()\n{\n}\n\nModuleLoader::~ModuleLoader()\n{\n}\n\nModuleInfo* ModuleLoader::loadModule(const char* filename)\n{\n ModuleInfo* rval = NULL;\n \n \/\/ open library\n void* handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);\n if(handle != NULL)\n {\n CreateModestModuleFn create;\n FreeModestModuleFn free;\n \n \/\/ clear error\n char* error = dlerror();\n \n \/\/ try to get create module function\n create = (CreateModestModuleFn)dlsym(handle, \"createModestModule\");\n if((error = dlerror()) == NULL)\n {\n \/\/ clear error\n error = dlerror();\n \n \/\/ try to get free module function\n free = (FreeModestModuleFn)dlsym(handle, \"freeModestModule\");\n error = dlerror();\n }\n \n if(error == NULL)\n {\n \/\/ create ModuleInfo\n rval = new ModuleInfo();\n rval->handle = handle;\n rval->module = create();\n rval->freeModule = free;\n }\n else\n {\n \/\/ could not load create or free functions\n ExceptionRef e = new Exception(\n \"Could not load module.\", \"db.modest.BadModule\");\n e->getDetails()[\"filename\"] = filename;\n e->getDetails()[\"error\"] = error;\n Exception::setLast(e, false);\n }\n }\n else\n {\n \/\/ failed to open module\n char* error = dlerror();\n ExceptionRef e = new Exception(\n \"Could not open module file.\", \"db.modest.BadModuleFile\");\n e->getDetails()[\"filename\"] = filename;\n e->getDetails()[\"error\"] = error;\n Exception::setLast(e, false);\n }\n \n return rval;\n}\n\nvoid ModuleLoader::unloadModule(ModuleInfo* mi)\n{\n \/\/ free module\n mi->freeModule(mi->module);\n \n \/\/ close handle\n dlclose(mi->handle);\n \n \/\/ delete module info\n delete mi;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/test\/Test.h\"\n#include \"db\/test\/Tester.h\"\n#include \"db\/test\/TestRunner.h\"\n#include \"db\/io\/ByteArrayInputStream.h\"\n#include \"db\/data\/xml\/DomTypes.h\"\n#include \"db\/upnp\/ControlPoint.h\"\n#include \"db\/upnp\/DeviceDiscoverer.h\"\n#include \"db\/upnp\/SoapEnvelope.h\"\n\nusing namespace std;\nusing namespace db::test;\nusing namespace db::data::xml;\nusing namespace db::io;\nusing namespace db::rt;\nusing namespace db::upnp;\n\nvoid runSoapEnvelopeTest(TestRunner& tr)\n{\n tr.group(\"SoapEnvelope\");\n \n tr.test(\"create\");\n {\n const char* expect =\n \"\"\n \"\"\n \"\"\n \"IBM<\/m:StockName>\"\n \"<\/m:GetStockPrice>\"\n \"<\/soap:Body>\"\n \"<\/soap:Envelope>\";\n \n SoapEnvelope env;\n SoapMessage msg;\n msg[\"name\"] = \"GetStockPrice\";\n msg[\"namespace\"] = \"http:\/\/www.example.org\/stock\";\n msg[\"params\"][\"StockName\"] = \"IBM\";\n string envelope = env.create(msg);\n \n assertStrCmp(expect, envelope.c_str());\n }\n tr.passIfNoException();\n \n tr.test(\"parse message\");\n {\n const char* expect =\n \"\"\n \"\"\n \"\"\n \"IBM<\/m:StockName>\"\n \"<\/m:GetStockPrice>\"\n \"<\/soap:Body>\"\n \"<\/soap:Envelope>\";\n \n ByteArrayInputStream bais(expect, strlen(expect));\n \n SoapEnvelope env;\n SoapResult result;\n env.parse(&bais, result);\n assertNoException();\n \n \/\/ result is not a fault\n assert(!result[\"fault\"]->getBoolean());\n \n \/\/ compare message\n SoapMessage expectMessage;\n expectMessage[\"name\"] = \"GetStockPrice\";\n expectMessage[\"namespace\"] = \"http:\/\/www.example.org\/stock\";\n expectMessage[\"params\"][\"StockName\"] = \"IBM\";\n assert(expectMessage == result[\"message\"]);\n }\n tr.passIfNoException();\n \n tr.test(\"parse fault\");\n {\n const char* expect =\n \"\"\n \"\"\n \"\"\n \"soap:Client.AppError<\/faultcode>\"\n \"Application Error<\/faultstring>\"\n \"\"\n \"You did something wrong.<\/message>\"\n \"1000<\/errorcode>\"\n \"<\/detail>\"\n \"<\/soap:Fault>\"\n \"<\/soap:Body>\"\n \"<\/soap:Envelope>\";\n \n ByteArrayInputStream bais(expect, strlen(expect));\n \n SoapEnvelope env;\n SoapResult result;\n env.parse(&bais, result);\n assertNoException();\n \n \/\/ result is a fault\n assert(result[\"fault\"]->getBoolean());\n \n \/\/ compare message\n SoapMessage expectMessage;\n expectMessage[\"name\"] = \"Fault\";\n expectMessage[\"namespace\"] = \"http:\/\/schemas.xmlsoap.org\/soap\/envelope\";\n expectMessage[\"params\"][\"faultcode\"] = \"soap:Client.AppError\";\n expectMessage[\"params\"][\"faultstring\"] = \"Application Error\";\n expectMessage[\"params\"][\"detail\"][\"message\"] = \"You did something wrong.\";\n expectMessage[\"params\"][\"detail\"][\"errorcode\"] = 1000;\n assert(expectMessage == result[\"message\"]);\n }\n tr.passIfNoException();\n \n tr.ungroup();\n}\n\nvoid runPortMappingTest(TestRunner& tr)\n{\n tr.group(\"PortMapping\");\n \n PortMapping mapping;\n mapping[\"NewRemoteHost\"] = \"\";\n mapping[\"NewExternalPort\"] = 19100;\n mapping[\"NewProtocol\"] = \"TCP\";\n mapping[\"NewInternalPort\"] = 19100;\n mapping[\"NewInternalClient\"] = \"10.10.0.10\";\n mapping[\"NewEnabled\"] = \"1\";\n mapping[\"NewPortMappingDescription\"] = \"A test port mapping.\";\n mapping[\"NewLeaseDuration\"] = \"0\";\n \n Device igd(NULL);\n Service wipcs(NULL);\n \n tr.test(\"discover internet gateway device\");\n {\n \/\/ search for 1 internet gateway device... 30 seconds to find one\n DeviceDiscoverer dd;\n DeviceList devices;\n if(dd.discover(devices, UPNP_DEVICE_TYPE_IGD, 30 * 1000, 1) == 1)\n {\n \/\/ found!\n igd = devices.first();\n }\n assert(!igd.isNull());\n }\n tr.passIfNoException();\n \n tr.test(\"get device description\");\n {\n ControlPoint cp;\n cp.getDeviceDescription(igd);\n assertNoException();\n }\n tr.passIfNoException();\n \n tr.test(\"get wan ip connection service\");\n {\n ControlPoint cp;\n wipcs = cp.getWanIpConnectionService(igd);\n assert(!wipcs.isNull());\n }\n tr.passIfNoException();\n \n tr.test(\"get service description\");\n {\n ControlPoint cp;\n cp.getServiceDescription(wipcs);\n assertNoException();\n }\n tr.passIfNoException();\n#if 0\n tr.test(\"remove if exists\");\n {\n ControlPoint cp;\n PortMapping pm = mapping.clone();\n bool dne;\n if(!cp.removePortMapping(pm, wipcs, &dne))\n {\n \/\/ if dne then the mapping already does not exist, which is fine\n if(dne)\n {\n Exception::clear();\n }\n }\n }\n tr.passIfNoException();\n#endif\n tr.test(\"add mapping\");\n {\n ControlPoint cp;\n PortMapping pm = mapping.clone();\n cp.addPortMapping(pm, wipcs);\n }\n tr.passIfNoException();\n \n tr.test(\"get all mappings\");\n {\n ControlPoint cp;\n PortMapping pm;\n pm->setType(Map);\n printf(\"\\nSTART PORT MAPPINGS:\\n\");\n for(int i = 0; !pm.isNull(); i++)\n {\n pm->clear();\n if(cp.getPortMapping(pm, i, wipcs))\n {\n if(pm.isNull())\n {\n \/\/ last port mapping found\n Exception::clear();\n }\n else\n {\n dumpDynamicObject(pm);\n }\n }\n else\n {\n pm.setNull();\n }\n }\n printf(\"END PORT MAPPINGS.\\n\");\n }\n tr.passIfNoException();\n \n tr.test(\"get specific mapping\");\n {\n ControlPoint cp;\n PortMapping pm;\n pm[\"NewRemoteHost\"] = mapping[\"NewRemoteHost\"].clone();\n pm[\"NewExternalPort\"] = mapping[\"NewExternalPort\"].clone();\n pm[\"NewProtocol\"] = mapping[\"NewProtocol\"].clone();\n cp.getPortMapping(pm, wipcs);\n \/\/dumpDynamicObject(pm);\n assert(pm == mapping);\n }\n tr.passIfNoException();\n#if 0\n tr.test(\"remove mapping\");\n {\n ControlPoint cp;\n PortMapping pm = mapping.clone();\n cp.removePortMapping(pm, wipcs, NULL);\n }\n tr.passIfNoException();\n#endif\n tr.ungroup();\n}\n\nclass DbUpnpTester : public db::test::Tester\n{\npublic:\n DbUpnpTester()\n {\n setName(\"upnp\");\n }\n\n \/**\n * Run automatic unit tests.\n *\/\n virtual int runAutomaticTests(TestRunner& tr)\n {\n runSoapEnvelopeTest(tr);\n \n return 0;\n }\n\n \/**\n * Runs interactive unit tests.\n *\/\n virtual int runInteractiveTests(TestRunner& tr)\n {\n runPortMappingTest(tr);\n \n return 0;\n }\n};\n\ndb::test::Tester* getDbUpnpTester() { return new DbUpnpTester(); }\n\n\nDB_TEST_MAIN(DbUpnpTester)\nAdded test to get all mappings after deleting the test mapping.\/*\n * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \"db\/test\/Test.h\"\n#include \"db\/test\/Tester.h\"\n#include \"db\/test\/TestRunner.h\"\n#include \"db\/io\/ByteArrayInputStream.h\"\n#include \"db\/data\/xml\/DomTypes.h\"\n#include \"db\/upnp\/ControlPoint.h\"\n#include \"db\/upnp\/DeviceDiscoverer.h\"\n#include \"db\/upnp\/SoapEnvelope.h\"\n\nusing namespace std;\nusing namespace db::test;\nusing namespace db::data::xml;\nusing namespace db::io;\nusing namespace db::rt;\nusing namespace db::upnp;\n\nvoid runSoapEnvelopeTest(TestRunner& tr)\n{\n tr.group(\"SoapEnvelope\");\n \n tr.test(\"create\");\n {\n const char* expect =\n \"\"\n \"\"\n \"\"\n \"IBM<\/m:StockName>\"\n \"<\/m:GetStockPrice>\"\n \"<\/soap:Body>\"\n \"<\/soap:Envelope>\";\n \n SoapEnvelope env;\n SoapMessage msg;\n msg[\"name\"] = \"GetStockPrice\";\n msg[\"namespace\"] = \"http:\/\/www.example.org\/stock\";\n msg[\"params\"][\"StockName\"] = \"IBM\";\n string envelope = env.create(msg);\n \n assertStrCmp(expect, envelope.c_str());\n }\n tr.passIfNoException();\n \n tr.test(\"parse message\");\n {\n const char* expect =\n \"\"\n \"\"\n \"\"\n \"IBM<\/m:StockName>\"\n \"<\/m:GetStockPrice>\"\n \"<\/soap:Body>\"\n \"<\/soap:Envelope>\";\n \n ByteArrayInputStream bais(expect, strlen(expect));\n \n SoapEnvelope env;\n SoapResult result;\n env.parse(&bais, result);\n assertNoException();\n \n \/\/ result is not a fault\n assert(!result[\"fault\"]->getBoolean());\n \n \/\/ compare message\n SoapMessage expectMessage;\n expectMessage[\"name\"] = \"GetStockPrice\";\n expectMessage[\"namespace\"] = \"http:\/\/www.example.org\/stock\";\n expectMessage[\"params\"][\"StockName\"] = \"IBM\";\n assert(expectMessage == result[\"message\"]);\n }\n tr.passIfNoException();\n \n tr.test(\"parse fault\");\n {\n const char* expect =\n \"\"\n \"\"\n \"\"\n \"soap:Client.AppError<\/faultcode>\"\n \"Application Error<\/faultstring>\"\n \"\"\n \"You did something wrong.<\/message>\"\n \"1000<\/errorcode>\"\n \"<\/detail>\"\n \"<\/soap:Fault>\"\n \"<\/soap:Body>\"\n \"<\/soap:Envelope>\";\n \n ByteArrayInputStream bais(expect, strlen(expect));\n \n SoapEnvelope env;\n SoapResult result;\n env.parse(&bais, result);\n assertNoException();\n \n \/\/ result is a fault\n assert(result[\"fault\"]->getBoolean());\n \n \/\/ compare message\n SoapMessage expectMessage;\n expectMessage[\"name\"] = \"Fault\";\n expectMessage[\"namespace\"] = \"http:\/\/schemas.xmlsoap.org\/soap\/envelope\";\n expectMessage[\"params\"][\"faultcode\"] = \"soap:Client.AppError\";\n expectMessage[\"params\"][\"faultstring\"] = \"Application Error\";\n expectMessage[\"params\"][\"detail\"][\"message\"] = \"You did something wrong.\";\n expectMessage[\"params\"][\"detail\"][\"errorcode\"] = 1000;\n assert(expectMessage == result[\"message\"]);\n }\n tr.passIfNoException();\n \n tr.ungroup();\n}\n\nvoid runPortMappingTest(TestRunner& tr)\n{\n tr.group(\"PortMapping\");\n \n PortMapping mapping;\n mapping[\"NewRemoteHost\"] = \"\";\n mapping[\"NewExternalPort\"] = 19100;\n mapping[\"NewProtocol\"] = \"TCP\";\n mapping[\"NewInternalPort\"] = 19100;\n mapping[\"NewInternalClient\"] = \"10.10.0.10\";\n mapping[\"NewEnabled\"] = \"1\";\n mapping[\"NewPortMappingDescription\"] = \"A test port mapping.\";\n mapping[\"NewLeaseDuration\"] = \"0\";\n \n Device igd(NULL);\n Service wipcs(NULL);\n \n tr.test(\"discover internet gateway device\");\n {\n \/\/ search for 1 internet gateway device... 30 seconds to find one\n DeviceDiscoverer dd;\n DeviceList devices;\n if(dd.discover(devices, UPNP_DEVICE_TYPE_IGD, 30 * 1000, 1) == 1)\n {\n \/\/ found!\n igd = devices.first();\n }\n assert(!igd.isNull());\n }\n tr.passIfNoException();\n \n tr.test(\"get device description\");\n {\n ControlPoint cp;\n cp.getDeviceDescription(igd);\n assertNoException();\n }\n tr.passIfNoException();\n \n tr.test(\"get wan ip connection service\");\n {\n ControlPoint cp;\n wipcs = cp.getWanIpConnectionService(igd);\n assert(!wipcs.isNull());\n }\n tr.passIfNoException();\n \n tr.test(\"get service description\");\n {\n ControlPoint cp;\n cp.getServiceDescription(wipcs);\n assertNoException();\n }\n tr.passIfNoException();\n \n tr.test(\"remove if exists\");\n {\n ControlPoint cp;\n PortMapping pm = mapping.clone();\n bool dne;\n if(!cp.removePortMapping(pm, wipcs, &dne))\n {\n \/\/ if dne then the mapping already does not exist, which is fine\n if(dne)\n {\n Exception::clear();\n }\n }\n }\n tr.passIfNoException();\n \n tr.test(\"add mapping\");\n {\n ControlPoint cp;\n PortMapping pm = mapping.clone();\n cp.addPortMapping(pm, wipcs);\n }\n tr.passIfNoException();\n \n tr.test(\"get all mappings\");\n {\n ControlPoint cp;\n PortMapping pm;\n pm->setType(Map);\n printf(\"\\nSTART PORT MAPPINGS:\\n\");\n for(int i = 0; !pm.isNull(); i++)\n {\n pm->clear();\n if(cp.getPortMapping(pm, i, wipcs))\n {\n if(pm.isNull())\n {\n \/\/ last port mapping found\n Exception::clear();\n }\n else\n {\n dumpDynamicObject(pm);\n }\n }\n else\n {\n pm.setNull();\n }\n }\n printf(\"END PORT MAPPINGS.\\n\");\n }\n tr.passIfNoException();\n \n tr.test(\"get specific mapping\");\n {\n ControlPoint cp;\n PortMapping pm;\n pm[\"NewRemoteHost\"] = mapping[\"NewRemoteHost\"].clone();\n pm[\"NewExternalPort\"] = mapping[\"NewExternalPort\"].clone();\n pm[\"NewProtocol\"] = mapping[\"NewProtocol\"].clone();\n cp.getPortMapping(pm, wipcs);\n \/\/dumpDynamicObject(pm);\n assert(pm == mapping);\n }\n tr.passIfNoException();\n \n tr.test(\"remove mapping\");\n {\n ControlPoint cp;\n PortMapping pm = mapping.clone();\n cp.removePortMapping(pm, wipcs, NULL);\n }\n tr.passIfNoException();\n \n tr.test(\"get all mappings after remove\");\n {\n ControlPoint cp;\n PortMapping pm;\n pm->setType(Map);\n printf(\"\\nSTART PORT MAPPINGS:\\n\");\n for(int i = 0; !pm.isNull(); i++)\n {\n pm->clear();\n if(cp.getPortMapping(pm, i, wipcs))\n {\n if(pm.isNull())\n {\n \/\/ last port mapping found\n Exception::clear();\n }\n else\n {\n dumpDynamicObject(pm);\n }\n }\n else\n {\n pm.setNull();\n }\n }\n printf(\"END PORT MAPPINGS.\\n\");\n }\n tr.passIfNoException();\n \n tr.ungroup();\n}\n\nclass DbUpnpTester : public db::test::Tester\n{\npublic:\n DbUpnpTester()\n {\n setName(\"upnp\");\n }\n\n \/**\n * Run automatic unit tests.\n *\/\n virtual int runAutomaticTests(TestRunner& tr)\n {\n runSoapEnvelopeTest(tr);\n \n return 0;\n }\n\n \/**\n * Runs interactive unit tests.\n *\/\n virtual int runInteractiveTests(TestRunner& tr)\n {\n runPortMappingTest(tr);\n \n return 0;\n }\n};\n\ndb::test::Tester* getDbUpnpTester() { return new DbUpnpTester(); }\n\n\nDB_TEST_MAIN(DbUpnpTester)\n<|endoftext|>"} {"text":"\/\/******************************************************************\n\/\/\n\/\/ Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n#ifndef OC_LOG_STREAM_HPP_\n#define OC_LOG_STREAM_HPP_\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"oc_logger.h\"\n\nnamespace OC {\n\nclass oc_log_stream : boost::iostreams::sink\n{\n std::shared_ptr m_log;\n\n public:\n typedef char char_type;\n typedef boost::iostreams::sink_tag category;\n\n public:\n template \n oc_log_stream(ContextCtor& c)\n : m_log { c(), oc_log_destroy }\n {}\n\n template \n oc_log_stream(ContextCtor& c, void *world)\n : m_log { c(world), oc_log_destroy }\n {}\n\n public:\n inline void flush() BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }\n inline void set_level(const oc_log_level new_level) BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }\n inline int set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }\n\n public:\n std::streamsize write(const char_type *s, std::streamsize n)\n {\n \/* It may seem strange to do this here, but it's a consequence of the\n underlying library not supporting ptr+len style buffers at this time: *\/\n std::string s2(s, n + s);\n\n oc_log_write(m_log.get(), s2.c_str());\n\n return n;\n }\n\n private:\n oc_log_stream operator=(const oc_log_stream&) = delete;\n};\n\n} \/\/ namespace OC\n\n#endif\noc_logger: Removing \/W4 warnings\/\/******************************************************************\n\/\/\n\/\/ Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n#ifndef OC_LOG_STREAM_HPP_\n#define OC_LOG_STREAM_HPP_\n\n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ Warning disabled due to a known \"unreachable code\" issue in boost iostreams.\n\/\/ For more information see: https:\/\/svn.boost.org\/trac\/boost\/ticket\/5904\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable : 4702)\n#endif\n\n#include \n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n#include \n#include \n\n#include \"oc_logger.h\"\n\nnamespace OC {\n\nclass oc_log_stream : boost::iostreams::sink\n{\n std::shared_ptr m_log;\n\n public:\n typedef char char_type;\n typedef boost::iostreams::sink_tag category;\n\n public:\n template \n oc_log_stream(ContextCtor& c)\n : m_log { c(), oc_log_destroy }\n {}\n\n template \n oc_log_stream(ContextCtor& c, void *world)\n : m_log { c(world), oc_log_destroy }\n {}\n\n public:\n inline void flush() BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }\n inline void set_level(const oc_log_level new_level) BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }\n inline int set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }\n\n public:\n std::streamsize write(const char_type *s, std::streamsize n)\n {\n \/* It may seem strange to do this here, but it's a consequence of the\n underlying library not supporting ptr+len style buffers at this time: *\/\n std::string s2(s, n + s);\n\n oc_log_write(m_log.get(), s2.c_str());\n\n return n;\n }\n\n private:\n oc_log_stream operator=(const oc_log_stream&) = delete;\n};\n\n} \/\/ namespace OC\n\n#endif\n<|endoftext|>"} {"text":"\/* -*- Mode: C -*-\n\n $Id$\n\n Copyright (C) 2001 by Klarlvdalens Datakonsult AB\n\n GPGMEPLUG is free software; you can redistribute it and\/or modify\n it under the terms of GNU General Public License as published by\n the Free Software Foundation; version 2 of the License.\n\n GPGMEPLUG is distributed in the hope that it will be useful,\n it under the terms of GNU General Public License as published by\n the Free Software Foundation; version 2 of the License\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"certificateinfowidgetimpl.h\"\n#include \"certmanager.h\"\n\nCertificateInfoWidgetImpl::CertificateInfoWidgetImpl( CertManager* manager, bool external,\n\t\t\t\t\t\t QWidget* parent, const char* name )\n : CertificateInfoWidget( parent, name ), _manager(manager), _external( external )\n{\n if( !external ) importButton->setEnabled(false);\n listView->setColumnWidthMode( 1, QListView::Manual );\n listView->setResizeMode( QListView::LastColumn );\n QFontMetrics fm = fontMetrics();\n listView->setColumnWidth( 1, fm.width( i18n(\"Information\") ) * 5 );\n\n listView->header()->setClickEnabled( false );\n listView->setSorting( -1 );\n\n connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ),\n\t this, SLOT( slotShowInfo( QListViewItem* ) ) );\n pathView->setColumnWidthMode( 0, QListView::Manual );\n pathView->setResizeMode( QListView::LastColumn );\n pathView->header()->hide();\n\n connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ),\n\t this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );\n connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ),\n\t this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );\n connect( importButton, SIGNAL( clicked() ),\n\t this, SLOT( slotImportCertificate() ) );\n}\n\nvoid CertificateInfoWidgetImpl::setCert( const CryptPlugWrapper::CertificateInfo& info )\n{\n listView->clear();\n pathView->clear();\n _info = info;\n\n \/* Check if we already have the cert in question *\/\n if( _manager ) {\n importButton->setEnabled( !_manager->haveCertificate( info.fingerprint ) );\n } else { \n importButton->setEnabled( false );\n }\n \/\/ These will show in the opposite order\n new QListViewItem( listView, i18n(\"Fingerprint\"), info.fingerprint );\n new QListViewItem( listView, i18n(\"Can be used for certification\"), \n\t\t info.certify?i18n(\"Yes\"):i18n(\"No\") );\n new QListViewItem( listView, i18n(\"Can be used for encryption\"), \n\t\t info.encrypt?i18n(\"Yes\"):i18n(\"No\") );\n new QListViewItem( listView, i18n(\"Can be used for signing\"), \n\t\t info.sign?i18n(\"Yes\"):i18n(\"No\") );\n\n new QListViewItem( listView, i18n(\"Valid\"), QString(\"From %1 to %2\")\n\t\t .arg( info.created.toString() ).arg(info.expire.toString()) );\n\n\n \/\/new QListViewItem( listView, i18n(\"Email\"), info.dn[\"1.2.840.113549.1.9.1\"] );\n new QListViewItem( listView, i18n(\"Country\"), info.dn[\"C\"] );\n new QListViewItem( listView, i18n(\"Organizational Unit\"), info.dn[\"OU\"] );\n new QListViewItem( listView, i18n(\"Organization\"), info.dn[\"O\"] );\n new QListViewItem( listView, i18n(\"Location\"), info.dn[\"L\"] );\n new QListViewItem( listView, i18n(\"Name\"), info.dn[\"CN\"] );\n new QListViewItem( listView, i18n(\"Issuer\"), info.issuer.stripWhiteSpace() );\n\n QStringList::ConstIterator it = info.userid.begin();\n QListViewItem* item = new QListViewItem( listView, i18n(\"Subject\"), \n\t\t\t (*it).stripWhiteSpace() );\n ++it;\n while( it != info.userid.end() ) {\n if( (*it)[0] == '<' ) {\n item = new QListViewItem( listView, item, i18n(\"Email\"), (*it).mid(1,(*it).length()-2));\n } else {\n item = new QListViewItem( listView, item, i18n(\"Aka\"), (*it).stripWhiteSpace() );\n }\n ++it; \n } \n\n \/\/ Set up cert. path\n if( !_manager ) return;\n const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();\n QString issuer = info.issuer;\n QStringList items;\n items << info.userid[0];\n while( true ) {\n bool found = false;\n CryptPlugWrapper::CertificateInfo info;\n for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();\n\t it != lst.end(); ++it ) {\n if( (*it).userid[0] == issuer && !items.contains( info.userid[0] ) ) {\n\tinfo = (*it);\n\tfound = true;\n\tbreak;\n }\n }\n if( found ) {\n items.prepend( info.userid[0] );\n issuer = info.issuer;\n \/\/ FIXME(steffen): Use real DN comparison\n if( info.userid[0] == info.issuer ) {\n\t\/\/ Root item\n\tbreak;\n } \n } else break;\n }\n item = 0;\n for( QStringList::Iterator it = items.begin(); it != items.end(); ++it ) {\n if( item ) item = new QListViewItem( item, (*it) );\n else item = new QListViewItem( pathView, (*it) );\n item->setOpen( true );\n }\n}\n\nvoid CertificateInfoWidgetImpl::slotShowInfo( QListViewItem* item )\n{\n textView->setText( item->text(1) );\n}\n\nvoid CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem* item )\n{\n if( !_manager ) return;\n const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();\n for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();\n it != lst.end(); ++it ) {\n if( (*it).userid[0] == item->text(0) ) {\n KDialogBase* dialog = new KDialogBase( this, \"dialog\", true, i18n(\"Additional Information for Key\"), KDialogBase::Close, KDialogBase::Close );\n\n CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog );\n dialog->setMainWidget( top );\n top->setCert( *it ); \n dialog->exec();\n delete dialog;\n }\n }\n}\n\n\n\nvoid CertificateInfoWidgetImpl::slotImportCertificate()\n{\n if( !_manager ) return;\n QApplication::setOverrideCursor( QCursor::WaitCursor );\n QString info;\n int retval = _manager->importCertificateWithFingerprint( _info.fingerprint, &info );\n QApplication::restoreOverrideCursor();\n\n if( retval == -42 ) {\n KMessageBox::error( this, i18n(\"Cryptplug returned success, but no certiftcate was imported.\\nYou may need to import the issuer certificate %1 first.\").arg( _info.issuer ), i18n(\"Import error\") ); \n } else if( retval ) {\n KMessageBox::error( this, i18n(\"Error importing certificate.\\nCryptPlug returned %1. Additional info: %2\").arg(retval).arg( info ), i18n(\"Import error\") );\n } else {\n KMessageBox::information( this, i18n(\"Certificate %1 with fingerprint %2 is imported to the local database. Additional info: %3\").arg(_info.userid[0]).arg(_info.fingerprint).arg( info ), i18n(\"Certificate Imported\") );\n importButton->setEnabled( false );\n }\n}\n#include \"certificateinfowidgetimpl.moc\"\nindicate when the root certificate is unknown\/* -*- Mode: C -*-\n\n $Id$\n\n Copyright (C) 2001 by Klarlvdalens Datakonsult AB\n\n GPGMEPLUG is free software; you can redistribute it and\/or modify\n it under the terms of GNU General Public License as published by\n the Free Software Foundation; version 2 of the License.\n\n GPGMEPLUG is distributed in the hope that it will be useful,\n it under the terms of GNU General Public License as published by\n the Free Software Foundation; version 2 of the License\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"certificateinfowidgetimpl.h\"\n#include \"certmanager.h\"\n\nCertificateInfoWidgetImpl::CertificateInfoWidgetImpl( CertManager* manager, bool external,\n\t\t\t\t\t\t QWidget* parent, const char* name )\n : CertificateInfoWidget( parent, name ), _manager(manager), _external( external )\n{\n if( !external ) importButton->setEnabled(false);\n listView->setColumnWidthMode( 1, QListView::Manual );\n listView->setResizeMode( QListView::LastColumn );\n QFontMetrics fm = fontMetrics();\n listView->setColumnWidth( 1, fm.width( i18n(\"Information\") ) * 5 );\n\n listView->header()->setClickEnabled( false );\n listView->setSorting( -1 );\n\n connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ),\n\t this, SLOT( slotShowInfo( QListViewItem* ) ) );\n pathView->setColumnWidthMode( 0, QListView::Manual );\n pathView->setResizeMode( QListView::LastColumn );\n pathView->header()->hide();\n\n connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ),\n\t this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );\n connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ),\n\t this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );\n connect( importButton, SIGNAL( clicked() ),\n\t this, SLOT( slotImportCertificate() ) );\n}\n\nvoid CertificateInfoWidgetImpl::setCert( const CryptPlugWrapper::CertificateInfo& info )\n{\n listView->clear();\n pathView->clear();\n _info = info;\n\n \/* Check if we already have the cert in question *\/\n if( _manager ) {\n importButton->setEnabled( !_manager->haveCertificate( info.fingerprint ) );\n } else { \n importButton->setEnabled( false );\n }\n \/\/ These will show in the opposite order\n new QListViewItem( listView, i18n(\"Fingerprint\"), info.fingerprint );\n new QListViewItem( listView, i18n(\"Can be used for certification\"), \n\t\t info.certify?i18n(\"Yes\"):i18n(\"No\") );\n new QListViewItem( listView, i18n(\"Can be used for encryption\"), \n\t\t info.encrypt?i18n(\"Yes\"):i18n(\"No\") );\n new QListViewItem( listView, i18n(\"Can be used for signing\"), \n\t\t info.sign?i18n(\"Yes\"):i18n(\"No\") );\n\n new QListViewItem( listView, i18n(\"Valid\"), QString(\"From %1 to %2\")\n\t\t .arg( info.created.toString() ).arg(info.expire.toString()) );\n\n\n \/\/new QListViewItem( listView, i18n(\"Email\"), info.dn[\"1.2.840.113549.1.9.1\"] );\n new QListViewItem( listView, i18n(\"Country\"), info.dn[\"C\"] );\n new QListViewItem( listView, i18n(\"Organizational Unit\"), info.dn[\"OU\"] );\n new QListViewItem( listView, i18n(\"Organization\"), info.dn[\"O\"] );\n new QListViewItem( listView, i18n(\"Location\"), info.dn[\"L\"] );\n new QListViewItem( listView, i18n(\"Name\"), info.dn[\"CN\"] );\n new QListViewItem( listView, i18n(\"Issuer\"), info.issuer.stripWhiteSpace() );\n\n QStringList::ConstIterator it = info.userid.begin();\n QListViewItem* item = new QListViewItem( listView, i18n(\"Subject\"), \n\t\t\t (*it).stripWhiteSpace() );\n ++it;\n while( it != info.userid.end() ) {\n if( (*it)[0] == '<' ) {\n item = new QListViewItem( listView, item, i18n(\"Email\"), (*it).mid(1,(*it).length()-2));\n } else {\n item = new QListViewItem( listView, item, i18n(\"Aka\"), (*it).stripWhiteSpace() );\n }\n ++it; \n } \n\n \/\/ Set up cert. path\n if( !_manager ) return;\n const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();\n QString issuer = info.issuer;\n QStringList items;\n items << info.userid[0];\n bool root_found = false;\n while( true ) {\n bool found = false;\n CryptPlugWrapper::CertificateInfo info;\n for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();\n\t it != lst.end(); ++it ) {\n if( (*it).userid[0] == issuer && !items.contains( info.userid[0] ) ) {\n\tinfo = (*it);\n\tfound = true;\n\tbreak;\n }\n }\n if( found ) {\n items.prepend( info.userid[0] );\n issuer = info.issuer;\n \/\/ FIXME(steffen): Use real DN comparison\n if( info.userid[0] == info.issuer ) {\n\t\/\/ Root item\n\troot_found = true;\n\tbreak;\n } \n } else break;\n }\n item = 0;\n if( !root_found ) {\n if( items.count() > 0 ) items.prepend( QString::fromUtf8(\"Root certificate not found (%1)\").arg( issuer ) );\n else items.prepend( \"Root certificate not found\" );\n }\n for( QStringList::Iterator it = items.begin(); it != items.end(); ++it ) {\n if( item ) item = new QListViewItem( item, (*it) );\n else item = new QListViewItem( pathView, (*it) );\n item->setOpen( true );\n }\n}\n\nvoid CertificateInfoWidgetImpl::slotShowInfo( QListViewItem* item )\n{\n textView->setText( item->text(1) );\n}\n\nvoid CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem* item )\n{\n if( !_manager ) return;\n const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();\n for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();\n it != lst.end(); ++it ) {\n if( (*it).userid[0] == item->text(0) ) {\n KDialogBase* dialog = new KDialogBase( this, \"dialog\", true, i18n(\"Additional Information for Key\"), KDialogBase::Close, KDialogBase::Close );\n\n CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog );\n dialog->setMainWidget( top );\n top->setCert( *it ); \n dialog->exec();\n delete dialog;\n }\n }\n}\n\n\n\nvoid CertificateInfoWidgetImpl::slotImportCertificate()\n{\n if( !_manager ) return;\n QApplication::setOverrideCursor( QCursor::WaitCursor );\n QString info;\n int retval = _manager->importCertificateWithFingerprint( _info.fingerprint, &info );\n QApplication::restoreOverrideCursor();\n\n if( retval == -42 ) {\n KMessageBox::error( this, i18n(\"Cryptplug returned success, but no certiftcate was imported.\\nYou may need to import the issuer certificate %1 first.\").arg( _info.issuer ), i18n(\"Import error\") ); \n } else if( retval ) {\n KMessageBox::error( this, i18n(\"Error importing certificate.\\nCryptPlug returned %1. Additional info: %2\").arg(retval).arg( info ), i18n(\"Import error\") );\n } else {\n KMessageBox::information( this, i18n(\"Certificate %1 with fingerprint %2 is imported to the local database. Additional info: %3\").arg(_info.userid[0]).arg(_info.fingerprint).arg( info ), i18n(\"Certificate Imported\") );\n importButton->setEnabled( false );\n }\n}\n#include \"certificateinfowidgetimpl.moc\"\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace Doremi::Utilities;\n\nSpecificLogFile::SpecificLogFile() : m_fileStream(nullptr), m_timer(nullptr), m_flushTimerLimit(0), m_elapsedTime(0) {}\n\nSpecificLogFile::~SpecificLogFile()\n{\n if(m_fileStream != nullptr)\n {\n m_fileStream->close();\n delete m_fileStream;\n }\n\n if(m_timer != nullptr)\n {\n delete m_timer;\n }\n}\n\nvoid SpecificLogFile::Initialize(const Logging::LogTag& p_logTag)\n{\n m_flushTimerLimit = 1.0;\n m_timer = new Chrono::Timer();\n Logging::LogTagInfo fileNameInfo = Logging::LogTagConverter::convert(p_logTag);\n fileNameInfo.name.append(\".txt\");\n BuildLogFile(fileNameInfo.name);\n OpenFileStream(fileNameInfo.name);\n}\n\nvoid SpecificLogFile::BuildLogFile(const std::string& p_fileName)\n{\n void* fileHandle = CreateFile(String::StringToWideString(p_fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);\n if(fileHandle == nullptr)\n {\n const std::string message = std::string(\"Failed to build logfile with given name: \") + p_fileName;\n throw std::runtime_error(message);\n }\n CloseHandle(fileHandle);\n}\n\nvoid SpecificLogFile::OpenFileStream(const std::string& p_fileName)\n{\n m_fileStream = new std::ofstream(p_fileName, std::ofstream::out | std::ofstream::app);\n if(m_fileStream->is_open() == false)\n {\n const std::string message = std::string(\"Failed to open filestream to given filename: \") + p_fileName;\n throw std::runtime_error(message);\n }\n}\n\nvoid SpecificLogFile::Write(void*& p_data)\n{\n \/\/ Rebuilddata\n const Logging::TextMetaData* textMetaData = static_cast(p_data);\n\n \/\/ Fetch pointer to function text\n void* function = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData));\n\n \/\/ Fetch pointer to messagetext\n void* message = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData) + textMetaData->functionLength);\n\n \/\/ Actually cout the data to a file\n *m_fileStream << static_cast(message) << \"\\n\";\n if(textMetaData->logLevel == Logging::LogLevel::INFO)\n {\n std::cout << static_cast(message) << \"\\n\";\n }\n\n \/\/ If called often, flush\n m_elapsedTime += m_timer->Tick().GetElapsedTimeInSeconds();\n if(m_elapsedTime > m_flushTimerLimit)\n {\n Flush();\n }\n}\n\nvoid SpecificLogFile::Flush()\n{\n m_elapsedTime = 0;\n m_fileStream->flush();\n}\nColor in logger, also logs more of the message#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace Doremi::Utilities;\n\nSpecificLogFile::SpecificLogFile() : m_fileStream(nullptr), m_timer(nullptr), m_flushTimerLimit(0), m_elapsedTime(0) {}\n\nSpecificLogFile::~SpecificLogFile()\n{\n if(m_fileStream != nullptr)\n {\n m_fileStream->close();\n delete m_fileStream;\n }\n\n if(m_timer != nullptr)\n {\n delete m_timer;\n }\n}\n\nvoid SpecificLogFile::Initialize(const Logging::LogTag& p_logTag)\n{\n m_flushTimerLimit = 1.0;\n m_timer = new Chrono::Timer();\n Logging::LogTagInfo fileNameInfo = Logging::LogTagConverter::convert(p_logTag);\n fileNameInfo.name.append(\".txt\");\n BuildLogFile(fileNameInfo.name);\n OpenFileStream(fileNameInfo.name);\n}\n\nvoid SpecificLogFile::BuildLogFile(const std::string& p_fileName)\n{\n void* fileHandle = CreateFile(String::StringToWideString(p_fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);\n if(fileHandle == nullptr)\n {\n const std::string message = std::string(\"Failed to build logfile with given name: \") + p_fileName;\n throw std::runtime_error(message);\n }\n CloseHandle(fileHandle);\n}\n\nvoid SpecificLogFile::OpenFileStream(const std::string& p_fileName)\n{\n m_fileStream = new std::ofstream(p_fileName, std::ofstream::out | std::ofstream::app);\n if(m_fileStream->is_open() == false)\n {\n const std::string message = std::string(\"Failed to open filestream to given filename: \") + p_fileName;\n throw std::runtime_error(message);\n }\n}\n\nvoid SpecificLogFile::Write(void*& p_data)\n{\n using namespace Logging;\n \/\/ Rebuilddata\n const Logging::TextMetaData* textMetaData = static_cast(p_data);\n\n \/\/ Fetch pointer to function text\n void* function = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData));\n\n \/\/ Fetch pointer to messagetext\n void* message = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData) + textMetaData->functionLength);\n\n auto& logtag = LogTagConverter::convert(textMetaData->logTag).name;\n auto& logLevel = LogLevelConverter::convert(textMetaData->logLevel).name;\n\n \/\/ Actually cout the data to a file\n *m_fileStream << \"[\" << logtag << \":\" << logLevel << \"] \" << static_cast(message) << \"\\n\";\n if(textMetaData->logLevel == Logging::LogLevel::INFO)\n {\n if(textMetaData->logLevel == LogLevel::WARNING)\n {\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14);\n }\n else if(textMetaData->logLevel == LogLevel::FATAL_ERROR)\n {\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);\n }\n else\n {\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);\n }\n std::cout << \"[\" << logtag << \":\" << logLevel << \"] \" << static_cast(message) << \"\\n\";\n }\n\n \/\/ If called often, flush\n m_elapsedTime += m_timer->Tick().GetElapsedTimeInSeconds();\n if(m_elapsedTime > m_flushTimerLimit)\n {\n Flush();\n }\n}\n\nvoid SpecificLogFile::Flush()\n{\n m_elapsedTime = 0;\n m_fileStream->flush();\n}\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n\/***********************************************************************************************************************\n * SceneHandlerItem.cpp\n *\n * Created on: Jan 17, 2011\n * Author: Dimitar Asenov\n **********************************************************************************************************************\/\n\n#include \"items\/SceneHandlerItem.h\"\n#include \"Scene.h\"\n#include \"items\/ItemStyle.h\"\n\nnamespace Visualization {\n\nITEM_COMMON_DEFINITIONS(SceneHandlerItem, \"item\")\n\nSceneHandlerItem::SceneHandlerItem(Scene* scene) :\n\tItem(nullptr, itemStyles().get())\n{\n\t\/\/ It should be possible to click inside the item. This happens when the user clicks on an \"empty\" space in the scene\n\t\/\/ as this item is automatically moved to that empty spot before the click is processed.\n\tsetSize(3,3);\n\tscene->addItem(this);\n\n\t\/\/ Make sure this item is behind all others.\n\tsetZValue(Item::LAYER_DEFAULT_Z - 1);\n}\n\nvoid SceneHandlerItem::determineChildren()\n{\n}\n\nvoid SceneHandlerItem::updateGeometry(int, int)\n{\n}\n\n}\nMake the scenehandler item be a menu item\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n\/***********************************************************************************************************************\n * SceneHandlerItem.cpp\n *\n * Created on: Jan 17, 2011\n * Author: Dimitar Asenov\n **********************************************************************************************************************\/\n\n#include \"items\/SceneHandlerItem.h\"\n#include \"Scene.h\"\n#include \"items\/ItemStyle.h\"\n\nnamespace Visualization {\n\nITEM_COMMON_DEFINITIONS(SceneHandlerItem, \"item\")\n\nSceneHandlerItem::SceneHandlerItem(Scene* scene) :\n\tItem(nullptr, itemStyles().get())\n{\n\t\/\/ It should be possible to click inside the item. This happens when the user clicks on an \"empty\" space in the scene\n\t\/\/ as this item is automatically moved to that empty spot before the click is processed.\n\tsetSize(3,3);\n\tsetItemCategory(Scene::MenuItemCategory);\n\tscene->addItem(this);\n\n\t\/\/ Make sure this item is behind all others.\n\tsetZValue(Item::LAYER_DEFAULT_Z - 1);\n}\n\nvoid SceneHandlerItem::determineChildren()\n{\n}\n\nvoid SceneHandlerItem::updateGeometry(int, int)\n{\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLES2PixelFormat.h\"\n#include \"OgreRoot.h\"\n#include \"OgreRenderSystem.h\"\n#include \"OgreBitwise.h\"\n\nnamespace Ogre {\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n return GL_ALPHA;\n\n case PF_L8:\n case PF_L16:\n case PF_FLOAT16_R:\n case PF_FLOAT32_R:\n return GL_LUMINANCE;\n\n case PF_BYTE_LA:\n case PF_SHORT_GR:\n case PF_FLOAT16_GR:\n case PF_FLOAT32_GR:\n return GL_LUMINANCE_ALPHA;\n\n \/\/ PVRTC compressed formats\n#if GL_IMG_texture_compression_pvrtc\n case PF_PVRTC_RGB2:\n return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGB4:\n return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n case PF_PVRTC_RGBA2:\n return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGBA4:\n return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n#endif \n case PF_R5G6B5:\n case PF_B5G6R5:\n return GL_RGB;\n\n case PF_A1R5G5B5:\n return GL_BGRA;\n case PF_A4R4G4B4:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n return GL_RGBA;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n \/\/ Formats are in native endian, so R8G8B8 on little endian is\n \/\/ BGR, on big endian it is RGB.\n case PF_R8G8B8:\n return GL_RGB;\n case PF_B8G8R8:\n return 0;\n#else\n case PF_R8G8B8:\n return GL_RGB;\n case PF_B8G8R8:\n return 0;\n#endif\n case PF_DXT1:\n#if GL_EXT_texture_compression_dxt1\n return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\n#endif\n case PF_DXT3:\n#if GL_EXT_texture_compression_s3tc\n return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n#endif\n case PF_DXT5:\n#if GL_EXT_texture_compression_s3tc\n return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\n#endif\n default:\n return 0;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n case PF_L8:\n case PF_L16:\n case PF_R8G8B8:\n case PF_B8G8R8:\n case PF_BYTE_LA:\n return GL_UNSIGNED_BYTE;\n case PF_R5G6B5:\n case PF_B5G6R5:\n return GL_UNSIGNED_SHORT_5_6_5;\n case PF_A4R4G4B4:\n\t\t\t\treturn GL_UNSIGNED_SHORT_4_4_4_4;\n case PF_A1R5G5B5:\n return GL_UNSIGNED_SHORT_5_5_5_1;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_B8G8R8A8:\n return GL_UNSIGNED_BYTE;\n case PF_R8G8B8A8:\n return GL_UNSIGNED_BYTE;\n#else\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_R8G8B8A8:\n return GL_UNSIGNED_BYTE;\n#endif\n case PF_DXT1:\n case PF_DXT3:\n case PF_DXT5:\n case PF_R3G3B2:\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n \/\/ TODO not supported\n default:\n return 0;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)\n {\n switch (fmt)\n {\n case PF_L8:\n case PF_L16:\n return GL_LUMINANCE;\n\n case PF_A8:\n return GL_ALPHA;\n\n case PF_BYTE_LA:\n return GL_LUMINANCE_ALPHA;\n\n#if GL_IMG_texture_compression_pvrtc\n case PF_PVRTC_RGB2:\n return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGB4:\n return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n case PF_PVRTC_RGBA2:\n return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGBA4:\n return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n#endif\n \n case PF_X8B8G8R8:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_A1R5G5B5:\n case PF_A4R4G4B4:\n return GL_RGBA;\n case PF_R5G6B5:\n case PF_B5G6R5:\n case PF_R8G8B8:\n case PF_B8G8R8:\n return GL_RGB;\n case PF_A4L4:\n case PF_R3G3B2:\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_R:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_GR:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n\t\t\tcase PF_DXT1:\n#if GL_EXT_texture_compression_dxt1\n\t\t\t\tif (!hwGamma)\n\t\t\t\t\treturn GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\n#endif\n case PF_DXT3:\n#if GL_EXT_texture_compression_s3tc\n\t\t\t\tif (!hwGamma)\n\t return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n#endif\n case PF_DXT5:\n#if GL_EXT_texture_compression_s3tc\n\t\t\t\tif (!hwGamma)\n\t return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n#endif\n default:\n return 0;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,\n bool hwGamma)\n {\n GLenum format = getGLInternalFormat(mFormat, hwGamma);\n if (format == GL_NONE)\n {\n if (hwGamma)\n {\n \/\/ TODO not supported\n return 0;\n }\n else\n {\n return GL_RGBA;\n }\n }\n else\n {\n return format;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum fmt, GLenum dataType)\n {\n switch (fmt)\n {\n#if GL_IMG_texture_compression_pvrtc\n case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:\n return PF_PVRTC_RGB2;\n case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:\n return PF_PVRTC_RGBA2;\n case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:\n return PF_PVRTC_RGB4;\n case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:\n return PF_PVRTC_RGBA4;\n#endif\n case GL_LUMINANCE:\n return PF_L8;\n case GL_ALPHA:\n return PF_A8;\n case GL_LUMINANCE_ALPHA:\n return PF_BYTE_LA;\n \n case GL_RGB:\n switch(dataType)\n {\n case GL_UNSIGNED_SHORT_5_6_5:\n return PF_B5G6R5;\n default:\n return PF_R8G8B8;\n };\n case GL_RGBA:\n switch(dataType)\n {\n case GL_UNSIGNED_SHORT_5_5_5_1:\n return PF_A1R5G5B5;\n case GL_UNSIGNED_SHORT_4_4_4_4:\n return PF_A4R4G4B4;\n default:\n#if (OGRE_PLATFORM == OGRE_PLATFORM_TEGRA2)\n return PF_X8B8G8R8;\n#elif (OGRE_PLATFORM == OGRE_PLATFORM_ANDROID)\n return PF_A8B8G8R8;\n#else\n return PF_A8R8G8B8;\n#endif\n }\n#ifdef GL_BGRA\n case GL_BGRA:\n return PF_A8B8G8R8;\n#endif\n\n#if GL_EXT_texture_compression_dxt1\n case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:\n case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:\n return PF_DXT1;\n#endif\n#if GL_EXT_texture_compression_s3tc\n case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:\n return PF_DXT3;\n case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:\n return PF_DXT5;\n#endif\n default:\n \/\/TODO: not supported\n return PF_A8R8G8B8;\n };\n }\n\t\/\/-----------------------------------------------------------------------------\n size_t GLES2PixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,\n PixelFormat format)\n {\n size_t count = 0;\n\n do {\n if (width > 1)\n {\n width = width \/ 2;\n }\n if (height > 1)\n {\n height = height \/ 2;\n }\n if (depth > 1)\n {\n depth = depth \/ 2;\n }\n \/*\n NOT needed, compressed formats will have mipmaps up to 1x1\n if(PixelUtil::isValidExtent(width, height, depth, format))\n count ++;\n else\n break;\n *\/\n count++;\n } while (!(width == 1 && height == 1 && depth == 1));\n\n return count;\n }\n\t\/\/-----------------------------------------------------------------------------\n size_t GLES2PixelUtil::optionalPO2(size_t value)\n {\n const RenderSystemCapabilities *caps =\n Root::getSingleton().getRenderSystem()->getCapabilities();\n\n if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))\n {\n return value;\n }\n else\n {\n return Bitwise::firstPO2From((uint32)value);\n }\n }\n\n void GLES2PixelUtil::convertToGLformat(const PixelBox &src, const PixelBox &dst)\n {\n \/\/ Always need to convert PF_A4R4G4B4, GL expects the colors to be in the \n \/\/ reverse order\n if (dst.format == PF_A4R4G4B4)\n {\n \/\/ Convert PF_A4R4G4B4 -> PF_B4G4R4A4\n \/\/ Reverse pixel order\n uint16 *srcptr = static_cast(src.data)\n\t\t\t+ (src.left + src.top * src.rowPitch + src.front * src.slicePitch);\n uint16 *dstptr = static_cast(dst.data)\n\t\t\t+ (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch);\n const size_t srcSliceSkip = src.getSliceSkip();\n const size_t dstSliceSkip = dst.getSliceSkip();\n const size_t k = src.right - src.left;\n for(size_t z=src.front; z>4) | \/\/ R\n ((srcptr[x]&0xF000)>>12); \/\/ A\n }\n srcptr += src.rowPitch;\n dstptr += dst.rowPitch;\n }\n srcptr += srcSliceSkip;\n dstptr += dstSliceSkip;\n } \n }\n }\n}\nGLES2: Fix the use of B8G8R8 textures.\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreGLES2PixelFormat.h\"\n#include \"OgreRoot.h\"\n#include \"OgreRenderSystem.h\"\n#include \"OgreBitwise.h\"\n\nnamespace Ogre {\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n return GL_ALPHA;\n\n case PF_L8:\n case PF_L16:\n case PF_FLOAT16_R:\n case PF_FLOAT32_R:\n return GL_LUMINANCE;\n\n case PF_BYTE_LA:\n case PF_SHORT_GR:\n case PF_FLOAT16_GR:\n case PF_FLOAT32_GR:\n return GL_LUMINANCE_ALPHA;\n\n \/\/ PVRTC compressed formats\n#if GL_IMG_texture_compression_pvrtc\n case PF_PVRTC_RGB2:\n return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGB4:\n return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n case PF_PVRTC_RGBA2:\n return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGBA4:\n return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n#endif \n case PF_R5G6B5:\n case PF_B5G6R5:\n case PF_R8G8B8:\n case PF_B8G8R8:\n return GL_RGB;\n\n case PF_A1R5G5B5:\n return GL_BGRA;\n case PF_A4R4G4B4:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n return GL_RGBA;\n\n case PF_DXT1:\n#if GL_EXT_texture_compression_dxt1\n return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\n#endif\n case PF_DXT3:\n#if GL_EXT_texture_compression_s3tc\n return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n#endif\n case PF_DXT5:\n#if GL_EXT_texture_compression_s3tc\n return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\n#endif\n default:\n return 0;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat mFormat)\n {\n switch (mFormat)\n {\n case PF_A8:\n case PF_L8:\n case PF_L16:\n case PF_R8G8B8:\n case PF_B8G8R8:\n case PF_BYTE_LA:\n return GL_UNSIGNED_BYTE;\n case PF_R5G6B5:\n case PF_B5G6R5:\n return GL_UNSIGNED_SHORT_5_6_5;\n case PF_A4R4G4B4:\n\t\t\t\treturn GL_UNSIGNED_SHORT_4_4_4_4;\n case PF_A1R5G5B5:\n return GL_UNSIGNED_SHORT_5_5_5_1;\n\n#if OGRE_ENDIAN == OGRE_ENDIAN_BIG\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n case PF_B8G8R8A8:\n return GL_UNSIGNED_BYTE;\n case PF_R8G8B8A8:\n return GL_UNSIGNED_BYTE;\n#else\n case PF_X8B8G8R8:\n case PF_A8B8G8R8:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_R8G8B8A8:\n return GL_UNSIGNED_BYTE;\n#endif\n case PF_DXT1:\n case PF_DXT3:\n case PF_DXT5:\n case PF_R3G3B2:\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n \/\/ TODO not supported\n default:\n return 0;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma)\n {\n switch (fmt)\n {\n case PF_L8:\n case PF_L16:\n return GL_LUMINANCE;\n\n case PF_A8:\n return GL_ALPHA;\n\n case PF_BYTE_LA:\n return GL_LUMINANCE_ALPHA;\n\n#if GL_IMG_texture_compression_pvrtc\n case PF_PVRTC_RGB2:\n return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGB4:\n return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;\n case PF_PVRTC_RGBA2:\n return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;\n case PF_PVRTC_RGBA4:\n return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;\n#endif\n \n case PF_X8B8G8R8:\n case PF_X8R8G8B8:\n case PF_A8R8G8B8:\n case PF_B8G8R8A8:\n case PF_A1R5G5B5:\n case PF_A4R4G4B4:\n return GL_RGBA;\n case PF_R5G6B5:\n case PF_B5G6R5:\n case PF_R8G8B8:\n case PF_B8G8R8:\n return GL_RGB;\n case PF_A4L4:\n case PF_R3G3B2:\n case PF_A2R10G10B10:\n case PF_A2B10G10R10:\n case PF_FLOAT16_R:\n case PF_FLOAT16_RGB:\n case PF_FLOAT16_GR:\n case PF_FLOAT16_RGBA:\n case PF_FLOAT32_R:\n case PF_FLOAT32_GR:\n case PF_FLOAT32_RGB:\n case PF_FLOAT32_RGBA:\n case PF_SHORT_RGBA:\n case PF_SHORT_RGB:\n case PF_SHORT_GR:\n\t\t\tcase PF_DXT1:\n#if GL_EXT_texture_compression_dxt1\n\t\t\t\tif (!hwGamma)\n\t\t\t\t\treturn GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\n#endif\n case PF_DXT3:\n#if GL_EXT_texture_compression_s3tc\n\t\t\t\tif (!hwGamma)\n\t return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n#endif\n case PF_DXT5:\n#if GL_EXT_texture_compression_s3tc\n\t\t\t\tif (!hwGamma)\n\t return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\n#endif\n default:\n return 0;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n GLenum GLES2PixelUtil::getClosestGLInternalFormat(PixelFormat mFormat,\n bool hwGamma)\n {\n GLenum format = getGLInternalFormat(mFormat, hwGamma);\n if (format == GL_NONE)\n {\n if (hwGamma)\n {\n \/\/ TODO not supported\n return 0;\n }\n else\n {\n return GL_RGBA;\n }\n }\n else\n {\n return format;\n }\n }\n\t\/\/-----------------------------------------------------------------------------\n PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum fmt, GLenum dataType)\n {\n switch (fmt)\n {\n#if GL_IMG_texture_compression_pvrtc\n case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:\n return PF_PVRTC_RGB2;\n case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:\n return PF_PVRTC_RGBA2;\n case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:\n return PF_PVRTC_RGB4;\n case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:\n return PF_PVRTC_RGBA4;\n#endif\n case GL_LUMINANCE:\n return PF_L8;\n case GL_ALPHA:\n return PF_A8;\n case GL_LUMINANCE_ALPHA:\n return PF_BYTE_LA;\n \n case GL_RGB:\n switch(dataType)\n {\n case GL_UNSIGNED_SHORT_5_6_5:\n return PF_B5G6R5;\n default:\n return PF_R8G8B8;\n };\n case GL_RGBA:\n switch(dataType)\n {\n case GL_UNSIGNED_SHORT_5_5_5_1:\n return PF_A1R5G5B5;\n case GL_UNSIGNED_SHORT_4_4_4_4:\n return PF_A4R4G4B4;\n default:\n#if (OGRE_PLATFORM == OGRE_PLATFORM_TEGRA2)\n return PF_X8B8G8R8;\n#elif (OGRE_PLATFORM == OGRE_PLATFORM_ANDROID)\n return PF_A8B8G8R8;\n#else\n return PF_A8R8G8B8;\n#endif\n }\n#ifdef GL_BGRA\n case GL_BGRA:\n return PF_A8B8G8R8;\n#endif\n\n#if GL_EXT_texture_compression_dxt1\n case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:\n case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:\n return PF_DXT1;\n#endif\n#if GL_EXT_texture_compression_s3tc\n case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:\n return PF_DXT3;\n case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:\n return PF_DXT5;\n#endif\n default:\n \/\/TODO: not supported\n return PF_A8R8G8B8;\n };\n }\n\t\/\/-----------------------------------------------------------------------------\n size_t GLES2PixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth,\n PixelFormat format)\n {\n size_t count = 0;\n\n do {\n if (width > 1)\n {\n width = width \/ 2;\n }\n if (height > 1)\n {\n height = height \/ 2;\n }\n if (depth > 1)\n {\n depth = depth \/ 2;\n }\n \/*\n NOT needed, compressed formats will have mipmaps up to 1x1\n if(PixelUtil::isValidExtent(width, height, depth, format))\n count ++;\n else\n break;\n *\/\n count++;\n } while (!(width == 1 && height == 1 && depth == 1));\n\n return count;\n }\n\t\/\/-----------------------------------------------------------------------------\n size_t GLES2PixelUtil::optionalPO2(size_t value)\n {\n const RenderSystemCapabilities *caps =\n Root::getSingleton().getRenderSystem()->getCapabilities();\n\n if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES))\n {\n return value;\n }\n else\n {\n return Bitwise::firstPO2From((uint32)value);\n }\n }\n\n void GLES2PixelUtil::convertToGLformat(const PixelBox &src, const PixelBox &dst)\n {\n \/\/ Always need to convert PF_A4R4G4B4, GL expects the colors to be in the \n \/\/ reverse order\n if (dst.format == PF_A4R4G4B4)\n {\n \/\/ Convert PF_A4R4G4B4 -> PF_B4G4R4A4\n \/\/ Reverse pixel order\n uint16 *srcptr = static_cast(src.data)\n\t\t\t+ (src.left + src.top * src.rowPitch + src.front * src.slicePitch);\n uint16 *dstptr = static_cast(dst.data)\n\t\t\t+ (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch);\n const size_t srcSliceSkip = src.getSliceSkip();\n const size_t dstSliceSkip = dst.getSliceSkip();\n const size_t k = src.right - src.left;\n for(size_t z=src.front; z>4) | \/\/ R\n ((srcptr[x]&0xF000)>>12); \/\/ A\n }\n srcptr += src.rowPitch;\n dstptr += dst.rowPitch;\n }\n srcptr += srcSliceSkip;\n dstptr += dstSliceSkip;\n } \n }\n }\n}\n<|endoftext|>"} {"text":"#define BOOST_AUTO_TEST_MAIN\r\n\r\n#include \r\n#include \r\n#include \"RemoveExtraSpaces\/RemoveExtraSpaces.h\"\r\n\r\nbool VerifyRemoveExtraSpaces(std::string const& inputString, std::string const& expectedString)\r\n{\r\n std::string processedString = RemoveExtraSpaces(inputString);\r\n return (processedString == expectedString);\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE(RemoveExtraSpacesTests)\r\n\r\nBOOST_AUTO_TEST_CASE(AllTestCases)\r\n{\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"\", \"\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"TextWithoutSpaces\", \"TextWithoutSpaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"Normal text with some spaces\", \"Normal text with some spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"Text with trailing spaces \", \"Text with trailing spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\" Text with beginning spaces\", \"Text with beginning spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"Text with two spaces\", \"Text with two spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\" Text with extra blanks \", \"Text with extra blanks\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\nДополнил тесты.#define BOOST_AUTO_TEST_MAIN\r\n\r\n#include \r\n#include \r\n#include \"RemoveExtraSpaces\/RemoveExtraSpaces.h\"\r\n\r\nbool VerifyRemoveExtraSpaces(std::string const& inputString, std::string const& expectedString)\r\n{\r\n std::string processedString = RemoveExtraSpaces(inputString);\r\n return (processedString == expectedString);\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE(RemoveExtraSpacesTests)\r\n\r\nBOOST_AUTO_TEST_CASE(AllTestCases)\r\n{\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"\", \"\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\" \", \"\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"A\", \"A\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"TextWithoutSpaces\", \"TextWithoutSpaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"Normal text with some spaces\", \"Normal text with some spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"Text with trailing spaces \", \"Text with trailing spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\" Text with beginning spaces\", \"Text with beginning spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\"Text with two spaces\", \"Text with two spaces\"));\r\n BOOST_CHECK(VerifyRemoveExtraSpaces(\" Text with extra blanks \", \"Text with extra blanks\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n<|endoftext|>"} {"text":"\/**\n * @file\n * exercise_15_03.cpp\n * @author\n * Henrik Samuelsson, henrik.samuelsson(at)gmail.com\n * @brief\n * Test program for exercise 15.3 from the book C++ Primer (5th edition).\n * @details\n * Creates an object and then uses this object to calculate the price of \n * 100 copies of the book.\n *\/\n#include\n#include\"Quote.h\"\n\nint main() {\n Quote q(\"0321714113\", 39.95);\n std::cout << \"The price for 100 C++ Primer is $\" << q.net_price(100);\n return 0;\n}\n\nEdit of main class.\/**\n * @file\n * exercise_15_03.cpp\n * @author\n * Henrik Samuelsson, henrik.samuelsson(at)gmail.com\n * @brief\n * Test program for exercise 15.3 from the book C++ Primer (5th edition).\n * @details\n * Creates an object and then uses this object to calculate the price of \n * 100 copies of the book.\n *\/\n#include\n#include\"Quote.h\"\n\nint main() {\n Quote q(\"0321714113\", 39.95);\n std::cout << \"The price for 100 C++ Primer is $\" << q.net_price(100);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/Copyright (c) 2020 Ultimaker B.V.\n#ifndef BOOST_INTERFACE_HPP\n#define BOOST_INTERFACE_HPP\n\n#include \n#include \n\n#include \"utils\/IntPoint.h\"\n#include \"utils\/PolygonsSegmentIndex.h\"\n#include \"utils\/polygon.h\"\n\n\nusing CSegment = arachne::PolygonsSegmentIndex;\nusing CPolygon = boost::polygon::polygon_data;\nusing CPolygonSet = std::vector;\n\nnamespace boost {\nnamespace polygon {\n\n\ntemplate <>\nstruct geometry_concept\n{\n typedef point_concept type;\n};\n\ntemplate <>\nstruct point_traits\n{\n typedef int coordinate_type;\n\n static inline coordinate_type get(\n const cura::Point& point, orientation_2d orient)\n {\n return (orient == HORIZONTAL) ? point.X : point.Y;\n }\n};\n\ntemplate <>\nstruct geometry_concept\n{\n typedef segment_concept type;\n};\n\ntemplate <>\nstruct segment_traits\n{\n typedef cura::coord_t coordinate_type;\n typedef cura::Point point_type;\n static inline point_type get(const CSegment& CSegment, direction_1d dir) {\n return dir.to_int() ? CSegment.p() : CSegment.next().p();\n }\n};\n\n\n\n} \/\/ polygon\n} \/\/ boost\n\n#endif \/\/ BOOST_INTERFACE_HPP\nUse coord_t for coordinate types\/\/Copyright (c) 2020 Ultimaker B.V.\n#ifndef BOOST_INTERFACE_HPP\n#define BOOST_INTERFACE_HPP\n\n#include \n#include \n\n#include \"utils\/IntPoint.h\"\n#include \"utils\/PolygonsSegmentIndex.h\"\n#include \"utils\/polygon.h\"\n\n\nusing CSegment = arachne::PolygonsSegmentIndex;\nusing CPolygon = boost::polygon::polygon_data;\nusing CPolygonSet = std::vector;\n\nnamespace boost {\nnamespace polygon {\n\n\ntemplate <>\nstruct geometry_concept\n{\n typedef point_concept type;\n};\n\ntemplate <>\nstruct point_traits\n{\n typedef cura::coord_t coordinate_type;\n\n static inline coordinate_type get(\n const cura::Point& point, orientation_2d orient)\n {\n return (orient == HORIZONTAL) ? point.X : point.Y;\n }\n};\n\ntemplate <>\nstruct geometry_concept\n{\n typedef segment_concept type;\n};\n\ntemplate <>\nstruct segment_traits\n{\n typedef cura::coord_t coordinate_type;\n typedef cura::Point point_type;\n static inline point_type get(const CSegment& CSegment, direction_1d dir) {\n return dir.to_int() ? CSegment.p() : CSegment.next().p();\n }\n};\n\n\n\n} \/\/ polygon\n} \/\/ boost\n\n#endif \/\/ BOOST_INTERFACE_HPP\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: saxparser.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2003-04-15 17:08:56 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \"LocaleNode.hxx\"\n\nusing namespace ::rtl;\nusing namespace ::std;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::com::sun::star::io;\n\n\n\n\n\n\n\/************\n * Sequence of bytes -> InputStream\n ************\/\nclass OInputStream : public WeakImplHelper1 < XInputStream >\n{\npublic:\n OInputStream( const Sequence< sal_Int8 >&seq ) :\n m_seq( seq ),\n nPos( 0 )\n {}\n\npublic:\n virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n {\n nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ?\n m_seq.getLength() - nPos :\n nBytesToRead;\n aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead );\n nPos += nBytesToRead;\n return nBytesToRead;\n }\n virtual sal_Int32 SAL_CALL readSomeBytes(\n ::com::sun::star::uno::Sequence< sal_Int8 >& aData,\n sal_Int32 nMaxBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n {\n return readBytes( aData, nMaxBytesToRead );\n }\n virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )\n throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n {\n \/\/ not implemented\n }\n virtual sal_Int32 SAL_CALL available( )\n throw(NotConnectedException, IOException, RuntimeException)\n {\n return m_seq.getLength() - nPos;\n }\n virtual void SAL_CALL closeInput( )\n throw(NotConnectedException, IOException, RuntimeException)\n {\n \/\/ not needed\n }\n sal_Int32 nPos;\n Sequence< sal_Int8> m_seq;\n};\n\n\/\/-------------------------------\n\/\/ Helper : create an input stream from a file\n\/\/------------------------------\nReference< XInputStream > createStreamFromFile(\n const char *pcFile )\n{\n FILE *f = fopen( pcFile , \"rb\" );\n Reference< XInputStream > r;\n\n if( f ) {\n fseek( f , 0 , SEEK_END );\n int nLength = ftell( f );\n fseek( f , 0 , SEEK_SET );\n\n Sequence seqIn(nLength);\n fread( seqIn.getArray() , nLength , 1 , f );\n\n r = Reference< XInputStream > ( new OInputStream( seqIn ) );\n fclose( f );\n }\n return r;\n}\n\n\nclass TestDocumentHandler :\n public WeakImplHelper3< XExtendedDocumentHandler , XEntityResolver , XErrorHandler >\n{\npublic:\n TestDocumentHandler(const char* locale, const char* outFile ) :\n of(outFile, locale), nbOfCurrencies(0), nbOfCalendars(0), nbOfCollations(0),\n nbOfFormatElements(0), nbOfDays(50), nbOfMonths(50), nbOfEras(10),\n nbOfTransliterations(0), isStartDayOfWeek(false), foundDefaultName(false),\n flag(-1), foundVarient(false), openElement(false), rootNode(0)\n {\n strncpy( theLocale, locale, sizeof(theLocale) );\n theLocale[sizeof(theLocale)-1] = 0;\n }\n\n ~TestDocumentHandler( )\n {\n of.closeOutput();\n }\n\n\npublic: \/\/ Error handler\n virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException)\n {\n printf( \"Error !\\n\" );\n throw SAXException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"error from error handler\")) ,\n Reference < XInterface >() ,\n aSAXParseException );\n }\n virtual void SAL_CALL fatalError(const Any& aSAXParseException) throw (SAXException, RuntimeException)\n {\n printf( \"Fatal Error !\\n\" );\n }\n virtual void SAL_CALL warning(const Any& aSAXParseException) throw (SAXException, RuntimeException)\n {\n printf( \"Warning !\\n\" );\n }\n\n\npublic: \/\/ ExtendedDocumentHandler\n\n\n\n stack currentNode ;\n sal_Bool fElement ;\n LocaleNode * rootNode;\n\n virtual void SAL_CALL startDocument(void) throw (SAXException, RuntimeException)\n {\n printf( \"parsing document %s started\\n\", theLocale);\n of.writeAsciiString(\"#include \\n\\n\\n\");\n#if SUPD > 618\n of.writeAsciiString(\"#include \/\/ debug printfs\\n\\n\");\n#endif \/\/ SUPD > 618\n of.writeAsciiString(\"extern \\\"C\\\" {\\n\\n\");\n }\n\n virtual void SAL_CALL endDocument(void) throw (SAXException, RuntimeException)\n {\n if (rootNode)\n rootNode->generateCode(of);\n printf( \"parsing document %s finished\\n\", theLocale);\n\n of.writeAsciiString(\"} \/\/ extern \\\"C\\\"\\n\\n\");\n of.closeOutput();\n }\n\n virtual void SAL_CALL startElement(const OUString& aName,\n const Reference< XAttributeList > & xAttribs)\n throw (SAXException,RuntimeException)\n {\n\n LocaleNode * l = LocaleNode::createNode (aName, xAttribs);\n if (!currentNode.empty() ) {\n LocaleNode * ln = (LocaleNode *) currentNode . top();\n ln->addChild(l);\n } else {\n rootNode = l;\n }\n currentNode . push (l);\n }\n\n\n virtual void SAL_CALL endElement(const OUString& aName) throw (SAXException,RuntimeException)\n {\n currentNode . pop();\n }\n\n virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException)\n {\n\n LocaleNode * l = currentNode . top();\n l->setValue (aChars);\n ::rtl::OUString str(aChars);\n sal_Unicode nonBreakSPace[2]= {0xa, 0x0};\n if(!openElement || str.equals(nonBreakSPace))\n return;\n }\n\n virtual void SAL_CALL ignorableWhitespace(const OUString& aWhitespaces) throw (SAXException,RuntimeException)\n {\n }\n\n virtual void SAL_CALL processingInstruction(const OUString& aTarget, const OUString& aData) throw (SAXException,RuntimeException)\n {\n \/\/ ignored\n }\n\n virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & xLocator)\n throw (SAXException,RuntimeException)\n {\n \/\/ ignored\n }\n\n virtual InputSource SAL_CALL resolveEntity(\n const OUString& sPublicId,\n const OUString& sSystemId)\n throw (RuntimeException)\n {\n InputSource source;\n source.sSystemId = sSystemId;\n source.sPublicId = sPublicId;\n\n source.aInputStream = createStreamFromFile(\n OUStringToOString( sSystemId , RTL_TEXTENCODING_ASCII_US) );\n\n return source;\n }\n\n virtual void SAL_CALL startCDATA(void) throw (SAXException,RuntimeException)\n {\n }\n virtual void SAL_CALL endCDATA(void) throw (RuntimeException)\n {\n }\n virtual void SAL_CALL comment(const OUString& sComment) throw (SAXException,RuntimeException)\n {\n }\n virtual void SAL_CALL unknown(const OUString& sString) throw (SAXException,RuntimeException)\n {\n }\n\n virtual void SAL_CALL allowLineBreak( void) throw (SAXException, RuntimeException )\n {\n\n }\n\npublic:\n ::rtl::OUString currentElement;\n sal_Int16 nbOfCurrencies;\n sal_Int16 nbOfCalendars;\n sal_Int16 nbOfFormatElements;\n sal_Int16 nbOfTransliterations;\n sal_Int16 nbOfCollations;\n Sequence nbOfDays;\n Sequence nbOfMonths;\n Sequence nbOfEras;\n sal_Char *elementTag;\n sal_Char theLocale[50];\n sal_Int16 flag;\n OFileWriter of;\n sal_Bool isStartDayOfWeek;\n sal_Bool foundDefaultName;\n sal_Bool foundVarient;\n sal_Bool openElement;\n};\n\n\n\n\n\nint SAL_CALL main (int argc, char **argv)\n{\n\n\n if( argc < 6) {\n printf( \"usage : %s \\n\", argv[0] );\n exit( 1 );\n }\n\n \/\/ create service manager\n Reference< XMultiServiceFactory > xSMgr;\n try\n {\n xSMgr = createRegistryServiceFactory(\n ::rtl::OUString::createFromAscii(argv[4]),\n ::rtl::OUString::createFromAscii(argv[5]) );\n }\n catch ( Exception& )\n {\n printf( \"Exception on createRegistryServiceFactory\\n\" );\n exit(1);\n }\n\n Reference < XImplementationRegistration > xReg;\n try\n {\n \/\/ Create registration service\n Reference < XInterface > x = xSMgr->createInstance(\n OUString::createFromAscii( \"com.sun.star.registry.ImplementationRegistration\" ) );\n xReg = Reference< XImplementationRegistration > ( x , UNO_QUERY );\n }\n catch( Exception & ) {\n printf( \"Couldn't create ImplementationRegistration service\\n\" );\n exit(1);\n }\n\n OString sTestName;\n try\n {\n \/\/ Load dll for the tested component\n#ifdef SAL_W32\n OUString aDllName = OUString::createFromAscii( \"sax\" );\n#else\n#ifdef MACOSX\n OUString aDllName = OUString::createFromAscii( \"libsax.dylib.framework\" );\n#else\n OUString aDllName = OUString::createFromAscii( \"libsax.so\" );\n#endif\n#endif\n xReg->registerImplementation(\n OUString::createFromAscii( \"com.sun.star.loader.SharedLibrary\" ),\n aDllName,\n Reference< XSimpleRegistry > () );\n }\n catch( Exception &e ) {\n printf( \"Couldn't reach sax dll\\n\" );\n printf( \"%s\\n\" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );\n\n exit(1);\n }\n\n\n \/\/--------------------------------\n \/\/ parser demo\n \/\/ read xml from a file and count elements\n \/\/--------------------------------\n Reference< XInterface > x = xSMgr->createInstance(\n OUString::createFromAscii( \"com.sun.star.xml.sax.Parser\" ) );\n if( x.is() )\n {\n Reference< XParser > rParser( x , UNO_QUERY );\n\n \/\/ create and connect the document handler to the parser\n TestDocumentHandler *pDocHandler = new TestDocumentHandler( argv[1], argv[3]);\n\n Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler );\n Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler );\n\n rParser->setDocumentHandler( rDocHandler );\n rParser->setEntityResolver( rEntityResolver );\n\n \/\/ create the input stream\n InputSource source;\n source.aInputStream = createStreamFromFile( argv[2] );\n source.sSystemId = OUString::createFromAscii( argv[2] );\n\n try\n {\n \/\/ start parsing\n rParser->parseStream( source );\n }\n\n catch( Exception & e )\n {\n OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 );\n printf( \"Exception during parsing : %s\\n\" , o1.getStr() );\n exit(1);\n }\n }\n else\n {\n printf( \"couln't create sax-parser component\\n\" );\n exit(1);\n }\n\n return 0;\n}\n#100000# MHU: Removed unused dependency on vos module.hxx and dynload.hxx.\/*************************************************************************\n *\n * $RCSfile: saxparser.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2003-04-22 16:33:45 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \"LocaleNode.hxx\"\n\nusing namespace ::rtl;\nusing namespace ::std;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::com::sun::star::io;\n\n\n\n\n\n\n\/************\n * Sequence of bytes -> InputStream\n ************\/\nclass OInputStream : public WeakImplHelper1 < XInputStream >\n{\npublic:\n OInputStream( const Sequence< sal_Int8 >&seq ) :\n m_seq( seq ),\n nPos( 0 )\n {}\n\npublic:\n virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n {\n nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ?\n m_seq.getLength() - nPos :\n nBytesToRead;\n aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead );\n nPos += nBytesToRead;\n return nBytesToRead;\n }\n virtual sal_Int32 SAL_CALL readSomeBytes(\n ::com::sun::star::uno::Sequence< sal_Int8 >& aData,\n sal_Int32 nMaxBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n {\n return readBytes( aData, nMaxBytesToRead );\n }\n virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )\n throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n {\n \/\/ not implemented\n }\n virtual sal_Int32 SAL_CALL available( )\n throw(NotConnectedException, IOException, RuntimeException)\n {\n return m_seq.getLength() - nPos;\n }\n virtual void SAL_CALL closeInput( )\n throw(NotConnectedException, IOException, RuntimeException)\n {\n \/\/ not needed\n }\n sal_Int32 nPos;\n Sequence< sal_Int8> m_seq;\n};\n\n\/\/-------------------------------\n\/\/ Helper : create an input stream from a file\n\/\/------------------------------\nReference< XInputStream > createStreamFromFile(\n const char *pcFile )\n{\n FILE *f = fopen( pcFile , \"rb\" );\n Reference< XInputStream > r;\n\n if( f ) {\n fseek( f , 0 , SEEK_END );\n int nLength = ftell( f );\n fseek( f , 0 , SEEK_SET );\n\n Sequence seqIn(nLength);\n fread( seqIn.getArray() , nLength , 1 , f );\n\n r = Reference< XInputStream > ( new OInputStream( seqIn ) );\n fclose( f );\n }\n return r;\n}\n\n\nclass TestDocumentHandler :\n public WeakImplHelper3< XExtendedDocumentHandler , XEntityResolver , XErrorHandler >\n{\npublic:\n TestDocumentHandler(const char* locale, const char* outFile ) :\n of(outFile, locale), nbOfCurrencies(0), nbOfCalendars(0), nbOfCollations(0),\n nbOfFormatElements(0), nbOfDays(50), nbOfMonths(50), nbOfEras(10),\n nbOfTransliterations(0), isStartDayOfWeek(false), foundDefaultName(false),\n flag(-1), foundVarient(false), openElement(false), rootNode(0)\n {\n strncpy( theLocale, locale, sizeof(theLocale) );\n theLocale[sizeof(theLocale)-1] = 0;\n }\n\n ~TestDocumentHandler( )\n {\n of.closeOutput();\n }\n\n\npublic: \/\/ Error handler\n virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException)\n {\n printf( \"Error !\\n\" );\n throw SAXException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"error from error handler\")) ,\n Reference < XInterface >() ,\n aSAXParseException );\n }\n virtual void SAL_CALL fatalError(const Any& aSAXParseException) throw (SAXException, RuntimeException)\n {\n printf( \"Fatal Error !\\n\" );\n }\n virtual void SAL_CALL warning(const Any& aSAXParseException) throw (SAXException, RuntimeException)\n {\n printf( \"Warning !\\n\" );\n }\n\n\npublic: \/\/ ExtendedDocumentHandler\n\n\n\n stack currentNode ;\n sal_Bool fElement ;\n LocaleNode * rootNode;\n\n virtual void SAL_CALL startDocument(void) throw (SAXException, RuntimeException)\n {\n printf( \"parsing document %s started\\n\", theLocale);\n of.writeAsciiString(\"#include \\n\\n\\n\");\n#if SUPD > 618\n of.writeAsciiString(\"#include \/\/ debug printfs\\n\\n\");\n#endif \/\/ SUPD > 618\n of.writeAsciiString(\"extern \\\"C\\\" {\\n\\n\");\n }\n\n virtual void SAL_CALL endDocument(void) throw (SAXException, RuntimeException)\n {\n if (rootNode)\n rootNode->generateCode(of);\n printf( \"parsing document %s finished\\n\", theLocale);\n\n of.writeAsciiString(\"} \/\/ extern \\\"C\\\"\\n\\n\");\n of.closeOutput();\n }\n\n virtual void SAL_CALL startElement(const OUString& aName,\n const Reference< XAttributeList > & xAttribs)\n throw (SAXException,RuntimeException)\n {\n\n LocaleNode * l = LocaleNode::createNode (aName, xAttribs);\n if (!currentNode.empty() ) {\n LocaleNode * ln = (LocaleNode *) currentNode . top();\n ln->addChild(l);\n } else {\n rootNode = l;\n }\n currentNode . push (l);\n }\n\n\n virtual void SAL_CALL endElement(const OUString& aName) throw (SAXException,RuntimeException)\n {\n currentNode . pop();\n }\n\n virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException)\n {\n\n LocaleNode * l = currentNode . top();\n l->setValue (aChars);\n ::rtl::OUString str(aChars);\n sal_Unicode nonBreakSPace[2]= {0xa, 0x0};\n if(!openElement || str.equals(nonBreakSPace))\n return;\n }\n\n virtual void SAL_CALL ignorableWhitespace(const OUString& aWhitespaces) throw (SAXException,RuntimeException)\n {\n }\n\n virtual void SAL_CALL processingInstruction(const OUString& aTarget, const OUString& aData) throw (SAXException,RuntimeException)\n {\n \/\/ ignored\n }\n\n virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & xLocator)\n throw (SAXException,RuntimeException)\n {\n \/\/ ignored\n }\n\n virtual InputSource SAL_CALL resolveEntity(\n const OUString& sPublicId,\n const OUString& sSystemId)\n throw (RuntimeException)\n {\n InputSource source;\n source.sSystemId = sSystemId;\n source.sPublicId = sPublicId;\n\n source.aInputStream = createStreamFromFile(\n OUStringToOString( sSystemId , RTL_TEXTENCODING_ASCII_US) );\n\n return source;\n }\n\n virtual void SAL_CALL startCDATA(void) throw (SAXException,RuntimeException)\n {\n }\n virtual void SAL_CALL endCDATA(void) throw (RuntimeException)\n {\n }\n virtual void SAL_CALL comment(const OUString& sComment) throw (SAXException,RuntimeException)\n {\n }\n virtual void SAL_CALL unknown(const OUString& sString) throw (SAXException,RuntimeException)\n {\n }\n\n virtual void SAL_CALL allowLineBreak( void) throw (SAXException, RuntimeException )\n {\n\n }\n\npublic:\n ::rtl::OUString currentElement;\n sal_Int16 nbOfCurrencies;\n sal_Int16 nbOfCalendars;\n sal_Int16 nbOfFormatElements;\n sal_Int16 nbOfTransliterations;\n sal_Int16 nbOfCollations;\n Sequence nbOfDays;\n Sequence nbOfMonths;\n Sequence nbOfEras;\n sal_Char *elementTag;\n sal_Char theLocale[50];\n sal_Int16 flag;\n OFileWriter of;\n sal_Bool isStartDayOfWeek;\n sal_Bool foundDefaultName;\n sal_Bool foundVarient;\n sal_Bool openElement;\n};\n\n\n\n\n\nint SAL_CALL main (int argc, char **argv)\n{\n\n\n if( argc < 6) {\n printf( \"usage : %s \\n\", argv[0] );\n exit( 1 );\n }\n\n \/\/ create service manager\n Reference< XMultiServiceFactory > xSMgr;\n try\n {\n xSMgr = createRegistryServiceFactory(\n ::rtl::OUString::createFromAscii(argv[4]),\n ::rtl::OUString::createFromAscii(argv[5]) );\n }\n catch ( Exception& )\n {\n printf( \"Exception on createRegistryServiceFactory\\n\" );\n exit(1);\n }\n\n Reference < XImplementationRegistration > xReg;\n try\n {\n \/\/ Create registration service\n Reference < XInterface > x = xSMgr->createInstance(\n OUString::createFromAscii( \"com.sun.star.registry.ImplementationRegistration\" ) );\n xReg = Reference< XImplementationRegistration > ( x , UNO_QUERY );\n }\n catch( Exception & ) {\n printf( \"Couldn't create ImplementationRegistration service\\n\" );\n exit(1);\n }\n\n OString sTestName;\n try\n {\n \/\/ Load dll for the tested component\n#ifdef SAL_W32\n OUString aDllName = OUString::createFromAscii( \"sax\" );\n#else\n#ifdef MACOSX\n OUString aDllName = OUString::createFromAscii( \"libsax.dylib.framework\" );\n#else\n OUString aDllName = OUString::createFromAscii( \"libsax.so\" );\n#endif\n#endif\n xReg->registerImplementation(\n OUString::createFromAscii( \"com.sun.star.loader.SharedLibrary\" ),\n aDllName,\n Reference< XSimpleRegistry > () );\n }\n catch( Exception &e ) {\n printf( \"Couldn't reach sax dll\\n\" );\n printf( \"%s\\n\" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );\n\n exit(1);\n }\n\n\n \/\/--------------------------------\n \/\/ parser demo\n \/\/ read xml from a file and count elements\n \/\/--------------------------------\n Reference< XInterface > x = xSMgr->createInstance(\n OUString::createFromAscii( \"com.sun.star.xml.sax.Parser\" ) );\n if( x.is() )\n {\n Reference< XParser > rParser( x , UNO_QUERY );\n\n \/\/ create and connect the document handler to the parser\n TestDocumentHandler *pDocHandler = new TestDocumentHandler( argv[1], argv[3]);\n\n Reference < XDocumentHandler > rDocHandler( (XDocumentHandler *) pDocHandler );\n Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler );\n\n rParser->setDocumentHandler( rDocHandler );\n rParser->setEntityResolver( rEntityResolver );\n\n \/\/ create the input stream\n InputSource source;\n source.aInputStream = createStreamFromFile( argv[2] );\n source.sSystemId = OUString::createFromAscii( argv[2] );\n\n try\n {\n \/\/ start parsing\n rParser->parseStream( source );\n }\n\n catch( Exception & e )\n {\n OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 );\n printf( \"Exception during parsing : %s\\n\" , o1.getStr() );\n exit(1);\n }\n }\n else\n {\n printf( \"couln't create sax-parser component\\n\" );\n exit(1);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mvdMainWindow.h\"\n#include \"ui_mvdMainWindow.h\"\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n#include \n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdAboutDialog.h\"\n#include \"mvdApplication.h\"\n#include \"mvdColorDynamicsController.h\"\n#include \"mvdColorDynamicsWidget.h\"\n#include \"mvdColorSetupController.h\"\n#include \"mvdDatasetModel.h\"\n#include \"mvdGLImageWidget.h\"\n#include \"mvdImageModelRenderer.h\"\n#include \"mvdImageViewManipulator.h\"\n#include \"mvdQuicklookModel.h\"\n#include \"mvdQuicklookViewManipulator.h\"\n#include \"mvdVectorImageModel.h\"\n\nnamespace mvd\n{\n\/*\n TRANSLATOR mvd::MainWindow\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\/*****************************************************************************\/\nMainWindow\n::MainWindow( QWidget* parent, Qt::WindowFlags flags ) :\n QMainWindow( parent, flags ), \n m_UI( new mvd::Ui::MainWindow() )\n{\n m_UI->setupUi( this );\n\n Initialize();\n}\n\n\/*****************************************************************************\/\nMainWindow\n::~MainWindow()\n{\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::Initialize()\n{\n setObjectName( \"mvd::MainWindow\" );\n setWindowTitle( PROJECT_NAME );\n\n \/\/ instanciate the manipulator and the renderer relative to this widget\n m_ImageViewManipulator = new ImageViewManipulator();\n m_ImageModelRenderer = new ImageModelRenderer();\n\n \/\/ set the GLImageWidget as the centralWidget in MainWindow.\n setCentralWidget(\n new GLImageWidget(\n m_ImageViewManipulator,\n m_ImageModelRenderer,\n this\n )\n );\n \n \/\/ instanciate the Ql manipulator\/renderer \n m_QLModelRenderer = new ImageModelRenderer();\n m_QLViewManipulator = new QuicklookViewManipulator();\n\n \/\/ Connect centralWidget manipulator to Ql renderer when viewportRegionChanged\n QObject::connect(\n m_ImageViewManipulator, SIGNAL( ViewportRegionRepresentationChanged(const PointType&, const PointType&) ), \n m_QLModelRenderer, SLOT( OnViewportRegionRepresentationChanged(const PointType&, const PointType&) )\n );\n\n \/\/ Connect ql mousePressEventpressed to centralWidget manipulator\n QObject::connect(\n m_QLViewManipulator, SIGNAL( ViewportRegionChanged(double, double) ), \n m_ImageViewManipulator, SLOT( OnViewportRegionChanged(double, double) )\n );\n\n \/\/ add the needed docks \n InitializeDockWidgets();\n\n \/\/ add needed widget to the status bar\n InitializeStatusBarWidgets();\n\n \/\/ Connect Quit action of main menu to QApplication's quit() slot.\n QObject::connect(\n m_UI->action_Quit, SIGNAL( activated() ),\n qApp, SLOT( quit() )\n );\n\n \/\/ Connect Appllication and MainWindow when selected model is about\n \/\/ to change.\n QObject::connect(\n qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ),\n this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) )\n );\n\n \/\/ Connect Appllication and MainWindow when selected model has been\n \/\/ changed.\n QObject::connect(\n qApp, SIGNAL( SelectedModelChanged( AbstractModel* ) ),\n this, SLOT( OnSelectedModelChanged( AbstractModel* ) )\n );\n\n \/\/ Change to NULL model to force emitting GUI signals when GUI is\n \/\/ instanciated. So, GUI will be initialized and controller-widgets\n \/\/ disabled.\n Application::Instance()->SetModel( NULL );\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::InitializeStatusBarWidgets()\n{\n \/\/ Add a QLabel to the status bar to show pixel coordinates\n QLabel * currentPixelLabel = new QLabel(statusBar());\n currentPixelLabel->setAlignment(Qt::AlignCenter);\n \n \/\/ connect this widget to receive notification from \n \/\/ ImageViewManipulator\n QObject::connect(\n m_ImageViewManipulator, \n SIGNAL( CurrentCoordinatesUpdated(const QString& ) ),\n currentPixelLabel,\n SLOT( setText(const QString &) )\n );\n \n statusBar()->addWidget(currentPixelLabel);\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::InitializeDockWidgets()\n{\n \/\/\n \/\/ EXPERIMENTAL QUICKLOOK Widget.\n assert( qobject_cast< GLImageWidget* >( centralWidget() )!=NULL );\n\n GLImageWidget* qlWidget = new GLImageWidget(\n m_QLViewManipulator,\n m_QLModelRenderer,\n this,\n qobject_cast< GLImageWidget* >( centralWidget() )\n );\n \/\/ TODO: Set better minimum size for quicklook GL widget.\n qlWidget->setMinimumSize(100,100);\n\n AddWidgetToDock( \n qlWidget,\n QUICKLOOK_DOCK,\n tr( \"Quicklook\" ),\n Qt::LeftDockWidgetArea\n );\n\n \/\/\n \/\/ COLOR SETUP.\n ColorSetupWidget* colorSetupWgt = new ColorSetupWidget( this );\n\n ColorSetupController* colorSetupCtrl = new ColorSetupController(\n \/\/ wraps:\n colorSetupWgt,\n \/\/ as child of:\n AddWidgetToDock(\n colorSetupWgt,\n VIDEO_COLOR_SETUP_DOCK,\n tr( \"Video color setup\" ),\n Qt::LeftDockWidgetArea\n )\n );\n\n \/\/\n \/\/ COLOR DYNAMICS.\n ColorDynamicsWidget* colorDynWgt = new ColorDynamicsWidget( this );\n\n \/\/ Controller is childed to dock.\n ColorDynamicsController* colorDynamicsCtrl = new ColorDynamicsController(\n \/\/ wraps:\n colorDynWgt,\n \/\/ as child of:\n AddWidgetToDock(\n colorDynWgt,\n VIDEO_COLOR_DYNAMICS_DOCK,\n tr( \"Video color dynamics\" ),\n Qt::LeftDockWidgetArea\n )\n );\n\n \/\/\n \/\/ CHAIN CONTROLLERS.\n \/\/ Forward model update signals of color-setup controller...\n QObject::connect(\n colorSetupCtrl,\n SIGNAL( RgbChannelIndexChanged( RgbaChannel, int ) ),\n \/\/ to: ...color-dynamics controller model update signal.\n colorDynamicsCtrl,\n SLOT( OnRgbChannelIndexChanged( RgbaChannel, int ) )\n );\n\n \/\/\n \/\/ EXPERIMENTAL TOOLBOX.\n\n#if 0\n\n QToolBox* toolBox = new QToolBox( this );\n\n toolBox->setObjectName( \"mvd::VideoColorToolBox\" );\n\n toolBox->addItem( new ColorSetupWidget( toolBox ), tr( \"Video color setup\" ) );\n toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( \"Video color dynamics\" ) );\n\n AddWidgetToDock( \n toolBox,\n \"videoColorSettingsDock\",\n tr( \"Video color dynamics\" ),\n Qt::LeftDockWidgetArea\n );\n#endif\n}\n\n\/*****************************************************************************\/\nQDockWidget*\nMainWindow\n::AddWidgetToDock( QWidget* widget,\n\t\t const QString& dockName,\n\t\t const QString& dockTitle,\n\t\t Qt::DockWidgetArea dockArea )\n{\n \/\/ New dock.\n QDockWidget* dockWidget = new QDockWidget( dockTitle, this );\n\n \/\/ You can use findChild( dockName ) to get dock-widget.\n dockWidget->setObjectName( dockName );\n dockWidget->setWidget( widget );\n\n \/\/ Features.\n dockWidget->setFloating( false );\n dockWidget->setFeatures(\n QDockWidget::DockWidgetMovable |\n QDockWidget::DockWidgetFloatable\n );\n\n \/\/ Add dock.\n addDockWidget( dockArea, dockWidget );\n\n return dockWidget;\n}\n\n\/*****************************************************************************\/\n\/* SLOTS *\/\n\/*****************************************************************************\/\nvoid\nMainWindow\n::on_action_Open_activated()\n{\n QString filename(\n QFileDialog::getOpenFileName( this, tr( \"Open file...\" ) )\n );\n\n if( filename.isNull() )\n {\n return;\n }\n \n try\n {\n \/\/ TODO: Replace with complex model (list of DatasetModel) when implemented.\n DatasetModel* model = Application::LoadDatasetModel(\n filename,\n \/\/ TODO: Remove width and height from dataset model loading.\n centralWidget()->width(), centralWidget()->height()\n );\n\n Application::Instance()->SetModel( model );\n }\n catch( std::exception& exc )\n {\n QMessageBox::warning( this, tr(\"Exception!\"), exc.what() );\n return;\n }\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::on_action_About_activated()\n{\n AboutDialog aboutDialog( this );\n\n aboutDialog.exec();\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::OnAboutToChangeSelectedModel( const AbstractModel* )\n{\n \/\/\n \/\/ COLOR SETUP.\n SetControllerModel( GetColorSetupDock(), NULL );\n\n \/\/\n \/\/ COLOR DYNAMICS.\n SetControllerModel( GetColorDynamicsDock(), NULL );\n\n \/\/ De-assign models to view after controllers (LIFO disconnect).\n qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel( NULL );\n qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(\n NULL\n );\n\n \/\/\n \/\/\n const Application* app = Application::ConstInstance();\n assert( app!=NULL );\n\n const DatasetModel* datasetModel = \n qobject_cast< const DatasetModel* >( app->GetModel() );\n\n \/\/ It is Ok there is no previously selected model (e.g. at\n \/\/ application startup.\n if( datasetModel==NULL )\n {\n return;\n }\n\n assert( datasetModel->HasSelectedImageModel() );\n\n const VectorImageModel* vectorImageModel =\n qobject_cast< const VectorImageModel* >(\n datasetModel->GetSelectedImageModel()\n );\n\n assert( vectorImageModel!=NULL );\n\n \/\/\n \/\/ MAIN VIEW.\n\n \/\/ Disconnect previously selected model from view.\n QObject::disconnect(\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n centralWidget(),\n SLOT( updateGL() )\n );\n\n \/\/ TODO : where to do this\n QObject::disconnect(\n \/\/ vectorImageModel->GetQuicklookModel(),\n \/\/ TODO: Remove temporary hack by better design.\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n\n \/\/\n \/\/ disconnect the vectorimage model spacing change (when zooming)\n QObject::disconnect(\n vectorImageModel,\n SIGNAL( SpacingChanged(const SpacingType&) ),\n \/\/ to:\n centralWidget(),\n SLOT( OnSpacingChanged(const SpacingType&) )\n );\n\n \/\/ disconnect signal used to update the ql widget\n QObject::disconnect(\n centralWidget(),\n SIGNAL( CentralWidgetUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::OnSelectedModelChanged( AbstractModel* model )\n{\n if( model==NULL )\n return;\n\n DatasetModel* datasetModel = qobject_cast< DatasetModel* >( model );\n\n assert( datasetModel!=NULL );\n assert( datasetModel->HasSelectedImageModel() );\n\n VectorImageModel* vectorImageModel =\n qobject_cast< VectorImageModel* >(\n datasetModel->GetSelectedImageModel()\n );\n\n assert( vectorImageModel!=NULL );\n\n itk::OStringStream oss;\n oss<GetFilename());\n \/\/<<\" (\"<ToImageBase()->GetNumberOfComponentsPerPixel()<ToImageBase()->GetLargestPossibleRegion().GetSize()[0]<<\"x\"<ToImageBase()->GetLargestPossibleRegion().GetSize()[1]<( centralWidget() )->SetImageModel(\n vectorImageModel\n );\n\n \/\/ Connect newly selected model to view (after all other widgets are\n \/\/ connected to prevent signals\/slots to produce multiple view\n \/\/ refreshes).\n QObject::connect(\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n centralWidget(),\n SLOT( updateGL() )\n );\n\n \/\/\n \/\/ QUICKLOOK VIEW.\n\n \/\/ Assign newly selected model to view.\n qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(\n vectorImageModel->GetQuicklookModel()\n );\n\n \/\/ Connect newly selected model to view (after all other widgets are\n \/\/ connected to prevent signals\/slots to produce multiple view\n \/\/ refreshes).\n \/\/ TODO : find where to do this\n QObject::connect(\n \/\/ vectorImageModel->GetQuicklookModel(),\n \/\/ TODO: Remove temporary hack by better design.\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n\n \/\/\n \/\/ connect the vectorimage model spacing change (when zooming)\n QObject::connect(\n vectorImageModel,\n SIGNAL( SpacingChanged(const SpacingType&) ),\n \/\/ to:\n centralWidget(),\n SLOT( OnSpacingChanged(const SpacingType&) )\n );\n\n \/\/ signal used to update the ql widget\n QObject::connect(\n centralWidget(),\n SIGNAL( CentralWidgetUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n}\n\n\/*****************************************************************************\/\n\n} \/\/ end namespace 'mvd'\nENH: More informative window title (done)\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mvdMainWindow.h\"\n#include \"ui_mvdMainWindow.h\"\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n#include \n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdAboutDialog.h\"\n#include \"mvdApplication.h\"\n#include \"mvdColorDynamicsController.h\"\n#include \"mvdColorDynamicsWidget.h\"\n#include \"mvdColorSetupController.h\"\n#include \"mvdDatasetModel.h\"\n#include \"mvdGLImageWidget.h\"\n#include \"mvdImageModelRenderer.h\"\n#include \"mvdImageViewManipulator.h\"\n#include \"mvdQuicklookModel.h\"\n#include \"mvdQuicklookViewManipulator.h\"\n#include \"mvdVectorImageModel.h\"\n\nnamespace mvd\n{\n\/*\n TRANSLATOR mvd::MainWindow\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\/*****************************************************************************\/\nMainWindow\n::MainWindow( QWidget* parent, Qt::WindowFlags flags ) :\n QMainWindow( parent, flags ), \n m_UI( new mvd::Ui::MainWindow() )\n{\n m_UI->setupUi( this );\n\n Initialize();\n}\n\n\/*****************************************************************************\/\nMainWindow\n::~MainWindow()\n{\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::Initialize()\n{\n setObjectName( \"mvd::MainWindow\" );\n setWindowTitle( PROJECT_NAME );\n\n \/\/ instanciate the manipulator and the renderer relative to this widget\n m_ImageViewManipulator = new ImageViewManipulator();\n m_ImageModelRenderer = new ImageModelRenderer();\n\n \/\/ set the GLImageWidget as the centralWidget in MainWindow.\n setCentralWidget(\n new GLImageWidget(\n m_ImageViewManipulator,\n m_ImageModelRenderer,\n this\n )\n );\n \n \/\/ instanciate the Ql manipulator\/renderer \n m_QLModelRenderer = new ImageModelRenderer();\n m_QLViewManipulator = new QuicklookViewManipulator();\n\n \/\/ Connect centralWidget manipulator to Ql renderer when viewportRegionChanged\n QObject::connect(\n m_ImageViewManipulator, SIGNAL( ViewportRegionRepresentationChanged(const PointType&, const PointType&) ), \n m_QLModelRenderer, SLOT( OnViewportRegionRepresentationChanged(const PointType&, const PointType&) )\n );\n\n \/\/ Connect ql mousePressEventpressed to centralWidget manipulator\n QObject::connect(\n m_QLViewManipulator, SIGNAL( ViewportRegionChanged(double, double) ), \n m_ImageViewManipulator, SLOT( OnViewportRegionChanged(double, double) )\n );\n\n \/\/ add the needed docks \n InitializeDockWidgets();\n\n \/\/ add needed widget to the status bar\n InitializeStatusBarWidgets();\n\n \/\/ Connect Quit action of main menu to QApplication's quit() slot.\n QObject::connect(\n m_UI->action_Quit, SIGNAL( activated() ),\n qApp, SLOT( quit() )\n );\n\n \/\/ Connect Appllication and MainWindow when selected model is about\n \/\/ to change.\n QObject::connect(\n qApp, SIGNAL( AboutToChangeSelectedModel( const AbstractModel* ) ),\n this, SLOT( OnAboutToChangeSelectedModel( const AbstractModel* ) )\n );\n\n \/\/ Connect Appllication and MainWindow when selected model has been\n \/\/ changed.\n QObject::connect(\n qApp, SIGNAL( SelectedModelChanged( AbstractModel* ) ),\n this, SLOT( OnSelectedModelChanged( AbstractModel* ) )\n );\n\n \/\/ Change to NULL model to force emitting GUI signals when GUI is\n \/\/ instanciated. So, GUI will be initialized and controller-widgets\n \/\/ disabled.\n Application::Instance()->SetModel( NULL );\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::InitializeStatusBarWidgets()\n{\n \/\/ Add a QLabel to the status bar to show pixel coordinates\n QLabel * currentPixelLabel = new QLabel(statusBar());\n currentPixelLabel->setAlignment(Qt::AlignCenter);\n \n \/\/ connect this widget to receive notification from \n \/\/ ImageViewManipulator\n QObject::connect(\n m_ImageViewManipulator, \n SIGNAL( CurrentCoordinatesUpdated(const QString& ) ),\n currentPixelLabel,\n SLOT( setText(const QString &) )\n );\n \n statusBar()->addWidget(currentPixelLabel);\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::InitializeDockWidgets()\n{\n \/\/\n \/\/ EXPERIMENTAL QUICKLOOK Widget.\n assert( qobject_cast< GLImageWidget* >( centralWidget() )!=NULL );\n\n GLImageWidget* qlWidget = new GLImageWidget(\n m_QLViewManipulator,\n m_QLModelRenderer,\n this,\n qobject_cast< GLImageWidget* >( centralWidget() )\n );\n \/\/ TODO: Set better minimum size for quicklook GL widget.\n qlWidget->setMinimumSize(100,100);\n\n AddWidgetToDock( \n qlWidget,\n QUICKLOOK_DOCK,\n tr( \"Quicklook\" ),\n Qt::LeftDockWidgetArea\n );\n\n \/\/\n \/\/ COLOR SETUP.\n ColorSetupWidget* colorSetupWgt = new ColorSetupWidget( this );\n\n ColorSetupController* colorSetupCtrl = new ColorSetupController(\n \/\/ wraps:\n colorSetupWgt,\n \/\/ as child of:\n AddWidgetToDock(\n colorSetupWgt,\n VIDEO_COLOR_SETUP_DOCK,\n tr( \"Video color setup\" ),\n Qt::LeftDockWidgetArea\n )\n );\n\n \/\/\n \/\/ COLOR DYNAMICS.\n ColorDynamicsWidget* colorDynWgt = new ColorDynamicsWidget( this );\n\n \/\/ Controller is childed to dock.\n ColorDynamicsController* colorDynamicsCtrl = new ColorDynamicsController(\n \/\/ wraps:\n colorDynWgt,\n \/\/ as child of:\n AddWidgetToDock(\n colorDynWgt,\n VIDEO_COLOR_DYNAMICS_DOCK,\n tr( \"Video color dynamics\" ),\n Qt::LeftDockWidgetArea\n )\n );\n\n \/\/\n \/\/ CHAIN CONTROLLERS.\n \/\/ Forward model update signals of color-setup controller...\n QObject::connect(\n colorSetupCtrl,\n SIGNAL( RgbChannelIndexChanged( RgbaChannel, int ) ),\n \/\/ to: ...color-dynamics controller model update signal.\n colorDynamicsCtrl,\n SLOT( OnRgbChannelIndexChanged( RgbaChannel, int ) )\n );\n\n \/\/\n \/\/ EXPERIMENTAL TOOLBOX.\n\n#if 0\n\n QToolBox* toolBox = new QToolBox( this );\n\n toolBox->setObjectName( \"mvd::VideoColorToolBox\" );\n\n toolBox->addItem( new ColorSetupWidget( toolBox ), tr( \"Video color setup\" ) );\n toolBox->addItem( new ColorDynamicsWidget( toolBox ), tr( \"Video color dynamics\" ) );\n\n AddWidgetToDock( \n toolBox,\n \"videoColorSettingsDock\",\n tr( \"Video color dynamics\" ),\n Qt::LeftDockWidgetArea\n );\n#endif\n}\n\n\/*****************************************************************************\/\nQDockWidget*\nMainWindow\n::AddWidgetToDock( QWidget* widget,\n\t\t const QString& dockName,\n\t\t const QString& dockTitle,\n\t\t Qt::DockWidgetArea dockArea )\n{\n \/\/ New dock.\n QDockWidget* dockWidget = new QDockWidget( dockTitle, this );\n\n \/\/ You can use findChild( dockName ) to get dock-widget.\n dockWidget->setObjectName( dockName );\n dockWidget->setWidget( widget );\n\n \/\/ Features.\n dockWidget->setFloating( false );\n dockWidget->setFeatures(\n QDockWidget::DockWidgetMovable |\n QDockWidget::DockWidgetFloatable\n );\n\n \/\/ Add dock.\n addDockWidget( dockArea, dockWidget );\n\n return dockWidget;\n}\n\n\/*****************************************************************************\/\n\/* SLOTS *\/\n\/*****************************************************************************\/\nvoid\nMainWindow\n::on_action_Open_activated()\n{\n QString filename(\n QFileDialog::getOpenFileName( this, tr( \"Open file...\" ) )\n );\n\n if( filename.isNull() )\n {\n return;\n }\n \n try\n {\n \/\/ TODO: Replace with complex model (list of DatasetModel) when implemented.\n DatasetModel* model = Application::LoadDatasetModel(\n filename,\n \/\/ TODO: Remove width and height from dataset model loading.\n centralWidget()->width(), centralWidget()->height()\n );\n\n Application::Instance()->SetModel( model );\n }\n catch( std::exception& exc )\n {\n QMessageBox::warning( this, tr(\"Exception!\"), exc.what() );\n return;\n }\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::on_action_About_activated()\n{\n AboutDialog aboutDialog( this );\n\n aboutDialog.exec();\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::OnAboutToChangeSelectedModel( const AbstractModel* )\n{\n \/\/\n \/\/ COLOR SETUP.\n SetControllerModel( GetColorSetupDock(), NULL );\n\n \/\/\n \/\/ COLOR DYNAMICS.\n SetControllerModel( GetColorDynamicsDock(), NULL );\n\n \/\/ De-assign models to view after controllers (LIFO disconnect).\n qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel( NULL );\n qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(\n NULL\n );\n\n \/\/\n \/\/\n const Application* app = Application::ConstInstance();\n assert( app!=NULL );\n\n const DatasetModel* datasetModel = \n qobject_cast< const DatasetModel* >( app->GetModel() );\n\n \/\/ It is Ok there is no previously selected model (e.g. at\n \/\/ application startup.\n if( datasetModel==NULL )\n {\n return;\n }\n\n assert( datasetModel->HasSelectedImageModel() );\n\n const VectorImageModel* vectorImageModel =\n qobject_cast< const VectorImageModel* >(\n datasetModel->GetSelectedImageModel()\n );\n\n assert( vectorImageModel!=NULL );\n\n \/\/\n \/\/ MAIN VIEW.\n\n \/\/ Disconnect previously selected model from view.\n QObject::disconnect(\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n centralWidget(),\n SLOT( updateGL() )\n );\n\n \/\/ TODO : where to do this\n QObject::disconnect(\n \/\/ vectorImageModel->GetQuicklookModel(),\n \/\/ TODO: Remove temporary hack by better design.\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n\n \/\/\n \/\/ disconnect the vectorimage model spacing change (when zooming)\n QObject::disconnect(\n vectorImageModel,\n SIGNAL( SpacingChanged(const SpacingType&) ),\n \/\/ to:\n centralWidget(),\n SLOT( OnSpacingChanged(const SpacingType&) )\n );\n\n \/\/ disconnect signal used to update the ql widget\n QObject::disconnect(\n centralWidget(),\n SIGNAL( CentralWidgetUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n\n}\n\n\/*****************************************************************************\/\nvoid\nMainWindow\n::OnSelectedModelChanged( AbstractModel* model )\n{\n if( model==NULL )\n return;\n\n DatasetModel* datasetModel = qobject_cast< DatasetModel* >( model );\n\n assert( datasetModel!=NULL );\n assert( datasetModel->HasSelectedImageModel() );\n\n VectorImageModel* vectorImageModel =\n qobject_cast< VectorImageModel* >(\n datasetModel->GetSelectedImageModel()\n );\n\n assert( vectorImageModel!=NULL );\n\n itk::OStringStream oss;\n oss<GetFilename())<<\" (\"<ToImage()->GetNumberOfComponentsPerPixel()<<\" bands, \"<ToImage()->GetLargestPossibleRegion().GetSize()[0]<<\"x\"<ToImage()->GetLargestPossibleRegion().GetSize()[1]<<\" pixels)\";\n \n setWindowTitle( FromStdString(oss.str()) );\n\n \/\/\n \/\/ COLOR SETUP.\n SetControllerModel( GetColorSetupDock(), vectorImageModel );\n\n \/\/\n \/\/ COLOR DYNAMICS.\n SetControllerModel( GetColorDynamicsDock(), vectorImageModel );\n\n \/\/\n \/\/ MAIN VIEW.\n\n \/\/ Assign newly selected model to view.\n qobject_cast< GLImageWidget *>( centralWidget() )->SetImageModel(\n vectorImageModel\n );\n\n \/\/ Connect newly selected model to view (after all other widgets are\n \/\/ connected to prevent signals\/slots to produce multiple view\n \/\/ refreshes).\n QObject::connect(\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n centralWidget(),\n SLOT( updateGL() )\n );\n\n \/\/\n \/\/ QUICKLOOK VIEW.\n\n \/\/ Assign newly selected model to view.\n qobject_cast< GLImageWidget * >( GetQuicklookDock()->widget() )->SetImageModel(\n vectorImageModel->GetQuicklookModel()\n );\n\n \/\/ Connect newly selected model to view (after all other widgets are\n \/\/ connected to prevent signals\/slots to produce multiple view\n \/\/ refreshes).\n \/\/ TODO : find where to do this\n QObject::connect(\n \/\/ vectorImageModel->GetQuicklookModel(),\n \/\/ TODO: Remove temporary hack by better design.\n vectorImageModel,\n SIGNAL( SettingsUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n\n \/\/\n \/\/ connect the vectorimage model spacing change (when zooming)\n QObject::connect(\n vectorImageModel,\n SIGNAL( SpacingChanged(const SpacingType&) ),\n \/\/ to:\n centralWidget(),\n SLOT( OnSpacingChanged(const SpacingType&) )\n );\n\n \/\/ signal used to update the ql widget\n QObject::connect(\n centralWidget(),\n SIGNAL( CentralWidgetUpdated() ),\n \/\/ to:\n GetQuicklookDock()->widget(),\n SLOT( updateGL() )\n );\n}\n\n\/*****************************************************************************\/\n\n} \/\/ end namespace 'mvd'\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"fault_handler.h\"\n#include \n#include \n#include \"base\/macros.h\"\n#include \"globals.h\"\n#include \"base\/logging.h\"\n#include \"base\/hex_dump.h\"\n#include \"thread.h\"\n#include \"mirror\/art_method-inl.h\"\n#include \"mirror\/class-inl.h\"\n#include \"mirror\/dex_cache.h\"\n#include \"mirror\/object_array-inl.h\"\n#include \"mirror\/object-inl.h\"\n#include \"object_utils.h\"\n#include \"scoped_thread_state_change.h\"\n#include \"verify_object-inl.h\"\n\nnamespace art {\n\/\/ Static fault manger object accessed by signal handler.\nFaultManager fault_manager;\n\n\/\/ Signal handler called on SIGSEGV.\nstatic void art_fault_handler(int sig, siginfo_t* info, void* context) {\n fault_manager.HandleFault(sig, info, context);\n}\n\nFaultManager::FaultManager() {\n sigaction(SIGSEGV, nullptr, &oldaction_);\n}\n\nFaultManager::~FaultManager() {\n sigaction(SIGSEGV, &oldaction_, nullptr); \/\/ Restore old handler.\n}\n\nvoid FaultManager::Init() {\n struct sigaction action;\n action.sa_sigaction = art_fault_handler;\n sigemptyset(&action.sa_mask);\n action.sa_flags = SA_SIGINFO | SA_ONSTACK;\n action.sa_restorer = nullptr;\n sigaction(SIGSEGV, &action, &oldaction_);\n}\n\nvoid FaultManager::HandleFault(int sig, siginfo_t* info, void* context) {\n bool handled = false;\n if (IsInGeneratedCode(context)) {\n for (auto& handler : handlers_) {\n handled = handler->Action(sig, info, context);\n if (handled) {\n return;\n }\n }\n }\n\n if (!handled) {\n LOG(INFO)<< \"Caught unknown SIGSEGV in ART fault handler\";\n oldaction_.sa_sigaction(sig, info, context);\n }\n}\n\nvoid FaultManager::AddHandler(FaultHandler* handler) {\n handlers_.push_back(handler);\n}\n\nvoid FaultManager::RemoveHandler(FaultHandler* handler) {\n for (Handlers::iterator i = handlers_.begin(); i != handlers_.end(); ++i) {\n FaultHandler* h = *i;\n if (h == handler) {\n handlers_.erase(i);\n return;\n }\n }\n}\n\n\n\/\/ This function is called within the signal handler. It checks that\n\/\/ the mutator_lock is held (shared). No annotalysis is done.\nbool FaultManager::IsInGeneratedCode(void *context) {\n \/\/ We can only be running Java code in the current thread if it\n \/\/ is in Runnable state.\n Thread* thread = Thread::Current();\n if (thread == nullptr) {\n return false;\n }\n\n ThreadState state = thread->GetState();\n if (state != kRunnable) {\n return false;\n }\n\n \/\/ Current thread is runnable.\n \/\/ Make sure it has the mutator lock.\n if (!Locks::mutator_lock_->IsSharedHeld(thread)) {\n return false;\n }\n\n uintptr_t potential_method = 0;\n uintptr_t return_pc = 0;\n\n \/\/ Get the architecture specific method address and return address. These\n \/\/ are in architecture specific files in arch\/\/fault_handler_.cc\n GetMethodAndReturnPC(context, \/*out*\/potential_method, \/*out*\/return_pc);\n\n \/\/ If we don't have a potential method, we're outta here.\n if (potential_method == 0) {\n return false;\n }\n\n \/\/ Verify that the potential method is indeed a method.\n \/\/ TODO: check the GC maps to make sure it's an object.\n\n mirror::Object* method_obj =\n reinterpret_cast(potential_method);\n\n \/\/ Check that the class pointer inside the object is not null and is aligned.\n mirror::Class* cls = method_obj->GetClass();\n if (cls == nullptr) {\n return false;\n }\n if (!IsAligned(cls)) {\n return false;\n }\n\n\n if (!VerifyClassClass(cls)) {\n return false;\n }\n\n \/\/ Now make sure the class is a mirror::ArtMethod.\n if (!cls->IsArtMethodClass()) {\n return false;\n }\n\n \/\/ We can be certain that this is a method now. Check if we have a GC map\n \/\/ at the return PC address.\n mirror::ArtMethod* method =\n reinterpret_cast(potential_method);\n return method->ToDexPc(return_pc, false) != DexFile::kDexNoIndex;\n}\n\n\/\/\n\/\/ Null pointer fault handler\n\/\/\n\nNullPointerHandler::NullPointerHandler(FaultManager* manager) {\n manager->AddHandler(this);\n}\n\n\/\/\n\/\/ Suspension fault handler\n\/\/\n\nSuspensionHandler::SuspensionHandler(FaultManager* manager) {\n manager->AddHandler(this);\n}\n\n\/\/\n\/\/ Stack overflow fault handler\n\/\/\n\nStackOverflowHandler::StackOverflowHandler(FaultManager* manager) {\n manager->AddHandler(this);\n}\n} \/\/ namespace art\n\nmips has no sa_restorer.\/*\n * Copyright (C) 2008 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"fault_handler.h\"\n#include \n#include \n#include \"base\/macros.h\"\n#include \"globals.h\"\n#include \"base\/logging.h\"\n#include \"base\/hex_dump.h\"\n#include \"thread.h\"\n#include \"mirror\/art_method-inl.h\"\n#include \"mirror\/class-inl.h\"\n#include \"mirror\/dex_cache.h\"\n#include \"mirror\/object_array-inl.h\"\n#include \"mirror\/object-inl.h\"\n#include \"object_utils.h\"\n#include \"scoped_thread_state_change.h\"\n#include \"verify_object-inl.h\"\n\nnamespace art {\n\/\/ Static fault manger object accessed by signal handler.\nFaultManager fault_manager;\n\n\/\/ Signal handler called on SIGSEGV.\nstatic void art_fault_handler(int sig, siginfo_t* info, void* context) {\n fault_manager.HandleFault(sig, info, context);\n}\n\nFaultManager::FaultManager() {\n sigaction(SIGSEGV, nullptr, &oldaction_);\n}\n\nFaultManager::~FaultManager() {\n sigaction(SIGSEGV, &oldaction_, nullptr); \/\/ Restore old handler.\n}\n\nvoid FaultManager::Init() {\n struct sigaction action;\n action.sa_sigaction = art_fault_handler;\n sigemptyset(&action.sa_mask);\n action.sa_flags = SA_SIGINFO | SA_ONSTACK;\n#if !defined(__mips__)\n action.sa_restorer = nullptr;\n#endif\n sigaction(SIGSEGV, &action, &oldaction_);\n}\n\nvoid FaultManager::HandleFault(int sig, siginfo_t* info, void* context) {\n bool handled = false;\n if (IsInGeneratedCode(context)) {\n for (auto& handler : handlers_) {\n handled = handler->Action(sig, info, context);\n if (handled) {\n return;\n }\n }\n }\n\n if (!handled) {\n LOG(INFO)<< \"Caught unknown SIGSEGV in ART fault handler\";\n oldaction_.sa_sigaction(sig, info, context);\n }\n}\n\nvoid FaultManager::AddHandler(FaultHandler* handler) {\n handlers_.push_back(handler);\n}\n\nvoid FaultManager::RemoveHandler(FaultHandler* handler) {\n for (Handlers::iterator i = handlers_.begin(); i != handlers_.end(); ++i) {\n FaultHandler* h = *i;\n if (h == handler) {\n handlers_.erase(i);\n return;\n }\n }\n}\n\n\n\/\/ This function is called within the signal handler. It checks that\n\/\/ the mutator_lock is held (shared). No annotalysis is done.\nbool FaultManager::IsInGeneratedCode(void *context) {\n \/\/ We can only be running Java code in the current thread if it\n \/\/ is in Runnable state.\n Thread* thread = Thread::Current();\n if (thread == nullptr) {\n return false;\n }\n\n ThreadState state = thread->GetState();\n if (state != kRunnable) {\n return false;\n }\n\n \/\/ Current thread is runnable.\n \/\/ Make sure it has the mutator lock.\n if (!Locks::mutator_lock_->IsSharedHeld(thread)) {\n return false;\n }\n\n uintptr_t potential_method = 0;\n uintptr_t return_pc = 0;\n\n \/\/ Get the architecture specific method address and return address. These\n \/\/ are in architecture specific files in arch\/\/fault_handler_.cc\n GetMethodAndReturnPC(context, \/*out*\/potential_method, \/*out*\/return_pc);\n\n \/\/ If we don't have a potential method, we're outta here.\n if (potential_method == 0) {\n return false;\n }\n\n \/\/ Verify that the potential method is indeed a method.\n \/\/ TODO: check the GC maps to make sure it's an object.\n\n mirror::Object* method_obj =\n reinterpret_cast(potential_method);\n\n \/\/ Check that the class pointer inside the object is not null and is aligned.\n mirror::Class* cls = method_obj->GetClass();\n if (cls == nullptr) {\n return false;\n }\n if (!IsAligned(cls)) {\n return false;\n }\n\n\n if (!VerifyClassClass(cls)) {\n return false;\n }\n\n \/\/ Now make sure the class is a mirror::ArtMethod.\n if (!cls->IsArtMethodClass()) {\n return false;\n }\n\n \/\/ We can be certain that this is a method now. Check if we have a GC map\n \/\/ at the return PC address.\n mirror::ArtMethod* method =\n reinterpret_cast(potential_method);\n return method->ToDexPc(return_pc, false) != DexFile::kDexNoIndex;\n}\n\n\/\/\n\/\/ Null pointer fault handler\n\/\/\n\nNullPointerHandler::NullPointerHandler(FaultManager* manager) {\n manager->AddHandler(this);\n}\n\n\/\/\n\/\/ Suspension fault handler\n\/\/\n\nSuspensionHandler::SuspensionHandler(FaultManager* manager) {\n manager->AddHandler(this);\n}\n\n\/\/\n\/\/ Stack overflow fault handler\n\/\/\n\nStackOverflowHandler::StackOverflowHandler(FaultManager* manager) {\n manager->AddHandler(this);\n}\n} \/\/ namespace art\n\n<|endoftext|>"} {"text":"\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace Beard {\nnamespace txt {\n\n\/\/ class Cursor implementation\n\n\/\/ positioning\n\nbool\nCursor::row_bound() noexcept {\n\tif (signed_cast(get_tree().lines()) <= m_row) {\n\t\trow_extent(txt::Extent::tail);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid\nCursor::row_abs(\n\tposition_type row\n) noexcept {\n\trow = max_ce(\n\t\trow,\n\t\tmax_ce(\n\t\t\tsigned_cast(std::size_t{0u}),\n\t\t\tsigned_cast(get_tree().lines()) - 1\n\t\t)\n\t);\n\tif (row != m_row) {\n\t\tm_row = row;\n\t\tcol_recalc();\n\t}\n}\n\nvoid\nCursor::col_recalc() noexcept {\n\tposition_type col = 0;\n\tauto const& node = get_node();\n\tauto const end = node.cend();\n\tauto step = node.cbegin(), from = step;\n\twhile (\n\t\tfrom < (step = txt::EncUtils::next(from, end)) &&\n\t\tcol > m_col\n\t) {\n\t\tfrom = step;\n\t\t++col;\n\t}\n\tm_col = col;\n\tm_index = std::distance(node.cbegin(), from);\n}\n\nvoid\nCursor::col_step(\n\tdifference_type const n\n) noexcept {\n\tif (0 == n) {\n\t\treturn;\n\t}\n\n\tauto const& node = get_node();\n\tdifference_type const dest = m_col + n;\n\tDUCT_DEBUGF(\n\t\t\"col_step: m_col = %zd, m_index = %zd, dest = %ld, n = %ld, \"\n\t\t\"diff = %zd, abs = %zd\",\n\t\tm_col, m_index, dest, n,\n\t\tdest - m_col,\n\t\tstd::abs(dest - m_col)\n\t);\n\n\t\/\/ Recalculate (i.e., count from the beginning) or step\n\t\/\/ depending on the distance from the current column\n\tif (0 >= dest) {\n\t\tDUCT_DEBUG(\" to head\");\n\t\tm_col = 0;\n\t\tm_index = 0;\n\t} else if (node.points() <= unsigned_cast(dest)) {\n\t\tDUCT_DEBUG(\" to tail\");\n\t\tm_col = signed_cast(node.points());\n\t\tm_index = signed_cast(node.units());\n\t} else if (node.singular()) {\n\t\tDUCT_DEBUG(\" singular\");\n\t\tm_col = dest;\n\t\tm_index = dest;\n\t} else if (dest < std::abs(dest - m_col)) {\n\t\tDUCT_DEBUG(\" recalculating\");\n\t\tm_col = dest;\n\t\tcol_recalc();\n\t} else {\n\t\tauto const begin = node.cbegin(), end = node.cend();\n\t\tauto step = begin + m_index, from = step;\n\t\tif (0 > n) {\n\t\t\t\/\/ Step backward\n\t\t\tDUCT_DEBUG(\" stepping backward\");\n\t\t\twhile (\n\t\t\t\tfrom > (step = txt::EncUtils::prev(from, begin)) &&\n\t\t\t\tdest < m_col\n\t\t\t) {\n\t\t\t\tfrom = step;\n\t\t\t\t--m_col;\n\t\t\t\tDUCT_DEBUG(\" --\");\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Step forward\n\t\t\tDUCT_DEBUG(\" stepping forward\");\n\t\t\twhile (\n\t\t\t\tfrom < (step = txt::EncUtils::next(from, end)) &&\n\t\t\t\tdest > m_col\n\t\t\t) {\n\t\t\t\tfrom = step;\n\t\t\t\t++m_col;\n\t\t\t\tDUCT_DEBUG(\" ++\");\n\t\t\t}\n\t\t}\n\t\tm_index = std::distance(begin, from);\n\t\tDUCT_DEBUGF(\n\t\t\t\" m_col = %zd, m_index = %zd, dist = %ld\",\n\t\t\tm_col,\n\t\t\tm_index,\n\t\t\tstd::distance(begin, from)\n\t\t);\n\t}\n}\n\n\/\/ operations\n\nvoid\nCursor::assign(\n\tString const& str\n) {\n\tauto& node = get_node();\n\tauto const ucount = signed_cast(node.units());\n\tauto const pcount = signed_cast(node.points());\n\tnode.m_buffer.assign(str.cbegin(), str.cend());\n\tauto const new_pcount = signed_cast(\n\t\ttxt::EncUtils::count(str.cbegin(), str.cend(), false)\n\t);\n\tget_tree().update_counts(\n\t\tnode,\n\t\tsigned_cast(node.units()) - ucount,\n\t\tnew_pcount - pcount\n\t);\n\tcol_recalc();\n}\n\nstd::size_t\nCursor::insert(\n\tchar32 const cp\n) {\n\ttxt::EncUtils::char_type units[txt::EncUtils::max_units];\n\tauto const it = txt::EncUtils::encode(\n\t\tcp,\n\t\tstd::begin(units),\n\t\tduct::CHAR_NULL\n\t);\n\tif (std::begin(units) != it) {\n\t\tauto& node = get_node();\n\t\tnode.m_buffer.insert(node.cbegin() + m_index, std::begin(units), it);\n\t\tauto const size = std::distance(std::begin(units), it);\n\t\tget_tree().update_counts(node, size, 1);\n\t\treturn unsigned_cast(size);\n\t} else {\n\t\t\/\/ Invalid code point (ignored)\n\t\treturn 0u;\n\t}\n}\n\nstd::size_t\nCursor::insert_step(\n\tchar32 const cp\n) {\n\tauto const size = insert(cp);\n\tif (0u < size) {\n\t\tDUCT_DEBUGF(\n\t\t\t\"insert_step: m_col = %zd, m_index = %zd, size = %zu\",\n\t\t\tm_col, m_index, size\n\t\t);\n\t\t++m_col;\n\t\tm_index += size;\n\t}\n\treturn size;\n}\n\nstd::size_t\nCursor::erase() {\n\tauto& node = get_node();\n\tDUCT_DEBUGF(\n\t\t\"erase: m_col = %zd, m_index = %zd, ucount = %zu\",\n\t\tm_col, m_index, node.units()\n\t);\n\tif (signed_cast(node.units()) <= m_index) {\n\t\treturn 0u;\n\t}\n\n\tauto const it = node.cbegin() + m_index;\n\tauto const size = txt::EncUtils::required_first_whole(*it);\n\tDUCT_DEBUGF(\" size = %u\", size);\n\tif (it + size <= node.cend()) {\n\t\tDUCT_DEBUG(\" erasing\");\n\t\tnode.m_buffer.erase(it, it + size);\n\t\tget_tree().update_counts(node, -size, -1);\n\t\treturn size;\n\t} else {\n\t\t\/\/ Incomplete sequence\n\t\tDUCT_DEBUG(\" ics\");\n\t\treturn 0u;\n\t}\n}\n\nstd::size_t\nCursor::erase_before() {\n\tDUCT_DEBUGF(\n\t\t\"erase_before: m_col = %zu, m_index = %zu\",\n\t\tm_col, m_index\n\t);\n\tif (0 < m_col) {\n\t\tcol_prev();\n\t\treturn erase();\n\t} else {\n\t\t\/\/ Nothing preceding the cursor to erase\n\t\treturn 0u;\n\t}\n}\n\n} \/\/ namespace Beard\n} \/\/ namespace txt\ntxt::Cursor: optimized col_recalc() when node is singular or col is invalid.\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace Beard {\nnamespace txt {\n\n\/\/ class Cursor implementation\n\n\/\/ positioning\n\nbool\nCursor::row_bound() noexcept {\n\tif (signed_cast(get_tree().lines()) <= m_row) {\n\t\trow_extent(txt::Extent::tail);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid\nCursor::row_abs(\n\tposition_type row\n) noexcept {\n\trow = max_ce(\n\t\trow,\n\t\tmax_ce(\n\t\t\tsigned_cast(std::size_t{0u}),\n\t\t\tsigned_cast(get_tree().lines()) - 1\n\t\t)\n\t);\n\tif (row != m_row) {\n\t\tm_row = row;\n\t\tcol_recalc();\n\t}\n}\n\nvoid\nCursor::col_recalc() noexcept {\n\tauto const& node = get_node();\n\tif (0 >= m_col) {\n\t\tm_col = 0;\n\t\tm_index = 0;\n\t} else if (node.points() <= unsigned_cast(m_col)) {\n\t\tm_col = signed_cast(node.points());\n\t\tm_index = signed_cast(node.units());\n\t} else if (node.singular()) {\n\t\tm_col = dest;\n\t\tm_index = dest;\n\t} else {\n\t\tposition_type col = 0;\n\t\tauto const end = node.cend();\n\t\tauto step = node.cbegin(), from = step;\n\t\twhile (\n\t\t\tfrom < (step = txt::EncUtils::next(from, end)) &&\n\t\t\tcol > m_col\n\t\t) {\n\t\t\tfrom = step;\n\t\t\t++col;\n\t\t}\n\t\tm_col = col;\n\t\tm_index = std::distance(node.cbegin(), from);\n\t}\n}\n\nvoid\nCursor::col_step(\n\tdifference_type const n\n) noexcept {\n\tif (0 == n) {\n\t\treturn;\n\t}\n\n\tauto const& node = get_node();\n\tdifference_type const dest = m_col + n;\n\tDUCT_DEBUGF(\n\t\t\"col_step: m_col = %zd, m_index = %zd, dest = %ld, n = %ld, \"\n\t\t\"diff = %zd, abs = %zd\",\n\t\tm_col, m_index, dest, n,\n\t\tdest - m_col,\n\t\tstd::abs(dest - m_col)\n\t);\n\n\t\/\/ Recalculate (i.e., count from the beginning) or step\n\t\/\/ depending on the distance from the current column\n\tif (0 >= dest) {\n\t\tDUCT_DEBUG(\" to head\");\n\t\tm_col = 0;\n\t\tm_index = 0;\n\t} else if (node.points() <= unsigned_cast(dest)) {\n\t\tDUCT_DEBUG(\" to tail\");\n\t\tm_col = signed_cast(node.points());\n\t\tm_index = signed_cast(node.units());\n\t} else if (node.singular()) {\n\t\tDUCT_DEBUG(\" singular\");\n\t\tm_col = dest;\n\t\tm_index = dest;\n\t} else if (dest < std::abs(dest - m_col)) {\n\t\tDUCT_DEBUG(\" recalculating\");\n\t\tm_col = dest;\n\t\tcol_recalc();\n\t} else {\n\t\tauto const begin = node.cbegin(), end = node.cend();\n\t\tauto step = begin + m_index, from = step;\n\t\tif (0 > n) {\n\t\t\t\/\/ Step backward\n\t\t\tDUCT_DEBUG(\" stepping backward\");\n\t\t\twhile (\n\t\t\t\tfrom > (step = txt::EncUtils::prev(from, begin)) &&\n\t\t\t\tdest < m_col\n\t\t\t) {\n\t\t\t\tfrom = step;\n\t\t\t\t--m_col;\n\t\t\t\tDUCT_DEBUG(\" --\");\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Step forward\n\t\t\tDUCT_DEBUG(\" stepping forward\");\n\t\t\twhile (\n\t\t\t\tfrom < (step = txt::EncUtils::next(from, end)) &&\n\t\t\t\tdest > m_col\n\t\t\t) {\n\t\t\t\tfrom = step;\n\t\t\t\t++m_col;\n\t\t\t\tDUCT_DEBUG(\" ++\");\n\t\t\t}\n\t\t}\n\t\tm_index = std::distance(begin, from);\n\t\tDUCT_DEBUGF(\n\t\t\t\" m_col = %zd, m_index = %zd, dist = %ld\",\n\t\t\tm_col,\n\t\t\tm_index,\n\t\t\tstd::distance(begin, from)\n\t\t);\n\t}\n}\n\n\/\/ operations\n\nvoid\nCursor::assign(\n\tString const& str\n) {\n\tauto& node = get_node();\n\tauto const ucount = signed_cast(node.units());\n\tauto const pcount = signed_cast(node.points());\n\tnode.m_buffer.assign(str.cbegin(), str.cend());\n\tauto const new_pcount = signed_cast(\n\t\ttxt::EncUtils::count(str.cbegin(), str.cend(), false)\n\t);\n\tget_tree().update_counts(\n\t\tnode,\n\t\tsigned_cast(node.units()) - ucount,\n\t\tnew_pcount - pcount\n\t);\n\tcol_recalc();\n}\n\nstd::size_t\nCursor::insert(\n\tchar32 const cp\n) {\n\ttxt::EncUtils::char_type units[txt::EncUtils::max_units];\n\tauto const it = txt::EncUtils::encode(\n\t\tcp,\n\t\tstd::begin(units),\n\t\tduct::CHAR_NULL\n\t);\n\tif (std::begin(units) != it) {\n\t\tauto& node = get_node();\n\t\tnode.m_buffer.insert(node.cbegin() + m_index, std::begin(units), it);\n\t\tauto const size = std::distance(std::begin(units), it);\n\t\tget_tree().update_counts(node, size, 1);\n\t\treturn unsigned_cast(size);\n\t} else {\n\t\t\/\/ Invalid code point (ignored)\n\t\treturn 0u;\n\t}\n}\n\nstd::size_t\nCursor::insert_step(\n\tchar32 const cp\n) {\n\tauto const size = insert(cp);\n\tif (0u < size) {\n\t\tDUCT_DEBUGF(\n\t\t\t\"insert_step: m_col = %zd, m_index = %zd, size = %zu\",\n\t\t\tm_col, m_index, size\n\t\t);\n\t\t++m_col;\n\t\tm_index += size;\n\t}\n\treturn size;\n}\n\nstd::size_t\nCursor::erase() {\n\tauto& node = get_node();\n\tDUCT_DEBUGF(\n\t\t\"erase: m_col = %zd, m_index = %zd, ucount = %zu\",\n\t\tm_col, m_index, node.units()\n\t);\n\tif (signed_cast(node.units()) <= m_index) {\n\t\treturn 0u;\n\t}\n\n\tauto const it = node.cbegin() + m_index;\n\tauto const size = txt::EncUtils::required_first_whole(*it);\n\tDUCT_DEBUGF(\" size = %u\", size);\n\tif (it + size <= node.cend()) {\n\t\tDUCT_DEBUG(\" erasing\");\n\t\tnode.m_buffer.erase(it, it + size);\n\t\tget_tree().update_counts(node, -size, -1);\n\t\treturn size;\n\t} else {\n\t\t\/\/ Incomplete sequence\n\t\tDUCT_DEBUG(\" ics\");\n\t\treturn 0u;\n\t}\n}\n\nstd::size_t\nCursor::erase_before() {\n\tDUCT_DEBUGF(\n\t\t\"erase_before: m_col = %zu, m_index = %zu\",\n\t\tm_col, m_index\n\t);\n\tif (0 < m_col) {\n\t\tcol_prev();\n\t\treturn erase();\n\t} else {\n\t\t\/\/ Nothing preceding the cursor to erase\n\t\treturn 0u;\n\t}\n}\n\n} \/\/ namespace Beard\n} \/\/ namespace txt\n<|endoftext|>"} {"text":"\/*\nMIT License Block\n\nCopyright (c) 2016 Alex Barry\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"include\/zmqio.h\"\n\n\/\/-------------------------Inbound ZMQ Admin----------------------------------\/\/\n\n\/\/Constructor & Destructor\nZmqi::Zmqi(zmq::context_t &context, int connection_type)\n{\n if (connection_type == REQ_RESP) {\n zmqi = new zmq::socket_t (context, ZMQ_REP);\n }\n else if (connection_type == PUB_SUB) {\n zmqi = new zmq::socket_t (context, ZMQ_SUB);\n }\n conn_type = connection_type;\n request = new zmq::message_t;\n}\n\nZmqi::~Zmqi()\n{\n delete zmqi;\n delete request;\n if (rcv_cstr) {delete[] rcv_cstr;}\n}\n\n\/\/Bind the inbound socket\nvoid Zmqi::bind(std::string conn_str)\n{\n if (conn_type == REQ_RESP) {\n zmqi->bind(conn_str);\n }\n else if (conn_type == PUB_SUB) {\n zmqi->connect(conn_str);\n }\n}\n\n\/\/Recieve an inbound message\nstd::string Zmqi::recv()\n{\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (started) {\n request->rebuild();\n }\n\n \/\/ Wait for next request from client\n zmqi->recv (request);\n\n \/\/Convert the OMQ message into a string to be passed\n req_string.assign(static_cast(request->data()), request->size());\n started = true;\n return req_string;\n}\n\n\/\/Recieve an inbound message\nchar * Zmqi::crecv() {\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (started) {request->rebuild();}\n if (rcv_cstr) {delete[] rcv_cstr;rcv_cstr=NULL;}\n\n \/\/ Wait for next request from client\n zmqi->recv (request);\n\n \/\/ Take the data out of the message\n if (request->size() > 0 {\n rcv_cstr = new char [request->size()];\n std::memcpy(rcv_cstr, request->data(), request->size());\n }\n\n started = true;\n\n \/\/Convert the OMQ message into a string to be passed\n \/\/rcv_cstr = static_cast(request.data()), request.size();\n return rcv_cstr;\n}\n\n\/\/Send a response\nvoid Zmqi::send(const char * msg, int msg_size)\n{\n \/\/ Send reply back to client\n zmq::message_t reply (msg_size);\n\n \/\/Prepare return data\n memcpy (reply.data (), msg, msg_size);\n \/\/Send the response\n zmqi->send (reply);\n}\n\n\/\/Send a string response\nvoid Zmqi::send(std::string msg)\n{\n msg_cstr = msg.c_str();\n send(msg_cstr, msg.size());\n}\n\nvoid Zmqi::subscribe(std::string filter)\n{\n zmqi->setsockopt(ZMQ_SUBSCRIBE, filter.c_str(), filter.size());\n}\n\n\/\/-------------------------Outbound ZMQ Admin---------------------------------\/\/\n\n\/\/Constructor & Destructor\nZmqo::Zmqo(zmq::context_t &context, int connection_type)\n{\n if (connection_type == REQ_RESP) {\n zmqo = new zmq::socket_t (context, ZMQ_REQ);\n }\n else if (connection_type == PUB_SUB) {\n zmqo = new zmq::socket_t (context, ZMQ_PUB);\n }\n conn_type = connection_type;\n}\n\nZmqo::~Zmqo()\n{\n delete zmqo;\n if (rcv_cstr) {delete[] rcv_cstr;}\n}\n\n\/\/Connect to the Socket\nvoid Zmqo::connect(std::string conn_str)\n{\n if (conn_type == REQ_RESP) {\n zmqo->connect(conn_str);\n }\n else if (conn_type == PUB_SUB) {\n zmqo->bind(conn_str);\n }\n}\n\n\/\/Send a message\nvoid Zmqo::send(const char * msg, int msg_size)\n{\n std::lock_guard lock(send_mutex);\n \/\/Set up the message to go out on 0MQ\n zmq::message_t req (msg_size);\n memcpy (req.data (), msg, msg_size);\n\n \/\/Send the message\n zmqo->send (req);\n}\n\n\/\/Send a string message\nvoid Zmqo::send(std::string msg) {\n msg_cstr = msg.c_str();\n send(msg_cstr, msg.size());\n}\n\n\/\/Recieve a Response\nstd::string Zmqo::recv()\n{\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (!started) {\n request.rebuild();\n }\n \/\/ Get the reply.\n zmqo->recv (&request);\n\n \/\/Process the reply\n r_str.assign(static_cast(request.data()), request.size());\n started = true;\n return r_str;\n}\n\n\/\/Recieve an response\nchar * Zmqo::crecv() {\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (!started) {\n request.rebuild();\n }\n\n if (rcv_cstr) {delete[] rcv_cstr;rcv_cstr=NULL;}\n\n \/\/ Wait for next request from client\n zmqo->recv (&request);\n\n \/\/ Take the data out of the message\n rcv_cstr = new char [request.size()];\n std::memcpy(rcv_cstr, request.data(), request.size());\n\n started = true;\n\n \/\/Convert the OMQ message into a string to be passed\n \/\/rcv_cstr = static_cast(request.data()), request.size();\n return rcv_cstr;\n}\nZMQ Memory allocation fix\/*\nMIT License Block\n\nCopyright (c) 2016 Alex Barry\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"include\/zmqio.h\"\n\n\/\/-------------------------Inbound ZMQ Admin----------------------------------\/\/\n\n\/\/Constructor & Destructor\nZmqi::Zmqi(zmq::context_t &context, int connection_type)\n{\n if (connection_type == REQ_RESP) {\n zmqi = new zmq::socket_t (context, ZMQ_REP);\n }\n else if (connection_type == PUB_SUB) {\n zmqi = new zmq::socket_t (context, ZMQ_SUB);\n }\n conn_type = connection_type;\n request = new zmq::message_t;\n}\n\nZmqi::~Zmqi()\n{\n delete zmqi;\n delete request;\n if (rcv_cstr) {delete[] rcv_cstr;}\n}\n\n\/\/Bind the inbound socket\nvoid Zmqi::bind(std::string conn_str)\n{\n if (conn_type == REQ_RESP) {\n zmqi->bind(conn_str);\n }\n else if (conn_type == PUB_SUB) {\n zmqi->connect(conn_str);\n }\n}\n\n\/\/Recieve an inbound message\nstd::string Zmqi::recv()\n{\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (started) {\n request->rebuild();\n }\n\n \/\/ Wait for next request from client\n zmqi->recv (request);\n\n \/\/Convert the OMQ message into a string to be passed\n req_string.assign(static_cast(request->data()), request->size());\n started = true;\n return req_string;\n}\n\n\/\/Recieve an inbound message\nchar * Zmqi::crecv() {\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (started) {request->rebuild();}\n if (rcv_cstr) {delete[] rcv_cstr;rcv_cstr=NULL;}\n\n \/\/ Wait for next request from client\n zmqi->recv (request);\n\n \/\/ Take the data out of the message\n if (request->size() > 0) {\n rcv_cstr = new char [request->size()];\n std::memcpy(rcv_cstr, request->data(), request->size());\n }\n\n started = true;\n\n \/\/Convert the OMQ message into a string to be passed\n \/\/rcv_cstr = static_cast(request.data()), request.size();\n return rcv_cstr;\n}\n\n\/\/Send a response\nvoid Zmqi::send(const char * msg, int msg_size)\n{\n \/\/ Send reply back to client\n zmq::message_t reply (msg_size);\n\n \/\/Prepare return data\n memcpy (reply.data (), msg, msg_size);\n \/\/Send the response\n zmqi->send (reply);\n}\n\n\/\/Send a string response\nvoid Zmqi::send(std::string msg)\n{\n msg_cstr = msg.c_str();\n send(msg_cstr, msg.size());\n}\n\nvoid Zmqi::subscribe(std::string filter)\n{\n zmqi->setsockopt(ZMQ_SUBSCRIBE, filter.c_str(), filter.size());\n}\n\n\/\/-------------------------Outbound ZMQ Admin---------------------------------\/\/\n\n\/\/Constructor & Destructor\nZmqo::Zmqo(zmq::context_t &context, int connection_type)\n{\n if (connection_type == REQ_RESP) {\n zmqo = new zmq::socket_t (context, ZMQ_REQ);\n }\n else if (connection_type == PUB_SUB) {\n zmqo = new zmq::socket_t (context, ZMQ_PUB);\n }\n conn_type = connection_type;\n}\n\nZmqo::~Zmqo()\n{\n delete zmqo;\n if (rcv_cstr) {delete[] rcv_cstr;}\n}\n\n\/\/Connect to the Socket\nvoid Zmqo::connect(std::string conn_str)\n{\n if (conn_type == REQ_RESP) {\n zmqo->connect(conn_str);\n }\n else if (conn_type == PUB_SUB) {\n zmqo->bind(conn_str);\n }\n}\n\n\/\/Send a message\nvoid Zmqo::send(const char * msg, int msg_size)\n{\n std::lock_guard lock(send_mutex);\n \/\/Set up the message to go out on 0MQ\n zmq::message_t req (msg_size);\n memcpy (req.data (), msg, msg_size);\n\n \/\/Send the message\n zmqo->send (req);\n}\n\n\/\/Send a string message\nvoid Zmqo::send(std::string msg) {\n msg_cstr = msg.c_str();\n send(msg_cstr, msg.size());\n}\n\n\/\/Recieve a Response\nstd::string Zmqo::recv()\n{\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (!started) {\n request.rebuild();\n }\n \/\/ Get the reply.\n zmqo->recv (&request);\n\n \/\/Process the reply\n r_str.assign(static_cast(request.data()), request.size());\n started = true;\n return r_str;\n}\n\n\/\/Recieve an response\nchar * Zmqo::crecv() {\n \/\/ Rebuild the ZeroMQ Message Object\n \/\/ Close the message object and then re-build, this means that\n \/\/ any resources from the message MAY NOT BE PRESENT after the next message has been recieved\n if (!started) {\n request.rebuild();\n }\n\n if (rcv_cstr) {delete[] rcv_cstr;rcv_cstr=NULL;}\n\n \/\/ Wait for next request from client\n zmqo->recv (&request);\n\n \/\/ Take the data out of the message\n rcv_cstr = new char [request.size()];\n std::memcpy(rcv_cstr, request.data(), request.size());\n\n started = true;\n\n \/\/Convert the OMQ message into a string to be passed\n \/\/rcv_cstr = static_cast(request.data()), request.size();\n return rcv_cstr;\n}\n<|endoftext|>"} {"text":"#ifndef GUARD_identity_map_hpp\n#define GUARD_identity_map_hpp\n\n#include \"handle.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ For debugging\n\t#include \n\t#include \n\t#include \n\tusing std::endl;\n\nnamespace sqloxx\n{\n\n\ntemplate \nclass IdentityMap\n{\npublic:\n\n\ttypedef typename T::Id Id;\n\ttypedef typename T::Id ProxyKey;\n\n\tIdentityMap(Connection& p_connection);\n\tIdentityMap(IdentityMap const& rhs);\n\t~IdentityMap();\n\tIdentityMap& operator=(IdentityMap const& rhs);\n\t\/**\n\t * Provide handle to object of T, representing a newly created object\n\t * that has not yet been persisted to the database\n\t *\/\n\tHandle provide_object();\n\n\t\/**\n\t * Provide handle to object of type T, representing an object\n\t * already stored in the database, with id p_id.\n\t *\/\n\tHandle provide_object(Id p_id);\n\t\n\t\/**\n\t * Register id of newly saved T.\n\t *\/\n\tvoid register_id(ProxyKey proxy_key, Id allocated_id);\n\n\tvoid erase_object_proxied(ProxyKey proxy_key);\n\n\t\/**\n\t * Notify the IdentityMap that there are no handles left that are\n\t * pointing to this object.\n\t *\/\n\tvoid notify_nil_handles(ProxyKey proxy_key);\n\n\tvoid enable_caching();\n\n\tvoid disable_caching();\n\n\t\/**\n\t * @returns a reference to the database connection with which\n\t * this IdentityMap is associated.\n\t *\n\t * Exception safety: nothrow guarantee<\/em>.\n\t *\n\t * @todo Testing.\n\t *\/\n\tConnection& connection();\n\nprivate:\n\n\t\/\/ Find the next available proxy key\n\t\/\/ WARNING Move the implementation out of the class body.\n\tProxyKey next_proxy_key();\n\ttypedef typename boost::shared_ptr Record;\n\ttypedef boost::unordered_map IdMap;\n\ttypedef std::map ProxyKeyMap;\n\n\tProxyKeyMap& proxy_map() const\n\t{\n\t\treturn m_map_data->proxy_map;\n\t}\n\n\tIdMap& id_map() const\n\t{\n\t\treturn m_map_data->id_map;\n\t}\n\n\tbool& caching() const\n\t{\n\t\treturn m_map_data->caching;\n\t}\n\n\t\/\/ Data members\n\n\t\/\/ Hold in a struct to facilitate safe, shallow copying.\n\tstruct MapData\n\t{\n\t\tMapData(Connection& p_connection):\n\t\t\tconnection(p_connection),\n\t\t\tcaching(false)\n\t\t{\n\t\t}\n\t\tProxyKeyMap proxy_map; \/\/ For all objects.\n\t\tIdMap id_map; \/\/ For objects that exist in the database.\n\t\t\/\/ Indicates whether the IdentityMap is currently\n\t\t\/\/ holding objects indefinitely in the cache (m_caching == true),\n\t\t\/\/ or whether it is\n\t\t\/\/ clearing each object out when there are no longer handles\n\t\t\/\/ pointing to it (m_caching == false).\n\t\tConnection& connection; \n\t\tbool caching; \n\t};\n\tboost::shared_ptr m_map_data;\n};\n\n\ntemplate \ninline\nIdentityMap::IdentityMap(Connection& p_connection):\n\tm_map_data(new MapData(p_connection))\n{\n}\n\ntemplate \ninline\nIdentityMap::IdentityMap(IdentityMap const& rhs):\n\tm_map_data(rhs.m_map_data)\n{\n}\n\ntemplate \ninline\nIdentityMap::~IdentityMap()\n{\n}\n\ntemplate \ninline\nIdentityMap&\nIdentityMap::operator=(IdentityMap const& rhs)\n{\n\tm_map_data = rhs.m_map_data;\n\treturn *this;\n}\n\ntemplate \nHandle\nIdentityMap::provide_object()\n{\n\t\n\tRecord obj_ptr((new T(*this)));\n\tProxyKey const proxy_key = next_proxy_key();\n\tobj_ptr->set_proxy_key(proxy_key);\n\tproxy_map()[proxy_key] = obj_ptr;\n\treturn Handle(obj_ptr.get());\n}\n\n\ntemplate \nHandle\nIdentityMap::provide_object(Id p_id)\n{\n\ttypename IdMap::iterator it = id_map().find(p_id);\n\tif (it == id_map().end())\n\t{\n\t\t\/\/ Then we need to create this object.\n\t\tRecord obj_ptr(new T(*this, p_id));\n\t\tid_map()[p_id] = obj_ptr;\n\t\tProxyKey proxy_key = next_proxy_key();\n\t\tproxy_map()[proxy_key] = obj_ptr;\n\t\tobj_ptr->set_proxy_key(proxy_key);\n\t\treturn Handle(obj_ptr.get()); \n\t}\n\tassert (it != id_map().end());\n\treturn Handle(it->second.get());\n}\n\ntemplate \nvoid\nIdentityMap::register_id(ProxyKey proxy_key, Id allocated_id)\n{\n\tid_map()[allocated_id] = proxy_map()[proxy_key];\n\treturn;\n}\n\n\ntemplate \nvoid\nIdentityMap::erase_object_proxied(ProxyKey proxy_key)\n{\n\tRecord const record = proxy_map().find(proxy_key)->second;\n\tif (record->has_id())\n\t{\n\t\tassert (id_map().find(record->id()) != id_map().end());\n\t\tid_map().erase(record->id());\n\t}\n\tproxy_map().erase(proxy_key);\n\treturn;\n}\n\ntemplate \nvoid\nIdentityMap::notify_nil_handles(ProxyKey proxy_key)\n{\n\tif (!caching())\n\t{\n\t\terase_object_proxied(proxy_key);\n\t}\n\treturn;\n}\n\ntemplate \nvoid\nIdentityMap::enable_caching()\n{\n\tcaching() = true;\n}\n\ntemplate \nvoid\nIdentityMap::disable_caching()\n{\n\tif (caching())\n\t{\n\t\ttypename ProxyKeyMap::iterator const endpoint = proxy_map().end();\n\t\tfor\n\t\t(\ttypename ProxyKeyMap::iterator it = proxy_map().begin();\n\t\t\tit != endpoint;\n\t\t\t++it\n\t\t)\n\t\t{\n\t\t\tif (it->second->is_orphaned())\n\t\t\t{\n\t\t\t\terase_object_proxied(it->first);\n\t\t\t}\n\t\t}\n\t\tcaching() = false;\n\t}\n\treturn;\n}\n\ntemplate \ninline\nConnection&\nIdentityMap::connection()\n{\n\treturn m_map_data->connection;\n}\n\n\ntemplate \ntypename IdentityMap::ProxyKey\nIdentityMap::next_proxy_key()\n{\n\t\/\/ TODO Change this so that vacated slots are filled, rather\n\t\/\/ than just always taking least - 1. Currently there is\n\t\/\/ a danger that we will just forever move towards min, until\n\t\/\/ we overflow.\n\n\t\/\/ Using negative numbers to avoid any possible confusion\n\t\/\/ with Id.\n\t\/\/ Relies on this being a std::map, in which the first\n\t\/\/ key is less than any other key.\n\tProxyKey const least = proxy_map().begin()->first;\n\tif (least == std::numeric_limits::min())\n\t{\n\t\tthrow OverflowException(\"Proxy key has reached numeric limit.\");\n\t}\n\treturn least - 1;\n}\n\n} \/\/ namespace sqloxx\n\n#endif \/\/ GUARD_identity_map_hpp\nWorked on documentation for sqloxx::IdentityMap.#ifndef GUARD_identity_map_hpp\n#define GUARD_identity_map_hpp\n\n#include \"handle.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ For debugging\n\t#include \n\t#include \n\t#include \n\tusing std::endl;\n\nnamespace sqloxx\n{\n\n\n\/**\n * Provides an in-memory cache for objects of type T, where such\n * objects are persisted to a database via a database connection of\n * type Connection. T and Connection are passed as template parameters\n * to the class template. It is expected that T is a subclass of\n * sqloxx::PersistentObject, and Connection is a\n * subclass of sqloxx::DatabaseConnection.\n *\n * Each instance of IdentityMap has a particular Connection associated\n * with it. The IdentityMap caches objects loaded from the database,\n * and provides clients - in particular the sqloxx::Handle class -\n * pointers to these objects. My using IdentityMap to cache objects,\n * application code can be sure that each single record of type T\n * that is stored in the database, has at most a single in-memory\n * object of type T associated with that record, loaded in memory\n * at any one time. IdentityMap thus implements the \"Identity Map\"\n * pattern detailed in Martin Fowler's book, \"Patterns of Enterprise\n * Application Architecture\". By having at most a single in-memory\n * object per in-database record, we guard against the possibility\n * of the same object being edited inconsistently in different\n * locations. By keeping objects in a cache, we speed execution of\n * read and write operations, by avoiding a trip to the disk when an\n * object has already been loaded.\n *\n * IdentityMap is intended to work in conjunction with sqloxx::Handle\n * and sqloxx::PersistentObject. See also the documentation\n * for those classes.\n *\n * @todo Documentation and testing.\n *\/\ntemplate \nclass IdentityMap\n{\npublic:\n\n\ttypedef typename T::Id Id;\n\ttypedef typename T::Id ProxyKey;\n\n\t\/**\n\t * Construct an IdentityMap associated with the database\n\t * connection Connection. Connection should be a subclass\n\t * of sqloxx::DatabaseConnection.\n\t *\n\t * @throws std::bad_alloc in the case of memory allocation\n\t * failure. (This is very unlikely.)\n\t *\n\t * Exception safety: strong guarantee<\/em>.\n\t *\n\t * @todo Testing.\n\t *\/\n\tIdentityMap(Connection& p_connection);\n\n\t\/**\n\t * Copy constructor. Performs a shallow copy. The underlying\n\t * structures (e.g. database connection and cache) employed\n\t * by the new IdentitMap will be the very same as those employed\n\t * by rhs.\n\t *\n\t * Exception safety: nothrow guarantee<\/em>.\n\t *\/\n\tIdentityMap(IdentityMap const& rhs);\n\t\n\t\/**\n\t * Destructor. The underlying cache is automatically emptied\n\t * of all objects (i.e. instances of T) on destruction of\n\t * the IdentityMap, by the calling the destructor of each\n\t * object in the cache. The cache is then itself destructed.\n\t * However the database connection (Connection instance) referenced\n\t * by the IdentityMap is \\e not destructed merely by virtue\n\t * of the destruction of the IdentityMap.\n\t *\n\t * Exception safety: the nothrow guarantee<\/em> is provided,\n\t * providing the destructor of T does not throw.\n\t *\n\t * @todo Testing.\n\t *\/\n\t~IdentityMap();\n\n\t\/**\n\t * Assignment is shallow, and behaves as per the copy constructor\n\t *\n\t * Exception safety: nothrow guarantee<\/em>.\n\t *\n\t * @todo Testing.\n\t *\/\n\tIdentityMap& operator=(IdentityMap const& rhs);\n\n\t\/**\n\t * Provide handle to object of T, representing a newly created object\n\t * that has not yet been persisted to the database\n\t *\/\n\tHandle provide_object();\n\n\t\/**\n\t * Provide handle to object of type T, representing an object\n\t * already stored in the database, with id p_id.\n\t *\/\n\tHandle provide_object(Id p_id);\n\t\n\t\/**\n\t * Register id of newly saved T.\n\t *\/\n\tvoid register_id(ProxyKey proxy_key, Id allocated_id);\n\n\tvoid erase_object_proxied(ProxyKey proxy_key);\n\n\t\/**\n\t * Notify the IdentityMap that there are no handles left that are\n\t * pointing to this object.\n\t *\/\n\tvoid notify_nil_handles(ProxyKey proxy_key);\n\n\tvoid enable_caching();\n\n\tvoid disable_caching();\n\n\t\/**\n\t * @returns a reference to the database connection with which\n\t * this IdentityMap is associated.\n\t *\n\t * Exception safety: nothrow guarantee<\/em>.\n\t *\n\t * @todo Testing.\n\t *\/\n\tConnection& connection();\n\nprivate:\n\n\t\/\/ Find the next available proxy key\n\t\/\/ WARNING Move the implementation out of the class body.\n\tProxyKey next_proxy_key();\n\ttypedef typename boost::shared_ptr Record;\n\ttypedef boost::unordered_map IdMap;\n\ttypedef std::map ProxyKeyMap;\n\n\tProxyKeyMap& proxy_map() const\n\t{\n\t\treturn m_map_data->proxy_map;\n\t}\n\n\tIdMap& id_map() const\n\t{\n\t\treturn m_map_data->id_map;\n\t}\n\n\tbool& caching() const\n\t{\n\t\treturn m_map_data->caching;\n\t}\n\n\t\/\/ Data members\n\n\t\/\/ Hold in a struct to facilitate safe, shallow copying.\n\tstruct MapData\n\t{\n\t\tMapData(Connection& p_connection):\n\t\t\tconnection(p_connection),\n\t\t\tcaching(false)\n\t\t{\n\t\t}\n\t\tProxyKeyMap proxy_map; \/\/ For all objects.\n\t\tIdMap id_map; \/\/ For objects that exist in the database.\n\t\t\/\/ Indicates whether the IdentityMap is currently\n\t\t\/\/ holding objects indefinitely in the cache (m_caching == true),\n\t\t\/\/ or whether it is\n\t\t\/\/ clearing each object out when there are no longer handles\n\t\t\/\/ pointing to it (m_caching == false).\n\t\tConnection& connection; \n\t\tbool caching; \n\t};\n\tboost::shared_ptr m_map_data;\n};\n\n\ntemplate \ninline\nIdentityMap::IdentityMap(Connection& p_connection):\n\tm_map_data(new MapData(p_connection))\n{\n}\n\ntemplate \ninline\nIdentityMap::IdentityMap(IdentityMap const& rhs):\n\tm_map_data(rhs.m_map_data)\n{\n}\n\ntemplate \ninline\nIdentityMap::~IdentityMap()\n{\n}\n\ntemplate \ninline\nIdentityMap&\nIdentityMap::operator=(IdentityMap const& rhs)\n{\n\tm_map_data = rhs.m_map_data;\n\treturn *this;\n}\n\ntemplate \nHandle\nIdentityMap::provide_object()\n{\n\t\n\tRecord obj_ptr((new T(*this)));\n\tProxyKey const proxy_key = next_proxy_key();\n\tobj_ptr->set_proxy_key(proxy_key);\n\tproxy_map()[proxy_key] = obj_ptr;\n\treturn Handle(obj_ptr.get());\n}\n\n\ntemplate \nHandle\nIdentityMap::provide_object(Id p_id)\n{\n\ttypename IdMap::iterator it = id_map().find(p_id);\n\tif (it == id_map().end())\n\t{\n\t\t\/\/ Then we need to create this object.\n\t\tRecord obj_ptr(new T(*this, p_id));\n\t\tid_map()[p_id] = obj_ptr;\n\t\tProxyKey proxy_key = next_proxy_key();\n\t\tproxy_map()[proxy_key] = obj_ptr;\n\t\tobj_ptr->set_proxy_key(proxy_key);\n\t\treturn Handle(obj_ptr.get()); \n\t}\n\tassert (it != id_map().end());\n\treturn Handle(it->second.get());\n}\n\ntemplate \nvoid\nIdentityMap::register_id(ProxyKey proxy_key, Id allocated_id)\n{\n\tid_map()[allocated_id] = proxy_map()[proxy_key];\n\treturn;\n}\n\n\ntemplate \nvoid\nIdentityMap::erase_object_proxied(ProxyKey proxy_key)\n{\n\tRecord const record = proxy_map().find(proxy_key)->second;\n\tif (record->has_id())\n\t{\n\t\tassert (id_map().find(record->id()) != id_map().end());\n\t\tid_map().erase(record->id());\n\t}\n\tproxy_map().erase(proxy_key);\n\treturn;\n}\n\ntemplate \nvoid\nIdentityMap::notify_nil_handles(ProxyKey proxy_key)\n{\n\tif (!caching())\n\t{\n\t\terase_object_proxied(proxy_key);\n\t}\n\treturn;\n}\n\ntemplate \nvoid\nIdentityMap::enable_caching()\n{\n\tcaching() = true;\n}\n\ntemplate \nvoid\nIdentityMap::disable_caching()\n{\n\tif (caching())\n\t{\n\t\ttypename ProxyKeyMap::iterator const endpoint = proxy_map().end();\n\t\tfor\n\t\t(\ttypename ProxyKeyMap::iterator it = proxy_map().begin();\n\t\t\tit != endpoint;\n\t\t\t++it\n\t\t)\n\t\t{\n\t\t\tif (it->second->is_orphaned())\n\t\t\t{\n\t\t\t\terase_object_proxied(it->first);\n\t\t\t}\n\t\t}\n\t\tcaching() = false;\n\t}\n\treturn;\n}\n\ntemplate \ninline\nConnection&\nIdentityMap::connection()\n{\n\treturn m_map_data->connection;\n}\n\n\ntemplate \ntypename IdentityMap::ProxyKey\nIdentityMap::next_proxy_key()\n{\n\t\/\/ TODO Change this so that vacated slots are filled, rather\n\t\/\/ than just always taking least - 1. Currently there is\n\t\/\/ a danger that we will just forever move towards min, until\n\t\/\/ we overflow.\n\n\t\/\/ Using negative numbers to avoid any possible confusion\n\t\/\/ with Id.\n\t\/\/ Relies on this being a std::map, in which the first\n\t\/\/ key is less than any other key.\n\tProxyKey const least = proxy_map().begin()->first;\n\tif (least == std::numeric_limits::min())\n\t{\n\t\tthrow OverflowException(\"Proxy key has reached numeric limit.\");\n\t}\n\treturn least - 1;\n}\n\n} \/\/ namespace sqloxx\n\n#endif \/\/ GUARD_identity_map_hpp\n<|endoftext|>"} {"text":"\/\/=============================================================================\n\/\/ File: token.cpp\n\/\/ Contents: Definitions for DwTokenizer, DwRfc822Tokenizer\n\/\/ Maintainer: Doug Sauder \n\/\/ WWW: http:\/\/www.fwb.gulf.net\/~dwsauder\/mimepp.html\n\/\/ $Revision$\n\/\/ $Date$\n\/\/\n\/\/ Copyright (c) 1996, 1997 Douglas W. Sauder\n\/\/ All rights reserved.\n\/\/\n\/\/ IN NO EVENT SHALL DOUGLAS W. SAUDER BE LIABLE TO ANY PARTY FOR DIRECT,\n\/\/ INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF\n\/\/ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF DOUGLAS W. SAUDER\n\/\/ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ DOUGLAS W. SAUDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT\n\/\/ NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\/\/ PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN \"AS IS\"\n\/\/ BASIS, AND DOUGLAS W. SAUDER HAS NO OBLIGATION TO PROVIDE MAINTENANCE,\n\/\/ SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\/\/\n\/\/=============================================================================\n\n#define DW_IMPLEMENTATION\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstd::ostream* DwTokenizer::mDebugOut = 0;\n\n\nDwTokenizer::DwTokenizer(const DwString& aStr)\n : mString(aStr)\n{\n mTokenStart = 0;\n mTokenLength = 0;\n mNextStart = 0;\n mTkType = eTkError;\n}\n\n\nDwTokenizer::DwTokenizer(const char* aCStr)\n : mString(aCStr)\n{\n mTokenStart = 0;\n mTokenLength = 0;\n mNextStart = 0;\n mTkType = eTkError;\n}\n\n\nDwTokenizer::~DwTokenizer()\n{\n}\n\n\nvoid DwTokenizer::StripDelimiters()\n{\n if (mTokenLength < 2) return;\n \/\/ const ref -- avoids copy on write when using operator[]\n const DwString& token = mToken;\n switch (mTkType) {\n case eTkQuotedString:\n if (token[0] == '\"') {\n mToken = mToken.substr(1);\n ++mTokenStart;\n --mTokenLength;\n }\n if (mTokenLength > 0 && token[mTokenLength-1] == '\"') {\n mToken = mToken.substr(0, mTokenLength-1);\n --mTokenLength;\n }\n break;\n case eTkDomainLiteral:\n if (token[0] == '[') {\n mToken = mToken.substr(1);\n ++mTokenStart;\n --mTokenLength;\n }\n if (mTokenLength > 0 && token[mTokenLength-1] == ']') {\n mToken = mToken.substr(0, mTokenLength-1);\n --mTokenLength;\n }\n break;\n case eTkComment:\n if (token[0] == '(') {\n mToken = mToken.substr(1);\n ++mTokenStart;\n --mTokenLength;\n }\n if (mTokenLength > 0 && token[mTokenLength-1] == ')') {\n mToken = mToken.substr(0, mTokenLength-1);\n --mTokenLength;\n }\n break;\n }\n}\n\n\nvoid DwTokenizer::ParseQuotedString()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n else if (mString[pos] == '\\\\') {\n \/\/ Quoted character\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n }\n else if (mString[pos] == '\"') {\n \/\/ End of quoted string\n ++pos;\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\n\nvoid DwTokenizer::ParseComment()\n{\n size_t pos = mTokenStart;\n int level = 1;\n while (1) {\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n else if (mString[pos] == '\\\\') {\n \/\/ Quoted character\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n }\n else if (mString[pos] == ')') {\n --level;\n if (level == 0) {\n \/\/ End of comment\n ++pos;\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n else if (mString[pos] == '(') {\n ++level;\n }\n }\n}\n\n\nvoid DwTokenizer::ParseDomainLiteral()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n else if (mString[pos] == '\\\\') {\n \/\/ Quoted character\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n }\n else if (mString[pos] == ']') {\n \/\/ End of domain literal\n ++pos;\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\n\nvoid DwTokenizer::PrintToken(std::ostream* aOut)\n{\n if (!aOut) return;\n const char* type = 0;\n switch (mTkType) {\n case eTkError:\n type = \"error \";\n break;\n case eTkNull:\n type = \"null \";\n break;\n case eTkSpecial:\n type = \"special \";\n break;\n case eTkAtom:\n type = \"atom \";\n break;\n case eTkComment:\n type = \"comment \";\n break;\n case eTkQuotedString:\n type = \"quoted string \";\n break;\n case eTkDomainLiteral:\n type = \"domain literal \";\n break;\n case eTkTspecial:\n type = \"tspecial \";\n break;\n case eTkToken:\n type = \"token \";\n break;\n default:\n type = \"unknown \";\n break;\n }\n *aOut << type << mToken << '\\n';\n}\n\n\n#define isspecial(c) ((c)=='('||(c)==')'||(c)=='<'||(c)=='>'||(c)=='@'\\\n ||(c)==','||(c)==';'||(c)==':'||(c)=='\\\\'||(c)=='\"'||(c)=='.'\\\n ||(c)=='['||(c)==']')\n\n\nDwRfc822Tokenizer::DwRfc822Tokenizer(const DwString& aStr)\n : DwTokenizer(aStr)\n{\n ParseToken();\n}\n\n\nDwRfc822Tokenizer::DwRfc822Tokenizer(const char* aCStr)\n : DwTokenizer(aCStr)\n{\n ParseToken();\n}\n\n\nDwRfc822Tokenizer::~DwRfc822Tokenizer()\n{\n}\n\n\nint DwRfc822Tokenizer::Restart()\n{\n mNextStart = 0;\n ParseToken();\n return mTkType;\n}\n\n\nint DwRfc822Tokenizer::operator ++ ()\n{\n ParseToken();\n return mTkType;\n}\n\n\nvoid DwRfc822Tokenizer::ParseToken()\n{\n \/\/ Assume the field body has already been extracted. That is, we don't\n \/\/ have to watch for the end of the field body or folding. We just\n \/\/ treat any CRs or LFs as white space.\n mTokenStart = mNextStart;\n mTokenLength = 0;\n mTkType = eTkNull;\n if (mTokenStart >= mString.length()) {\n return;\n }\n \/\/ Skip leading space. Also, since control chars are not permitted\n \/\/ in atoms, skip these, too.\n while (1) {\n if (mTokenStart >= mString.length()) {\n return;\n }\n if (!isspace(mString[mTokenStart]) && !iscntrl(mString[mTokenStart]))\n break;\n ++mTokenStart;\n }\n char ch = mString[mTokenStart];\n \/\/ Quoted string\n if (ch == '\"') {\n mTkType = eTkQuotedString;\n ParseQuotedString();\n }\n \/\/ Comment\n else if (ch == '(') {\n mTkType = eTkComment;\n ParseComment();\n }\n \/\/ Domain literal\n else if (ch == '[') {\n mTkType = eTkDomainLiteral;\n ParseDomainLiteral();\n }\n \/\/ Special\n else if (isspecial(ch)) {\n mTkType = eTkSpecial;\n mTokenLength = 1;\n mToken = mString.substr(mTokenStart, 1);\n mNextStart = mTokenStart + 1;\n }\n \/\/ Atom\n else {\n mTkType = eTkAtom;\n ParseAtom();\n }\n if (mDebugOut) PrintToken(mDebugOut);\n}\n\n\nvoid DwRfc822Tokenizer::ParseAtom()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n char ch = (pos < mString.length()) ? mString[pos] : (char) 0;\n if (pos >= mString.length()\n || isspace(ch)\n || iscntrl(ch)\n || isspecial(ch)) {\n\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\nstatic inline bool istspecial( char c ) \n{\n switch ( c ) {\n case '(':\n case ')':\n case '<':\n case '>':\n case '@':\n case ',':\n case ';':\n case ':':\n case '\\\\':\n case '\"':\n case '\/':\n case '[':\n case ']':\n case '?':\n case '=':\n return true;\n default:\n return false;\n }\n }\n\nDwRfc1521Tokenizer::DwRfc1521Tokenizer(const DwString& aStr)\n : DwTokenizer(aStr)\n{\n ParseToken();\n}\n\n\nDwRfc1521Tokenizer::DwRfc1521Tokenizer(const char* aCStr)\n : DwTokenizer(aCStr)\n{\n ParseToken();\n}\n\n\nDwRfc1521Tokenizer::~DwRfc1521Tokenizer()\n{\n}\n\n\nint DwRfc1521Tokenizer::Restart()\n{\n mNextStart = 0;\n ParseToken();\n return mTkType;\n}\n\n\nint DwRfc1521Tokenizer::operator ++ ()\n{\n ParseToken();\n return mTkType;\n}\n\n\nvoid DwRfc1521Tokenizer::ParseToken()\n{\n \/\/ Assume the field body has already been extracted. That is, we don't\n \/\/ have to watch for the end of the field body or folding. We just\n \/\/ treat any CRs or LFs as white space.\n mTokenStart = mNextStart;\n mTokenLength = 0;\n mTkType = eTkNull;\n if (mTokenStart >= mString.length()) {\n return;\n }\n \/\/ Skip leading space. Also, since control chars are not permitted\n \/\/ in atoms, skip these, too.\n while (1) {\n if (mTokenStart >= mString.length()) {\n return;\n }\n if (!isspace(mString[mTokenStart]) && !iscntrl(mString[mTokenStart]))\n break;\n ++mTokenStart;\n }\n char ch = mString[mTokenStart];\n \/\/ Quoted string\n if (ch == '\"') {\n mTkType = eTkQuotedString;\n ParseQuotedString();\n }\n \/\/ Comment\n else if (ch == '(') {\n mTkType = eTkComment;\n ParseComment();\n }\n \/\/ Domain literal\n else if (ch == '[') {\n mTkType = eTkDomainLiteral;\n ParseDomainLiteral();\n }\n \/\/ Special\n else if (istspecial(ch)) {\n mTkType = eTkTspecial;\n mTokenLength = 1;\n mToken = mString.substr(mTokenStart, 1);\n mNextStart = mTokenStart + 1;\n }\n \/\/ Atom\n else {\n mTkType = eTkToken;\n ParseAtom();\n }\n if (mDebugOut) PrintToken(mDebugOut);\n}\n\n\nvoid DwRfc1521Tokenizer::ParseAtom()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n char ch = (pos < mString.length()) ? mString[pos] : (char) 0;\n if (pos >= mString.length()\n || isspace(ch)\n || iscntrl(ch)\n || istspecial(ch)) {\n\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\n\nDwTokenString::DwTokenString(const DwString& aStr)\n : mString(aStr)\n{\n mTokensStart = 0;\n mTokensLength = 0;\n}\n\n\nDwTokenString::~DwTokenString()\n{\n}\n\n\nvoid DwTokenString::SetFirst(const DwTokenizer& aTkzr)\n{\n switch (aTkzr.Type()) {\n case eTkError:\n case eTkNull:\n mTokensStart = aTkzr.mTokenStart;\n mTokensLength = 0;\n break;\n case eTkComment:\n case eTkDomainLiteral:\n case eTkQuotedString:\n case eTkSpecial:\n case eTkAtom:\n case eTkTspecial:\n case eTkToken:\n mTokensStart = aTkzr.mTokenStart;\n mTokensLength = aTkzr.mTokenLength;\n break;\n }\n mTokens = mString.substr(mTokensStart, mTokensLength);\n}\n\n\nvoid DwTokenString::SetLast(const DwTokenizer& aTkzr)\n{\n assert(aTkzr.mTokenStart >= mTokensStart);\n if (aTkzr.mTokenStart < mTokensStart) return;\n mTokensLength = aTkzr.mTokenStart + aTkzr.mTokenLength - mTokensStart;\n mTokens = mString.substr(mTokensStart, mTokensLength);\n}\n\n\nvoid DwTokenString::ExtendTo(const DwTokenizer& aTkzr)\n{\n assert(aTkzr.mTokenStart >= mTokensStart);\n if (aTkzr.mTokenStart < mTokensStart) return;\n mTokensLength = aTkzr.mTokenStart - mTokensStart;\n mTokens = mString.substr(mTokensStart, mTokensLength);\n}\n5% faster kmail (or equivalently, 5% less cpu depending on how fast your chip is) by using table lookups instead of if() chains and function calls. Also eliminate redundant calls.\/\/=============================================================================\n\/\/ File: token.cpp\n\/\/ Contents: Definitions for DwTokenizer, DwRfc822Tokenizer\n\/\/ Maintainer: Doug Sauder \n\/\/ WWW: http:\/\/www.fwb.gulf.net\/~dwsauder\/mimepp.html\n\/\/ $Revision$\n\/\/ $Date$\n\/\/\n\/\/ Copyright (c) 1996, 1997 Douglas W. Sauder\n\/\/ All rights reserved.\n\/\/\n\/\/ IN NO EVENT SHALL DOUGLAS W. SAUDER BE LIABLE TO ANY PARTY FOR DIRECT,\n\/\/ INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF\n\/\/ THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF DOUGLAS W. SAUDER\n\/\/ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ DOUGLAS W. SAUDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT\n\/\/ NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\/\/ PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN \"AS IS\"\n\/\/ BASIS, AND DOUGLAS W. SAUDER HAS NO OBLIGATION TO PROVIDE MAINTENANCE,\n\/\/ SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\/\/\n\/\/=============================================================================\n\n#define DW_IMPLEMENTATION\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstd::ostream* DwTokenizer::mDebugOut = 0;\n\n\nDwTokenizer::DwTokenizer(const DwString& aStr)\n : mString(aStr)\n{\n mTokenStart = 0;\n mTokenLength = 0;\n mNextStart = 0;\n mTkType = eTkError;\n}\n\n\nDwTokenizer::DwTokenizer(const char* aCStr)\n : mString(aCStr)\n{\n mTokenStart = 0;\n mTokenLength = 0;\n mNextStart = 0;\n mTkType = eTkError;\n}\n\n\nDwTokenizer::~DwTokenizer()\n{\n}\n\n\nvoid DwTokenizer::StripDelimiters()\n{\n if (mTokenLength < 2) return;\n \/\/ const ref -- avoids copy on write when using operator[]\n const DwString& token = mToken;\n switch (mTkType) {\n case eTkQuotedString:\n if (token[0] == '\"') {\n mToken = mToken.substr(1);\n ++mTokenStart;\n --mTokenLength;\n }\n if (mTokenLength > 0 && token[mTokenLength-1] == '\"') {\n mToken = mToken.substr(0, mTokenLength-1);\n --mTokenLength;\n }\n break;\n case eTkDomainLiteral:\n if (token[0] == '[') {\n mToken = mToken.substr(1);\n ++mTokenStart;\n --mTokenLength;\n }\n if (mTokenLength > 0 && token[mTokenLength-1] == ']') {\n mToken = mToken.substr(0, mTokenLength-1);\n --mTokenLength;\n }\n break;\n case eTkComment:\n if (token[0] == '(') {\n mToken = mToken.substr(1);\n ++mTokenStart;\n --mTokenLength;\n }\n if (mTokenLength > 0 && token[mTokenLength-1] == ')') {\n mToken = mToken.substr(0, mTokenLength-1);\n --mTokenLength;\n }\n break;\n }\n}\n\n\nvoid DwTokenizer::ParseQuotedString()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n else if (mString[pos] == '\\\\') {\n \/\/ Quoted character\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n }\n else if (mString[pos] == '\"') {\n \/\/ End of quoted string\n ++pos;\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\n\nvoid DwTokenizer::ParseComment()\n{\n size_t pos = mTokenStart;\n int level = 1;\n while (1) {\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n else if (mString[pos] == '\\\\') {\n \/\/ Quoted character\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n }\n else if (mString[pos] == ')') {\n --level;\n if (level == 0) {\n \/\/ End of comment\n ++pos;\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n else if (mString[pos] == '(') {\n ++level;\n }\n }\n}\n\n\nvoid DwTokenizer::ParseDomainLiteral()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n else if (mString[pos] == '\\\\') {\n \/\/ Quoted character\n ++pos;\n if (pos >= mString.length()) {\n \/\/ Ran out of string\n mTokenLength = 0;\n mToken = \"\";\n mNextStart = pos;\n mTkType = eTkError;\n break;\n }\n }\n else if (mString[pos] == ']') {\n \/\/ End of domain literal\n ++pos;\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\n\nvoid DwTokenizer::PrintToken(std::ostream* aOut)\n{\n if (!aOut) return;\n const char* type = 0;\n switch (mTkType) {\n case eTkError:\n type = \"error \";\n break;\n case eTkNull:\n type = \"null \";\n break;\n case eTkSpecial:\n type = \"special \";\n break;\n case eTkAtom:\n type = \"atom \";\n break;\n case eTkComment:\n type = \"comment \";\n break;\n case eTkQuotedString:\n type = \"quoted string \";\n break;\n case eTkDomainLiteral:\n type = \"domain literal \";\n break;\n case eTkTspecial:\n type = \"tspecial \";\n break;\n case eTkToken:\n type = \"token \";\n break;\n default:\n type = \"unknown \";\n break;\n }\n *aOut << type << mToken << '\\n';\n}\n\n\nstatic inline bool isspecialorspaceorcntrl( char c ) \n{\n switch ( c ) {\n case '(':\n case ')':\n case '<':\n case '>':\n case '@':\n case ',':\n case ';':\n case ':':\n case '\\\\':\n case '\"':\n case '.':\n case '[':\n case ']':\n \/\/ isspace()\n case ' ':\n \/\/case '\\r': included in iscntrl()\n \/\/case '\\f': included in iscntrl()\n \/\/case '\\t': included in iscntrl()\n \/\/case '\\n': included in iscntrl()\n \/\/case '\\v': included in iscntrl()\n \/\/ iscntrl()\n case 0 ... 15:\n case 17 ... 31:\n return true;\n default:\n return false;\n }\n}\n\nstatic inline bool isnotspaceorcntrl( char c ) \n{\n switch ( c ) {\n \/\/ isspace()\n case ' ':\n \/\/case '\\r': included in iscntrl()\n \/\/case '\\f': included in iscntrl()\n \/\/case '\\t': included in iscntrl()\n \/\/case '\\n': included in iscntrl()\n \/\/case '\\v': included in iscntrl()\n \/\/ iscntrl()\n case 0 ... 15:\n case 17 ... 31:\n return false;\n default:\n return true;\n }\n}\n\nDwRfc822Tokenizer::DwRfc822Tokenizer(const DwString& aStr)\n : DwTokenizer(aStr)\n{\n ParseToken();\n}\n\n\nDwRfc822Tokenizer::DwRfc822Tokenizer(const char* aCStr)\n : DwTokenizer(aCStr)\n{\n ParseToken();\n}\n\n\nDwRfc822Tokenizer::~DwRfc822Tokenizer()\n{\n}\n\n\nint DwRfc822Tokenizer::Restart()\n{\n mNextStart = 0;\n ParseToken();\n return mTkType;\n}\n\n\nint DwRfc822Tokenizer::operator ++ ()\n{\n ParseToken();\n return mTkType;\n}\n\n\nvoid DwRfc822Tokenizer::ParseToken()\n{\n \/\/ Assume the field body has already been extracted. That is, we don't\n \/\/ have to watch for the end of the field body or folding. We just\n \/\/ treat any CRs or LFs as white space.\n mTokenStart = mNextStart;\n mTokenLength = 0;\n mTkType = eTkNull;\n \/\/ Skip leading space. Also, since control chars are not permitted\n \/\/ in atoms, skip these, too.\n while (1) {\n if (mTokenStart >= mString.length()) {\n return;\n }\n if (isnotspaceorcntrl(mString[mTokenStart]))\n break;\n ++mTokenStart;\n }\n char ch = mString[mTokenStart];\n switch (ch) {\n \/\/ Quoted string\n case '\"':\n mTkType = eTkQuotedString;\n ParseQuotedString();\n break;\n \/\/ Comment\n case '(':\n mTkType = eTkComment;\n ParseComment();\n break;\n \/\/ Domain literal\n case '[':\n mTkType = eTkDomainLiteral;\n ParseDomainLiteral();\n break;\n \/\/ Special\n case ')':\n case '<':\n case '>':\n case '@':\n case ',':\n case ';':\n case ':':\n case '\\\\':\n case '.':\n case ']':\n mTkType = eTkSpecial;\n mTokenLength = 1;\n mToken = mString.substr(mTokenStart, 1);\n mNextStart = mTokenStart + 1;\n break;\n default:\n mTkType = eTkAtom;\n ParseAtom();\n break;\n }\n if (mDebugOut) PrintToken(mDebugOut);\n}\n\n\nvoid DwRfc822Tokenizer::ParseAtom()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n char ch = (pos < mString.length()) ? mString[pos] : (char) 0;\n if (pos >= mString.length()\n || isspecialorspaceorcntrl(ch)) {\n\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\nstatic inline bool istspecialorspaceorcntrl( char c ) \n{\n switch ( c ) {\n case '(':\n case ')':\n case '<':\n case '>':\n case '@':\n case ',':\n case ';':\n case ':':\n case '\\\\':\n case '\"':\n case '\/':\n case '[':\n case ']':\n case '?':\n case '=':\n \/\/ isspace()\n case ' ':\n \/\/case '\\r': included in iscntrl()\n \/\/case '\\f': included in iscntrl()\n \/\/case '\\t': included in iscntrl()\n \/\/case '\\n': included in iscntrl()\n \/\/case '\\v': included in iscntrl()\n \/\/ iscntrl()\n case 0 ... 15:\n case 17 ... 31:\n return true;\n default:\n return false;\n }\n }\n\nDwRfc1521Tokenizer::DwRfc1521Tokenizer(const DwString& aStr)\n : DwTokenizer(aStr)\n{\n ParseToken();\n}\n\n\nDwRfc1521Tokenizer::DwRfc1521Tokenizer(const char* aCStr)\n : DwTokenizer(aCStr)\n{\n ParseToken();\n}\n\n\nDwRfc1521Tokenizer::~DwRfc1521Tokenizer()\n{\n}\n\n\nint DwRfc1521Tokenizer::Restart()\n{\n mNextStart = 0;\n ParseToken();\n return mTkType;\n}\n\n\nint DwRfc1521Tokenizer::operator ++ ()\n{\n ParseToken();\n return mTkType;\n}\n\n\nvoid DwRfc1521Tokenizer::ParseToken()\n{\n \/\/ Assume the field body has already been extracted. That is, we don't\n \/\/ have to watch for the end of the field body or folding. We just\n \/\/ treat any CRs or LFs as white space.\n mTokenStart = mNextStart;\n mTokenLength = 0;\n mTkType = eTkNull;\n \/\/ Skip leading space. Also, since control chars are not permitted\n \/\/ in atoms, skip these, too.\n while (1) {\n if (mTokenStart >= mString.length()) {\n return;\n }\n if (isnotspaceorcntrl(mString[mTokenStart]))\n break;\n ++mTokenStart;\n }\n char ch = mString[mTokenStart];\n switch (ch) {\n \/\/ Quoted string\n case '\"':\n mTkType = eTkQuotedString;\n ParseQuotedString();\n break;\n \/\/ Comment\n case '(':\n mTkType = eTkComment;\n ParseComment();\n break;\n \/\/ Domain literal\n case '[':\n mTkType = eTkDomainLiteral;\n ParseDomainLiteral();\n break;\n \/\/ Special\n case ')':\n case '<':\n case '>':\n case '@':\n case ',':\n case ';':\n case ':':\n case '\\\\':\n case '\/':\n case ']':\n case '?':\n case '=':\n mTkType = eTkTspecial;\n mTokenLength = 1;\n mToken = mString.substr(mTokenStart, 1);\n mNextStart = mTokenStart + 1;\n break;\n default:\n mTkType = eTkToken;\n ParseAtom();\n break;\n }\n if (mDebugOut) PrintToken(mDebugOut);\n}\n\n\nvoid DwRfc1521Tokenizer::ParseAtom()\n{\n size_t pos = mTokenStart;\n while (1) {\n ++pos;\n char ch = (pos < mString.length()) ? mString[pos] : (char) 0;\n if (pos >= mString.length()\n || istspecialorspaceorcntrl(ch)) {\n\n mTokenLength = pos - mTokenStart;\n mToken = mString.substr(mTokenStart, mTokenLength);\n mNextStart = pos;\n break;\n }\n }\n}\n\n\nDwTokenString::DwTokenString(const DwString& aStr)\n : mString(aStr)\n{\n mTokensStart = 0;\n mTokensLength = 0;\n}\n\n\nDwTokenString::~DwTokenString()\n{\n}\n\n\nvoid DwTokenString::SetFirst(const DwTokenizer& aTkzr)\n{\n switch (aTkzr.Type()) {\n case eTkError:\n case eTkNull:\n mTokensStart = aTkzr.mTokenStart;\n mTokensLength = 0;\n break;\n case eTkComment:\n case eTkDomainLiteral:\n case eTkQuotedString:\n case eTkSpecial:\n case eTkAtom:\n case eTkTspecial:\n case eTkToken:\n mTokensStart = aTkzr.mTokenStart;\n mTokensLength = aTkzr.mTokenLength;\n break;\n }\n mTokens = mString.substr(mTokensStart, mTokensLength);\n}\n\n\nvoid DwTokenString::SetLast(const DwTokenizer& aTkzr)\n{\n assert(aTkzr.mTokenStart >= mTokensStart);\n if (aTkzr.mTokenStart < mTokensStart) return;\n mTokensLength = aTkzr.mTokenStart + aTkzr.mTokenLength - mTokensStart;\n mTokens = mString.substr(mTokensStart, mTokensLength);\n}\n\n\nvoid DwTokenString::ExtendTo(const DwTokenizer& aTkzr)\n{\n assert(aTkzr.mTokenStart >= mTokensStart);\n if (aTkzr.mTokenStart < mTokensStart) return;\n mTokensLength = aTkzr.mTokenStart - mTokensStart;\n mTokens = mString.substr(mTokensStart, mTokensLength);\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \n\n#include \n\n#include \"blackhole\/config\/node.hpp\"\n#include \"blackhole\/config\/option.hpp\"\n\nnamespace blackhole {\nnamespace detail {\nnamespace config {\n\nusing blackhole::config::make_option;\nusing blackhole::config::node_t;\n\ntypedef blackhole::config::option option_t;\n\nclass type_mismatch : public std::logic_error {\n struct {\n std::string cursor;\n std::string expected;\n std::string actual;\n } data;\n\npublic:\n type_mismatch(std::string cursor, std::string expected, std::string actual) :\n std::logic_error(\"type mismatch at \\\"\" + cursor + \"\\\": \" +\n \"expected \\\"\" + expected + \"\\\", actual \\\"\" + actual + \"\\\"\")\n {\n data.cursor = std::move(cursor);\n data.expected = std::move(expected);\n data.actual = std::move(actual);\n }\n\n ~type_mismatch() throw() {}\n\n auto expected() const -> std::string {\n return data.expected;\n }\n\n auto actual() const -> std::string {\n return data.actual;\n }\n\n auto cursor() const -> std::string {\n return data.cursor;\n }\n};\n\n\/\/ TODO: Separate hpp\/cpp.\nclass json_t : public node_t {\n const rapidjson::Value& value;\n std::string cursor;\n\npublic:\n explicit json_t(const rapidjson::Value& value) :\n value(value)\n {}\n\n json_t(const rapidjson::Value& value, std::string cursor) :\n value(value),\n cursor(std::move(cursor))\n {}\n\n auto to_bool() const -> bool {\n if (value.IsBool()) {\n return value.GetBool();\n }\n\n type_mismatch(\"bool\");\n }\n\n auto to_sint64() const -> std::int64_t {\n if (value.IsInt64()) {\n return value.GetInt64();\n }\n\n type_mismatch(\"int64\");\n }\n\n auto to_uint64() const -> std::uint64_t {\n if (value.IsUint64()) {\n return value.GetUint64();\n }\n\n type_mismatch(\"uint64\");\n }\n\n auto to_double() const -> double {\n if (value.IsDouble()) {\n return value.GetDouble();\n }\n\n type_mismatch(\"double\");\n }\n\n auto to_string() const -> std::string {\n if (value.IsString()) {\n return value.GetString();\n }\n\n type_mismatch(\"string\");\n }\n\n auto each(const each_function& fn) -> void {\n if (!value.IsArray()) {\n type_mismatch(\"array\");\n }\n\n for (auto it = value.Begin(); it != value.End(); ++it) {\n fn(json_t(*it, advance(static_cast(std::distance(value.Begin(), it)))));\n }\n }\n\n auto each_map(const member_function& fn) -> void {\n if (!value.IsObject()) {\n type_mismatch(\"object\");\n }\n\n for (auto it = value.MemberBegin(); it != value.MemberEnd(); ++it) {\n fn(it->name.GetString(), json_t(it->value, advance(it->name.GetString())));\n }\n }\n\n auto operator[](const std::size_t& idx) const -> option_t {\n if (value.IsArray() && idx < value.Size()) {\n return make_option(value[static_cast(idx)], advance(idx));\n }\n\n return {};\n }\n\n auto operator[](const std::string& key) const -> option_t {\n if (value.IsObject() && value.HasMember(key.c_str())) {\n return make_option(value[key.c_str()], advance(key));\n }\n\n return {};\n }\n\nprivate:\n auto advance(const std::size_t& idx) const -> std::string {\n return cursor + \"\/\" + boost::lexical_cast(idx);\n }\n\n auto advance(const std::string& key) const -> std::string {\n return cursor + \"\/\" + key;\n }\n\n __attribute((noreturn)) auto type_mismatch(const std::string& expected) const -> void {\n throw config::type_mismatch(cursor.empty() ? \"\/\" : cursor, expected, type());\n }\n\n auto type() const -> std::string {\n switch (value.GetType()) {\n case rapidjson::kNullType:\n return \"null\";\n case rapidjson::kTrueType:\n case rapidjson::kFalseType:\n return \"bool\";\n case rapidjson::kNumberType:\n return \"number\";\n case rapidjson::kStringType:\n return \"string\";\n case rapidjson::kArrayType:\n return \"array\";\n case rapidjson::kObjectType:\n return \"object\";\n }\n }\n};\n\n} \/\/ namespace config\n} \/\/ namespace detail\n} \/\/ namespace blackhole\nfix(config\/json): upgrade specifiers#pragma once\n\n#include \n\n#include \n\n#include \n\n#include \"blackhole\/config\/node.hpp\"\n#include \"blackhole\/config\/option.hpp\"\n\nnamespace blackhole {\nnamespace detail {\nnamespace config {\n\nusing blackhole::config::make_option;\nusing blackhole::config::node_t;\n\ntypedef blackhole::config::option option_t;\n\nclass type_mismatch : public std::logic_error {\n struct {\n std::string cursor;\n std::string expected;\n std::string actual;\n } data;\n\npublic:\n type_mismatch(std::string cursor, std::string expected, std::string actual) :\n std::logic_error(\"type mismatch at \\\"\" + cursor + \"\\\": \" +\n \"expected \\\"\" + expected + \"\\\", actual \\\"\" + actual + \"\\\"\")\n {\n data.cursor = std::move(cursor);\n data.expected = std::move(expected);\n data.actual = std::move(actual);\n }\n\n type_mismatch(const type_mismatch& other) = default;\n type_mismatch(type_mismatch&& other) = default;\n\n ~type_mismatch() noexcept {}\n\n auto expected() const -> std::string {\n return data.expected;\n }\n\n auto actual() const -> std::string {\n return data.actual;\n }\n\n auto cursor() const -> std::string {\n return data.cursor;\n }\n};\n\nclass json_t : public node_t {\n const rapidjson::Value& value;\n std::string cursor;\n\npublic:\n explicit json_t(const rapidjson::Value& value) :\n value(value)\n {}\n\n json_t(const rapidjson::Value& value, std::string cursor) :\n value(value),\n cursor(std::move(cursor))\n {}\n\n auto to_bool() const -> bool {\n if (value.IsBool()) {\n return value.GetBool();\n }\n\n type_mismatch(\"bool\");\n }\n\n auto to_sint64() const -> std::int64_t {\n if (value.IsInt64()) {\n return value.GetInt64();\n }\n\n type_mismatch(\"int64\");\n }\n\n auto to_uint64() const -> std::uint64_t {\n if (value.IsUint64()) {\n return value.GetUint64();\n }\n\n type_mismatch(\"uint64\");\n }\n\n auto to_double() const -> double {\n if (value.IsDouble()) {\n return value.GetDouble();\n }\n\n type_mismatch(\"double\");\n }\n\n auto to_string() const -> std::string {\n if (value.IsString()) {\n return value.GetString();\n }\n\n type_mismatch(\"string\");\n }\n\n auto each(const each_function& fn) -> void {\n if (!value.IsArray()) {\n type_mismatch(\"array\");\n }\n\n for (auto it = value.Begin(); it != value.End(); ++it) {\n fn(json_t(*it, advance(static_cast(std::distance(value.Begin(), it)))));\n }\n }\n\n auto each_map(const member_function& fn) -> void {\n if (!value.IsObject()) {\n type_mismatch(\"object\");\n }\n\n for (auto it = value.MemberBegin(); it != value.MemberEnd(); ++it) {\n fn(it->name.GetString(), json_t(it->value, advance(it->name.GetString())));\n }\n }\n\n auto operator[](const std::size_t& idx) const -> option_t {\n if (value.IsArray() && idx < value.Size()) {\n return make_option(value[static_cast(idx)], advance(idx));\n }\n\n return {};\n }\n\n auto operator[](const std::string& key) const -> option_t {\n if (value.IsObject() && value.HasMember(key.c_str())) {\n return make_option(value[key.c_str()], advance(key));\n }\n\n return {};\n }\n\nprivate:\n auto advance(const std::size_t& idx) const -> std::string {\n return cursor + \"\/\" + boost::lexical_cast(idx);\n }\n\n auto advance(const std::string& key) const -> std::string {\n return cursor + \"\/\" + key;\n }\n\n __attribute((noreturn)) auto type_mismatch(const std::string& expected) const -> void {\n throw config::type_mismatch(cursor.empty() ? \"\/\" : cursor, expected, type());\n }\n\n auto type() const -> std::string {\n switch (value.GetType()) {\n case rapidjson::kNullType:\n return \"null\";\n case rapidjson::kTrueType:\n case rapidjson::kFalseType:\n return \"bool\";\n case rapidjson::kNumberType:\n return \"number\";\n case rapidjson::kStringType:\n return \"string\";\n case rapidjson::kArrayType:\n return \"array\";\n case rapidjson::kObjectType:\n return \"object\";\n }\n }\n};\n\n} \/\/ namespace config\n} \/\/ namespace detail\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"\/\/\n\/\/ ScrollView.cpp\n\/\/ moFlo\n\/\/\n\/\/ Created by Scott Downie on 27\/04\/2011.\n\/\/ Copyright 2011 Tag Games. All rights reserved.\n\/\/\n\n#include \n\n#include \n#include \n\n#if CS_ENABLE_DEBUGDRAWING\n#include \n#include \n#endif\n\nnamespace ChilliSource\n{\n namespace GUI\n {\n\t\tDEFINE_META_CLASS(ScrollView)\n\n\t\tDEFINE_PROPERTY(ScrollHorizontally);\n\t\tDEFINE_PROPERTY(ScrollVertically);\n\n const f32 kfScrollDeceleration = 0.9f;\n \n \/\/--------------------------------------------\n \/\/\/ Constructor\n \/\/\/\n \/\/\/ Default\n \/\/--------------------------------------------\n ScrollView::ScrollView() \n\t\t: ScrollHorizontally(true), ScrollVertically(true), mpContainerView(new GUIView), mbTouchMoved(false), mbTouchActive(false), mfTouchTravel(0.0f),mbDrawDebug(false)\n {\n \/\/A scroll view that doesn't clip is useless\n EnableSubviewClipping(true);\n \n \/\/Lets give the scroll view an empty container that we can check bounds against\n \/\/this container will expand to hold all it's children\n mpContainerView->SetSize(1.0f, 1.0f, 0.0f, 0.0f);\n mpContainerView->SetLocalAlignment(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableAlignmentToParent(true);\n mpContainerView->SetAlignmentToParent(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableTouchConsumption(false);\n GUIView::AddSubview(mpContainerView);\n }\n \/\/--------------------------------------------\n \/\/\/ Constructor\n \/\/\/\n \/\/\/ From param dictionary\n \/\/--------------------------------------------\n ScrollView::ScrollView(const Core::ParamDictionary& insParams) \n\t\t: GUIView(insParams), ScrollHorizontally(true), ScrollVertically(true), mpContainerView(new GUIView), mbTouchMoved(false), mbTouchActive(false), mfTouchTravel(0.0f),mbDrawDebug(false)\n {\n \/\/A scroll view that doesn't clip is useless\n EnableSubviewClipping(true);\n \n std::string strValue;\n \n \/\/---Enable Horizontal scrolling\n if(insParams.TryGetValue(\"ScrollHorizontally\", strValue))\n {\n ScrollHorizontally = Core::ParseBool(strValue);\n }\n \/\/---Enable Vertical scrolling\n if(insParams.TryGetValue(\"ScrollVertically\", strValue))\n {\n ScrollVertically = Core::ParseBool(strValue);\n }\n \n \/\/Lets give the scroll view an empty container that we can check bounds against\n \/\/this container will expand to hold all it's children\n mpContainerView->SetSize(1.0f, 1.0f, 0.0f, 0.0f);\n mpContainerView->SetLocalAlignment(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableAlignmentToParent(true);\n mpContainerView->SetAlignmentToParent(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableTouchConsumption(false);\n GUIView::AddSubview(mpContainerView);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Add Subview\n \/\/\/\n \/\/\/ Add a view to the hierarchy\n \/\/\/\n \/\/\/ @param GUIView shared pointer\n \/\/-----------------------------------------------------\n void ScrollView::AddSubview(const GUIViewSPtr& inpSubview)\n {\n mpContainerView->AddSubview(inpSubview);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Remove Subview (Internal)\n \/\/\/\n \/\/\/ Remove a view from our hierarchy\n \/\/\/\n \/\/\/ @param GUIView pointer\n \/\/-----------------------------------------------------\n void ScrollView::RemoveSubview(GUIView* inpSubview)\n {\n mpContainerView->RemoveSubview(inpSubview);\n }\n \/\/-----------------------------------------------------------\n \/\/\/ Enable Horizontal Scrolling\n \/\/\/\n \/\/\/ @param Whether the scroll view allows sideways scrolling\n \/\/-----------------------------------------------------------\n void ScrollView::EnableHorizontalScrolling(bool inbEnabled)\n {\n ScrollHorizontally = inbEnabled;\n }\n \/\/-----------------------------------------------------------\n \/\/\/ Enable Vertical Scrolling\n \/\/\/\n \/\/\/ @param Whether the scroll view allows vertical scrolling\n \/\/-----------------------------------------------------------\n void ScrollView::EnableVerticalScrolling(bool inbEnabled)\n {\n ScrollVertically = inbEnabled;\n }\n\t\t\/\/-----------------------------------------------------------\n\t\t\/\/\/ Is Horizontal Scrolling Enabled\n\t\t\/\/\/\n\t\t\/\/\/ @return Whether the scroll view allows sideways scrolling\n\t\t\/\/-----------------------------------------------------------\n\t\tbool ScrollView::IsHorizontalScrollingEnabled() const\n\t\t{\n\t\t\treturn ScrollHorizontally;\n\t\t}\n\t\t\/\/-----------------------------------------------------------\n\t\t\/\/\/ Is Vertical Scrolling Enabled\n\t\t\/\/\/\n\t\t\/\/\/ @return Whether the scroll view allows vertical scrolling\n\t\t\/\/-----------------------------------------------------------\n\t\tbool ScrollView::IsVerticalScrollingEnabled() const\n\t\t{\n\t\t\treturn ScrollVertically;\n\t\t}\n \/\/-----------------------------------------------------\n \/\/\/ Update\n \/\/\/\n \/\/\/ @param Time between frames\n \/\/-----------------------------------------------------\n void ScrollView::Update(f32 infDt)\n {\n if(Visible)\n {\n \/\/Check if the container exceeds the bounds of the scroll view\n\t\t\t\t\/\/Get edge positions\n\t\t\t\tCore::Vector2 vTopLeft = GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft);\n\t\t\t\tCore::Vector2 vBottomRight = GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight);\n\t\t\t\t\n\t\t\t\t\/\/We don't want the scrollable items to fly into oblivion we must cap them.\n\t\t\t\t\/\/The objects can only move in a direction until the furthest object in that direction is within the scroll view\n\t\t\t\t\/\/at this point we \"bounce\" the objects.\n\t\t\t\t\n\t\t\t\tCore::Vector2 vNewLeftPosition = mvVelocity + mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft);\n\t\t\t\tCore::Vector2 vNewRightPosition = mvVelocity + mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight);\n\t\t\t\t\n\t\t\t\tCore::Vector2 vSizeOfContainer = mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topRight) - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomLeft);\n\t\t\t\t\n\t\t\t\tif(vSizeOfContainer.x > vBottomRight.x - vTopLeft.x)\n\t\t\t\t{\n\t\t\t\t\t\/\/ AM: Make sure we're not going to fly past the left edge\n\t\t\t\t\tif(vNewLeftPosition.x >= vTopLeft.x)\n\t\t\t\t\t{\n\t\t\t\t\t\tmvVelocity.x = vTopLeft.x - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft).x;\n\t\t\t\t\t}\n \/\/ AM: Make sure we're not going to fly past the right edge\n\t\t\t\t\telse if(vNewRightPosition.x <= vBottomRight.x)\n {\n mvVelocity.x = vBottomRight.x - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight).x;\n } \n\t\t\t\t}\n\t\t\t\telse\n {\n\t\t\t\t\tmvVelocity.x = 0;\n }\n\t\t\t\t\n\t\t\t\tif(vSizeOfContainer.y > vTopLeft.y - vBottomRight.y)\n\t\t\t\t{\n\t\t\t\t\t\/\/ AM: Make sure we're not going to fly past the top edge\n\t\t\t\t\tif(vNewLeftPosition.y <= vTopLeft.y)\n\t\t\t\t\t{\n\t\t\t\t\t\tmvVelocity.y = vTopLeft.y - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft).y;\n\t\t\t\t\t}\n \/\/ AM: Make sure we're not going to fly past the bottom edge\n\t\t\t\t\telse if(vNewRightPosition.y >= vBottomRight.y)\n {\n mvVelocity.y = vBottomRight.y - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight).y;\n }\n\t\t\t\t}\n\t\t\t\telse\n {\n\t\t\t\t\tmvVelocity.y = 0;\n\t\t\t\t}\n \n mpContainerView->MoveBy(0.0f, 0.0f, mvVelocity.x, mvVelocity.y);\n\t\t\t\t\/\/Decelaration\n\t\t\t\tif(mbTouchActive && !mbTouchMoved)\n\t\t\t\t{\n\t\t\t\t\tmvVelocity = Core::Vector2::k_zero;\n\t\t\t\t}\n\t\t\t\telse if(!mbTouchActive)\n\t\t\t\t{\n\t\t\t\t\tmvVelocity *= kfScrollDeceleration;\n\t\t\t\t}\n\t\t\t\tif(mbTouchMoved)\n\t\t\t\t{\n\t\t\t\t\tmvRealPreviousTouchPosition = mvNextRealPreviousTouchPosition;\n\t\t\t\t\tmbTouchMoved = false;\n\t\t\t\t}\n\t\t\t\t\n GUIView::Update(infDt);\n\t\t\t}\n }\n \/\/-----------------------------------------------------\n \/\/\/ Reset\n \/\/\/\n \/\/\/ Resets the scroller back to the default\n \/\/-----------------------------------------------------\n void ScrollView::Reset()\n {\n mvVelocity = Core::Vector2::k_zero;\n mpContainerView->SetOffsetFromParentAlignment(Core::UnifiedVector2(Core::Vector2::k_zero, Core::Vector2::k_zero));\n }\n \/\/-----------------------------------------------------\n \/\/\/ Jump To\n \/\/\/\n \/\/\/ Jumps to the given position\n \/\/\/\n \/\/\/ @param The new position\n \/\/-----------------------------------------------------\n void ScrollView::JumpTo(const Core::UnifiedVector2& inuvPosition)\n {\n Reset();\n Core::Vector2 vAbsPos = inuvPosition.GetAbsolute() + (inuvPosition.GetRelative()*mpContainerView->GetAbsoluteSize());\n mpContainerView->MoveBy(0.0f, 0.0f, vAbsPos.x, vAbsPos.y);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Set Absolute Content Size\n \/\/\/\n \/\/\/ @param Content size\n \/\/-----------------------------------------------------\n void ScrollView::SetAbsoluteContentSize(const Core::Vector2& invSize)\n {\n mpContainerView->SetSize(0.0f, 0.0f, invSize.x, invSize.y);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Get Absolute Content Size\n \/\/\/\n \/\/\/ @return Content size\n \/\/-----------------------------------------------------\n Core::Vector2 ScrollView::GetAbsoluteContentSize() const\n {\n if(!mpContainerView)\n return Core::Vector2::k_zero;\n return mpContainerView->GetAbsoluteSize();\n }\n \/\/-----------------------------------------------------------\n \/\/\/ Get Absolute Content Position\n \/\/\/\n \/\/\/ @return The current absolute position of the content\n \/\/\/ from the top left corner of the scroll view\n \/\/-----------------------------------------------------------\n Core::Vector2 ScrollView::GetAbsoluteContentPosition() const\n {\n if(!mpContainerView)\n return Core::Vector2::k_zero;\n return mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft) - GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Set Velocity\n \/\/\/\n \/\/\/ @param Velocity\n \/\/-----------------------------------------------------\n void ScrollView::SetVelocity(const Core::Vector2& invVelocity)\n {\n mvVelocity = invVelocity;\n }\n \/\/-----------------------------------------------------------\n \/\/-----------------------------------------------------------\n bool ScrollView::OnPointerDown(const Input::PointerSystem::Pointer& in_pointer, f64 in_timestamp, Input::PointerSystem::InputType in_inputType)\n {\n if(UserInteraction && Visible)\n {\n\t\t\t\tmbTouchActive = true;\n\t\t\t\tmvRealPreviousTouchPosition = in_pointer.m_location;\n\t\t\t\t\n \/\/Stop! Hammer time...\n mvVelocity = Core::Vector2::k_zero; \n\t\t\t\tmfTouchTravel = 0.0f;\n }\n \n return GUIView::OnPointerDown(in_pointer, in_timestamp, in_inputType);\n }\n \/\/-----------------------------------------------------------\n \/\/-----------------------------------------------------------\n bool ScrollView::OnPointerMoved(const Input::PointerSystem::Pointer& in_pointer, f64 in_timestamp)\n {\n if(UserInteraction && Visible && mbTouchActive && Contains(in_pointer.m_location))\n {\n \/\/Calculate the displacement\n mvVelocity = in_pointer.m_location - mvRealPreviousTouchPosition;\n\t\t\t\tmfTouchTravel += mvVelocity.LengthSquared();\n\t\t\t\t\n if(!ScrollHorizontally)\n {\n mvVelocity.x = 0.0f;\n }\n if(!ScrollVertically)\n {\n mvVelocity.y = 0.0f;\n }\n\t\t\t\t\n\t\t\t\tmvNextRealPreviousTouchPosition = in_pointer.m_location;\n\t\t\t\tmbTouchMoved = true;\n\t\t\t\t\n\t\t\t\tGUIView::OnPointerMoved(in_pointer, in_timestamp);\n }\n \n return false;\n }\n\t\t\/\/-----------------------------------------------------------\n \/\/-----------------------------------------------------------\n void ScrollView::OnPointerUp(const Input::PointerSystem::Pointer& in_pointer, f64 in_timestamp, Input::PointerSystem::InputType in_inputType)\n {\n\t\t\tif(UserInteraction && Visible)\n\t\t\t{\n\t\t\t\tmbTouchActive = false;\n\t\t\t}\n\n GUIView::OnPointerUp(in_pointer, in_timestamp, in_inputType);\n }\n \/\/-------------------------------------------------------\n \/\/\/ Draw\n \/\/\/\n \/\/\/ Draw all our subviews in neat rows and columns. Each\n \/\/\/ cell is based on the size of the largest content\n \/\/\/\n \/\/\/ @param Canvas renderer pointer\n \/\/-------------------------------------------------------\n void ScrollView::Draw(Rendering::CanvasRenderer* inpCanvas)\n {\n#if CS_ENABLE_DEBUGDRAWING\n if(mbDrawDebug)\n {\n Rendering::TextureManager* pMgr = (Rendering::TextureManager*)(Core::ResourceManagerDispenser::GetSingletonPtr()->GetResourceManagerForType(Rendering::Texture::InterfaceID));\n inpCanvas->DrawBox(GetTransform(), GetAbsoluteSize(), pMgr->GetDefaultTexture(), Core::Rectangle(Core::Vector2::k_zero, Core::Vector2::k_zero), Core::Colour(1.0f,0.0f,0.0f,0.5f));\n }\n#endif\n \n GUIView::Draw(inpCanvas);\n }\n\t\t\/\/-------------------------------------------------------\n\t\t\/\/\/ Sets Debug Drawing\n\t\t\/\/\/\n\t\t\/\/\/ Enables\/Disables debug drawing\n\t\t\/\/\/\n\t\t\/\/\/ @param New value for this flag. DEBUG_DRAWING must be\n\t\t\/\/\/ set to TRUE\n\t\t\/\/-------------------------------------------------------\n\t\tvoid ScrollView::EnableDebugDrawing(bool inbValue)\n\t\t{\n#if CS_ENABLE_DEBUGDRAWING\n\t\t\tmbDrawDebug = inbValue;\n#else\n\t\t\tmbDrawDebug = false;\n#endif\n\t\t}\n \/\/-----------------------------------------------------------\n \/\/\/ Get Container View\n \/\/\/\n \/\/\/ @return The GUIView that contains all scrollable subviews\n \/\/\/ within the scroll view.\n \/\/-----------------------------------------------------------\n const GUIViewSPtr& ScrollView::GetContainerView() const\n {\n return mpContainerView;\n }\n }\n}\nScroll view fix for move not accepting touches outside of bounds\/\/\n\/\/ ScrollView.cpp\n\/\/ moFlo\n\/\/\n\/\/ Created by Scott Downie on 27\/04\/2011.\n\/\/ Copyright 2011 Tag Games. All rights reserved.\n\/\/\n\n#include \n\n#include \n#include \n\n#if CS_ENABLE_DEBUGDRAWING\n#include \n#include \n#endif\n\nnamespace ChilliSource\n{\n namespace GUI\n {\n\t\tDEFINE_META_CLASS(ScrollView)\n\n\t\tDEFINE_PROPERTY(ScrollHorizontally);\n\t\tDEFINE_PROPERTY(ScrollVertically);\n\n const f32 kfScrollDeceleration = 0.9f;\n \n \/\/--------------------------------------------\n \/\/\/ Constructor\n \/\/\/\n \/\/\/ Default\n \/\/--------------------------------------------\n ScrollView::ScrollView() \n\t\t: ScrollHorizontally(true), ScrollVertically(true), mpContainerView(new GUIView), mbTouchMoved(false), mbTouchActive(false), mfTouchTravel(0.0f),mbDrawDebug(false)\n {\n \/\/A scroll view that doesn't clip is useless\n EnableSubviewClipping(true);\n \n \/\/Lets give the scroll view an empty container that we can check bounds against\n \/\/this container will expand to hold all it's children\n mpContainerView->SetSize(1.0f, 1.0f, 0.0f, 0.0f);\n mpContainerView->SetLocalAlignment(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableAlignmentToParent(true);\n mpContainerView->SetAlignmentToParent(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableTouchConsumption(false);\n GUIView::AddSubview(mpContainerView);\n }\n \/\/--------------------------------------------\n \/\/\/ Constructor\n \/\/\/\n \/\/\/ From param dictionary\n \/\/--------------------------------------------\n ScrollView::ScrollView(const Core::ParamDictionary& insParams) \n\t\t: GUIView(insParams), ScrollHorizontally(true), ScrollVertically(true), mpContainerView(new GUIView), mbTouchMoved(false), mbTouchActive(false), mfTouchTravel(0.0f),mbDrawDebug(false)\n {\n \/\/A scroll view that doesn't clip is useless\n EnableSubviewClipping(true);\n \n std::string strValue;\n \n \/\/---Enable Horizontal scrolling\n if(insParams.TryGetValue(\"ScrollHorizontally\", strValue))\n {\n ScrollHorizontally = Core::ParseBool(strValue);\n }\n \/\/---Enable Vertical scrolling\n if(insParams.TryGetValue(\"ScrollVertically\", strValue))\n {\n ScrollVertically = Core::ParseBool(strValue);\n }\n \n \/\/Lets give the scroll view an empty container that we can check bounds against\n \/\/this container will expand to hold all it's children\n mpContainerView->SetSize(1.0f, 1.0f, 0.0f, 0.0f);\n mpContainerView->SetLocalAlignment(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableAlignmentToParent(true);\n mpContainerView->SetAlignmentToParent(Rendering::AlignmentAnchor::k_topLeft);\n mpContainerView->EnableTouchConsumption(false);\n GUIView::AddSubview(mpContainerView);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Add Subview\n \/\/\/\n \/\/\/ Add a view to the hierarchy\n \/\/\/\n \/\/\/ @param GUIView shared pointer\n \/\/-----------------------------------------------------\n void ScrollView::AddSubview(const GUIViewSPtr& inpSubview)\n {\n mpContainerView->AddSubview(inpSubview);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Remove Subview (Internal)\n \/\/\/\n \/\/\/ Remove a view from our hierarchy\n \/\/\/\n \/\/\/ @param GUIView pointer\n \/\/-----------------------------------------------------\n void ScrollView::RemoveSubview(GUIView* inpSubview)\n {\n mpContainerView->RemoveSubview(inpSubview);\n }\n \/\/-----------------------------------------------------------\n \/\/\/ Enable Horizontal Scrolling\n \/\/\/\n \/\/\/ @param Whether the scroll view allows sideways scrolling\n \/\/-----------------------------------------------------------\n void ScrollView::EnableHorizontalScrolling(bool inbEnabled)\n {\n ScrollHorizontally = inbEnabled;\n }\n \/\/-----------------------------------------------------------\n \/\/\/ Enable Vertical Scrolling\n \/\/\/\n \/\/\/ @param Whether the scroll view allows vertical scrolling\n \/\/-----------------------------------------------------------\n void ScrollView::EnableVerticalScrolling(bool inbEnabled)\n {\n ScrollVertically = inbEnabled;\n }\n\t\t\/\/-----------------------------------------------------------\n\t\t\/\/\/ Is Horizontal Scrolling Enabled\n\t\t\/\/\/\n\t\t\/\/\/ @return Whether the scroll view allows sideways scrolling\n\t\t\/\/-----------------------------------------------------------\n\t\tbool ScrollView::IsHorizontalScrollingEnabled() const\n\t\t{\n\t\t\treturn ScrollHorizontally;\n\t\t}\n\t\t\/\/-----------------------------------------------------------\n\t\t\/\/\/ Is Vertical Scrolling Enabled\n\t\t\/\/\/\n\t\t\/\/\/ @return Whether the scroll view allows vertical scrolling\n\t\t\/\/-----------------------------------------------------------\n\t\tbool ScrollView::IsVerticalScrollingEnabled() const\n\t\t{\n\t\t\treturn ScrollVertically;\n\t\t}\n \/\/-----------------------------------------------------\n \/\/\/ Update\n \/\/\/\n \/\/\/ @param Time between frames\n \/\/-----------------------------------------------------\n void ScrollView::Update(f32 infDt)\n {\n if(Visible)\n {\n \/\/Check if the container exceeds the bounds of the scroll view\n\t\t\t\t\/\/Get edge positions\n\t\t\t\tCore::Vector2 vTopLeft = GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft);\n\t\t\t\tCore::Vector2 vBottomRight = GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight);\n\t\t\t\t\n\t\t\t\t\/\/We don't want the scrollable items to fly into oblivion we must cap them.\n\t\t\t\t\/\/The objects can only move in a direction until the furthest object in that direction is within the scroll view\n\t\t\t\t\/\/at this point we \"bounce\" the objects.\n\t\t\t\t\n\t\t\t\tCore::Vector2 vNewLeftPosition = mvVelocity + mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft);\n\t\t\t\tCore::Vector2 vNewRightPosition = mvVelocity + mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight);\n\t\t\t\t\n\t\t\t\tCore::Vector2 vSizeOfContainer = mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topRight) - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomLeft);\n\t\t\t\t\n\t\t\t\tif(vSizeOfContainer.x > vBottomRight.x - vTopLeft.x)\n\t\t\t\t{\n\t\t\t\t\t\/\/ AM: Make sure we're not going to fly past the left edge\n\t\t\t\t\tif(vNewLeftPosition.x >= vTopLeft.x)\n\t\t\t\t\t{\n\t\t\t\t\t\tmvVelocity.x = vTopLeft.x - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft).x;\n\t\t\t\t\t}\n \/\/ AM: Make sure we're not going to fly past the right edge\n\t\t\t\t\telse if(vNewRightPosition.x <= vBottomRight.x)\n {\n mvVelocity.x = vBottomRight.x - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight).x;\n } \n\t\t\t\t}\n\t\t\t\telse\n {\n\t\t\t\t\tmvVelocity.x = 0;\n }\n\t\t\t\t\n\t\t\t\tif(vSizeOfContainer.y > vTopLeft.y - vBottomRight.y)\n\t\t\t\t{\n\t\t\t\t\t\/\/ AM: Make sure we're not going to fly past the top edge\n\t\t\t\t\tif(vNewLeftPosition.y <= vTopLeft.y)\n\t\t\t\t\t{\n\t\t\t\t\t\tmvVelocity.y = vTopLeft.y - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft).y;\n\t\t\t\t\t}\n \/\/ AM: Make sure we're not going to fly past the bottom edge\n\t\t\t\t\telse if(vNewRightPosition.y >= vBottomRight.y)\n {\n mvVelocity.y = vBottomRight.y - mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_bottomRight).y;\n }\n\t\t\t\t}\n\t\t\t\telse\n {\n\t\t\t\t\tmvVelocity.y = 0;\n\t\t\t\t}\n \n mpContainerView->MoveBy(0.0f, 0.0f, mvVelocity.x, mvVelocity.y);\n\t\t\t\t\/\/Decelaration\n\t\t\t\tif(mbTouchActive && !mbTouchMoved)\n\t\t\t\t{\n\t\t\t\t\tmvVelocity = Core::Vector2::k_zero;\n\t\t\t\t}\n\t\t\t\telse if(!mbTouchActive)\n\t\t\t\t{\n\t\t\t\t\tmvVelocity *= kfScrollDeceleration;\n\t\t\t\t}\n\t\t\t\tif(mbTouchMoved)\n\t\t\t\t{\n\t\t\t\t\tmvRealPreviousTouchPosition = mvNextRealPreviousTouchPosition;\n\t\t\t\t\tmbTouchMoved = false;\n\t\t\t\t}\n\t\t\t\t\n GUIView::Update(infDt);\n\t\t\t}\n }\n \/\/-----------------------------------------------------\n \/\/\/ Reset\n \/\/\/\n \/\/\/ Resets the scroller back to the default\n \/\/-----------------------------------------------------\n void ScrollView::Reset()\n {\n mvVelocity = Core::Vector2::k_zero;\n mpContainerView->SetOffsetFromParentAlignment(Core::UnifiedVector2(Core::Vector2::k_zero, Core::Vector2::k_zero));\n }\n \/\/-----------------------------------------------------\n \/\/\/ Jump To\n \/\/\/\n \/\/\/ Jumps to the given position\n \/\/\/\n \/\/\/ @param The new position\n \/\/-----------------------------------------------------\n void ScrollView::JumpTo(const Core::UnifiedVector2& inuvPosition)\n {\n Reset();\n Core::Vector2 vAbsPos = inuvPosition.GetAbsolute() + (inuvPosition.GetRelative()*mpContainerView->GetAbsoluteSize());\n mpContainerView->MoveBy(0.0f, 0.0f, vAbsPos.x, vAbsPos.y);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Set Absolute Content Size\n \/\/\/\n \/\/\/ @param Content size\n \/\/-----------------------------------------------------\n void ScrollView::SetAbsoluteContentSize(const Core::Vector2& invSize)\n {\n mpContainerView->SetSize(0.0f, 0.0f, invSize.x, invSize.y);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Get Absolute Content Size\n \/\/\/\n \/\/\/ @return Content size\n \/\/-----------------------------------------------------\n Core::Vector2 ScrollView::GetAbsoluteContentSize() const\n {\n if(!mpContainerView)\n return Core::Vector2::k_zero;\n return mpContainerView->GetAbsoluteSize();\n }\n \/\/-----------------------------------------------------------\n \/\/\/ Get Absolute Content Position\n \/\/\/\n \/\/\/ @return The current absolute position of the content\n \/\/\/ from the top left corner of the scroll view\n \/\/-----------------------------------------------------------\n Core::Vector2 ScrollView::GetAbsoluteContentPosition() const\n {\n if(!mpContainerView)\n return Core::Vector2::k_zero;\n return mpContainerView->GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft) - GetAbsoluteScreenSpaceAnchorPoint(Rendering::AlignmentAnchor::k_topLeft);\n }\n \/\/-----------------------------------------------------\n \/\/\/ Set Velocity\n \/\/\/\n \/\/\/ @param Velocity\n \/\/-----------------------------------------------------\n void ScrollView::SetVelocity(const Core::Vector2& invVelocity)\n {\n mvVelocity = invVelocity;\n }\n \/\/-----------------------------------------------------------\n \/\/-----------------------------------------------------------\n bool ScrollView::OnPointerDown(const Input::PointerSystem::Pointer& in_pointer, f64 in_timestamp, Input::PointerSystem::InputType in_inputType)\n {\n if(UserInteraction && Visible)\n {\n\t\t\t\tmbTouchActive = true;\n\t\t\t\tmvRealPreviousTouchPosition = in_pointer.m_location;\n\t\t\t\t\n \/\/Stop! Hammer time...\n mvVelocity = Core::Vector2::k_zero; \n\t\t\t\tmfTouchTravel = 0.0f;\n }\n \n return GUIView::OnPointerDown(in_pointer, in_timestamp, in_inputType);\n }\n \/\/-----------------------------------------------------------\n \/\/-----------------------------------------------------------\n bool ScrollView::OnPointerMoved(const Input::PointerSystem::Pointer& in_pointer, f64 in_timestamp)\n {\n if(UserInteraction && Visible && mbTouchActive && (Contains(in_pointer.m_location) == true || IsAcceptTouchesOutsideOfBoundsEnabled() == true))\n {\n \/\/Calculate the displacement\n mvVelocity = in_pointer.m_location - mvRealPreviousTouchPosition;\n\t\t\t\tmfTouchTravel += mvVelocity.LengthSquared();\n\t\t\t\t\n if(!ScrollHorizontally)\n {\n mvVelocity.x = 0.0f;\n }\n if(!ScrollVertically)\n {\n mvVelocity.y = 0.0f;\n }\n\t\t\t\t\n\t\t\t\tmvNextRealPreviousTouchPosition = in_pointer.m_location;\n\t\t\t\tmbTouchMoved = true;\n\t\t\t\t\n\t\t\t\tGUIView::OnPointerMoved(in_pointer, in_timestamp);\n }\n \n return false;\n }\n\t\t\/\/-----------------------------------------------------------\n \/\/-----------------------------------------------------------\n void ScrollView::OnPointerUp(const Input::PointerSystem::Pointer& in_pointer, f64 in_timestamp, Input::PointerSystem::InputType in_inputType)\n {\n\t\t\tif(UserInteraction && Visible)\n\t\t\t{\n\t\t\t\tmbTouchActive = false;\n\t\t\t}\n\n GUIView::OnPointerUp(in_pointer, in_timestamp, in_inputType);\n }\n \/\/-------------------------------------------------------\n \/\/\/ Draw\n \/\/\/\n \/\/\/ Draw all our subviews in neat rows and columns. Each\n \/\/\/ cell is based on the size of the largest content\n \/\/\/\n \/\/\/ @param Canvas renderer pointer\n \/\/-------------------------------------------------------\n void ScrollView::Draw(Rendering::CanvasRenderer* inpCanvas)\n {\n#if CS_ENABLE_DEBUGDRAWING\n if(mbDrawDebug)\n {\n Rendering::TextureManager* pMgr = (Rendering::TextureManager*)(Core::ResourceManagerDispenser::GetSingletonPtr()->GetResourceManagerForType(Rendering::Texture::InterfaceID));\n inpCanvas->DrawBox(GetTransform(), GetAbsoluteSize(), pMgr->GetDefaultTexture(), Core::Rectangle(Core::Vector2::k_zero, Core::Vector2::k_zero), Core::Colour(1.0f,0.0f,0.0f,0.5f));\n }\n#endif\n \n GUIView::Draw(inpCanvas);\n }\n\t\t\/\/-------------------------------------------------------\n\t\t\/\/\/ Sets Debug Drawing\n\t\t\/\/\/\n\t\t\/\/\/ Enables\/Disables debug drawing\n\t\t\/\/\/\n\t\t\/\/\/ @param New value for this flag. DEBUG_DRAWING must be\n\t\t\/\/\/ set to TRUE\n\t\t\/\/-------------------------------------------------------\n\t\tvoid ScrollView::EnableDebugDrawing(bool inbValue)\n\t\t{\n#if CS_ENABLE_DEBUGDRAWING\n\t\t\tmbDrawDebug = inbValue;\n#else\n\t\t\tmbDrawDebug = false;\n#endif\n\t\t}\n \/\/-----------------------------------------------------------\n \/\/\/ Get Container View\n \/\/\/\n \/\/\/ @return The GUIView that contains all scrollable subviews\n \/\/\/ within the scroll view.\n \/\/-----------------------------------------------------------\n const GUIViewSPtr& ScrollView::GetContainerView() const\n {\n return mpContainerView;\n }\n }\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the Delaunay project.\n\n Copyright T.J. Corona\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"ConstrainedDelaunayMesh.hh\"\n\n#include \"Discretization\/InsertLineSegment.hh\"\n#include \"Discretization\/RemoveBoundedRegion.hh\"\n#include \"Shape\/PolygonUtilities.hh\"\n\n#include \n\nnamespace Delaunay\n{\nnamespace Discretization\n{\nvoid ConstrainedDelaunayMesh::operator()(\n const Delaunay::Shape::Polygon& polygon, Delaunay::Mesh::Mesh& mesh)\n{\n std::array bounds(Shape::Bounds(polygon));\n double xLen = bounds[1] - bounds[0];\n double yLen = bounds[3] - bounds[2];\n bounds[0] -= .2*xLen;\n bounds[1] += .2*xLen;\n bounds[2] -= .2*yLen;\n bounds[3] += .2*yLen;\n\n bool inSitu = mesh.GetVertices().empty();\n\n Mesh::Mesh mesh_;\n Mesh::Mesh* augmentedMesh;\n if (inSitu)\n augmentedMesh = &mesh;\n else\n augmentedMesh = &mesh_;\n\n const Mesh::Vertex& v0 = *(this->InsertVertex(\n Shape::Point(bounds[0],bounds[2]),\n *augmentedMesh)).first;\n const Mesh::Vertex& v1 = *(this->InsertVertex(\n Shape::Point(bounds[1],bounds[2]),\n *augmentedMesh)).first;\n const Mesh::Vertex& v2 = *(this->InsertVertex(\n Shape::Point(bounds[0],bounds[3]),\n *augmentedMesh)).first;\n const Mesh::Vertex& v3 = *(this->InsertVertex(\n Shape::Point(bounds[1],bounds[3]),\n *augmentedMesh)).first;\n\n const Mesh::Edge& e01 =*(this->InsertEdge(v0,v1,*augmentedMesh)).first;\n const Mesh::Edge& e02 =*(this->InsertEdge(v0,v2,*augmentedMesh)).first;\n const Mesh::Edge& e12 =*(this->InsertEdge(v1,v2,*augmentedMesh)).first;\n const Mesh::Edge& e13 =*(this->InsertEdge(v1,v3,*augmentedMesh)).first;\n const Mesh::Edge& e23 =*(this->InsertEdge(v2,v3,*augmentedMesh)).first;\n\n this->GetTriangles(*augmentedMesh).emplace(e01,e02,e12);\n this->GetTriangles(*augmentedMesh).emplace(e13,e23,e12);\n\n InsertLineSegment insertLineSegment;\n\n Mesh::VertexList list;\n std::pair firstEdge;\n for (Shape::PointList::const_iterator it = polygon.GetPoints().begin();\n it != polygon.GetPoints().end(); ++it)\n {\n Shape::PointList::const_iterator next = std::next(it);\n if (next == polygon.GetPoints().end())\n next = polygon.GetPoints().begin();\n Shape::LineSegment l(*it, *next);\n const Mesh::Edge* edge = insertLineSegment(l, mesh);\n list.push_back(std::cref(edge->A() == *it ? edge->A() : edge->B()));\n if (it == polygon.GetPoints().begin())\n {\n bool isCCW =\n\tShape::Dot(edge->B() - edge->A(), *next - *it) > 0.;\n firstEdge = std::make_pair(edge, isCCW);\n }\n }\n\n RemoveBoundedRegion removeBoundedRegion;\n removeBoundedRegion(*firstEdge.first, !firstEdge.second, *augmentedMesh);\n\n if (inSitu)\n {\n this->GetPerimeter(mesh).SetVertices(list);\n }\n else\n {\n RemoveBoundedRegion removeBoundedRegion;\n removeBoundedRegion(*firstEdge.first, !firstEdge.second, *augmentedMesh);\n\n if (inSitu)\n {\n this->GetPerimeter(mesh).SetPoints(vec);\n }\n else\n {\n for (auto& triangle : mesh_.GetTriangles())\n {\n const Mesh::Vertex& a = *(this->InsertVertex(\n triangle.AB().A(),mesh)).first;\n const Mesh::Vertex& b = *(this->InsertVertex(\n triangle.AB().B(),mesh)).first;\n const Mesh::Vertex& c = *(this->InsertVertex(\n triangle.AC().B(),mesh)).first;\n const Mesh::Edge& ab = *(this->InsertEdge(a,b,mesh)).first;\n const Mesh::Edge& bc = *(this->InsertEdge(b,c,mesh)).first;\n const Mesh::Edge& ac = *(this->InsertEdge(a,c,mesh)).first;\n this->InsertTriangle(ab,bc,ac,mesh);\n }\n }\n }\n}\n\n}\n}\nFix merge bug\/******************************************************************************\n\n This source file is part of the Delaunay project.\n\n Copyright T.J. Corona\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"ConstrainedDelaunayMesh.hh\"\n\n#include \"Discretization\/InsertLineSegment.hh\"\n#include \"Discretization\/RemoveBoundedRegion.hh\"\n#include \"Shape\/PolygonUtilities.hh\"\n\n#include \n\nnamespace Delaunay\n{\nnamespace Discretization\n{\nvoid ConstrainedDelaunayMesh::operator()(\n const Delaunay::Shape::Polygon& polygon, Delaunay::Mesh::Mesh& mesh)\n{\n std::array bounds(Shape::Bounds(polygon));\n double xLen = bounds[1] - bounds[0];\n double yLen = bounds[3] - bounds[2];\n bounds[0] -= .2*xLen;\n bounds[1] += .2*xLen;\n bounds[2] -= .2*yLen;\n bounds[3] += .2*yLen;\n\n bool inSitu = mesh.GetVertices().empty();\n\n Mesh::Mesh mesh_;\n Mesh::Mesh* augmentedMesh;\n if (inSitu)\n augmentedMesh = &mesh;\n else\n augmentedMesh = &mesh_;\n\n const Mesh::Vertex& v0 = *(this->InsertVertex(\n Shape::Point(bounds[0],bounds[2]),\n *augmentedMesh)).first;\n const Mesh::Vertex& v1 = *(this->InsertVertex(\n Shape::Point(bounds[1],bounds[2]),\n *augmentedMesh)).first;\n const Mesh::Vertex& v2 = *(this->InsertVertex(\n Shape::Point(bounds[0],bounds[3]),\n *augmentedMesh)).first;\n const Mesh::Vertex& v3 = *(this->InsertVertex(\n Shape::Point(bounds[1],bounds[3]),\n *augmentedMesh)).first;\n\n const Mesh::Edge& e01 =*(this->InsertEdge(v0,v1,*augmentedMesh)).first;\n const Mesh::Edge& e02 =*(this->InsertEdge(v0,v2,*augmentedMesh)).first;\n const Mesh::Edge& e12 =*(this->InsertEdge(v1,v2,*augmentedMesh)).first;\n const Mesh::Edge& e13 =*(this->InsertEdge(v1,v3,*augmentedMesh)).first;\n const Mesh::Edge& e23 =*(this->InsertEdge(v2,v3,*augmentedMesh)).first;\n\n this->GetTriangles(*augmentedMesh).emplace(e01,e02,e12);\n this->GetTriangles(*augmentedMesh).emplace(e13,e23,e12);\n\n InsertLineSegment insertLineSegment;\n\n Mesh::VertexList list;\n std::pair firstEdge;\n for (Shape::PointList::const_iterator it = polygon.GetPoints().begin();\n it != polygon.GetPoints().end(); ++it)\n {\n Shape::PointList::const_iterator next = std::next(it);\n if (next == polygon.GetPoints().end())\n next = polygon.GetPoints().begin();\n Shape::LineSegment l(*it, *next);\n const Mesh::Edge* edge = insertLineSegment(l, mesh);\n list.push_back(std::cref(edge->A() == *it ? edge->A() : edge->B()));\n if (it == polygon.GetPoints().begin())\n {\n bool isCCW =\n\tShape::Dot(edge->B() - edge->A(), *next - *it) > 0.;\n firstEdge = std::make_pair(edge, isCCW);\n }\n }\n\n RemoveBoundedRegion removeBoundedRegion;\n removeBoundedRegion(*firstEdge.first, !firstEdge.second, *augmentedMesh);\n\n if (inSitu)\n {\n this->GetPerimeter(mesh).SetVertices(list);\n }\n else\n {\n RemoveBoundedRegion removeBoundedRegion;\n removeBoundedRegion(*firstEdge.first, !firstEdge.second, *augmentedMesh);\n\n if (inSitu)\n {\n this->GetPerimeter(mesh).SetVertices(list);\n }\n else\n {\n for (auto& triangle : mesh_.GetTriangles())\n {\n const Mesh::Vertex& a = *(this->InsertVertex(\n triangle.AB().A(),mesh)).first;\n const Mesh::Vertex& b = *(this->InsertVertex(\n triangle.AB().B(),mesh)).first;\n const Mesh::Vertex& c = *(this->InsertVertex(\n triangle.AC().B(),mesh)).first;\n const Mesh::Edge& ab = *(this->InsertEdge(a,b,mesh)).first;\n const Mesh::Edge& bc = *(this->InsertEdge(b,c,mesh)).first;\n const Mesh::Edge& ac = *(this->InsertEdge(a,c,mesh)).first;\n this->InsertTriangle(ab,bc,ac,mesh);\n }\n }\n }\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED\n#define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n#include \n#endif\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/invariant_check.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/bandwidth_limit.hpp\"\n#include \"libtorrent\/bandwidth_queue_entry.hpp\"\n\nusing boost::weak_ptr;\nusing boost::shared_ptr;\nusing boost::intrusive_ptr;\nusing boost::bind;\n\n\nnamespace libtorrent {\n\ntemplate\nstruct bandwidth_manager\n{\n\tbandwidth_manager(int channel\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\t, bool log = false\n#endif\t\t\n\t\t)\n\t\t: m_queued_bytes(0)\n\t\t, m_channel(channel)\n\t\t, m_abort(false)\n\t{\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\tif (log)\n\t\t\tm_log.open(\"bandwidth_limiter.log\", std::ios::trunc);\n\t\tm_start = time_now();\n#endif\n\t}\n\n\tvoid close()\n\t{\n\t\tm_abort = true;\n\t\tm_queue.clear();\n\t\tm_queued_bytes = 0;\n\t\terror_code ec;\n\t}\n\n#ifdef TORRENT_DEBUG\n\tbool is_queued(PeerConnection const* peer) const\n\t{\n\t\tfor (typename queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tif (i->peer.get() == peer) return true;\n\t\t}\n\t\treturn false;\n\t}\n#endif\n\n\tint queue_size() const\n\t{\n\t\treturn m_queue.size();\n\t}\n\n\tint queued_bytes() const\n\t{\n\t\treturn m_queued_bytes;\n\t}\n\t\n\t\/\/ non prioritized means that, if there's a line for bandwidth,\n\t\/\/ others will cut in front of the non-prioritized peers.\n\t\/\/ this is used by web seeds\n\tvoid request_bandwidth(intrusive_ptr const& peer\n\t\t, int blk, int priority\n\t\t, bandwidth_channel* chan1 = 0\n\t\t, bandwidth_channel* chan2 = 0\n\t\t, bandwidth_channel* chan3 = 0\n\t\t, bandwidth_channel* chan4 = 0\n\t\t, bandwidth_channel* chan5 = 0\n\t\t)\n\t{\n\t\tINVARIANT_CHECK;\n\t\tif (m_abort) return;\n\n\t\tTORRENT_ASSERT(blk > 0);\n\t\tTORRENT_ASSERT(priority > 0);\n\t\tTORRENT_ASSERT(!is_queued(peer.get()));\n\n\t\tbw_request bwr(peer, blk, priority);\n\t\tint i = 0;\n\t\tif (chan1 && chan1->throttle() > 0) bwr.channel[i++] = chan1;\n\t\tif (chan2 && chan2->throttle() > 0) bwr.channel[i++] = chan2;\n\t\tif (chan3 && chan3->throttle() > 0) bwr.channel[i++] = chan3;\n\t\tif (chan4 && chan4->throttle() > 0) bwr.channel[i++] = chan4;\n\t\tif (chan5 && chan5->throttle() > 0) bwr.channel[i++] = chan5;\n\t\tif (i == 0)\n\t\t{\n\t\t\t\/\/ the connection is not rate limited by any of its\n\t\t\t\/\/ bandwidth channels, or it doesn't belong to any\n\t\t\t\/\/ channels. There's no point in adding it to\n\t\t\t\/\/ the queue, just satisfy the request immediately\n\t\t\tbwr.peer->assign_bandwidth(m_channel, blk);\n\t\t\treturn;\n\t\t}\n\t\tm_queued_bytes += blk;\n\t\tm_queue.push_back(bwr);\n\t}\n\n#ifdef TORRENT_DEBUG\n\tvoid check_invariant() const\n\t{\n\t}\n#endif\n\n\tvoid update_quotas(time_duration const& dt)\n\t{\n\t\tif (m_abort) return;\n\t\tif (m_queue.empty()) return;\n\n\t\tINVARIANT_CHECK;\n\n\t\tint dt_milliseconds = total_milliseconds(dt);\n\t\tif (dt_milliseconds > 3000) dt_milliseconds = 3000;\n\n\t\t\/\/ for each bandwidth channel, call update_quota(dt)\n\n\t\tstd::vector channels;\n\n\t\tfor (typename queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tif (i->peer->is_disconnecting())\n\t\t\t{\n\t\t\t\tm_queued_bytes -= i->request_size - i->assigned;\n\n\t\t\t\t\/\/ return all assigned quota to all the\n\t\t\t\t\/\/ bandwidth channels this peer belongs to\n\t\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t\t{\n\t\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\t\tbwc->return_quota(i->assigned);\n\t\t\t\t}\n\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tbwc->tmp = 0;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\tfor (typename queue_t::iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tif (bwc->tmp == 0) channels.push_back(bwc);\n\t\t\t\tbwc->tmp += i->priority;\n\t\t\t\tTORRENT_ASSERT(i->priority > 0);\n\t\t\t}\n\t\t}\n\n\t\tfor (std::vector::iterator i = channels.begin()\n\t\t\t, end(channels.end()); i != end; ++i)\n\t\t{\n\t\t\t(*i)->update_quota(dt_milliseconds);\n\t\t}\n\n\t\tqueue_t tm;\n\n\t\tfor (typename queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tint a = i->assign_bandwidth();\n\t\t\tif (i->assigned == i->request_size\n\t\t\t\t|| (i->ttl <= 0 && i->assigned > 0))\n\t\t\t{\n\t\t\t\tTORRENT_ASSERT(i->assigned <= i->request_size);\n\t\t\t\ttm.push_back(*i);\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tm_queued_bytes -= a;\n\t\t}\n\n\t\twhile (!tm.empty())\n\t\t{\n\t\t\tbw_request& bwr = tm.back();\n\t\t\tbwr.peer->assign_bandwidth(m_channel, bwr.assigned);\n\t\t\ttm.pop_back();\n\t\t}\n\t}\n\n\n\t\/\/ these are the consumers that want bandwidth\n\ttypedef std::vector > queue_t;\n\tqueue_t m_queue;\n\t\/\/ the number of bytes all the requests in queue are for\n\tint m_queued_bytes;\n\n\t\/\/ this is the channel within the consumers\n\t\/\/ that bandwidth is assigned to (upload or download)\n\tint m_channel;\n\n\tbool m_abort;\n\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\tstd::ofstream m_log;\n\tptime m_start;\n#endif\n};\n\n}\n\n#endif\n\nfixed bug in ratelimiter's outstanding bytes counter\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED\n#define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n#include \n#endif\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/invariant_check.hpp\"\n#include \"libtorrent\/assert.hpp\"\n#include \"libtorrent\/bandwidth_limit.hpp\"\n#include \"libtorrent\/bandwidth_queue_entry.hpp\"\n\nusing boost::weak_ptr;\nusing boost::shared_ptr;\nusing boost::intrusive_ptr;\nusing boost::bind;\n\n\nnamespace libtorrent {\n\ntemplate\nstruct bandwidth_manager\n{\n\tbandwidth_manager(int channel\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\t, bool log = false\n#endif\t\t\n\t\t)\n\t\t: m_queued_bytes(0)\n\t\t, m_channel(channel)\n\t\t, m_abort(false)\n\t{\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\tif (log)\n\t\t\tm_log.open(\"bandwidth_limiter.log\", std::ios::trunc);\n\t\tm_start = time_now();\n#endif\n\t}\n\n\tvoid close()\n\t{\n\t\tm_abort = true;\n\t\tm_queue.clear();\n\t\tm_queued_bytes = 0;\n\t\terror_code ec;\n\t}\n\n#ifdef TORRENT_DEBUG\n\tbool is_queued(PeerConnection const* peer) const\n\t{\n\t\tfor (typename queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tif (i->peer.get() == peer) return true;\n\t\t}\n\t\treturn false;\n\t}\n#endif\n\n\tint queue_size() const\n\t{\n\t\treturn m_queue.size();\n\t}\n\n\tint queued_bytes() const\n\t{\n\t\treturn m_queued_bytes;\n\t}\n\t\n\t\/\/ non prioritized means that, if there's a line for bandwidth,\n\t\/\/ others will cut in front of the non-prioritized peers.\n\t\/\/ this is used by web seeds\n\tvoid request_bandwidth(intrusive_ptr const& peer\n\t\t, int blk, int priority\n\t\t, bandwidth_channel* chan1 = 0\n\t\t, bandwidth_channel* chan2 = 0\n\t\t, bandwidth_channel* chan3 = 0\n\t\t, bandwidth_channel* chan4 = 0\n\t\t, bandwidth_channel* chan5 = 0\n\t\t)\n\t{\n\t\tINVARIANT_CHECK;\n\t\tif (m_abort) return;\n\n\t\tTORRENT_ASSERT(blk > 0);\n\t\tTORRENT_ASSERT(priority > 0);\n\t\tTORRENT_ASSERT(!is_queued(peer.get()));\n\n\t\tbw_request bwr(peer, blk, priority);\n\t\tint i = 0;\n\t\tif (chan1 && chan1->throttle() > 0) bwr.channel[i++] = chan1;\n\t\tif (chan2 && chan2->throttle() > 0) bwr.channel[i++] = chan2;\n\t\tif (chan3 && chan3->throttle() > 0) bwr.channel[i++] = chan3;\n\t\tif (chan4 && chan4->throttle() > 0) bwr.channel[i++] = chan4;\n\t\tif (chan5 && chan5->throttle() > 0) bwr.channel[i++] = chan5;\n\t\tif (i == 0)\n\t\t{\n\t\t\t\/\/ the connection is not rate limited by any of its\n\t\t\t\/\/ bandwidth channels, or it doesn't belong to any\n\t\t\t\/\/ channels. There's no point in adding it to\n\t\t\t\/\/ the queue, just satisfy the request immediately\n\t\t\tbwr.peer->assign_bandwidth(m_channel, blk);\n\t\t\treturn;\n\t\t}\n\t\tm_queued_bytes += blk;\n\t\tm_queue.push_back(bwr);\n\t}\n\n#ifdef TORRENT_DEBUG\n\tvoid check_invariant() const\n\t{\n\t\tint queued = 0;\n\t\tfor (typename queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tqueued += i->request_size - i->assigned;\n\t\t}\n\t\tTORRENT_ASSERT(queued == m_queued_bytes);\n\t}\n#endif\n\n\tvoid update_quotas(time_duration const& dt)\n\t{\n\t\tif (m_abort) return;\n\t\tif (m_queue.empty()) return;\n\n\t\tINVARIANT_CHECK;\n\n\t\tint dt_milliseconds = total_milliseconds(dt);\n\t\tif (dt_milliseconds > 3000) dt_milliseconds = 3000;\n\n\t\t\/\/ for each bandwidth channel, call update_quota(dt)\n\n\t\tstd::vector channels;\n\n\t\tfor (typename queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tif (i->peer->is_disconnecting())\n\t\t\t{\n\t\t\t\tm_queued_bytes -= i->request_size - i->assigned;\n\n\t\t\t\t\/\/ return all assigned quota to all the\n\t\t\t\t\/\/ bandwidth channels this peer belongs to\n\t\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t\t{\n\t\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\t\tbwc->return_quota(i->assigned);\n\t\t\t\t}\n\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tbwc->tmp = 0;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\tfor (typename queue_t::iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tif (bwc->tmp == 0) channels.push_back(bwc);\n\t\t\t\tbwc->tmp += i->priority;\n\t\t\t\tTORRENT_ASSERT(i->priority > 0);\n\t\t\t}\n\t\t}\n\n\t\tfor (std::vector::iterator i = channels.begin()\n\t\t\t, end(channels.end()); i != end; ++i)\n\t\t{\n\t\t\t(*i)->update_quota(dt_milliseconds);\n\t\t}\n\n\t\tqueue_t tm;\n\n\t\tfor (typename queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tint a = i->assign_bandwidth();\n\t\t\tif (i->assigned == i->request_size\n\t\t\t\t|| (i->ttl <= 0 && i->assigned > 0))\n\t\t\t{\n\t\t\t\ta += i->request_size - i->assigned;\n\t\t\t\tTORRENT_ASSERT(i->assigned <= i->request_size);\n\t\t\t\ttm.push_back(*i);\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tm_queued_bytes -= a;\n\t\t}\n\n\t\twhile (!tm.empty())\n\t\t{\n\t\t\tbw_request& bwr = tm.back();\n\t\t\tbwr.peer->assign_bandwidth(m_channel, bwr.assigned);\n\t\t\ttm.pop_back();\n\t\t}\n\t}\n\n\n\t\/\/ these are the consumers that want bandwidth\n\ttypedef std::vector > queue_t;\n\tqueue_t m_queue;\n\t\/\/ the number of bytes all the requests in queue are for\n\tint m_queued_bytes;\n\n\t\/\/ this is the channel within the consumers\n\t\/\/ that bandwidth is assigned to (upload or download)\n\tint m_channel;\n\n\tbool m_abort;\n\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\tstd::ofstream m_log;\n\tptime m_start;\n#endif\n};\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/* mockturtle: C++ logic network library\n * Copyright (C) 2018-2019 EPFL\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/*!\n \\file window_view.hpp\n \\brief Implements an isolated view on a window in a network\n\n \\author Heinz Riener\n*\/\n\n#pragma once\n\n#include \"..\/traits.hpp\"\n#include \"..\/networks\/detail\/foreach.hpp\"\n#include \"..\/utils\/window_utils.hpp\"\n#include \"immutable_view.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mockturtle\n{\n\n\/*! \\brief Implements an isolated view on a window in a network.\n *\n * This view creates a network from a window in a large network. The\n * window is specified by three parameters:\n * 1.) `inputs` are the common support of all window nodes, they do\n * not overlap with `gates` (i.e., the intersection of `inputs` and\n * `gates` is the empty set).\n * 2.) `gates` are the nodes in the window, supported by the\n * `inputs` (i.e., `gates` are in the transitive fanout of the\n * `inputs`,\n * 3.) `outputs` are signals (regular or complemented nodes)\n * pointing to nodes in `gates` or `inputs`. Not all fanouts\n * of an output node are already part of the window.\n *\n * The second parameter `gates` has to be passed and is not\n * automatically computed (for example in contrast to `cut_view`),\n * because there are different strategies to construct a window from a\n * support set. The outputs could be automatically computed.\n *\n * The window_view implements one new API method:\n * 1.) `belongs_to`: takes a node (or a signal) and returns true if and\n * only if the corresponding node belongs to the window\n *\/\ntemplate\nclass window_view : public immutable_view\n{\npublic:\n using storage = typename Ntk::storage;\n using node = typename Ntk::node;\n using signal = typename Ntk::signal;\n\npublic:\n template>>\n explicit window_view( Ntk const& ntk, std::vector const& inputs, std::vector const& outputs, std::vector const& gates )\n : immutable_view( ntk )\n , _inputs( inputs )\n , _outputs( outputs )\n {\n construct( inputs, gates );\n }\n\n explicit window_view( Ntk const& ntk, std::vector const& inputs, std::vector const& outputs, std::vector const& gates )\n : immutable_view( ntk )\n , _inputs( inputs )\n {\n construct( inputs, gates );\n\n \/* convert output nodes to signals *\/\n std::transform( std::begin( outputs ), std::end( outputs ), std::back_inserter( _outputs ),\n [this]( node const& n ){\n return this->make_signal( n );\n });\n }\n\n#pragma region Window\n template>>\n inline bool belongs_to( signal const& s ) const\n {\n return std::find( std::begin( _nodes ), std::end( _nodes ), get_node( s ) ) != std::end( _nodes );\n }\n\n inline bool belongs_to( node const& n ) const\n {\n return std::find( std::begin( _nodes ), std::end( _nodes ), n ) != std::end( _nodes );\n }\n#pragma endregion\n\n#pragma region Structural properties\n inline uint32_t size() const\n {\n return static_cast( _nodes.size() );\n }\n\n inline uint32_t num_cis() const\n {\n return num_pis();\n }\n\n inline uint32_t num_cos() const\n {\n return num_pos();\n }\n\n inline uint32_t num_latches() const\n {\n return 0u;\n }\n\n inline uint32_t num_pis() const\n {\n return static_cast( _inputs.size() );\n }\n\n inline uint32_t num_pos() const\n {\n return static_cast( _outputs.size() );\n }\n\n inline uint32_t num_registers() const\n {\n return 0u;\n }\n\n inline uint32_t num_gates() const\n {\n return static_cast( _nodes.size() - _inputs.size() - 1u );\n }\n\n inline uint32_t fanout_size( node const& n ) const = delete;\n\n inline uint32_t node_to_index( node const& n ) const\n {\n return _node_to_index.at( n );\n }\n\n inline node index_to_node( uint32_t index ) const\n {\n return _nodes[index];\n }\n\n inline bool is_pi( node const& n ) const\n {\n return std::find( std::begin( _inputs ), std::end( _inputs ), n ) != std::end( _inputs );\n }\n\n inline bool is_ci( node const& n ) const\n {\n return is_pi( n );\n }\n#pragma endregion\n\n#pragma region Node and signal iterators\n template\n void foreach_pi( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _inputs ), std::end( _inputs ), fn );\n }\n\n template\n void foreach_po( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _outputs ), std::end( _outputs ), fn );\n }\n\n template\n void foreach_ci( Fn&& fn ) const\n {\n foreach_pi( fn );\n }\n\n template\n void foreach_co( Fn&& fn ) const\n {\n foreach_po( fn );\n }\n\n template\n void foreach_ro( Fn&& fn ) const\n {\n (void)fn;\n }\n\n template\n void foreach_ri( Fn&& fn ) const\n {\n (void)fn;\n }\n\n template\n void foreach_register( Fn&& fn ) const\n {\n (void)fn;\n }\n\n template\n void foreach_node( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _nodes ), std::end( _nodes ), fn );\n }\n\n template\n void foreach_gate( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _nodes ) + 1u + _inputs.size(), std::end( _nodes ), fn );\n }\n\n template\n void foreach_fanin( node const& n, Fn&& fn ) const\n {\n \/* constants and inputs do not have fanins *\/\n if ( this->is_constant( n ) ||\n std::find( std::begin( _inputs ), std::end( _inputs ), n ) != std::end( _inputs ) )\n {\n return;\n }\n\n \/* if it's not a window input, the node has to be a window node *\/\n assert( std::find( std::begin( _nodes ) + 1 + _inputs.size(), std::end( _nodes ), n ) != std::end( _nodes ) );\n immutable_view::foreach_fanin( n, fn );\n }\n#pragma endregion\n\nprotected:\n void construct( std::vector const& inputs, std::vector const& gates )\n {\n \/* copy constant to nodes *\/\n _nodes.emplace_back( this->get_node( this->get_constant( false ) ) );\n\n \/* copy inputs to nodes *\/\n std::copy( std::begin( inputs ), std::end( inputs ), std::back_inserter( _nodes ) );\n\n \/* copy gates to nodes *\/\n std::copy( std::begin( gates ), std::end( gates ), std::back_inserter( _nodes ) );\n\n \/* create a mapping from node id (index in the original network) to window index *\/\n for ( uint32_t index = 0; index < _nodes.size(); ++index )\n {\n _node_to_index[_nodes.at( index )] = index;\n }\n }\n\nprotected:\n std::vector _inputs;\n std::vector _outputs;\n std::vector _nodes;\n std::unordered_map _node_to_index;\n}; \/* window_view *\/\n\n} \/* namespace mockturtle *\/\nNew API methods `foreach_internal_fanout` and `foreach_external_fanout` in `window_view`. (#399)\/* mockturtle: C++ logic network library\n * Copyright (C) 2018-2020 EPFL\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/*!\n \\file window_view.hpp\n \\brief Implements an isolated view on a window in a network\n\n \\author Heinz Riener\n*\/\n\n#pragma once\n\n#include \"..\/traits.hpp\"\n#include \"..\/networks\/detail\/foreach.hpp\"\n#include \"..\/utils\/window_utils.hpp\"\n#include \"immutable_view.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace mockturtle\n{\n\n\/*! \\brief Implements an isolated view on a window in a network.\n *\n * This view creates a network from a window in a large network. The\n * window is specified by three parameters:\n * 1.) `inputs` are the common support of all window nodes, they do\n * not overlap with `gates` (i.e., the intersection of `inputs` and\n * `gates` is the empty set).\n * 2.) `gates` are the nodes in the window, supported by the\n * `inputs` (i.e., `gates` are in the transitive fanout of the\n * `inputs`,\n * 3.) `outputs` are signals (regular or complemented nodes)\n * pointing to nodes in `gates` or `inputs`. Not all fanouts\n * of an output node are already part of the window.\n *\n * The second parameter `gates` has to be passed and is not\n * automatically computed (for example in contrast to `cut_view`),\n * because there are different strategies to construct a window from a\n * support set. The outputs could be automatically computed.\n *\n * The window_view implements three new API methods:\n * 1.) `belongs_to`: takes a node (or a signal) and returns true if and\n * only if the corresponding node belongs to the window\n * 2.) `foreach_internal_fanout`: takes a node and invokes a predicate\n on all fanout nodes of the node that belong to the window\n * 3.) `foreach_exnteral_fanout`: takes a node and invokes a predicate\n on all fanouts of the node that do not belong to the window\n *\/\ntemplate\nclass window_view : public immutable_view\n{\npublic:\n using storage = typename Ntk::storage;\n using node = typename Ntk::node;\n using signal = typename Ntk::signal;\n\npublic:\n template>>\n explicit window_view( Ntk const& ntk, std::vector const& inputs, std::vector const& outputs, std::vector const& gates )\n : immutable_view( ntk )\n , _inputs( inputs )\n , _outputs( outputs )\n {\n construct( inputs, gates );\n }\n\n explicit window_view( Ntk const& ntk, std::vector const& inputs, std::vector const& outputs, std::vector const& gates )\n : immutable_view( ntk )\n , _inputs( inputs )\n {\n construct( inputs, gates );\n\n \/* convert output nodes to signals *\/\n std::transform( std::begin( outputs ), std::end( outputs ), std::back_inserter( _outputs ),\n [this]( node const& n ){\n return this->make_signal( n );\n });\n }\n\n#pragma region Window\n template>>\n inline bool belongs_to( signal const& s ) const\n {\n return std::find( std::begin( _nodes ), std::end( _nodes ), get_node( s ) ) != std::end( _nodes );\n }\n\n inline bool belongs_to( node const& n ) const\n {\n return std::find( std::begin( _nodes ), std::end( _nodes ), n ) != std::end( _nodes );\n }\n#pragma endregion\n\n#pragma region Structural properties\n inline uint32_t size() const\n {\n return static_cast( _nodes.size() );\n }\n\n inline uint32_t num_cis() const\n {\n return num_pis();\n }\n\n inline uint32_t num_cos() const\n {\n return num_pos();\n }\n\n inline uint32_t num_latches() const\n {\n return 0u;\n }\n\n inline uint32_t num_pis() const\n {\n return static_cast( _inputs.size() );\n }\n\n inline uint32_t num_pos() const\n {\n return static_cast( _outputs.size() );\n }\n\n inline uint32_t num_registers() const\n {\n return 0u;\n }\n\n inline uint32_t num_gates() const\n {\n return static_cast( _nodes.size() - _inputs.size() - 1u );\n }\n\n inline uint32_t fanout_size( node const& n ) const = delete;\n\n inline uint32_t node_to_index( node const& n ) const\n {\n return _node_to_index.at( n );\n }\n\n inline node index_to_node( uint32_t index ) const\n {\n return _nodes[index];\n }\n\n inline bool is_pi( node const& n ) const\n {\n return std::find( std::begin( _inputs ), std::end( _inputs ), n ) != std::end( _inputs );\n }\n\n inline bool is_ci( node const& n ) const\n {\n return is_pi( n );\n }\n\n signal po_at( uint32_t index ) const\n {\n assert( index < _outputs.size() );\n return *( std::begin( _outputs ) + index );\n }\n\n signal co_at( uint32_t index ) const\n {\n return po_at( index );\n }\n#pragma endregion\n\n#pragma region Node and signal iterators\n template\n void foreach_pi( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _inputs ), std::end( _inputs ), fn );\n }\n\n template\n void foreach_po( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _outputs ), std::end( _outputs ), fn );\n }\n\n template\n void foreach_ci( Fn&& fn ) const\n {\n foreach_pi( fn );\n }\n\n template\n void foreach_co( Fn&& fn ) const\n {\n foreach_po( fn );\n }\n\n template\n void foreach_ro( Fn&& fn ) const\n {\n (void)fn;\n }\n\n template\n void foreach_ri( Fn&& fn ) const\n {\n (void)fn;\n }\n\n template\n void foreach_register( Fn&& fn ) const\n {\n (void)fn;\n }\n\n template\n void foreach_node( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _nodes ), std::end( _nodes ), fn );\n }\n\n template\n void foreach_gate( Fn&& fn ) const\n {\n detail::foreach_element( std::begin( _nodes ) + 1u + _inputs.size(), std::end( _nodes ), fn );\n }\n\n template\n void foreach_fanin( node const& n, Fn&& fn ) const\n {\n \/* constants and inputs do not have fanins *\/\n if ( this->is_constant( n ) ||\n std::find( std::begin( _inputs ), std::end( _inputs ), n ) != std::end( _inputs ) )\n {\n return;\n }\n\n \/* if it's not a window input, the node has to be a window node *\/\n assert( std::find( std::begin( _nodes ) + 1 + _inputs.size(), std::end( _nodes ), n ) != std::end( _nodes ) );\n immutable_view::foreach_fanin( n, fn );\n }\n\n template\n void foreach_internal_fanout( node const& n, Fn&& fn ) const\n {\n this->foreach_fanout( n, [&]( node const& fo ){\n if ( tbelongs_to( fo ) )\n {\n fn( fo );\n }\n });\n }\n\n template\n void foreach_external_fanout( node const& n, Fn&& fn ) const\n {\n this->foreach_fanout( n, [&]( node const& fo ){\n if ( !belongs_to( fo ) )\n {\n fn( fo );\n }\n });\n }\n#pragma endregion\n\nprotected:\n void construct( std::vector const& inputs, std::vector const& gates )\n {\n \/* copy constant to nodes *\/\n _nodes.emplace_back( this->get_node( this->get_constant( false ) ) );\n\n \/* copy inputs to nodes *\/\n std::copy( std::begin( inputs ), std::end( inputs ), std::back_inserter( _nodes ) );\n\n \/* copy gates to nodes *\/\n std::copy( std::begin( gates ), std::end( gates ), std::back_inserter( _nodes ) );\n\n \/* create a mapping from node id (index in the original network) to window index *\/\n for ( uint32_t index = 0; index < _nodes.size(); ++index )\n {\n _node_to_index[_nodes.at( index )] = index;\n }\n }\n\nprotected:\n std::vector _inputs;\n std::vector _outputs;\n std::vector _nodes;\n std::unordered_map _node_to_index;\n}; \/* window_view *\/\n\n} \/* namespace mockturtle *\/\n<|endoftext|>"} {"text":"#ifndef RBX_UTIL_THREAD_HPP\n#define RBX_UTIL_THREAD_HPP\n\n#define USE_PTHREADS\n\n#ifdef USE_PTHREADS\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace thread {\n enum Code {\n cLocked,\n cUnlocked,\n cLockBusy,\n cNotYours,\n cReady,\n cTimedOut\n };\n\n#if 0\n static void block_all_signals() {\n sigset_t set;\n sigfillset(&set);\n\n pthread_sigmask(SIG_BLOCK, &set, NULL);\n }\n\n static void accept_signal(int sig) {\n sigset_t set;\n sigemptyset(&set);\n sigaddset(&set, sig);\n\n pthread_sigmask(SIG_UNBLOCK, &set, NULL);\n }\n\n static void ignore_signal(int sig) {\n sigset_t set;\n sigemptyset(&set);\n sigaddset(&set, sig);\n\n pthread_sigmask(SIG_BLOCK, &set, NULL);\n }\n\n static void wait_on_signal(int sig) {\n sigset_t set;\n sigemptyset(&set);\n sigaddset(&set, sig);\n\n int bunk;\n sigwait(&set, &bunk);\n }\n#endif\n template \n class ThreadData {\n pthread_key_t native_;\n\n public:\n ThreadData() {\n assert(pthread_key_create(&native_, NULL) == 0);\n }\n\n ~ThreadData() {\n assert(pthread_key_delete(native_) == 0);\n }\n\n T get() {\n return reinterpret_cast(pthread_getspecific(native_));\n }\n\n void set(T val) {\n assert(pthread_setspecific(native_, reinterpret_cast(val)) == 0);\n }\n };\n\n class Thread {\n pthread_t native_;\n bool delete_on_exit_;\n size_t stack_size_;\n\n static void* trampoline(void* arg) {\n Thread* self = reinterpret_cast(arg);\n self->perform();\n if(self->delete_on_exit()) delete self;\n return NULL;\n }\n\n public:\n Thread(size_t stack_size = 0, pthread_t tid = 0)\n : native_(tid)\n , stack_size_(stack_size)\n {\n delete_on_exit_ = (tid != 0);\n }\n\n virtual ~Thread() { }\n\n pthread_t* native() {\n return &native_;\n }\n\n void run() {\n pthread_attr_t attrs;\n pthread_attr_init(&attrs);\n if(stack_size_) {\n pthread_attr_setstacksize(&attrs, stack_size_);\n }\n\n assert(pthread_create(&native_, &attrs, trampoline, (void*)this) == 0);\n }\n\n virtual void perform() { }\n\n void detach() {\n assert(pthread_detach(native_) == 0);\n }\n\n bool equal(Thread& other) {\n if(pthread_equal(native_, *other.native())) {\n return true;\n }\n\n return false;\n }\n\n void join() {\n void* bunk;\n int err = pthread_join(native_, &bunk);\n if(err != 0) {\n if(err == EDEADLK) {\n std::cout << \"Thread deadlock!\\n\";\n }\n\n assert(0);\n }\n }\n\n void cancel() {\n assert(pthread_cancel(native_) == 0);\n }\n\n void kill(int sig) {\n assert(pthread_kill(native_, sig) == 0);\n }\n\n int priority() {\n int _policy;\n struct sched_param params;\n\n assert(pthread_getschedparam(native_, &_policy, ¶ms) == 0);\n\n return params.sched_priority;\n }\n\n bool set_priority(int priority) {\n int _policy;\n struct sched_param params;\n\n assert(pthread_getschedparam(native_, &_policy, ¶ms) == 0);\n int max = sched_get_priority_max(_policy);\n int min = sched_get_priority_min(_policy);\n\n if(min > priority) {\n priority = min;\n }\n else if(max < priority) {\n priority = max;\n }\n\n params.sched_priority = priority;\n\n int err = pthread_setschedparam(native_, _policy, ¶ms);\n if(err == ENOTSUP) return false;\n\n return true;\n }\n\n bool delete_on_exit() {\n return delete_on_exit_;\n }\n\n void set_delete_on_exit() {\n delete_on_exit_ = true;\n }\n };\n\n \/*\n * A stacklet object for locking and unlocking.\n *\/\n\n#ifdef DEBUG_LOCKGUARD\n const bool cDebugLockGuard = true;\n#else\n const bool cDebugLockGuard = false;\n#endif\n\n template \n class LockGuardTemplate {\n public:\n T& lock_;\n bool locked_;\n\n LockGuardTemplate(T& in_lock, bool initial = false)\n : lock_(in_lock)\n , locked_(initial)\n { }\n\n void lock() {\n if(locked_) return;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" Locking \" << lock_.describe() << \" ]]\\n\";\n }\n lock_.lock();\n locked_ = true;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" Locked \" << lock_.describe() << \" ]]\\n\";\n }\n }\n\n void unlock() {\n if(!locked_) return;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" Unlocking \" << lock_.describe() << \" ]]\\n\";\n }\n lock_.unlock();\n locked_ = false;\n }\n };\n\n template \n class StackLockGuard : public LockGuardTemplate {\n public:\n StackLockGuard(T& in_lock)\n : LockGuardTemplate(in_lock, false)\n {\n this->lock();\n }\n\n ~StackLockGuard() {\n this->unlock();\n }\n };\n\n template \n class StackUnlockGuard : public LockGuardTemplate {\n public:\n StackUnlockGuard(T& lock_obj)\n : LockGuardTemplate(lock_obj, true)\n {\n this->unlock();\n }\n\n ~StackUnlockGuard() {\n this->lock();\n }\n };\n\n class Mutex {\n public: \/\/ Types\n typedef StackLockGuard LockGuard;\n typedef StackUnlockGuard UnlockGuard;\n\n private:\n pthread_mutex_t native_;\n\n public:\n Mutex() {\n assert(pthread_mutex_init(&native_, NULL) == 0);\n }\n\n ~Mutex() {\n int err = pthread_mutex_destroy(&native_);\n if(err != 0) {\n if(err == EBUSY) assert(0 && \"mutex is busy!\");\n if(err == EINVAL) assert(0 && \"mutex is dead!\");\n assert(0 && \"mutex is screwed!\");\n }\n }\n\n pthread_mutex_t* native() {\n return &native_;\n }\n\n void lock() {\n int err;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" MLocking \" << describe() << \" ]]\\n\";\n }\n if((err = pthread_mutex_lock(&native_)) != 0) {\n if(err == EDEADLK) {\n std::cout << \"Thread deadlock!\\n\";\n }\n\n assert(0);\n }\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" MLocked \" << describe() << \" ]]\\n\";\n }\n }\n\n Code try_lock() {\n int err = pthread_mutex_trylock(&native_);\n if(err != 0) {\n if(err == EBUSY) return cLockBusy;\n assert(0);\n }\n\n return cLocked;\n }\n\n Code unlock() {\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" MUnlocking \" << describe() << \" ]]\\n\";\n }\n int err = pthread_mutex_unlock(&native_);\n if(err != 0) {\n if(err == EPERM) return cNotYours;\n assert(0);\n }\n\n return cUnlocked;\n }\n\n std::string describe() {\n std::stringstream ss;\n ss << \"Mutex \";\n ss << (void*)this;\n return ss.str();\n }\n };\n\n class Condition {\n pthread_cond_t native_;\n bool ready_;\n\n public:\n Condition()\n : ready_(false)\n {\n assert(pthread_cond_init(&native_, NULL) == 0);\n }\n\n ~Condition() {\n assert(pthread_cond_destroy(&native_) == 0);\n }\n\n void reset() {\n ready_ = false;\n }\n\n void signal() {\n ready_ = true;\n assert(pthread_cond_signal(&native_) == 0);\n }\n\n void broadcast() {\n ready_ = true;\n assert(pthread_cond_broadcast(&native_) == 0);\n }\n\n void wait(Mutex& mutex) {\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CUnlocking \" << mutex.describe() << \" ]]\\n\";\n }\n while(!ready_) {\n assert(pthread_cond_wait(&native_, mutex.native()) == 0);\n }\n\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CLocked \" << mutex.describe() << \" ]]\\n\";\n }\n }\n\n Code wait_until(Mutex& mutex, const struct timespec* ts) {\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CUnlocking \" << mutex.describe() << \" ]]\\n\";\n }\n\n while(!ready_) {\n int err = pthread_cond_timedwait(&native_, mutex.native(), ts);\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CLocked \" << mutex.describe() << \" ]]\\n\";\n }\n\n if(err != 0) {\n if(err == ETIMEDOUT) {\n if(ready_) return cReady;\n return cTimedOut;\n }\n\n switch(err) {\n case EINVAL:\n \/\/ This is not really correct, but it works for us:\n \/\/ We treat this error as ONLY ts being invalid, ie, it's for\n \/\/ a time in the past. Thus we can just say everything is ready.\n \/\/\n \/\/ EINVAL can mean that both native_ and mutex.native() are invalid\n \/\/ too, but we've got no recourse if that is true.\n return cReady;\n default:\n std::cout << \"Unknown failure from pthread_cond_timedwait!\\n\";\n }\n\n assert(0);\n }\n }\n\n return cReady;\n }\n };\n}\n\n#ifdef HAVE_OSX_SPINLOCK\n\n#include \n\nnamespace thread {\n\n class SpinLock {\n public: \/\/ Types\n typedef StackLockGuard LockGuard;\n typedef StackUnlockGuard UnlockGuard;\n\n private:\n OSSpinLock native_;\n\n public:\n SpinLock()\n : native_(0)\n {}\n\n void lock() {\n OSSpinLockLock(&native_);\n }\n\n void unlock() {\n OSSpinLockUnlock(&native_);\n }\n\n Code try_lock() {\n if(OSSpinLockTry(&native_)) {\n return cLockBusy;\n }\n\n return cLocked;\n }\n\n std::string describe() {\n std::stringstream ss;\n ss << \"SpinLock \";\n ss << (void*)this;\n return ss.str();\n }\n };\n};\n\n#else\n\nnamespace thread {\n typedef Mutex SpinLock;\n};\n\n#endif\n\n#else\n\n#error \"No thread implementation defined\"\n\n#endif\n\n#endif\nMake thread::Mutex recursive by default#ifndef RBX_UTIL_THREAD_HPP\n#define RBX_UTIL_THREAD_HPP\n\n#define USE_PTHREADS\n\n#ifdef USE_PTHREADS\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace thread {\n enum Code {\n cLocked,\n cUnlocked,\n cLockBusy,\n cNotYours,\n cReady,\n cTimedOut\n };\n\n#if 0\n static void block_all_signals() {\n sigset_t set;\n sigfillset(&set);\n\n pthread_sigmask(SIG_BLOCK, &set, NULL);\n }\n\n static void accept_signal(int sig) {\n sigset_t set;\n sigemptyset(&set);\n sigaddset(&set, sig);\n\n pthread_sigmask(SIG_UNBLOCK, &set, NULL);\n }\n\n static void ignore_signal(int sig) {\n sigset_t set;\n sigemptyset(&set);\n sigaddset(&set, sig);\n\n pthread_sigmask(SIG_BLOCK, &set, NULL);\n }\n\n static void wait_on_signal(int sig) {\n sigset_t set;\n sigemptyset(&set);\n sigaddset(&set, sig);\n\n int bunk;\n sigwait(&set, &bunk);\n }\n#endif\n template \n class ThreadData {\n pthread_key_t native_;\n\n public:\n ThreadData() {\n assert(pthread_key_create(&native_, NULL) == 0);\n }\n\n ~ThreadData() {\n assert(pthread_key_delete(native_) == 0);\n }\n\n T get() {\n return reinterpret_cast(pthread_getspecific(native_));\n }\n\n void set(T val) {\n assert(pthread_setspecific(native_, reinterpret_cast(val)) == 0);\n }\n };\n\n class Thread {\n pthread_t native_;\n bool delete_on_exit_;\n size_t stack_size_;\n\n static void* trampoline(void* arg) {\n Thread* self = reinterpret_cast(arg);\n self->perform();\n if(self->delete_on_exit()) delete self;\n return NULL;\n }\n\n public:\n Thread(size_t stack_size = 0, pthread_t tid = 0)\n : native_(tid)\n , stack_size_(stack_size)\n {\n delete_on_exit_ = (tid != 0);\n }\n\n virtual ~Thread() { }\n\n pthread_t* native() {\n return &native_;\n }\n\n void run() {\n pthread_attr_t attrs;\n pthread_attr_init(&attrs);\n if(stack_size_) {\n pthread_attr_setstacksize(&attrs, stack_size_);\n }\n\n assert(pthread_create(&native_, &attrs, trampoline, (void*)this) == 0);\n }\n\n virtual void perform() { }\n\n void detach() {\n assert(pthread_detach(native_) == 0);\n }\n\n bool equal(Thread& other) {\n if(pthread_equal(native_, *other.native())) {\n return true;\n }\n\n return false;\n }\n\n void join() {\n void* bunk;\n int err = pthread_join(native_, &bunk);\n if(err != 0) {\n if(err == EDEADLK) {\n std::cout << \"Thread deadlock!\\n\";\n }\n\n assert(0);\n }\n }\n\n void cancel() {\n assert(pthread_cancel(native_) == 0);\n }\n\n void kill(int sig) {\n assert(pthread_kill(native_, sig) == 0);\n }\n\n int priority() {\n int _policy;\n struct sched_param params;\n\n assert(pthread_getschedparam(native_, &_policy, ¶ms) == 0);\n\n return params.sched_priority;\n }\n\n bool set_priority(int priority) {\n int _policy;\n struct sched_param params;\n\n assert(pthread_getschedparam(native_, &_policy, ¶ms) == 0);\n int max = sched_get_priority_max(_policy);\n int min = sched_get_priority_min(_policy);\n\n if(min > priority) {\n priority = min;\n }\n else if(max < priority) {\n priority = max;\n }\n\n params.sched_priority = priority;\n\n int err = pthread_setschedparam(native_, _policy, ¶ms);\n if(err == ENOTSUP) return false;\n\n return true;\n }\n\n bool delete_on_exit() {\n return delete_on_exit_;\n }\n\n void set_delete_on_exit() {\n delete_on_exit_ = true;\n }\n };\n\n \/*\n * A stacklet object for locking and unlocking.\n *\/\n\n#ifdef DEBUG_LOCKGUARD\n const bool cDebugLockGuard = true;\n#else\n const bool cDebugLockGuard = false;\n#endif\n\n template \n class LockGuardTemplate {\n public:\n T& lock_;\n bool locked_;\n\n LockGuardTemplate(T& in_lock, bool initial = false)\n : lock_(in_lock)\n , locked_(initial)\n { }\n\n void lock() {\n if(locked_) return;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" Locking \" << lock_.describe() << \" ]]\\n\";\n }\n lock_.lock();\n locked_ = true;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" Locked \" << lock_.describe() << \" ]]\\n\";\n }\n }\n\n void unlock() {\n if(!locked_) return;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" Unlocking \" << lock_.describe() << \" ]]\\n\";\n }\n lock_.unlock();\n locked_ = false;\n }\n };\n\n template \n class StackLockGuard : public LockGuardTemplate {\n public:\n StackLockGuard(T& in_lock)\n : LockGuardTemplate(in_lock, false)\n {\n this->lock();\n }\n\n ~StackLockGuard() {\n this->unlock();\n }\n };\n\n template \n class StackUnlockGuard : public LockGuardTemplate {\n public:\n StackUnlockGuard(T& lock_obj)\n : LockGuardTemplate(lock_obj, true)\n {\n this->unlock();\n }\n\n ~StackUnlockGuard() {\n this->lock();\n }\n };\n\n class Mutex {\n public: \/\/ Types\n typedef StackLockGuard LockGuard;\n typedef StackUnlockGuard UnlockGuard;\n\n private:\n pthread_mutex_t native_;\n\n public:\n Mutex() {\n pthread_mutexattr_t attr;\n pthread_mutexattr_init(&attr);\n pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);\n assert(pthread_mutex_init(&native_, &attr) == 0);\n }\n\n ~Mutex() {\n int err = pthread_mutex_destroy(&native_);\n if(err != 0) {\n if(err == EBUSY) assert(0 && \"mutex is busy!\");\n if(err == EINVAL) assert(0 && \"mutex is dead!\");\n assert(0 && \"mutex is screwed!\");\n }\n }\n\n pthread_mutex_t* native() {\n return &native_;\n }\n\n void lock() {\n int err;\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" MLocking \" << describe() << \" ]]\\n\";\n }\n if((err = pthread_mutex_lock(&native_)) != 0) {\n if(err == EDEADLK) {\n std::cout << \"Thread deadlock!\\n\";\n }\n\n assert(0);\n }\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" MLocked \" << describe() << \" ]]\\n\";\n }\n }\n\n Code try_lock() {\n int err = pthread_mutex_trylock(&native_);\n if(err != 0) {\n if(err == EBUSY) return cLockBusy;\n assert(0);\n }\n\n return cLocked;\n }\n\n Code unlock() {\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" MUnlocking \" << describe() << \" ]]\\n\";\n }\n int err = pthread_mutex_unlock(&native_);\n if(err != 0) {\n if(err == EPERM) return cNotYours;\n assert(0);\n }\n\n return cUnlocked;\n }\n\n std::string describe() {\n std::stringstream ss;\n ss << \"Mutex \";\n ss << (void*)this;\n return ss.str();\n }\n };\n\n class Condition {\n pthread_cond_t native_;\n bool ready_;\n\n public:\n Condition()\n : ready_(false)\n {\n assert(pthread_cond_init(&native_, NULL) == 0);\n }\n\n ~Condition() {\n assert(pthread_cond_destroy(&native_) == 0);\n }\n\n void reset() {\n ready_ = false;\n }\n\n void signal() {\n ready_ = true;\n assert(pthread_cond_signal(&native_) == 0);\n }\n\n void broadcast() {\n ready_ = true;\n assert(pthread_cond_broadcast(&native_) == 0);\n }\n\n void wait(Mutex& mutex) {\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CUnlocking \" << mutex.describe() << \" ]]\\n\";\n }\n while(!ready_) {\n assert(pthread_cond_wait(&native_, mutex.native()) == 0);\n }\n\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CLocked \" << mutex.describe() << \" ]]\\n\";\n }\n }\n\n Code wait_until(Mutex& mutex, const struct timespec* ts) {\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CUnlocking \" << mutex.describe() << \" ]]\\n\";\n }\n\n while(!ready_) {\n int err = pthread_cond_timedwait(&native_, mutex.native(), ts);\n if(cDebugLockGuard) {\n std::cout << \"[[ \" << pthread_self() << \" CLocked \" << mutex.describe() << \" ]]\\n\";\n }\n\n if(err != 0) {\n if(err == ETIMEDOUT) {\n if(ready_) return cReady;\n return cTimedOut;\n }\n\n switch(err) {\n case EINVAL:\n \/\/ This is not really correct, but it works for us:\n \/\/ We treat this error as ONLY ts being invalid, ie, it's for\n \/\/ a time in the past. Thus we can just say everything is ready.\n \/\/\n \/\/ EINVAL can mean that both native_ and mutex.native() are invalid\n \/\/ too, but we've got no recourse if that is true.\n return cReady;\n default:\n std::cout << \"Unknown failure from pthread_cond_timedwait!\\n\";\n }\n\n assert(0);\n }\n }\n\n return cReady;\n }\n };\n}\n\n#ifdef HAVE_OSX_SPINLOCK\n\n#include \n\nnamespace thread {\n\n class SpinLock {\n public: \/\/ Types\n typedef StackLockGuard LockGuard;\n typedef StackUnlockGuard UnlockGuard;\n\n private:\n OSSpinLock native_;\n\n public:\n SpinLock()\n : native_(0)\n {}\n\n void lock() {\n OSSpinLockLock(&native_);\n }\n\n void unlock() {\n OSSpinLockUnlock(&native_);\n }\n\n Code try_lock() {\n if(OSSpinLockTry(&native_)) {\n return cLockBusy;\n }\n\n return cLocked;\n }\n\n std::string describe() {\n std::stringstream ss;\n ss << \"SpinLock \";\n ss << (void*)this;\n return ss.str();\n }\n };\n};\n\n#else\n\nnamespace thread {\n typedef Mutex SpinLock;\n};\n\n#endif\n\n#else\n\n#error \"No thread implementation defined\"\n\n#endif\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT,\n * Applied Mathematics, Norway.\n *\n * Contact information: E-mail: tor.dokken@sintef.no \n * SINTEF ICT, Department of Applied Mathematics, \n * P.O. Box 124 Blindern, \n * 0314 Oslo, Norway. \n *\n * This file is part of GoTools.\n *\n * GoTools is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version. \n *\n * GoTools is distributed in the hope that it will be useful, \n * but WITHOUT ANY WARRANTY; without even the implied warranty of \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with GoTools. If not, see\n * .\n *\n * In accordance with Section 7(b) of the GNU Affero General Public\n * License, a covered work must retain the producer line in every data\n * file that is created or manipulated using GoTools.\n *\n * Other Usage\n * You can be released from the requirements of the license by purchasing\n * a commercial license. Buying such a license is mandatory as soon as you\n * develop commercial activities involving the GoTools library without\n * disclosing the source code of your own applications.\n *\n * This file may be used in accordance with the terms contained in a\n * written agreement between you and SINTEF ICT. \n *\/\n\n#define BOOST_TEST_MODULE compositemodel\/offsetSurfaceSetTest\n#include \n\n#include \"GoTools\/compositemodel\/OffsetSurfaceUtils.h\"\n#include \"GoTools\/utils\/errormacros.h\"\n#include \"GoTools\/geometry\/Utils.h\"\n#include \"GoTools\/geometry\/ObjectHeader.h\"\n#include \"GoTools\/geometry\/BoundedSurface.h\"\n#include \"GoTools\/geometry\/GoTools.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace Go;\nusing std::vector;\nusing std::string;\nusing std::ifstream;\n\n\/\/ #define TEST_NEW_CASES\n\n\/\/ #define TEST_UNSUPPORTED_CASES\n\n\/\/ #define TEST_FAILING_CASES\n\n#define TEST_WORKING_CASES\n\nstruct Config {\npublic:\n Config()\n : output_filename(\"tmp\/testHermiteApprEvalSurf_result.g2\")\n\n {\n\n const std::string data_basedir(\"..\/..\/gotools-private-data\/compositemodel\/Offset\");\n\n#ifdef GOTOOLS_TEST_PRIVATE_DATA\n\n \/\/ NEW CASES!!!\n#ifdef TEST_NEW_CASES\n\n#endif\n\n \/\/ CASES NOT SUPPORTED (EARLY EXIT WITH ERROR MESSAGE)!!! \n#ifdef TEST_UNSUPPORTED_CASES\n\n \/\/ Degenerate patch (triangle): Ok w\/ offset=1e-02,eps=1e-03. Using 0.01*epsgeo as curvature_tol.\n \/\/ Contains kink curve which is not an iso curve. Exits with failure.\n filenames.push_back(data_basedir+\"\/fanta_ro2_sub2b.g2\");\n offset.push_back(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-03);\/\/6;\n\n \/\/ Tricky case with a degenerate surface. The degenerate point is not well defined with the\n \/\/ normal varying as the evaluation approaches from different iso lines. Will require extensive\n \/\/ smoothing. Currently not handled using SplineSurface (equation system too large). We need\n \/\/ LRSplineSurface (and even with that the task may be to tricky). Exits with failure.\n filenames.push_back(data_basedir+\"\/fanta_ro2_sub.g2\");\n offset.push_back(0.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n#endif\n\n \/\/ FAILING CASES!!!\n#ifdef TEST_FAILING_CASES\n \/\/ Added 2017-10-09. Crash 3. Tricky case with a degenerate underlying surface, with a trimmed\n \/\/ boundary meeting in a degenerate corner (parallell tangents).\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_BoundedSurf__20170929-115934.549.g2\");\n offset.push_back(1.0e-03);\n epsgeo.push_back(1.0e-04);\n#endif\n\n \/\/ WORKING CASES!!!\n#ifdef TEST_WORKING_CASES\n \n \/\/ Added 2017-10-09. Crash 2.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf_OffsetTest_20170929-110347.373_406_434.g2\");\n offset.push_back(1.0e-03);\n epsgeo.push_back(1.0e-04); \/\/ Initially given epsgeo = 1.0e-03, conflicts with topology (too many twin edges).\n\n \/\/ Added 2017-10-09. Crash 1.\n filenames.push_back(data_basedir+\"\/TopSolid\/Source-TopSolid_SplineSurf_OffsetTest_20170929-103855.922_949.g2\");\n offset.push_back(1.0e-03);\n epsgeo.push_back(1.0e-04); \/\/ Initially given epsgeo = 1.0e-03, conflicts with topology (too many twin edges).\n\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_BoundedSurf__20170623-173106.658.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ Added 2017-06-23\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170623-173106.544.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ Added 2017-06-23\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170623-173916.090.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ Added 2017-06-23\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170623-175900.205.g2\");\n\/\/ filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170627-130342.267.g2\"); The same set.\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ 2 bilinear quadrats with z = 0.018.\n \/\/ Tricky case which required us to to define a transition zone.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_Surf__20170313-174324.189_221.g2\");\n offset.push_back(0.1);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-05);\/\/3);\/\/6;\n\n \/\/ 4 planes meeting in kinks along linear segments.\n \/\/ Tricky case which required us to to define a transition zone.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170504-1332_kinks.g2\");\n offset.push_back(3.0e-03);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-05);\/\/3);\/\/6;\n\n \/\/ A single surface with a bump in the interior. Use a negative offset value to create a self\n \/\/ intersection in the bump. Easy when using a positive offset dist, tricky when using a negative\n \/\/ offset dist. With a large offset value (< -3.0e-03) the self intersection is global.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_bump.g2\");\n offset.push_back(-3.0e-03);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-05);\/\/3);\/\/6;\n\n \/\/ Self-intersections for offset dist of appr 0.3 and larger.\n filenames.push_back(data_basedir+\"\/test_bezier.g2\");\n offset.push_back(0.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n\n \/\/ Self-int: offset=1e-02,eps=1e-03.\n \/\/ Success with removing self intersections using smoothing: offset=1e-03,eps=1e-04.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_Surf__20170404-123801.816.g2\");\n offset.push_back(0.001);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n\n \/\/ Two orthogonal planes joined by a trimmed cylinder segment (w\/ radius of curvature -1.38843).\n \/\/ 201706: Success after setting the twist vector to zero and reducing precond omega from 0.1 to 0.01.\n filenames.push_back(data_basedir+\"\/yta4.g2\");\n offset.push_back(-1.5);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n\n \/\/ Illegal bounded surface, the trim loop is CW! The offset works but the offset surface is flipped.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_BoundedSurf__20170623-173916.162.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n#endif\n\n#endif\n\n GoTools::init();\n\n }\n\npublic:\n vector filenames;\n vector offset;\n vector epsgeo;\n ObjectHeader header;\n \/\/const std::string input_filename;\n const std::string output_filename;\n \/\/ const std::string input_filename(\"tmp\/testHermiteApprEvalSurf_input.g2\");\n \/\/ const std::string output_filename(\"tmp\/testHermiteApprEvalSurf_result.g2\");\n\n};\n\n\nBOOST_FIXTURE_TEST_CASE(offsetSurfaceSet, Config)\n{\n int num_success = 0;\n int num_failures = 0;\n int num_exceptions = 0; \n for (size_t ki = 0; ki < filenames.size(); ++ki)\n {\n \/\/ Read input arguments\n std::ifstream infile(filenames[ki].c_str());\n BOOST_CHECK_MESSAGE(infile.good(), \"Input file not found or file corrupt\");\n\n vector > sfs;\n while (!infile.eof())\n {\n infile >> header;\n shared_ptr sf;\n if (header.classType() == Class_SplineSurface)\n {\n sf = shared_ptr(new SplineSurface());\n }\n else if (header.classType() == Class_BoundedSurface)\n {\n sf = shared_ptr(new BoundedSurface());\n }\n else\n {\n BOOST_ERROR(\"Input surface type not yet supported: \" << header.classType());\n continue;\n }\n\n sf->read(infile);\n\n sfs.push_back(sf);\n\n Utils::eatwhite(infile);\n } \n\n shared_ptr offset_sf;\n OffsetSurfaceStatus status;\n try\n {\n status = OffsetSurfaceUtils::offsetSurfaceSet(sfs, offset[ki], epsgeo[ki], offset_sf);\n }\n catch (...)\n {\n std::cout << \"offsetSurfaceSet(): Caught exception for filename \" << filenames[ki] << std::endl;\n BOOST_ERROR(\"Exception caught\");\n ++num_exceptions;\n continue;\n }\n\n BOOST_CHECK_MESSAGE(status == OFFSET_OK,\n \"offsetSurfaceSet(): Failure! Returned status (!= 0): \" << status);\n if (status == OFFSET_OK)\n {\n ++num_success;\n if (offset_sf.get())\n {\n std::ofstream fileout(output_filename);\n offset_sf->writeStandardHeader(fileout);\n offset_sf->write(fileout);\n }\n }\n else\n {\n ++num_failures;\n }\n }\n\n BOOST_TEST_MESSAGE(\"\\nnum files: \" << filenames.size() << \", num success: \" << num_success << \", num failures: \" <<\n num_failures << \", num_exceptions: \" << num_exceptions);\n\n}\nRemoved old code.\/*\n * Copyright (C) 1998, 2000-2007, 2010, 2011, 2012, 2013 SINTEF ICT,\n * Applied Mathematics, Norway.\n *\n * Contact information: E-mail: tor.dokken@sintef.no \n * SINTEF ICT, Department of Applied Mathematics, \n * P.O. Box 124 Blindern, \n * 0314 Oslo, Norway. \n *\n * This file is part of GoTools.\n *\n * GoTools is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version. \n *\n * GoTools is distributed in the hope that it will be useful, \n * but WITHOUT ANY WARRANTY; without even the implied warranty of \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with GoTools. If not, see\n * .\n *\n * In accordance with Section 7(b) of the GNU Affero General Public\n * License, a covered work must retain the producer line in every data\n * file that is created or manipulated using GoTools.\n *\n * Other Usage\n * You can be released from the requirements of the license by purchasing\n * a commercial license. Buying such a license is mandatory as soon as you\n * develop commercial activities involving the GoTools library without\n * disclosing the source code of your own applications.\n *\n * This file may be used in accordance with the terms contained in a\n * written agreement between you and SINTEF ICT. \n *\/\n\n#define BOOST_TEST_MODULE compositemodel\/offsetSurfaceSetTest\n#include \n\n#include \"GoTools\/compositemodel\/OffsetSurfaceUtils.h\"\n#include \"GoTools\/utils\/errormacros.h\"\n#include \"GoTools\/geometry\/Utils.h\"\n#include \"GoTools\/geometry\/ObjectHeader.h\"\n#include \"GoTools\/geometry\/BoundedSurface.h\"\n#include \"GoTools\/geometry\/GoTools.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace Go;\nusing std::vector;\nusing std::string;\nusing std::ifstream;\n\n\/\/ #define TEST_NEW_CASES\n\n\/\/ #define TEST_UNSUPPORTED_CASES\n\n\/\/ #define TEST_FAILING_CASES\n\n#define TEST_WORKING_CASES\n\nstruct Config {\npublic:\n Config()\n : output_filename(\"tmp\/offsetSurfaceSetTest_result.g2\")\n\n {\n\n const std::string data_basedir(\"..\/..\/gotools-private-data\/compositemodel\/Offset\");\n\n#ifdef GOTOOLS_TEST_PRIVATE_DATA\n\n \/\/ NEW CASES!!!\n#ifdef TEST_NEW_CASES\n\n#endif\n\n \/\/ CASES NOT SUPPORTED (EARLY EXIT WITH ERROR MESSAGE)!!! \n#ifdef TEST_UNSUPPORTED_CASES\n\n \/\/ Degenerate patch (triangle): Ok w\/ offset=1e-02,eps=1e-03. Using 0.01*epsgeo as curvature_tol.\n \/\/ Contains kink curve which is not an iso curve. Exits with failure.\n filenames.push_back(data_basedir+\"\/fanta_ro2_sub2b.g2\");\n offset.push_back(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-03);\/\/6;\n\n \/\/ Tricky case with a degenerate surface. The degenerate point is not well defined with the\n \/\/ normal varying as the evaluation approaches from different iso lines. Will require extensive\n \/\/ smoothing. Currently not handled using SplineSurface (equation system too large). We need\n \/\/ LRSplineSurface (and even with that the task may be to tricky). Exits with failure.\n filenames.push_back(data_basedir+\"\/fanta_ro2_sub.g2\");\n offset.push_back(0.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n#endif\n\n \/\/ FAILING CASES!!!\n#ifdef TEST_FAILING_CASES\n \/\/ Added 2017-10-09. Crash 3. Tricky case with a degenerate underlying surface, with a trimmed\n \/\/ boundary meeting in a degenerate corner (parallell tangents).\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_BoundedSurf__20170929-115934.549.g2\");\n offset.push_back(1.0e-03);\n epsgeo.push_back(1.0e-04);\n#endif\n\n \/\/ WORKING CASES!!!\n#ifdef TEST_WORKING_CASES\n \n \/\/ Added 2017-10-09. Crash 2.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf_OffsetTest_20170929-110347.373_406_434.g2\");\n offset.push_back(1.0e-03);\n epsgeo.push_back(1.0e-04); \/\/ Initially given epsgeo = 1.0e-03, conflicts with topology (too many twin edges).\n\n \/\/ Added 2017-10-09. Crash 1.\n filenames.push_back(data_basedir+\"\/TopSolid\/Source-TopSolid_SplineSurf_OffsetTest_20170929-103855.922_949.g2\");\n offset.push_back(1.0e-03);\n epsgeo.push_back(1.0e-04); \/\/ Initially given epsgeo = 1.0e-03, conflicts with topology (too many twin edges).\n\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_BoundedSurf__20170623-173106.658.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ Added 2017-06-23\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170623-173106.544.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ Added 2017-06-23\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170623-173916.090.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ Added 2017-06-23\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170623-175900.205.g2\");\n\/\/ filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170627-130342.267.g2\"); The same set.\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n\n \/\/ 2 bilinear quadrats with z = 0.018.\n \/\/ Tricky case which required us to to define a transition zone.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_Surf__20170313-174324.189_221.g2\");\n offset.push_back(0.1);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-05);\/\/3);\/\/6;\n\n \/\/ 4 planes meeting in kinks along linear segments.\n \/\/ Tricky case which required us to to define a transition zone.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_SplineSurf__20170504-1332_kinks.g2\");\n offset.push_back(3.0e-03);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-05);\/\/3);\/\/6;\n\n \/\/ A single surface with a bump in the interior. Use a negative offset value to create a self\n \/\/ intersection in the bump. Easy when using a positive offset dist, tricky when using a negative\n \/\/ offset dist. With a large offset value (< -3.0e-03) the self intersection is global.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_bump.g2\");\n offset.push_back(-3.0e-03);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-05);\/\/3);\/\/6;\n\n \/\/ Self-intersections for offset dist of appr 0.3 and larger.\n filenames.push_back(data_basedir+\"\/test_bezier.g2\");\n offset.push_back(0.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n\n \/\/ Self-int: offset=1e-02,eps=1e-03.\n \/\/ Success with removing self intersections using smoothing: offset=1e-03,eps=1e-04.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_Surf__20170404-123801.816.g2\");\n offset.push_back(0.001);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n\n \/\/ Two orthogonal planes joined by a trimmed cylinder segment (w\/ radius of curvature -1.38843).\n \/\/ 201706: Success after setting the twist vector to zero and reducing precond omega from 0.1 to 0.01.\n filenames.push_back(data_basedir+\"\/yta4.g2\");\n offset.push_back(-1.5);\/\/1.3);\/\/(0.01);\/\/0.1;\/\/1.23; \/\/0.2;\n epsgeo.push_back(1.0e-04);\/\/3);\/\/6;\n\n \/\/ Illegal bounded surface, the trim loop is CW! The offset works but the offset surface is flipped.\n filenames.push_back(data_basedir+\"\/TopSolid\/TopSolid_BoundedSurf__20170623-173916.162.g2\");\n offset.push_back(5.0e-03);\n epsgeo.push_back(1.0e-03);\n#endif\n\n#endif\n\n GoTools::init();\n\n }\n\npublic:\n vector filenames;\n vector offset;\n vector epsgeo;\n ObjectHeader header;\n const std::string output_filename;\n\n};\n\n\nBOOST_FIXTURE_TEST_CASE(offsetSurfaceSet, Config)\n{\n int num_success = 0;\n int num_failures = 0;\n int num_exceptions = 0; \n for (size_t ki = 0; ki < filenames.size(); ++ki)\n {\n \/\/ Read input arguments\n std::ifstream infile(filenames[ki].c_str());\n BOOST_CHECK_MESSAGE(infile.good(), \"Input file not found or file corrupt\");\n\n vector > sfs;\n while (!infile.eof())\n {\n infile >> header;\n shared_ptr sf;\n if (header.classType() == Class_SplineSurface)\n {\n sf = shared_ptr(new SplineSurface());\n }\n else if (header.classType() == Class_BoundedSurface)\n {\n sf = shared_ptr(new BoundedSurface());\n }\n else\n {\n BOOST_ERROR(\"Input surface type not yet supported: \" << header.classType());\n continue;\n }\n\n sf->read(infile);\n\n sfs.push_back(sf);\n\n Utils::eatwhite(infile);\n } \n\n shared_ptr offset_sf;\n OffsetSurfaceStatus status;\n try\n {\n status = OffsetSurfaceUtils::offsetSurfaceSet(sfs, offset[ki], epsgeo[ki], offset_sf);\n }\n catch (...)\n {\n std::cout << \"offsetSurfaceSet(): Caught exception for filename \" << filenames[ki] << std::endl;\n BOOST_ERROR(\"Exception caught\");\n ++num_exceptions;\n continue;\n }\n\n BOOST_CHECK_MESSAGE(status == OFFSET_OK,\n \"offsetSurfaceSet(): Failure! Returned status (!= 0): \" << status);\n if (status == OFFSET_OK)\n {\n ++num_success;\n if (offset_sf.get())\n {\n std::ofstream fileout(output_filename);\n offset_sf->writeStandardHeader(fileout);\n offset_sf->write(fileout);\n }\n }\n else\n {\n ++num_failures;\n }\n }\n\n BOOST_TEST_MESSAGE(\"\\nnum files: \" << filenames.size() << \", num success: \" << num_success << \", num failures: \" <<\n num_failures << \", num_exceptions: \" << num_exceptions);\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 1999 Lars Knoll (knoll@kde.org)\n * (C) 1999 Antti Koivisto (koivisto@kde.org)\n * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)\n * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)\n * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.\n * Copyright (C) 2010, 2012 Google Inc. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/RenderLayerModelObject.h\"\n\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderView.h\"\n\nnamespace blink {\n\nbool RenderLayerModelObject::s_wasFloating = false;\n\nRenderLayerModelObject::RenderLayerModelObject(ContainerNode* node)\n : RenderObject(node)\n{\n}\n\nRenderLayerModelObject::~RenderLayerModelObject()\n{\n \/\/ Our layer should have been destroyed and cleared by now\n ASSERT(!hasLayer());\n ASSERT(!m_layer);\n}\n\nvoid RenderLayerModelObject::destroyLayer()\n{\n setHasLayer(false);\n m_layer = nullptr;\n}\n\nvoid RenderLayerModelObject::createLayer(LayerType type)\n{\n ASSERT(!m_layer);\n m_layer = adoptPtr(new RenderLayer(this, type));\n setHasLayer(true);\n m_layer->insertOnlyThisLayer();\n}\n\nbool RenderLayerModelObject::hasSelfPaintingLayer() const\n{\n return m_layer && m_layer->isSelfPaintingLayer();\n}\n\nScrollableArea* RenderLayerModelObject::scrollableArea() const\n{\n return m_layer ? m_layer->scrollableArea() : 0;\n}\n\nvoid RenderLayerModelObject::willBeDestroyed()\n{\n if (isPositioned()) {\n \/\/ Don't use this->view() because the document's renderView has been set to 0 during destruction.\n if (LocalFrame* frame = this->frame()) {\n if (FrameView* frameView = frame->view()) {\n if (style()->hasViewportConstrainedPosition())\n frameView->removeViewportConstrainedObject(this);\n }\n }\n }\n\n RenderObject::willBeDestroyed();\n\n destroyLayer();\n}\n\nvoid RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)\n{\n s_wasFloating = isFloating();\n\n if (RenderStyle* oldStyle = style()) {\n if (parent() && diff.needsPaintInvalidationLayer()) {\n if (oldStyle->hasAutoClip() != newStyle.hasAutoClip()\n || oldStyle->clip() != newStyle.clip())\n layer()->clipper().clearClipRectsIncludingDescendants();\n }\n }\n\n RenderObject::styleWillChange(diff, newStyle);\n}\n\nvoid RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)\n{\n bool hadTransform = hasTransform();\n\n RenderObject::styleDidChange(diff, oldStyle);\n updateFromStyle();\n\n LayerType type = layerTypeRequired();\n if (type != NoLayer) {\n if (!layer() && layerCreationAllowedForSubtree()) {\n if (s_wasFloating && isFloating())\n setChildNeedsLayout();\n createLayer(type);\n if (parent() && !needsLayout()) {\n \/\/ FIXME: This invalidation is overly broad. We should update to\n \/\/ do the correct invalidation at RenderStyle::diff time. crbug.com\/349061\n layer()->renderer()->setShouldDoFullPaintInvalidation(true);\n \/\/ FIXME: We should call a specialized version of this function.\n layer()->updateLayerPositionsAfterLayout();\n }\n }\n } else if (layer() && layer()->parent()) {\n setHasTransform(false); \/\/ Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.\n setHasReflection(false);\n layer()->removeOnlyThisLayer(); \/\/ calls destroyLayer() which clears m_layer\n if (s_wasFloating && isFloating())\n setChildNeedsLayout();\n if (hadTransform)\n setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();\n }\n\n if (layer()) {\n \/\/ FIXME: Ideally we shouldn't need this setter but we can't easily infer an overflow-only layer\n \/\/ from the style.\n layer()->setLayerType(type);\n layer()->styleChanged(diff, oldStyle);\n }\n\n if (FrameView *frameView = view()->frameView()) {\n bool newStyleIsViewportConstained = style()->hasViewportConstrainedPosition();\n bool oldStyleIsViewportConstrained = oldStyle && oldStyle->hasViewportConstrainedPosition();\n if (newStyleIsViewportConstained != oldStyleIsViewportConstrained) {\n if (newStyleIsViewportConstained && layer())\n frameView->addViewportConstrainedObject(this);\n else\n frameView->removeViewportConstrainedObject(this);\n }\n }\n}\n\nvoid RenderLayerModelObject::addLayerHitTestRects(LayerHitTestRects& rects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const\n{\n if (hasLayer()) {\n if (isRenderView()) {\n \/\/ RenderView is handled with a special fast-path, but it needs to know the current layer.\n RenderObject::addLayerHitTestRects(rects, layer(), LayoutPoint(), LayoutRect());\n } else {\n \/\/ Since a RenderObject never lives outside it's container RenderLayer, we can switch\n \/\/ to marking entire layers instead. This may sometimes mark more than necessary (when\n \/\/ a layer is made of disjoint objects) but in practice is a significant performance\n \/\/ savings.\n layer()->addLayerHitTestRects(rects);\n }\n } else {\n RenderObject::addLayerHitTestRects(rects, currentLayer, layerOffset, containerRect);\n }\n}\n\nInvalidationReason RenderLayerModelObject::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)\n{\n const LayoutRect oldPaintInvalidationRect = previousPaintInvalidationRect();\n const LayoutPoint oldPositionFromPaintInvalidationContainer = previousPositionFromPaintInvalidationContainer();\n setPreviousPaintInvalidationRect(boundsRectForPaintInvalidation(&newPaintInvalidationContainer, &paintInvalidationState));\n setPreviousPositionFromPaintInvalidationContainer(RenderLayer::positionFromPaintInvalidationContainer(this, &newPaintInvalidationContainer, &paintInvalidationState));\n\n \/\/ If we are set to do a full paint invalidation that means the RenderView will issue\n \/\/ paint invalidations. We can then skip issuing of paint invalidations for the child\n \/\/ renderers as they'll be covered by the RenderView.\n if (view()->doingFullPaintInvalidation())\n return InvalidationNone;\n\n return RenderObject::invalidatePaintIfNeeded(newPaintInvalidationContainer, oldPaintInvalidationRect, oldPositionFromPaintInvalidationContainer, paintInvalidationState);\n}\n\nvoid RenderLayerModelObject::invalidateTreeIfNeeded(const PaintInvalidationState& paintInvalidationState)\n{\n \/\/ FIXME: SVG should probably also go through this unified paint invalidation system.\n ASSERT(!needsLayout());\n\n if (!shouldCheckForPaintInvalidation(paintInvalidationState))\n return;\n\n bool establishesNewPaintInvalidationContainer = isPaintInvalidationContainer();\n const RenderLayerModelObject& newPaintInvalidationContainer = *adjustCompositedContainerForSpecialAncestors(establishesNewPaintInvalidationContainer ? this : &paintInvalidationState.paintInvalidationContainer());\n ASSERT(&newPaintInvalidationContainer == containerForPaintInvalidation());\n\n InvalidationReason reason = invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);\n\n PaintInvalidationState childTreeWalkState(paintInvalidationState, *this, newPaintInvalidationContainer);\n if (reason == InvalidationLocationChange || reason == InvalidationFull)\n childTreeWalkState.setForceCheckForPaintInvalidation();\n RenderObject::invalidateTreeIfNeeded(childTreeWalkState);\n}\n\n} \/\/ namespace blink\n\nRemove redundant invalidation in RenderLayerModelObject::styleDidChange()\/*\n * Copyright (C) 1999 Lars Knoll (knoll@kde.org)\n * (C) 1999 Antti Koivisto (koivisto@kde.org)\n * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)\n * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)\n * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.\n * Copyright (C) 2010, 2012 Google Inc. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/RenderLayerModelObject.h\"\n\n#include \"core\/frame\/LocalFrame.h\"\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderView.h\"\n\nnamespace blink {\n\nbool RenderLayerModelObject::s_wasFloating = false;\n\nRenderLayerModelObject::RenderLayerModelObject(ContainerNode* node)\n : RenderObject(node)\n{\n}\n\nRenderLayerModelObject::~RenderLayerModelObject()\n{\n \/\/ Our layer should have been destroyed and cleared by now\n ASSERT(!hasLayer());\n ASSERT(!m_layer);\n}\n\nvoid RenderLayerModelObject::destroyLayer()\n{\n setHasLayer(false);\n m_layer = nullptr;\n}\n\nvoid RenderLayerModelObject::createLayer(LayerType type)\n{\n ASSERT(!m_layer);\n m_layer = adoptPtr(new RenderLayer(this, type));\n setHasLayer(true);\n m_layer->insertOnlyThisLayer();\n}\n\nbool RenderLayerModelObject::hasSelfPaintingLayer() const\n{\n return m_layer && m_layer->isSelfPaintingLayer();\n}\n\nScrollableArea* RenderLayerModelObject::scrollableArea() const\n{\n return m_layer ? m_layer->scrollableArea() : 0;\n}\n\nvoid RenderLayerModelObject::willBeDestroyed()\n{\n if (isPositioned()) {\n \/\/ Don't use this->view() because the document's renderView has been set to 0 during destruction.\n if (LocalFrame* frame = this->frame()) {\n if (FrameView* frameView = frame->view()) {\n if (style()->hasViewportConstrainedPosition())\n frameView->removeViewportConstrainedObject(this);\n }\n }\n }\n\n RenderObject::willBeDestroyed();\n\n destroyLayer();\n}\n\nvoid RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)\n{\n s_wasFloating = isFloating();\n\n if (RenderStyle* oldStyle = style()) {\n if (parent() && diff.needsPaintInvalidationLayer()) {\n if (oldStyle->hasAutoClip() != newStyle.hasAutoClip()\n || oldStyle->clip() != newStyle.clip())\n layer()->clipper().clearClipRectsIncludingDescendants();\n }\n }\n\n RenderObject::styleWillChange(diff, newStyle);\n}\n\nvoid RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)\n{\n bool hadTransform = hasTransform();\n\n RenderObject::styleDidChange(diff, oldStyle);\n updateFromStyle();\n\n LayerType type = layerTypeRequired();\n if (type != NoLayer) {\n if (!layer() && layerCreationAllowedForSubtree()) {\n if (s_wasFloating && isFloating())\n setChildNeedsLayout();\n createLayer(type);\n if (parent() && !needsLayout()) {\n \/\/ FIXME: We should call a specialized version of this function.\n layer()->updateLayerPositionsAfterLayout();\n }\n }\n } else if (layer() && layer()->parent()) {\n setHasTransform(false); \/\/ Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.\n setHasReflection(false);\n layer()->removeOnlyThisLayer(); \/\/ calls destroyLayer() which clears m_layer\n if (s_wasFloating && isFloating())\n setChildNeedsLayout();\n if (hadTransform)\n setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();\n }\n\n if (layer()) {\n \/\/ FIXME: Ideally we shouldn't need this setter but we can't easily infer an overflow-only layer\n \/\/ from the style.\n layer()->setLayerType(type);\n layer()->styleChanged(diff, oldStyle);\n }\n\n if (FrameView *frameView = view()->frameView()) {\n bool newStyleIsViewportConstained = style()->hasViewportConstrainedPosition();\n bool oldStyleIsViewportConstrained = oldStyle && oldStyle->hasViewportConstrainedPosition();\n if (newStyleIsViewportConstained != oldStyleIsViewportConstrained) {\n if (newStyleIsViewportConstained && layer())\n frameView->addViewportConstrainedObject(this);\n else\n frameView->removeViewportConstrainedObject(this);\n }\n }\n}\n\nvoid RenderLayerModelObject::addLayerHitTestRects(LayerHitTestRects& rects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const\n{\n if (hasLayer()) {\n if (isRenderView()) {\n \/\/ RenderView is handled with a special fast-path, but it needs to know the current layer.\n RenderObject::addLayerHitTestRects(rects, layer(), LayoutPoint(), LayoutRect());\n } else {\n \/\/ Since a RenderObject never lives outside it's container RenderLayer, we can switch\n \/\/ to marking entire layers instead. This may sometimes mark more than necessary (when\n \/\/ a layer is made of disjoint objects) but in practice is a significant performance\n \/\/ savings.\n layer()->addLayerHitTestRects(rects);\n }\n } else {\n RenderObject::addLayerHitTestRects(rects, currentLayer, layerOffset, containerRect);\n }\n}\n\nInvalidationReason RenderLayerModelObject::invalidatePaintIfNeeded(const PaintInvalidationState& paintInvalidationState, const RenderLayerModelObject& newPaintInvalidationContainer)\n{\n const LayoutRect oldPaintInvalidationRect = previousPaintInvalidationRect();\n const LayoutPoint oldPositionFromPaintInvalidationContainer = previousPositionFromPaintInvalidationContainer();\n setPreviousPaintInvalidationRect(boundsRectForPaintInvalidation(&newPaintInvalidationContainer, &paintInvalidationState));\n setPreviousPositionFromPaintInvalidationContainer(RenderLayer::positionFromPaintInvalidationContainer(this, &newPaintInvalidationContainer, &paintInvalidationState));\n\n \/\/ If we are set to do a full paint invalidation that means the RenderView will issue\n \/\/ paint invalidations. We can then skip issuing of paint invalidations for the child\n \/\/ renderers as they'll be covered by the RenderView.\n if (view()->doingFullPaintInvalidation())\n return InvalidationNone;\n\n return RenderObject::invalidatePaintIfNeeded(newPaintInvalidationContainer, oldPaintInvalidationRect, oldPositionFromPaintInvalidationContainer, paintInvalidationState);\n}\n\nvoid RenderLayerModelObject::invalidateTreeIfNeeded(const PaintInvalidationState& paintInvalidationState)\n{\n \/\/ FIXME: SVG should probably also go through this unified paint invalidation system.\n ASSERT(!needsLayout());\n\n if (!shouldCheckForPaintInvalidation(paintInvalidationState))\n return;\n\n bool establishesNewPaintInvalidationContainer = isPaintInvalidationContainer();\n const RenderLayerModelObject& newPaintInvalidationContainer = *adjustCompositedContainerForSpecialAncestors(establishesNewPaintInvalidationContainer ? this : &paintInvalidationState.paintInvalidationContainer());\n ASSERT(&newPaintInvalidationContainer == containerForPaintInvalidation());\n\n InvalidationReason reason = invalidatePaintIfNeeded(paintInvalidationState, newPaintInvalidationContainer);\n\n PaintInvalidationState childTreeWalkState(paintInvalidationState, *this, newPaintInvalidationContainer);\n if (reason == InvalidationLocationChange || reason == InvalidationFull)\n childTreeWalkState.setForceCheckForPaintInvalidation();\n RenderObject::invalidateTreeIfNeeded(childTreeWalkState);\n}\n\n} \/\/ namespace blink\n\n<|endoftext|>"} {"text":"\/************************************************************************\/\n\/* *\/\n\/* Copyright 2014 by Thorsten Beier and Ullrich Koethe *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* ullrich.koethe@iwr.uni-heidelberg.de or *\/\n\/* vigra@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/\n\/* *\/\n\/************************************************************************\/\n\n\/**\n * This header provides definitions of graph-related algorithms\n *\/\n\n#ifndef VIGRA_GRAPH_RAG_PROJECT_BACK_HXX\n#define VIGRA_GRAPH_RAG_PROJECT_BACK_HXX\n\n\/*std*\/\n#include \n#include \n#include \n#include \n\n\n\/*vigra*\/\n#include \"graphs.hxx\"\n#include \"graph_generalization.hxx\"\n#include \"multi_gridgraph.hxx\"\n#include \"priority_queue.hxx\"\n#include \"union_find.hxx\"\n#include \"adjacency_list_graph.hxx\"\n#include \"graph_maps.hxx\"\n#include \"timing.hxx\"\n\n\n\n\n#include \"timing.hxx\"\n\n\n\nnamespace vigra{\n\n namespace detail_rag_project_back{\n\n template<\n class BASE_GRAPH,\n class BASE_GRAPH_LABELS,\n class RAG_FEATURES,\n class BASE_GRAPH_FEATURES\n >\n struct RagProjectBack{\n\n\n static void projectBack(\n const AdjacencyListGraph & rag,\n const BASE_GRAPH & bg,\n const Int64 ignoreLabel,\n const BASE_GRAPH_LABELS bgLabels,\n const RAG_FEATURES & ragFeatures,\n BASE_GRAPH_FEATURES & bgFeatures\n ){\n typedef BASE_GRAPH Bg;\n typedef typename Bg::NodeIt BgNodeIt;\n typedef typename Bg::Node BgNode;\n\n if(ignoreLabel==-1){\n for(BgNodeIt iter(bg); iter!=lemon::INVALID; ++iter){\n const BgNode bgNode(*iter);\n bgFeatures[bgNode] = ragFeatures[rag.nodeFromId(bgLabels[bgNode])];\n }\n }\n else{\n for(BgNodeIt iter(bg); iter!=lemon::INVALID; ++iter){\n const BgNode bgNode(*iter);\n if(static_cast(bgLabels[bgNode])!=ignoreLabel)\n bgFeatures[bgNode] = ragFeatures[rag.nodeFromId(bgLabels[bgNode])];\n }\n }\n }\n };\n\n\n template<\n class BASE_GRAPH_LABELS,\n class RAG_FEATURES,\n class BASE_GRAPH_FEATURES\n >\n struct RagProjectBack<\n vigra::GridGraph<3, boost::undirected_tag>,\n BASE_GRAPH_LABELS,\n RAG_FEATURES,\n BASE_GRAPH_FEATURES\n >{\n typedef vigra::GridGraph<3, boost::undirected_tag> BASE_GRAPH;\n\n static void projectBack(\n const AdjacencyListGraph & rag,\n const BASE_GRAPH & bg,\n const Int64 ignoreLabel,\n const BASE_GRAPH_LABELS bgLabels,\n const RAG_FEATURES & ragFeatures,\n BASE_GRAPH_FEATURES & bgFeatures\n ){\n typedef BASE_GRAPH Bg;\n typedef typename Bg::Node BgNode;\n\n\n vigra::TinyVector shape = bg.shape();\n\n\n if(ignoreLabel==-1){\n \n #pragma omp parallel for\n for(Int64 z=0; z(bgLabels[node])!=ignoreLabel)\n bgFeatures[node] = ragFeatures[rag.nodeFromId(bgLabels[node])];\n } \n }\n }\n }\n };\n\n\n\n }\n\n\n \/\/\/ project node features of a region adjacency\n \/\/\/ graph back to the base graph.\n \/\/\/\n \/\/\/ This function can be used to show a segmentation\n \/\/\/ or node features of RAG on pixel \/ voxel level\n template< class BASE_GRAPH,\n class BASE_GRAPH_LABELS,\n class RAG_FEATURES,\n class BASE_GRAPH_FEATURES \n >\n inline void projectBack(\n const AdjacencyListGraph & rag,\n const BASE_GRAPH & bg,\n const Int64 ignoreLabel,\n const BASE_GRAPH_LABELS bgLabels,\n const RAG_FEATURES & ragFeatures,\n BASE_GRAPH_FEATURES & bgFeatures\n ){\n using namespace detail_rag_project_back;\n detail_rag_project_back::RagProjectBack< BASE_GRAPH,BASE_GRAPH_LABELS,RAG_FEATURES,BASE_GRAPH_FEATURES>::projectBack(rag,\n bg,ignoreLabel,bgLabels,ragFeatures,bgFeatures);\n }\n\n\n\n}\n\n#endif \/* VIGRA_GRAPH_RAG_PROJECT_BACK_HXX *\/\n\ncleanup\/************************************************************************\/\n\/* *\/\n\/* Copyright 2014 by Thorsten Beier and Ullrich Koethe *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* ullrich.koethe@iwr.uni-heidelberg.de or *\/\n\/* vigra@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/\n\/* *\/\n\/************************************************************************\/\n\n\/**\n * This header provides definitions of graph-related algorithms\n *\/\n\n#ifndef VIGRA_GRAPH_RAG_PROJECT_BACK_HXX\n#define VIGRA_GRAPH_RAG_PROJECT_BACK_HXX\n\n\/*std*\/\n#include \n#include \n#include \n#include \n\n\n\/*vigra*\/\n#include \"graphs.hxx\"\n#include \"graph_generalization.hxx\"\n#include \"multi_gridgraph.hxx\"\n#include \"priority_queue.hxx\"\n#include \"union_find.hxx\"\n#include \"adjacency_list_graph.hxx\"\n#include \"graph_maps.hxx\"\n\n\n\nnamespace vigra{\n\n \/\/\/ \\cond\n namespace detail_rag_project_back{\n\n template<\n class BASE_GRAPH,\n class BASE_GRAPH_LABELS,\n class RAG_FEATURES,\n class BASE_GRAPH_FEATURES\n >\n struct RagProjectBack{\n\n\n static void projectBack(\n const AdjacencyListGraph & rag,\n const BASE_GRAPH & bg,\n const Int64 ignoreLabel,\n const BASE_GRAPH_LABELS bgLabels,\n const RAG_FEATURES & ragFeatures,\n BASE_GRAPH_FEATURES & bgFeatures\n ){\n typedef BASE_GRAPH Bg;\n typedef typename Bg::NodeIt BgNodeIt;\n typedef typename Bg::Node BgNode;\n\n if(ignoreLabel==-1){\n for(BgNodeIt iter(bg); iter!=lemon::INVALID; ++iter){\n const BgNode bgNode(*iter);\n bgFeatures[bgNode] = ragFeatures[rag.nodeFromId(bgLabels[bgNode])];\n }\n }\n else{\n for(BgNodeIt iter(bg); iter!=lemon::INVALID; ++iter){\n const BgNode bgNode(*iter);\n if(static_cast(bgLabels[bgNode])!=ignoreLabel)\n bgFeatures[bgNode] = ragFeatures[rag.nodeFromId(bgLabels[bgNode])];\n }\n }\n }\n };\n\n\n template<\n class BASE_GRAPH_LABELS,\n class RAG_FEATURES,\n class BASE_GRAPH_FEATURES\n >\n struct RagProjectBack<\n vigra::GridGraph<3, boost::undirected_tag>,\n BASE_GRAPH_LABELS,\n RAG_FEATURES,\n BASE_GRAPH_FEATURES\n >{\n typedef vigra::GridGraph<3, boost::undirected_tag> BASE_GRAPH;\n\n static void projectBack(\n const AdjacencyListGraph & rag,\n const BASE_GRAPH & bg,\n const Int64 ignoreLabel,\n const BASE_GRAPH_LABELS bgLabels,\n const RAG_FEATURES & ragFeatures,\n BASE_GRAPH_FEATURES & bgFeatures\n ){\n typedef BASE_GRAPH Bg;\n typedef typename Bg::Node BgNode;\n\n\n vigra::TinyVector shape = bg.shape();\n\n\n if(ignoreLabel==-1){\n \n #pragma omp parallel for\n for(Int64 z=0; z(bgLabels[node])!=ignoreLabel)\n bgFeatures[node] = ragFeatures[rag.nodeFromId(bgLabels[node])];\n } \n }\n }\n }\n };\n\n\n\n }\n \/\/\/ \\endcond\n\n \/\/\/ project node features of a region adjacency\n \/\/\/ graph back to the base graph.\n \/\/\/\n \/\/\/ This function can be used to show a segmentation\n \/\/\/ or node features of RAG on pixel \/ voxel level\n template< class BASE_GRAPH,\n class BASE_GRAPH_LABELS,\n class RAG_FEATURES,\n class BASE_GRAPH_FEATURES \n >\n inline void projectBack(\n const AdjacencyListGraph & rag,\n const BASE_GRAPH & bg,\n const Int64 ignoreLabel,\n const BASE_GRAPH_LABELS bgLabels,\n const RAG_FEATURES & ragFeatures,\n BASE_GRAPH_FEATURES & bgFeatures\n ){\n using namespace detail_rag_project_back;\n detail_rag_project_back::RagProjectBack< BASE_GRAPH,BASE_GRAPH_LABELS,RAG_FEATURES,BASE_GRAPH_FEATURES>::projectBack(rag,\n bg,ignoreLabel,bgLabels,ragFeatures,bgFeatures);\n }\n\n\n\n}\n\n#endif \/* VIGRA_GRAPH_RAG_PROJECT_BACK_HXX *\/\n\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2013-2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nCollapsibleGroupBoxWidgetQt::CollapsibleGroupBoxWidgetQt(std::string displayName, bool isCheckable)\n : PropertyWidgetQt()\n , PropertyOwnerObserver()\n , displayName_(displayName)\n , collapsed_(false)\n , checked_(false)\n , propertyOwner_(nullptr)\n , showIfEmpty_(false)\n , checkable_(isCheckable) {\n setObjectName(\"CompositeWidget\");\n\n generateWidget();\n updateFromProperty();\n}\n\nCollapsibleGroupBoxWidgetQt::CollapsibleGroupBoxWidgetQt(Property* property, bool isCheckable)\n : PropertyWidgetQt(property)\n , PropertyOwnerObserver()\n , displayName_(property->getDisplayName())\n , collapsed_(false)\n , checked_(false)\n , propertyOwner_(nullptr)\n , showIfEmpty_(false)\n , checkable_(isCheckable) {\n setObjectName(\"CompositeWidget\");\n\n generateWidget();\n updateFromProperty();\n}\n\nvoid CollapsibleGroupBoxWidgetQt::generateWidget() {\n propertyWidgetGroupLayout_ = new QGridLayout();\n propertyWidgetGroupLayout_->setAlignment(Qt::AlignTop);\n propertyWidgetGroupLayout_->setContentsMargins(\n PropertyWidgetQt::spacing, PropertyWidgetQt::spacing, 0, PropertyWidgetQt::spacing);\n propertyWidgetGroupLayout_->setHorizontalSpacing(0);\n propertyWidgetGroupLayout_->setVerticalSpacing(PropertyWidgetQt::spacing);\n\n propertyWidgetGroup_ = new QWidget(this);\n propertyWidgetGroup_->setObjectName(\"CompositeContents\");\n propertyWidgetGroup_->setLayout(propertyWidgetGroupLayout_);\n\n defaultLabel_ = new QLabel(\"No properties available\");\n\n propertyWidgetGroupLayout_->addWidget(defaultLabel_, 0, 0);\n propertyWidgetGroupLayout_->addItem(\n new QSpacerItem(PropertyWidgetQt::spacing, 1, QSizePolicy::Fixed), 0, 1);\n propertyWidgetGroupLayout_->setColumnStretch(0, 1);\n propertyWidgetGroupLayout_->setColumnStretch(1, 0);\n\n btnCollapse_ = new QToolButton(this);\n btnCollapse_->setObjectName(\"collapseButton\");\n btnCollapse_->setIcon(QIcon(\":\/stylesheets\/images\/arrow_lighter_down.png\"));\n connect(btnCollapse_, &QToolButton::clicked, this,\n &CollapsibleGroupBoxWidgetQt::toggleCollapsed);\n\n if (property_) {\n label_ = new EditableLabelQt(this, property_, false);\n } else {\n label_ = new EditableLabelQt(this, displayName_, false);\n }\n label_->setObjectName(\"compositeLabel\");\n QSizePolicy labelPol = label_->sizePolicy();\n labelPol.setHorizontalStretch(10);\n label_->setSizePolicy(labelPol);\n connect(label_, &EditableLabelQt::textChanged, this,\n [&]() { setDisplayName(label_->getText()); });\n\n resetButton_ = new QToolButton(this);\n resetButton_->setIconSize(QSize(20, 20));\n resetButton_->setObjectName(\"resetButton\");\n connect(resetButton_, &QToolButton::clicked, this, [&]() {\n if (property_) {\n property_->resetToDefaultState();\n } else if (propertyOwner_) {\n propertyOwner_->resetAllPoperties();\n }\n });\n\n resetButton_->setToolTip(tr(\"Reset the group of properties to its default state\"));\n\n checkBox_ = new QCheckBox(this);\n checkBox_->setMinimumSize(5, 5);\n checkBox_->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));\n checkBox_->setChecked(checked_);\n checkBox_->setVisible(checkable_);\n\n QObject::connect(checkBox_, &QCheckBox::clicked, this,\n [&]() { setChecked(checkBox_->isChecked()); });\n\n QHBoxLayout* heading = new QHBoxLayout();\n heading->setContentsMargins(0, 0, 0, 0);\n heading->setSpacing(PropertyWidgetQt::spacing);\n heading->addWidget(btnCollapse_);\n heading->addWidget(label_);\n heading->addStretch(1);\n heading->addWidget(checkBox_);\n heading->addWidget(resetButton_);\n\n QVBoxLayout* layout = new QVBoxLayout();\n setSpacingAndMargins(layout);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->setSpacing(0);\n layout->addLayout(heading);\n layout->addWidget(propertyWidgetGroup_);\n\n \/\/ Adjust the margins when using a border, i.e. margin >= border width.\n \/\/ Otherwise the border might be overdrawn by children.\n this->setContentsMargins(margin, margin, margin, margin);\n\n this->setLayout(layout);\n}\n\nstd::unique_ptr CollapsibleGroupBoxWidgetQt::getContextMenu() {\n auto menu = PropertyWidgetQt::getContextMenu();\n\n if (propertyOwner_ && !property_) {\n menu->addAction(QString::fromStdString(displayName_));\n menu->addSeparator();\n\n auto resetAction = menu->addAction(tr(\"&Reset to default\"));\n resetAction->setToolTip(tr(\"&RReset the group of properties to its default state\"));\n connect(resetAction, &QAction::triggered, this,\n [&]() { propertyOwner_->resetAllPoperties(); });\n }\n return menu;\n}\n\nQSize CollapsibleGroupBoxWidgetQt::sizeHint() const {\n QSize size = layout()->sizeHint();\n size.setWidth(std::max(PropertyWidgetQt::minimumWidth, size.width()));\n return size;\n}\n\nQSize CollapsibleGroupBoxWidgetQt::minimumSizeHint() const {\n QSize size = layout()->sizeHint();\n QSize minSize = layout()->minimumSize();\n size.setWidth(std::max(PropertyWidgetQt::minimumWidth, minSize.width()));\n return size;\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setReadOnly(bool readonly) {\n label_->setDisabled(readonly);\n checkBox_->setDisabled(readonly);\n resetButton_->setDisabled(readonly);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::addProperty(Property* prop) {\n properties_.push_back(prop);\n\n auto factory = InviwoApplication::getPtr()->getPropertyWidgetFactory();\n if (auto propertyWidget = static_cast(factory->create(prop).release())) {\n if (auto collapsibleWidget = dynamic_cast(propertyWidget)) {\n collapsibleWidget->setNestedDepth(this->getNestedDepth() + 1);\n \/\/ make the collapsible widget go all the way to the right border\n propertyWidgetGroupLayout_->addWidget(propertyWidget,\n propertyWidgetGroupLayout_->rowCount(), 0, 1, -1);\n } else { \/\/ not a collapsible widget\n propertyWidget->setNestedDepth(this->getNestedDepth());\n \/\/ property widget should only be added to the left column of the layout\n propertyWidgetGroupLayout_->addWidget(propertyWidget,\n propertyWidgetGroupLayout_->rowCount(), 0);\n }\n\n propertyWidgets_.push_back(propertyWidget);\n connect(propertyWidget, &PropertyWidgetQt::updateSemantics, this,\n &CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics);\n\n propertyWidget->setParentPropertyWidget(this, getBaseContainer());\n propertyWidget->initState();\n\n } else {\n LogWarn(\"Could not find a widget for property: \" << prop->getClassIdentifier());\n }\n}\n\nstd::string CollapsibleGroupBoxWidgetQt::getDisplayName() const { return displayName_; }\n\nvoid CollapsibleGroupBoxWidgetQt::setDisplayName(const std::string& displayName) {\n displayName_ = displayName;\n if (propertyOwner_) {\n if (Processor* p = dynamic_cast(propertyOwner_)) {\n try {\n p->setIdentifier(displayName);\n } catch (Exception& e) {\n label_->setText(p->getIdentifier());\n LogWarn(e.getMessage());\n }\n }\n }\n}\n\nconst std::vector& CollapsibleGroupBoxWidgetQt::getProperties() { return properties_; }\n\nvoid CollapsibleGroupBoxWidgetQt::toggleCollapsed() { setCollapsed(!isCollapsed()); }\n\nbool CollapsibleGroupBoxWidgetQt::isCollapsed() const { return collapsed_; }\n\nbool CollapsibleGroupBoxWidgetQt::isChecked() const { return checked_; }\n\nvoid CollapsibleGroupBoxWidgetQt::setChecked(bool checked) {\n if (!checkable_) {\n return;\n }\n\n checked_ = checked;\n \/\/ update checkbox\n checkBox_->setChecked(checked_);\n}\n\nbool CollapsibleGroupBoxWidgetQt::isCheckable() const { return checkable_; }\n\nvoid CollapsibleGroupBoxWidgetQt::setCheckable(bool checkable) {\n if (checkable_ == checkable) {\n return;\n }\n\n checkable_ = checkable;\n \/\/ update header\n checkBox_->setVisible(checkable_);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setVisible(bool visible) {\n bool empty = util::all_of(properties_, [](Property* w) { return !w->getVisible(); });\n defaultLabel_->setVisible(empty);\n\n if (showIfEmpty_ || !empty) {\n PropertyWidgetQt::setVisible(visible);\n } else {\n PropertyWidgetQt::setVisible(false);\n }\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setCollapsed(bool collapse) {\n setUpdatesEnabled(false);\n if (collapsed_ && !collapse) {\n propertyWidgetGroup_->show();\n btnCollapse_->setIcon(QIcon(\":\/stylesheets\/images\/arrow_lighter_down.png\"));\n } else if (!collapsed_ && collapse) {\n propertyWidgetGroup_->hide();\n btnCollapse_->setIcon(QIcon(\":\/stylesheets\/images\/arrow_lighter_right.png\"));\n }\n collapsed_ = collapse;\n setUpdatesEnabled(true);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics(PropertyWidgetQt* widget) {\n setUpdatesEnabled(false);\n Property* prop = widget->getProperty();\n\n auto pit = std::find(properties_.begin(), properties_.end(), prop);\n auto wit = std::find(propertyWidgets_.begin(), propertyWidgets_.end(), widget);\n\n if (pit != properties_.end() && wit != propertyWidgets_.end()) {\n auto factory = InviwoApplication::getPtr()->getPropertyWidgetFactory();\n if (auto newWidget = static_cast(factory->create(prop).release())) {\n\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n propertyWidgetGroupLayout_->replaceWidget(widget, newWidget,\n Qt::FindDirectChildrenOnly);\n#else\n int layoutPosition = propertyWidgetGroupLayout_->indexOf(widget);\n propertyWidgetGroupLayout_->removeWidget(widget);\n propertyWidgetGroupLayout_->addWidget(newWidget, layoutPosition, 0);\n#endif \/\/ QT_VERSION >= 5.2\n widget->deleteLater();\n\n \/\/ Replace the item in propertyWidgets_;\n *wit = newWidget;\n\n connect(newWidget, &PropertyWidgetQt::updateSemantics, this,\n &CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics);\n\n newWidget->setNestedDepth(this->getNestedDepth());\n newWidget->setParentPropertyWidget(this, getBaseContainer());\n newWidget->initState();\n\n } else {\n LogWarn(\"Could not change semantic for property: \" << prop->getClassIdentifier());\n }\n }\n setUpdatesEnabled(true);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::onDidAddProperty(Property* prop, size_t index) {\n setUpdatesEnabled(false);\n std::vector::iterator insertPoint = properties_.begin() + index;\n if (insertPoint != properties_.end()) ++insertPoint;\n\n properties_.insert(insertPoint, prop);\n\n auto factory = InviwoApplication::getPtr()->getPropertyWidgetFactory();\n if (auto propertyWidget = static_cast(factory->create(prop).release())) {\n const int insertPos = static_cast(index) + 1;\n\n if (auto collapsibleWidget = dynamic_cast(propertyWidget)) {\n collapsibleWidget->setNestedDepth(this->getNestedDepth() + 1);\n \/\/ make the collapsible widget go all the way to the right border\n propertyWidgetGroupLayout_->addWidget(propertyWidget, insertPos, 0, 1, -1);\n\n } else { \/\/ not a collapsible widget\n propertyWidget->setNestedDepth(this->getNestedDepth());\n \/\/ property widget should only be added to the left column of the layout\n propertyWidgetGroupLayout_->addWidget(propertyWidget, insertPos, 0);\n }\n\n auto widgetInsertPoint = propertyWidgets_.begin() + index;\n if (widgetInsertPoint != propertyWidgets_.end()) ++widgetInsertPoint;\n\n propertyWidgets_.insert(widgetInsertPoint, propertyWidget);\n connect(propertyWidget, &PropertyWidgetQt::updateSemantics, this,\n &CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics);\n\n propertyWidget->setParentPropertyWidget(this, getBaseContainer());\n propertyWidget->initState();\n\n } else {\n LogWarn(\"Could not find a widget for property: \" << prop->getClassIdentifier());\n }\n setUpdatesEnabled(true);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::onWillRemoveProperty(Property* \/*prop*\/, size_t index) {\n PropertyWidgetQt* propertyWidget = propertyWidgets_[index];\n\n propertyWidgetGroupLayout_->removeWidget(propertyWidget);\n propertyWidgets_.erase(propertyWidgets_.begin() + index);\n properties_.erase(properties_.begin() + index);\n propertyWidget->deleteLater();\n}\n\nvoid CollapsibleGroupBoxWidgetQt::onProcessorIdentifierChange(Processor* processor) {\n displayName_ = processor->getIdentifier();\n label_->setText(processor->getIdentifier());\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setPropertyOwner(PropertyOwner* propertyOwner) {\n propertyOwner_ = propertyOwner;\n}\n\nPropertyOwner* CollapsibleGroupBoxWidgetQt::getPropertyOwner() const { return propertyOwner_; }\n\nconst std::vector& CollapsibleGroupBoxWidgetQt::getPropertyWidgets() {\n return propertyWidgets_;\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setShowIfEmpty(bool val) { showIfEmpty_ = val; }\n} \/\/ namespace inviwo\nQt: delete later is evil...\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2013-2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nCollapsibleGroupBoxWidgetQt::CollapsibleGroupBoxWidgetQt(std::string displayName, bool isCheckable)\n : PropertyWidgetQt()\n , PropertyOwnerObserver()\n , displayName_(displayName)\n , collapsed_(false)\n , checked_(false)\n , propertyOwner_(nullptr)\n , showIfEmpty_(false)\n , checkable_(isCheckable) {\n setObjectName(\"CompositeWidget\");\n\n generateWidget();\n updateFromProperty();\n}\n\nCollapsibleGroupBoxWidgetQt::CollapsibleGroupBoxWidgetQt(Property* property, bool isCheckable)\n : PropertyWidgetQt(property)\n , PropertyOwnerObserver()\n , displayName_(property->getDisplayName())\n , collapsed_(false)\n , checked_(false)\n , propertyOwner_(nullptr)\n , showIfEmpty_(false)\n , checkable_(isCheckable) {\n setObjectName(\"CompositeWidget\");\n\n generateWidget();\n updateFromProperty();\n}\n\nvoid CollapsibleGroupBoxWidgetQt::generateWidget() {\n propertyWidgetGroupLayout_ = new QGridLayout();\n propertyWidgetGroupLayout_->setAlignment(Qt::AlignTop);\n propertyWidgetGroupLayout_->setContentsMargins(\n PropertyWidgetQt::spacing, PropertyWidgetQt::spacing, 0, PropertyWidgetQt::spacing);\n propertyWidgetGroupLayout_->setHorizontalSpacing(0);\n propertyWidgetGroupLayout_->setVerticalSpacing(PropertyWidgetQt::spacing);\n\n propertyWidgetGroup_ = new QWidget(this);\n propertyWidgetGroup_->setObjectName(\"CompositeContents\");\n propertyWidgetGroup_->setLayout(propertyWidgetGroupLayout_);\n\n defaultLabel_ = new QLabel(\"No properties available\");\n\n propertyWidgetGroupLayout_->addWidget(defaultLabel_, 0, 0);\n propertyWidgetGroupLayout_->addItem(\n new QSpacerItem(PropertyWidgetQt::spacing, 1, QSizePolicy::Fixed), 0, 1);\n propertyWidgetGroupLayout_->setColumnStretch(0, 1);\n propertyWidgetGroupLayout_->setColumnStretch(1, 0);\n\n btnCollapse_ = new QToolButton(this);\n btnCollapse_->setObjectName(\"collapseButton\");\n btnCollapse_->setIcon(QIcon(\":\/stylesheets\/images\/arrow_lighter_down.png\"));\n connect(btnCollapse_, &QToolButton::clicked, this,\n &CollapsibleGroupBoxWidgetQt::toggleCollapsed);\n\n if (property_) {\n label_ = new EditableLabelQt(this, property_, false);\n } else {\n label_ = new EditableLabelQt(this, displayName_, false);\n }\n label_->setObjectName(\"compositeLabel\");\n QSizePolicy labelPol = label_->sizePolicy();\n labelPol.setHorizontalStretch(10);\n label_->setSizePolicy(labelPol);\n connect(label_, &EditableLabelQt::textChanged, this,\n [&]() { setDisplayName(label_->getText()); });\n\n resetButton_ = new QToolButton(this);\n resetButton_->setIconSize(QSize(20, 20));\n resetButton_->setObjectName(\"resetButton\");\n connect(resetButton_, &QToolButton::clicked, this, [&]() {\n if (property_) {\n property_->resetToDefaultState();\n } else if (propertyOwner_) {\n propertyOwner_->resetAllPoperties();\n }\n });\n\n resetButton_->setToolTip(tr(\"Reset the group of properties to its default state\"));\n\n checkBox_ = new QCheckBox(this);\n checkBox_->setMinimumSize(5, 5);\n checkBox_->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));\n checkBox_->setChecked(checked_);\n checkBox_->setVisible(checkable_);\n\n QObject::connect(checkBox_, &QCheckBox::clicked, this,\n [&]() { setChecked(checkBox_->isChecked()); });\n\n QHBoxLayout* heading = new QHBoxLayout();\n heading->setContentsMargins(0, 0, 0, 0);\n heading->setSpacing(PropertyWidgetQt::spacing);\n heading->addWidget(btnCollapse_);\n heading->addWidget(label_);\n heading->addStretch(1);\n heading->addWidget(checkBox_);\n heading->addWidget(resetButton_);\n\n QVBoxLayout* layout = new QVBoxLayout();\n setSpacingAndMargins(layout);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->setSpacing(0);\n layout->addLayout(heading);\n layout->addWidget(propertyWidgetGroup_);\n\n \/\/ Adjust the margins when using a border, i.e. margin >= border width.\n \/\/ Otherwise the border might be overdrawn by children.\n this->setContentsMargins(margin, margin, margin, margin);\n\n this->setLayout(layout);\n}\n\nstd::unique_ptr CollapsibleGroupBoxWidgetQt::getContextMenu() {\n auto menu = PropertyWidgetQt::getContextMenu();\n\n if (propertyOwner_ && !property_) {\n menu->addAction(QString::fromStdString(displayName_));\n menu->addSeparator();\n\n auto resetAction = menu->addAction(tr(\"&Reset to default\"));\n resetAction->setToolTip(tr(\"&RReset the group of properties to its default state\"));\n connect(resetAction, &QAction::triggered, this,\n [&]() { propertyOwner_->resetAllPoperties(); });\n }\n return menu;\n}\n\nQSize CollapsibleGroupBoxWidgetQt::sizeHint() const {\n QSize size = layout()->sizeHint();\n size.setWidth(std::max(PropertyWidgetQt::minimumWidth, size.width()));\n return size;\n}\n\nQSize CollapsibleGroupBoxWidgetQt::minimumSizeHint() const {\n QSize size = layout()->sizeHint();\n QSize minSize = layout()->minimumSize();\n size.setWidth(std::max(PropertyWidgetQt::minimumWidth, minSize.width()));\n return size;\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setReadOnly(bool readonly) {\n label_->setDisabled(readonly);\n checkBox_->setDisabled(readonly);\n resetButton_->setDisabled(readonly);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::addProperty(Property* prop) {\n properties_.push_back(prop);\n\n auto factory = InviwoApplication::getPtr()->getPropertyWidgetFactory();\n if (auto propertyWidget = static_cast(factory->create(prop).release())) {\n if (auto collapsibleWidget = dynamic_cast(propertyWidget)) {\n collapsibleWidget->setNestedDepth(this->getNestedDepth() + 1);\n \/\/ make the collapsible widget go all the way to the right border\n propertyWidgetGroupLayout_->addWidget(propertyWidget,\n propertyWidgetGroupLayout_->rowCount(), 0, 1, -1);\n } else { \/\/ not a collapsible widget\n propertyWidget->setNestedDepth(this->getNestedDepth());\n \/\/ property widget should only be added to the left column of the layout\n propertyWidgetGroupLayout_->addWidget(propertyWidget,\n propertyWidgetGroupLayout_->rowCount(), 0);\n }\n\n propertyWidgets_.push_back(propertyWidget);\n connect(propertyWidget, &PropertyWidgetQt::updateSemantics, this,\n &CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics);\n\n propertyWidget->setParentPropertyWidget(this, getBaseContainer());\n propertyWidget->initState();\n\n } else {\n LogWarn(\"Could not find a widget for property: \" << prop->getClassIdentifier());\n }\n}\n\nstd::string CollapsibleGroupBoxWidgetQt::getDisplayName() const { return displayName_; }\n\nvoid CollapsibleGroupBoxWidgetQt::setDisplayName(const std::string& displayName) {\n displayName_ = displayName;\n if (propertyOwner_) {\n if (Processor* p = dynamic_cast(propertyOwner_)) {\n try {\n p->setIdentifier(displayName);\n } catch (Exception& e) {\n label_->setText(p->getIdentifier());\n LogWarn(e.getMessage());\n }\n }\n }\n}\n\nconst std::vector& CollapsibleGroupBoxWidgetQt::getProperties() { return properties_; }\n\nvoid CollapsibleGroupBoxWidgetQt::toggleCollapsed() { setCollapsed(!isCollapsed()); }\n\nbool CollapsibleGroupBoxWidgetQt::isCollapsed() const { return collapsed_; }\n\nbool CollapsibleGroupBoxWidgetQt::isChecked() const { return checked_; }\n\nvoid CollapsibleGroupBoxWidgetQt::setChecked(bool checked) {\n if (!checkable_) {\n return;\n }\n\n checked_ = checked;\n \/\/ update checkbox\n checkBox_->setChecked(checked_);\n}\n\nbool CollapsibleGroupBoxWidgetQt::isCheckable() const { return checkable_; }\n\nvoid CollapsibleGroupBoxWidgetQt::setCheckable(bool checkable) {\n if (checkable_ == checkable) {\n return;\n }\n\n checkable_ = checkable;\n \/\/ update header\n checkBox_->setVisible(checkable_);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setVisible(bool visible) {\n bool empty = util::all_of(properties_, [](Property* w) { return !w->getVisible(); });\n defaultLabel_->setVisible(empty);\n\n if (showIfEmpty_ || !empty) {\n PropertyWidgetQt::setVisible(visible);\n } else {\n PropertyWidgetQt::setVisible(false);\n }\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setCollapsed(bool collapse) {\n setUpdatesEnabled(false);\n if (collapsed_ && !collapse) {\n propertyWidgetGroup_->show();\n btnCollapse_->setIcon(QIcon(\":\/stylesheets\/images\/arrow_lighter_down.png\"));\n } else if (!collapsed_ && collapse) {\n propertyWidgetGroup_->hide();\n btnCollapse_->setIcon(QIcon(\":\/stylesheets\/images\/arrow_lighter_right.png\"));\n }\n collapsed_ = collapse;\n setUpdatesEnabled(true);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics(PropertyWidgetQt* widget) {\n setUpdatesEnabled(false);\n Property* prop = widget->getProperty();\n\n auto pit = std::find(properties_.begin(), properties_.end(), prop);\n auto wit = std::find(propertyWidgets_.begin(), propertyWidgets_.end(), widget);\n\n if (pit != properties_.end() && wit != propertyWidgets_.end()) {\n auto factory = InviwoApplication::getPtr()->getPropertyWidgetFactory();\n if (auto newWidget = static_cast(factory->create(prop).release())) {\n\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))\n propertyWidgetGroupLayout_->replaceWidget(widget, newWidget,\n Qt::FindDirectChildrenOnly);\n#else\n int layoutPosition = propertyWidgetGroupLayout_->indexOf(widget);\n propertyWidgetGroupLayout_->removeWidget(widget);\n propertyWidgetGroupLayout_->addWidget(newWidget, layoutPosition, 0);\n#endif \/\/ QT_VERSION >= 5.2\n delete widget;\n\n \/\/ Replace the item in propertyWidgets_;\n *wit = newWidget;\n\n connect(newWidget, &PropertyWidgetQt::updateSemantics, this,\n &CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics);\n\n newWidget->setNestedDepth(this->getNestedDepth());\n newWidget->setParentPropertyWidget(this, getBaseContainer());\n newWidget->initState();\n\n } else {\n LogWarn(\"Could not change semantic for property: \" << prop->getClassIdentifier());\n }\n }\n setUpdatesEnabled(true);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::onDidAddProperty(Property* prop, size_t index) {\n setUpdatesEnabled(false);\n std::vector::iterator insertPoint = properties_.begin() + index;\n if (insertPoint != properties_.end()) ++insertPoint;\n\n properties_.insert(insertPoint, prop);\n\n auto factory = InviwoApplication::getPtr()->getPropertyWidgetFactory();\n if (auto propertyWidget = static_cast(factory->create(prop).release())) {\n const int insertPos = static_cast(index) + 1;\n\n if (auto collapsibleWidget = dynamic_cast(propertyWidget)) {\n collapsibleWidget->setNestedDepth(this->getNestedDepth() + 1);\n \/\/ make the collapsible widget go all the way to the right border\n propertyWidgetGroupLayout_->addWidget(propertyWidget, insertPos, 0, 1, -1);\n\n } else { \/\/ not a collapsible widget\n propertyWidget->setNestedDepth(this->getNestedDepth());\n \/\/ property widget should only be added to the left column of the layout\n propertyWidgetGroupLayout_->addWidget(propertyWidget, insertPos, 0);\n }\n\n auto widgetInsertPoint = propertyWidgets_.begin() + index;\n if (widgetInsertPoint != propertyWidgets_.end()) ++widgetInsertPoint;\n\n propertyWidgets_.insert(widgetInsertPoint, propertyWidget);\n connect(propertyWidget, &PropertyWidgetQt::updateSemantics, this,\n &CollapsibleGroupBoxWidgetQt::updatePropertyWidgetSemantics);\n\n propertyWidget->setParentPropertyWidget(this, getBaseContainer());\n propertyWidget->initState();\n\n } else {\n LogWarn(\"Could not find a widget for property: \" << prop->getClassIdentifier());\n }\n setUpdatesEnabled(true);\n}\n\nvoid CollapsibleGroupBoxWidgetQt::onWillRemoveProperty(Property* \/*prop*\/, size_t index) {\n PropertyWidgetQt* propertyWidget = propertyWidgets_[index];\n\n propertyWidgetGroupLayout_->removeWidget(propertyWidget);\n propertyWidgets_.erase(propertyWidgets_.begin() + index);\n properties_.erase(properties_.begin() + index);\n delete propertyWidget;\n}\n\nvoid CollapsibleGroupBoxWidgetQt::onProcessorIdentifierChange(Processor* processor) {\n displayName_ = processor->getIdentifier();\n label_->setText(processor->getIdentifier());\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setPropertyOwner(PropertyOwner* propertyOwner) {\n propertyOwner_ = propertyOwner;\n}\n\nPropertyOwner* CollapsibleGroupBoxWidgetQt::getPropertyOwner() const { return propertyOwner_; }\n\nconst std::vector& CollapsibleGroupBoxWidgetQt::getPropertyWidgets() {\n return propertyWidgets_;\n}\n\nvoid CollapsibleGroupBoxWidgetQt::setShowIfEmpty(bool val) { showIfEmpty_ = val; }\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"#include \"CodeGen_Internal.h\"\n#include \"IROperator.h\"\n#include \"CSE.h\"\n#include \"Debug.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::map;\nusing std::vector;\nusing std::pair;\n\nusing namespace llvm;\n\nnamespace {\n\nvector llvm_types(const Closure& closure, llvm::StructType *buffer_t, LLVMContext &context) {\n vector res;\n for (const pair &i : closure.vars) {\n res.push_back(llvm_type_of(&context, i.second));\n }\n for (const pair &i : closure.buffers) {\n res.push_back(llvm_type_of(&context, i.second.type)->getPointerTo());\n res.push_back(buffer_t->getPointerTo());\n }\n return res;\n}\n\n} \/\/ namespace\n\nStructType *build_closure_type(const Closure& closure, llvm::StructType *buffer_t, LLVMContext *context) {\n StructType *struct_t = StructType::create(*context, \"closure_t\");\n struct_t->setBody(llvm_types(closure, buffer_t, *context), false);\n return struct_t;\n}\n\nvoid pack_closure(llvm::Type *\n#if LLVM_VERSION >= 37\n type\n#endif\n ,\n Value *dst,\n const Closure& closure,\n const Scope &src,\n llvm::StructType *buffer_t,\n IRBuilder<> *builder) {\n \/\/ type, type of dst should be a pointer to a struct of the type returned by build_type\n int idx = 0;\n LLVMContext &context = builder->getContext();\n vector nm = closure.names();\n vector ty = llvm_types(closure, buffer_t, context);\n for (size_t i = 0; i < nm.size(); i++) {\n#if LLVM_VERSION >= 37\n Value *ptr = builder->CreateConstInBoundsGEP2_32(type, dst, 0, idx);\n#else\n Value *ptr = builder->CreateConstInBoundsGEP2_32(dst, 0, idx);\n#endif\n Value *val;\n if (!ends_with(nm[i], \".buffer\") || src.contains(nm[i])) {\n val = src.get(nm[i]);\n if (val->getType() != ty[i]) {\n val = builder->CreateBitCast(val, ty[i]);\n }\n } else {\n \/\/ Skip over buffers not in the symbol table. They must not be needed.\n val = ConstantPointerNull::get(buffer_t->getPointerTo());\n }\n builder->CreateStore(val, ptr);\n idx++;\n }\n}\n\nvoid unpack_closure(const Closure& closure,\n Scope &dst,\n llvm::Type *\n#if LLVM_VERSION >= 37\n type\n#endif\n ,\n Value *src,\n IRBuilder<> *builder) {\n \/\/ type, type of src should be a pointer to a struct of the type returned by build_type\n int idx = 0;\n LLVMContext &context = builder->getContext();\n vector nm = closure.names();\n for (size_t i = 0; i < nm.size(); i++) {\n#if LLVM_VERSION >= 37\n Value *ptr = builder->CreateConstInBoundsGEP2_32(type, src, 0, idx++);\n#else\n Value *ptr = builder->CreateConstInBoundsGEP2_32(src, 0, idx++);\n#endif\n LoadInst *load = builder->CreateLoad(ptr);\n if (load->getType()->isPointerTy()) {\n \/\/ Give it a unique type so that tbaa tells llvm that this can't alias anything\n LLVMMDNodeArgumentType md_args[] = {MDString::get(context, nm[i])};\n load->setMetadata(\"tbaa\", MDNode::get(context, md_args));\n }\n dst.push(nm[i], load);\n load->setName(nm[i]);\n }\n}\n\nllvm::Type *llvm_type_of(LLVMContext *c, Halide::Type t) {\n if (t.lanes() == 1) {\n if (t.is_float()) {\n switch (t.bits()) {\n case 16:\n return llvm::Type::getHalfTy(*c);\n case 32:\n return llvm::Type::getFloatTy(*c);\n case 64:\n return llvm::Type::getDoubleTy(*c);\n default:\n internal_error << \"There is no llvm type matching this floating-point bit width: \" << t << \"\\n\";\n return nullptr;\n }\n } else if (t.is_handle()) {\n return llvm::Type::getInt8PtrTy(*c);\n } else {\n return llvm::Type::getIntNTy(*c, t.bits());\n }\n } else {\n llvm::Type *element_type = llvm_type_of(c, t.element_of());\n return VectorType::get(element_type, t.lanes());\n }\n}\n\n\/\/ Returns true if the given function name is one of the Halide runtime\n\/\/ functions that takes a user_context pointer as its first parameter.\nbool function_takes_user_context(const std::string &name) {\n static const char *user_context_runtime_funcs[] = {\n \"halide_copy_to_host\",\n \"halide_copy_to_device\",\n \"halide_current_time_ns\",\n \"halide_debug_to_file\",\n \"halide_device_free\",\n \"halide_device_malloc\",\n \"halide_device_sync\",\n \"halide_do_par_for\",\n \"halide_do_task\",\n \"halide_error\",\n \"halide_free\",\n \"halide_malloc\",\n \"halide_print\",\n \"halide_profiler_memory_allocate\",\n \"halide_profiler_memory_free\",\n \"halide_profiler_pipeline_start\",\n \"halide_profiler_pipeline_end\",\n \"halide_profiler_stack_peak_update\",\n \"halide_spawn_thread\",\n \"halide_device_release\",\n \"halide_start_clock\",\n \"halide_trace\",\n \"halide_memoization_cache_lookup\",\n \"halide_memoization_cache_store\",\n \"halide_memoization_cache_release\",\n \"halide_cuda_run\",\n \"halide_opencl_run\",\n \"halide_opengl_run\",\n \"halide_openglcompute_run\",\n \"halide_renderscript_run\",\n \"halide_metal_run\",\n \"halide_cuda_initialize_kernels\",\n \"halide_opencl_initialize_kernels\",\n \"halide_opengl_initialize_kernels\",\n \"halide_openglcompute_initialize_kernels\",\n \"halide_renderscript_initialize_kernels\",\n \"halide_metal_initialize_kernels\",\n \"halide_get_gpu_device\",\n };\n const int num_funcs = sizeof(user_context_runtime_funcs) \/\n sizeof(user_context_runtime_funcs[0]);\n for (int i = 0; i < num_funcs; ++i) {\n if (name == user_context_runtime_funcs[i]) {\n return true;\n }\n }\n \/\/ The error functions all take a user context\n return starts_with(name, \"halide_error_\");\n}\n\nbool can_allocation_fit_on_stack(int32_t size) {\n user_assert(size > 0) << \"Allocation size should be a positive number\\n\";\n return (size <= 1024 * 16);\n}\n\nExpr lower_euclidean_div(Expr a, Expr b) {\n internal_assert(a.type() == b.type());\n \/\/ IROperator's div_round_to_zero will replace this with a \/ b for\n \/\/ unsigned ops, so create the intrinsic directly.\n Expr q = Call::make(a.type(), Call::div_round_to_zero, {a, b}, Call::PureIntrinsic);\n if (a.type().is_int()) {\n \/\/ Signed integer division sucks. It should be defined such\n \/\/ that it satisifies (a\/b)*b + a%b = a, where 0 <= a%b < |b|,\n \/\/ i.e. Euclidean division.\n\n \/\/ We get rounding to work by examining the implied remainder\n \/\/ and correcting the quotient.\n\n \/* Here's the C code that we're trying to match:\n int q = a \/ b;\n int r = a - q * b;\n int bs = b >> (t.bits() - 1);\n int rs = r >> (t.bits() - 1);\n return q - (rs & bs) + (rs & ~bs);\n *\/\n\n Expr r = a - q*b;\n Expr bs = b >> (a.type().bits() - 1);\n Expr rs = r >> (a.type().bits() - 1);\n q = q - (rs & bs) + (rs & ~bs);\n return common_subexpression_elimination(q);\n } else {\n return q;\n }\n}\n\nExpr lower_euclidean_mod(Expr a, Expr b) {\n internal_assert(a.type() == b.type());\n \/\/ IROperator's mod_round_to_zero will replace this with a % b for\n \/\/ unsigned ops, so create the intrinsic directly.\n Expr r = Call::make(a.type(), Call::mod_round_to_zero, {a, b}, Call::PureIntrinsic);\n if (a.type().is_int()) {\n \/\/ Match this non-overflowing C code\n \/*\n T r = a % b;\n r = r + (r < 0 ? abs(b) : 0);\n *\/\n\n r = select(r < 0, r + abs(b), r);\n return common_subexpression_elimination(r);\n } else {\n return r;\n }\n}\n\nbool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {\n #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)\n llvm::ConstantInt *c = llvm::cast(value);\n #else\n llvm::ConstantAsMetadata *cam = llvm::cast(value);\n llvm::ConstantInt *c = llvm::cast(cam->getValue());\n #endif\n if (c) {\n result = !c->isZero();\n return true;\n }\n return false;\n}\n\nbool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {\n #if LLVM_VERSION < 36\n if (llvm::dyn_cast(value)) {\n result = \"\";\n return true;\n }\n llvm::ConstantDataArray *c = llvm::cast(value);\n if (c) {\n result = c->getAsCString();\n return true;\n }\n #else\n llvm::MDString *c = llvm::dyn_cast(value);\n if (c) {\n result = c->getString();\n return true;\n }\n #endif\n return false;\n}\n\nvoid get_target_options(const llvm::Module &module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {\n bool use_soft_float_abi = false;\n get_md_bool(module.getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi);\n get_md_string(module.getModuleFlag(\"halide_mcpu\"), mcpu);\n get_md_string(module.getModuleFlag(\"halide_mattrs\"), mattrs);\n\n options = llvm::TargetOptions();\n options.LessPreciseFPMADOption = true;\n options.AllowFPOpFusion = llvm::FPOpFusion::Fast;\n options.UnsafeFPMath = true;\n options.NoInfsFPMath = true;\n options.NoNaNsFPMath = true;\n options.HonorSignDependentRoundingFPMathOption = false;\n #if LLVM_VERSION < 37\n options.NoFramePointerElim = false;\n options.UseSoftFloat = false;\n #endif\n options.NoZerosInBSS = false;\n options.GuaranteedTailCallOpt = false;\n #if LLVM_VERSION < 37\n options.DisableTailCalls = false;\n #endif\n options.StackAlignmentOverride = 0;\n #if LLVM_VERSION < 37\n options.TrapFuncName = \"\";\n #endif\n options.FunctionSections = true;\n #ifdef WITH_NATIVE_CLIENT\n options.UseInitArray = true;\n #else\n options.UseInitArray = false;\n #endif\n options.FloatABIType =\n use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;\n}\n\n\nvoid clone_target_options(const llvm::Module &from, llvm::Module &to) {\n to.setTargetTriple(from.getTargetTriple());\n\n llvm::LLVMContext &context = to.getContext();\n\n bool use_soft_float_abi = false;\n if (get_md_bool(from.getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi))\n to.addModuleFlag(llvm::Module::Warning, \"halide_use_soft_float_abi\", use_soft_float_abi ? 1 : 0);\n\n std::string mcpu;\n if (get_md_string(from.getModuleFlag(\"halide_mcpu\"), mcpu)) {\n #if LLVM_VERSION < 36\n to.addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::ConstantDataArray::getString(context, mcpu));\n #else\n to.addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::MDString::get(context, mcpu));\n #endif\n }\n\n std::string mattrs;\n if (get_md_string(from.getModuleFlag(\"halide_mattrs\"), mattrs)) {\n #if LLVM_VERSION < 36\n to.addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::ConstantDataArray::getString(context, mattrs));\n #else\n to.addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::MDString::get(context, mattrs));\n #endif\n }\n}\n\nllvm::TargetMachine *get_target_machine(const llvm::Module &module) {\n std::string error_string;\n\n const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module.getTargetTriple(), error_string);\n if (!target) {\n std::cout << error_string << std::endl;\n llvm::TargetRegistry::printRegisteredTargetsForVersion();\n }\n internal_assert(target) << \"Could not create target for \" << module.getTargetTriple() << \"\\n\";\n\n llvm::TargetOptions options;\n std::string mcpu = \"\";\n std::string mattrs = \"\";\n get_target_options(module, options, mcpu, mattrs);\n\n return target->createTargetMachine(module.getTargetTriple(),\n mcpu, mattrs,\n options,\n llvm::Reloc::PIC_,\n llvm::CodeModel::Default,\n llvm::CodeGenOpt::Aggressive);\n}\n\n}\n}\nTurn off unsafe fp math :(#include \"CodeGen_Internal.h\"\n#include \"IROperator.h\"\n#include \"CSE.h\"\n#include \"Debug.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::map;\nusing std::vector;\nusing std::pair;\n\nusing namespace llvm;\n\nnamespace {\n\nvector llvm_types(const Closure& closure, llvm::StructType *buffer_t, LLVMContext &context) {\n vector res;\n for (const pair &i : closure.vars) {\n res.push_back(llvm_type_of(&context, i.second));\n }\n for (const pair &i : closure.buffers) {\n res.push_back(llvm_type_of(&context, i.second.type)->getPointerTo());\n res.push_back(buffer_t->getPointerTo());\n }\n return res;\n}\n\n} \/\/ namespace\n\nStructType *build_closure_type(const Closure& closure, llvm::StructType *buffer_t, LLVMContext *context) {\n StructType *struct_t = StructType::create(*context, \"closure_t\");\n struct_t->setBody(llvm_types(closure, buffer_t, *context), false);\n return struct_t;\n}\n\nvoid pack_closure(llvm::Type *\n#if LLVM_VERSION >= 37\n type\n#endif\n ,\n Value *dst,\n const Closure& closure,\n const Scope &src,\n llvm::StructType *buffer_t,\n IRBuilder<> *builder) {\n \/\/ type, type of dst should be a pointer to a struct of the type returned by build_type\n int idx = 0;\n LLVMContext &context = builder->getContext();\n vector nm = closure.names();\n vector ty = llvm_types(closure, buffer_t, context);\n for (size_t i = 0; i < nm.size(); i++) {\n#if LLVM_VERSION >= 37\n Value *ptr = builder->CreateConstInBoundsGEP2_32(type, dst, 0, idx);\n#else\n Value *ptr = builder->CreateConstInBoundsGEP2_32(dst, 0, idx);\n#endif\n Value *val;\n if (!ends_with(nm[i], \".buffer\") || src.contains(nm[i])) {\n val = src.get(nm[i]);\n if (val->getType() != ty[i]) {\n val = builder->CreateBitCast(val, ty[i]);\n }\n } else {\n \/\/ Skip over buffers not in the symbol table. They must not be needed.\n val = ConstantPointerNull::get(buffer_t->getPointerTo());\n }\n builder->CreateStore(val, ptr);\n idx++;\n }\n}\n\nvoid unpack_closure(const Closure& closure,\n Scope &dst,\n llvm::Type *\n#if LLVM_VERSION >= 37\n type\n#endif\n ,\n Value *src,\n IRBuilder<> *builder) {\n \/\/ type, type of src should be a pointer to a struct of the type returned by build_type\n int idx = 0;\n LLVMContext &context = builder->getContext();\n vector nm = closure.names();\n for (size_t i = 0; i < nm.size(); i++) {\n#if LLVM_VERSION >= 37\n Value *ptr = builder->CreateConstInBoundsGEP2_32(type, src, 0, idx++);\n#else\n Value *ptr = builder->CreateConstInBoundsGEP2_32(src, 0, idx++);\n#endif\n LoadInst *load = builder->CreateLoad(ptr);\n if (load->getType()->isPointerTy()) {\n \/\/ Give it a unique type so that tbaa tells llvm that this can't alias anything\n LLVMMDNodeArgumentType md_args[] = {MDString::get(context, nm[i])};\n load->setMetadata(\"tbaa\", MDNode::get(context, md_args));\n }\n dst.push(nm[i], load);\n load->setName(nm[i]);\n }\n}\n\nllvm::Type *llvm_type_of(LLVMContext *c, Halide::Type t) {\n if (t.lanes() == 1) {\n if (t.is_float()) {\n switch (t.bits()) {\n case 16:\n return llvm::Type::getHalfTy(*c);\n case 32:\n return llvm::Type::getFloatTy(*c);\n case 64:\n return llvm::Type::getDoubleTy(*c);\n default:\n internal_error << \"There is no llvm type matching this floating-point bit width: \" << t << \"\\n\";\n return nullptr;\n }\n } else if (t.is_handle()) {\n return llvm::Type::getInt8PtrTy(*c);\n } else {\n return llvm::Type::getIntNTy(*c, t.bits());\n }\n } else {\n llvm::Type *element_type = llvm_type_of(c, t.element_of());\n return VectorType::get(element_type, t.lanes());\n }\n}\n\n\/\/ Returns true if the given function name is one of the Halide runtime\n\/\/ functions that takes a user_context pointer as its first parameter.\nbool function_takes_user_context(const std::string &name) {\n static const char *user_context_runtime_funcs[] = {\n \"halide_copy_to_host\",\n \"halide_copy_to_device\",\n \"halide_current_time_ns\",\n \"halide_debug_to_file\",\n \"halide_device_free\",\n \"halide_device_malloc\",\n \"halide_device_sync\",\n \"halide_do_par_for\",\n \"halide_do_task\",\n \"halide_error\",\n \"halide_free\",\n \"halide_malloc\",\n \"halide_print\",\n \"halide_profiler_memory_allocate\",\n \"halide_profiler_memory_free\",\n \"halide_profiler_pipeline_start\",\n \"halide_profiler_pipeline_end\",\n \"halide_profiler_stack_peak_update\",\n \"halide_spawn_thread\",\n \"halide_device_release\",\n \"halide_start_clock\",\n \"halide_trace\",\n \"halide_memoization_cache_lookup\",\n \"halide_memoization_cache_store\",\n \"halide_memoization_cache_release\",\n \"halide_cuda_run\",\n \"halide_opencl_run\",\n \"halide_opengl_run\",\n \"halide_openglcompute_run\",\n \"halide_renderscript_run\",\n \"halide_metal_run\",\n \"halide_cuda_initialize_kernels\",\n \"halide_opencl_initialize_kernels\",\n \"halide_opengl_initialize_kernels\",\n \"halide_openglcompute_initialize_kernels\",\n \"halide_renderscript_initialize_kernels\",\n \"halide_metal_initialize_kernels\",\n \"halide_get_gpu_device\",\n };\n const int num_funcs = sizeof(user_context_runtime_funcs) \/\n sizeof(user_context_runtime_funcs[0]);\n for (int i = 0; i < num_funcs; ++i) {\n if (name == user_context_runtime_funcs[i]) {\n return true;\n }\n }\n \/\/ The error functions all take a user context\n return starts_with(name, \"halide_error_\");\n}\n\nbool can_allocation_fit_on_stack(int32_t size) {\n user_assert(size > 0) << \"Allocation size should be a positive number\\n\";\n return (size <= 1024 * 16);\n}\n\nExpr lower_euclidean_div(Expr a, Expr b) {\n internal_assert(a.type() == b.type());\n \/\/ IROperator's div_round_to_zero will replace this with a \/ b for\n \/\/ unsigned ops, so create the intrinsic directly.\n Expr q = Call::make(a.type(), Call::div_round_to_zero, {a, b}, Call::PureIntrinsic);\n if (a.type().is_int()) {\n \/\/ Signed integer division sucks. It should be defined such\n \/\/ that it satisifies (a\/b)*b + a%b = a, where 0 <= a%b < |b|,\n \/\/ i.e. Euclidean division.\n\n \/\/ We get rounding to work by examining the implied remainder\n \/\/ and correcting the quotient.\n\n \/* Here's the C code that we're trying to match:\n int q = a \/ b;\n int r = a - q * b;\n int bs = b >> (t.bits() - 1);\n int rs = r >> (t.bits() - 1);\n return q - (rs & bs) + (rs & ~bs);\n *\/\n\n Expr r = a - q*b;\n Expr bs = b >> (a.type().bits() - 1);\n Expr rs = r >> (a.type().bits() - 1);\n q = q - (rs & bs) + (rs & ~bs);\n return common_subexpression_elimination(q);\n } else {\n return q;\n }\n}\n\nExpr lower_euclidean_mod(Expr a, Expr b) {\n internal_assert(a.type() == b.type());\n \/\/ IROperator's mod_round_to_zero will replace this with a % b for\n \/\/ unsigned ops, so create the intrinsic directly.\n Expr r = Call::make(a.type(), Call::mod_round_to_zero, {a, b}, Call::PureIntrinsic);\n if (a.type().is_int()) {\n \/\/ Match this non-overflowing C code\n \/*\n T r = a % b;\n r = r + (r < 0 ? abs(b) : 0);\n *\/\n\n r = select(r < 0, r + abs(b), r);\n return common_subexpression_elimination(r);\n } else {\n return r;\n }\n}\n\nbool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {\n #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)\n llvm::ConstantInt *c = llvm::cast(value);\n #else\n llvm::ConstantAsMetadata *cam = llvm::cast(value);\n llvm::ConstantInt *c = llvm::cast(cam->getValue());\n #endif\n if (c) {\n result = !c->isZero();\n return true;\n }\n return false;\n}\n\nbool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {\n #if LLVM_VERSION < 36\n if (llvm::dyn_cast(value)) {\n result = \"\";\n return true;\n }\n llvm::ConstantDataArray *c = llvm::cast(value);\n if (c) {\n result = c->getAsCString();\n return true;\n }\n #else\n llvm::MDString *c = llvm::dyn_cast(value);\n if (c) {\n result = c->getString();\n return true;\n }\n #endif\n return false;\n}\n\nvoid get_target_options(const llvm::Module &module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {\n bool use_soft_float_abi = false;\n get_md_bool(module.getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi);\n get_md_string(module.getModuleFlag(\"halide_mcpu\"), mcpu);\n get_md_string(module.getModuleFlag(\"halide_mattrs\"), mattrs);\n\n options = llvm::TargetOptions();\n options.LessPreciseFPMADOption = true;\n options.AllowFPOpFusion = llvm::FPOpFusion::Fast;\n \/\/ Disabled because it makes LLVM compile vector division to\n \/\/ multiplication by approx reciprocal, which is too inaccurate\n \/\/ even for us.\n options.UnsafeFPMath = false;\n options.NoInfsFPMath = true;\n options.NoNaNsFPMath = true;\n options.HonorSignDependentRoundingFPMathOption = false;\n #if LLVM_VERSION < 37\n options.NoFramePointerElim = false;\n options.UseSoftFloat = false;\n #endif\n options.NoZerosInBSS = false;\n options.GuaranteedTailCallOpt = false;\n #if LLVM_VERSION < 37\n options.DisableTailCalls = false;\n #endif\n options.StackAlignmentOverride = 0;\n #if LLVM_VERSION < 37\n options.TrapFuncName = \"\";\n #endif\n options.FunctionSections = true;\n #ifdef WITH_NATIVE_CLIENT\n options.UseInitArray = true;\n #else\n options.UseInitArray = false;\n #endif\n options.FloatABIType =\n use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;\n}\n\n\nvoid clone_target_options(const llvm::Module &from, llvm::Module &to) {\n to.setTargetTriple(from.getTargetTriple());\n\n llvm::LLVMContext &context = to.getContext();\n\n bool use_soft_float_abi = false;\n if (get_md_bool(from.getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi))\n to.addModuleFlag(llvm::Module::Warning, \"halide_use_soft_float_abi\", use_soft_float_abi ? 1 : 0);\n\n std::string mcpu;\n if (get_md_string(from.getModuleFlag(\"halide_mcpu\"), mcpu)) {\n #if LLVM_VERSION < 36\n to.addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::ConstantDataArray::getString(context, mcpu));\n #else\n to.addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::MDString::get(context, mcpu));\n #endif\n }\n\n std::string mattrs;\n if (get_md_string(from.getModuleFlag(\"halide_mattrs\"), mattrs)) {\n #if LLVM_VERSION < 36\n to.addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::ConstantDataArray::getString(context, mattrs));\n #else\n to.addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::MDString::get(context, mattrs));\n #endif\n }\n}\n\nllvm::TargetMachine *get_target_machine(const llvm::Module &module) {\n std::string error_string;\n\n const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module.getTargetTriple(), error_string);\n if (!target) {\n std::cout << error_string << std::endl;\n llvm::TargetRegistry::printRegisteredTargetsForVersion();\n }\n internal_assert(target) << \"Could not create target for \" << module.getTargetTriple() << \"\\n\";\n\n llvm::TargetOptions options;\n std::string mcpu = \"\";\n std::string mattrs = \"\";\n get_target_options(module, options, mcpu, mattrs);\n\n return target->createTargetMachine(module.getTargetTriple(),\n mcpu, mattrs,\n options,\n llvm::Reloc::PIC_,\n llvm::CodeModel::Default,\n llvm::CodeGenOpt::Aggressive);\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \"rtl\/uuid.h\"\n#include \"osl\/thread.h\"\n#include \"osl\/mutex.hxx\"\n\n#include \"uno\/environment.hxx\"\n#include \"uno\/mapping.hxx\"\n#include \"typelib\/typedescription.h\"\n\n#include \"current.hxx\"\n\n\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\n\nnamespace cppu\n{\n\nstatic typelib_InterfaceTypeDescription * get_type_XCurrentContext()\n{\n static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0;\n if (0 == s_type_XCurrentContext)\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if (0 == s_type_XCurrentContext)\n {\n OUString sTypeName(\"com.sun.star.uno.XCurrentContext\");\n typelib_InterfaceTypeDescription * pTD = 0;\n typelib_TypeDescriptionReference * pMembers[1] = { 0 };\n OUString sMethodName0(\"com.sun.star.uno.XCurrentContext::getValueByName\");\n typelib_typedescriptionreference_new(\n &pMembers[0],\n typelib_TypeClass_INTERFACE_METHOD,\n sMethodName0.pData );\n typelib_typedescription_newInterface(\n &pTD,\n sTypeName.pData, 0, 0, 0, 0, 0,\n * typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ),\n 1,\n pMembers );\n\n typelib_typedescription_register( (typelib_TypeDescription**)&pTD );\n typelib_typedescriptionreference_release( pMembers[0] );\n\n typelib_InterfaceMethodTypeDescription * pMethod = 0;\n typelib_Parameter_Init aParameters[1];\n OUString sParamName0(\"Name\");\n OUString sParamType0(\"string\");\n aParameters[0].pParamName = sParamName0.pData;\n aParameters[0].eTypeClass = typelib_TypeClass_STRING;\n aParameters[0].pTypeName = sParamType0.pData;\n aParameters[0].bIn = sal_True;\n aParameters[0].bOut = sal_False;\n rtl_uString * pExceptions[1];\n OUString sExceptionName0(\"com.sun.star.uno.RuntimeException\");\n pExceptions[0] = sExceptionName0.pData;\n OUString sReturnType0(\"any\");\n typelib_typedescription_newInterfaceMethod(\n &pMethod,\n 3, sal_False,\n sMethodName0.pData,\n typelib_TypeClass_ANY, sReturnType0.pData,\n 1, aParameters, 1, pExceptions );\n typelib_typedescription_register( (typelib_TypeDescription**)&pMethod );\n typelib_typedescription_release( (typelib_TypeDescription*)pMethod );\n \/\/ another static ref:\n ++reinterpret_cast< typelib_TypeDescription * >( pTD )->\n nStaticRefCount;\n s_type_XCurrentContext = pTD;\n }\n }\n return s_type_XCurrentContext;\n}\n\n\n\n\nclass ThreadKey\n{\n bool _bInit;\n oslThreadKey _hThreadKey;\n oslThreadKeyCallbackFunction _pCallback;\n\npublic:\n inline oslThreadKey getThreadKey() SAL_THROW(());\n\n inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(());\n inline ~ThreadKey() SAL_THROW(());\n};\n\ninline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(())\n : _bInit( false )\n , _pCallback( pCallback )\n{\n}\n\ninline ThreadKey::~ThreadKey() SAL_THROW(())\n{\n if (_bInit)\n {\n ::osl_destroyThreadKey( _hThreadKey );\n }\n}\n\ninline oslThreadKey ThreadKey::getThreadKey() SAL_THROW(())\n{\n if (! _bInit)\n {\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n if (! _bInit)\n {\n _hThreadKey = ::osl_createThreadKey( _pCallback );\n _bInit = true;\n }\n }\n return _hThreadKey;\n}\n\n\nextern \"C\" void SAL_CALL delete_IdContainer( void * p )\n{\n if (p)\n {\n IdContainer * pId = reinterpret_cast< IdContainer * >( p );\n if (pId->pCurrentContext)\n {\n (*pId->pCurrentContextEnv->releaseInterface)(\n pId->pCurrentContextEnv, pId->pCurrentContext );\n (*((uno_Environment *)pId->pCurrentContextEnv)->release)(\n (uno_Environment *)pId->pCurrentContextEnv );\n }\n if (pId->bInit)\n {\n ::rtl_byte_sequence_release( pId->pLocalThreadId );\n ::rtl_byte_sequence_release( pId->pCurrentId );\n }\n delete pId;\n }\n}\n\nIdContainer * getIdContainer() SAL_THROW(())\n{\n static ThreadKey s_key( delete_IdContainer );\n oslThreadKey aKey = s_key.getThreadKey();\n\n IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) );\n if (! pId)\n {\n pId = new IdContainer();\n pId->pCurrentContext = 0;\n pId->pCurrentContextEnv = 0;\n pId->bInit = false;\n ::osl_setThreadKeyData( aKey, pId );\n }\n return pId;\n}\n\n}\n\n\nextern \"C\" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_setCurrentContext(\n void * pCurrentContext,\n rtl_uString * pEnvTypeName, void * pEnvContext )\n SAL_THROW_EXTERN_C()\n{\n IdContainer * pId = getIdContainer();\n OSL_ASSERT( pId );\n\n \/\/ free old one\n if (pId->pCurrentContext)\n {\n (*pId->pCurrentContextEnv->releaseInterface)(\n pId->pCurrentContextEnv, pId->pCurrentContext );\n (*((uno_Environment *)pId->pCurrentContextEnv)->release)(\n (uno_Environment *)pId->pCurrentContextEnv );\n pId->pCurrentContextEnv = 0;\n\n pId->pCurrentContext = 0;\n }\n\n if (pCurrentContext)\n {\n uno_Environment * pEnv = 0;\n ::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext );\n OSL_ASSERT( pEnv && pEnv->pExtEnv );\n if (pEnv)\n {\n if (pEnv->pExtEnv)\n {\n pId->pCurrentContextEnv = pEnv->pExtEnv;\n (*pId->pCurrentContextEnv->acquireInterface)(\n pId->pCurrentContextEnv, pCurrentContext );\n pId->pCurrentContext = pCurrentContext;\n }\n else\n {\n (*pEnv->release)( pEnv );\n return sal_False;\n }\n }\n else\n {\n return sal_False;\n }\n }\n return sal_True;\n}\n\nextern \"C\" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_getCurrentContext(\n void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext )\n SAL_THROW_EXTERN_C()\n{\n IdContainer * pId = getIdContainer();\n OSL_ASSERT( pId );\n\n Environment target_env;\n\n \/\/ release inout parameter\n if (*ppCurrentContext)\n {\n target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);\n OSL_ASSERT( target_env.is() );\n if (! target_env.is())\n return sal_False;\n uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv;\n OSL_ASSERT( 0 != pEnv );\n if (0 == pEnv)\n return sal_False;\n (*pEnv->releaseInterface)( pEnv, *ppCurrentContext );\n\n *ppCurrentContext = 0;\n }\n\n \/\/ case: null-ref\n if (0 == pId->pCurrentContext)\n return sal_True;\n\n if (! target_env.is())\n {\n target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);\n OSL_ASSERT( target_env.is() );\n if (! target_env.is())\n return sal_False;\n }\n\n Mapping mapping((uno_Environment *) pId->pCurrentContextEnv, target_env.get());\n OSL_ASSERT( mapping.is() );\n if (! mapping.is())\n return sal_False;\n\n mapping.mapInterface(ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() );\n\n return sal_True;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ncoverity#707713 Uninitialized pointer field\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \"rtl\/uuid.h\"\n#include \"osl\/thread.h\"\n#include \"osl\/mutex.hxx\"\n\n#include \"uno\/environment.hxx\"\n#include \"uno\/mapping.hxx\"\n#include \"typelib\/typedescription.h\"\n\n#include \"current.hxx\"\n\n\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\n\nnamespace cppu\n{\n\nstatic typelib_InterfaceTypeDescription * get_type_XCurrentContext()\n{\n static typelib_InterfaceTypeDescription * s_type_XCurrentContext = 0;\n if (0 == s_type_XCurrentContext)\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if (0 == s_type_XCurrentContext)\n {\n OUString sTypeName(\"com.sun.star.uno.XCurrentContext\");\n typelib_InterfaceTypeDescription * pTD = 0;\n typelib_TypeDescriptionReference * pMembers[1] = { 0 };\n OUString sMethodName0(\"com.sun.star.uno.XCurrentContext::getValueByName\");\n typelib_typedescriptionreference_new(\n &pMembers[0],\n typelib_TypeClass_INTERFACE_METHOD,\n sMethodName0.pData );\n typelib_typedescription_newInterface(\n &pTD,\n sTypeName.pData, 0, 0, 0, 0, 0,\n * typelib_static_type_getByTypeClass( typelib_TypeClass_INTERFACE ),\n 1,\n pMembers );\n\n typelib_typedescription_register( (typelib_TypeDescription**)&pTD );\n typelib_typedescriptionreference_release( pMembers[0] );\n\n typelib_InterfaceMethodTypeDescription * pMethod = 0;\n typelib_Parameter_Init aParameters[1];\n OUString sParamName0(\"Name\");\n OUString sParamType0(\"string\");\n aParameters[0].pParamName = sParamName0.pData;\n aParameters[0].eTypeClass = typelib_TypeClass_STRING;\n aParameters[0].pTypeName = sParamType0.pData;\n aParameters[0].bIn = sal_True;\n aParameters[0].bOut = sal_False;\n rtl_uString * pExceptions[1];\n OUString sExceptionName0(\"com.sun.star.uno.RuntimeException\");\n pExceptions[0] = sExceptionName0.pData;\n OUString sReturnType0(\"any\");\n typelib_typedescription_newInterfaceMethod(\n &pMethod,\n 3, sal_False,\n sMethodName0.pData,\n typelib_TypeClass_ANY, sReturnType0.pData,\n 1, aParameters, 1, pExceptions );\n typelib_typedescription_register( (typelib_TypeDescription**)&pMethod );\n typelib_typedescription_release( (typelib_TypeDescription*)pMethod );\n \/\/ another static ref:\n ++reinterpret_cast< typelib_TypeDescription * >( pTD )->\n nStaticRefCount;\n s_type_XCurrentContext = pTD;\n }\n }\n return s_type_XCurrentContext;\n}\n\n\n\n\nclass ThreadKey\n{\n bool _bInit;\n oslThreadKey _hThreadKey;\n oslThreadKeyCallbackFunction _pCallback;\n\npublic:\n inline oslThreadKey getThreadKey() SAL_THROW(());\n\n inline ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(());\n inline ~ThreadKey() SAL_THROW(());\n};\n\ninline ThreadKey::ThreadKey( oslThreadKeyCallbackFunction pCallback ) SAL_THROW(())\n : _bInit( false )\n , _hThreadKey( 0 )\n , _pCallback( pCallback )\n{\n}\n\ninline ThreadKey::~ThreadKey() SAL_THROW(())\n{\n if (_bInit)\n {\n ::osl_destroyThreadKey( _hThreadKey );\n }\n}\n\ninline oslThreadKey ThreadKey::getThreadKey() SAL_THROW(())\n{\n if (! _bInit)\n {\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n if (! _bInit)\n {\n _hThreadKey = ::osl_createThreadKey( _pCallback );\n _bInit = true;\n }\n }\n return _hThreadKey;\n}\n\n\nextern \"C\" void SAL_CALL delete_IdContainer( void * p )\n{\n if (p)\n {\n IdContainer * pId = reinterpret_cast< IdContainer * >( p );\n if (pId->pCurrentContext)\n {\n (*pId->pCurrentContextEnv->releaseInterface)(\n pId->pCurrentContextEnv, pId->pCurrentContext );\n (*((uno_Environment *)pId->pCurrentContextEnv)->release)(\n (uno_Environment *)pId->pCurrentContextEnv );\n }\n if (pId->bInit)\n {\n ::rtl_byte_sequence_release( pId->pLocalThreadId );\n ::rtl_byte_sequence_release( pId->pCurrentId );\n }\n delete pId;\n }\n}\n\nIdContainer * getIdContainer() SAL_THROW(())\n{\n static ThreadKey s_key( delete_IdContainer );\n oslThreadKey aKey = s_key.getThreadKey();\n\n IdContainer * pId = reinterpret_cast< IdContainer * >( ::osl_getThreadKeyData( aKey ) );\n if (! pId)\n {\n pId = new IdContainer();\n pId->pCurrentContext = 0;\n pId->pCurrentContextEnv = 0;\n pId->bInit = false;\n ::osl_setThreadKeyData( aKey, pId );\n }\n return pId;\n}\n\n}\n\n\nextern \"C\" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_setCurrentContext(\n void * pCurrentContext,\n rtl_uString * pEnvTypeName, void * pEnvContext )\n SAL_THROW_EXTERN_C()\n{\n IdContainer * pId = getIdContainer();\n OSL_ASSERT( pId );\n\n \/\/ free old one\n if (pId->pCurrentContext)\n {\n (*pId->pCurrentContextEnv->releaseInterface)(\n pId->pCurrentContextEnv, pId->pCurrentContext );\n (*((uno_Environment *)pId->pCurrentContextEnv)->release)(\n (uno_Environment *)pId->pCurrentContextEnv );\n pId->pCurrentContextEnv = 0;\n\n pId->pCurrentContext = 0;\n }\n\n if (pCurrentContext)\n {\n uno_Environment * pEnv = 0;\n ::uno_getEnvironment( &pEnv, pEnvTypeName, pEnvContext );\n OSL_ASSERT( pEnv && pEnv->pExtEnv );\n if (pEnv)\n {\n if (pEnv->pExtEnv)\n {\n pId->pCurrentContextEnv = pEnv->pExtEnv;\n (*pId->pCurrentContextEnv->acquireInterface)(\n pId->pCurrentContextEnv, pCurrentContext );\n pId->pCurrentContext = pCurrentContext;\n }\n else\n {\n (*pEnv->release)( pEnv );\n return sal_False;\n }\n }\n else\n {\n return sal_False;\n }\n }\n return sal_True;\n}\n\nextern \"C\" CPPU_DLLPUBLIC sal_Bool SAL_CALL uno_getCurrentContext(\n void ** ppCurrentContext, rtl_uString * pEnvTypeName, void * pEnvContext )\n SAL_THROW_EXTERN_C()\n{\n IdContainer * pId = getIdContainer();\n OSL_ASSERT( pId );\n\n Environment target_env;\n\n \/\/ release inout parameter\n if (*ppCurrentContext)\n {\n target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);\n OSL_ASSERT( target_env.is() );\n if (! target_env.is())\n return sal_False;\n uno_ExtEnvironment * pEnv = target_env.get()->pExtEnv;\n OSL_ASSERT( 0 != pEnv );\n if (0 == pEnv)\n return sal_False;\n (*pEnv->releaseInterface)( pEnv, *ppCurrentContext );\n\n *ppCurrentContext = 0;\n }\n\n \/\/ case: null-ref\n if (0 == pId->pCurrentContext)\n return sal_True;\n\n if (! target_env.is())\n {\n target_env = Environment(rtl::OUString(pEnvTypeName), pEnvContext);\n OSL_ASSERT( target_env.is() );\n if (! target_env.is())\n return sal_False;\n }\n\n Mapping mapping((uno_Environment *) pId->pCurrentContextEnv, target_env.get());\n OSL_ASSERT( mapping.is() );\n if (! mapping.is())\n return sal_False;\n\n mapping.mapInterface(ppCurrentContext, pId->pCurrentContext, ::cppu::get_type_XCurrentContext() );\n\n return sal_True;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*\nPart of Scallop Transcript Assembler\n(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.\nSee LICENSE for licensing.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"transcript.h\"\n\ntranscript::transcript()\n{\n}\n\ntranscript::transcript(const item &e)\n{\n\tassign(e);\n\texons.clear();\n}\n\ntranscript::~transcript()\n{\n}\n\nint transcript::assign(const item &e)\n{\n\t\/\/assert(e.feature == \"transcript\");\n\tseqname = e.seqname;\n\tsource = e.source;\n\tfeature = e.feature;\n\tgene_id = e.gene_id;\n\ttranscript_id = e.transcript_id;\n\tstart = e.start;\n\tend = e.end;\n\tstrand = e.strand;\n\tframe = e.frame;\n\tcoverage = e.coverage;\n\tRPKM = e.RPKM;\n\tFPKM = e.FPKM;\n\tTPM = e.TPM;\n\treturn 0;\n}\n\nbool transcript::operator< (const transcript &t) const\n{\n\tint b = seqname.compare(t.seqname);\n\tif(b < 0) return true;\n\tif(b > 0) return false;\n\tif(exons.size() == 0) return true;\n\tif(t.exons.size() == 0) return false;\n\tif(exons[0].first < t.exons[0].first) return true;\n\telse return false;\n}\n\nint transcript::clear()\n{\n\texons.clear();\n\tseqname = \"\";\n\tsource = \"\";\n\tfeature = \"\";\n\tgene_id = \"\";\n\ttranscript_id = \"\";\n\tstart = 0;\n\tend = 0;\n\tstrand = '.';\n\tframe = -1;\n\tcoverage = 0;\n\tRPKM = 0;\n\tTPM = 0;\n\treturn 0;\n}\n\nint transcript::add_exon(int s, int t)\n{\n\texons.push_back(PI32(s, t));\n\treturn 0;\n}\n\nint transcript::add_exon(const item &e)\n{\n\tassert(e.transcript_id == transcript_id);\n\tadd_exon(e.start, e.end);\n\treturn 0;\n}\n\nint transcript::sort()\n{\n\tstd::sort(exons.begin(), exons.end());\n\treturn 0;\n}\n\nint transcript::shrink()\n{\n\tif(exons.size() == 0) return 0;\n\tvector v;\n\tPI32 p = exons[0];\n\tfor(int i = 1; i < exons.size(); i++)\n\t{\n\t\tPI32 q = exons[i];\n\t\tif(p.second == q.first)\n\t\t{\n\t\t\tp.second = q.second;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/assert(p.second < q.first);\n\t\t\tv.push_back(p);\n\t\t\tp = q;\n\t\t}\n\t}\n\tv.push_back(p);\n\texons = v;\n\treturn 0;\n}\n\nint transcript::assign_RPKM(double factor)\n{\n\tRPKM = coverage * factor;\n\treturn 0;\n}\n\nint transcript::length() const\n{\n\tint s = 0;\n\tfor(int i = 0; i < exons.size(); i++)\n\t{\n\t\tassert(exons[i].second > exons[i].first);\n\t\ts += exons[i].second - exons[i].first;\n\t}\n\treturn s;\n}\n\nPI32 transcript::get_bounds() const\n{\n\tif(exons.size() == 0) return PI32(-1, -1);\n\tint32_t p = exons[0].first;\n\tint32_t q = exons[exons.size() - 1].second;\n\treturn PI32(p, q);\n}\n\nPI32 transcript::get_first_intron() const\n{\n\tif(exons.size() <= 1) return PI32(-1, -1);\n\tint32_t p = exons[0].second;\n\tint32_t q = exons[1].first;\n\treturn PI32(p, q);\n}\n\nbool transcript::intron_chain_match(const transcript &t) const\n{\n\tif(exons.size() != t.exons.size()) return false;\n\tif(exons.size() <= 1) return false;\n\tint n = exons.size() - 1;\n\tif(exons[0].second != t.exons[0].second) return false;\n\tif(exons[n].first != t.exons[n].first) return false;\n\tfor(int k = 1; k < n - 1; k++)\n\t{\n\t\tif(exons[k].first != t.exons[k].first) return false;\n\t\tif(exons[k].second != t.exons[k].second) return false;\n\t}\n\treturn true;\n}\n\nstring transcript::label() const\n{\n\tchar buf[10240];\n\tPI32 p = get_bounds();\n\tsprintf(buf, \"%s:%d-%d\", seqname.c_str(), p.first, p.second);\n\treturn string(buf);\n}\n\nint transcript::write(ostream &fout) const\n{\n\tfout.precision(4);\n\tfout<do not print TPM or FPKM\/*\nPart of Scallop Transcript Assembler\n(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.\nSee LICENSE for licensing.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"transcript.h\"\n\ntranscript::transcript()\n{\n}\n\ntranscript::transcript(const item &e)\n{\n\tassign(e);\n\texons.clear();\n}\n\ntranscript::~transcript()\n{\n}\n\nint transcript::assign(const item &e)\n{\n\t\/\/assert(e.feature == \"transcript\");\n\tseqname = e.seqname;\n\tsource = e.source;\n\tfeature = e.feature;\n\tgene_id = e.gene_id;\n\ttranscript_id = e.transcript_id;\n\tstart = e.start;\n\tend = e.end;\n\tstrand = e.strand;\n\tframe = e.frame;\n\tcoverage = e.coverage;\n\tRPKM = e.RPKM;\n\tFPKM = e.FPKM;\n\tTPM = e.TPM;\n\treturn 0;\n}\n\nbool transcript::operator< (const transcript &t) const\n{\n\tint b = seqname.compare(t.seqname);\n\tif(b < 0) return true;\n\tif(b > 0) return false;\n\tif(exons.size() == 0) return true;\n\tif(t.exons.size() == 0) return false;\n\tif(exons[0].first < t.exons[0].first) return true;\n\telse return false;\n}\n\nint transcript::clear()\n{\n\texons.clear();\n\tseqname = \"\";\n\tsource = \"\";\n\tfeature = \"\";\n\tgene_id = \"\";\n\ttranscript_id = \"\";\n\tstart = 0;\n\tend = 0;\n\tstrand = '.';\n\tframe = -1;\n\tcoverage = 0;\n\tRPKM = 0;\n\tTPM = 0;\n\treturn 0;\n}\n\nint transcript::add_exon(int s, int t)\n{\n\texons.push_back(PI32(s, t));\n\treturn 0;\n}\n\nint transcript::add_exon(const item &e)\n{\n\tassert(e.transcript_id == transcript_id);\n\tadd_exon(e.start, e.end);\n\treturn 0;\n}\n\nint transcript::sort()\n{\n\tstd::sort(exons.begin(), exons.end());\n\treturn 0;\n}\n\nint transcript::shrink()\n{\n\tif(exons.size() == 0) return 0;\n\tvector v;\n\tPI32 p = exons[0];\n\tfor(int i = 1; i < exons.size(); i++)\n\t{\n\t\tPI32 q = exons[i];\n\t\tif(p.second == q.first)\n\t\t{\n\t\t\tp.second = q.second;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/assert(p.second < q.first);\n\t\t\tv.push_back(p);\n\t\t\tp = q;\n\t\t}\n\t}\n\tv.push_back(p);\n\texons = v;\n\treturn 0;\n}\n\nint transcript::assign_RPKM(double factor)\n{\n\tRPKM = coverage * factor;\n\treturn 0;\n}\n\nint transcript::length() const\n{\n\tint s = 0;\n\tfor(int i = 0; i < exons.size(); i++)\n\t{\n\t\tassert(exons[i].second > exons[i].first);\n\t\ts += exons[i].second - exons[i].first;\n\t}\n\treturn s;\n}\n\nPI32 transcript::get_bounds() const\n{\n\tif(exons.size() == 0) return PI32(-1, -1);\n\tint32_t p = exons[0].first;\n\tint32_t q = exons[exons.size() - 1].second;\n\treturn PI32(p, q);\n}\n\nPI32 transcript::get_first_intron() const\n{\n\tif(exons.size() <= 1) return PI32(-1, -1);\n\tint32_t p = exons[0].second;\n\tint32_t q = exons[1].first;\n\treturn PI32(p, q);\n}\n\nbool transcript::intron_chain_match(const transcript &t) const\n{\n\tif(exons.size() != t.exons.size()) return false;\n\tif(exons.size() <= 1) return false;\n\tint n = exons.size() - 1;\n\tif(exons[0].second != t.exons[0].second) return false;\n\tif(exons[n].first != t.exons[n].first) return false;\n\tfor(int k = 1; k < n - 1; k++)\n\t{\n\t\tif(exons[k].first != t.exons[k].first) return false;\n\t\tif(exons[k].second != t.exons[k].second) return false;\n\t}\n\treturn true;\n}\n\nstring transcript::label() const\n{\n\tchar buf[10240];\n\tPI32 p = get_bounds();\n\tsprintf(buf, \"%s:%d-%d\", seqname.c_str(), p.first, p.second);\n\treturn string(buf);\n}\n\nint transcript::write(ostream &fout) const\n{\n\tfout.precision(4);\n\tfout<"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace phosphor\n{\nnamespace network\n{\n\nusing namespace std::chrono_literals;\n\n\/\/ wait for three seconds before restarting the networkd\nconstexpr auto restartTimeout = 3s;\n\n\/\/ refresh the objets after five seconds as network\n\/\/ configuration takes 3-4 sec after systemd-networkd restart.\nconstexpr auto refreshTimeout = restartTimeout + 7s;\n\nnamespace systemd\n{\nnamespace config\n{\n\nconstexpr auto networkFilePrefix = \"00-bmc-\";\nconstexpr auto networkFileSuffix = \".network\";\nconstexpr auto deviceFileSuffix = \".netdev\";\n\n} \/\/ namespace config\n} \/\/ namespace systemd\n\nusing IntfName = std::string;\n\nstruct AddrInfo\n{\n uint8_t addrType;\n std::string ipaddress;\n uint16_t prefix;\n};\n\nusing Addr_t = ifaddrs*;\n\nstruct AddrDeleter\n{\n void operator()(Addr_t ptr) const\n {\n freeifaddrs(ptr);\n }\n};\n\nusing AddrPtr = std::unique_ptr;\n\n\/* Need a custom deleter for freeing up sd_event *\/\nstruct EventDeleter\n{\n void operator()(sd_event* event) const\n {\n event = sd_event_unref(event);\n }\n};\nusing EventPtr = std::unique_ptr;\n\ntemplate \nusing UniquePtr = std::unique_ptr>;\n\nusing AddrList = std::list;\nusing IntfAddrMap = std::map;\nusing InterfaceList = std::set;\n\nusing Timer = sdeventplus::utility::Timer;\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\ntypes: Add types for IPs and MACs in byte form#pragma once\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace phosphor\n{\nnamespace network\n{\n\nusing namespace std::chrono_literals;\n\n\/\/ wait for three seconds before restarting the networkd\nconstexpr auto restartTimeout = 3s;\n\n\/\/ refresh the objets after five seconds as network\n\/\/ configuration takes 3-4 sec after systemd-networkd restart.\nconstexpr auto refreshTimeout = restartTimeout + 7s;\n\nnamespace systemd\n{\nnamespace config\n{\n\nconstexpr auto networkFilePrefix = \"00-bmc-\";\nconstexpr auto networkFileSuffix = \".network\";\nconstexpr auto deviceFileSuffix = \".netdev\";\n\n} \/\/ namespace config\n} \/\/ namespace systemd\n\nusing IntfName = std::string;\n\nstruct AddrInfo\n{\n uint8_t addrType;\n std::string ipaddress;\n uint16_t prefix;\n};\n\nusing Addr_t = ifaddrs*;\n\nstruct AddrDeleter\n{\n void operator()(Addr_t ptr) const\n {\n freeifaddrs(ptr);\n }\n};\n\nusing AddrPtr = std::unique_ptr;\n\n\/* Need a custom deleter for freeing up sd_event *\/\nstruct EventDeleter\n{\n void operator()(sd_event* event) const\n {\n event = sd_event_unref(event);\n }\n};\nusing EventPtr = std::unique_ptr;\n\ntemplate \nusing UniquePtr = std::unique_ptr>;\n\n\/\/ Byte representations for common address types in network byte order\nusing InAddrAny = std::variant;\nusing MacAddr = std::array;\n\nusing AddrList = std::list;\nusing IntfAddrMap = std::map;\nusing InterfaceList = std::set;\n\nusing Timer = sdeventplus::utility::Timer;\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\n<|endoftext|>"} {"text":"#include \"bloomierHash.h\"\n\nBloomierHash::BloomierHash(size_t pHashSeed, size_t pM, size_t pK, size_t pQ, size_t pByte) {\n\n}\n\nsize_t BloomierHash::getHashValue(size_t pKey) {\n\n}\nsize_t BloomierHash::getM(size_t pKey) {\n\n}\nvsize_t* BloomierHash::getNeighborhood(size_t pKey){\n\n}\nvsize_t* BloomierHash::getM(size_t pKey){\n\n}Implementation added#include \"bloomierHash.h\"\n\nBloomierHash::BloomierHash(size_t pM, size_t pK, size_t pBitVectorSize) {\n\tmM = pM;\n\tmK = pK;\n\t\/\/ mQ = pQ;\n\tmHash = new Hash();\n\tmBitVectorSize = pBitVectorSize;\n};\nBloomierHash::~BloomierHash() {\n\n};\nbitVector* BloomierHash::getMask(size_t pKey) {\n\tbitVector* mask = new bitVector(mBitVectorSize);\n\tfor (size_t i = 0; i < mBitVectorSize; ++i) {\n\t\tsrand(pKey);\n\t\t(*mask)[i] = static_cast(rand() % 255);\n\t}\n\treturn mask;\n};\nvsize_t* BloomierHash::getKNeighbors(size_t pElement, size_t pK, size_t pModulo) {\n\t\n\tvsize_t* kNeighbors = new vsize_t(pK);\n\tfor (size_t i = 0; i < pK; ++i) {\n\t\t(*kNeighbors)[i] = mHash->hash(pElement+1, pModulo, i+1);\n\t}\n\treturn kNeighbors;\n};<|endoftext|>"} {"text":"\/*\n * CoordinateSystem.hpp\n *\n * Created on: Oct 15, 2014\n * Author: Carsten Uphoff (uphoff@mytum.de)\n *\/\n#ifndef HPLOTLIB_LEGEND_HPP\n#define HPLOTLIB_LEGEND_HPP\n\n#include \"Plot.hpp\"\n#include \"Statistics.hpp\"\n\n#include \n\n#include \n\nnamespace hpl\n{\nclass Font;\nclass CoordinateSystem {\npublic:\n\ttypedef IDBase ID;\n\n\tstatic constexpr float XOffset = 0.12f;\n\tstatic constexpr float YOffset = 0.08f;\n\tstatic constexpr int Ticks = 8;\n\tstatic constexpr float TickLength = 0.02f;\n\n CoordinateSystem(Font* font);\n ~CoordinateSystem();\n\n float* getLines() const;\n inline unsigned int getLinesCount() const {\n return 8 + 2*Ticks*4;\n } \n inline Registry& getPlots() {\n return plots;\n }\n \n void setColor(const Color& c);\n void setGeometry(Geometry geom);\n \n template\n T& addPlot(int n, double const* x, double const* y);\n\n\tvirtual void init(GLuint lineprogram, GLuint textprogram);\n\tvirtual void destroy();\n\tvirtual void draw(float const* mvp);\n\t\n\tvirtual void update();\n\n Delegate<> changed;\n \n inline ID id() const { return csId; }\n inline void setId(ID id) { csId = id; }\n\t\nprivate:\n void updateLimits(double xmin, double xmax, double ymin, double ymax);\n\n Registry plots;\n\tstd::queue plotInit;\n ID csId;\n\tGeometry geometry;\n\n\tFont* font;\n\tColor drawColor;\n\tbool updateLabels = false;\n\n\tdouble xmin = std::numeric_limits::min();\n\tdouble xmax = std::numeric_limits::max();\n\tdouble ymin = std::numeric_limits::min();\n\tdouble ymax = std::numeric_limits::max();\n\n GLuint lineBuffer;\n GLuint textBuffer;\n GLuint lineprogram;\n GLuint textprogram;\n \n\tGLint linepos, linerect, linecolor, linemvp, textpos, textuv, textrect, textglyphs, textmvp, textcolor;\n\tint numLines = 0;\n\tint numChars = 0;\n\n float* lines = nullptr;\n};\n\ntemplate\nT& CoordinateSystem::addPlot(int n, double const* x, double const* y)\n{\n\tupdateLimits(hpl::min(n, x), hpl::max(n, x), hpl::min(n, y), hpl::max(n, y));\n\t\n T* plot = new T(n, x, y);\n plot->changed.template bind, &Delegate<>::invoke>(&changed);\n Plot::ID id = plots.add(plot); \n plotInit.push(id);\n setGeometry(geometry);\n changed.invoke();\n return *plot;\n}\n}\n\n#endif\n\nFixed header guard\/*\n * CoordinateSystem.hpp\n *\n * Created on: Oct 15, 2014\n * Author: Carsten Uphoff (uphoff@mytum.de)\n *\/\n#ifndef HPLOTLIB_COORDINATESYSTEM_HPP\n#define HPLOTLIB_COORDINATESYSTEM_HPP\n\n#include \"Plot.hpp\"\n#include \"Statistics.hpp\"\n\n#include \n\n#include \n\nnamespace hpl\n{\nclass Font;\nclass CoordinateSystem {\npublic:\n\ttypedef IDBase ID;\n\n\tstatic constexpr float XOffset = 0.12f;\n\tstatic constexpr float YOffset = 0.08f;\n\tstatic constexpr int Ticks = 8;\n\tstatic constexpr float TickLength = 0.02f;\n\n CoordinateSystem(Font* font);\n ~CoordinateSystem();\n\n float* getLines() const;\n inline unsigned int getLinesCount() const {\n return 8 + 2*Ticks*4;\n } \n inline Registry& getPlots() {\n return plots;\n }\n \n void setColor(const Color& c);\n void setGeometry(Geometry geom);\n \n template\n T& addPlot(int n, double const* x, double const* y);\n\n\tvirtual void init(GLuint lineprogram, GLuint textprogram);\n\tvirtual void destroy();\n\tvirtual void draw(float const* mvp);\n\t\n\tvirtual void update();\n\n Delegate<> changed;\n \n inline ID id() const { return csId; }\n inline void setId(ID id) { csId = id; }\n\t\nprivate:\n void updateLimits(double xmin, double xmax, double ymin, double ymax);\n\n Registry plots;\n\tstd::queue plotInit;\n ID csId;\n\tGeometry geometry;\n\n\tFont* font;\n\tColor drawColor;\n\tbool updateLabels = false;\n\n\tdouble xmin = std::numeric_limits::min();\n\tdouble xmax = std::numeric_limits::max();\n\tdouble ymin = std::numeric_limits::min();\n\tdouble ymax = std::numeric_limits::max();\n\n GLuint lineBuffer;\n GLuint textBuffer;\n GLuint lineprogram;\n GLuint textprogram;\n \n\tGLint linepos, linerect, linecolor, linemvp, textpos, textuv, textrect, textglyphs, textmvp, textcolor;\n\tint numLines = 0;\n\tint numChars = 0;\n\n float* lines = nullptr;\n};\n\ntemplate\nT& CoordinateSystem::addPlot(int n, double const* x, double const* y)\n{\n\tupdateLimits(hpl::min(n, x), hpl::max(n, x), hpl::min(n, y), hpl::max(n, y));\n\t\n T* plot = new T(n, x, y);\n plot->changed.template bind, &Delegate<>::invoke>(&changed);\n Plot::ID id = plots.add(plot); \n plotInit.push(id);\n setGeometry(geometry);\n changed.invoke();\n return *plot;\n}\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: VAxisProperties.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 01:37:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"VAxisProperties.hxx\"\n#include \"macros.hxx\"\n#include \"ViewDefines.hxx\"\n#include \"CommonConverters.hxx\"\n\n#ifndef _TOOLS_COLOR_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART_CHARTAXISARRANGEORDERTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TEXT_WRITINGMODE2_HPP_\n#include \n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::chart2;\n\nsal_Int32 lcl_calcTickLengthForDepth(sal_Int32 nDepth,sal_Int32 nTickmarkStyle)\n{\n sal_Int32 nWidth = AXIS2D_TICKLENGTH; \/\/@maybefuturetodo this length could be offered by the model\n double fPercent = 1.0;\n switch(nDepth)\n {\n case 0:\n fPercent = 1.0;\n break;\n case 1:\n fPercent = 0.75;\/\/percentage like in the old chart\n break;\n case 2:\n fPercent = 0.5;\n break;\n default:\n fPercent = 0.3;\n break;\n }\n if(nTickmarkStyle==3)\/\/inner and outer tickmarks\n fPercent*=2.0;\n return static_cast(nWidth*fPercent);\n}\n\ndouble lcl_getTickOffset(sal_Int32 nLength,sal_Int32 nTickmarkStyle)\n{\n double fPercent = 0.0; \/\/0<=fPercent<=1\n \/\/0.0: completly inner\n \/\/1.0: completly outer\n \/\/0.5: half and half\n\n \/*\n nTickmarkStyle:\n 1: inner tickmarks\n 2: outer tickmarks\n 3: inner and outer tickmarks\n *\/\n switch(nTickmarkStyle)\n {\n case 1:\n fPercent = 0.0;\n break;\n case 2:\n fPercent = 1.0;\n break;\n default:\n fPercent = 0.5;\n break;\n }\n return fPercent*nLength;\n}\n\nVLineProperties AxisProperties::makeLinePropertiesForDepth( sal_Int32 nDepth ) const\n{\n \/\/@todo get this from somewhere; maybe for each subincrement\n \/\/so far the model does not offer different settings for each tick depth\n return m_aLineProperties;\n}\n\nTickmarkProperties AxisProperties::makeTickmarkProperties(\n sal_Int32 nDepth ) const\n{\n \/*\n nTickmarkStyle:\n 1: inner tickmarks\n 2: outer tickmarks\n 3: inner and outer tickmarks\n *\/\n sal_Int32 nTickmarkStyle = 1;\n if(nDepth==0)\n {\n nTickmarkStyle = m_nMajorTickmarks;\n if(!nTickmarkStyle)\n {\n \/\/create major tickmarks as if they were minor tickmarks\n nDepth = 1;\n nTickmarkStyle = m_nMinorTickmarks;\n }\n }\n else if( nDepth==1)\n {\n nTickmarkStyle = m_nMinorTickmarks;\n }\n\n if( m_fInnerDirectionSign == 0.0 )\n {\n if( nTickmarkStyle != 0 )\n nTickmarkStyle = 3; \/\/inner and outer tickmarks\n }\n\n TickmarkProperties aTickmarkProperties;\n aTickmarkProperties.Length = lcl_calcTickLengthForDepth(nDepth,nTickmarkStyle);\n aTickmarkProperties.RelativePos = static_cast(lcl_getTickOffset(aTickmarkProperties.Length,nTickmarkStyle));\n aTickmarkProperties.aLineProperties = this->makeLinePropertiesForDepth( nDepth );\n return aTickmarkProperties;\n}\n\n\/\/--------------------------------------------------------------------------\n\nAxisProperties::AxisProperties( const uno::Reference< XAxis >& xAxisModel\n , const ::com::sun::star::awt::Size& rReferenceSize )\n : m_xAxisModel(xAxisModel)\n , m_aReferenceSize(rReferenceSize)\n , m_bIsMainAxis(true)\n , m_pfMainLinePositionAtOtherAxis(NULL)\n , m_pfExrtaLinePositionAtOtherAxis(NULL)\n , m_fInnerDirectionSign(1.0)\n , m_bLabelsOutside(true)\n , m_aLabelAlignment(LABEL_ALIGN_RIGHT_TOP)\n , m_bDisplayLabels( true )\n\/\/ , m_eRelativeLabelPosition(LEFTORBOTTOM_OF_AXIS)\n , m_nMajorTickmarks(1)\n , m_nMinorTickmarks(1)\n , m_aTickmarkPropertiesList()\n , m_aLineProperties()\n{\n}\n\nAxisProperties::AxisProperties( const AxisProperties& rAxisProperties )\n : m_xAxisModel( rAxisProperties.m_xAxisModel )\n , m_aReferenceSize( rAxisProperties.m_aReferenceSize )\n , m_bIsMainAxis( rAxisProperties.m_bIsMainAxis )\n , m_pfMainLinePositionAtOtherAxis( NULL )\n , m_pfExrtaLinePositionAtOtherAxis( NULL )\n , m_fInnerDirectionSign( rAxisProperties.m_fInnerDirectionSign )\n , m_bLabelsOutside( rAxisProperties.m_bLabelsOutside )\n , m_aLabelAlignment( rAxisProperties.m_aLabelAlignment )\n , m_bDisplayLabels( rAxisProperties.m_bDisplayLabels )\n\/\/ , m_eRelativeLabelPosition( rAxisProperties.m_eRelativeLabelPosition )\n , m_nMajorTickmarks( rAxisProperties.m_nMajorTickmarks )\n , m_nMinorTickmarks( rAxisProperties.m_nMinorTickmarks )\n , m_aTickmarkPropertiesList( rAxisProperties.m_aTickmarkPropertiesList )\n , m_aLineProperties( rAxisProperties.m_aLineProperties )\n{\n if( rAxisProperties.m_pfMainLinePositionAtOtherAxis )\n m_pfMainLinePositionAtOtherAxis = new double(*rAxisProperties.m_pfMainLinePositionAtOtherAxis);\n if( rAxisProperties.m_pfExrtaLinePositionAtOtherAxis )\n m_pfExrtaLinePositionAtOtherAxis = new double (*rAxisProperties.m_pfExrtaLinePositionAtOtherAxis);\n}\n\nAxisProperties::~AxisProperties()\n{\n delete m_pfMainLinePositionAtOtherAxis;\n delete m_pfExrtaLinePositionAtOtherAxis;\n}\n\nLabelAlignment lcl_getLabelAlignment( const AxisProperties& rAxisProperties, bool bIsYAxis )\n{\n LabelAlignment aRet( LABEL_ALIGN_LEFT );\n if(bIsYAxis)\n {\n if(rAxisProperties.m_bIsMainAxis)\n {\n if( rAxisProperties.m_bLabelsOutside )\n aRet = LABEL_ALIGN_LEFT;\n else\n aRet = LABEL_ALIGN_RIGHT;\n }\n else\n {\n if( !rAxisProperties.m_bLabelsOutside )\n aRet = LABEL_ALIGN_LEFT;\n else\n aRet = LABEL_ALIGN_RIGHT;\n }\n }\n else\n {\n if(rAxisProperties.m_bIsMainAxis )\n {\n if(rAxisProperties.m_bLabelsOutside)\n aRet = LABEL_ALIGN_BOTTOM;\n else\n aRet = LABEL_ALIGN_TOP;\n }\n else\n {\n if(!rAxisProperties.m_bLabelsOutside)\n aRet = LABEL_ALIGN_BOTTOM;\n else\n aRet = LABEL_ALIGN_TOP;\n }\n }\n return aRet;\n}\n\nvoid AxisProperties::init( bool bCartesian )\n{\n if( bCartesian )\n {\n sal_Int32 nDimensionIndex = m_xAxisModel->getRepresentedDimension();\n m_fInnerDirectionSign = m_bIsMainAxis ? 1 : -1;\n if(nDimensionIndex==1)\n m_fInnerDirectionSign*=-1;\n m_aLabelAlignment = lcl_getLabelAlignment(*this,nDimensionIndex==1);\n }\n\n uno::Reference< beans::XPropertySet > xProp =\n uno::Reference::query( this->m_xAxisModel );\n if( !xProp.is() )\n return;\n\n try\n {\n \/\/init LineProperties\n m_aLineProperties.initFromPropertySet( xProp );\n\n \/\/init display labels\n xProp->getPropertyValue( C2U( \"DisplayLabels\" ) ) >>= m_bDisplayLabels;\n\n \/\/init TickmarkProperties\n xProp->getPropertyValue( C2U( \"MajorTickmarks\" ) ) >>= m_nMajorTickmarks;\n xProp->getPropertyValue( C2U( \"MinorTickmarks\" ) ) >>= m_nMinorTickmarks;\n\n sal_Int32 nMaxDepth = 0;\n if(m_nMinorTickmarks!=0)\n nMaxDepth=2;\n else if(m_nMajorTickmarks!=0)\n nMaxDepth=1;\n\n this->m_aTickmarkPropertiesList.clear();\n for( sal_Int32 nDepth=0; nDepthmakeTickmarkProperties( nDepth );\n this->m_aTickmarkPropertiesList.push_back( aTickmarkProperties );\n }\n }\n catch( uno::Exception& e )\n {\n e;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\nAxisLabelProperties::AxisLabelProperties()\n : aNumberFormat()\n , eStaggering( SIDE_BY_SIDE )\n , bLineBreakAllowed( true )\n , bOverlapAllowed( false )\n , bStackCharacters( false )\n , fRotationAngleDegree( 0.0 )\n , nRhythm( 1 )\n , bRhythmIsFix(false)\n{\n \/*\n aLocale.Language = C2U( \"en\" );\n aLocale.Country = C2U( \"US\" );\n\n \/\/aLocale.Language = C2U( \"ar\" );\n \/\/aLocale.Country = C2U( \"IR\" );\n\n \/\/aLocale.Language = C2U( \"ja\" );\n \/\/aLocale.Country = C2U( \"JP\" );\n *\/\n}\n\nvoid AxisLabelProperties::init( const uno::Reference< XAxis >& xAxisModel )\n{\n uno::Reference< beans::XPropertySet > xProp =\n uno::Reference::query( xAxisModel );\n if(xProp.is())\n {\n try\n {\n if( !( xProp->getPropertyValue( C2U( \"NumberFormat\" ) ) >>= this->aNumberFormat ) )\n {\n \/\/@todo get number format from calc\n }\n\n xProp->getPropertyValue( C2U( \"TextBreak\" ) ) >>= this->bLineBreakAllowed;\n xProp->getPropertyValue( C2U( \"TextOverlap\" ) ) >>= this->bOverlapAllowed;\n xProp->getPropertyValue( C2U( \"StackCharacters\" ) ) >>= this->bStackCharacters;\n xProp->getPropertyValue( C2U( \"TextRotation\" ) ) >>= this->fRotationAngleDegree;\n\n ::com::sun::star::chart::ChartAxisArrangeOrderType eArrangeOrder;\n xProp->getPropertyValue( C2U( \"ArrangeOrder\" ) ) >>= eArrangeOrder;\n switch(eArrangeOrder)\n {\n case ::com::sun::star::chart::ChartAxisArrangeOrderType_SIDE_BY_SIDE:\n this->eStaggering = SIDE_BY_SIDE;\n break;\n case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_EVEN:\n this->eStaggering = STAGGER_EVEN;\n break;\n case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_ODD:\n this->eStaggering = STAGGER_ODD;\n break;\n default:\n this->eStaggering = STAGGER_AUTO;\n break;\n }\n }\n catch( uno::Exception& e )\n {\n e;\n }\n }\n}\n\n\/*\nsal_Int16 getSwappedWritingMode( sal_Int16 nWritingMode )\n{\n \/\/LR_TB == LT\n \/\/RL_TB == RT (Arabic, Hebrew)\n \/\/TB_RL == TR (Japanese, Chinese, Korean)\n \/\/ ?? TL (Mongolian) see also text::WritingMode2\n\n switch(nWritingMode)\n {\n case text::WritingMode2::RL_TB:\n return text::WritingMode2::TB_RL;\n case text::WritingMode2::TB_RL:\n return text::WritingMode2::RL_TB;\n case text::WritingMode2::LR_TB:\n return text::WritingMode2::TB_LR;\n default:\n return text::WritingMode2::LR_TB;\n }\n}\n*\/\n\nsal_Bool AxisLabelProperties::getIsStaggered() const\n{\n if( STAGGER_ODD == eStaggering || STAGGER_EVEN == eStaggering )\n return sal_True;\n return sal_False;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\nINTEGRATION: CWS pchfix02 (1.9.80); FILE MERGED 2006\/09\/01 17:18:56 kaib 1.9.80.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: VAxisProperties.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 13:31:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"VAxisProperties.hxx\"\n#include \"macros.hxx\"\n#include \"ViewDefines.hxx\"\n#include \"CommonConverters.hxx\"\n\n#ifndef _TOOLS_COLOR_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART_CHARTAXISARRANGEORDERTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TEXT_WRITINGMODE2_HPP_\n#include \n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::chart2;\n\nsal_Int32 lcl_calcTickLengthForDepth(sal_Int32 nDepth,sal_Int32 nTickmarkStyle)\n{\n sal_Int32 nWidth = AXIS2D_TICKLENGTH; \/\/@maybefuturetodo this length could be offered by the model\n double fPercent = 1.0;\n switch(nDepth)\n {\n case 0:\n fPercent = 1.0;\n break;\n case 1:\n fPercent = 0.75;\/\/percentage like in the old chart\n break;\n case 2:\n fPercent = 0.5;\n break;\n default:\n fPercent = 0.3;\n break;\n }\n if(nTickmarkStyle==3)\/\/inner and outer tickmarks\n fPercent*=2.0;\n return static_cast(nWidth*fPercent);\n}\n\ndouble lcl_getTickOffset(sal_Int32 nLength,sal_Int32 nTickmarkStyle)\n{\n double fPercent = 0.0; \/\/0<=fPercent<=1\n \/\/0.0: completly inner\n \/\/1.0: completly outer\n \/\/0.5: half and half\n\n \/*\n nTickmarkStyle:\n 1: inner tickmarks\n 2: outer tickmarks\n 3: inner and outer tickmarks\n *\/\n switch(nTickmarkStyle)\n {\n case 1:\n fPercent = 0.0;\n break;\n case 2:\n fPercent = 1.0;\n break;\n default:\n fPercent = 0.5;\n break;\n }\n return fPercent*nLength;\n}\n\nVLineProperties AxisProperties::makeLinePropertiesForDepth( sal_Int32 nDepth ) const\n{\n \/\/@todo get this from somewhere; maybe for each subincrement\n \/\/so far the model does not offer different settings for each tick depth\n return m_aLineProperties;\n}\n\nTickmarkProperties AxisProperties::makeTickmarkProperties(\n sal_Int32 nDepth ) const\n{\n \/*\n nTickmarkStyle:\n 1: inner tickmarks\n 2: outer tickmarks\n 3: inner and outer tickmarks\n *\/\n sal_Int32 nTickmarkStyle = 1;\n if(nDepth==0)\n {\n nTickmarkStyle = m_nMajorTickmarks;\n if(!nTickmarkStyle)\n {\n \/\/create major tickmarks as if they were minor tickmarks\n nDepth = 1;\n nTickmarkStyle = m_nMinorTickmarks;\n }\n }\n else if( nDepth==1)\n {\n nTickmarkStyle = m_nMinorTickmarks;\n }\n\n if( m_fInnerDirectionSign == 0.0 )\n {\n if( nTickmarkStyle != 0 )\n nTickmarkStyle = 3; \/\/inner and outer tickmarks\n }\n\n TickmarkProperties aTickmarkProperties;\n aTickmarkProperties.Length = lcl_calcTickLengthForDepth(nDepth,nTickmarkStyle);\n aTickmarkProperties.RelativePos = static_cast(lcl_getTickOffset(aTickmarkProperties.Length,nTickmarkStyle));\n aTickmarkProperties.aLineProperties = this->makeLinePropertiesForDepth( nDepth );\n return aTickmarkProperties;\n}\n\n\/\/--------------------------------------------------------------------------\n\nAxisProperties::AxisProperties( const uno::Reference< XAxis >& xAxisModel\n , const ::com::sun::star::awt::Size& rReferenceSize )\n : m_xAxisModel(xAxisModel)\n , m_aReferenceSize(rReferenceSize)\n , m_bIsMainAxis(true)\n , m_pfMainLinePositionAtOtherAxis(NULL)\n , m_pfExrtaLinePositionAtOtherAxis(NULL)\n , m_fInnerDirectionSign(1.0)\n , m_bLabelsOutside(true)\n , m_aLabelAlignment(LABEL_ALIGN_RIGHT_TOP)\n , m_bDisplayLabels( true )\n\/\/ , m_eRelativeLabelPosition(LEFTORBOTTOM_OF_AXIS)\n , m_nMajorTickmarks(1)\n , m_nMinorTickmarks(1)\n , m_aTickmarkPropertiesList()\n , m_aLineProperties()\n{\n}\n\nAxisProperties::AxisProperties( const AxisProperties& rAxisProperties )\n : m_xAxisModel( rAxisProperties.m_xAxisModel )\n , m_aReferenceSize( rAxisProperties.m_aReferenceSize )\n , m_bIsMainAxis( rAxisProperties.m_bIsMainAxis )\n , m_pfMainLinePositionAtOtherAxis( NULL )\n , m_pfExrtaLinePositionAtOtherAxis( NULL )\n , m_fInnerDirectionSign( rAxisProperties.m_fInnerDirectionSign )\n , m_bLabelsOutside( rAxisProperties.m_bLabelsOutside )\n , m_aLabelAlignment( rAxisProperties.m_aLabelAlignment )\n , m_bDisplayLabels( rAxisProperties.m_bDisplayLabels )\n\/\/ , m_eRelativeLabelPosition( rAxisProperties.m_eRelativeLabelPosition )\n , m_nMajorTickmarks( rAxisProperties.m_nMajorTickmarks )\n , m_nMinorTickmarks( rAxisProperties.m_nMinorTickmarks )\n , m_aTickmarkPropertiesList( rAxisProperties.m_aTickmarkPropertiesList )\n , m_aLineProperties( rAxisProperties.m_aLineProperties )\n{\n if( rAxisProperties.m_pfMainLinePositionAtOtherAxis )\n m_pfMainLinePositionAtOtherAxis = new double(*rAxisProperties.m_pfMainLinePositionAtOtherAxis);\n if( rAxisProperties.m_pfExrtaLinePositionAtOtherAxis )\n m_pfExrtaLinePositionAtOtherAxis = new double (*rAxisProperties.m_pfExrtaLinePositionAtOtherAxis);\n}\n\nAxisProperties::~AxisProperties()\n{\n delete m_pfMainLinePositionAtOtherAxis;\n delete m_pfExrtaLinePositionAtOtherAxis;\n}\n\nLabelAlignment lcl_getLabelAlignment( const AxisProperties& rAxisProperties, bool bIsYAxis )\n{\n LabelAlignment aRet( LABEL_ALIGN_LEFT );\n if(bIsYAxis)\n {\n if(rAxisProperties.m_bIsMainAxis)\n {\n if( rAxisProperties.m_bLabelsOutside )\n aRet = LABEL_ALIGN_LEFT;\n else\n aRet = LABEL_ALIGN_RIGHT;\n }\n else\n {\n if( !rAxisProperties.m_bLabelsOutside )\n aRet = LABEL_ALIGN_LEFT;\n else\n aRet = LABEL_ALIGN_RIGHT;\n }\n }\n else\n {\n if(rAxisProperties.m_bIsMainAxis )\n {\n if(rAxisProperties.m_bLabelsOutside)\n aRet = LABEL_ALIGN_BOTTOM;\n else\n aRet = LABEL_ALIGN_TOP;\n }\n else\n {\n if(!rAxisProperties.m_bLabelsOutside)\n aRet = LABEL_ALIGN_BOTTOM;\n else\n aRet = LABEL_ALIGN_TOP;\n }\n }\n return aRet;\n}\n\nvoid AxisProperties::init( bool bCartesian )\n{\n if( bCartesian )\n {\n sal_Int32 nDimensionIndex = m_xAxisModel->getRepresentedDimension();\n m_fInnerDirectionSign = m_bIsMainAxis ? 1 : -1;\n if(nDimensionIndex==1)\n m_fInnerDirectionSign*=-1;\n m_aLabelAlignment = lcl_getLabelAlignment(*this,nDimensionIndex==1);\n }\n\n uno::Reference< beans::XPropertySet > xProp =\n uno::Reference::query( this->m_xAxisModel );\n if( !xProp.is() )\n return;\n\n try\n {\n \/\/init LineProperties\n m_aLineProperties.initFromPropertySet( xProp );\n\n \/\/init display labels\n xProp->getPropertyValue( C2U( \"DisplayLabels\" ) ) >>= m_bDisplayLabels;\n\n \/\/init TickmarkProperties\n xProp->getPropertyValue( C2U( \"MajorTickmarks\" ) ) >>= m_nMajorTickmarks;\n xProp->getPropertyValue( C2U( \"MinorTickmarks\" ) ) >>= m_nMinorTickmarks;\n\n sal_Int32 nMaxDepth = 0;\n if(m_nMinorTickmarks!=0)\n nMaxDepth=2;\n else if(m_nMajorTickmarks!=0)\n nMaxDepth=1;\n\n this->m_aTickmarkPropertiesList.clear();\n for( sal_Int32 nDepth=0; nDepthmakeTickmarkProperties( nDepth );\n this->m_aTickmarkPropertiesList.push_back( aTickmarkProperties );\n }\n }\n catch( uno::Exception& e )\n {\n e;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\nAxisLabelProperties::AxisLabelProperties()\n : aNumberFormat()\n , eStaggering( SIDE_BY_SIDE )\n , bLineBreakAllowed( true )\n , bOverlapAllowed( false )\n , bStackCharacters( false )\n , fRotationAngleDegree( 0.0 )\n , nRhythm( 1 )\n , bRhythmIsFix(false)\n{\n \/*\n aLocale.Language = C2U( \"en\" );\n aLocale.Country = C2U( \"US\" );\n\n \/\/aLocale.Language = C2U( \"ar\" );\n \/\/aLocale.Country = C2U( \"IR\" );\n\n \/\/aLocale.Language = C2U( \"ja\" );\n \/\/aLocale.Country = C2U( \"JP\" );\n *\/\n}\n\nvoid AxisLabelProperties::init( const uno::Reference< XAxis >& xAxisModel )\n{\n uno::Reference< beans::XPropertySet > xProp =\n uno::Reference::query( xAxisModel );\n if(xProp.is())\n {\n try\n {\n if( !( xProp->getPropertyValue( C2U( \"NumberFormat\" ) ) >>= this->aNumberFormat ) )\n {\n \/\/@todo get number format from calc\n }\n\n xProp->getPropertyValue( C2U( \"TextBreak\" ) ) >>= this->bLineBreakAllowed;\n xProp->getPropertyValue( C2U( \"TextOverlap\" ) ) >>= this->bOverlapAllowed;\n xProp->getPropertyValue( C2U( \"StackCharacters\" ) ) >>= this->bStackCharacters;\n xProp->getPropertyValue( C2U( \"TextRotation\" ) ) >>= this->fRotationAngleDegree;\n\n ::com::sun::star::chart::ChartAxisArrangeOrderType eArrangeOrder;\n xProp->getPropertyValue( C2U( \"ArrangeOrder\" ) ) >>= eArrangeOrder;\n switch(eArrangeOrder)\n {\n case ::com::sun::star::chart::ChartAxisArrangeOrderType_SIDE_BY_SIDE:\n this->eStaggering = SIDE_BY_SIDE;\n break;\n case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_EVEN:\n this->eStaggering = STAGGER_EVEN;\n break;\n case ::com::sun::star::chart::ChartAxisArrangeOrderType_STAGGER_ODD:\n this->eStaggering = STAGGER_ODD;\n break;\n default:\n this->eStaggering = STAGGER_AUTO;\n break;\n }\n }\n catch( uno::Exception& e )\n {\n e;\n }\n }\n}\n\n\/*\nsal_Int16 getSwappedWritingMode( sal_Int16 nWritingMode )\n{\n \/\/LR_TB == LT\n \/\/RL_TB == RT (Arabic, Hebrew)\n \/\/TB_RL == TR (Japanese, Chinese, Korean)\n \/\/ ?? TL (Mongolian) see also text::WritingMode2\n\n switch(nWritingMode)\n {\n case text::WritingMode2::RL_TB:\n return text::WritingMode2::TB_RL;\n case text::WritingMode2::TB_RL:\n return text::WritingMode2::RL_TB;\n case text::WritingMode2::LR_TB:\n return text::WritingMode2::TB_LR;\n default:\n return text::WritingMode2::LR_TB;\n }\n}\n*\/\n\nsal_Bool AxisLabelProperties::getIsStaggered() const\n{\n if( STAGGER_ODD == eStaggering || STAGGER_EVEN == eStaggering )\n return sal_True;\n return sal_False;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Fangfang Bai, fangfang@multicorewareinc.com\n\/\/ Jin Ma, jin@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors as is and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"..\/perf_precomp.hpp\"\n#include \"opencv2\/ts\/ocl_perf.hpp\"\n\n#ifdef HAVE_OPENCL\n\nnamespace cvtest {\nnamespace ocl {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ dft \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum OCL_FFT_TYPE\n{\n R2R = 0,\n C2R = 1,\n R2C = 2,\n C2C = 3\n};\n\ntypedef tuple DftParams;\ntypedef TestBaseWithParam DftFixture;\n\nOCL_PERF_TEST_P(DftFixture, Dft, ::testing::Combine(Values(C2C, R2R, C2R, R2C),\n Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3, Size(512, 512), Size(1024, 1024), Size(2048, 2048)),\n Values((int) 0, (int)DFT_ROWS, (int)DFT_SCALE, (int)DFT_INVERSE,\n (int)DFT_INVERSE | DFT_SCALE, (int)DFT_ROWS | DFT_INVERSE)))\n{\n const DftParams params = GetParam();\n const int dft_type = get<0>(params);\n const Size srcSize = get<1>(params);\n int flags = get<2>(params);\n\n int in_cn, out_cn;\n switch (dft_type)\n {\n case R2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 1; out_cn = 1; break;\n case C2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 2; out_cn = 2; break;\n case R2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 1; out_cn = 2; break;\n case C2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 2; out_cn = 2; break;\n }\n\n UMat src(srcSize, CV_MAKE_TYPE(CV_32F, in_cn)), dst(srcSize, CV_MAKE_TYPE(CV_32F, out_cn));\n declare.in(src, WARMUP_RNG).out(dst);\n\n OCL_TEST_CYCLE() cv::dft(src, dst, flags);\n\n SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ MulSpectrums \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef tuple MulSpectrumsParams;\ntypedef TestBaseWithParam MulSpectrumsFixture;\n\nOCL_PERF_TEST_P(MulSpectrumsFixture, MulSpectrums,\n ::testing::Combine(Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3),\n Bool()))\n{\n const MulSpectrumsParams params = GetParam();\n const Size srcSize = get<0>(params);\n const bool conj = get<1>(params);\n\n UMat src1(srcSize, CV_32FC2), src2(srcSize, CV_32FC2), dst(srcSize, CV_32FC2);\n declare.in(src1, src2, WARMUP_RNG).out(dst);\n\n OCL_TEST_CYCLE() cv::mulSpectrums(src1, src2, dst, 0, conj);\n\n SANITY_CHECK(dst, 1e-3);\n}\n\n} } \/\/ namespace cvtest::ocl\n\n#endif \/\/ HAVE_OPENCL\nFixed warning with \"uninitialized local variable\"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Fangfang Bai, fangfang@multicorewareinc.com\n\/\/ Jin Ma, jin@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors as is and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#include \"..\/perf_precomp.hpp\"\n#include \"opencv2\/ts\/ocl_perf.hpp\"\n\n#ifdef HAVE_OPENCL\n\nnamespace cvtest {\nnamespace ocl {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ dft \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum OCL_FFT_TYPE\n{\n R2R = 0,\n C2R = 1,\n R2C = 2,\n C2C = 3\n};\n\ntypedef tuple DftParams;\ntypedef TestBaseWithParam DftFixture;\n\nOCL_PERF_TEST_P(DftFixture, Dft, ::testing::Combine(Values(C2C, R2R, C2R, R2C),\n Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3, Size(512, 512), Size(1024, 1024), Size(2048, 2048)),\n Values((int) 0, (int)DFT_ROWS, (int)DFT_SCALE, (int)DFT_INVERSE,\n (int)DFT_INVERSE | DFT_SCALE, (int)DFT_ROWS | DFT_INVERSE)))\n{\n const DftParams params = GetParam();\n const int dft_type = get<0>(params);\n const Size srcSize = get<1>(params);\n int flags = get<2>(params);\n\n int in_cn = 0, out_cn = 0;\n switch (dft_type)\n {\n case R2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 1; out_cn = 1; break;\n case C2R: flags |= cv::DFT_REAL_OUTPUT; in_cn = 2; out_cn = 2; break;\n case R2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 1; out_cn = 2; break;\n case C2C: flags |= cv::DFT_COMPLEX_OUTPUT; in_cn = 2; out_cn = 2; break;\n }\n\n UMat src(srcSize, CV_MAKE_TYPE(CV_32F, in_cn)), dst(srcSize, CV_MAKE_TYPE(CV_32F, out_cn));\n declare.in(src, WARMUP_RNG).out(dst);\n\n OCL_TEST_CYCLE() cv::dft(src, dst, flags);\n\n SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/ MulSpectrums \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef tuple MulSpectrumsParams;\ntypedef TestBaseWithParam MulSpectrumsFixture;\n\nOCL_PERF_TEST_P(MulSpectrumsFixture, MulSpectrums,\n ::testing::Combine(Values(OCL_SIZE_1, OCL_SIZE_2, OCL_SIZE_3),\n Bool()))\n{\n const MulSpectrumsParams params = GetParam();\n const Size srcSize = get<0>(params);\n const bool conj = get<1>(params);\n\n UMat src1(srcSize, CV_32FC2), src2(srcSize, CV_32FC2), dst(srcSize, CV_32FC2);\n declare.in(src1, src2, WARMUP_RNG).out(dst);\n\n OCL_TEST_CYCLE() cv::mulSpectrums(src1, src2, dst, 0, conj);\n\n SANITY_CHECK(dst, 1e-3);\n}\n\n} } \/\/ namespace cvtest::ocl\n\n#endif \/\/ HAVE_OPENCL\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_browser_main_posix.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\n#if defined(OS_ANDROID)\n#include \/\/ for PAGE_SIZE needed by PTHREAD_STACK_MIN\n#endif\n\n#if defined(TOOLKIT_USES_GTK)\n#include \"chrome\/browser\/chrome_browser_main_extra_parts_gtk.h\"\n#include \"chrome\/browser\/printing\/print_dialog_gtk.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace {\n\n\/\/ See comment in |PreEarlyInitialization()|, where sigaction is called.\nvoid SIGCHLDHandler(int signal) {\n}\n\nint g_shutdown_pipe_write_fd = -1;\nint g_shutdown_pipe_read_fd = -1;\n\n\/\/ Common code between SIG{HUP, INT, TERM}Handler.\nvoid GracefulShutdownHandler(int signal) {\n \/\/ Reinstall the default handler. We had one shot at graceful shutdown.\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIG_DFL;\n RAW_CHECK(sigaction(signal, &action, NULL) == 0);\n\n RAW_CHECK(g_shutdown_pipe_write_fd != -1);\n RAW_CHECK(g_shutdown_pipe_read_fd != -1);\n size_t bytes_written = 0;\n do {\n int rv = HANDLE_EINTR(\n write(g_shutdown_pipe_write_fd,\n reinterpret_cast(&signal) + bytes_written,\n sizeof(signal) - bytes_written));\n RAW_CHECK(rv >= 0);\n bytes_written += rv;\n } while (bytes_written < sizeof(signal));\n}\n\n\/\/ See comment in |PostMainMessageLoopStart()|, where sigaction is called.\nvoid SIGHUPHandler(int signal) {\n RAW_CHECK(signal == SIGHUP);\n GracefulShutdownHandler(signal);\n}\n\n\/\/ See comment in |PostMainMessageLoopStart()|, where sigaction is called.\nvoid SIGINTHandler(int signal) {\n RAW_CHECK(signal == SIGINT);\n GracefulShutdownHandler(signal);\n}\n\n\/\/ See comment in |PostMainMessageLoopStart()|, where sigaction is called.\nvoid SIGTERMHandler(int signal) {\n RAW_CHECK(signal == SIGTERM);\n GracefulShutdownHandler(signal);\n}\n\nclass ShutdownDetector : public base::PlatformThread::Delegate {\n public:\n explicit ShutdownDetector(int shutdown_fd);\n\n virtual void ThreadMain();\n\n private:\n const int shutdown_fd_;\n\n DISALLOW_COPY_AND_ASSIGN(ShutdownDetector);\n};\n\nShutdownDetector::ShutdownDetector(int shutdown_fd)\n : shutdown_fd_(shutdown_fd) {\n CHECK_NE(shutdown_fd_, -1);\n}\n\n\n\/\/ These functions are used to help us diagnose crash dumps that happen\n\/\/ during the shutdown process.\nNOINLINE void ShutdownFDReadError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(UINT_MAX);\n}\n\nNOINLINE void ShutdownFDClosedError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(UINT_MAX);\n}\n\nNOINLINE void ExitPosted() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(UINT_MAX);\n}\n\nvoid ShutdownDetector::ThreadMain() {\n base::PlatformThread::SetName(\"CrShutdownDetector\");\n\n int signal;\n size_t bytes_read = 0;\n ssize_t ret;\n do {\n ret = HANDLE_EINTR(\n read(shutdown_fd_,\n reinterpret_cast(&signal) + bytes_read,\n sizeof(signal) - bytes_read));\n if (ret < 0) {\n NOTREACHED() << \"Unexpected error: \" << strerror(errno);\n ShutdownFDReadError();\n break;\n } else if (ret == 0) {\n NOTREACHED() << \"Unexpected closure of shutdown pipe.\";\n ShutdownFDClosedError();\n break;\n }\n bytes_read += ret;\n } while (bytes_read < sizeof(signal));\n VLOG(1) << \"Handling shutdown for signal \" << signal << \".\";\n#if defined(OS_CHROMEOS)\n \/\/ On ChromeOS, exiting on signal should be always clean.\n base::Closure task = base::Bind(&BrowserList::ExitCleanly);\n#else\n base::Closure task = base::Bind(&BrowserList::AttemptExit);\n#endif\n\n if (!BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task)) {\n \/\/ Without a UI thread to post the exit task to, there aren't many\n \/\/ options. Raise the signal again. The default handler will pick it up\n \/\/ and cause an ungraceful exit.\n RAW_LOG(WARNING, \"No UI thread, exiting ungracefully.\");\n kill(getpid(), signal);\n\n \/\/ The signal may be handled on another thread. Give that a chance to\n \/\/ happen.\n sleep(3);\n\n \/\/ We really should be dead by now. For whatever reason, we're not. Exit\n \/\/ immediately, with the exit status set to the signal number with bit 8\n \/\/ set. On the systems that we care about, this exit status is what is\n \/\/ normally used to indicate an exit by this signal's default handler.\n \/\/ This mechanism isn't a de jure standard, but even in the worst case, it\n \/\/ should at least result in an immediate exit.\n RAW_LOG(WARNING, \"Still here, exiting really ungracefully.\");\n _exit(signal | (1 << 7));\n }\n ExitPosted();\n}\n\n\/\/ Sets the file descriptor soft limit to |max_descriptors| or the OS hard\n\/\/ limit, whichever is lower.\nvoid SetFileDescriptorLimit(unsigned int max_descriptors) {\n struct rlimit limits;\n if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {\n unsigned int new_limit = max_descriptors;\n if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {\n new_limit = limits.rlim_max;\n }\n limits.rlim_cur = new_limit;\n if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {\n PLOG(INFO) << \"Failed to set file descriptor limit\";\n }\n } else {\n PLOG(INFO) << \"Failed to get file descriptor limit\";\n }\n}\n\n} \/\/ namespace\n\n\/\/ ChromeBrowserMainPartsPosix -------------------------------------------------\n\nChromeBrowserMainPartsPosix::ChromeBrowserMainPartsPosix(\n const content::MainFunctionParams& parameters)\n : ChromeBrowserMainParts(parameters) {\n}\n\nvoid ChromeBrowserMainPartsPosix::PreEarlyInitialization() {\n ChromeBrowserMainParts::PreEarlyInitialization();\n\n \/\/ We need to accept SIGCHLD, even though our handler is a no-op because\n \/\/ otherwise we cannot wait on children. (According to POSIX 2001.)\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIGCHLDHandler;\n CHECK(sigaction(SIGCHLD, &action, NULL) == 0);\n\n const std::string fd_limit_string =\n parsed_command_line().GetSwitchValueASCII(\n switches::kFileDescriptorLimit);\n int fd_limit = 0;\n if (!fd_limit_string.empty()) {\n base::StringToInt(fd_limit_string, &fd_limit);\n }\n#if defined(OS_MACOSX)\n \/\/ We use quite a few file descriptors for our IPC, and the default limit on\n \/\/ the Mac is low (256), so bump it up if there is no explicit override.\n if (fd_limit == 0) {\n fd_limit = 1024;\n }\n#endif \/\/ OS_MACOSX\n if (fd_limit > 0)\n SetFileDescriptorLimit(fd_limit);\n}\n\nvoid ChromeBrowserMainPartsPosix::PostMainMessageLoopStart() {\n ChromeBrowserMainParts::PostMainMessageLoopStart();\n\n int pipefd[2];\n int ret = pipe(pipefd);\n if (ret < 0) {\n PLOG(DFATAL) << \"Failed to create pipe\";\n } else {\n g_shutdown_pipe_read_fd = pipefd[0];\n g_shutdown_pipe_write_fd = pipefd[1];\n const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN;\n \/\/ TODO(viettrungluu,willchan): crbug.com\/29675 - This currently leaks, so\n \/\/ if you change this, you'll probably need to change the suppression.\n if (!base::PlatformThread::CreateNonJoinable(\n kShutdownDetectorThreadStackSize,\n new ShutdownDetector(g_shutdown_pipe_read_fd))) {\n LOG(DFATAL) << \"Failed to create shutdown detector task.\";\n }\n }\n \/\/ Setup signal handlers for shutdown AFTER shutdown pipe is setup because\n \/\/ it may be called right away after handler is set.\n\n \/\/ If adding to this list of signal handlers, note the new signal probably\n \/\/ needs to be reset in child processes. See\n \/\/ base\/process_util_posix.cc:LaunchProcess.\n\n \/\/ We need to handle SIGTERM, because that is how many POSIX-based distros ask\n \/\/ processes to quit gracefully at shutdown time.\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIGTERMHandler;\n CHECK(sigaction(SIGTERM, &action, NULL) == 0);\n \/\/ Also handle SIGINT - when the user terminates the browser via Ctrl+C. If\n \/\/ the browser process is being debugged, GDB will catch the SIGINT first.\n action.sa_handler = SIGINTHandler;\n CHECK(sigaction(SIGINT, &action, NULL) == 0);\n \/\/ And SIGHUP, for when the terminal disappears. On shutdown, many Linux\n \/\/ distros send SIGHUP, SIGTERM, and then SIGKILL.\n action.sa_handler = SIGHUPHandler;\n CHECK(sigaction(SIGHUP, &action, NULL) == 0);\n\n#if defined(TOOLKIT_USES_GTK)\n printing::PrintingContextGtk::SetCreatePrintDialogFunction(\n &PrintDialogGtk::CreatePrintDialog);\n#endif\n}\n\nvoid ChromeBrowserMainPartsPosix::ShowMissingLocaleMessageBox() {\n#if defined(OS_CHROMEOS)\n NOTREACHED(); \/\/ Should not ever happen on ChromeOS.\n#elif defined(OS_ANDROID)\n \/\/ TODO(port) Update this as needed.\n \/\/ Probably should not ever happen on Android, but at the time of this\n \/\/ writing, Android isn't even using ChromeBrowserMainPartsPosix yet.\n NOTREACHED();\n#elif defined(OS_MACOSX)\n \/\/ Not called on Mac because we load the locale files differently.\n NOTREACHED();\n#elif defined(TOOLKIT_USES_GTK)\n ChromeBrowserMainExtraPartsGtk::ShowMessageBox(\n chrome_browser::kMissingLocaleDataMessage);\n#else\n#error \"Need MessageBox implementation.\"\n#endif\n}\nAura\/ash split: Fix ToT linux use_aura compile.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_browser_main_posix.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\n#if defined(OS_ANDROID)\n#include \/\/ for PAGE_SIZE needed by PTHREAD_STACK_MIN\n#endif\n\n#if defined(TOOLKIT_USES_GTK)\n#include \"chrome\/browser\/chrome_browser_main_extra_parts_gtk.h\"\n#include \"chrome\/browser\/printing\/print_dialog_gtk.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace {\n\n\/\/ See comment in |PreEarlyInitialization()|, where sigaction is called.\nvoid SIGCHLDHandler(int signal) {\n}\n\nint g_shutdown_pipe_write_fd = -1;\nint g_shutdown_pipe_read_fd = -1;\n\n\/\/ Common code between SIG{HUP, INT, TERM}Handler.\nvoid GracefulShutdownHandler(int signal) {\n \/\/ Reinstall the default handler. We had one shot at graceful shutdown.\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIG_DFL;\n RAW_CHECK(sigaction(signal, &action, NULL) == 0);\n\n RAW_CHECK(g_shutdown_pipe_write_fd != -1);\n RAW_CHECK(g_shutdown_pipe_read_fd != -1);\n size_t bytes_written = 0;\n do {\n int rv = HANDLE_EINTR(\n write(g_shutdown_pipe_write_fd,\n reinterpret_cast(&signal) + bytes_written,\n sizeof(signal) - bytes_written));\n RAW_CHECK(rv >= 0);\n bytes_written += rv;\n } while (bytes_written < sizeof(signal));\n}\n\n\/\/ See comment in |PostMainMessageLoopStart()|, where sigaction is called.\nvoid SIGHUPHandler(int signal) {\n RAW_CHECK(signal == SIGHUP);\n GracefulShutdownHandler(signal);\n}\n\n\/\/ See comment in |PostMainMessageLoopStart()|, where sigaction is called.\nvoid SIGINTHandler(int signal) {\n RAW_CHECK(signal == SIGINT);\n GracefulShutdownHandler(signal);\n}\n\n\/\/ See comment in |PostMainMessageLoopStart()|, where sigaction is called.\nvoid SIGTERMHandler(int signal) {\n RAW_CHECK(signal == SIGTERM);\n GracefulShutdownHandler(signal);\n}\n\nclass ShutdownDetector : public base::PlatformThread::Delegate {\n public:\n explicit ShutdownDetector(int shutdown_fd);\n\n virtual void ThreadMain();\n\n private:\n const int shutdown_fd_;\n\n DISALLOW_COPY_AND_ASSIGN(ShutdownDetector);\n};\n\nShutdownDetector::ShutdownDetector(int shutdown_fd)\n : shutdown_fd_(shutdown_fd) {\n CHECK_NE(shutdown_fd_, -1);\n}\n\n\n\/\/ These functions are used to help us diagnose crash dumps that happen\n\/\/ during the shutdown process.\nNOINLINE void ShutdownFDReadError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(UINT_MAX);\n}\n\nNOINLINE void ShutdownFDClosedError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(UINT_MAX);\n}\n\nNOINLINE void ExitPosted() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(UINT_MAX);\n}\n\nvoid ShutdownDetector::ThreadMain() {\n base::PlatformThread::SetName(\"CrShutdownDetector\");\n\n int signal;\n size_t bytes_read = 0;\n ssize_t ret;\n do {\n ret = HANDLE_EINTR(\n read(shutdown_fd_,\n reinterpret_cast(&signal) + bytes_read,\n sizeof(signal) - bytes_read));\n if (ret < 0) {\n NOTREACHED() << \"Unexpected error: \" << strerror(errno);\n ShutdownFDReadError();\n break;\n } else if (ret == 0) {\n NOTREACHED() << \"Unexpected closure of shutdown pipe.\";\n ShutdownFDClosedError();\n break;\n }\n bytes_read += ret;\n } while (bytes_read < sizeof(signal));\n VLOG(1) << \"Handling shutdown for signal \" << signal << \".\";\n#if defined(OS_CHROMEOS)\n \/\/ On ChromeOS, exiting on signal should be always clean.\n base::Closure task = base::Bind(&BrowserList::ExitCleanly);\n#else\n base::Closure task = base::Bind(&BrowserList::AttemptExit);\n#endif\n\n if (!BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task)) {\n \/\/ Without a UI thread to post the exit task to, there aren't many\n \/\/ options. Raise the signal again. The default handler will pick it up\n \/\/ and cause an ungraceful exit.\n RAW_LOG(WARNING, \"No UI thread, exiting ungracefully.\");\n kill(getpid(), signal);\n\n \/\/ The signal may be handled on another thread. Give that a chance to\n \/\/ happen.\n sleep(3);\n\n \/\/ We really should be dead by now. For whatever reason, we're not. Exit\n \/\/ immediately, with the exit status set to the signal number with bit 8\n \/\/ set. On the systems that we care about, this exit status is what is\n \/\/ normally used to indicate an exit by this signal's default handler.\n \/\/ This mechanism isn't a de jure standard, but even in the worst case, it\n \/\/ should at least result in an immediate exit.\n RAW_LOG(WARNING, \"Still here, exiting really ungracefully.\");\n _exit(signal | (1 << 7));\n }\n ExitPosted();\n}\n\n\/\/ Sets the file descriptor soft limit to |max_descriptors| or the OS hard\n\/\/ limit, whichever is lower.\nvoid SetFileDescriptorLimit(unsigned int max_descriptors) {\n struct rlimit limits;\n if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {\n unsigned int new_limit = max_descriptors;\n if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {\n new_limit = limits.rlim_max;\n }\n limits.rlim_cur = new_limit;\n if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {\n PLOG(INFO) << \"Failed to set file descriptor limit\";\n }\n } else {\n PLOG(INFO) << \"Failed to get file descriptor limit\";\n }\n}\n\n} \/\/ namespace\n\n\/\/ ChromeBrowserMainPartsPosix -------------------------------------------------\n\nChromeBrowserMainPartsPosix::ChromeBrowserMainPartsPosix(\n const content::MainFunctionParams& parameters)\n : ChromeBrowserMainParts(parameters) {\n}\n\nvoid ChromeBrowserMainPartsPosix::PreEarlyInitialization() {\n ChromeBrowserMainParts::PreEarlyInitialization();\n\n \/\/ We need to accept SIGCHLD, even though our handler is a no-op because\n \/\/ otherwise we cannot wait on children. (According to POSIX 2001.)\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIGCHLDHandler;\n CHECK(sigaction(SIGCHLD, &action, NULL) == 0);\n\n const std::string fd_limit_string =\n parsed_command_line().GetSwitchValueASCII(\n switches::kFileDescriptorLimit);\n int fd_limit = 0;\n if (!fd_limit_string.empty()) {\n base::StringToInt(fd_limit_string, &fd_limit);\n }\n#if defined(OS_MACOSX)\n \/\/ We use quite a few file descriptors for our IPC, and the default limit on\n \/\/ the Mac is low (256), so bump it up if there is no explicit override.\n if (fd_limit == 0) {\n fd_limit = 1024;\n }\n#endif \/\/ OS_MACOSX\n if (fd_limit > 0)\n SetFileDescriptorLimit(fd_limit);\n}\n\nvoid ChromeBrowserMainPartsPosix::PostMainMessageLoopStart() {\n ChromeBrowserMainParts::PostMainMessageLoopStart();\n\n int pipefd[2];\n int ret = pipe(pipefd);\n if (ret < 0) {\n PLOG(DFATAL) << \"Failed to create pipe\";\n } else {\n g_shutdown_pipe_read_fd = pipefd[0];\n g_shutdown_pipe_write_fd = pipefd[1];\n const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN;\n \/\/ TODO(viettrungluu,willchan): crbug.com\/29675 - This currently leaks, so\n \/\/ if you change this, you'll probably need to change the suppression.\n if (!base::PlatformThread::CreateNonJoinable(\n kShutdownDetectorThreadStackSize,\n new ShutdownDetector(g_shutdown_pipe_read_fd))) {\n LOG(DFATAL) << \"Failed to create shutdown detector task.\";\n }\n }\n \/\/ Setup signal handlers for shutdown AFTER shutdown pipe is setup because\n \/\/ it may be called right away after handler is set.\n\n \/\/ If adding to this list of signal handlers, note the new signal probably\n \/\/ needs to be reset in child processes. See\n \/\/ base\/process_util_posix.cc:LaunchProcess.\n\n \/\/ We need to handle SIGTERM, because that is how many POSIX-based distros ask\n \/\/ processes to quit gracefully at shutdown time.\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n action.sa_handler = SIGTERMHandler;\n CHECK(sigaction(SIGTERM, &action, NULL) == 0);\n \/\/ Also handle SIGINT - when the user terminates the browser via Ctrl+C. If\n \/\/ the browser process is being debugged, GDB will catch the SIGINT first.\n action.sa_handler = SIGINTHandler;\n CHECK(sigaction(SIGINT, &action, NULL) == 0);\n \/\/ And SIGHUP, for when the terminal disappears. On shutdown, many Linux\n \/\/ distros send SIGHUP, SIGTERM, and then SIGKILL.\n action.sa_handler = SIGHUPHandler;\n CHECK(sigaction(SIGHUP, &action, NULL) == 0);\n\n#if defined(TOOLKIT_USES_GTK)\n printing::PrintingContextGtk::SetCreatePrintDialogFunction(\n &PrintDialogGtk::CreatePrintDialog);\n#endif\n}\n\nvoid ChromeBrowserMainPartsPosix::ShowMissingLocaleMessageBox() {\n#if defined(OS_CHROMEOS)\n NOTREACHED(); \/\/ Should not ever happen on ChromeOS.\n#elif defined(OS_ANDROID)\n \/\/ TODO(port) Update this as needed.\n \/\/ Probably should not ever happen on Android, but at the time of this\n \/\/ writing, Android isn't even using ChromeBrowserMainPartsPosix yet.\n NOTREACHED();\n#elif defined(OS_MACOSX)\n \/\/ Not called on Mac because we load the locale files differently.\n NOTREACHED();\n#elif defined(TOOLKIT_USES_GTK)\n ChromeBrowserMainExtraPartsGtk::ShowMessageBox(\n chrome_browser::kMissingLocaleDataMessage);\n#elif defined(USE_AURA)\n \/\/ TODO(port): We may want a views based message dialog here eventually, but\n \/\/ for now, crash.\n NOTREACHED();\n#else\n#error \"Need MessageBox implementation.\"\n#endif\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ImportFilter.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2008-01-10 11:54:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SU_STAR_DRAWING_XDRAWPAGESUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include \n#endif\n#ifndef INCLUDED_DOMAINMAPPER_HXX\n#include \n#endif\n#ifndef _WRITERFILTER_HXX\n#include \n#endif\n#ifndef INCLUDED_WW8_DOCUMENT_HXX\n#include \n#endif\n#ifndef INCLUDED_OOXML_DOCUMENT_HXX\n#include \n#endif\n#ifdef DEBUG_IMPORT\n#include \n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nsal_Bool WriterFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )\n throw (uno::RuntimeException)\n{\n sal_Int32 nLength = aDescriptor.getLength();\n const beans::PropertyValue * pValue = aDescriptor.getConstArray();\n uno::Reference < io::XInputStream > xInputStream;\n ::rtl::OUString sFilterName;\n for ( sal_Int32 i = 0 ; i < nLength; i++)\n {\n if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"InputStream\" ) ) )\n pValue[i].Value >>= xInputStream;\n else if( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"FilterName\" ) ) )\n pValue[i].Value >>= sFilterName;\n }\n if ( !xInputStream.is() )\n {\n return sal_False;\n }\n\n#ifdef DEBUG_IMPORT\n TimeValue t1;\n osl_getSystemTime(&t1);\n\n writerfilter::logger(\"DEBUG\", \"\");\n writerfilter::logger(\"DEBUG\", string(\"\") + string(t1.Seconds)\n + \"<\/starttime>\");\n#endif\n\n writerfilter::dmapper::SourceDocumentType eType = m_sFilterName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"writer_MS_Word_2007\" ) ) ?\n writerfilter::dmapper::DOCUMENT_OOXML : writerfilter::dmapper::DOCUMENT_DOC;\n writerfilter::Stream::Pointer_t pStream(new writerfilter::dmapper::DomainMapper(m_xContext, m_xDoc, eType));\n \/\/create the tokenizer and domain mapper\n if( eType == writerfilter::dmapper::DOCUMENT_OOXML )\n {\n writerfilter::ooxml::OOXMLStream::Pointer_t pDocStream = writerfilter::ooxml::OOXMLDocumentFactory::createStream(m_xContext, xInputStream);\n writerfilter::ooxml::OOXMLDocument::Pointer_t pDocument(writerfilter::ooxml::OOXMLDocumentFactory::createDocument(pDocStream));\n\n uno::Reference xModel(m_xDoc, uno::UNO_QUERY_THROW);\n pDocument->setModel(xModel);\n\n uno::Reference xDrawings\n (m_xDoc, uno::UNO_QUERY_THROW);\n uno::Reference xShapes\n (xDrawings->getDrawPage(), uno::UNO_QUERY_THROW);\n pDocument->setShapes(xShapes);\n\n pDocument->resolve(*pStream);\n }\n else\n {\n writerfilter::doctok::WW8Stream::Pointer_t pDocStream = writerfilter::doctok::WW8DocumentFactory::createStream(m_xContext, xInputStream);\n writerfilter::doctok::WW8Document::Pointer_t pDocument(writerfilter::doctok::WW8DocumentFactory::createDocument(pDocStream));\n\n pDocument->resolve(*pStream);\n }\n\n#ifdef DEBUG_IMPORT\n TimeValue t2;\n osl_getSystemTime(&t2);\n\n writerfilter::logger(\"DEBUG\", string(\"\")\n + string(t2.Seconds - t1.Seconds) + \"<\/importtime>\");\n writerfilter::logger(\"DEBUG\", \"<\/out>\");\n#endif\n\n return sal_True;\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid WriterFilter::cancel( ) throw (uno::RuntimeException)\n{\n}\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid WriterFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )\n throw (lang::IllegalArgumentException, uno::RuntimeException)\n{\n m_xDoc = xDoc;\n}\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid WriterFilter::initialize( const uno::Sequence< uno::Any >& aArguments ) throw (uno::Exception, uno::RuntimeException)\n{\n uno::Sequence < beans::PropertyValue > aAnySeq;\n sal_Int32 nLength = aArguments.getLength();\n if ( nLength && ( aArguments[0] >>= aAnySeq ) )\n {\n const beans::PropertyValue * pValue = aAnySeq.getConstArray();\n nLength = aAnySeq.getLength();\n for ( sal_Int32 i = 0 ; i < nLength; i++)\n {\n if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"Type\" ) ) )\n {\n pValue[i].Value >>= m_sFilterName;\n break;\n }\n }\n }\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nOUString WriterFilter_getImplementationName () throw (uno::RuntimeException)\n{\n return OUString ( RTL_CONSTASCII_USTRINGPARAM ( \"com.sun.star.comp.Writer.WriterFilter\" ) );\n}\n\n#define SERVICE_NAME1 \"com.sun.star.document.ImportFilter\"\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nsal_Bool WriterFilter_supportsService( const OUString& ServiceName ) throw (uno::RuntimeException)\n{\n return (ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ));\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nuno::Sequence< OUString > WriterFilter_getSupportedServiceNames( ) throw (uno::RuntimeException)\n{\n uno::Sequence < OUString > aRet(1);\n OUString* pArray = aRet.getArray();\n pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );\n return aRet;\n}\n#undef SERVICE_NAME1\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nuno::Reference< uno::XInterface > WriterFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)\n throw( uno::Exception )\n{\n return (cppu::OWeakObject*) new WriterFilter( xContext );\n}\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nOUString WriterFilter::getImplementationName( ) throw (uno::RuntimeException)\n{\n return WriterFilter_getImplementationName();\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nsal_Bool WriterFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)\n{\n return WriterFilter_supportsService( rServiceName );\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nuno::Sequence< OUString > WriterFilter::getSupportedServiceNames( ) throw (uno::RuntimeException)\n{\n return WriterFilter_getSupportedServiceNames();\n}\n\nINTEGRATION: CWS changefileheader (1.7.20); FILE MERGED 2008\/04\/01 16:06:45 thb 1.7.20.3: #i85898# Stripping all external header guards 2008\/04\/01 13:02:30 thb 1.7.20.2: #i85898# Stripping all external header guards 2008\/03\/28 15:53:02 rt 1.7.20.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ImportFilter.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \n#include \n#ifndef _COM_SU_STAR_DRAWING_XDRAWPAGESUPPLIER_HPP_\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#ifdef DEBUG_IMPORT\n#include \n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nsal_Bool WriterFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )\n throw (uno::RuntimeException)\n{\n sal_Int32 nLength = aDescriptor.getLength();\n const beans::PropertyValue * pValue = aDescriptor.getConstArray();\n uno::Reference < io::XInputStream > xInputStream;\n ::rtl::OUString sFilterName;\n for ( sal_Int32 i = 0 ; i < nLength; i++)\n {\n if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"InputStream\" ) ) )\n pValue[i].Value >>= xInputStream;\n else if( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"FilterName\" ) ) )\n pValue[i].Value >>= sFilterName;\n }\n if ( !xInputStream.is() )\n {\n return sal_False;\n }\n\n#ifdef DEBUG_IMPORT\n TimeValue t1;\n osl_getSystemTime(&t1);\n\n writerfilter::logger(\"DEBUG\", \"\");\n writerfilter::logger(\"DEBUG\", string(\"\") + string(t1.Seconds)\n + \"<\/starttime>\");\n#endif\n\n writerfilter::dmapper::SourceDocumentType eType = m_sFilterName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"writer_MS_Word_2007\" ) ) ?\n writerfilter::dmapper::DOCUMENT_OOXML : writerfilter::dmapper::DOCUMENT_DOC;\n writerfilter::Stream::Pointer_t pStream(new writerfilter::dmapper::DomainMapper(m_xContext, m_xDoc, eType));\n \/\/create the tokenizer and domain mapper\n if( eType == writerfilter::dmapper::DOCUMENT_OOXML )\n {\n writerfilter::ooxml::OOXMLStream::Pointer_t pDocStream = writerfilter::ooxml::OOXMLDocumentFactory::createStream(m_xContext, xInputStream);\n writerfilter::ooxml::OOXMLDocument::Pointer_t pDocument(writerfilter::ooxml::OOXMLDocumentFactory::createDocument(pDocStream));\n\n uno::Reference xModel(m_xDoc, uno::UNO_QUERY_THROW);\n pDocument->setModel(xModel);\n\n uno::Reference xDrawings\n (m_xDoc, uno::UNO_QUERY_THROW);\n uno::Reference xShapes\n (xDrawings->getDrawPage(), uno::UNO_QUERY_THROW);\n pDocument->setShapes(xShapes);\n\n pDocument->resolve(*pStream);\n }\n else\n {\n writerfilter::doctok::WW8Stream::Pointer_t pDocStream = writerfilter::doctok::WW8DocumentFactory::createStream(m_xContext, xInputStream);\n writerfilter::doctok::WW8Document::Pointer_t pDocument(writerfilter::doctok::WW8DocumentFactory::createDocument(pDocStream));\n\n pDocument->resolve(*pStream);\n }\n\n#ifdef DEBUG_IMPORT\n TimeValue t2;\n osl_getSystemTime(&t2);\n\n writerfilter::logger(\"DEBUG\", string(\"\")\n + string(t2.Seconds - t1.Seconds) + \"<\/importtime>\");\n writerfilter::logger(\"DEBUG\", \"<\/out>\");\n#endif\n\n return sal_True;\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid WriterFilter::cancel( ) throw (uno::RuntimeException)\n{\n}\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid WriterFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )\n throw (lang::IllegalArgumentException, uno::RuntimeException)\n{\n m_xDoc = xDoc;\n}\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid WriterFilter::initialize( const uno::Sequence< uno::Any >& aArguments ) throw (uno::Exception, uno::RuntimeException)\n{\n uno::Sequence < beans::PropertyValue > aAnySeq;\n sal_Int32 nLength = aArguments.getLength();\n if ( nLength && ( aArguments[0] >>= aAnySeq ) )\n {\n const beans::PropertyValue * pValue = aAnySeq.getConstArray();\n nLength = aAnySeq.getLength();\n for ( sal_Int32 i = 0 ; i < nLength; i++)\n {\n if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( \"Type\" ) ) )\n {\n pValue[i].Value >>= m_sFilterName;\n break;\n }\n }\n }\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nOUString WriterFilter_getImplementationName () throw (uno::RuntimeException)\n{\n return OUString ( RTL_CONSTASCII_USTRINGPARAM ( \"com.sun.star.comp.Writer.WriterFilter\" ) );\n}\n\n#define SERVICE_NAME1 \"com.sun.star.document.ImportFilter\"\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nsal_Bool WriterFilter_supportsService( const OUString& ServiceName ) throw (uno::RuntimeException)\n{\n return (ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ));\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nuno::Sequence< OUString > WriterFilter_getSupportedServiceNames( ) throw (uno::RuntimeException)\n{\n uno::Sequence < OUString > aRet(1);\n OUString* pArray = aRet.getArray();\n pArray[0] = OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );\n return aRet;\n}\n#undef SERVICE_NAME1\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nuno::Reference< uno::XInterface > WriterFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)\n throw( uno::Exception )\n{\n return (cppu::OWeakObject*) new WriterFilter( xContext );\n}\n\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nOUString WriterFilter::getImplementationName( ) throw (uno::RuntimeException)\n{\n return WriterFilter_getImplementationName();\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nsal_Bool WriterFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)\n{\n return WriterFilter_supportsService( rServiceName );\n}\n\/*-- 09.06.2006 10:15:20---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nuno::Sequence< OUString > WriterFilter::getSupportedServiceNames( ) throw (uno::RuntimeException)\n{\n return WriterFilter_getSupportedServiceNames();\n}\n\n<|endoftext|>"} {"text":"#line 2 \"sxc:Account\/Account.cxx\"\n\/\/ LICENSE\/*{{{*\/\n\/*\n sxc - Simple Xmpp Client\n Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n Permission to use, copy, modify, and\/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\/*}}}*\/\n\n\n\/\/ INCLUDE\/*{{{*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n\n#ifdef DEBUG\n# include \n#endif\n\n\/*}}}*\/\n\nnamespace Account\n{\n Account::Account(\/*{{{*\/\n gloox::Client &client,\n Roster &roster,\n ::File::AbcOutput &out)\n : _thread()\n , _client(client) \/\/ Fill in the passphrase later.\n , _roster(roster)\n# ifdef DEBUG\n , _logHandler()\n# endif\n , _presence(gloox::Presence::Available)\n , _priority(0)\n , _status(\"\")\n , _in(*this, client.jid().bare())\n , _out(out)\n {\n _client.registerConnectionListener(this);\n\n# ifdef DEBUG\n _client.logInstance().registerLogHandler(\n gloox::LogLevelDebug,\n gloox::LogAreaAll,\n &_logHandler);\n# endif\n }\/*}}}*\/\n Account::~Account()\/*{{{*\/\n {\n LOG(\"Exit.\");\n\n disconnect();\n pthread_join(_thread, NULL);\n\n _client.removeConnectionListener(this);\n\n# if DEBUG\n _client.logInstance().removeLogHandler(&_logHandler);\n# endif\n }\/*}}}*\/\n\n void Account::run()\/*{{{*\/\n {\n _in.listen();\n }\/*}}}*\/\n void Account::setPassphrase(const std::string &pass)\/*{{{*\/\n {\n LOG(\"Set passphrase: \\\"\" + pass + \"\\\".\");\n\n _client.setPassword(pass);\n }\/*}}}*\/\n void Account::setPresence(\/*{{{*\/\n gloox::Presence::PresenceType presence,\n int priority,\n const std::string &status)\n {\n std::stringstream text;\n text << \"Set presence: (\\\"\" << libsxc::genPresenceString(presence)\n << \"\\\" (\" << presence << \"), priority: \" << priority\n << \", message: \\\"\" << status << \"\\\").\";;\n LOG(text.str());\n\n \/\/ Don't trust _client, but instead store the presence information\n \/\/ locally.\n _presence = presence;\n _priority = priority;\n _status = status;\n\n _client.setPresence(presence, priority, status);\n\n \/\/ Don't connect if already connected or connecting.\n if (_thread)\n return;\n if (\"\" == _client.password())\n _out.write(\"Password not set.\");\n else\n pthread_create(&_thread, NULL, _run, (void*)this);\n }\/*}}}*\/\n void Account::setPresence(\/*{{{*\/\n gloox::Presence::PresenceType presence,\n const std::string &status)\n {\n setPresence(presence, _priority, status);\n }\/*}}}*\/\n void Account::setPriority(int priority)\/*{{{*\/\n {\n setPresence(_presence, priority, _status);\n }\/*}}}*\/\n void Account::disconnect()\/*{{{*\/\n {\n LOG(\"Disconnect.\");\n\n _client.disconnect();\n }\/*}}}*\/\n\n void Account::sendMessage(\/*{{{*\/\n const gloox::JID &to,\n const std::string &body)\n {\n gloox::Message message(\n gloox::Message::Normal, \/\/ Not Chat.\n to,\n body);\n _client.send(message);\n }\/*}}}*\/\n void Account::addContact(const gloox::JID &jid)\/*{{{*\/\n {\n _roster.addContact(jid);\n }\/*}}}*\/\n void Account::removeContact(const gloox::JID &jid) const\/*{{{*\/\n {\n _roster.removeContact(jid);\n }\/*}}}*\/\n void Account::subscribe(const gloox::JID &jid, const std::string &message) const\/*{{{*\/\n {\n _roster.subscribe(jid, message);\n }\/*}}}*\/\n void Account::unsubscribe(\/*{{{*\/\n const gloox::JID &jid,\n const std::string &message) const\n {\n _roster.unsubscribe(jid, message);\n }\/*}}}*\/\n void Account::acknowledgeSubscription(const gloox::JID &jid) const\/*{{{*\/\n {\n _roster.acknowledgeSubscription(jid);\n }\/*}}}*\/\n void Account::declineSubscription(const gloox::JID &jid) const\/*{{{*\/\n {\n _roster.declineSubscription(jid);\n }\/*}}}*\/\n\n void Account::handleError(\/*{{{*\/\n libsxc::Exception::Exception &e,\n bool isCritical) const\n {\n if (isCritical) {\n \/\/LOG(e.what()); \/\/ FIXME\n exit(e.getExitCode());\n }\n _out.write(e.what());\n }\/*}}}*\/\n\n void Account::onConnect()\/*{{{*\/\n {\n LOG(\"Connected: Connection established.\");\n }\/*}}}*\/\n void Account::onDisconnect(gloox::ConnectionError e)\/*{{{*\/\n {\n LOG(\"Disconnected: \" + libsxc::genConnErrorString(\n e,\n _client.streamError(),\n _client.streamErrorText(),\n _client.authError(),\n \/* Debug = *\/ true));\n\n std::string text = libsxc::genConnErrorString(\n e,\n _client.streamError(),\n _client.streamErrorText(),\n _client.authError());\n if (!text.empty())\n _out.write(\"Disconnected: \" + text);\n }\/*}}}*\/\n bool Account::onTLSConnect(const gloox::CertInfo &info)\/*{{{*\/\n {\n LOG(\"Acknowledge TLS certificate.\");\n\n return true;\n }\/*}}}*\/\n\n void *Account::_run(void *rawThat)\/*{{{*\/\n {\n LOG(\"Start socket receiving thread.\");\n\n Account *that = (Account *) rawThat;\n that->_client.connect(); \/\/ Blocking.\n\n LOG(\"End socket receiving thread.\");\n\n return (void *) NULL;\n }\/*}}}*\/\n}\n\n\/\/ Use no tabs at all; two spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker\nMake threading more stable#line 2 \"sxc:Account\/Account.cxx\"\n\/\/ LICENSE\/*{{{*\/\n\/*\n sxc - Simple Xmpp Client\n Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n Permission to use, copy, modify, and\/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\/*}}}*\/\n\n\n\/\/ INCLUDE\/*{{{*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n\n#ifdef DEBUG\n# include \n#endif\n\n\/*}}}*\/\n\nnamespace Account\n{\n Account::Account(\/*{{{*\/\n gloox::Client &client,\n Roster &roster,\n ::File::AbcOutput &out)\n : _thread(0)\n , _client(client) \/\/ Fill in the passphrase later.\n , _roster(roster)\n# ifdef DEBUG\n , _logHandler()\n# endif\n , _presence(gloox::Presence::Available)\n , _priority(0)\n , _status(\"\")\n , _in(*this, client.jid().bare())\n , _out(out)\n {\n _client.registerConnectionListener(this);\n\n# ifdef DEBUG\n _client.logInstance().registerLogHandler(\n gloox::LogLevelDebug,\n gloox::LogAreaAll,\n &_logHandler);\n# endif\n }\/*}}}*\/\n Account::~Account()\/*{{{*\/\n {\n pthread_t thread = _thread;\n disconnect();\n if (thread)\n pthread_join(thread, NULL);\n\n _client.removeConnectionListener(this);\n\n# if DEBUG\n _client.logInstance().removeLogHandler(&_logHandler);\n# endif\n }\/*}}}*\/\n\n void Account::run()\/*{{{*\/\n {\n _in.listen();\n }\/*}}}*\/\n void Account::setPassphrase(const std::string &pass)\/*{{{*\/\n {\n LOG(\"Set passphrase: \\\"\" + pass + \"\\\".\");\n\n _client.setPassword(pass);\n }\/*}}}*\/\n void Account::setPresence(\/*{{{*\/\n gloox::Presence::PresenceType presence,\n int priority,\n const std::string &status)\n {\n std::stringstream text;\n text << \"Set presence: (\\\"\" << libsxc::genPresenceString(presence)\n << \"\\\" (\" << presence << \"), priority: \" << priority\n << \", message: \\\"\" << status << \"\\\").\";;\n LOG(text.str());\n\n \/\/ Don't trust _client, but instead store the presence information\n \/\/ locally.\n _presence = presence;\n _priority = priority;\n _status = status;\n\n _client.setPresence(presence, priority, status);\n\n \/\/ Don't connect if already connected or connecting.\n if (_thread)\n return;\n if (\"\" == _client.password())\n _out.write(\"Password not set.\");\n else\n pthread_create(&_thread, NULL, _run, (void*)this);\n }\/*}}}*\/\n void Account::setPresence(\/*{{{*\/\n gloox::Presence::PresenceType presence,\n const std::string &status)\n {\n setPresence(presence, _priority, status);\n }\/*}}}*\/\n void Account::setPriority(int priority)\/*{{{*\/\n {\n setPresence(_presence, priority, _status);\n }\/*}}}*\/\n void Account::disconnect()\/*{{{*\/\n {\n LOG(\"Disconnect.\");\n\n _client.disconnect();\n _thread = 0; \/\/ Reset to be able to restart another thread.\n }\/*}}}*\/\n\n void Account::sendMessage(\/*{{{*\/\n const gloox::JID &to,\n const std::string &body)\n {\n gloox::Message message(\n gloox::Message::Normal, \/\/ Not Chat.\n to,\n body);\n _client.send(message);\n }\/*}}}*\/\n void Account::addContact(const gloox::JID &jid)\/*{{{*\/\n {\n _roster.addContact(jid);\n }\/*}}}*\/\n void Account::removeContact(const gloox::JID &jid) const\/*{{{*\/\n {\n _roster.removeContact(jid);\n }\/*}}}*\/\n void Account::subscribe(const gloox::JID &jid, const std::string &message) const\/*{{{*\/\n {\n _roster.subscribe(jid, message);\n }\/*}}}*\/\n void Account::unsubscribe(\/*{{{*\/\n const gloox::JID &jid,\n const std::string &message) const\n {\n _roster.unsubscribe(jid, message);\n }\/*}}}*\/\n void Account::acknowledgeSubscription(const gloox::JID &jid) const\/*{{{*\/\n {\n _roster.acknowledgeSubscription(jid);\n }\/*}}}*\/\n void Account::declineSubscription(const gloox::JID &jid) const\/*{{{*\/\n {\n _roster.declineSubscription(jid);\n }\/*}}}*\/\n\n void Account::handleError(\/*{{{*\/\n libsxc::Exception::Exception &e,\n bool isCritical) const\n {\n if (isCritical) {\n \/\/LOG(e.what()); \/\/ FIXME\n exit(e.getExitCode());\n }\n _out.write(e.what());\n }\/*}}}*\/\n\n void Account::onConnect()\/*{{{*\/\n {\n LOG(\"Connected: Connection established.\");\n }\/*}}}*\/\n void Account::onDisconnect(gloox::ConnectionError e)\/*{{{*\/\n {\n LOG(\"Disconnected: \" + libsxc::genConnErrorString(\n e,\n _client.streamError(),\n _client.streamErrorText(),\n _client.authError(),\n \/* Debug = *\/ true));\n\n std::string text = libsxc::genConnErrorString(\n e,\n _client.streamError(),\n _client.streamErrorText(),\n _client.authError());\n if (!text.empty())\n _out.write(\"Disconnected: \" + text);\n }\/*}}}*\/\n bool Account::onTLSConnect(const gloox::CertInfo &info)\/*{{{*\/\n {\n LOG(\"Acknowledge TLS certificate.\");\n\n return true;\n }\/*}}}*\/\n\n void *Account::_run(void *rawThat)\/*{{{*\/\n {\n LOG(\"Start socket receiving thread.\");\n\n Account *that = (Account *) rawThat;\n that->_client.connect(); \/\/ Blocking.\n\n LOG(\"End socket receiving thread.\");\n\n return (void *) NULL;\n }\/*}}}*\/\n}\n\n\/\/ Use no tabs at all; two spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker\n<|endoftext|>"} {"text":"\/* rsspp - Copyright (C) 2008-2009 Andreas Krennmair \n * Licensed under the MIT\/X Consortium License. See file LICENSE\n * for more information.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace newsbeuter;\n\nstatic size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {\n\tstd::string * pbuf = static_cast(userp);\n\tpbuf->append(static_cast(buffer), size * nmemb);\n\treturn size * nmemb;\n}\n\nnamespace rsspp {\n\nparser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) \n\t: to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) {\n}\n\nparser::~parser() {\n\tif (doc)\n\t\txmlFreeDoc(doc);\n}\n\nstruct header_values {\n\ttime_t lastmodified;\n\tstd::string etag;\n};\n\nstatic size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) {\n\tchar * header = new char[size*nmemb + 1];\n\theader_values * values = (header_values *)data;\n\n\tmemcpy(header, ptr, size*nmemb);\n\theader[size*nmemb] = '\\0';\n\n\tif (!strncasecmp(\"Last-Modified:\", header, 14)) {\n\t\tvalues->lastmodified = curl_getdate(header+14, NULL);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got last-modified %s (%d)\", header+14, values->lastmodified);\n\t} else if (!strncasecmp(\"ETag:\",header, 5)) {\n\t\tvalues->etag = std::string(header+5);\n\t\tutils::trim(values->etag);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got etag %s\", values->etag.c_str());\n\t}\n\n\tdelete[] header;\n\n\treturn size * nmemb;\n}\n\nfeed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag) {\n\tstd::string buf;\n\tCURLcode ret;\n\n\tCURL * easyhandle = curl_easy_init();\n\tif (!easyhandle) {\n\t\tthrow exception(_(\"couldn't initialize libcurl\"));\n\t}\n\n\tif (ua) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);\n\t}\n\tcurl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());\n\tcurl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);\n\tcurl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_ENCODING, \"gzip, deflate\");\n\tif (to != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);\n\n\tif (prx)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);\n\n\tif (prxauth)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);\n\n\theader_values hdrs = { 0, \"\" };\n\n\tcurl_slist * custom_headers = NULL;\n\n\tif (lastmodified != 0) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\tif (etag.length() > 0) {\n\t\tcustom_headers = curl_slist_append(custom_headers, utils::strprintf(\"If-None-Match: %s\", etag.c_str()).c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\n\tret = curl_easy_perform(easyhandle);\n\n\tlm = hdrs.lastmodified;\n\tet = hdrs.etag;\n\n\tif (custom_headers) {\n\t\tcurl_slist_free_all(custom_headers);\n\t}\n\n\tLOG(LOG_DEBUG, \"rsspp::parser::parse_url: ret = %d\", ret);\n\n\tlong status;\n\tcurl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);\n\n\tif (status >= 400) {\n\t\tLOG(LOG_USERERROR, _(\"Error: trying to download feed `%s' returned HTTP status code %ld.\"), url.c_str(), status);\n\t}\n\n\tcurl_easy_cleanup(easyhandle);\n\n\tif (ret != 0) {\n\t\tLOG(LOG_ERROR, \"rsspp::parser::parse_url: curl_easy_perform returned err %d: %s\", ret, curl_easy_strerror(ret));\n\t\tthrow exception(curl_easy_strerror(ret));\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_url: retrieved data for %s: %s\", url.c_str(), buf.c_str());\n\n\tif (buf.length() > 0) {\n\t\tLOG(LOG_DEBUG, \"parser::parse_url: handing over data to parse_buffer()\");\n\t\treturn parse_buffer(buf.c_str(), buf.length(), url.c_str());\n\t}\n\n\treturn feed();\n}\n\nfeed parser::parse_buffer(const char * buffer, size_t size, const char * url) {\n\tdoc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse buffer\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_buffer: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_file(const std::string& filename) {\n\tdoc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse file\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_file: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_xmlnode(xmlNode* node) {\n\tfeed f;\n\n\tif (node) {\n\t\tif (node->name && node->type == XML_ELEMENT_NODE) {\n\t\t\tif (strcmp((const char *)node->name, \"rss\")==0) {\n\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\tif (!version) {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"no RSS version\"));\n\t\t\t\t}\n\t\t\t\tif (strcmp(version, \"0.91\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_91;\n\t\t\t\telse if (strcmp(version, \"0.92\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_92;\n\t\t\t\telse if (strcmp(version, \"2.0\")==0)\n\t\t\t\t\tf.rss_version = RSS_2_0;\n\t\t\t\telse {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"invalid RSS version\"));\n\t\t\t\t}\n\t\t\t\txmlFree((void *)version);\n\t\t\t} else if (strcmp((const char *)node->name, \"RDF\")==0) {\n\t\t\t\tf.rss_version = RSS_1_0;\n\t\t\t} else if (strcmp((const char *)node->name, \"feed\")==0) {\n\t\t\t\tif (node->ns && node->ns->href) {\n\t\t\t\t\tif (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_0_3;\n\t\t\t\t\t} else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_1_0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow exception(_(\"no Atom version\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::tr1::shared_ptr parser = rss_parser_factory::get_object(f, doc);\n\n\t\t\ttry {\n\t\t\t\tparser->parse_feed(f, node);\n\t\t\t} catch (exception& e) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\t}\n\n\treturn f;\n}\n\nvoid parser::global_init() {\n\tLIBXML_TEST_VERSION\n\tcurl_global_init(CURL_GLOBAL_ALL);\n}\n\nvoid parser::global_cleanup() {\n\txmlCleanupParser();\n\tcurl_global_cleanup();\n}\n\n\n}\nadded rss version \"2\" as workaround for broken feeds.\/* rsspp - Copyright (C) 2008-2009 Andreas Krennmair \n * Licensed under the MIT\/X Consortium License. See file LICENSE\n * for more information.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace newsbeuter;\n\nstatic size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {\n\tstd::string * pbuf = static_cast(userp);\n\tpbuf->append(static_cast(buffer), size * nmemb);\n\treturn size * nmemb;\n}\n\nnamespace rsspp {\n\nparser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) \n\t: to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) {\n}\n\nparser::~parser() {\n\tif (doc)\n\t\txmlFreeDoc(doc);\n}\n\nstruct header_values {\n\ttime_t lastmodified;\n\tstd::string etag;\n};\n\nstatic size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) {\n\tchar * header = new char[size*nmemb + 1];\n\theader_values * values = (header_values *)data;\n\n\tmemcpy(header, ptr, size*nmemb);\n\theader[size*nmemb] = '\\0';\n\n\tif (!strncasecmp(\"Last-Modified:\", header, 14)) {\n\t\tvalues->lastmodified = curl_getdate(header+14, NULL);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got last-modified %s (%d)\", header+14, values->lastmodified);\n\t} else if (!strncasecmp(\"ETag:\",header, 5)) {\n\t\tvalues->etag = std::string(header+5);\n\t\tutils::trim(values->etag);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got etag %s\", values->etag.c_str());\n\t}\n\n\tdelete[] header;\n\n\treturn size * nmemb;\n}\n\nfeed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag) {\n\tstd::string buf;\n\tCURLcode ret;\n\n\tCURL * easyhandle = curl_easy_init();\n\tif (!easyhandle) {\n\t\tthrow exception(_(\"couldn't initialize libcurl\"));\n\t}\n\n\tif (ua) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);\n\t}\n\tcurl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());\n\tcurl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);\n\tcurl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_ENCODING, \"gzip, deflate\");\n\tif (to != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);\n\n\tif (prx)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);\n\n\tif (prxauth)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);\n\n\theader_values hdrs = { 0, \"\" };\n\n\tcurl_slist * custom_headers = NULL;\n\n\tif (lastmodified != 0) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\tif (etag.length() > 0) {\n\t\tcustom_headers = curl_slist_append(custom_headers, utils::strprintf(\"If-None-Match: %s\", etag.c_str()).c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\t}\n\n\tret = curl_easy_perform(easyhandle);\n\n\tlm = hdrs.lastmodified;\n\tet = hdrs.etag;\n\n\tif (custom_headers) {\n\t\tcurl_slist_free_all(custom_headers);\n\t}\n\n\tLOG(LOG_DEBUG, \"rsspp::parser::parse_url: ret = %d\", ret);\n\n\tlong status;\n\tcurl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);\n\n\tif (status >= 400) {\n\t\tLOG(LOG_USERERROR, _(\"Error: trying to download feed `%s' returned HTTP status code %ld.\"), url.c_str(), status);\n\t}\n\n\tcurl_easy_cleanup(easyhandle);\n\n\tif (ret != 0) {\n\t\tLOG(LOG_ERROR, \"rsspp::parser::parse_url: curl_easy_perform returned err %d: %s\", ret, curl_easy_strerror(ret));\n\t\tthrow exception(curl_easy_strerror(ret));\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_url: retrieved data for %s: %s\", url.c_str(), buf.c_str());\n\n\tif (buf.length() > 0) {\n\t\tLOG(LOG_DEBUG, \"parser::parse_url: handing over data to parse_buffer()\");\n\t\treturn parse_buffer(buf.c_str(), buf.length(), url.c_str());\n\t}\n\n\treturn feed();\n}\n\nfeed parser::parse_buffer(const char * buffer, size_t size, const char * url) {\n\tdoc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse buffer\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_buffer: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_file(const std::string& filename) {\n\tdoc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse file\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_file: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_xmlnode(xmlNode* node) {\n\tfeed f;\n\n\tif (node) {\n\t\tif (node->name && node->type == XML_ELEMENT_NODE) {\n\t\t\tif (strcmp((const char *)node->name, \"rss\")==0) {\n\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\tif (!version) {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"no RSS version\"));\n\t\t\t\t}\n\t\t\t\tif (strcmp(version, \"0.91\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_91;\n\t\t\t\telse if (strcmp(version, \"0.92\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_92;\n\t\t\t\telse if (strcmp(version, \"2.0\")==0 || strcmp(version, \"2\")==0)\n\t\t\t\t\tf.rss_version = RSS_2_0;\n\t\t\t\telse {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"invalid RSS version\"));\n\t\t\t\t}\n\t\t\t\txmlFree((void *)version);\n\t\t\t} else if (strcmp((const char *)node->name, \"RDF\")==0) {\n\t\t\t\tf.rss_version = RSS_1_0;\n\t\t\t} else if (strcmp((const char *)node->name, \"feed\")==0) {\n\t\t\t\tif (node->ns && node->ns->href) {\n\t\t\t\t\tif (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_0_3;\n\t\t\t\t\t} else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_1_0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow exception(_(\"no Atom version\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::tr1::shared_ptr parser = rss_parser_factory::get_object(f, doc);\n\n\t\t\ttry {\n\t\t\t\tparser->parse_feed(f, node);\n\t\t\t} catch (exception& e) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\t}\n\n\treturn f;\n}\n\nvoid parser::global_init() {\n\tLIBXML_TEST_VERSION\n\tcurl_global_init(CURL_GLOBAL_ALL);\n}\n\nvoid parser::global_cleanup() {\n\txmlCleanupParser();\n\tcurl_global_cleanup();\n}\n\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Author: wan@google.com (Zhanyong Wan)\n\/\/\n\/\/ Tests for Google C++ Mocking Framework (Google Mock)\n\/\/\n\/\/ Sometimes it's desirable to build most of Google Mock's own tests\n\/\/ by compiling a single file. This file serves this purpose.\n#include \"test\/gmock-actions_test.cc\"\n#include \"test\/gmock-cardinalities_test.cc\"\n#include \"test\/gmock-generated-actions_test.cc\"\n#include \"test\/gmock-generated-function-mockers_test.cc\"\n#include \"test\/gmock-generated-internal-utils_test.cc\"\n#include \"test\/gmock-generated-matchers_test.cc\"\n#include \"test\/gmock-internal-utils_test.cc\"\n#include \"test\/gmock-matchers_test.cc\"\n#include \"test\/gmock-more-actions_test.cc\"\n#include \"test\/gmock-nice-strict_test.cc\"\n#include \"test\/gmock-port_test.cc\"\n#include \"test\/gmock-spec-builders_test.cc\"\n#include \"test\/gmock_test.cc\"\nClarify the rationale for gmock_all_test.cc, and pull in gtest 669\/\/ Copyright 2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Author: wan@google.com (Zhanyong Wan)\n\/\/\n\/\/ Tests for Google C++ Mocking Framework (Google Mock)\n\/\/\n\/\/ Some users use a build system that Google Mock doesn't support directly,\n\/\/ yet they still want to build and run Google Mock's own tests. This file\n\/\/ includes most such tests, making it easier for these users to maintain\n\/\/ their build scripts (they just need to build this file, even though the\n\/\/ below list of actual *_test.cc files might change).\n#include \"test\/gmock-actions_test.cc\"\n#include \"test\/gmock-cardinalities_test.cc\"\n#include \"test\/gmock-generated-actions_test.cc\"\n#include \"test\/gmock-generated-function-mockers_test.cc\"\n#include \"test\/gmock-generated-internal-utils_test.cc\"\n#include \"test\/gmock-generated-matchers_test.cc\"\n#include \"test\/gmock-internal-utils_test.cc\"\n#include \"test\/gmock-matchers_test.cc\"\n#include \"test\/gmock-more-actions_test.cc\"\n#include \"test\/gmock-nice-strict_test.cc\"\n#include \"test\/gmock-port_test.cc\"\n#include \"test\/gmock-spec-builders_test.cc\"\n#include \"test\/gmock_test.cc\"\n<|endoftext|>"} {"text":"#include \"gt\/gtl\/test_common.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Parser )\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_emptyProgramIsValid ) {\n \/\/ given\n std::string content;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_valueParamDefinition ) {\n \/\/ given\n std::string content =\n \"LET value1 BE 10;\\n\"\n \"LET value2 BE 20.0;\\n\"\n \"LET value3 BE 3e1;\\n\"\n \"LET value4 BE 4.0e1;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 4 ); \/\/ parsed 4 definitions\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 4 ); \/\/ created 4 parameters from numbers\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_identifierParamDefinition ) {\n \/\/ given\n std::string content =\n \"LET value1 BE id;\\n\"\n \"LET value2 BE _id;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 2 ); \/\/ parsed 2 definitions\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 2 ); \/\/ created 2 parameters from identifiers\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_playerDefinition ) {\n \/\/ given\n std::string content =\n \"LET _player BE\\n\"\n \"PLAYER p1 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \"};\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 1 ); \/\/ parsed 1 definition \n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 1 ); \/\/ created 1 player\n BOOST_CHECK_EQUAL( driver.identifiers.getAddedElements(), 2 ); \/\/ created collection of 2 strategies\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_strategicGameDefinition ) {\n \/\/ given\n std::string content =\n \"LET _game BE\\n\"\n \"STRATEGIC GAME WITH\\n\"\n \" PLAYER p1 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" },\\n\"\n \" PLAYER p2 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" }\\n\"\n \"SUCH AS\\n\"\n \" { p1=s1, p2=s1 : 10, param1 },\\n\"\n \" { p1=s1, p2=s2 : param2, 20.0 },\\n\"\n \" { p1=s2 :\\n\"\n \" { p2=s1 : 3e1, param3 },\\n\"\n \" { p2=s2 : param4, 4.0e1 }\\n\"\n \" };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 1 ); \/\/ parsed 1 definition\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ created 2 players\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 8 ); \/\/ created 8 parameters from numbers\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_treeGameDefinition ) {\n \/\/ given\n std::string content =\n \"LET _game BE\\n\"\n \"TREE GAME WITH\\n\"\n \" PLAYER p1 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" },\\n\"\n \" PLAYER p2 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" }\\n\"\n \"SUCH AS\\n\"\n \" { p1=s1 :\\n\"\n \" { p2=s1 : 10, param1 },\\n\"\n \" { p2=s2 : param2, 20.0 }\\n\"\n \" },\\n\"\n \" { p1=s2 :\\n\"\n \" { p2=s1 : 3e1, param3 },\\n\"\n \" { p2=s2 : param4, 4.0e1 }\\n\"\n \" };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 1 ); \/\/ parsed 1 definition\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ created 2 players\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 8 ); \/\/ created 8 parameters from numbers\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_queryForType ) {\n \/\/ given\n std::string content =\n \"FIND type\\n\"\n \"FOR\\n\"\n \" 10,\\n\"\n \" 20.0,\\n\"\n \" 3e1,\\n\"\n \" 4.0e1,\\n\"\n \" identifier,\\n\"\n \" PLAYER p { s1, s2 },\\n\"\n \" STRATEGIC GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s, p2=s : 10, 20 }\\n\"\n \" END,\\n\"\n \" TREE GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s :\\n\"\n \" { p2=s : 10, 20 }\\n\"\n \" }\\n\"\n \" END;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parser 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 9 ); \/\/ created 9 parameters from numbers (8) nad identifiers (1)\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 5 ); \/\/ crated 5 players\n BOOST_CHECK_EQUAL( driver.game.getCreatedStrategicGames(), 1 ); \/\/ created 1 strategy game\n BOOST_CHECK_EQUAL( driver.game.getCreatedTreeGames(), 1 ); \/\/ created 1 tree game\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_queryForValue ) {\n \/\/ given\n std::string content =\n \"FIND value\\n\"\n \"FOR\\n\"\n \" 10,\\n\"\n \" 20.0,\\n\"\n \" 3e1,\\n\"\n \" 4.0e1,\\n\"\n \" identifier;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parser 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 5 ); \/\/ created 5 parameters from numbers (4) nad identifiers (1)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_queryForEquilibrium ) {\n \/\/ given\n std::string content =\n \"FIND pure_equilibrium, mixed_equilibrium\\n\"\n \"FOR\\n\"\n \" STRATEGIC GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s, p2=s : 10, 20 }\\n\"\n \" END,\\n\"\n \" TREE GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s :\\n\"\n \" { p2=s : 10, 20 }\\n\"\n \" }\\n\"\n \" END;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parsed 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 4 ); \/\/ created 4 parameters from numbers\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 4 ); \/\/ crated 4 players\n BOOST_CHECK_EQUAL( driver.game.getCreatedStrategicGames(), 1 ); \/\/ created 1 strategy game\n BOOST_CHECK_EQUAL( driver.game.getCreatedTreeGames(), 1 ); \/\/ created 1 tree game\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_defineThenQuery ) {\n \/\/ given\n std::string content =\n \"LET player1 BE\\n\"\n \" PLAYER p1 { s };\\n\"\n \"LET player2 BE\\n\"\n \" PLAYER p2 { s };\\n\"\n \"FIND pure_equilibrium, mixed_equilibrium\\n\"\n \"FOR\\n\"\n \" STRATEGIC GAME\\n\"\n \" WITH\\n\"\n \" player1,\\n\"\n \" player2\\n\"\n \" SUCH AS\\n\"\n \" { p1=s, p2=s : 10, 20 };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 2 ); \/\/ parsed 2 definitions\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parsed 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 4 ); \/\/ created 4 parameters from numbers (2) and identifiers (2)\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ crated 2 players\n BOOST_CHECK_EQUAL( driver.game.getCreatedStrategicGames(), 1 ); \/\/ created 1 strategy game\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_recoverFromErrorAtStatement ) {\n \/\/ given\n std::string content =\n \"error;\\n\"\n \"LET player1 BE\\n\"\n \" PLAYER p1 { s };\\n\"\n \"LET player2 BE\\n\"\n \" PLAYER p2 { s };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ recovered from parsing error\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 1 ); \/\/ 1 error occured\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 2 ); \/\/ parsed 2 definitions\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ created 2 players\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n* Modified parser test to match convension used in project.#include \"gt\/gtl\/test_common.hpp\"\n\nBOOST_AUTO_TEST_SUITE( Parser )\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE( Parser_emptyProgramIsValid ) {\n \/\/ given\n std::string content;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n}\n\nBOOST_AUTO_TEST_CASE( Parser_valueParamDefinition ) {\n \/\/ given\n std::string content =\n \"LET value1 BE 10;\\n\"\n \"LET value2 BE 20.0;\\n\"\n \"LET value3 BE 3e1;\\n\"\n \"LET value4 BE 4.0e1;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 4 ); \/\/ parsed 4 definitions\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 4 ); \/\/ created 4 parameters from numbers\n}\n\nBOOST_AUTO_TEST_CASE( Parser_identifierParamDefinition ) {\n \/\/ given\n std::string content =\n \"LET value1 BE id;\\n\"\n \"LET value2 BE _id;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 2 ); \/\/ parsed 2 definitions\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 2 ); \/\/ created 2 parameters from identifiers\n}\n\nBOOST_AUTO_TEST_CASE( Parser_playerDefinition ) {\n \/\/ given\n std::string content =\n \"LET _player BE\\n\"\n \"PLAYER p1 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \"};\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 1 ); \/\/ parsed 1 definition \n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 1 ); \/\/ created 1 player\n BOOST_CHECK_EQUAL( driver.identifiers.getAddedElements(), 2 ); \/\/ created collection of 2 strategies\n}\n\nBOOST_AUTO_TEST_CASE( Parser_strategicGameDefinition ) {\n \/\/ given\n std::string content =\n \"LET _game BE\\n\"\n \"STRATEGIC GAME WITH\\n\"\n \" PLAYER p1 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" },\\n\"\n \" PLAYER p2 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" }\\n\"\n \"SUCH AS\\n\"\n \" { p1=s1, p2=s1 : 10, param1 },\\n\"\n \" { p1=s1, p2=s2 : param2, 20.0 },\\n\"\n \" { p1=s2 :\\n\"\n \" { p2=s1 : 3e1, param3 },\\n\"\n \" { p2=s2 : param4, 4.0e1 }\\n\"\n \" };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 1 ); \/\/ parsed 1 definition\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ created 2 players\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 8 ); \/\/ created 8 parameters from numbers\n}\n\nBOOST_AUTO_TEST_CASE( Parser_treeGameDefinition ) {\n \/\/ given\n std::string content =\n \"LET _game BE\\n\"\n \"TREE GAME WITH\\n\"\n \" PLAYER p1 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" },\\n\"\n \" PLAYER p2 {\\n\"\n \" s1,\\n\"\n \" s2\\n\"\n \" }\\n\"\n \"SUCH AS\\n\"\n \" { p1=s1 :\\n\"\n \" { p2=s1 : 10, param1 },\\n\"\n \" { p2=s2 : param2, 20.0 }\\n\"\n \" },\\n\"\n \" { p1=s2 :\\n\"\n \" { p2=s1 : 3e1, param3 },\\n\"\n \" { p2=s2 : param4, 4.0e1 }\\n\"\n \" };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 1 ); \/\/ parsed 1 definition\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ created 2 players\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 8 ); \/\/ created 8 parameters from numbers\n}\n\nBOOST_AUTO_TEST_CASE( Parser_queryForType ) {\n \/\/ given\n std::string content =\n \"FIND type\\n\"\n \"FOR\\n\"\n \" 10,\\n\"\n \" 20.0,\\n\"\n \" 3e1,\\n\"\n \" 4.0e1,\\n\"\n \" identifier,\\n\"\n \" PLAYER p { s1, s2 },\\n\"\n \" STRATEGIC GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s, p2=s : 10, 20 }\\n\"\n \" END,\\n\"\n \" TREE GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s :\\n\"\n \" { p2=s : 10, 20 }\\n\"\n \" }\\n\"\n \" END;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parser 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 9 ); \/\/ created 9 parameters from numbers (8) nad identifiers (1)\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 5 ); \/\/ crated 5 players\n BOOST_CHECK_EQUAL( driver.game.getCreatedStrategicGames(), 1 ); \/\/ created 1 strategy game\n BOOST_CHECK_EQUAL( driver.game.getCreatedTreeGames(), 1 ); \/\/ created 1 tree game\n}\n\nBOOST_AUTO_TEST_CASE( Parser_queryForValue ) {\n \/\/ given\n std::string content =\n \"FIND value\\n\"\n \"FOR\\n\"\n \" 10,\\n\"\n \" 20.0,\\n\"\n \" 3e1,\\n\"\n \" 4.0e1,\\n\"\n \" identifier;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parser 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 5 ); \/\/ created 5 parameters from numbers (4) nad identifiers (1)\n}\n\nBOOST_AUTO_TEST_CASE( Parser_queryForEquilibrium ) {\n \/\/ given\n std::string content =\n \"FIND pure_equilibrium, mixed_equilibrium\\n\"\n \"FOR\\n\"\n \" STRATEGIC GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s, p2=s : 10, 20 }\\n\"\n \" END,\\n\"\n \" TREE GAME\\n\"\n \" WITH\\n\"\n \" PLAYER p1 { s },\\n\"\n \" PLAYER p2 { s }\\n\"\n \" SUCH AS\\n\"\n \" { p1=s :\\n\"\n \" { p2=s : 10, 20 }\\n\"\n \" }\\n\"\n \" END;\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parsed 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 4 ); \/\/ created 4 parameters from numbers\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 4 ); \/\/ crated 4 players\n BOOST_CHECK_EQUAL( driver.game.getCreatedStrategicGames(), 1 ); \/\/ created 1 strategy game\n BOOST_CHECK_EQUAL( driver.game.getCreatedTreeGames(), 1 ); \/\/ created 1 tree game\n}\n\nBOOST_AUTO_TEST_CASE( Parser_defineThenQuery ) {\n \/\/ given\n std::string content =\n \"LET player1 BE\\n\"\n \" PLAYER p1 { s };\\n\"\n \"LET player2 BE\\n\"\n \" PLAYER p2 { s };\\n\"\n \"FIND pure_equilibrium, mixed_equilibrium\\n\"\n \"FOR\\n\"\n \" STRATEGIC GAME\\n\"\n \" WITH\\n\"\n \" player1,\\n\"\n \" player2\\n\"\n \" SUCH AS\\n\"\n \" { p1=s, p2=s : 10, 20 };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ no errors occured\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 0 ); \/\/ no errors shown\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 2 ); \/\/ parsed 2 definitions\n BOOST_CHECK_EQUAL( driver.statement.getExecutedQueries(), 1 ); \/\/ parsed 1 query\n BOOST_CHECK_EQUAL( driver.value.getUsedParameters(), 4 ); \/\/ created 4 parameters from numbers (2) and identifiers (2)\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ crated 2 players\n BOOST_CHECK_EQUAL( driver.game.getCreatedStrategicGames(), 1 ); \/\/ created 1 strategy game\n}\n\nBOOST_AUTO_TEST_CASE( Parser_recoverFromErrorAtStatement ) {\n \/\/ given\n std::string content =\n \"error;\\n\"\n \"LET player1 BE\\n\"\n \" PLAYER p1 { s };\\n\"\n \"LET player2 BE\\n\"\n \" PLAYER p2 { s };\\n\"\n ;\n std::istringstream stream(content);\n GT::GTL::Scanner scanner(&stream);\n TestDriverImpl driver;\n\n \/\/ when\n GT::GTL::Parser parser(scanner, driver);\n \/\/ parser.set_debug_level(1);\n\n \/\/ then\n BOOST_REQUIRE_EQUAL( parser.parse(), 0 ); \/\/ recovered from parsing error\n BOOST_CHECK_EQUAL( driver.getShownErrors(), 1 ); \/\/ 1 error occured\n BOOST_CHECK_EQUAL( driver.statement.getExecutedDefinitions(), 2 ); \/\/ parsed 2 definitions\n BOOST_CHECK_EQUAL( driver.game.getCreatedPlayers(), 2 ); \/\/ created 2 players\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/find_bar_win.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass FindInPageControllerTest : public UITest {\n public:\n FindInPageControllerTest() {\n show_window_ = true;\n }\n};\n\nconst std::wstring kFramePage = L\"files\/find_in_page\/frames.html\";\nconst std::wstring kUserSelectPage = L\"files\/find_in_page\/user-select.html\";\nconst std::wstring kCrashPage = L\"files\/find_in_page\/crash_1341577.html\";\nconst std::wstring kTooFewMatchesPage = L\"files\/find_in_page\/bug_1155639.html\";\n\n\/\/ This test loads a page with frames and starts FindInPage requests\nTEST_F(FindInPageControllerTest, FindInPageFrames) {\n TestServer server(L\"chrome\/test\/data\");\n\n \/\/ First we navigate to our frames page.\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ Try incremental search (mimicking user typing in).\n EXPECT_EQ(18, tab->FindInPage(L\"g\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(11, tab->FindInPage(L\"go\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(04, tab->FindInPage(L\"goo\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(03, tab->FindInPage(L\"goog\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(02, tab->FindInPage(L\"googl\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(01, tab->FindInPage(L\"google\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(00, tab->FindInPage(L\"google!\", FWD, IGNORE_CASE, false));\n\n \/\/ Negative test (no matches should be found).\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n\n \/\/ 'horse' only exists in the three right frames.\n EXPECT_EQ(3, tab->FindInPage(L\"horse\", FWD, IGNORE_CASE, false));\n\n \/\/ 'cat' only exists in the first frame.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching again, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching backwards, ignoring case, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"CAT\", BACK, IGNORE_CASE, false));\n\n \/\/ Try case sensitive, should NOT find it.\n EXPECT_EQ(0, tab->FindInPage(L\"CAT\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try again case sensitive, but this time with right case.\n EXPECT_EQ(1, tab->FindInPage(L\"dog\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n}\n\n\/\/ Load a page with no selectable text and make sure we don't crash.\nTEST_F(FindInPageControllerTest, FindUnSelectableText) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kUserSelectPage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_EQ(0, tab->FindInPage(L\"text\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n}\n\n\/\/ Try to reproduce the crash seen in issue 1341577.\nTEST_F(FindInPageControllerTest, FindCrash_Issue1341577) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kCrashPage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This would crash the tab. These must be the first two find requests issued\n \/\/ against the frame, otherwise an active frame pointer is set and it wont\n \/\/ produce the crash.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, false));\n \/\/ FindNext returns -1 for match count because it doesn't bother with\n \/\/ recounting the number of matches. We don't care about the match count\n \/\/ anyway in this case, we just want to make sure it doesn't crash.\n EXPECT_EQ(-1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, true));\n\n \/\/ This should work fine.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D24\\u0D46\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"nostring\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ Test to make sure Find does the right thing when restarting from a timeout.\n\/\/ We used to have a problem where we'd stop finding matches when all of the\n\/\/ following conditions were true:\n\/\/ 1) The page has a lot of text to search.\n\/\/ 2) The page contains more than one match.\n\/\/ 3) It takes longer than the time-slice given to each Find operation (100\n\/\/ ms) to find one or more of those matches (so Find times out and has to try\n\/\/ again from where it left off).\nTEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1155639) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kTooFewMatchesPage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This string appears 5 times at the bottom of a long page. If Find restarts\n \/\/ properly after a timeout, it will find 5 matches, not just 1.\n EXPECT_EQ(5, tab->FindInPage(L\"008.xml\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ The find window should not change its location just because we open and close\n\/\/ a new tab.\nTEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {\n fprintf(stderr, \"Starting FindMovesOnTabClose_Issue1343052\\n\");\n TestServer server(L\"chrome\/test\/data\");\n\n fprintf(stderr, \"TestServerPageW\\n\");\n GURL url = server.TestServerPageW(kFramePage);\n fprintf(stderr, \"GetActiveTab A\\n\");\n scoped_ptr tabA(GetActiveTab());\n fprintf(stderr, \"Navigate A\\n\");\n ASSERT_TRUE(tabA->NavigateToURL(url));\n fprintf(stderr, \"WaitUntilTabCount(1) for A\\n\");\n WaitUntilTabCount(1);\n\n fprintf(stderr, \"GetBrowserWindow(0)\\n\");\n scoped_ptr browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get() != NULL);\n\n \/\/ Toggle the bookmark bar state.\n fprintf(stderr, \"ApplyAccelerator bookmark bar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkVisibility\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));\n\n \/\/ Open the Find window and wait for it to animate.\n fprintf(stderr, \"OpenFindInPage in A\\n\");\n EXPECT_TRUE(tabA->OpenFindInPage());\n fprintf(stderr, \"WaitForWindowFullyVisible in A\\n\");\n EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));\n\n \/\/ Find its location.\n int x = -1, y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab B).\n fprintf(stderr, \"AppendTab B\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab B\\n\");\n scoped_ptr tabB(GetActiveTab());\n\n \/\/ Close tab B.\n fprintf(stderr, \"Tab Close B\\n\");\n EXPECT_TRUE(tabB->Close(true));\n\n \/\/ See if the Find window has moved.\n int new_x = -1, new_y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n\n \/\/ Now reset the bookmarks bar state and try the same again.\n fprintf(stderr, \"ApplyAccelerator BookmarksBar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkBarVisibilityChange\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));\n\n \/\/ Bookmark bar has moved, reset our coordinates.\n fprintf(stderr, \"GetFindWindowLocation again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab C).\n fprintf(stderr, \"Append tab C\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab C\\n\");\n scoped_ptr tabC(GetActiveTab());\n\n \/\/ Close it.\n fprintf(stderr, \"Close tab C\\n\");\n EXPECT_TRUE(tabC->Close(true));\n\n \/\/ See if the Find window has moved.\n fprintf(stderr, \"GetFindWindowLocation yet again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n fprintf(stderr, \"Done!\\n\");\n}\nFix include path from last checkin. Review URL: http:\/\/codereview.chromium.org\/7815\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/views\/find_bar_win.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nclass FindInPageControllerTest : public UITest {\n public:\n FindInPageControllerTest() {\n show_window_ = true;\n }\n};\n\nconst std::wstring kFramePage = L\"files\/find_in_page\/frames.html\";\nconst std::wstring kUserSelectPage = L\"files\/find_in_page\/user-select.html\";\nconst std::wstring kCrashPage = L\"files\/find_in_page\/crash_1341577.html\";\nconst std::wstring kTooFewMatchesPage = L\"files\/find_in_page\/bug_1155639.html\";\n\n\/\/ This test loads a page with frames and starts FindInPage requests\nTEST_F(FindInPageControllerTest, FindInPageFrames) {\n TestServer server(L\"chrome\/test\/data\");\n\n \/\/ First we navigate to our frames page.\n GURL url = server.TestServerPageW(kFramePage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ Try incremental search (mimicking user typing in).\n EXPECT_EQ(18, tab->FindInPage(L\"g\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(11, tab->FindInPage(L\"go\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(04, tab->FindInPage(L\"goo\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(03, tab->FindInPage(L\"goog\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(02, tab->FindInPage(L\"googl\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(01, tab->FindInPage(L\"google\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(00, tab->FindInPage(L\"google!\", FWD, IGNORE_CASE, false));\n\n \/\/ Negative test (no matches should be found).\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n\n \/\/ 'horse' only exists in the three right frames.\n EXPECT_EQ(3, tab->FindInPage(L\"horse\", FWD, IGNORE_CASE, false));\n\n \/\/ 'cat' only exists in the first frame.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching again, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"cat\", FWD, IGNORE_CASE, false));\n\n \/\/ Try searching backwards, ignoring case, should still come up with 1 match.\n EXPECT_EQ(1, tab->FindInPage(L\"CAT\", BACK, IGNORE_CASE, false));\n\n \/\/ Try case sensitive, should NOT find it.\n EXPECT_EQ(0, tab->FindInPage(L\"CAT\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try again case sensitive, but this time with right case.\n EXPECT_EQ(1, tab->FindInPage(L\"dog\", FWD, CASE_SENSITIVE, false));\n\n \/\/ Try non-Latin characters ('Hreggvidur' with 'eth' for 'd' in left frame).\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(1, tab->FindInPage(L\"Hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"hreggvi\\u00F0ur\", FWD, CASE_SENSITIVE, false));\n}\n\n\/\/ Load a page with no selectable text and make sure we don't crash.\nTEST_F(FindInPageControllerTest, FindUnSelectableText) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kUserSelectPage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n EXPECT_EQ(0, tab->FindInPage(L\"text\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"Non-existing string\", FWD, IGNORE_CASE,\n false));\n}\n\n\/\/ Try to reproduce the crash seen in issue 1341577.\nTEST_F(FindInPageControllerTest, FindCrash_Issue1341577) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kCrashPage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This would crash the tab. These must be the first two find requests issued\n \/\/ against the frame, otherwise an active frame pointer is set and it wont\n \/\/ produce the crash.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, false));\n \/\/ FindNext returns -1 for match count because it doesn't bother with\n \/\/ recounting the number of matches. We don't care about the match count\n \/\/ anyway in this case, we just want to make sure it doesn't crash.\n EXPECT_EQ(-1, tab->FindInPage(L\"\\u0D4C\", FWD, IGNORE_CASE, true));\n\n \/\/ This should work fine.\n EXPECT_EQ(1, tab->FindInPage(L\"\\u0D24\\u0D46\", FWD, IGNORE_CASE, false));\n EXPECT_EQ(0, tab->FindInPage(L\"nostring\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ Test to make sure Find does the right thing when restarting from a timeout.\n\/\/ We used to have a problem where we'd stop finding matches when all of the\n\/\/ following conditions were true:\n\/\/ 1) The page has a lot of text to search.\n\/\/ 2) The page contains more than one match.\n\/\/ 3) It takes longer than the time-slice given to each Find operation (100\n\/\/ ms) to find one or more of those matches (so Find times out and has to try\n\/\/ again from where it left off).\nTEST_F(FindInPageControllerTest, FindEnoughMatches_Issue1155639) {\n TestServer server(L\"chrome\/test\/data\");\n\n GURL url = server.TestServerPageW(kTooFewMatchesPage);\n scoped_ptr tab(GetActiveTab());\n ASSERT_TRUE(tab->NavigateToURL(url));\n WaitUntilTabCount(1);\n\n \/\/ This string appears 5 times at the bottom of a long page. If Find restarts\n \/\/ properly after a timeout, it will find 5 matches, not just 1.\n EXPECT_EQ(5, tab->FindInPage(L\"008.xml\", FWD, IGNORE_CASE, false));\n}\n\n\/\/ The find window should not change its location just because we open and close\n\/\/ a new tab.\nTEST_F(FindInPageControllerTest, FindMovesOnTabClose_Issue1343052) {\n fprintf(stderr, \"Starting FindMovesOnTabClose_Issue1343052\\n\");\n TestServer server(L\"chrome\/test\/data\");\n\n fprintf(stderr, \"TestServerPageW\\n\");\n GURL url = server.TestServerPageW(kFramePage);\n fprintf(stderr, \"GetActiveTab A\\n\");\n scoped_ptr tabA(GetActiveTab());\n fprintf(stderr, \"Navigate A\\n\");\n ASSERT_TRUE(tabA->NavigateToURL(url));\n fprintf(stderr, \"WaitUntilTabCount(1) for A\\n\");\n WaitUntilTabCount(1);\n\n fprintf(stderr, \"GetBrowserWindow(0)\\n\");\n scoped_ptr browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get() != NULL);\n\n \/\/ Toggle the bookmark bar state.\n fprintf(stderr, \"ApplyAccelerator bookmark bar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkVisibility\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), true));\n\n \/\/ Open the Find window and wait for it to animate.\n fprintf(stderr, \"OpenFindInPage in A\\n\");\n EXPECT_TRUE(tabA->OpenFindInPage());\n fprintf(stderr, \"WaitForWindowFullyVisible in A\\n\");\n EXPECT_TRUE(WaitForFindWindowFullyVisible(tabA.get()));\n\n \/\/ Find its location.\n int x = -1, y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab B).\n fprintf(stderr, \"AppendTab B\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab B\\n\");\n scoped_ptr tabB(GetActiveTab());\n\n \/\/ Close tab B.\n fprintf(stderr, \"Tab Close B\\n\");\n EXPECT_TRUE(tabB->Close(true));\n\n \/\/ See if the Find window has moved.\n int new_x = -1, new_y = -1;\n fprintf(stderr, \"GetFindWindowLocation in A\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n\n \/\/ Now reset the bookmarks bar state and try the same again.\n fprintf(stderr, \"ApplyAccelerator BookmarksBar\\n\");\n browser->ApplyAccelerator(IDC_SHOW_BOOKMARKS_BAR);\n fprintf(stderr, \"WaitForBookmarkBarVisibilityChange\\n\");\n EXPECT_TRUE(WaitForBookmarkBarVisibilityChange(browser.get(), false));\n\n \/\/ Bookmark bar has moved, reset our coordinates.\n fprintf(stderr, \"GetFindWindowLocation again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&x, &y));\n\n \/\/ Open another tab (tab C).\n fprintf(stderr, \"Append tab C\\n\");\n EXPECT_TRUE(browser->AppendTab(url));\n fprintf(stderr, \"GetActiveTab C\\n\");\n scoped_ptr tabC(GetActiveTab());\n\n \/\/ Close it.\n fprintf(stderr, \"Close tab C\\n\");\n EXPECT_TRUE(tabC->Close(true));\n\n \/\/ See if the Find window has moved.\n fprintf(stderr, \"GetFindWindowLocation yet again\\n\");\n EXPECT_TRUE(tabA->GetFindWindowLocation(&new_x, &new_y));\n\n EXPECT_EQ(x, new_x);\n EXPECT_EQ(y, new_y);\n fprintf(stderr, \"Done!\\n\");\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: semaphor.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2003-03-26 16:45:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _OSL_SEMAPHORE_HXX_\n#define _OSL_SEMAPHORE_HXX_\n\n#ifdef __cplusplus\n\n#include \n\n\nnamespace osl\n{\n\n class Semaphore {\n oslSemaphore semaphore;\n\n public:\n\n \/** Creates a semaphore.
\n @param InitialCount denotes the starting value the semaphore. If you set it to\n zero, the first acquire() blocks. Otherwise InitialCount acquire()s are\n immedeatly successfull.\n @return 0 if the semaphore could not be created, otherwise a handle to the sem.\n *\/\n\n Semaphore(sal_uInt32 initialCount)\n {\n semaphore = osl_createSemaphore(initialCount);\n }\n\n \/** Release the OS-structures and free semaphore data-structure\n @return fbbb\n *\/\n ~Semaphore()\n {\n osl_destroySemaphore(semaphore);\n }\n\n \/** acquire() decreases the count. It will block if it tries to\n decrease below zero.\n @return False if the system-call failed.\n *\/\n sal_Bool acquire()\n {\n return osl_acquireSemaphore(semaphore);\n }\n\n \/** tryToAcquire() tries to decreases the count. It will\n return with False if it would decrease the count below zero.\n (When acquire() would block.) If it could successfully\n decrease the count, it will return True.\n *\/\n sal_Bool tryToAcquire()\n {\n return osl_tryToAcquireSemaphore(semaphore);\n }\n\n \/** release() increases the count.\n @return False if the system-call failed.\n *\/\n sal_Bool release()\n {\n return osl_releaseSemaphore(semaphore);\n }\n };\n}\n\n#endif \/* __cplusplus *\/\n#endif \/* _OSL_SEMAPHORE_HXX_ *\/\nINTEGRATION: CWS qdiet01 (1.6.78); FILE MERGED 2003\/09\/17 09:45:36 obr 1.6.78.1: #110999# made synchrnoization objects non copy constructable \/ assignable and updated documentation.\/*************************************************************************\n *\n * $RCSfile: semaphor.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2003-10-20 16:11:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _OSL_SEMAPHORE_HXX_\n#define _OSL_SEMAPHORE_HXX_\n\n#ifdef __cplusplus\n\n#include \n\n\nnamespace osl\n{\n\n class Semaphore {\n\n public:\n\n \/** Creates a semaphore.
\n @param InitialCount denotes the starting value the semaphore. If you set it to\n zero, the first acquire() blocks. Otherwise InitialCount acquire()s are\n immedeatly successfull.\n @return 0 if the semaphore could not be created, otherwise a handle to the sem.\n *\/\n\n Semaphore(sal_uInt32 initialCount)\n {\n semaphore = osl_createSemaphore(initialCount);\n }\n\n \/** Release the OS-structures and free semaphore data-structure\n @return fbbb\n *\/\n ~Semaphore()\n {\n osl_destroySemaphore(semaphore);\n }\n\n \/** acquire() decreases the count. It will block if it tries to\n decrease below zero.\n @return False if the system-call failed.\n *\/\n sal_Bool acquire()\n {\n return osl_acquireSemaphore(semaphore);\n }\n\n \/** tryToAcquire() tries to decreases the count. It will\n return with False if it would decrease the count below zero.\n (When acquire() would block.) If it could successfully\n decrease the count, it will return True.\n *\/\n sal_Bool tryToAcquire()\n {\n return osl_tryToAcquireSemaphore(semaphore);\n }\n\n \/** release() increases the count.\n @return False if the system-call failed.\n *\/\n sal_Bool release()\n {\n return osl_releaseSemaphore(semaphore);\n }\n\n private:\n oslSemaphore semaphore;\n\n \/** The underlying oslSemaphore has no reference count.\n\n Since the underlying oslSemaphore is not a reference counted object, copy\n constructed Semaphore may work on an already destructed oslSemaphore object.\n\n *\/\n Semaphore(const Semaphore&);\n\n \/** The underlying oslSemaphore has no reference count.\n\n When destructed, the Semaphore object destroys the undelying oslSemaphore,\n which might cause severe problems in case it's a temporary object.\n\n *\/\n Semaphore(oslSemaphore Semaphore);\n\n \/** This assignment operator is private for the same reason as\n the copy constructor.\n *\/\n Semaphore& operator= (const Semaphore&);\n\n \/** This assignment operator is private for the same reason as\n the constructor taking a oslSemaphore argument.\n *\/\n Semaphore& operator= (oslSemaphore);\n };\n}\n\n#endif \/* __cplusplus *\/\n#endif \/* _OSL_SEMAPHORE_HXX_ *\/\n<|endoftext|>"} {"text":"\/*\n Copyright (c) by respective owners including Yahoo!, Microsoft, and\n individual contributors. All rights reserved. Released under a BSD (revised)\n license as described in the file LICENSE.\n *\/\n#include \n#include \n#ifdef _WIN32\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n#include \"parse_example.h\"\n#include \"constant.h\"\n#include \"sparse_dense.h\"\n#include \"gd.h\"\n#include \"cache.h\"\n#include \"simple_label.h\"\n#include \"rand48.h\"\n#include \"vw.h\"\n#include \n#include \"hash.h\"\n#include \n#include \"parse_primitives.h\"\n\nusing namespace std;\n\nusing namespace LEARNER;\n\nnamespace MF {\n\nstruct mf {\n vector pairs;\n\n uint32_t rank;\n\n uint32_t increment;\n\n \/\/ array to cache w*x, (l^k * x_l) and (r^k * x_r)\n \/\/ [ w*(1,x_l,x_r) , l^1*x_l, r^1*x_r, l^2*x_l, r^2*x_2, ... ]\n v_array sub_predictions;\n\n \/\/ array for temp storage of indices\n v_array indices;\n\n \/\/ array for temp storage of features\n v_array temp_features;\n\n vw* all;\n};\n\ntemplate \nvoid predict(mf *data, learner& base, example* ec) {\n vw* all = data->all;\n\n float prediction = 0;\n if (cache_sub_predictions)\n data->sub_predictions.resize(2*all->rank+1, true);\n\n \/\/ predict from linear terms\n base.predict(ec);\n\n \/\/ store linear prediction\n if (cache_sub_predictions)\n data->sub_predictions[0] = ec->partial_prediction;\n prediction += ec->partial_prediction;\n\n \/\/ store namespace indices\n copy_array(data->indices, ec->indices);\n\n \/\/ add interaction terms to prediction\n for (vector::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {\n\n int left_ns = (int) (*i)[0];\n int right_ns = (int) (*i)[1];\n\n if (ec->atomics[left_ns].size() > 0 && ec->atomics[right_ns].size() > 0) {\n for (size_t k = 1; k <= all->rank; k++) {\n\n\t\/\/ set example to left namespace only\n\tec->indices.erase();\n\tec->indices.push_back(left_ns);\n\n\t\/\/ compute l^k * x_l using base learner\n\tbase.predict(ec, k);\n\tfloat x_dot_l = ec->partial_prediction;\n\tif (cache_sub_predictions)\n\t data->sub_predictions[2*k-1] = x_dot_l;\n\n\t\/\/ set example to right namespace only\n\tec->indices.erase();\n\tec->indices.push_back(right_ns);\n\n\t\/\/ compute r^k * x_r using base learner\n\tbase.predict(ec, k + all->rank);\n\tfloat x_dot_r = ec->partial_prediction;\n\tif (cache_sub_predictions)\n\t data->sub_predictions[2*k] = x_dot_r;\n\n\t\/\/ accumulate prediction\n\tprediction += (x_dot_l * x_dot_r);\n }\n }\n }\n \/\/ restore namespace indices and label\n copy_array(ec->indices, data->indices);\n\n \/\/ finalize prediction\n ec->partial_prediction = prediction;\n ec->final_prediction = GD::finalize_prediction(*(data->all), ec->partial_prediction);\n}\n\nvoid learn(mf* data, learner& base, example* ec) {\n vw* all = data->all;\n\n \/\/ predict with current weights\n predict(data, base, ec);\n\n \/\/ update linear weights\n base.update(ec);\n\n \/\/ store namespace indices\n copy_array(data->indices, ec->indices);\n\n \/\/ update interaction terms\n \/\/ looping over all pairs of non-empty namespaces\n for (vector::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {\n\n int left_ns = (int) (*i)[0];\n int right_ns = (int) (*i)[1];\n\n if (ec->atomics[left_ns].size() > 0 && ec->atomics[right_ns].size() > 0) {\n\n \/\/ set example to left namespace only\n ec->indices.erase();\n ec->indices.push_back(left_ns);\n\n \/\/ store feature values in left namespace\n copy_array(data->temp_features, ec->atomics[left_ns]);\n\n for (size_t k = 1; k <= all->rank; k++) {\n\n\t\/\/ multiply features in left namespace by r^k * x_r\n\tfor (feature* f = ec->atomics[left_ns].begin; f != ec->atomics[left_ns].end; f++)\n\t f->x *= data->sub_predictions[2*k];\n\n\t\/\/ update l^k using base learner\n\tbase.update(ec, k);\n\n\t\/\/ restore left namespace features (undoing multiply)\n\tcopy_array(ec->atomics[left_ns], data->temp_features);\n }\n\n\n \/\/ set example to right namespace only\n ec->indices.erase();\n ec->indices.push_back(right_ns);\n\n \/\/ store feature values for right namespace\n copy_array(data->temp_features, ec->atomics[right_ns]);\n\n for (size_t k = 1; k <= all->rank; k++) {\n\n\t\/\/ multiply features in right namespace by l^k * x_l\n\tfor (feature* f = ec->atomics[right_ns].begin; f != ec->atomics[right_ns].end; f++)\n\t f->x *= data->sub_predictions[2*k-1];\n\n\t\/\/ update r^k using base learner\n\tbase.update(ec, k + all->rank);\n\n\t\/\/ restore right namespace features\n\tcopy_array(ec->atomics[right_ns], data->temp_features);\n }\n }\n }\n \/\/ restore namespace indices\n copy_array(ec->indices, data->indices);\n}\n\nvoid finish(mf* o) {\n \/\/ restore global pairs\n o->all->pairs = o->pairs;\n\n \/\/ clean up local v_arrays\n o->indices.delete_v();\n o->sub_predictions.delete_v();\n}\n\n\nlearner* setup(vw& all, po::variables_map& vm) {\n mf* data = new mf;\n\n \/\/ copy global data locally\n data->all = &all;\n data->rank = all.rank;\n\n \/\/ store global pairs in local data structure and clear global pairs\n \/\/ for eventual calls to base learner\n data->pairs = all.pairs;\n all.pairs.clear();\n\n \/\/ initialize weights randomly\n if(!vm.count(\"initial_regressor\"))\n {\n for (size_t j = 0; j < (all.reg.weight_mask + 1) \/ all.reg.stride; j++)\n\tall.reg.weight_vector[j*all.reg.stride] = (float) (0.1 * frand48());\n }\n learner* l = new learner(data, all.l, 2*data->rank+1);\n l->set_learn();\n l->set_predict >();\n l->set_finish();\n return l;\n}\n}\nfaster namespace manipulation\/*\n Copyright (c) by respective owners including Yahoo!, Microsoft, and\n individual contributors. All rights reserved. Released under a BSD (revised)\n license as described in the file LICENSE.\n *\/\n#include \n#include \n#ifdef _WIN32\n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n#include \"parse_example.h\"\n#include \"constant.h\"\n#include \"sparse_dense.h\"\n#include \"gd.h\"\n#include \"cache.h\"\n#include \"simple_label.h\"\n#include \"rand48.h\"\n#include \"vw.h\"\n#include \n#include \"hash.h\"\n#include \n#include \"parse_primitives.h\"\n\nusing namespace std;\n\nusing namespace LEARNER;\n\nnamespace MF {\n\nstruct mf {\n vector pairs;\n\n uint32_t rank;\n\n uint32_t increment;\n\n \/\/ array to cache w*x, (l^k * x_l) and (r^k * x_r)\n \/\/ [ w*(1,x_l,x_r) , l^1*x_l, r^1*x_r, l^2*x_l, r^2*x_2, ... ]\n v_array sub_predictions;\n\n \/\/ array for temp storage of indices\n v_array indices;\n\n \/\/ array for temp storage of features\n v_array temp_features;\n\n vw* all;\n};\n\ntemplate \nvoid predict(mf *data, learner& base, example* ec) {\n vw* all = data->all;\n\n float prediction = 0;\n if (cache_sub_predictions)\n data->sub_predictions.resize(2*all->rank+1, true);\n\n \/\/ predict from linear terms\n base.predict(ec);\n\n \/\/ store linear prediction\n if (cache_sub_predictions)\n data->sub_predictions[0] = ec->partial_prediction;\n prediction += ec->partial_prediction;\n\n \/\/ store namespace indices\n copy_array(data->indices, ec->indices);\n\n \/\/ erase indices\n ec->indices.erase();\n ec->indices.push_back(0);\n\n \/\/ add interaction terms to prediction\n for (vector::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {\n\n int left_ns = (int) (*i)[0];\n int right_ns = (int) (*i)[1];\n\n if (ec->atomics[left_ns].size() > 0 && ec->atomics[right_ns].size() > 0) {\n for (size_t k = 1; k <= all->rank; k++) {\n\n\tec->indices[0] = left_ns;\n\n\t\/\/ compute l^k * x_l using base learner\n\tbase.predict(ec, k);\n\tfloat x_dot_l = ec->partial_prediction;\n\tif (cache_sub_predictions)\n\t data->sub_predictions[2*k-1] = x_dot_l;\n\n\t\/\/ set example to right namespace only\n\tec->indices[0] = right_ns;\n\n\t\/\/ compute r^k * x_r using base learner\n\tbase.predict(ec, k + all->rank);\n\tfloat x_dot_r = ec->partial_prediction;\n\tif (cache_sub_predictions)\n\t data->sub_predictions[2*k] = x_dot_r;\n\n\t\/\/ accumulate prediction\n\tprediction += (x_dot_l * x_dot_r);\n }\n }\n }\n \/\/ restore namespace indices and label\n copy_array(ec->indices, data->indices);\n\n \/\/ finalize prediction\n ec->partial_prediction = prediction;\n ec->final_prediction = GD::finalize_prediction(*(data->all), ec->partial_prediction);\n}\n\nvoid learn(mf* data, learner& base, example* ec) {\n vw* all = data->all;\n\n \/\/ predict with current weights\n predict(data, base, ec);\n\n \/\/ update linear weights\n base.update(ec);\n\n \/\/ store namespace indices\n copy_array(data->indices, ec->indices);\n\n \/\/ erase indices\n ec->indices.erase();\n ec->indices.push_back(0);\n\n \/\/ update interaction terms\n \/\/ looping over all pairs of non-empty namespaces\n for (vector::iterator i = data->pairs.begin(); i != data->pairs.end(); i++) {\n\n int left_ns = (int) (*i)[0];\n int right_ns = (int) (*i)[1];\n\n if (ec->atomics[left_ns].size() > 0 && ec->atomics[right_ns].size() > 0) {\n\n \/\/ set example to left namespace only\n ec->indices[0] = left_ns;\n\n \/\/ store feature values in left namespace\n copy_array(data->temp_features, ec->atomics[left_ns]);\n\n for (size_t k = 1; k <= all->rank; k++) {\n\n\t\/\/ multiply features in left namespace by r^k * x_r\n\tfor (feature* f = ec->atomics[left_ns].begin; f != ec->atomics[left_ns].end; f++)\n\t f->x *= data->sub_predictions[2*k];\n\n\t\/\/ update l^k using base learner\n\tbase.update(ec, k);\n\n\t\/\/ restore left namespace features (undoing multiply)\n\tcopy_array(ec->atomics[left_ns], data->temp_features);\n }\n\n \/\/ set example to right namespace only\n ec->indices[0] = right_ns;\n\n \/\/ store feature values for right namespace\n copy_array(data->temp_features, ec->atomics[right_ns]);\n\n for (size_t k = 1; k <= all->rank; k++) {\n\n\t\/\/ multiply features in right namespace by l^k * x_l\n\tfor (feature* f = ec->atomics[right_ns].begin; f != ec->atomics[right_ns].end; f++)\n\t f->x *= data->sub_predictions[2*k-1];\n\n\t\/\/ update r^k using base learner\n\tbase.update(ec, k + all->rank);\n\n\t\/\/ restore right namespace features\n\tcopy_array(ec->atomics[right_ns], data->temp_features);\n }\n }\n }\n \/\/ restore namespace indices\n copy_array(ec->indices, data->indices);\n}\n\nvoid finish(mf* o) {\n \/\/ restore global pairs\n o->all->pairs = o->pairs;\n\n \/\/ clean up local v_arrays\n o->indices.delete_v();\n o->sub_predictions.delete_v();\n}\n\n\nlearner* setup(vw& all, po::variables_map& vm) {\n mf* data = new mf;\n\n \/\/ copy global data locally\n data->all = &all;\n data->rank = all.rank;\n\n \/\/ store global pairs in local data structure and clear global pairs\n \/\/ for eventual calls to base learner\n data->pairs = all.pairs;\n all.pairs.clear();\n\n \/\/ initialize weights randomly\n if(!vm.count(\"initial_regressor\"))\n {\n for (size_t j = 0; j < (all.reg.weight_mask + 1) \/ all.reg.stride; j++)\n\tall.reg.weight_vector[j*all.reg.stride] = (float) (0.1 * frand48());\n }\n learner* l = new learner(data, all.l, 2*data->rank+1);\n l->set_learn();\n l->set_predict >();\n l->set_finish();\n return l;\n}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"base\/path_service.h\"\n#include \"base\/perftimer.h\"\n#include \"base\/time.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nusing base::TimeDelta;\n\nnamespace {\n\nclass NewTabUIStartupTest : public UITest {\n public:\n NewTabUIStartupTest() {\n show_window_ = true;\n }\n\n void SetUp() {}\n void TearDown() {}\n\n static const int kNumCycles = 5;\n\n void PrintTimings(const char* label, TimeDelta timings[kNumCycles],\n bool important) {\n std::string times;\n for (int i = 0; i < kNumCycles; ++i)\n StringAppendF(×, \"%.2f,\", timings[i].InMillisecondsF());\n PrintResultList(\"new_tab\", \"\", label, times, \"ms\", important);\n }\n\n \/\/ Run the test, by bringing up a browser and timing the new tab startup.\n \/\/ |want_warm| is true if we should output warm-disk timings, false if\n \/\/ we should report cold timings.\n void RunStartupTest(const char* label, bool want_warm, bool important,\n int profile_type) {\n \/\/ Install the location of the test profile file.\n set_template_user_data(UITest::ComputeTypicalUserDataSource(\n profile_type).ToWStringHack());\n\n \/\/ Disable the first run notification because it has an animation which\n \/\/ masks any real performance regressions.\n launch_arguments_.AppendSwitch(switches::kDisableNewTabFirstRun);\n\n TimeDelta timings[kNumCycles];\n for (int i = 0; i < kNumCycles; ++i) {\n UITest::SetUp();\n\n \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n \/\/ first (the first is about:blank).\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ We resize the window so that we hit the normal layout of the NTP and\n \/\/ not the small layout mode.\n#if defined(OS_WIN)\n\/\/ TODO(port): SetBounds returns false when not implemented.\n\/\/ It is OK to comment out the resize since it will still be useful to test the\n\/\/ default size of the window.\n ASSERT_TRUE(window->GetWindow().get()->SetBounds(gfx::Rect(1000, 1000)));\n#endif\n int tab_count = -1;\n ASSERT_TRUE(window->GetTabCount(&tab_count));\n ASSERT_EQ(1, tab_count);\n\n \/\/ Hit ctl-t and wait for the tab to load.\n window->ApplyAccelerator(IDC_NEW_TAB);\n ASSERT_TRUE(window->WaitForTabCountToBecome(2, 5000));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n timings[i] = TimeDelta::FromMilliseconds(load_time);\n\n if (want_warm) {\n \/\/ Bring up a second tab, now that we've already shown one tab.\n window->ApplyAccelerator(IDC_NEW_TAB);\n ASSERT_TRUE(window->WaitForTabCountToBecome(3, 5000));\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n timings[i] = TimeDelta::FromMilliseconds(load_time);\n }\n\n window = NULL;\n UITest::TearDown();\n }\n\n PrintTimings(label, timings, important);\n }\n};\n\n\/\/ TODO(pamg): run these tests with a reference build?\nTEST_F(NewTabUIStartupTest, PerfCold) {\n RunStartupTest(\"tab_cold\", false \/* cold *\/, true \/* important *\/,\n UITest::DEFAULT_THEME);\n}\n\nTEST_F(NewTabUIStartupTest, DISABLED_PerfWarm) {\n RunStartupTest(\"tab_warm\", true \/* warm *\/, false \/* not important *\/,\n UITest::DEFAULT_THEME);\n}\n\nTEST_F(NewTabUIStartupTest, ComplexThemeCold) {\n RunStartupTest(\"tab_complex_theme_cold\", false \/* cold *\/,\n false \/* not important *\/,\n UITest::COMPLEX_THEME);\n}\n\n} \/\/ namespace\nTurn off startup test until I figure out problem.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"base\/path_service.h\"\n#include \"base\/perftimer.h\"\n#include \"base\/time.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nusing base::TimeDelta;\n\nnamespace {\n\nclass NewTabUIStartupTest : public UITest {\n public:\n NewTabUIStartupTest() {\n show_window_ = true;\n }\n\n void SetUp() {}\n void TearDown() {}\n\n static const int kNumCycles = 5;\n\n void PrintTimings(const char* label, TimeDelta timings[kNumCycles],\n bool important) {\n std::string times;\n for (int i = 0; i < kNumCycles; ++i)\n StringAppendF(×, \"%.2f,\", timings[i].InMillisecondsF());\n PrintResultList(\"new_tab\", \"\", label, times, \"ms\", important);\n }\n\n \/\/ Run the test, by bringing up a browser and timing the new tab startup.\n \/\/ |want_warm| is true if we should output warm-disk timings, false if\n \/\/ we should report cold timings.\n void RunStartupTest(const char* label, bool want_warm, bool important,\n int profile_type) {\n \/\/ Install the location of the test profile file.\n set_template_user_data(UITest::ComputeTypicalUserDataSource(\n profile_type).ToWStringHack());\n\n \/\/ Disable the first run notification because it has an animation which\n \/\/ masks any real performance regressions.\n launch_arguments_.AppendSwitch(switches::kDisableNewTabFirstRun);\n\n TimeDelta timings[kNumCycles];\n for (int i = 0; i < kNumCycles; ++i) {\n UITest::SetUp();\n\n \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n \/\/ first (the first is about:blank).\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ We resize the window so that we hit the normal layout of the NTP and\n \/\/ not the small layout mode.\n#if defined(OS_WIN)\n\/\/ TODO(port): SetBounds returns false when not implemented.\n\/\/ It is OK to comment out the resize since it will still be useful to test the\n\/\/ default size of the window.\n ASSERT_TRUE(window->GetWindow().get()->SetBounds(gfx::Rect(1000, 1000)));\n#endif\n int tab_count = -1;\n ASSERT_TRUE(window->GetTabCount(&tab_count));\n ASSERT_EQ(1, tab_count);\n\n \/\/ Hit ctl-t and wait for the tab to load.\n window->ApplyAccelerator(IDC_NEW_TAB);\n ASSERT_TRUE(window->WaitForTabCountToBecome(2, 5000));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n timings[i] = TimeDelta::FromMilliseconds(load_time);\n\n if (want_warm) {\n \/\/ Bring up a second tab, now that we've already shown one tab.\n window->ApplyAccelerator(IDC_NEW_TAB);\n ASSERT_TRUE(window->WaitForTabCountToBecome(3, 5000));\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n timings[i] = TimeDelta::FromMilliseconds(load_time);\n }\n\n window = NULL;\n UITest::TearDown();\n }\n\n PrintTimings(label, timings, important);\n }\n};\n\n\/\/ TODO(pamg): run these tests with a reference build?\nTEST_F(NewTabUIStartupTest, PerfCold) {\n RunStartupTest(\"tab_cold\", false \/* cold *\/, true \/* important *\/,\n UITest::DEFAULT_THEME);\n}\n\nTEST_F(NewTabUIStartupTest, DISABLED_PerfWarm) {\n RunStartupTest(\"tab_warm\", true \/* warm *\/, false \/* not important *\/,\n UITest::DEFAULT_THEME);\n}\n\n\/\/TEST_F(NewTabUIStartupTest, ComplexThemeCold) {\n\/\/ RunStartupTest(\"tab_complex_theme_cold\", false \/* cold *\/,\n\/\/ false \/* not important *\/,\n\/\/ UITest::COMPLEX_THEME);\n\/\/}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/ RUN: cat %s | %cling -Xclang -verify -I%p | FileCheck %s\n\/\/ XFAIL: *\n\n\/\/ Test the ability of including a wrong file see diagnostics and remove the\n\/\/ cached files so that all the changes are going to be seen next time it gets\n\/\/ included.\n\n#include \n#include \nstd::ofstream myfile;\nmyfile.open(\"TmpClassDef.h\");\nmyfile << \"class MyClass{};\\n\"\nmyfile << \"error_here;\";\nmyfile << \"\/\/ expected-error {{C++ requires a type specifier for all declarations}}\\n\"\nmyfile.close();\n#include \"TmpClassDef.h\"\n\nmyfile.open(\"TmpClassDef.h\");\nmyfile << \"class MyClass{ \\n\";\nmyfile << \"public: \\n\";\nmyfile << \" int gimme12(){\\n\";\nmyfile << \" return 12;\\n\"\nmyfile << \" }\\n\"\nmyfile << \"};\\n\";\nmyfile.close();\n#include \"TmpClassDef.h\"\n\nMyClass my;\nmy.gimme12()\n\/\/ CHECK: (int const) 12\nWith our resent patches in clang's cache system we are able to invalidate a cached file. This means that we can mark the test as expected to succeed.\/\/ RUN: cat %s | %cling -Xclang -verify -I%p | FileCheck %s\n\n\/\/ Test the ability of including a wrong file see diagnostics and remove the\n\/\/ cached files so that all the changes are going to be seen next time it gets\n\/\/ included.\n\n#include \n#include \nstd::ofstream myfile;\nmyfile.open(\"TmpClassDef.h\");\nmyfile << \"class MyClass{};\\n\"\nmyfile << \"error_here;\";\nmyfile << \"\/\/ expected-error {{C++ requires a type specifier for all declarations}}\\n\"\nmyfile.close();\n#include \"TmpClassDef.h\"\n\nmyfile.open(\"TmpClassDef.h\");\nmyfile << \"class MyClass{ \\n\";\nmyfile << \"public: \\n\";\nmyfile << \" int gimme12(){\\n\";\nmyfile << \" return 12;\\n\"\nmyfile << \" }\\n\"\nmyfile << \"};\\n\";\nmyfile.close();\n#include \"TmpClassDef.h\"\n\nMyClass my;\nmy.gimme12()\n\/\/ CHECK: (int const) 12\n<|endoftext|>"} {"text":"#include \"density.h\"\n\nnamespace sirius {\n\nDensity::Density(Simulation_context& ctx__)\n : ctx_(ctx__),\n unit_cell_(ctx_.unit_cell()),\n rho_pseudo_core_(nullptr),\n gaunt_coefs_(nullptr),\n high_freq_mixer_(nullptr),\n low_freq_mixer_(nullptr),\n mixer_(nullptr)\n{\n rho_ = new Periodic_function(ctx_, ctx_.lmmax_rho(), 1);\n\n \/* core density of the pseudopotential method *\/\n if (!ctx_.full_potential())\n {\n rho_pseudo_core_ = new Periodic_function(ctx_, 0, false);\n rho_pseudo_core_->zero();\n\n generate_pseudo_core_charge_density();\n }\n\n for (int i = 0; i < ctx_.num_mag_dims(); i++)\n magnetization_[i] = new Periodic_function(ctx_, ctx_.lmmax_rho(), 1);\n \n switch (ctx_.esm_type())\n {\n case full_potential_lapwlo:\n {\n gaunt_coefs_ = new Gaunt_coefficients(ctx_.lmax_apw(), ctx_.lmax_rho(), \n ctx_.lmax_apw(), SHT::gaunt_hybrid);\n break;\n }\n case full_potential_pwlo:\n {\n gaunt_coefs_ = new Gaunt_coefficients(ctx_.lmax_pw(), ctx_.lmax_rho(), \n ctx_.lmax_pw(), SHT::gaunt_hybrid);\n break;\n }\n\n case paw_pseudopotential:\n case ultrasoft_pseudopotential:\n case norm_conserving_pseudopotential:\n {\n break;\n }\n }\n\n l_by_lm_ = Utils::l_by_lm(ctx_.lmax_rho());\n\n if (!ctx_.full_potential())\n {\n lf_gvec_ = std::vector(ctx_.gvec_coarse().num_gvec());\n std::vector weights(ctx_.gvec_coarse().num_gvec() * (1 + ctx_.num_mag_dims()), 1.0);\n\n weights[0] = 0;\n lf_gvec_[0] = 0;\n\n for (int ig = 1; ig < ctx_.gvec_coarse().num_gvec(); ig++)\n {\n auto G = ctx_.gvec_coarse()[ig];\n \/* save index of low-frequency G-vector *\/\n lf_gvec_[ig] = ctx_.gvec().index_by_gvec(G);\n weights[ig] = fourpi * unit_cell_.omega() \/ std::pow(ctx_.gvec_coarse().gvec_len(ig), 2);\n }\n\n \/* find high-frequency G-vectors *\/\n for (int ig = 0; ig < ctx_.gvec().num_gvec(); ig++)\n {\n if (ctx_.gvec().gvec_len(ig) > 2 * ctx_.gk_cutoff()) hf_gvec_.push_back(ig);\n }\n\n if (static_cast(hf_gvec_.size()) != ctx_.gvec().num_gvec() - ctx_.gvec_coarse().num_gvec())\n {\n std::stringstream s;\n s << \"Wrong count of high-frequency G-vectors\" << std::endl\n << \"number of found high-frequency G-vectors: \" << hf_gvec_.size() << std::endl\n << \"expected number of high-frequency G-vectors: \" << ctx_.gvec().num_gvec() - ctx_.gvec_coarse().num_gvec() << std::endl\n << \"G-vector cutoff: \" << ctx_.gk_cutoff();\n TERMINATE(s);\n }\n\n high_freq_mixer_ = new Linear_mixer(hf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().beta_, ctx_.comm());\n\n if (ctx_.mixer_input_section().type_ == \"linear\")\n {\n low_freq_mixer_ = new Linear_mixer(lf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().beta_, ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden1\")\n {\n\n low_freq_mixer_ = new Broyden1(lf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n weights,\n ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden2\")\n {\n low_freq_mixer_ = new Broyden2(lf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n ctx_.mixer_input_section().beta0_,\n ctx_.mixer_input_section().linear_mix_rms_tol_,\n weights,\n ctx_.comm());\n } \n else\n {\n TERMINATE(\"wrong mixer type\");\n }\n }\n\n if (ctx_.full_potential())\n {\n if (ctx_.mixer_input_section().type_ == \"linear\")\n {\n mixer_ = new Linear_mixer(size(),\n ctx_.mixer_input_section().beta_,\n ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden1\")\n {\n std::vector weights;\n mixer_ = new Broyden1(size(),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n weights,\n ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden2\")\n {\n std::vector weights;\n mixer_ = new Broyden2(size(),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n ctx_.mixer_input_section().beta0_,\n ctx_.mixer_input_section().linear_mix_rms_tol_,\n weights,\n ctx_.comm());\n\n }\n else\n {\n TERMINATE(\"wrong mixer type\");\n }\n }\n\n \/* If we have ud and du spin blocks, don't compute one of them (du in this implementation)\n * because density matrix is symmetric. *\/\n int ndm = std::max(ctx_.num_mag_dims(), ctx_.num_spins());\n\n if (ctx_.full_potential()) {\n density_matrix_ = mdarray(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(), \n ndm, unit_cell_.spl_num_atoms().local_size());\n } else {\n density_matrix_ = mdarray(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(), \n ndm, unit_cell_.num_atoms());\n }\n\n \/\/--- Allocate local PAW density arrays ---\n\n for(int ia = 0; ia < unit_cell_.num_atoms(); ia++)\n {\n auto& atom = unit_cell_.atom(ia);\n\n auto& atype = atom.type();\n\n int n_mt_points = atype.num_mt_points();\n\n int rad_func_lmax = atype.indexr().lmax_lo();\n\n int n_rho_lm_comp = Utils::lmmax(rad_func_lmax);\n\n \/\/ allocate\n mdarray ae_atom_density(n_rho_lm_comp, n_mt_points);\n mdarray ps_atom_density(n_rho_lm_comp, n_mt_points);\n\n \/\/ add\n paw_ae_local_density_.push_back(std::move(ae_atom_density));\n paw_ps_local_density_.push_back(std::move(ps_atom_density));\n\n \/\/ magnetization\n mdarray ae_atom_magn(n_rho_lm_comp, n_mt_points, 3);\n mdarray ps_atom_magn(n_rho_lm_comp, n_mt_points, 3);\n\n ae_atom_magn.zero();\n ps_atom_magn.zero();\n\n paw_ae_local_magnetization_.push_back(std::move(ae_atom_magn));\n paw_ps_local_magnetization_.push_back(std::move(ps_atom_magn));\n\n }\n\n}\n\nDensity::~Density()\n{\n delete rho_;\n for (int j = 0; j < ctx_.num_mag_dims(); j++) delete magnetization_[j];\n\n if (rho_pseudo_core_ != nullptr) delete rho_pseudo_core_;\n if (gaunt_coefs_ != nullptr) delete gaunt_coefs_;\n if (low_freq_mixer_ != nullptr) delete low_freq_mixer_;\n if (high_freq_mixer_ != nullptr) delete high_freq_mixer_;\n if (mixer_ != nullptr) delete mixer_;\n}\n\n};\nminor fix#include \"density.h\"\n\nnamespace sirius {\n\nDensity::Density(Simulation_context& ctx__)\n : ctx_(ctx__),\n unit_cell_(ctx_.unit_cell()),\n rho_pseudo_core_(nullptr),\n gaunt_coefs_(nullptr),\n high_freq_mixer_(nullptr),\n low_freq_mixer_(nullptr),\n mixer_(nullptr)\n{\n rho_ = new Periodic_function(ctx_, ctx_.lmmax_rho(), 1);\n\n \/* core density of the pseudopotential method *\/\n if (!ctx_.full_potential())\n {\n rho_pseudo_core_ = new Periodic_function(ctx_, 0, false);\n rho_pseudo_core_->zero();\n\n generate_pseudo_core_charge_density();\n }\n\n for (int i = 0; i < ctx_.num_mag_dims(); i++)\n magnetization_[i] = new Periodic_function(ctx_, ctx_.lmmax_rho(), 1);\n \n switch (ctx_.esm_type())\n {\n case full_potential_lapwlo:\n {\n gaunt_coefs_ = new Gaunt_coefficients(ctx_.lmax_apw(), ctx_.lmax_rho(), \n ctx_.lmax_apw(), SHT::gaunt_hybrid);\n break;\n }\n case full_potential_pwlo:\n {\n gaunt_coefs_ = new Gaunt_coefficients(ctx_.lmax_pw(), ctx_.lmax_rho(), \n ctx_.lmax_pw(), SHT::gaunt_hybrid);\n break;\n }\n\n case paw_pseudopotential:\n case ultrasoft_pseudopotential:\n case norm_conserving_pseudopotential:\n {\n break;\n }\n }\n\n l_by_lm_ = Utils::l_by_lm(ctx_.lmax_rho());\n\n if (!ctx_.full_potential())\n {\n lf_gvec_ = std::vector(ctx_.gvec_coarse().num_gvec());\n std::vector weights(ctx_.gvec_coarse().num_gvec() * (1 + ctx_.num_mag_dims()), 1.0);\n\n weights[0] = 0;\n lf_gvec_[0] = 0;\n\n for (int ig = 1; ig < ctx_.gvec_coarse().num_gvec(); ig++)\n {\n auto G = ctx_.gvec_coarse()[ig];\n \/* save index of low-frequency G-vector *\/\n lf_gvec_[ig] = ctx_.gvec().index_by_gvec(G);\n weights[ig] = fourpi * unit_cell_.omega() \/ std::pow(ctx_.gvec_coarse().gvec_len(ig), 2);\n }\n\n \/* find high-frequency G-vectors *\/\n for (int ig = 0; ig < ctx_.gvec().num_gvec(); ig++)\n {\n if (ctx_.gvec().gvec_len(ig) > 2 * ctx_.gk_cutoff()) hf_gvec_.push_back(ig);\n }\n\n if (static_cast(hf_gvec_.size()) != ctx_.gvec().num_gvec() - ctx_.gvec_coarse().num_gvec())\n {\n std::stringstream s;\n s << \"Wrong count of high-frequency G-vectors\" << std::endl\n << \"number of found high-frequency G-vectors: \" << hf_gvec_.size() << std::endl\n << \"expected number of high-frequency G-vectors: \" << ctx_.gvec().num_gvec() - ctx_.gvec_coarse().num_gvec() << std::endl\n << \"G-vector cutoff: \" << ctx_.gk_cutoff();\n TERMINATE(s);\n }\n\n high_freq_mixer_ = new Linear_mixer(hf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().beta_, ctx_.comm());\n\n if (ctx_.mixer_input_section().type_ == \"linear\")\n {\n low_freq_mixer_ = new Linear_mixer(lf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().beta_, ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden1\")\n {\n\n low_freq_mixer_ = new Broyden1(lf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n weights,\n ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden2\")\n {\n low_freq_mixer_ = new Broyden2(lf_gvec_.size() * (1 + ctx_.num_mag_dims()),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n ctx_.mixer_input_section().beta0_,\n ctx_.mixer_input_section().linear_mix_rms_tol_,\n weights,\n ctx_.comm());\n } \n else\n {\n TERMINATE(\"wrong mixer type\");\n }\n }\n\n if (ctx_.full_potential())\n {\n if (ctx_.mixer_input_section().type_ == \"linear\")\n {\n mixer_ = new Linear_mixer(size(),\n ctx_.mixer_input_section().beta_,\n ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden1\")\n {\n std::vector weights;\n mixer_ = new Broyden1(size(),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n weights,\n ctx_.comm());\n }\n else if (ctx_.mixer_input_section().type_ == \"broyden2\")\n {\n std::vector weights;\n mixer_ = new Broyden2(size(),\n ctx_.mixer_input_section().max_history_,\n ctx_.mixer_input_section().beta_,\n ctx_.mixer_input_section().beta0_,\n ctx_.mixer_input_section().linear_mix_rms_tol_,\n weights,\n ctx_.comm());\n\n }\n else\n {\n TERMINATE(\"wrong mixer type\");\n }\n }\n\n \/* If we have ud and du spin blocks, don't compute one of them (du in this implementation)\n * because density matrix is symmetric. *\/\n int ndm = std::max(ctx_.num_mag_dims(), ctx_.num_spins());\n\n if (ctx_.full_potential()) {\n density_matrix_ = mdarray(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(), \n ndm, unit_cell_.spl_num_atoms().local_size());\n } else {\n density_matrix_ = mdarray(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(), \n ndm, unit_cell_.num_atoms());\n }\n\n \/\/--- Allocate local PAW density arrays ---\n\n for(int ia = 0; ia < unit_cell_.num_atoms(); ia++)\n {\n auto& atom = unit_cell_.atom(ia);\n\n auto& atype = atom.type();\n\n int n_mt_points = atype.num_mt_points();\n\n \/\/ allocate\n mdarray ae_atom_density(ctx_.lmmax_rho(), n_mt_points);\n mdarray ps_atom_density(ctx_.lmmax_rho(), n_mt_points);\n\n \/\/ add\n paw_ae_local_density_.push_back(std::move(ae_atom_density));\n paw_ps_local_density_.push_back(std::move(ps_atom_density));\n\n \/\/ magnetization\n mdarray ae_atom_magn(ctx_.lmmax_rho(), n_mt_points, 3);\n mdarray ps_atom_magn(ctx_.lmmax_rho(), n_mt_points, 3);\n\n ae_atom_magn.zero();\n ps_atom_magn.zero();\n\n paw_ae_local_magnetization_.push_back(std::move(ae_atom_magn));\n paw_ps_local_magnetization_.push_back(std::move(ps_atom_magn));\n\n }\n\n}\n\nDensity::~Density()\n{\n delete rho_;\n for (int j = 0; j < ctx_.num_mag_dims(); j++) delete magnetization_[j];\n\n if (rho_pseudo_core_ != nullptr) delete rho_pseudo_core_;\n if (gaunt_coefs_ != nullptr) delete gaunt_coefs_;\n if (low_freq_mixer_ != nullptr) delete low_freq_mixer_;\n if (high_freq_mixer_ != nullptr) delete high_freq_mixer_;\n if (mixer_ != nullptr) delete mixer_;\n}\n\n};\n<|endoftext|>"} {"text":"\/\/ See LICENSE file for copyright and license details.\n\n#include \n#include \n#include \n#include \n#include \"core\/misc.hpp\"\n#include \"ui\/gl.hpp\"\n\nstatic GLenum getTextureFormat(\n const SDL_Surface* surface, int nOfColors)\n{\n if (nOfColors == 4) {\n \/\/ contains an alpha channel\n if (surface->format->Rmask == 0xff) {\n return GL_RGBA;\n } else {\n return GL_BGRA;\n }\n } else if (nOfColors == 3) {\n \/\/ no alpha channel\n if (surface->format->Rmask == 0xff) {\n return GL_RGB;\n } else {\n return GL_BGR;\n }\n } else {\n die(\"gl.c: loadTexture(): \"\n \"the image is not truecolor..\"\n \" this will probably break\\n\");\n return 0;\n }\n}\n\nstatic void setTextureParameters() {\n glTexParameteri(GL_TEXTURE_2D,\n GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D,\n GL_TEXTURE_WRAP_T, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D,\n GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D,\n GL_TEXTURE_MIN_FILTER,\n GL_LINEAR_MIPMAP_LINEAR);\n glTexParameteri(GL_TEXTURE_2D,\n GL_GENERATE_MIPMAP, GL_TRUE);\n}\n\nstatic bool isPowerOfTwo(int n) {\n return ((n & (n - 1)) == 0);\n}\n\nint loadTexture(const char *filename) {\n GLuint id;\n SDL_Surface* surface = IMG_Load(filename);\n if (!surface) {\n die(\"gl.c: loadTexture(): Can't load file '%s'\\n\",\n filename);\n return 0;\n }\n if (!isPowerOfTwo(surface->w)\n || !isPowerOfTwo(surface->h))\n {\n die(\"ui\/gl.c: loadTexture(): \"\n \"image's height or width is not a power of 2\\n\");\n }\n GLint nOfColors = surface->format->BytesPerPixel;\n GLenum textureFormat = getTextureFormat(surface, nOfColors);\n glGenTextures(1, &id);\n glBindTexture(GL_TEXTURE_2D, id);\n setTextureParameters();\n glTexImage2D(GL_TEXTURE_2D, 0, nOfColors,\n surface->w, surface->h, 0,\n textureFormat, GL_UNSIGNED_BYTE, surface->pixels);\n if (surface) {\n SDL_FreeSurface(surface);\n }\n return static_cast(id);\n}\nSmall fixes in ui\/gl.cpp\/\/ See LICENSE file for copyright and license details.\n\n#include \n#include \n#include \n#include \n#include \"core\/misc.hpp\"\n#include \"ui\/gl.hpp\"\n\nstatic GLenum getTextureFormat(\n const SDL_Surface* surface, int nOfColors)\n{\n if (nOfColors == 4) {\n \/\/ contains an alpha channel\n if (surface->format->Rmask == 0xff) {\n return GL_RGBA;\n } else {\n return GL_BGRA;\n }\n } else if (nOfColors == 3) {\n \/\/ no alpha channel\n if (surface->format->Rmask == 0xff) {\n return GL_RGB;\n } else {\n return GL_BGR;\n }\n } else {\n die(\"gl.c: loadTexture(): \"\n \"the image is not truecolor..\"\n \" this will probably break\\n\");\n return 0;\n }\n}\n\nstatic void setTextureParameters() {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D,\n GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);\n}\n\nstatic bool isPowerOfTwo(int n) {\n return ((n & (n - 1)) == 0);\n}\n\nint loadTexture(const char *filename) {\n SDL_Surface* surface = IMG_Load(filename);\n if (!surface) {\n die(\"gl.c: loadTexture(): Can't load file '%s'\\n\",\n filename);\n }\n if (!isPowerOfTwo(surface->w) || !isPowerOfTwo(surface->h)) {\n die(\"ui\/gl.c: loadTexture(): \"\n \"image's height or width is not a power of 2\\n\");\n }\n GLint nOfColors = surface->format->BytesPerPixel;\n GLenum textureFormat = getTextureFormat(surface, nOfColors);\n GLuint id;\n glGenTextures(1, &id);\n glBindTexture(GL_TEXTURE_2D, id);\n setTextureParameters();\n glTexImage2D(GL_TEXTURE_2D, 0, nOfColors,\n surface->w, surface->h, 0,\n textureFormat, GL_UNSIGNED_BYTE, surface->pixels);\n SDL_FreeSurface(surface);\n return static_cast(id);\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * libparaver-api *\n * API Library for libparaver-kernel *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version: $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n#include \"tracecutter.h\"\n\/\/#include \"ktraceoptions.h\"\n#include \"traceoptions.h\"\n\/\/#include \"ktracecutter.h\"\n#include \"kernelconnection.h\"\n#include \"pcfparser\/ParaverTraceConfig.h\"\nusing namespace libparaver;\n#include \n#include \n#include \"eventlabels.h\"\n\nusing namespace std;\n\nstring TraceCutter::traceToolID = \"cutter\";\nstring TraceCutter::traceToolName = \"Cutter\";\nstring TraceCutter::traceToolExtension = \"chop\";\n\nTraceCutter *TraceCutter::create( KernelConnection *whichKernel,\n char *traceIn,\n char *traceOut,\n TraceOptions *options,\n ProgressController *progress )\n{\n return new TraceCutterProxy( whichKernel, traceIn, traceOut, options, progress );\n}\n\n\nTraceCutterProxy::TraceCutterProxy( const KernelConnection *whichKernel,\n char *traceIn,\n char *traceOut,\n TraceOptions *options,\n ProgressController *progress )\n{\n\/\/ char *pcf_name, *c;\n std::string pcf_name;\n FILE *pcfFile;\n vector< TEventType > typesWithValueZero;\n\n\/* pcf_name = strdup( traceIn );\n c = strrchr( pcf_name, '.' );\n sprintf( c, \".pcf\" );*\/\n\n pcf_name = LocalKernel::composeName( traceIn, string( \"pcf\" ) );\n if(( pcfFile = fopen( pcf_name.c_str(), \"r\" )) != NULL )\n {\n fclose( pcfFile );\n\n ParaverTraceConfig *config = new ParaverTraceConfig( pcf_name );\n EventLabels myEventLabels = EventLabels( *config, set() );\n vector< TEventType > allTypes;\n EventLabels labels;\n labels.getTypes( allTypes );\n map< TEventValue, string > currentEventValues;\n for( vector< TEventType >::iterator it = allTypes.begin(); it != allTypes.end(); ++it )\n {\n if ( labels.getValues( *it, currentEventValues ) )\n {\n if ( currentEventValues.find( TEventValue( 0 )) != currentEventValues.end() )\n {\n typesWithValueZero.push_back( *it );\n }\n currentEventValues.clear();\n }\n }\n\n delete config;\n }\n\n myTraceCutter = whichKernel->newTraceCutter( options, typesWithValueZero );\n myTraceCutter->execute( traceIn, traceOut, progress );\n}\n\n\nTraceCutterProxy::~TraceCutterProxy()\n{\n delete myTraceCutter;\n}\n\n\nvoid TraceCutterProxy::execute( char *trace_in, char *trace_out, ProgressController *progress )\n{\n myTraceCutter->execute( trace_in, trace_out, progress );\n}\n\n\nvoid TraceCutterProxy::set_by_time( bool whichByTime )\n{\n myTraceCutter->set_by_time( whichByTime );\n}\n\n\nvoid TraceCutterProxy::set_min_cutting_time( unsigned long long minCutTime )\n{\n myTraceCutter->set_min_cutting_time( minCutTime );\n}\n\nvoid TraceCutterProxy::set_max_cutting_time( unsigned long long maxCutTime )\n{\n myTraceCutter->set_min_cutting_time( maxCutTime );\n}\n\nvoid TraceCutterProxy::set_minimum_time_percentage( unsigned long long minimumPercentage )\n{\n myTraceCutter->set_minimum_time_percentage( minimumPercentage );\n}\n\nvoid TraceCutterProxy::set_maximum_time_percentage( unsigned long long maximumPercentage )\n{\n myTraceCutter->set_maximum_time_percentage( maximumPercentage );\n}\n\nvoid TraceCutterProxy::set_tasks_list( char *tasksList )\n{\n myTraceCutter->set_tasks_list( tasksList );\n}\n\nvoid TraceCutterProxy::set_original_time( bool originalTime )\n{\n myTraceCutter->set_original_time ( originalTime );\n}\n\nvoid TraceCutterProxy::set_max_trace_size( int traceSize )\n{\n myTraceCutter->set_max_trace_size( traceSize );\n}\n\nvoid TraceCutterProxy::set_break_states( bool breakStates )\n{\n myTraceCutter->set_break_states( breakStates );\n}\n\nvoid TraceCutterProxy::set_remFirstStates( bool remStates )\n{\n myTraceCutter->set_remFirstStates ( remStates );\n}\n\nvoid TraceCutterProxy::set_remLastStates( bool remStates )\n{\n myTraceCutter->set_remLastStates( remStates );\n}\n\nvoid TraceCutterProxy::set_keep_events( bool keepEvents )\n{\n myTraceCutter->set_keep_events( keepEvents );\n}\n\nvoid TraceCutterProxy::setCutterApplicationCaller( std::string caller )\n{\n myTraceCutter->setCutterApplicationCaller( caller );\n}\n\n\n*** empty log message ***\/*****************************************************************************\\\n * ANALYSIS PERFORMANCE TOOLS *\n * libparaver-api *\n * API Library for libparaver-kernel *\n *****************************************************************************\n * ___ This library is free software; you can redistribute it and\/or *\n * \/ __ modify it under the terms of the GNU LGPL as published *\n * \/ \/ _____ by the Free Software Foundation; either version 2.1 *\n * \/ \/ \/ \\ of the License, or (at your option) any later version. *\n * ( ( ( B S C ) *\n * \\ \\ \\_____\/ This library is distributed in hope that it will be *\n * \\ \\__ useful but WITHOUT ANY WARRANTY; without even the *\n * \\___ implied warranty of MERCHANTABILITY or FITNESS FOR A *\n * PARTICULAR PURPOSE. See the GNU LGPL for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with this library; if not, write to the Free Software Foundation, *\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n * The GNU LEsser General Public License is contained in the file COPYING. *\n * --------- *\n * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *\n\\*****************************************************************************\/\n\n\/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\\\n | @file: $HeadURL$\n | @last_commit: $Date$\n | @version: $Revision$\n\\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\/\n\n#include \"tracecutter.h\"\n\/\/#include \"ktraceoptions.h\"\n#include \"traceoptions.h\"\n\/\/#include \"ktracecutter.h\"\n#include \"kernelconnection.h\"\n#include \"pcfparser\/ParaverTraceConfig.h\"\nusing namespace libparaver;\n#include \n#include \n#include \"eventlabels.h\"\n\nusing namespace std;\n\nstring TraceCutter::traceToolID = \"cutter\";\nstring TraceCutter::traceToolName = \"Cutter\";\nstring TraceCutter::traceToolExtension = \"chop\";\n\nTraceCutter *TraceCutter::create( KernelConnection *whichKernel,\n char *traceIn,\n char *traceOut,\n TraceOptions *options,\n ProgressController *progress )\n{\n return new TraceCutterProxy( whichKernel, traceIn, traceOut, options, progress );\n}\n\n\nTraceCutterProxy::TraceCutterProxy( const KernelConnection *whichKernel,\n char *traceIn,\n char *traceOut,\n TraceOptions *options,\n ProgressController *progress )\n{\n\/\/ char *pcf_name, *c;\n std::string pcf_name;\n FILE *pcfFile;\n vector< TEventType > typesWithValueZero;\n struct stat tmpStatBuffer;\n\n\/* pcf_name = strdup( traceIn );\n c = strrchr( pcf_name, '.' );\n sprintf( c, \".pcf\" );*\/\n\n pcf_name = LocalKernel::composeName( traceIn, string( \"pcf\" ) );\n stat( pcf_name.c_str(), &tmpStatBuffer );\n\n if( tmpStatBuffer.st_size > 0 )\n {\n ParaverTraceConfig *config = new ParaverTraceConfig( pcf_name );\n EventLabels myEventLabels = EventLabels( *config, set() );\n vector< TEventType > allTypes;\n EventLabels labels;\n labels.getTypes( allTypes );\n map< TEventValue, string > currentEventValues;\n for( vector< TEventType >::iterator it = allTypes.begin(); it != allTypes.end(); ++it )\n {\n if ( labels.getValues( *it, currentEventValues ) )\n {\n if ( currentEventValues.find( TEventValue( 0 )) != currentEventValues.end() )\n {\n typesWithValueZero.push_back( *it );\n }\n currentEventValues.clear();\n }\n }\n\n delete config;\n }\n\n myTraceCutter = whichKernel->newTraceCutter( options, typesWithValueZero );\n myTraceCutter->execute( traceIn, traceOut, progress );\n}\n\n\nTraceCutterProxy::~TraceCutterProxy()\n{\n delete myTraceCutter;\n}\n\n\nvoid TraceCutterProxy::execute( char *trace_in, char *trace_out, ProgressController *progress )\n{\n myTraceCutter->execute( trace_in, trace_out, progress );\n}\n\n\nvoid TraceCutterProxy::set_by_time( bool whichByTime )\n{\n myTraceCutter->set_by_time( whichByTime );\n}\n\n\nvoid TraceCutterProxy::set_min_cutting_time( unsigned long long minCutTime )\n{\n myTraceCutter->set_min_cutting_time( minCutTime );\n}\n\nvoid TraceCutterProxy::set_max_cutting_time( unsigned long long maxCutTime )\n{\n myTraceCutter->set_min_cutting_time( maxCutTime );\n}\n\nvoid TraceCutterProxy::set_minimum_time_percentage( unsigned long long minimumPercentage )\n{\n myTraceCutter->set_minimum_time_percentage( minimumPercentage );\n}\n\nvoid TraceCutterProxy::set_maximum_time_percentage( unsigned long long maximumPercentage )\n{\n myTraceCutter->set_maximum_time_percentage( maximumPercentage );\n}\n\nvoid TraceCutterProxy::set_tasks_list( char *tasksList )\n{\n myTraceCutter->set_tasks_list( tasksList );\n}\n\nvoid TraceCutterProxy::set_original_time( bool originalTime )\n{\n myTraceCutter->set_original_time ( originalTime );\n}\n\nvoid TraceCutterProxy::set_max_trace_size( int traceSize )\n{\n myTraceCutter->set_max_trace_size( traceSize );\n}\n\nvoid TraceCutterProxy::set_break_states( bool breakStates )\n{\n myTraceCutter->set_break_states( breakStates );\n}\n\nvoid TraceCutterProxy::set_remFirstStates( bool remStates )\n{\n myTraceCutter->set_remFirstStates ( remStates );\n}\n\nvoid TraceCutterProxy::set_remLastStates( bool remStates )\n{\n myTraceCutter->set_remLastStates( remStates );\n}\n\nvoid TraceCutterProxy::set_keep_events( bool keepEvents )\n{\n myTraceCutter->set_keep_events( keepEvents );\n}\n\nvoid TraceCutterProxy::setCutterApplicationCaller( std::string caller )\n{\n myTraceCutter->setCutterApplicationCaller( caller );\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/asar\/archive.h\"\n\n#include \n#include \n\n#include \"atom\/common\/asar\/scoped_temporary_file.h\"\n#include \"base\/files\/file.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/logging.h\"\n#include \"base\/pickle.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/task_scheduler\/post_task.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/values.h\"\n\n#if defined(OS_WIN)\n#include \n#endif\n\nnamespace asar {\n\nnamespace {\n\n#if defined(OS_WIN)\nconst char kSeparators[] = \"\\\\\/\";\n#else\nconst char kSeparators[] = \"\/\";\n#endif\n\nbool GetNodeFromPath(std::string path,\n const base::DictionaryValue* root,\n const base::DictionaryValue** out);\n\n\/\/ Gets the \"files\" from \"dir\".\nbool GetFilesNode(const base::DictionaryValue* root,\n const base::DictionaryValue* dir,\n const base::DictionaryValue** out) {\n \/\/ Test for symbol linked directory.\n std::string link;\n if (dir->GetStringWithoutPathExpansion(\"link\", &link)) {\n const base::DictionaryValue* linked_node = nullptr;\n if (!GetNodeFromPath(link, root, &linked_node))\n return false;\n dir = linked_node;\n }\n\n return dir->GetDictionaryWithoutPathExpansion(\"files\", out);\n}\n\n\/\/ Gets sub-file \"name\" from \"dir\".\nbool GetChildNode(const base::DictionaryValue* root,\n const std::string& name,\n const base::DictionaryValue* dir,\n const base::DictionaryValue** out) {\n if (name == \"\") {\n *out = root;\n return true;\n }\n\n const base::DictionaryValue* files = nullptr;\n return GetFilesNode(root, dir, &files) &&\n files->GetDictionaryWithoutPathExpansion(name, out);\n}\n\n\/\/ Gets the node of \"path\" from \"root\".\nbool GetNodeFromPath(std::string path,\n const base::DictionaryValue* root,\n const base::DictionaryValue** out) {\n if (path == \"\") {\n *out = root;\n return true;\n }\n\n const base::DictionaryValue* dir = root;\n for (size_t delimiter_position = path.find_first_of(kSeparators);\n delimiter_position != std::string::npos;\n delimiter_position = path.find_first_of(kSeparators)) {\n const base::DictionaryValue* child = nullptr;\n if (!GetChildNode(root, path.substr(0, delimiter_position), dir, &child))\n return false;\n\n dir = child;\n path.erase(0, delimiter_position + 1);\n }\n\n return GetChildNode(root, path, dir, out);\n}\n\nbool FillFileInfoWithNode(Archive::FileInfo* info,\n uint32_t header_size,\n const base::DictionaryValue* node) {\n int size;\n if (!node->GetInteger(\"size\", &size))\n return false;\n info->size = static_cast(size);\n\n if (node->GetBoolean(\"unpacked\", &info->unpacked) && info->unpacked)\n return true;\n\n std::string offset;\n if (!node->GetString(\"offset\", &offset))\n return false;\n if (!base::StringToUint64(offset, &info->offset))\n return false;\n info->offset += header_size;\n\n node->GetBoolean(\"executable\", &info->executable);\n\n return true;\n}\n\n} \/\/ namespace\n\nArchive::Archive(const base::FilePath& path)\n : path_(path), file_(base::File::FILE_OK), header_size_(0) {\n {\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n file_.Initialize(path_, base::File::FLAG_OPEN | base::File::FLAG_READ);\n#if defined(OS_WIN)\n fd_ =\n _open_osfhandle(reinterpret_cast(file_.GetPlatformFile()), 0);\n#elif defined(OS_POSIX)\n fd_ = file_.GetPlatformFile();\n#else\n fd_ = -1;\n#endif\n }\n}\n\nArchive::~Archive() {\n#if defined(OS_WIN)\n if (fd_ != -1) {\n _close(fd_);\n \/\/ Don't close the handle since we already closed the fd.\n file_.TakePlatformFile();\n }\n#endif\n base::PostTaskWithTraits(\n FROM_HERE,\n {base::MayBlock(), base::TaskPriority::BACKGROUND,\n base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},\n base::Bind([](base::File file) { file.Close(); }, Passed(&file_)));\n}\n\nbool Archive::Init() {\n if (!file_.IsValid()) {\n if (file_.error_details() != base::File::FILE_ERROR_NOT_FOUND) {\n LOG(WARNING) << \"Opening \" << path_.value()\n << \": \" << base::File::ErrorToString(file_.error_details());\n }\n return false;\n }\n\n std::vector buf;\n int len;\n\n buf.resize(8);\n {\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n len = file_.ReadAtCurrentPos(buf.data(), buf.size());\n }\n if (len != static_cast(buf.size())) {\n PLOG(ERROR) << \"Failed to read header size from \" << path_.value();\n return false;\n }\n\n uint32_t size;\n if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadUInt32(\n &size)) {\n LOG(ERROR) << \"Failed to parse header size from \" << path_.value();\n return false;\n }\n\n buf.resize(size);\n {\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n len = file_.ReadAtCurrentPos(buf.data(), buf.size());\n }\n if (len != static_cast(buf.size())) {\n PLOG(ERROR) << \"Failed to read header from \" << path_.value();\n return false;\n }\n\n std::string header;\n if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadString(\n &header)) {\n LOG(ERROR) << \"Failed to parse header from \" << path_.value();\n return false;\n }\n\n std::string error;\n base::JSONReader reader;\n std::unique_ptr value(reader.ReadToValue(header));\n if (!value || !value->IsType(base::Value::Type::DICTIONARY)) {\n LOG(ERROR) << \"Failed to parse header: \" << error;\n return false;\n }\n\n header_size_ = 8 + size;\n header_.reset(static_cast(value.release()));\n return true;\n}\n\nbool Archive::GetFileInfo(const base::FilePath& path, FileInfo* info) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n std::string link;\n if (node->GetString(\"link\", &link))\n return GetFileInfo(base::FilePath::FromUTF8Unsafe(link), info);\n\n return FillFileInfoWithNode(info, header_size_, node);\n}\n\nbool Archive::Stat(const base::FilePath& path, Stats* stats) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n if (node->HasKey(\"link\")) {\n stats->is_file = false;\n stats->is_link = true;\n return true;\n }\n\n if (node->HasKey(\"files\")) {\n stats->is_file = false;\n stats->is_directory = true;\n return true;\n }\n\n return FillFileInfoWithNode(stats, header_size_, node);\n}\n\nbool Archive::Readdir(const base::FilePath& path,\n std::vector* list) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n const base::DictionaryValue* files;\n if (!GetFilesNode(header_.get(), node, &files))\n return false;\n\n base::DictionaryValue::Iterator iter(*files);\n while (!iter.IsAtEnd()) {\n list->push_back(base::FilePath::FromUTF8Unsafe(iter.key()));\n iter.Advance();\n }\n return true;\n}\n\nbool Archive::Realpath(const base::FilePath& path, base::FilePath* realpath) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n std::string link;\n if (node->GetString(\"link\", &link)) {\n *realpath = base::FilePath::FromUTF8Unsafe(link);\n return true;\n }\n\n *realpath = path;\n return true;\n}\n\nbool Archive::CopyFileOut(const base::FilePath& path, base::FilePath* out) {\n auto it = external_files_.find(path.value());\n if (it != external_files_.end()) {\n *out = it->second->path();\n return true;\n }\n\n FileInfo info;\n if (!GetFileInfo(path, &info))\n return false;\n\n if (info.unpacked) {\n *out = path_.AddExtension(FILE_PATH_LITERAL(\"unpacked\")).Append(path);\n return true;\n }\n\n std::unique_ptr temp_file(new ScopedTemporaryFile);\n base::FilePath::StringType ext = path.Extension();\n if (!temp_file->InitFromFile(&file_, ext, info.offset, info.size))\n return false;\n\n#if defined(OS_POSIX)\n if (info.executable) {\n \/\/ chmod a+x temp_file;\n base::SetPosixFilePermissions(temp_file->path(), 0755);\n }\n#endif\n\n *out = temp_file->path();\n external_files_[path.value()] = std::move(temp_file);\n return true;\n}\n\nint Archive::GetFD() const {\n return fd_;\n}\n\n} \/\/ namespace asar\nRemove unnecessary scope\/\/ Copyright (c) 2014 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/asar\/archive.h\"\n\n#include \n#include \n\n#include \"atom\/common\/asar\/scoped_temporary_file.h\"\n#include \"base\/files\/file.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/logging.h\"\n#include \"base\/pickle.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/task_scheduler\/post_task.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/values.h\"\n\n#if defined(OS_WIN)\n#include \n#endif\n\nnamespace asar {\n\nnamespace {\n\n#if defined(OS_WIN)\nconst char kSeparators[] = \"\\\\\/\";\n#else\nconst char kSeparators[] = \"\/\";\n#endif\n\nbool GetNodeFromPath(std::string path,\n const base::DictionaryValue* root,\n const base::DictionaryValue** out);\n\n\/\/ Gets the \"files\" from \"dir\".\nbool GetFilesNode(const base::DictionaryValue* root,\n const base::DictionaryValue* dir,\n const base::DictionaryValue** out) {\n \/\/ Test for symbol linked directory.\n std::string link;\n if (dir->GetStringWithoutPathExpansion(\"link\", &link)) {\n const base::DictionaryValue* linked_node = nullptr;\n if (!GetNodeFromPath(link, root, &linked_node))\n return false;\n dir = linked_node;\n }\n\n return dir->GetDictionaryWithoutPathExpansion(\"files\", out);\n}\n\n\/\/ Gets sub-file \"name\" from \"dir\".\nbool GetChildNode(const base::DictionaryValue* root,\n const std::string& name,\n const base::DictionaryValue* dir,\n const base::DictionaryValue** out) {\n if (name == \"\") {\n *out = root;\n return true;\n }\n\n const base::DictionaryValue* files = nullptr;\n return GetFilesNode(root, dir, &files) &&\n files->GetDictionaryWithoutPathExpansion(name, out);\n}\n\n\/\/ Gets the node of \"path\" from \"root\".\nbool GetNodeFromPath(std::string path,\n const base::DictionaryValue* root,\n const base::DictionaryValue** out) {\n if (path == \"\") {\n *out = root;\n return true;\n }\n\n const base::DictionaryValue* dir = root;\n for (size_t delimiter_position = path.find_first_of(kSeparators);\n delimiter_position != std::string::npos;\n delimiter_position = path.find_first_of(kSeparators)) {\n const base::DictionaryValue* child = nullptr;\n if (!GetChildNode(root, path.substr(0, delimiter_position), dir, &child))\n return false;\n\n dir = child;\n path.erase(0, delimiter_position + 1);\n }\n\n return GetChildNode(root, path, dir, out);\n}\n\nbool FillFileInfoWithNode(Archive::FileInfo* info,\n uint32_t header_size,\n const base::DictionaryValue* node) {\n int size;\n if (!node->GetInteger(\"size\", &size))\n return false;\n info->size = static_cast(size);\n\n if (node->GetBoolean(\"unpacked\", &info->unpacked) && info->unpacked)\n return true;\n\n std::string offset;\n if (!node->GetString(\"offset\", &offset))\n return false;\n if (!base::StringToUint64(offset, &info->offset))\n return false;\n info->offset += header_size;\n\n node->GetBoolean(\"executable\", &info->executable);\n\n return true;\n}\n\n} \/\/ namespace\n\nArchive::Archive(const base::FilePath& path)\n : path_(path), file_(base::File::FILE_OK), header_size_(0) {\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n file_.Initialize(path_, base::File::FLAG_OPEN | base::File::FLAG_READ);\n#if defined(OS_WIN)\n fd_ =\n _open_osfhandle(reinterpret_cast(file_.GetPlatformFile()), 0);\n#elif defined(OS_POSIX)\n fd_ = file_.GetPlatformFile();\n#else\n fd_ = -1;\n#endif\n}\n\nArchive::~Archive() {\n#if defined(OS_WIN)\n if (fd_ != -1) {\n _close(fd_);\n \/\/ Don't close the handle since we already closed the fd.\n file_.TakePlatformFile();\n }\n#endif\n base::PostTaskWithTraits(\n FROM_HERE,\n {base::MayBlock(), base::TaskPriority::BACKGROUND,\n base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},\n base::Bind([](base::File file) { file.Close(); }, Passed(&file_)));\n}\n\nbool Archive::Init() {\n if (!file_.IsValid()) {\n if (file_.error_details() != base::File::FILE_ERROR_NOT_FOUND) {\n LOG(WARNING) << \"Opening \" << path_.value()\n << \": \" << base::File::ErrorToString(file_.error_details());\n }\n return false;\n }\n\n std::vector buf;\n int len;\n\n buf.resize(8);\n {\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n len = file_.ReadAtCurrentPos(buf.data(), buf.size());\n }\n if (len != static_cast(buf.size())) {\n PLOG(ERROR) << \"Failed to read header size from \" << path_.value();\n return false;\n }\n\n uint32_t size;\n if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadUInt32(\n &size)) {\n LOG(ERROR) << \"Failed to parse header size from \" << path_.value();\n return false;\n }\n\n buf.resize(size);\n {\n base::ThreadRestrictions::ScopedAllowIO allow_io;\n len = file_.ReadAtCurrentPos(buf.data(), buf.size());\n }\n if (len != static_cast(buf.size())) {\n PLOG(ERROR) << \"Failed to read header from \" << path_.value();\n return false;\n }\n\n std::string header;\n if (!base::PickleIterator(base::Pickle(buf.data(), buf.size())).ReadString(\n &header)) {\n LOG(ERROR) << \"Failed to parse header from \" << path_.value();\n return false;\n }\n\n std::string error;\n base::JSONReader reader;\n std::unique_ptr value(reader.ReadToValue(header));\n if (!value || !value->IsType(base::Value::Type::DICTIONARY)) {\n LOG(ERROR) << \"Failed to parse header: \" << error;\n return false;\n }\n\n header_size_ = 8 + size;\n header_.reset(static_cast(value.release()));\n return true;\n}\n\nbool Archive::GetFileInfo(const base::FilePath& path, FileInfo* info) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n std::string link;\n if (node->GetString(\"link\", &link))\n return GetFileInfo(base::FilePath::FromUTF8Unsafe(link), info);\n\n return FillFileInfoWithNode(info, header_size_, node);\n}\n\nbool Archive::Stat(const base::FilePath& path, Stats* stats) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n if (node->HasKey(\"link\")) {\n stats->is_file = false;\n stats->is_link = true;\n return true;\n }\n\n if (node->HasKey(\"files\")) {\n stats->is_file = false;\n stats->is_directory = true;\n return true;\n }\n\n return FillFileInfoWithNode(stats, header_size_, node);\n}\n\nbool Archive::Readdir(const base::FilePath& path,\n std::vector* list) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n const base::DictionaryValue* files;\n if (!GetFilesNode(header_.get(), node, &files))\n return false;\n\n base::DictionaryValue::Iterator iter(*files);\n while (!iter.IsAtEnd()) {\n list->push_back(base::FilePath::FromUTF8Unsafe(iter.key()));\n iter.Advance();\n }\n return true;\n}\n\nbool Archive::Realpath(const base::FilePath& path, base::FilePath* realpath) {\n if (!header_)\n return false;\n\n const base::DictionaryValue* node;\n if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))\n return false;\n\n std::string link;\n if (node->GetString(\"link\", &link)) {\n *realpath = base::FilePath::FromUTF8Unsafe(link);\n return true;\n }\n\n *realpath = path;\n return true;\n}\n\nbool Archive::CopyFileOut(const base::FilePath& path, base::FilePath* out) {\n auto it = external_files_.find(path.value());\n if (it != external_files_.end()) {\n *out = it->second->path();\n return true;\n }\n\n FileInfo info;\n if (!GetFileInfo(path, &info))\n return false;\n\n if (info.unpacked) {\n *out = path_.AddExtension(FILE_PATH_LITERAL(\"unpacked\")).Append(path);\n return true;\n }\n\n std::unique_ptr temp_file(new ScopedTemporaryFile);\n base::FilePath::StringType ext = path.Extension();\n if (!temp_file->InitFromFile(&file_, ext, info.offset, info.size))\n return false;\n\n#if defined(OS_POSIX)\n if (info.executable) {\n \/\/ chmod a+x temp_file;\n base::SetPosixFilePermissions(temp_file->path(), 0755);\n }\n#endif\n\n *out = temp_file->path();\n external_files_[path.value()] = std::move(temp_file);\n return true;\n}\n\nint Archive::GetFD() const {\n return fd_;\n}\n\n} \/\/ namespace asar\n<|endoftext|>"} {"text":"\/* cobra\n * FairMessageQueue.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of cobra nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _FAIR_MESSAGE_QUEUE_HPP_\n#define _FAIR_MESSAGE_QUEUE_HPP_\n\n#include \"Time.hpp\"\n\nnamespace CBR {\n\nclass Message;\nclass Server;\nnamespace QueueEnum {\n enum PushResult {\n PushSucceeded,\n PushExceededMaximumSize\n };\n};\ntemplate class Queue {\n std::deque mMessages;\n uint32 mMaxSize;\npublic:\n Queue(uint32 max_size){\n mMaxSize=max_size;\n }\n ~Queue(){}\n\n QueueEnum::PushResult push(const Message &msg){\n if (mMessages.size()>=mMaxSize)\n return QueueEnum::PushExceededMaximumSize;\n mMessages.push_back(msg);\n return QueueEnum::PushSucceeded;\n }\n\n const Message& front() const{\n return mMessages.front();\n }\n Message& front() {\n return mMessages.front();\n }\n Message pop(){\n Message m;\n std::swap(m,mMessages.front());\n mMessages.pop_front();\n return m;\n }\n bool empty() const{\n return mMessages.empty();\n }\n};\n\ntemplate class Weight {\npublic:\n uint32 operator()(const MessageQueue&mq)const {\n return mq.front()->size();\n }\n};\ntemplate > > class FairMessageQueue {\npublic:\n struct ServerQueueInfo {\n ServerQueueInfo():nextFinishTime(0) {\n messageQueue=NULL;\n weight=1.0;\n }\n ServerQueueInfo(Queue* queue, float w)\n : messageQueue(queue), weight(w), nextFinishTime(0) {}\n\n Queue* messageQueue;\n float weight;\n Time nextFinishTime;\n };\n\n\n typedef std::map ServerQueueInfoMap;\n\n typedef Queue MessageQueue;\n FairMessageQueue(uint32 bytes_per_second)\n : mRate(bytes_per_second),\n mTotalWeight(0),\n mCurrentTime(0),\n mCurrentVirtualTime(0),\n mMessageBeingSent(NULL),\n mMessageSendFinishTime(0),\n mServerQueues(),\n bytes_sent(0){}\n\n ~FairMessageQueue(){\n typename ServerQueueInfoMap::iterator it = mServerQueues.begin();\n for(; it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n delete queue_info->messageQueue; \n }\n }\n\n void addQueue(MessageQueue *mq, Key server, float weight){\n assert(mq->empty());\n \n ServerQueueInfo queue_info (mq, weight);\n \n mTotalWeight += weight;\n mServerQueues[server] = queue_info;\n }\n bool removeQueue(Key server) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n bool retval=( where != mServerQueues.end() );\n if (retval) {\n delete where->second.messageQueue;\n mServerQueues.erase(where);\n }\n return retval;\n }\n bool hasQueue(Key server) const{\n return ( mServerQueues.find(server) != mServerQueues.end() );\n }\n\n QueueEnum::PushResult queueMessage(Key dest_server, Message *msg){\n typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server);\n\n assert( qi_it != mServerQueues.end() );\n \n ServerQueueInfo* queue_info = &qi_it->second;\n\n if (queue_info->messageQueue->empty())\n queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight);\n \n return queue_info->messageQueue->push(msg);\n }\n\n \/\/ returns a list of messages which should be delivered immediately\n std::vector tick(const Time& t){\n Duration since_last = t - mCurrentTime;\n mCurrentTime = t;\n \n std::vector msgs;\n \n bool processed_message = true;\n while( processed_message == true ) {\n processed_message = false;\n \n \/\/ If we are currently working on delivering a message, check if it can now be delivered\n if (mMessageBeingSent != NULL) {\n if ( mCurrentTime > mMessageSendFinishTime ) {\n msgs.push_back(mMessageBeingSent);\n mMessageBeingSent = NULL;\n processed_message = true;\n }\n } else {\n \/\/ with no processing, update the last finish time to the current time so we don't use\n \/\/ past time for processing a new message\n mMessageSendFinishTime = mCurrentTime;\n }\n \n \/\/ If no message is currently being processed (or we just finished processing one), check for\n \/\/ another message to process\n if (mMessageBeingSent == NULL) {\n \/\/ Find the non-empty queue with the earliest finish time\n ServerQueueInfo* min_queue_info = NULL;\n for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n if (queue_info->messageQueue->empty()) continue;\n if (min_queue_info == NULL || queue_info->nextFinishTime < min_queue_info->nextFinishTime)\n min_queue_info = queue_info;\n }\n \n \/\/ If we actually have something to deliver, deliver it\n if (min_queue_info) {\n mCurrentVirtualTime = min_queue_info->nextFinishTime;\n mMessageBeingSent = min_queue_info->messageQueue->pop();\n \n uint32 message_size = mMessageBeingSent->size();\n Duration duration_to_finish_send = Duration::milliseconds(message_size \/ (mRate\/1000.f));\n mMessageSendFinishTime = mMessageSendFinishTime + duration_to_finish_send;\n \n \/\/ update the next finish time if there's anything in the queue\n if (!min_queue_info->messageQueue->empty())\n min_queue_info->nextFinishTime = finishTime(WeightFunction()(*min_queue_info->messageQueue), min_queue_info->weight);\n }\n }\n }\n \n if (msgs.size() > 0) {\n for(uint32 k = 0; k < msgs.size(); k++) {\n bytes_sent += msgs[k]->size();\n }\n Duration since_start = mCurrentTime - Time(0);\n printf(\"%d \/ %f = %f bytes per second\\n\", bytes_sent, since_start.seconds(), bytes_sent \/ since_start.seconds());\n }\n \n return msgs;\n }\nprivate:\n \/\/ because I *CAN*\n Time FinnishTime(uint32 size, float weight) const{\n return finishTime(size,weight);\n }\n Time finishTime(uint32 size, float weight) const{\n float queue_frac = weight \/ mTotalWeight;\n Duration transmitTime = Duration::seconds( size \/ (mRate * queue_frac) );\n if (transmitTime == Duration(0)) transmitTime = Duration(1); \/\/ just make sure we take *some* time\n \n return mCurrentVirtualTime + transmitTime; \n }\n\n uint32 mRate;\n uint32 mTotalWeight;\n Time mCurrentTime;\n Time mCurrentVirtualTime;\n Message *mMessageBeingSent;\n Time mMessageSendFinishTime;\n ServerQueueInfoMap mServerQueues;\n\n uint32 bytes_sent;\n}; \/\/ class FairMessageQueue\n\n} \/\/ namespace Cobra\n\n#endif \/\/_FAIR_MESSAGE_QUEUE_HPP_\nGet rid of debugging printf.\/* cobra\n * FairMessageQueue.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of cobra nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _FAIR_MESSAGE_QUEUE_HPP_\n#define _FAIR_MESSAGE_QUEUE_HPP_\n\n#include \"Time.hpp\"\n\nnamespace CBR {\n\nclass Message;\nclass Server;\nnamespace QueueEnum {\n enum PushResult {\n PushSucceeded,\n PushExceededMaximumSize\n };\n};\ntemplate class Queue {\n std::deque mMessages;\n uint32 mMaxSize;\npublic:\n Queue(uint32 max_size){\n mMaxSize=max_size;\n }\n ~Queue(){}\n\n QueueEnum::PushResult push(const Message &msg){\n if (mMessages.size()>=mMaxSize)\n return QueueEnum::PushExceededMaximumSize;\n mMessages.push_back(msg);\n return QueueEnum::PushSucceeded;\n }\n\n const Message& front() const{\n return mMessages.front();\n }\n Message& front() {\n return mMessages.front();\n }\n Message pop(){\n Message m;\n std::swap(m,mMessages.front());\n mMessages.pop_front();\n return m;\n }\n bool empty() const{\n return mMessages.empty();\n }\n};\n\ntemplate class Weight {\npublic:\n uint32 operator()(const MessageQueue&mq)const {\n return mq.front()->size();\n }\n};\ntemplate > > class FairMessageQueue {\npublic:\n struct ServerQueueInfo {\n ServerQueueInfo():nextFinishTime(0) {\n messageQueue=NULL;\n weight=1.0;\n }\n ServerQueueInfo(Queue* queue, float w)\n : messageQueue(queue), weight(w), nextFinishTime(0) {}\n\n Queue* messageQueue;\n float weight;\n Time nextFinishTime;\n };\n\n\n typedef std::map ServerQueueInfoMap;\n\n typedef Queue MessageQueue;\n FairMessageQueue(uint32 bytes_per_second)\n : mRate(bytes_per_second),\n mTotalWeight(0),\n mCurrentTime(0),\n mCurrentVirtualTime(0),\n mMessageBeingSent(NULL),\n mMessageSendFinishTime(0),\n mServerQueues(),\n bytes_sent(0){}\n\n ~FairMessageQueue(){\n typename ServerQueueInfoMap::iterator it = mServerQueues.begin();\n for(; it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n delete queue_info->messageQueue;\n }\n }\n\n void addQueue(MessageQueue *mq, Key server, float weight){\n assert(mq->empty());\n\n ServerQueueInfo queue_info (mq, weight);\n\n mTotalWeight += weight;\n mServerQueues[server] = queue_info;\n }\n bool removeQueue(Key server) {\n typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);\n bool retval=( where != mServerQueues.end() );\n if (retval) {\n delete where->second.messageQueue;\n mServerQueues.erase(where);\n }\n return retval;\n }\n bool hasQueue(Key server) const{\n return ( mServerQueues.find(server) != mServerQueues.end() );\n }\n\n QueueEnum::PushResult queueMessage(Key dest_server, Message *msg){\n typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server);\n\n assert( qi_it != mServerQueues.end() );\n\n ServerQueueInfo* queue_info = &qi_it->second;\n\n if (queue_info->messageQueue->empty())\n queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight);\n\n return queue_info->messageQueue->push(msg);\n }\n\n \/\/ returns a list of messages which should be delivered immediately\n std::vector tick(const Time& t){\n Duration since_last = t - mCurrentTime;\n mCurrentTime = t;\n\n std::vector msgs;\n\n bool processed_message = true;\n while( processed_message == true ) {\n processed_message = false;\n\n \/\/ If we are currently working on delivering a message, check if it can now be delivered\n if (mMessageBeingSent != NULL) {\n if ( mCurrentTime > mMessageSendFinishTime ) {\n msgs.push_back(mMessageBeingSent);\n mMessageBeingSent = NULL;\n processed_message = true;\n }\n } else {\n \/\/ with no processing, update the last finish time to the current time so we don't use\n \/\/ past time for processing a new message\n mMessageSendFinishTime = mCurrentTime;\n }\n\n \/\/ If no message is currently being processed (or we just finished processing one), check for\n \/\/ another message to process\n if (mMessageBeingSent == NULL) {\n \/\/ Find the non-empty queue with the earliest finish time\n ServerQueueInfo* min_queue_info = NULL;\n for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {\n ServerQueueInfo* queue_info = &it->second;\n if (queue_info->messageQueue->empty()) continue;\n if (min_queue_info == NULL || queue_info->nextFinishTime < min_queue_info->nextFinishTime)\n min_queue_info = queue_info;\n }\n\n \/\/ If we actually have something to deliver, deliver it\n if (min_queue_info) {\n mCurrentVirtualTime = min_queue_info->nextFinishTime;\n mMessageBeingSent = min_queue_info->messageQueue->pop();\n\n uint32 message_size = mMessageBeingSent->size();\n Duration duration_to_finish_send = Duration::milliseconds(message_size \/ (mRate\/1000.f));\n mMessageSendFinishTime = mMessageSendFinishTime + duration_to_finish_send;\n\n \/\/ update the next finish time if there's anything in the queue\n if (!min_queue_info->messageQueue->empty())\n min_queue_info->nextFinishTime = finishTime(WeightFunction()(*min_queue_info->messageQueue), min_queue_info->weight);\n }\n }\n }\n\n if (msgs.size() > 0) {\n for(uint32 k = 0; k < msgs.size(); k++) {\n bytes_sent += msgs[k]->size();\n }\n Duration since_start = mCurrentTime - Time(0);\n \/\/printf(\"%d \/ %f = %f bytes per second\\n\", bytes_sent, since_start.seconds(), bytes_sent \/ since_start.seconds());\n }\n\n return msgs;\n }\nprivate:\n \/\/ because I *CAN*\n Time FinnishTime(uint32 size, float weight) const{\n return finishTime(size,weight);\n }\n Time finishTime(uint32 size, float weight) const{\n float queue_frac = weight \/ mTotalWeight;\n Duration transmitTime = Duration::seconds( size \/ (mRate * queue_frac) );\n if (transmitTime == Duration(0)) transmitTime = Duration(1); \/\/ just make sure we take *some* time\n\n return mCurrentVirtualTime + transmitTime;\n }\n\n uint32 mRate;\n uint32 mTotalWeight;\n Time mCurrentTime;\n Time mCurrentVirtualTime;\n Message *mMessageBeingSent;\n Time mMessageSendFinishTime;\n ServerQueueInfoMap mServerQueues;\n\n uint32 bytes_sent;\n}; \/\/ class FairMessageQueue\n\n} \/\/ namespace Cobra\n\n#endif \/\/_FAIR_MESSAGE_QUEUE_HPP_\n<|endoftext|>"} {"text":"\/*\r\nCopyright 2015 Esri\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n\r\nA local copy of the license and additional notices are located with the\r\nsource distribution at:\r\n\r\nhttp:\/\/github.com\/Esri\/lerc\/\r\n\r\nContributors: Thomas Maurer\r\n*\/\r\n\r\n#include \"Defines.h\"\r\n#include \"BitMask.h\"\r\n#include \r\n\r\nUSING_NAMESPACE_LERC\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nBitMask::BitMask(const BitMask& src) : m_pBits(nullptr)\r\n{\r\n SetSize(src.m_nCols, src.m_nRows);\r\n if (m_pBits && src.m_pBits)\r\n memcpy(m_pBits, src.m_pBits, Size());\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nBitMask& BitMask::operator= (const BitMask& src)\r\n{\r\n if (this == &src) return *this;\r\n\r\n SetSize(src.m_nCols, src.m_nRows);\r\n if (m_pBits && src.m_pBits)\r\n memcpy(m_pBits, src.m_pBits, Size());\r\n\r\n return *this;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nvoid BitMask::SetAllValid() const\r\n{\r\n memset(m_pBits, 255, Size());\r\n}\r\n\r\nvoid BitMask::SetAllInvalid() const\r\n{\r\n memset(m_pBits, 0, Size());\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nbool BitMask::SetSize(int nCols, int nRows)\r\n{\r\n if (nCols != m_nCols || nRows != m_nRows)\r\n {\r\n Clear();\r\n m_pBits = new Byte[(nCols * nRows + 7) >> 3];\r\n if (m_pBits)\r\n {\r\n m_nCols = nCols;\r\n m_nRows = nRows;\r\n }\r\n }\r\n return m_pBits != nullptr;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nint BitMask::CountValidBits() const\r\n{\r\n const Byte numBitsHB[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};\r\n const Byte* ptr = m_pBits;\r\n int sum = 0;\r\n int i = Size();\r\n while (i--)\r\n {\r\n sum += numBitsHB[*ptr & 15] + numBitsHB[*ptr >> 4];\r\n ptr++;\r\n }\r\n\r\n \/\/ subtract undefined bits potentially contained in the last byte\r\n for (int k = m_nCols * m_nRows; k < Size() * 8; k++)\r\n if (IsValid(k))\r\n sum--;\r\n\r\n return sum;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nvoid BitMask::Clear()\r\n{\r\n delete[] m_pBits;\r\n m_pBits = nullptr;\r\n m_nCols = 0;\r\n m_nRows = 0;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\ntmaurer3\/harden_bitmask_setsize\/*\r\nCopyright 2015 Esri\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n\r\nA local copy of the license and additional notices are located with the\r\nsource distribution at:\r\n\r\nhttp:\/\/github.com\/Esri\/lerc\/\r\n\r\nContributors: Thomas Maurer\r\n*\/\r\n\r\n#include \"Defines.h\"\r\n#include \"BitMask.h\"\r\n#include \r\n\r\nUSING_NAMESPACE_LERC\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nBitMask::BitMask(const BitMask& src) : m_pBits(nullptr), m_nCols(0), m_nRows(0)\r\n{\r\n SetSize(src.m_nCols, src.m_nRows);\r\n if (m_pBits && src.m_pBits)\r\n memcpy(m_pBits, src.m_pBits, Size());\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nBitMask& BitMask::operator= (const BitMask& src)\r\n{\r\n if (this == &src) return *this;\r\n\r\n SetSize(src.m_nCols, src.m_nRows);\r\n if (m_pBits && src.m_pBits)\r\n memcpy(m_pBits, src.m_pBits, Size());\r\n\r\n return *this;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nvoid BitMask::SetAllValid() const\r\n{\r\n memset(m_pBits, 255, Size());\r\n}\r\n\r\nvoid BitMask::SetAllInvalid() const\r\n{\r\n memset(m_pBits, 0, Size());\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nbool BitMask::SetSize(int nCols, int nRows)\r\n{\r\n if (nCols <= 0 || nRows <= 0)\r\n {\r\n Clear();\r\n return (nCols == 0 && nRows == 0);\r\n }\r\n\r\n if (nCols != m_nCols || nRows != m_nRows)\r\n {\r\n Clear();\r\n\r\n try\r\n {\r\n size_t nPix = (size_t)nCols * (size_t)nRows;\r\n m_pBits = new Byte[(nPix + 7) >> 3];\r\n }\r\n catch (...)\r\n {\r\n return false;\r\n }\r\n\r\n if (!m_pBits)\r\n return false;\r\n\r\n m_nCols = nCols;\r\n m_nRows = nRows;\r\n }\r\n\r\n return m_pBits != nullptr;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nint BitMask::CountValidBits() const\r\n{\r\n const Byte numBitsHB[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};\r\n const Byte* ptr = m_pBits;\r\n int sum = 0;\r\n int i = Size();\r\n while (i--)\r\n {\r\n sum += numBitsHB[*ptr & 15] + numBitsHB[*ptr >> 4];\r\n ptr++;\r\n }\r\n\r\n \/\/ subtract undefined bits potentially contained in the last byte\r\n for (int k = m_nCols * m_nRows; k < Size() * 8; k++)\r\n if (IsValid(k))\r\n sum--;\r\n\r\n return sum;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\nvoid BitMask::Clear()\r\n{\r\n delete[] m_pBits;\r\n m_pBits = nullptr;\r\n m_nCols = 0;\r\n m_nRows = 0;\r\n}\r\n\r\n\/\/ -------------------------------------------------------------------------- ;\r\n\r\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlstandaloneappwizard.h\"\n#include \"qmlstandaloneappwizardpages.h\"\n#include \"qmlstandaloneapp.h\"\n\n#include \"qmlprojectconstants.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace QmlProjectManager {\nnamespace Internal {\n\nclass QmlStandaloneAppWizardDialog : public ProjectExplorer::BaseProjectWizardDialog\n{\n Q_OBJECT\n\npublic:\n explicit QmlStandaloneAppWizardDialog(QmlStandaloneAppWizard::WizardType type, QWidget *parent = 0);\n\nprivate:\n QmlStandaloneAppWizard::WizardType m_type;\n class QmlStandaloneAppWizardSourcesPage *m_qmlSourcesPage;\n class QmlStandaloneAppWizardOptionsPage *m_qmlOptionsPage;\n friend class QmlStandaloneAppWizard;\n};\n\nQmlStandaloneAppWizardDialog::QmlStandaloneAppWizardDialog(QmlStandaloneAppWizard::WizardType type,\n QWidget *parent)\n : ProjectExplorer::BaseProjectWizardDialog(parent)\n , m_type(type)\n{\n setWindowTitle(m_type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"New Standalone QML Project\")\n : tr(\"Standalone QML Project from existing QML Project\"));\n setIntroDescription(m_type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"This wizard generates a Standalone QML application project.\")\n : tr(\"This wizard imports an existing QML application and creates a standalone version of it.\"));\n\n m_qmlSourcesPage = new QmlStandaloneAppWizardSourcesPage;\n m_qmlSourcesPage->setMainQmlFileChooserVisible(m_type == QmlStandaloneAppWizard::ImportQmlFile);\n if (m_type == QmlStandaloneAppWizard::ImportQmlFile) {\n const int qmlSourcesPagePageId = addPage(m_qmlSourcesPage);\n wizardProgress()->item(qmlSourcesPagePageId)->setTitle(tr(\"Qml Sources\"));\n }\n\n m_qmlOptionsPage = new QmlStandaloneAppWizardOptionsPage;\n const int qmlOptionsPagePageId = addPage(m_qmlOptionsPage);\n wizardProgress()->item(qmlOptionsPagePageId)->setTitle(tr(\"Qml App options\"));\n}\n\nclass QmlStandaloneAppWizardPrivate\n{\n QmlStandaloneAppWizard::WizardType type;\n class QmlStandaloneApp *standaloneApp;\n class QmlStandaloneAppWizardDialog *wizardDialog;\n friend class QmlStandaloneAppWizard;\n};\n\nQmlStandaloneAppWizard::QmlStandaloneAppWizard(WizardType type)\n : Core::BaseFileWizard(parameters(type))\n , m_d(new QmlStandaloneAppWizardPrivate)\n{\n m_d->type = type;\n m_d->standaloneApp = new QmlStandaloneApp;\n m_d->wizardDialog = 0;\n}\n\nQmlStandaloneAppWizard::~QmlStandaloneAppWizard()\n{\n delete m_d->standaloneApp;\n}\n\nCore::BaseFileWizardParameters QmlStandaloneAppWizard::parameters(WizardType type)\n{\n Core::BaseFileWizardParameters parameters(ProjectWizard);\n parameters.setIcon(QIcon(QLatin1String(Constants::QML_WIZARD_ICON)));\n parameters.setDisplayName(type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"Qt QML New Standalone Application\")\n : tr(\"Qt QML Imported Standalone Application\"));\n parameters.setId(QLatin1String(type == QmlStandaloneAppWizard::NewQmlFile\n ? \"QA.QML New Standalone Application\"\n : \"QA.QML Imported Standalone Application\"));\n parameters.setDescription(type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"Creates a standalone, mobile-deployable Qt QML application \"\n \"project. A lightweight Qt\/C++ application with a QDeclarativeView \"\n \"and a single QML file will be created.\")\n : tr(\"Creates a standalone, mobile-deployable Qt QML application \"\n \"project. An erxisting QML project will be imported and a lightweight \"\n \"Qt\/C++ application with a QDeclarativeView will be created for it.\"));\n parameters.setCategory(QLatin1String(Constants::QML_WIZARD_CATEGORY));\n parameters.setDisplayCategory(QCoreApplication::translate(Constants::QML_WIZARD_TR_SCOPE,\n Constants::QML_WIZARD_TR_CATEGORY));\n return parameters;\n}\n\nQWizard *QmlStandaloneAppWizard::createWizardDialog(QWidget *parent,\n const QString &defaultPath,\n const WizardPageList &extensionPages) const\n{\n m_d->wizardDialog = new QmlStandaloneAppWizardDialog(m_d->type, parent);\n\n m_d->wizardDialog->setPath(defaultPath);\n m_d->wizardDialog->setProjectName(QmlStandaloneAppWizardDialog::uniqueProjectName(defaultPath));\n m_d->wizardDialog->m_qmlOptionsPage->setSymbianSvgIcon(m_d->standaloneApp->symbianSvgIcon());\n m_d->wizardDialog->m_qmlOptionsPage->setOrientation(m_d->standaloneApp->orientation());\n m_d->wizardDialog->m_qmlOptionsPage->setNetworkEnabled(m_d->standaloneApp->networkEnabled());\n m_d->wizardDialog->m_qmlOptionsPage->setLoadDummyData(m_d->standaloneApp->loadDummyData());\n connect(m_d->wizardDialog, SIGNAL(introPageLeft(QString, QString)), SLOT(useProjectPath(QString, QString)));\n\n foreach (QWizardPage *p, extensionPages)\n BaseFileWizard::applyExtensionPageShortTitle(m_d->wizardDialog, m_d->wizardDialog->addPage(p));\n\n return m_d->wizardDialog;\n}\n\nCore::GeneratedFiles QmlStandaloneAppWizard::generateFiles(const QWizard *w,\n QString *errorMessage) const\n{\n Q_UNUSED(errorMessage)\n\n const QmlStandaloneAppWizardDialog *wizard = qobject_cast(w);\n\n m_d->standaloneApp->setProjectName(wizard->projectName());\n m_d->standaloneApp->setProjectPath(wizard->path());\n m_d->standaloneApp->setSymbianTargetUid(wizard->m_qmlOptionsPage->symbianUid());\n m_d->standaloneApp->setSymbianSvgIcon(wizard->m_qmlOptionsPage->symbianSvgIcon());\n m_d->standaloneApp->setOrientation(wizard->m_qmlOptionsPage->orientation());\n m_d->standaloneApp->setNetworkEnabled(wizard->m_qmlOptionsPage->networkEnabled());\n if (m_d->type == QmlStandaloneAppWizard::ImportQmlFile)\n m_d->standaloneApp->setMainQmlFile(wizard->m_qmlSourcesPage->mainQmlFile());\n\n return m_d->standaloneApp->generateFiles(errorMessage);\n}\n\nbool QmlStandaloneAppWizard::postGenerateFiles(const QWizard *wizard, const Core::GeneratedFiles &l, QString *errorMessage)\n{\n Q_UNUSED(wizard)\n const bool success = ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);\n if (success && m_d->type == QmlStandaloneAppWizard::ImportQmlFile) {\n ProjectExplorer::ProjectExplorerPlugin::instance()->setCurrentFile(0, m_d->standaloneApp->mainQmlFile());\n Core::EditorManager::instance()->openEditor(m_d->standaloneApp->mainQmlFile());\n }\n return success;\n}\n\nvoid QmlStandaloneAppWizard::useProjectPath(const QString &projectName, const QString &projectPath)\n{\n m_d->wizardDialog->m_qmlOptionsPage->setSymbianUid(QmlStandaloneApp::symbianUidForPath(projectPath + projectName));\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmlProjectManager\n\n#include \"qmlstandaloneappwizard.moc\"\nTypo fix.\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmlstandaloneappwizard.h\"\n#include \"qmlstandaloneappwizardpages.h\"\n#include \"qmlstandaloneapp.h\"\n\n#include \"qmlprojectconstants.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace QmlProjectManager {\nnamespace Internal {\n\nclass QmlStandaloneAppWizardDialog : public ProjectExplorer::BaseProjectWizardDialog\n{\n Q_OBJECT\n\npublic:\n explicit QmlStandaloneAppWizardDialog(QmlStandaloneAppWizard::WizardType type, QWidget *parent = 0);\n\nprivate:\n QmlStandaloneAppWizard::WizardType m_type;\n class QmlStandaloneAppWizardSourcesPage *m_qmlSourcesPage;\n class QmlStandaloneAppWizardOptionsPage *m_qmlOptionsPage;\n friend class QmlStandaloneAppWizard;\n};\n\nQmlStandaloneAppWizardDialog::QmlStandaloneAppWizardDialog(QmlStandaloneAppWizard::WizardType type,\n QWidget *parent)\n : ProjectExplorer::BaseProjectWizardDialog(parent)\n , m_type(type)\n{\n setWindowTitle(m_type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"New Standalone QML Project\")\n : tr(\"Standalone QML Project from existing QML Project\"));\n setIntroDescription(m_type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"This wizard generates a Standalone QML application project.\")\n : tr(\"This wizard imports an existing QML application and creates a standalone version of it.\"));\n\n m_qmlSourcesPage = new QmlStandaloneAppWizardSourcesPage;\n m_qmlSourcesPage->setMainQmlFileChooserVisible(m_type == QmlStandaloneAppWizard::ImportQmlFile);\n if (m_type == QmlStandaloneAppWizard::ImportQmlFile) {\n const int qmlSourcesPagePageId = addPage(m_qmlSourcesPage);\n wizardProgress()->item(qmlSourcesPagePageId)->setTitle(tr(\"Qml Sources\"));\n }\n\n m_qmlOptionsPage = new QmlStandaloneAppWizardOptionsPage;\n const int qmlOptionsPagePageId = addPage(m_qmlOptionsPage);\n wizardProgress()->item(qmlOptionsPagePageId)->setTitle(tr(\"Qml App options\"));\n}\n\nclass QmlStandaloneAppWizardPrivate\n{\n QmlStandaloneAppWizard::WizardType type;\n class QmlStandaloneApp *standaloneApp;\n class QmlStandaloneAppWizardDialog *wizardDialog;\n friend class QmlStandaloneAppWizard;\n};\n\nQmlStandaloneAppWizard::QmlStandaloneAppWizard(WizardType type)\n : Core::BaseFileWizard(parameters(type))\n , m_d(new QmlStandaloneAppWizardPrivate)\n{\n m_d->type = type;\n m_d->standaloneApp = new QmlStandaloneApp;\n m_d->wizardDialog = 0;\n}\n\nQmlStandaloneAppWizard::~QmlStandaloneAppWizard()\n{\n delete m_d->standaloneApp;\n}\n\nCore::BaseFileWizardParameters QmlStandaloneAppWizard::parameters(WizardType type)\n{\n Core::BaseFileWizardParameters parameters(ProjectWizard);\n parameters.setIcon(QIcon(QLatin1String(Constants::QML_WIZARD_ICON)));\n parameters.setDisplayName(type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"Qt QML New Standalone Application\")\n : tr(\"Qt QML Imported Standalone Application\"));\n parameters.setId(QLatin1String(type == QmlStandaloneAppWizard::NewQmlFile\n ? \"QA.QML New Standalone Application\"\n : \"QA.QML Imported Standalone Application\"));\n parameters.setDescription(type == QmlStandaloneAppWizard::NewQmlFile\n ? tr(\"Creates a standalone, mobile-deployable Qt QML application \"\n \"project. A lightweight Qt\/C++ application with a QDeclarativeView \"\n \"and a single QML file will be created.\")\n : tr(\"Creates a standalone, mobile-deployable Qt QML application \"\n \"project. An existing QML project will be imported and a lightweight \"\n \"Qt\/C++ application with a QDeclarativeView will be created for it.\"));\n parameters.setCategory(QLatin1String(Constants::QML_WIZARD_CATEGORY));\n parameters.setDisplayCategory(QCoreApplication::translate(Constants::QML_WIZARD_TR_SCOPE,\n Constants::QML_WIZARD_TR_CATEGORY));\n return parameters;\n}\n\nQWizard *QmlStandaloneAppWizard::createWizardDialog(QWidget *parent,\n const QString &defaultPath,\n const WizardPageList &extensionPages) const\n{\n m_d->wizardDialog = new QmlStandaloneAppWizardDialog(m_d->type, parent);\n\n m_d->wizardDialog->setPath(defaultPath);\n m_d->wizardDialog->setProjectName(QmlStandaloneAppWizardDialog::uniqueProjectName(defaultPath));\n m_d->wizardDialog->m_qmlOptionsPage->setSymbianSvgIcon(m_d->standaloneApp->symbianSvgIcon());\n m_d->wizardDialog->m_qmlOptionsPage->setOrientation(m_d->standaloneApp->orientation());\n m_d->wizardDialog->m_qmlOptionsPage->setNetworkEnabled(m_d->standaloneApp->networkEnabled());\n m_d->wizardDialog->m_qmlOptionsPage->setLoadDummyData(m_d->standaloneApp->loadDummyData());\n connect(m_d->wizardDialog, SIGNAL(introPageLeft(QString, QString)), SLOT(useProjectPath(QString, QString)));\n\n foreach (QWizardPage *p, extensionPages)\n BaseFileWizard::applyExtensionPageShortTitle(m_d->wizardDialog, m_d->wizardDialog->addPage(p));\n\n return m_d->wizardDialog;\n}\n\nCore::GeneratedFiles QmlStandaloneAppWizard::generateFiles(const QWizard *w,\n QString *errorMessage) const\n{\n Q_UNUSED(errorMessage)\n\n const QmlStandaloneAppWizardDialog *wizard = qobject_cast(w);\n\n m_d->standaloneApp->setProjectName(wizard->projectName());\n m_d->standaloneApp->setProjectPath(wizard->path());\n m_d->standaloneApp->setSymbianTargetUid(wizard->m_qmlOptionsPage->symbianUid());\n m_d->standaloneApp->setSymbianSvgIcon(wizard->m_qmlOptionsPage->symbianSvgIcon());\n m_d->standaloneApp->setOrientation(wizard->m_qmlOptionsPage->orientation());\n m_d->standaloneApp->setNetworkEnabled(wizard->m_qmlOptionsPage->networkEnabled());\n if (m_d->type == QmlStandaloneAppWizard::ImportQmlFile)\n m_d->standaloneApp->setMainQmlFile(wizard->m_qmlSourcesPage->mainQmlFile());\n\n return m_d->standaloneApp->generateFiles(errorMessage);\n}\n\nbool QmlStandaloneAppWizard::postGenerateFiles(const QWizard *wizard, const Core::GeneratedFiles &l, QString *errorMessage)\n{\n Q_UNUSED(wizard)\n const bool success = ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);\n if (success && m_d->type == QmlStandaloneAppWizard::ImportQmlFile) {\n ProjectExplorer::ProjectExplorerPlugin::instance()->setCurrentFile(0, m_d->standaloneApp->mainQmlFile());\n Core::EditorManager::instance()->openEditor(m_d->standaloneApp->mainQmlFile());\n }\n return success;\n}\n\nvoid QmlStandaloneAppWizard::useProjectPath(const QString &projectName, const QString &projectPath)\n{\n m_d->wizardDialog->m_qmlOptionsPage->setSymbianUid(QmlStandaloneApp::symbianUidForPath(projectPath + projectName));\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmlProjectManager\n\n#include \"qmlstandaloneappwizard.moc\"\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by dotdi on 16.11.16.\n\/\/\n\n#include \n#include \"InteractiveShell.h\"\n#include \"helpers.h\"\n#include \"Config.h\"\n\nnamespace CSAOpt {\n static char *prompt(EditLine *el __attribute__((__unused__))) {\n static char a[] = \">> \";\n\n return a;\n }\n\n InteractiveShell::InteractiveShell(CSAOpt::CSAOptManager &_manager) : manager(_manager) {\n\n };\n\n void InteractiveShell::enter() {\n\n \/* This holds all the state for our line editor *\/\n EditLine *el;\n\n \/* This holds the info for our history *\/\n History *hist;\n\n \/* Temp variables *\/\n int count;\n const char *line;\n HistEvent ev;\n\n \/* Initialize the EditLine state to use our prompt function and\n emacs style editing. *\/\n\n el = el_init(\"csaopt\", stdin, stdout, stderr);\n el_set(el, EL_PROMPT, &prompt);\n el_set(el, EL_EDITOR, \"emacs\");\n\n \/* Initialize the history *\/\n hist = history_init();\n if (hist == 0) {\n fprintf(stderr, \"history could not be initialized\\n\");\n return;\n }\n\n \/* Set the size of the history *\/\n history(hist, &ev, H_SETSIZE, 800);\n history(hist, &ev, H_LOAD, Config::getInteractiveHistoryPath());\n\n \/* This sets up the call back functions for history functionality *\/\n el_set(el, EL_HIST, history, hist);\n\n while (!this->aborted) {\n \/* count is the number of characters read.\n line is a const char* of our command line with the tailing \\n *\/\n line = el_gets(el, &count);\n\n \/* In order to use our history we have to explicitly add commands\n to the history *\/\n if (count > 0) {\n history(hist, &ev, H_ENTER, line);\n\n std::vector args;\n\n std::string token;\n std::istringstream ss(trim(line));\n\n while (std::getline(ss, token, ' ')) {\n args.push_back(trim(token));\n }\n\n this->manager.handleInteractiveCommand(args[0], args);\n }\n }\n\n history(hist, &ev, H_SAVE, Config::getInteractiveHistoryPath());\n\n\n \/* Clean up our memory *\/\n history_end(hist);\n el_end(el);\n }\n\n void InteractiveShell::abort() {\n this->aborted = true;\n }\n}made history file configurable\/\/\n\/\/ Created by dotdi on 16.11.16.\n\/\/\n\n#include \n#include \"InteractiveShell.h\"\n#include \"helpers.h\"\n#include \"Config.h\"\n\nnamespace CSAOpt {\n static char *prompt(EditLine *el __attribute__((__unused__))) {\n static char a[] = \">> \";\n\n return a;\n }\n\n InteractiveShell::InteractiveShell(CSAOpt::CSAOptManager &_manager) : manager(_manager) {\n\n };\n\n void InteractiveShell::enter() {\n\n \/* This holds all the state for our line editor *\/\n EditLine *el;\n\n \/* This holds the info for our history *\/\n History *hist;\n\n \/* Temp variables *\/\n int count;\n const char *line;\n HistEvent ev;\n\n \/* Initialize the EditLine state to use our prompt function and\n emacs style editing. *\/\n\n el = el_init(\"csaopt\", stdin, stdout, stderr);\n el_set(el, EL_PROMPT, &prompt);\n el_set(el, EL_EDITOR, \"emacs\");\n\n \/* Initialize the history *\/\n hist = history_init();\n if (hist == 0) {\n fprintf(stderr, \"history could not be initialized\\n\");\n return;\n }\n\n \/* Set the size of the history *\/\n history(hist, &ev, H_SETSIZE, 800);\n history(hist, &ev, H_LOAD, Config::getInteractiveHistoryPath().c_str());\n\n \/* This sets up the call back functions for history functionality *\/\n el_set(el, EL_HIST, history, hist);\n\n while (!this->aborted) {\n \/* count is the number of characters read.\n line is a const char* of our command line with the tailing \\n *\/\n line = el_gets(el, &count);\n\n \/* In order to use our history we have to explicitly add commands\n to the history *\/\n if (count > 0) {\n history(hist, &ev, H_ENTER, line);\n\n std::vector args;\n\n std::string token;\n std::istringstream ss(trim(line));\n\n while (std::getline(ss, token, ' ')) {\n args.push_back(trim(token));\n }\n\n this->manager.handleInteractiveCommand(args[0], args);\n }\n }\n\n history(hist, &ev, H_SAVE, Config::getInteractiveHistoryPath().c_str());\n\n\n \/* Clean up our memory *\/\n history_end(hist);\n el_end(el);\n }\n\n void InteractiveShell::abort() {\n this->aborted = true;\n }\n}<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n#include \n#include \n\n#include \"voice_engine\/main\/test\/auto_test\/fixtures\/after_streaming_fixture.h\"\n\n#ifdef MAC_IPHONE\n const int kMinimumReasonableDelayEstimateMs = 30;\n#else\n const int kMinimumReasonableDelayEstimateMs = 45;\n#endif \/\/ !MAC_IPHONE\n\nclass VideoSyncTest : public AfterStreamingFixture {\n protected:\n \/\/ This test will verify that delay estimates converge (e.g. the standard\n \/\/ deviation for the last five seconds' estimates is less than 20) without\n \/\/ manual observation. The test runs for 15 seconds, sampling once per second.\n \/\/ All samples are checked so they are greater than |min_estimate|.\n int CollectEstimatesDuring15Seconds(int min_estimate) {\n Sleep(1000);\n\n std::vector all_delay_estimates;\n for (int second = 0; second < 15; second++) {\n int delay_estimate = 0;\n EXPECT_EQ(0, voe_vsync_->GetDelayEstimate(channel_, delay_estimate));\n\n EXPECT_GT(delay_estimate, min_estimate) <<\n \"The delay estimate can not conceivably get lower than \" <<\n min_estimate << \" ms, it's unrealistic.\";\n\n all_delay_estimates.push_back(delay_estimate);\n Sleep(1000);\n }\n\n return ComputeStandardDeviation(\n all_delay_estimates.begin() + 10, all_delay_estimates.end());\n }\n\n void CheckEstimatesConvergeReasonablyWell(int min_estimate) {\n float standard_deviation = CollectEstimatesDuring15Seconds(min_estimate);\n EXPECT_LT(standard_deviation, 20.0f);\n }\n\n \/\/ Computes the standard deviation by first estimating the sample variance\n \/\/ with an unbiased estimator.\n float ComputeStandardDeviation(std::vector::const_iterator start,\n std::vector::const_iterator end) const {\n int num_elements = end - start;\n int mean = std::accumulate(start, end, 0) \/ num_elements;\n assert(num_elements > 1);\n\n float variance = 0;\n for (; start != end; ++start) {\n variance += (*start - mean) * (*start - mean) \/ (num_elements - 1);\n }\n return std::sqrt(variance);\n }\n};\n\nTEST_F(VideoSyncTest, CanGetPlayoutTimestampWhilePlayingWithoutSettingItFirst) {\n unsigned int ignored;\n EXPECT_EQ(0, voe_vsync_->GetPlayoutTimestamp(channel_, ignored));\n}\n\nTEST_F(VideoSyncTest, CannotSetInitTimestampWhilePlaying) {\n EXPECT_EQ(-1, voe_vsync_->SetInitTimestamp(channel_, 12345));\n}\n\nTEST_F(VideoSyncTest, CannotSetInitSequenceNumberWhilePlaying) {\n EXPECT_EQ(-1, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n}\n\nTEST_F(VideoSyncTest, CanSetInitTimestampWhileStopped) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitTimestamp(channel_, 12345));\n}\n\nTEST_F(VideoSyncTest, CanSetInitSequenceNumberWhileStopped) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n}\n\nTEST_F(VideoSyncTest, DelayEstimatesStabilizeDuring15sAndAreNotTooLow) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitTimestamp(channel_, 12345));\n EXPECT_EQ(0, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n EXPECT_EQ(0, voe_base_->StartSend(channel_));\n\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n}\n\nTEST_F(VideoSyncTest, DelayEstimatesStabilizeAfterNetEqMinDelayChanges45s) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitTimestamp(channel_, 12345));\n EXPECT_EQ(0, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n EXPECT_EQ(0, voe_base_->StartSend(channel_));\n\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n EXPECT_EQ(0, voe_vsync_->SetMinimumPlayoutDelay(channel_, 200));\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n EXPECT_EQ(0, voe_vsync_->SetMinimumPlayoutDelay(channel_, 0));\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n}\n\n#if !defined(WEBRTC_ANDROID)\nTEST_F(VideoSyncTest, CanGetPlayoutBufferSize) {\n int ignored;\n EXPECT_EQ(0, voe_vsync_->GetPlayoutBufferSize(ignored));\n}\n#endif \/\/ !ANDROID\nAdjusted the deviation limit since the test seems to fail on the bot.\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n#include \n#include \n\n#include \"voice_engine\/main\/test\/auto_test\/fixtures\/after_streaming_fixture.h\"\n\n#ifdef MAC_IPHONE\n const int kMinimumReasonableDelayEstimateMs = 30;\n#else\n const int kMinimumReasonableDelayEstimateMs = 45;\n#endif \/\/ !MAC_IPHONE\n\nclass VideoSyncTest : public AfterStreamingFixture {\n protected:\n \/\/ This test will verify that delay estimates converge (e.g. the standard\n \/\/ deviation for the last five seconds' estimates is less than 20) without\n \/\/ manual observation. The test runs for 15 seconds, sampling once per second.\n \/\/ All samples are checked so they are greater than |min_estimate|.\n int CollectEstimatesDuring15Seconds(int min_estimate) {\n Sleep(1000);\n\n std::vector all_delay_estimates;\n for (int second = 0; second < 15; second++) {\n int delay_estimate = 0;\n EXPECT_EQ(0, voe_vsync_->GetDelayEstimate(channel_, delay_estimate));\n\n EXPECT_GT(delay_estimate, min_estimate) <<\n \"The delay estimate can not conceivably get lower than \" <<\n min_estimate << \" ms, it's unrealistic.\";\n\n all_delay_estimates.push_back(delay_estimate);\n Sleep(1000);\n }\n\n return ComputeStandardDeviation(\n all_delay_estimates.begin() + 10, all_delay_estimates.end());\n }\n\n void CheckEstimatesConvergeReasonablyWell(int min_estimate) {\n float standard_deviation = CollectEstimatesDuring15Seconds(min_estimate);\n EXPECT_LT(standard_deviation, 30.0f);\n }\n\n \/\/ Computes the standard deviation by first estimating the sample variance\n \/\/ with an unbiased estimator.\n float ComputeStandardDeviation(std::vector::const_iterator start,\n std::vector::const_iterator end) const {\n int num_elements = end - start;\n int mean = std::accumulate(start, end, 0) \/ num_elements;\n assert(num_elements > 1);\n\n float variance = 0;\n for (; start != end; ++start) {\n variance += (*start - mean) * (*start - mean) \/ (num_elements - 1);\n }\n return std::sqrt(variance);\n }\n};\n\nTEST_F(VideoSyncTest, CanGetPlayoutTimestampWhilePlayingWithoutSettingItFirst) {\n unsigned int ignored;\n EXPECT_EQ(0, voe_vsync_->GetPlayoutTimestamp(channel_, ignored));\n}\n\nTEST_F(VideoSyncTest, CannotSetInitTimestampWhilePlaying) {\n EXPECT_EQ(-1, voe_vsync_->SetInitTimestamp(channel_, 12345));\n}\n\nTEST_F(VideoSyncTest, CannotSetInitSequenceNumberWhilePlaying) {\n EXPECT_EQ(-1, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n}\n\nTEST_F(VideoSyncTest, CanSetInitTimestampWhileStopped) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitTimestamp(channel_, 12345));\n}\n\nTEST_F(VideoSyncTest, CanSetInitSequenceNumberWhileStopped) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n}\n\nTEST_F(VideoSyncTest, DelayEstimatesStabilizeDuring15sAndAreNotTooLow) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitTimestamp(channel_, 12345));\n EXPECT_EQ(0, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n EXPECT_EQ(0, voe_base_->StartSend(channel_));\n\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n}\n\nTEST_F(VideoSyncTest, DelayEstimatesStabilizeAfterNetEqMinDelayChanges45s) {\n EXPECT_EQ(0, voe_base_->StopSend(channel_));\n EXPECT_EQ(0, voe_vsync_->SetInitTimestamp(channel_, 12345));\n EXPECT_EQ(0, voe_vsync_->SetInitSequenceNumber(channel_, 123));\n EXPECT_EQ(0, voe_base_->StartSend(channel_));\n\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n EXPECT_EQ(0, voe_vsync_->SetMinimumPlayoutDelay(channel_, 200));\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n EXPECT_EQ(0, voe_vsync_->SetMinimumPlayoutDelay(channel_, 0));\n CheckEstimatesConvergeReasonablyWell(kMinimumReasonableDelayEstimateMs);\n}\n\n#if !defined(WEBRTC_ANDROID)\nTEST_F(VideoSyncTest, CanGetPlayoutBufferSize) {\n int ignored;\n EXPECT_EQ(0, voe_vsync_->GetPlayoutBufferSize(ignored));\n}\n#endif \/\/ !ANDROID\n<|endoftext|>"} {"text":"\/\/\n\/\/ OCCAM\n\/\/\n\/\/ Copyright (c) 2011-2016, SRI International\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of SRI International nor the names of its contributors may\n\/\/ be used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/IR\/User.h\"\n#include \"llvm\/IR\/InstVisitor.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/PassManager.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \"PrevirtualizeInterfaces.h\"\n\n#include \n#include \n#include \n\nusing namespace llvm;\n\nnamespace previrt\n{\n static inline GlobalValue::LinkageTypes\n localizeLinkage(GlobalValue::LinkageTypes l)\n {\n switch (l) {\n \/\/ TODO I'm not sure if all external definitions have an appropriate internal counterpart\n default:\n errs() << \"Got other linkage! \" << l << \"\\n\";\n return l;\n case GlobalValue::ExternalLinkage:\n return GlobalValue::InternalLinkage;\n case GlobalValue::ExternalWeakLinkage:\n return GlobalValue::WeakODRLinkage;\n case GlobalValue::AppendingLinkage:\n return GlobalValue::AppendingLinkage;\n }\n }\n\n \/*\n * Remove all code from the given module that is not necessary to\n * implement the given interface.\n *\/\n bool\n MinimizeComponent(Module& M, ComponentInterface& I)\n {\n bool modified = false;\n int hidden = 0;\n int internalized = 0;\n\n \/*\n errs() << \"\\n\";\n I.dump();\n errs() << \"<\/interface>\\n\";\n *\/\n\n \/\/ Set all functions that are not in the interface to internal linkage only\n const StringMap >::const_iterator end =\n I.calls.end();\n for (Module::iterator f = M.begin(), e = M.end(); f != e; ++f) {\n if (!f->isDeclaration() && f->hasExternalLinkage() &&\n I.calls.find(f->getName()) == end &&\n I.references.find(f->getName()) == I.references.end()) {\n errs() << \"Hiding '\" << f->getName() << \"'\\n\";\n f->setLinkage(GlobalValue::InternalLinkage);\n\thidden++;\n modified = true;\n }\n }\n\n \/\/ Set all initialized global variables that are not referenced in the interface to \"localized linkage\" only\n for (Module::global_iterator i = M.global_begin(), e = M.global_end(); i != e; ++i) {\n if (i->hasExternalLinkage() && i->hasInitializer() &&\n I.references.find(i->getName()) == I.references.end()) {\n errs() << \"internalizing '\" << i->getName() << \"'\\n\";\n i->setLinkage(localizeLinkage(i->getLinkage()));\n\tinternalized++;\n modified = true;\n }\n }\n \/* TODO: We want to do this, but libc has some problems...\n for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e; ++i) {\n if (i->hasExternalLinkage() &&\n I.references.find(i->getName()) == I.references.end() &&\n I.calls.find(i->getName()) == end) {\n errs() << \"internalizing '\" << i->getName() << \"'\\n\";\n i->setLinkage(localizeLinkage(i->getLinkage()));\n modified = true;\n }\n }\n *\/\n\n\n\n \/\/ Perform global dead code elimination\n \/\/ TODO: To what extent should we do this here, versus\n \/\/ doing it elsewhere?\n PassManager cdeMgr;\n PassManager mcMgr;\n cdeMgr.addPass(createGlobalDCEPass());\n \/\/mfMgr.add(createMergeFunctionsPass());\n mcMgr.addPass(createConstantMergePass());\n bool moreToDo = true;\n unsigned int iters = 0;\n while (moreToDo && iters < 10000) {\n moreToDo = false;\n PreservedAnalyses cdePA = cdeMgr.run(M);\n if (cdePA.preserve()) \n\tmoreToDo =true;\n \/\/if (cdeMgr.run(M)) moreToDo = true;\n \/\/ (originally commented) if (mfMgr.run(M)) moreToDo = true;\n PreservedAnalyses mcPA = mcMgr.run(M);\n if (mcPA.preserve())\n\tmoreTodo = true;\n \/\/if (mcMgr.run(M)) moreToDo = true;\n modified = modified || moreToDo;\n ++iters;\n }\n\n if (moreToDo) {\n PreservedAnalyses cdePA = cdeMgr.run(M);\n if (cdePA.preserve()) \n\terrs() << \"GlobalDCE still had more to do\\n\";\n\n \/\/if (mfMgr.run(M)) errs() << \"MergeFunctions still had more to do\\n\";\n\n PreserveAnalyses mcPA = mcMgr.run(M);\n if (mcPA.preserve())\n\terrs() << \"MergeConstants still had more to do\\n\";\n }\n\n if (modified) {\n errs() << \"Progress: hidden = \" << hidden << \" internalized \" << internalized << \"\\n\";\n }\n\n return modified;\n }\n\n static cl::list OccamComponentInput(\n \"Poccam-input\", cl::NotHidden, cl::desc(\n \"specifies the interface to prune with respect to\"));\n class OccamPass : public ModulePass\n {\n public:\n ComponentInterface interface;\n static char ID;\n public:\n OccamPass() :\n ModulePass(ID)\n {\n\n errs() << \"OccamPass()\\n\";\n\n for (cl::list::const_iterator b =\n OccamComponentInput.begin(), e = OccamComponentInput.end(); b\n != e; ++b) {\n errs() << \"Reading file '\" << *b << \"'...\";\n if (interface.readFromFile(*b)) {\n errs() << \"success\\n\";\n } else {\n errs() << \"failed\\n\";\n }\n }\n errs() << \"Done reading.\\n\";\n }\n virtual\n ~OccamPass()\n {\n }\n public:\n virtual bool\n runOnModule(Module& M)\n {\n errs() << \"OccamPass::runOnModule: \" << M.getModuleIdentifier() << \"\\n\";\n return MinimizeComponent(M, this->interface);\n }\n };\n char OccamPass::ID;\n\n static RegisterPass X(\"Poccam\",\n \"hide\/eliminate all non-external dependencies\", false, false);\n\n}\nTravis 3.8 - 9\/\/\n\/\/ OCCAM\n\/\/\n\/\/ Copyright (c) 2011-2016, SRI International\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of SRI International nor the names of its contributors may\n\/\/ be used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/IR\/User.h\"\n#include \"llvm\/IR\/InstVisitor.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/PassManager.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \"PrevirtualizeInterfaces.h\"\n\n#include \n#include \n#include \n\nusing namespace llvm;\n\nnamespace previrt\n{\n static inline GlobalValue::LinkageTypes\n localizeLinkage(GlobalValue::LinkageTypes l)\n {\n switch (l) {\n \/\/ TODO I'm not sure if all external definitions have an appropriate internal counterpart\n default:\n errs() << \"Got other linkage! \" << l << \"\\n\";\n return l;\n case GlobalValue::ExternalLinkage:\n return GlobalValue::InternalLinkage;\n case GlobalValue::ExternalWeakLinkage:\n return GlobalValue::WeakODRLinkage;\n case GlobalValue::AppendingLinkage:\n return GlobalValue::AppendingLinkage;\n }\n }\n\n \/*\n * Remove all code from the given module that is not necessary to\n * implement the given interface.\n *\/\n bool\n MinimizeComponent(Module& M, ComponentInterface& I)\n {\n bool modified = false;\n int hidden = 0;\n int internalized = 0;\n\n \/*\n errs() << \"\\n\";\n I.dump();\n errs() << \"<\/interface>\\n\";\n *\/\n\n \/\/ Set all functions that are not in the interface to internal linkage only\n const StringMap >::const_iterator end =\n I.calls.end();\n for (Module::iterator f = M.begin(), e = M.end(); f != e; ++f) {\n if (!f->isDeclaration() && f->hasExternalLinkage() &&\n I.calls.find(f->getName()) == end &&\n I.references.find(f->getName()) == I.references.end()) {\n errs() << \"Hiding '\" << f->getName() << \"'\\n\";\n f->setLinkage(GlobalValue::InternalLinkage);\n\thidden++;\n modified = true;\n }\n }\n\n \/\/ Set all initialized global variables that are not referenced in the interface to \"localized linkage\" only\n for (Module::global_iterator i = M.global_begin(), e = M.global_end(); i != e; ++i) {\n if (i->hasExternalLinkage() && i->hasInitializer() &&\n I.references.find(i->getName()) == I.references.end()) {\n errs() << \"internalizing '\" << i->getName() << \"'\\n\";\n i->setLinkage(localizeLinkage(i->getLinkage()));\n\tinternalized++;\n modified = true;\n }\n }\n \/* TODO: We want to do this, but libc has some problems...\n for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e; ++i) {\n if (i->hasExternalLinkage() &&\n I.references.find(i->getName()) == I.references.end() &&\n I.calls.find(i->getName()) == end) {\n errs() << \"internalizing '\" << i->getName() << \"'\\n\";\n i->setLinkage(localizeLinkage(i->getLinkage()));\n modified = true;\n }\n }\n *\/\n\n\n\n \/\/ Perform global dead code elimination\n \/\/ TODO: To what extent should we do this here, versus\n \/\/ doing it elsewhere?\n PassManager cdeMgr;\n PassManager mcMgr;\n cdeMgr.addPass(createGlobalDCEPass());\n \/\/mfMgr.add(createMergeFunctionsPass());\n mcMgr.addPass(createConstantMergePass());\n bool moreToDo = true;\n unsigned int iters = 0;\n while (moreToDo && iters < 10000) {\n moreToDo = false;\n PreservedAnalyses cdePA = cdeMgr.run(M);\n if (cdePA.preserve()) \n\tmoreToDo =true;\n \/\/if (cdeMgr.run(M)) moreToDo = true;\n \/\/ (originally commented) if (mfMgr.run(M)) moreToDo = true;\n PreservedAnalyses mcPA = mcMgr.run(M);\n if (mcPA.preserve())\n\tmoreToDo = true;\n \/\/if (mcMgr.run(M)) moreToDo = true;\n modified = modified || moreToDo;\n ++iters;\n }\n\n if (moreToDo) {\n PreservedAnalyses cdePA = cdeMgr.run(M);\n if (cdePA.preserve()) \n\terrs() << \"GlobalDCE still had more to do\\n\";\n\n \/\/if (mfMgr.run(M)) errs() << \"MergeFunctions still had more to do\\n\";\n\n PreserveAnalyses mcPA = mcMgr.run(M);\n if (mcPA.preserve())\n\terrs() << \"MergeConstants still had more to do\\n\";\n }\n\n if (modified) {\n errs() << \"Progress: hidden = \" << hidden << \" internalized \" << internalized << \"\\n\";\n }\n\n return modified;\n }\n\n static cl::list OccamComponentInput(\n \"Poccam-input\", cl::NotHidden, cl::desc(\n \"specifies the interface to prune with respect to\"));\n class OccamPass : public ModulePass\n {\n public:\n ComponentInterface interface;\n static char ID;\n public:\n OccamPass() :\n ModulePass(ID)\n {\n\n errs() << \"OccamPass()\\n\";\n\n for (cl::list::const_iterator b =\n OccamComponentInput.begin(), e = OccamComponentInput.end(); b\n != e; ++b) {\n errs() << \"Reading file '\" << *b << \"'...\";\n if (interface.readFromFile(*b)) {\n errs() << \"success\\n\";\n } else {\n errs() << \"failed\\n\";\n }\n }\n errs() << \"Done reading.\\n\";\n }\n virtual\n ~OccamPass()\n {\n }\n public:\n virtual bool\n runOnModule(Module& M)\n {\n errs() << \"OccamPass::runOnModule: \" << M.getModuleIdentifier() << \"\\n\";\n return MinimizeComponent(M, this->interface);\n }\n };\n char OccamPass::ID;\n\n static RegisterPass X(\"Poccam\",\n \"hide\/eliminate all non-external dependencies\", false, false);\n\n}\n<|endoftext|>"} {"text":"#include \"common\/viditem\/vscviditemcam.h\"\r\n\r\nVSCVidItemCam::VSCVidItemCam(QTreeWidgetItem *parent)\r\n: VSCVidItemInf(parent)\r\n{\r\n\t\r\n}\r\nVSCVidItemCam::~VSCVidItemCam()\r\n{\r\n\t\r\n}add filter support#include \"common\/viditem\/vscviditemcam.h\"\r\n\r\nVSCVidItemCam::VSCVidItemCam(VidCamera cCam, ClientFactory &pFactory, QTreeWidgetItem *parent)\r\n: m_cCam(cCam), VSCVidItemInf(pFactory, parent)\r\n{\r\n\tQIcon icon1;\r\n\ticon1.addFile(QStringLiteral(\":\/device\/resources\/camera.png\"), QSize(), QIcon::Normal, QIcon::Off);\r\n\t\r\n\tsetIcon(0, icon1);\r\n\r\n\tsetText(0, QApplication::translate(\" \", m_cCam.strname().c_str(), 0));\t\r\n\t\/\/setHidden(true);\r\n}\r\nVSCVidItemCam::~VSCVidItemCam()\r\n{\r\n\t\r\n}\r\n\r\nvoid VSCVidItemCam::VidFilter(astring strFilter)\r\n{\r\n\tif (strFilter.size() == 0)\r\n\t{\r\n\t\tsetHidden(false);\r\n\t\treturn;\r\n\t}\r\n\tstd::size_t found = m_cCam.strname().find(strFilter);\r\n\tif (found != std::string::npos)\r\n\t{\r\n\t\tsetHidden(false);\r\n\t}else\r\n\t{\r\n\t\tsetHidden(true);\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"geojson_datasource.hpp\"\n#include \"geojson_featureset.hpp\"\n\n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing mapnik::datasource;\nusing mapnik::parameters;\n\nDATASOURCE_PLUGIN(geojson_datasource)\n\nstruct attr_value_converter : public boost::static_visitor\n{\n mapnik::eAttributeType operator() (mapnik::value_integer \/*val*\/) const\n {\n return mapnik::Integer;\n }\n\n mapnik::eAttributeType operator() (double \/*val*\/) const\n {\n return mapnik::Double;\n }\n\n mapnik::eAttributeType operator() (float \/*val*\/) const\n {\n return mapnik::Double;\n }\n\n mapnik::eAttributeType operator() (bool \/*val*\/) const\n {\n return mapnik::Boolean;\n }\n\n mapnik::eAttributeType operator() (std::string const& \/*val*\/) const\n {\n return mapnik::String;\n }\n\n mapnik::eAttributeType operator() (mapnik::value_unicode_string const& \/*val*\/) const\n {\n return mapnik::String;\n }\n\n mapnik::eAttributeType operator() (mapnik::value_null const& \/*val*\/) const\n {\n return mapnik::String;\n }\n};\n\ngeojson_datasource::geojson_datasource(parameters const& params)\n: datasource(params),\n type_(datasource::Vector),\n desc_(*params.get(\"type\"),\n *params.get(\"encoding\",\"utf-8\")),\n file_(*params.get(\"file\",\"\")),\n extent_(),\n tr_(new mapnik::transcoder(*params.get(\"encoding\",\"utf-8\"))),\n features_(),\n tree_(16,1)\n{\n if (file_.empty()) throw mapnik::datasource_exception(\"GeoJSON Plugin: missing parameter\");\n\n boost::optional base = params.get(\"base\");\n if (base)\n {\n file_ = *base + \"\/\" + file_;\n }\n\n typedef std::istreambuf_iterator base_iterator_type;\n\n#if defined (_WINDOWS)\n std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary);\n#else\n std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary);\n#endif\n if (!is.is_open())\n {\n throw mapnik::datasource_exception(\"GeoJSON Plugin: could not open: '\" + file_ + \"'\");\n }\n\n boost::spirit::multi_pass begin =\n boost::spirit::make_default_multi_pass(base_iterator_type(is));\n\n boost::spirit::multi_pass end =\n boost::spirit::make_default_multi_pass(base_iterator_type());\n\n mapnik::context_ptr ctx = std::make_shared();\n mapnik::json::feature_collection_parser > p(ctx,*tr_);\n bool result = p.parse(begin,end, features_);\n if (!result)\n {\n throw mapnik::datasource_exception(\"geojson_datasource: Failed parse GeoJSON file '\" + file_ + \"'\");\n }\n\n bool first = true;\n std::size_t count=0;\n for (mapnik::feature_ptr f : features_)\n {\n mapnik::box2d const& box = f->envelope();\n if (first)\n {\n extent_ = box;\n first = false;\n mapnik::feature_kv_iterator f_itr = f->begin();\n mapnik::feature_kv_iterator f_end = f->end();\n for ( ;f_itr!=f_end; ++f_itr)\n {\n desc_.add_descriptor(mapnik::attribute_descriptor(boost::get<0>(*f_itr),\n boost::apply_visitor(attr_value_converter(),boost::get<1>(*f_itr).base())));\n }\n }\n else\n {\n extent_.expand_to_include(box);\n }\n tree_.insert(box_type(point_type(box.minx(),box.miny()),point_type(box.maxx(),box.maxy())), count++);\n }\n}\n\ngeojson_datasource::~geojson_datasource() { }\n\nconst char * geojson_datasource::name()\n{\n return \"geojson\";\n}\n\nboost::optional geojson_datasource::get_geometry_type() const\n{\n boost::optional result;\n int multi_type = 0;\n unsigned num_features = features_.size();\n for (unsigned i = 0; i < num_features && i < 5; ++i)\n {\n mapnik::util::to_ds_type(features_[i]->paths(),result);\n if (result)\n {\n int type = static_cast(*result);\n if (multi_type > 0 && multi_type != type)\n {\n result.reset(mapnik::datasource::Collection);\n return result;\n }\n multi_type = type;\n }\n }\n return result;\n}\n\nmapnik::datasource::datasource_t geojson_datasource::type() const\n{\n return type_;\n}\n\nmapnik::box2d geojson_datasource::envelope() const\n{\n return extent_;\n}\n\nmapnik::layer_descriptor geojson_datasource::get_descriptor() const\n{\n return desc_;\n}\n\nmapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const\n{\n \/\/ if the query box intersects our world extent then query for features\n mapnik::box2d const& b = q.get_bbox();\n if (extent_.intersects(b))\n {\n box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy()));\n index_array_ = tree_.find(box);\n return std::make_shared(features_, index_array_.begin(), index_array_.end());\n }\n \/\/ otherwise return an empty featureset pointer\n return mapnik::featureset_ptr();\n}\n\nmapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const\n{\n mapnik::box2d query_bbox(pt, pt);\n query_bbox.pad(tol);\n mapnik::query q(query_bbox);\n std::vector const& desc = desc_.get_descriptors();\n std::vector::const_iterator itr = desc.begin();\n std::vector::const_iterator end = desc.end();\n for ( ;itr!=end;++itr)\n {\n q.add_property_name(itr->get_name());\n }\n return features(q);\n}\n+ avoid copying feature_ptr during r-tree initialisation\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"geojson_datasource.hpp\"\n#include \"geojson_featureset.hpp\"\n\n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing mapnik::datasource;\nusing mapnik::parameters;\n\nDATASOURCE_PLUGIN(geojson_datasource)\n\nstruct attr_value_converter : public boost::static_visitor\n{\n mapnik::eAttributeType operator() (mapnik::value_integer \/*val*\/) const\n {\n return mapnik::Integer;\n }\n\n mapnik::eAttributeType operator() (double \/*val*\/) const\n {\n return mapnik::Double;\n }\n\n mapnik::eAttributeType operator() (float \/*val*\/) const\n {\n return mapnik::Double;\n }\n\n mapnik::eAttributeType operator() (bool \/*val*\/) const\n {\n return mapnik::Boolean;\n }\n\n mapnik::eAttributeType operator() (std::string const& \/*val*\/) const\n {\n return mapnik::String;\n }\n\n mapnik::eAttributeType operator() (mapnik::value_unicode_string const& \/*val*\/) const\n {\n return mapnik::String;\n }\n\n mapnik::eAttributeType operator() (mapnik::value_null const& \/*val*\/) const\n {\n return mapnik::String;\n }\n};\n\ngeojson_datasource::geojson_datasource(parameters const& params)\n: datasource(params),\n type_(datasource::Vector),\n desc_(*params.get(\"type\"),\n *params.get(\"encoding\",\"utf-8\")),\n file_(*params.get(\"file\",\"\")),\n extent_(),\n tr_(new mapnik::transcoder(*params.get(\"encoding\",\"utf-8\"))),\n features_(),\n tree_(16,1)\n{\n if (file_.empty()) throw mapnik::datasource_exception(\"GeoJSON Plugin: missing parameter\");\n\n boost::optional base = params.get(\"base\");\n if (base)\n {\n file_ = *base + \"\/\" + file_;\n }\n\n typedef std::istreambuf_iterator base_iterator_type;\n\n#if defined (_WINDOWS)\n std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary);\n#else\n std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary);\n#endif\n if (!is.is_open())\n {\n throw mapnik::datasource_exception(\"GeoJSON Plugin: could not open: '\" + file_ + \"'\");\n }\n\n boost::spirit::multi_pass begin =\n boost::spirit::make_default_multi_pass(base_iterator_type(is));\n\n boost::spirit::multi_pass end =\n boost::spirit::make_default_multi_pass(base_iterator_type());\n\n mapnik::context_ptr ctx = std::make_shared();\n mapnik::json::feature_collection_parser > p(ctx,*tr_);\n bool result = p.parse(begin,end, features_);\n if (!result)\n {\n throw mapnik::datasource_exception(\"geojson_datasource: Failed parse GeoJSON file '\" + file_ + \"'\");\n }\n\n bool first = true;\n std::size_t count=0;\n for (mapnik::feature_ptr const& f : features_)\n {\n mapnik::box2d const& box = f->envelope();\n if (first)\n {\n extent_ = box;\n first = false;\n mapnik::feature_kv_iterator f_itr = f->begin();\n mapnik::feature_kv_iterator f_end = f->end();\n for ( ;f_itr!=f_end; ++f_itr)\n {\n desc_.add_descriptor(mapnik::attribute_descriptor(boost::get<0>(*f_itr),\n boost::apply_visitor(attr_value_converter(),boost::get<1>(*f_itr).base())));\n }\n }\n else\n {\n extent_.expand_to_include(box);\n }\n tree_.insert(box_type(point_type(box.minx(),box.miny()),point_type(box.maxx(),box.maxy())), count++);\n }\n}\n\ngeojson_datasource::~geojson_datasource() { }\n\nconst char * geojson_datasource::name()\n{\n return \"geojson\";\n}\n\nboost::optional geojson_datasource::get_geometry_type() const\n{\n boost::optional result;\n int multi_type = 0;\n unsigned num_features = features_.size();\n for (unsigned i = 0; i < num_features && i < 5; ++i)\n {\n mapnik::util::to_ds_type(features_[i]->paths(),result);\n if (result)\n {\n int type = static_cast(*result);\n if (multi_type > 0 && multi_type != type)\n {\n result.reset(mapnik::datasource::Collection);\n return result;\n }\n multi_type = type;\n }\n }\n return result;\n}\n\nmapnik::datasource::datasource_t geojson_datasource::type() const\n{\n return type_;\n}\n\nmapnik::box2d geojson_datasource::envelope() const\n{\n return extent_;\n}\n\nmapnik::layer_descriptor geojson_datasource::get_descriptor() const\n{\n return desc_;\n}\n\nmapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const\n{\n \/\/ if the query box intersects our world extent then query for features\n mapnik::box2d const& b = q.get_bbox();\n if (extent_.intersects(b))\n {\n box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy()));\n index_array_ = tree_.find(box);\n return std::make_shared(features_, index_array_.begin(), index_array_.end());\n }\n \/\/ otherwise return an empty featureset pointer\n return mapnik::featureset_ptr();\n}\n\nmapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const\n{\n mapnik::box2d query_bbox(pt, pt);\n query_bbox.pad(tol);\n mapnik::query q(query_bbox);\n std::vector const& desc = desc_.get_descriptors();\n std::vector::const_iterator itr = desc.begin();\n std::vector::const_iterator end = desc.end();\n for ( ;itr!=end;++itr)\n {\n q.add_property_name(itr->get_name());\n }\n return features(q);\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file PrimeGenerator.cpp\n\/\/\/ @brief After a segment has been sieved PrimeGenerator is\n\/\/\/ used to reconstruct primes and prime k-tuplets from\n\/\/\/ 1 bits of the sieve array.\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace primesieve {\n\n\/\/\/ popcount.cpp\nuint64_t popcount(const uint64_t* array, uint64_t size);\n\nconst uint64_t PrimeGenerator::bitmasks_[6][5] =\n{\n { END },\n { 0x06, 0x18, 0xc0, END }, \/\/ Twin primes: b00000110, b00011000, b11000000\n { 0x07, 0x0e, 0x1c, 0x38, END }, \/\/ Prime triplets: b00000111, b00001110, ...\n { 0x1e, END }, \/\/ Prime quadruplets: b00011110\n { 0x1f, 0x3e, END }, \/\/ Prime quintuplets\n { 0x3f, END } \/\/ Prime sextuplets\n};\n\nPrimeGenerator::PrimeGenerator(PrimeSieve& ps, const PreSieve& preSieve) :\n SieveOfEratosthenes(max(7, ps.getStart()),\n ps.getStop(),\n ps.getSieveSize(),\n preSieve),\n ps_(ps),\n counts_(ps_.getCounts())\n{\n if (ps_.isFlag(ps_.COUNT_TWINS, ps_.COUNT_SEXTUPLETS))\n init_kCounts();\n}\n\n\/\/\/ Calculate the number of twins, triplets, ...\n\/\/\/ for each possible byte value\n\/\/\/\nvoid PrimeGenerator::init_kCounts()\n{\n for (uint_t i = 1; i < counts_.size(); i++)\n {\n if (ps_.isCount(i))\n {\n kCounts_[i].resize(256);\n\n for (uint64_t j = 0; j < 256; j++)\n {\n byte_t count = 0;\n for (const uint64_t* b = bitmasks_[i]; *b <= j; b++)\n {\n if ((j & *b) == *b)\n count++;\n }\n kCounts_[i][j] = count;\n }\n }\n }\n}\n\n\/\/\/ Executed after each sieved segment.\n\/\/\/ @see sieveSegment() in SieveOfEratosthenes.cpp\n\/\/\/\nvoid PrimeGenerator::generatePrimes(const byte_t* sieve, uint64_t sieveSize)\n{\n if (ps_.isStore())\n storePrimes(ps_.getStore(), sieve, sieveSize);\n if (ps_.isCount())\n count(sieve, sieveSize);\n if (ps_.isPrint())\n print(sieve, sieveSize);\n if (ps_.isStatus())\n ps_.updateStatus(sieveSize * NUMBERS_PER_BYTE);\n}\n\nvoid PrimeGenerator::storePrimes(Store& store, const byte_t* sieve, uint64_t sieveSize) const\n{\n uint64_t low = getSegmentLow();\n\n for (uint64_t i = 0; i < sieveSize; i += 8)\n {\n uint64_t bits = littleendian_cast(&sieve[i]); \n while (bits)\n store(nextPrime(&bits, low));\n\n low += NUMBERS_PER_BYTE * 8;\n }\n}\n\n\/\/\/ Count the primes and prime k-tuplets\n\/\/\/ in the current segment\n\/\/\/\nvoid PrimeGenerator::count(const byte_t* sieve, uint64_t sieveSize)\n{\n if (ps_.isFlag(ps_.COUNT_PRIMES))\n counts_[0] += popcount((const uint64_t*) sieve, ceilDiv(sieveSize, 8));\n\n \/\/ i = 1 twins, i = 2 triplets, ...\n for (uint_t i = 1; i < counts_.size(); i++)\n {\n if (ps_.isCount(i))\n {\n uint64_t sum = 0;\n\n for (uint64_t j = 0; j < sieveSize; j += 4)\n {\n sum += kCounts_[i][sieve[j+0]];\n sum += kCounts_[i][sieve[j+1]];\n sum += kCounts_[i][sieve[j+2]];\n sum += kCounts_[i][sieve[j+3]];\n }\n\n counts_[i] += sum;\n }\n }\n}\n\n\/\/\/ Print primes and prime k-tuplets to cout.\n\/\/\/ primes <= 5 are handled in processSmallPrimes().\n\/\/\/\nvoid PrimeGenerator::print(const byte_t* sieve, uint64_t sieveSize) const\n{\n if (ps_.isFlag(ps_.PRINT_PRIMES))\n {\n uint64_t low = getSegmentLow();\n ostringstream primes;\n\n for (uint64_t i = 0; i < sieveSize; i += 8)\n {\n uint64_t bits = littleendian_cast(&sieve[i]); \n while (bits)\n primes << nextPrime(&bits, low) << '\\n';\n\n low += NUMBERS_PER_BYTE * 8;\n }\n\n cout << primes.str();\n }\n\n \/\/ print prime k-tuplets\n if (ps_.isFlag(ps_.PRINT_TWINS, ps_.PRINT_SEXTUPLETS))\n {\n uint_t i = 1; \/\/ i = 1 twins, i = 2 triplets, ...\n uint64_t low = getSegmentLow();\n ostringstream kTuplets;\n\n for (; !ps_.isPrint(i); i++);\n for (uint64_t j = 0; j < sieveSize; j++, low += NUMBERS_PER_BYTE)\n {\n for (const uint64_t* bitmask = bitmasks_[i]; *bitmask <= sieve[j]; bitmask++)\n {\n if ((sieve[j] & *bitmask) == *bitmask)\n {\n kTuplets << \"(\";\n uint64_t bits = *bitmask;\n while (bits != 0)\n {\n kTuplets << nextPrime(&bits, low);\n kTuplets << ((bits != 0) ? \", \" : \")\\n\");\n }\n }\n }\n }\n\n cout << kTuplets.str();\n }\n}\n\n} \/\/ namespace\nPrint primes faster\/\/\/\n\/\/\/ @file PrimeGenerator.cpp\n\/\/\/ @brief After a segment has been sieved PrimeGenerator is\n\/\/\/ used to reconstruct primes and prime k-tuplets from\n\/\/\/ 1 bits of the sieve array.\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace primesieve {\n\n\/\/\/ popcount.cpp\nuint64_t popcount(const uint64_t* array, uint64_t size);\n\nconst uint64_t PrimeGenerator::bitmasks_[6][5] =\n{\n { END },\n { 0x06, 0x18, 0xc0, END }, \/\/ Twin primes: b00000110, b00011000, b11000000\n { 0x07, 0x0e, 0x1c, 0x38, END }, \/\/ Prime triplets: b00000111, b00001110, ...\n { 0x1e, END }, \/\/ Prime quadruplets: b00011110\n { 0x1f, 0x3e, END }, \/\/ Prime quintuplets\n { 0x3f, END } \/\/ Prime sextuplets\n};\n\nPrimeGenerator::PrimeGenerator(PrimeSieve& ps, const PreSieve& preSieve) :\n SieveOfEratosthenes(max(7, ps.getStart()),\n ps.getStop(),\n ps.getSieveSize(),\n preSieve),\n ps_(ps),\n counts_(ps_.getCounts())\n{\n if (ps_.isFlag(ps_.COUNT_TWINS, ps_.COUNT_SEXTUPLETS))\n init_kCounts();\n}\n\n\/\/\/ Calculate the number of twins, triplets, ...\n\/\/\/ for each possible byte value\n\/\/\/\nvoid PrimeGenerator::init_kCounts()\n{\n for (uint_t i = 1; i < counts_.size(); i++)\n {\n if (ps_.isCount(i))\n {\n kCounts_[i].resize(256);\n\n for (uint64_t j = 0; j < 256; j++)\n {\n byte_t count = 0;\n for (const uint64_t* b = bitmasks_[i]; *b <= j; b++)\n {\n if ((j & *b) == *b)\n count++;\n }\n kCounts_[i][j] = count;\n }\n }\n }\n}\n\n\/\/\/ Executed after each sieved segment.\n\/\/\/ @see sieveSegment() in SieveOfEratosthenes.cpp\n\/\/\/\nvoid PrimeGenerator::generatePrimes(const byte_t* sieve, uint64_t sieveSize)\n{\n if (ps_.isStore())\n storePrimes(ps_.getStore(), sieve, sieveSize);\n if (ps_.isCount())\n count(sieve, sieveSize);\n if (ps_.isPrint())\n print(sieve, sieveSize);\n if (ps_.isStatus())\n ps_.updateStatus(sieveSize * NUMBERS_PER_BYTE);\n}\n\nvoid PrimeGenerator::storePrimes(Store& store, const byte_t* sieve, uint64_t sieveSize) const\n{\n uint64_t low = getSegmentLow();\n\n for (uint64_t i = 0; i < sieveSize; i += 8)\n {\n uint64_t bits = littleendian_cast(&sieve[i]); \n while (bits)\n store(nextPrime(&bits, low));\n\n low += NUMBERS_PER_BYTE * 8;\n }\n}\n\n\/\/\/ Count the primes and prime k-tuplets\n\/\/\/ in the current segment\n\/\/\/\nvoid PrimeGenerator::count(const byte_t* sieve, uint64_t sieveSize)\n{\n if (ps_.isFlag(ps_.COUNT_PRIMES))\n counts_[0] += popcount((const uint64_t*) sieve, ceilDiv(sieveSize, 8));\n\n \/\/ i = 1 twins, i = 2 triplets, ...\n for (uint_t i = 1; i < counts_.size(); i++)\n {\n if (ps_.isCount(i))\n {\n uint64_t sum = 0;\n\n for (uint64_t j = 0; j < sieveSize; j += 4)\n {\n sum += kCounts_[i][sieve[j+0]];\n sum += kCounts_[i][sieve[j+1]];\n sum += kCounts_[i][sieve[j+2]];\n sum += kCounts_[i][sieve[j+3]];\n }\n\n counts_[i] += sum;\n }\n }\n}\n\n\/\/\/ Print primes and prime k-tuplets to cout.\n\/\/\/ primes <= 5 are handled in processSmallPrimes().\n\/\/\/\nvoid PrimeGenerator::print(const byte_t* sieve, uint64_t sieveSize) const\n{\n if (ps_.isFlag(ps_.PRINT_PRIMES))\n {\n uint64_t i = 0;\n uint64_t low = getSegmentLow();\n\n while (i < sieveSize)\n {\n uint64_t size = min(i + (1 << 16), sieveSize);\n ostringstream primes;\n\n for (; i < size; i += 8)\n {\n uint64_t bits = littleendian_cast(&sieve[i]);\n while (bits)\n primes << nextPrime(&bits, low) << '\\n';\n\n low += NUMBERS_PER_BYTE * 8;\n }\n\n cout << primes.str();\n }\n }\n\n \/\/ print prime k-tuplets\n if (ps_.isFlag(ps_.PRINT_TWINS, ps_.PRINT_SEXTUPLETS))\n {\n uint_t i = 1; \/\/ i = 1 twins, i = 2 triplets, ...\n uint64_t low = getSegmentLow();\n ostringstream kTuplets;\n\n for (; !ps_.isPrint(i); i++);\n for (uint64_t j = 0; j < sieveSize; j++, low += NUMBERS_PER_BYTE)\n {\n for (const uint64_t* bitmask = bitmasks_[i]; *bitmask <= sieve[j]; bitmask++)\n {\n if ((sieve[j] & *bitmask) == *bitmask)\n {\n kTuplets << \"(\";\n uint64_t bits = *bitmask;\n while (bits != 0)\n {\n kTuplets << nextPrime(&bits, low);\n kTuplets << ((bits != 0) ? \", \" : \")\\n\");\n }\n }\n }\n }\n\n cout << kTuplets.str();\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \"pushBrowserApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::setup(){\n \n\tofBackground(0);\n ofSetFrameRate(FRAME_RATE);\n ofSetVerticalSync(VERTICAL_SYNC);\n ofSetLogLevel(LOG_LEVEL);\n\t\n bFullScreen = bUpdateURL = bQRControl = bBrowserLoaded = bUpdateQRCode = bHideCursor = false;\n currentURL = defaultURL = pushURL = QRCurrentURL = QRDefaultURL = QRPushURL = \"\";\n \n loadSettings();\n \n if (bFullScreen){ofSetFullscreen(bFullScreen); windowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();}\n else {ofSetWindowShape(windowWidth, windowHeight); ofSetWindowPosition(30, 50);}\n \n URLReceiver.setup(oscReceivePort);\n \n ofHideCursor();\n}\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::update(){\n\n if ((bBrowserLoaded == false)&&(defaultURL != \"\")){\n browser.setup(windowWidth, windowHeight);\n browser.loadURL(currentURL);\n bBrowserLoaded = true;\n\t\tofxAwesomium::clearSessionCache();\n\t\tofxAwesomium::clearSessionCookies();\n } else {\n \n ofxAwesomium::updateCore();\n browser.update();\n ofSetWindowTitle(browser.getTitle());\n }\n \n while(URLReceiver.hasWaitingMessages()){\n\n ofxOscMessage m;\n URLReceiver.getNextMessage(&m);\n if(m.getAddress() == \"\/pushURL\"){\n pushURL = m.getArgAsString(0);\n bUpdateURL = true;\n }\n\t\tif(m.getAddress() == \"\/pushQRURL\"){\n QRPushURL = m.getArgAsString(0);\n bUpdateQRCode = true;\n }\n }\n\n if ((bBrowserLoaded)&&(bUpdateURL)) {\n\n browser.loadURL(pushURL);\n currentURL = pushURL;\n pushURL = \"\";\n bUpdateURL = false;\n\t\tofxAwesomium::clearSessionCache();\n\t\tofxAwesomium::clearSessionCookies();\n\t}\n \n\tif (bUpdateQRCode) {\n\n\t\tloadQRCode(QRPushURL, QRCurrentSize);\n QRCurrentURL = QRPushURL; QRPushURL = \"\";\n bUpdateQRCode = false;\n\t}\n\n if ((windowWidth != ofGetWindowWidth()) || (windowHeight != ofGetWindowHeight())){\n \n\t\twindowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();\n browser.setup(windowWidth, windowHeight);\n browser.loadURL(currentURL);\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::draw(){\n\n\t\n if(browser.getIsLoading()) {ofSetColor(0); ofDrawBitmapString(\"Loading...\", 10, 15);}\n ofSetColor(255);\n browser.draw(0, 0);\n\n\tif ((bQRControl) && (QRControlCode.isAllocated())){\n\t\tofPushMatrix();\n\t\t\tif (QRCurrentHeight == QR_TOP) ofTranslate(0,(QRCurrentSize\/2) + QRCurrentMargin,0); \n\t\t\telse if (QRCurrentHeight == QR_BOTTOM) ofTranslate(0,ofGetWindowHeight()-(QRCurrentSize\/2)-QRCurrentMargin,0); \n\t\t\telse ofTranslate(0,ofGetWindowHeight()\/2,0);\n\n\t\t\tif ((QRCurrentSide == QR_LEFT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw((QRCurrentSize\/2) + QRCurrentMargin,0);\n\t\t\tif ((QRCurrentSide == QR_RIGHT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw(ofGetWindowWidth()-(QRCurrentSize\/2)-QRCurrentMargin,0);\n\n\t\tofPopMatrix();\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::keyPressed(int key){ browser.keyPressed(key);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::keyReleased(int key){ browser.keyReleased(key);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseMoved(int x, int y ){\n \n if (bHideCursor) ofHideCursor(); else ofShowCursor();\n browser.mouseMoved(x, y);\n}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseDragged(int x, int y, int button){ browser.mouseDragged(x, y, button);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mousePressed(int x, int y, int button){browser.mousePressed(x, y, button);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseReleased(int x, int y, int button){browser.mouseReleased(x, y, button);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseEntered(int x, int y){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseExited(int x, int y){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::windowResized(int w, int h){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::gotMessage(ofMessage msg){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::dragEvent(ofDragInfo dragInfo){}\n\nvoid pushBrowserApp::loadSettings(){\n \n ofxXmlSettings settings;\n settings.loadFile(DEFAULT_SETTINGS);\n windowWidth = origWindowWidth = settings.getValue(\"SETTINGS:WINDOW:WIDTH\", WINDOW_WIDTH_DEFAULT);\n\twindowHeight = origWindowHeight = settings.getValue(\"SETTINGS:WINDOW:HEIGHT\", WINDOW_HEIGHT_DEFAULT);\n string _bFullScreen = ofToLower(settings.getValue(\"SETTINGS:WINDOW:FULLSCREEN\", DEFAULT_FULLSCREEN));\n if (_bFullScreen == \"true\") bFullScreen = true; else bFullScreen = false;\n\tstring _bHideCursor = ofToLower(settings.getValue(\"SETTINGS:WINDOW:HIDE_CURSOR\", DEFAULT_HIDE_CURSOR));\n if (_bHideCursor == \"true\") bHideCursor = true; else bHideCursor = false;\n \n\tcurrentURL = defaultURL = settings.getValue(\"SETTINGS:DEFAULT_URL\", DEFAULT_URL);\n\t\n\tQRCurrentURL = QRDefaultURL = settings.getValue(\"SETTINGS:QR_CONTROL:DEFAULT_QR_URL\", DEFAULT_QR_URL);\n\tstring _bQRControl = ofToLower(settings.getValue(\"SETTINGS:QR_CONTROL:QR_ON\", DEFAULT_QR_ON));\n if (_bQRControl == \"true\") bQRControl = true; else bQRControl = false;\n\tstring _QRSide = ofToLower(settings.getValue(\"SETTINGS:QR_CONTROL:QR_SIDE\", DEFAULT_QR_SIDE));\n if (_QRSide == \"left\") QRCurrentSide = QR_LEFT; if (_QRSide == \"right\") QRCurrentSide = QR_RIGHT; if (_QRSide == \"both\") QRCurrentSide = QR_BOTH;\n\tstring _QRHeight = ofToLower(settings.getValue(\"SETTINGS:QR_CONTROL:QR_HEIGHT\", DEFAULT_QR_HEIGHT));\n if (_QRHeight == \"top\") QRCurrentHeight = QR_TOP; if (_QRHeight == \"middle\") QRCurrentHeight = QR_MIDDLE; if (_QRHeight == \"bottom\") QRCurrentHeight = QR_BOTTOM;\n\tQRCurrentSize = settings.getValue(\"SETTINGS:QR_CONTROL:QR_SIZE\", DEFAULT_QR_SIZE);\n\tQRCurrentMargin = settings.getValue(\"SETTINGS:QR_CONTROL:QR_MARGIN\", DEFAULT_QR_MARGIN);\n\tif (bQRControl) {loadQRCode(QRCurrentURL, QRCurrentSize);}\n\toscReceivePort = ofToInt(settings.getValue(\"SETTINGS:OSC_RECEIVE_PORT\", DEFAULT_OSC_RECEIVE_PORT));\n}\n\nvoid pushBrowserApp::loadQRCode(string url, int size){\n\n\tQRControlCode = QRCodeGenerator.generate(url, size);\n\tQRControlCode.setAnchorPercent(0.5, 0.5);\n}qr code case sensitive#include \"pushBrowserApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::setup(){\n \n\tofBackground(0);\n ofSetFrameRate(FRAME_RATE);\n ofSetVerticalSync(VERTICAL_SYNC);\n ofSetLogLevel(LOG_LEVEL);\n\t\n bFullScreen = bUpdateURL = bQRControl = bBrowserLoaded = bUpdateQRCode = bHideCursor = false;\n currentURL = defaultURL = pushURL = QRCurrentURL = QRDefaultURL = QRPushURL = \"\";\n \n loadSettings();\n \n if (bFullScreen){ofSetFullscreen(bFullScreen); windowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();}\n else {ofSetWindowShape(windowWidth, windowHeight); ofSetWindowPosition(30, 50);}\n \n URLReceiver.setup(oscReceivePort);\n \n ofHideCursor();\n}\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::update(){\n\n if ((bBrowserLoaded == false)&&(defaultURL != \"\")){\n browser.setup(windowWidth, windowHeight);\n browser.loadURL(currentURL);\n bBrowserLoaded = true;\n\t\tofxAwesomium::clearSessionCache();\n\t\tofxAwesomium::clearSessionCookies();\n } else {\n \n ofxAwesomium::updateCore();\n browser.update();\n ofSetWindowTitle(browser.getTitle());\n }\n \n while(URLReceiver.hasWaitingMessages()){\n\n ofxOscMessage m;\n URLReceiver.getNextMessage(&m);\n if(m.getAddress() == \"\/pushURL\"){\n pushURL = m.getArgAsString(0);\n bUpdateURL = true;\n }\n\t\tif(m.getAddress() == \"\/pushQRURL\"){\n QRPushURL = m.getArgAsString(0);\n bUpdateQRCode = true;\n }\n }\n\n if ((bBrowserLoaded)&&(bUpdateURL)) {\n\n browser.loadURL(pushURL);\n currentURL = pushURL;\n pushURL = \"\";\n bUpdateURL = false;\n\t\tofxAwesomium::clearSessionCache();\n\t\tofxAwesomium::clearSessionCookies();\n\t}\n \n\tif (bUpdateQRCode) {\n\n\t\tloadQRCode(QRPushURL, QRCurrentSize);\n QRCurrentURL = QRPushURL; QRPushURL = \"\";\n bUpdateQRCode = false;\n\t}\n\n if ((windowWidth != ofGetWindowWidth()) || (windowHeight != ofGetWindowHeight())){\n \n\t\twindowWidth = ofGetWindowWidth(); windowHeight = ofGetWindowHeight();\n browser.setup(windowWidth, windowHeight);\n browser.loadURL(currentURL);\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::draw(){\n\n\t\n if(browser.getIsLoading()) {ofSetColor(0); ofDrawBitmapString(\"Loading...\", 10, 15);}\n ofSetColor(255);\n browser.draw(0, 0);\n\n\tif ((bQRControl) && (QRControlCode.isAllocated())){\n\t\tofPushMatrix();\n\t\t\tif (QRCurrentHeight == QR_TOP) ofTranslate(0,(QRCurrentSize\/2) + QRCurrentMargin,0); \n\t\t\telse if (QRCurrentHeight == QR_BOTTOM) ofTranslate(0,ofGetWindowHeight()-(QRCurrentSize\/2)-QRCurrentMargin,0); \n\t\t\telse ofTranslate(0,ofGetWindowHeight()\/2,0);\n\n\t\t\tif ((QRCurrentSide == QR_LEFT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw((QRCurrentSize\/2) + QRCurrentMargin,0);\n\t\t\tif ((QRCurrentSide == QR_RIGHT) || (QRCurrentSide == QR_BOTH)) QRControlCode.draw(ofGetWindowWidth()-(QRCurrentSize\/2)-QRCurrentMargin,0);\n\n\t\tofPopMatrix();\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::keyPressed(int key){ browser.keyPressed(key);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::keyReleased(int key){ browser.keyReleased(key);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseMoved(int x, int y ){\n \n if (bHideCursor) ofHideCursor(); else ofShowCursor();\n browser.mouseMoved(x, y);\n}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseDragged(int x, int y, int button){ browser.mouseDragged(x, y, button);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mousePressed(int x, int y, int button){browser.mousePressed(x, y, button);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseReleased(int x, int y, int button){browser.mouseReleased(x, y, button);}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseEntered(int x, int y){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::mouseExited(int x, int y){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::windowResized(int w, int h){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::gotMessage(ofMessage msg){}\n\/\/--------------------------------------------------------------\nvoid pushBrowserApp::dragEvent(ofDragInfo dragInfo){}\n\nvoid pushBrowserApp::loadSettings(){\n \n ofxXmlSettings settings;\n settings.loadFile(DEFAULT_SETTINGS);\n windowWidth = origWindowWidth = settings.getValue(\"SETTINGS:WINDOW:WIDTH\", WINDOW_WIDTH_DEFAULT);\n\twindowHeight = origWindowHeight = settings.getValue(\"SETTINGS:WINDOW:HEIGHT\", WINDOW_HEIGHT_DEFAULT);\n string _bFullScreen = ofToLower(settings.getValue(\"SETTINGS:WINDOW:FULLSCREEN\", DEFAULT_FULLSCREEN));\n if (_bFullScreen == \"true\") bFullScreen = true; else bFullScreen = false;\n\tstring _bHideCursor = ofToLower(settings.getValue(\"SETTINGS:WINDOW:HIDE_CURSOR\", DEFAULT_HIDE_CURSOR));\n if (_bHideCursor == \"true\") bHideCursor = true; else bHideCursor = false;\n \n\tcurrentURL = defaultURL = settings.getValue(\"SETTINGS:DEFAULT_URL\", DEFAULT_URL);\n\t\n\tQRCurrentURL = QRDefaultURL = settings.getValue(\"SETTINGS:QR_CONTROL:DEFAULT_QR_URL\", DEFAULT_QR_URL);\n\tstring _bQRControl = ofToLower(settings.getValue(\"SETTINGS:QR_CONTROL:QR_ON\", DEFAULT_QR_ON));\n if (_bQRControl == \"true\") bQRControl = true; else bQRControl = false;\n\tstring _QRSide = ofToLower(settings.getValue(\"SETTINGS:QR_CONTROL:QR_SIDE\", DEFAULT_QR_SIDE));\n if (_QRSide == \"left\") QRCurrentSide = QR_LEFT; if (_QRSide == \"right\") QRCurrentSide = QR_RIGHT; if (_QRSide == \"both\") QRCurrentSide = QR_BOTH;\n\tstring _QRHeight = ofToLower(settings.getValue(\"SETTINGS:QR_CONTROL:QR_HEIGHT\", DEFAULT_QR_HEIGHT));\n if (_QRHeight == \"top\") QRCurrentHeight = QR_TOP; if (_QRHeight == \"middle\") QRCurrentHeight = QR_MIDDLE; if (_QRHeight == \"bottom\") QRCurrentHeight = QR_BOTTOM;\n\tQRCurrentSize = settings.getValue(\"SETTINGS:QR_CONTROL:QR_SIZE\", DEFAULT_QR_SIZE);\n\tQRCurrentMargin = settings.getValue(\"SETTINGS:QR_CONTROL:QR_MARGIN\", DEFAULT_QR_MARGIN);\n\tif (bQRControl) {loadQRCode(QRCurrentURL, QRCurrentSize);}\n\toscReceivePort = ofToInt(settings.getValue(\"SETTINGS:OSC_RECEIVE_PORT\", DEFAULT_OSC_RECEIVE_PORT));\n}\n\nvoid pushBrowserApp::loadQRCode(string url, int size){\n\n\tQRControlCode = QRCodeGenerator.generate(url, size, true, false);\n\tQRControlCode.setAnchorPercent(0.5, 0.5);\n}<|endoftext|>"} {"text":"#include \"braincloud\/internal\/SaveDataHelper.h\"\n\n#if !defined(__APPLE__)\n\n#if defined(WINDOWS) || defined(WIN32)\n#include \n#endif\n\n\nSaveDataHelper * SaveDataHelper::m_instance = NULL;\n\nSaveDataHelper::SaveDataHelper()\n: m_savePath(\"\")\n{\n\n}\n\nSaveDataHelper * SaveDataHelper::getInstance()\n{\n if (m_instance == NULL)\n {\n m_instance = new SaveDataHelper();\n }\n\n return m_instance;\n}\n\nvoid SaveDataHelper::initialize(const char * companyName, const char * appName)\n{\n#if defined(WINDOWS) || defined(WIN32)\n if (companyName != NULL && appName != NULL)\n {\n std::string companyNameStr = companyName;\n std::string gameNameStr = appName;\n m_savePath = std::string(\"Software\\\\\" + companyNameStr + \"\\\\\" + gameNameStr + \"\\\\\");\n }\n#endif\n}\n\nvoid SaveDataHelper::saveData(const char * key, const char * data)\n{\n#if defined(WINDOWS) || defined(WIN32)\n#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n std::string skey = key;\n std::string sdata = data;\n std::wstring wskey;\n std::wstring wsdata;\n for (auto c : skey) {\n wskey += (wchar_t)c;\n }\n for (auto c : sdata) {\n wsdata += (wchar_t)c;\n }\n Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;\n auto values = localSettings->Values;\n values->Insert(\n ref new Platform::String(wskey.c_str()),\n dynamic_cast(Windows::Foundation::PropertyValue::CreateString(ref new Platform::String(wsdata.c_str()))));\n#else\n if (m_savePath.empty())\n {\n return;\n }\n\n LONG status;\n HKEY hKey;\n\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));\n RegCloseKey(hKey);\n }\n else if (status == ERROR_FILE_NOT_FOUND) {\n \/\/ Key didn't exist, create it\n SECURITY_ATTRIBUTES sAttribs = { sizeof(SECURITY_ATTRIBUTES) };\n DWORD dwDisposition = 0;\n status = RegCreateKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, \"\", REG_OPTION_VOLATILE, KEY_ALL_ACCESS, &sAttribs, &hKey, &dwDisposition);\n if (status == ERROR_SUCCESS) {\n \/\/ Set it's value\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));\n RegCloseKey(hKey);\n }\n }\n }\n#endif\n#endif\n}\n\nstd::string SaveDataHelper::readData(const char * key)\n{\n std::string sdata;\n\n#if defined(WINDOWS) || defined(WIN32)\n#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n std::string skey = key;\n std::wstring wskey;\n for (auto c : skey) {\n wskey += (wchar_t)c;\n }\n Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;\n auto values = localSettings->Values;\n Platform::String^ value = safe_cast(localSettings->Values->Lookup(ref new Platform::String(wskey.c_str())));\n if (!value) return \"\";\n std::wstring wsdata = value->Data();\n for (auto c : wsdata) {\n sdata += (char)c;\n }\n#else\n if (m_savePath.empty())\n {\n return \"\";\n }\n\n LONG status;\n HKEY hKey;\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_READ, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n unsigned long type = REG_SZ, size = 1024;\n char res[1024] = \"\";\n\n status = RegQueryValueExA(hKey,\n key, NULL, &type, (LPBYTE)&res[0], &size);\n\n RegCloseKey(hKey);\n\n if (status == ERROR_SUCCESS) {\n sdata = res;\n }\n }\n#endif\n#else\n \/\/ android\/linux implementation?\n#endif\n\n return sdata;\n}\n\nvoid SaveDataHelper::deleteData(const char * key)\n{\n#if defined(WINDOWS) || defined(WIN32)\n#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n std::string skey = key;\n std::wstring wskey;\n for (auto c : skey) {\n wskey += (wchar_t)c;\n }\n Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;\n auto values = localSettings->Values;\n values->Remove(ref new Platform::String(wskey.c_str()));\n#else\n if (m_savePath.empty())\n {\n return;\n }\n\n std::string data;\n\n LONG status;\n HKEY hKey;\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_SET_VALUE, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n unsigned long type = REG_SZ, size = 1024;\n char res[1024] = \"\";\n\n status = RegDeleteValueA(hKey, key);\n RegCloseKey(hKey);\n }\n#endif\n#endif\n}\n\n#endif \/\/__APPLE__\nAdding missing header fix for Linux build#include \"braincloud\/internal\/SaveDataHelper.h\"\n\n#if !defined(__APPLE__)\n\n#if defined(WINDOWS) || defined(WIN32)\n#include \n#endif\n\n\nSaveDataHelper * SaveDataHelper::m_instance = NULL;\n\nSaveDataHelper::SaveDataHelper()\n: m_savePath(\"\")\n{\n\n}\n\nSaveDataHelper * SaveDataHelper::getInstance()\n{\n if (m_instance == NULL)\n {\n m_instance = new SaveDataHelper();\n }\n\n return m_instance;\n}\n\n\n\nvoid SaveDataHelper::initialize(const char * companyName, const char * appName, const char * wrapperName)\n{\n#if defined(WINDOWS) || defined(WIN32)\n if (companyName != NULL && appName != NULL)\n {\n std::string companyNameStr = companyName;\n std::string gameNameStr = appName;\n m_savePath = std::string(\"Software\\\\\" + companyNameStr + \"\\\\\" + gameNameStr + \"\\\\\");\n }\n#endif\n}\n\nvoid SaveDataHelper::saveData(const char * key, const char * data)\n{\n#if defined(WINDOWS) || defined(WIN32)\n#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n std::string skey = key;\n std::string sdata = data;\n std::wstring wskey;\n std::wstring wsdata;\n for (auto c : skey) {\n wskey += (wchar_t)c;\n }\n for (auto c : sdata) {\n wsdata += (wchar_t)c;\n }\n Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;\n auto values = localSettings->Values;\n values->Insert(\n ref new Platform::String(wskey.c_str()),\n dynamic_cast(Windows::Foundation::PropertyValue::CreateString(ref new Platform::String(wsdata.c_str()))));\n#else\n if (m_savePath.empty())\n {\n return;\n }\n\n LONG status;\n HKEY hKey;\n\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));\n RegCloseKey(hKey);\n }\n else if (status == ERROR_FILE_NOT_FOUND) {\n \/\/ Key didn't exist, create it\n SECURITY_ATTRIBUTES sAttribs = { sizeof(SECURITY_ATTRIBUTES) };\n DWORD dwDisposition = 0;\n status = RegCreateKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, \"\", REG_OPTION_VOLATILE, KEY_ALL_ACCESS, &sAttribs, &hKey, &dwDisposition);\n if (status == ERROR_SUCCESS) {\n \/\/ Set it's value\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_ALL_ACCESS, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n status = RegSetValueExA(hKey, key, 0, REG_SZ, (BYTE*)data, ((DWORD)strlen(data) + 1)*sizeof(char));\n RegCloseKey(hKey);\n }\n }\n }\n#endif\n#endif\n}\n\nstd::string SaveDataHelper::readData(const char * key)\n{\n std::string sdata;\n\n#if defined(WINDOWS) || defined(WIN32)\n#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n std::string skey = key;\n std::wstring wskey;\n for (auto c : skey) {\n wskey += (wchar_t)c;\n }\n Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;\n auto values = localSettings->Values;\n Platform::String^ value = safe_cast(localSettings->Values->Lookup(ref new Platform::String(wskey.c_str())));\n if (!value) return \"\";\n std::wstring wsdata = value->Data();\n for (auto c : wsdata) {\n sdata += (char)c;\n }\n#else\n if (m_savePath.empty())\n {\n return \"\";\n }\n\n LONG status;\n HKEY hKey;\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_READ, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n unsigned long type = REG_SZ, size = 1024;\n char res[1024] = \"\";\n\n status = RegQueryValueExA(hKey,\n key, NULL, &type, (LPBYTE)&res[0], &size);\n\n RegCloseKey(hKey);\n\n if (status == ERROR_SUCCESS) {\n sdata = res;\n }\n }\n#endif\n#else\n \/\/ android\/linux implementation?\n#endif\n\n return sdata;\n}\n\nvoid SaveDataHelper::deleteData(const char * key)\n{\n#if defined(WINDOWS) || defined(WIN32)\n#if defined WINAPI_FAMILY && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n std::string skey = key;\n std::wstring wskey;\n for (auto c : skey) {\n wskey += (wchar_t)c;\n }\n Windows::Storage::ApplicationDataContainer^ localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;\n auto values = localSettings->Values;\n values->Remove(ref new Platform::String(wskey.c_str()));\n#else\n if (m_savePath.empty())\n {\n return;\n }\n\n std::string data;\n\n LONG status;\n HKEY hKey;\n status = RegOpenKeyExA(HKEY_CURRENT_USER, m_savePath.c_str(), 0, KEY_SET_VALUE, &hKey);\n if ((status == ERROR_SUCCESS) && (hKey != NULL)) {\n unsigned long type = REG_SZ, size = 1024;\n char res[1024] = \"\";\n\n status = RegDeleteValueA(hKey, key);\n RegCloseKey(hKey);\n }\n#endif\n#endif\n}\n\n#endif \/\/__APPLE__\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeomappingmanagerengine_nokia.h\"\n#include \"qgeomapreply_nokia.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define LARGE_TILE_DIMENSION 256\n#define PI 3.14159265\n#include \n\nQGeoMappingManagerEngineNokia::QGeoMappingManagerEngineNokia(const QMap ¶meters, QGeoServiceProvider::Error *error, QString *errorString)\n : QGeoTiledMappingManagerEngine(parameters),\n m_host(\"loc.desktop.maps.svc.ovi.com\")\n{\n setTileSize(QSize(128,128));\n setMinimumZoomLevel(0.0);\n setMaximumZoomLevel(18.0);\n\n QList types;\n types << QGeoMapWidget::StreetMap;\n types << QGeoMapWidget::SatelliteMapDay;\n types << QGeoMapWidget::TerrainMap;\n setSupportedMapTypes(types);\n\n m_nam = new QNetworkAccessManager(this);\n m_cache = new QNetworkDiskCache(this);\n\n QDir dir = QDir::temp();\n dir.mkdir(\"maptiles\");\n dir.cd(\"maptiles\");\n\n m_cache->setCacheDirectory(dir.path());\n\n QList keys = parameters.keys();\n\n if (keys.contains(\"mapping.proxy\")) {\n QString proxy = parameters.value(\"mapping.proxy\").toString();\n if (!proxy.isEmpty())\n m_nam->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, 8080));\n }\n\n if (keys.contains(\"mapping.host\")) {\n QString host = parameters.value(\"mapping.host\").toString();\n if (!host.isEmpty())\n m_host = host;\n }\n\n if (keys.contains(\"mapping.cache.directory\")) {\n QString cacheDir = parameters.value(\"mapping.cache.directory\").toString();\n if (!cacheDir.isEmpty())\n m_cache->setCacheDirectory(cacheDir);\n }\n\n if (keys.contains(\"mapping.cache.size\")) {\n bool ok = false;\n qint64 cacheSize = parameters.value(\"mapping.cache.size\").toString().toLongLong(&ok);\n if (ok)\n m_cache->setMaximumCacheSize(cacheSize);\n }\n\n m_nam->setCache(m_cache);\n}\n\nQGeoMappingManagerEngineNokia::~QGeoMappingManagerEngineNokia() {}\n\nQGeoTiledMapReply* QGeoMappingManagerEngineNokia::getTileImage(const QGeoTiledMapRequest &request)\n{\n QString rawRequest = getRequestString(request);\n\n QNetworkRequest netRequest = QNetworkRequest(QUrl(rawRequest));\n netRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n m_cache->metaData(netRequest.url()).setLastModified(QDateTime::currentDateTime());\n\n QNetworkReply* netReply = m_nam->get(netRequest);\n\n QGeoTiledMapReply* mapReply = new QGeoMapReplyNokia(netReply, request, this);\n\n \/\/ TODO goes badly on linux\n \/\/qDebug() << \"request: \" << QString::number(reinterpret_cast(mapReply), 16) << \" \" << request.row() << \",\" << request.column();\n return mapReply;\n}\n\nQString QGeoMappingManagerEngineNokia::getRequestString(const QGeoTiledMapRequest &request) const\n{\n QString requestString = \"http:\/\/\";\n requestString += m_host;\n requestString += \"\/maptiler\/maptile\/newest\/\";\n requestString += mapTypeToStr(request.mapType());\n requestString += '\/';\n requestString += QString::number(request.zoomLevel());\n requestString += '\/';\n requestString += QString::number(request.column());\n requestString += '\/';\n requestString += QString::number(request.row());\n requestString += '\/';\n requestString += sizeToStr(tileSize());\n requestString += '\/';\n requestString += \"png\";\n\n if (!m_token.isEmpty()) {\n requestString += \"?token=\";\n requestString += m_token;\n\n if (!m_referrer.isEmpty()) {\n requestString += \"&referrer=\";\n requestString += m_referrer;\n }\n } else if (!m_referrer.isEmpty()) {\n requestString += \"?referrer=\";\n requestString += m_referrer;\n }\n\n return requestString;\n}\n\nQString QGeoMappingManagerEngineNokia::sizeToStr(const QSize &size)\n{\n if (size.height() >= LARGE_TILE_DIMENSION ||\n size.width() >= LARGE_TILE_DIMENSION)\n return \"256\";\n else\n return \"128\";\n}\n\nQString QGeoMappingManagerEngineNokia::mapTypeToStr(QGeoMapWidget::MapType type)\n{\n if (type == QGeoMapWidget::StreetMap)\n return \"normal.day\";\n else if (type == QGeoMapWidget::SatelliteMapDay ||\n type == QGeoMapWidget::SatelliteMapNight) {\n return \"satellite.day\";\n } else if (type == QGeoMapWidget::TerrainMap)\n return \"terrain.day\";\n else\n return \"normal.day\";\n}\n\nQGeoMappingManagerEngineNokia::getTileImage: Simplified something, added an alternative qDebug line\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeomappingmanagerengine_nokia.h\"\n#include \"qgeomapreply_nokia.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define LARGE_TILE_DIMENSION 256\n#define PI 3.14159265\n#include \n\nQGeoMappingManagerEngineNokia::QGeoMappingManagerEngineNokia(const QMap ¶meters, QGeoServiceProvider::Error *error, QString *errorString)\n : QGeoTiledMappingManagerEngine(parameters),\n m_host(\"loc.desktop.maps.svc.ovi.com\")\n{\n setTileSize(QSize(128,128));\n setMinimumZoomLevel(0.0);\n setMaximumZoomLevel(18.0);\n\n QList types;\n types << QGeoMapWidget::StreetMap;\n types << QGeoMapWidget::SatelliteMapDay;\n types << QGeoMapWidget::TerrainMap;\n setSupportedMapTypes(types);\n\n m_nam = new QNetworkAccessManager(this);\n m_cache = new QNetworkDiskCache(this);\n\n QDir dir = QDir::temp();\n dir.mkdir(\"maptiles\");\n dir.cd(\"maptiles\");\n\n m_cache->setCacheDirectory(dir.path());\n\n QList keys = parameters.keys();\n\n if (keys.contains(\"mapping.proxy\")) {\n QString proxy = parameters.value(\"mapping.proxy\").toString();\n if (!proxy.isEmpty())\n m_nam->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, 8080));\n }\n\n if (keys.contains(\"mapping.host\")) {\n QString host = parameters.value(\"mapping.host\").toString();\n if (!host.isEmpty())\n m_host = host;\n }\n\n if (keys.contains(\"mapping.cache.directory\")) {\n QString cacheDir = parameters.value(\"mapping.cache.directory\").toString();\n if (!cacheDir.isEmpty())\n m_cache->setCacheDirectory(cacheDir);\n }\n\n if (keys.contains(\"mapping.cache.size\")) {\n bool ok = false;\n qint64 cacheSize = parameters.value(\"mapping.cache.size\").toString().toLongLong(&ok);\n if (ok)\n m_cache->setMaximumCacheSize(cacheSize);\n }\n\n m_nam->setCache(m_cache);\n}\n\nQGeoMappingManagerEngineNokia::~QGeoMappingManagerEngineNokia() {}\n\nQGeoTiledMapReply* QGeoMappingManagerEngineNokia::getTileImage(const QGeoTiledMapRequest &request)\n{\n QString rawRequest = getRequestString(request);\n\n QNetworkRequest netRequest((QUrl(rawRequest))); \/\/ The extra pair of parens disambiguates this from a function declaration\n netRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n m_cache->metaData(netRequest.url()).setLastModified(QDateTime::currentDateTime());\n\n QNetworkReply* netReply = m_nam->get(netRequest);\n\n QGeoTiledMapReply* mapReply = new QGeoMapReplyNokia(netReply, request, this);\n\n \/\/ TODO goes badly on linux\n \/\/qDebug() << \"request: \" << QString::number(reinterpret_cast(mapReply), 16) << \" \" << request.row() << \",\" << request.column();\n \/\/ this one might work better. It follows defined behaviour, unlike reinterpret_cast\n \/\/qDebug(\"request: %p %i,%i @ %i\", mapReply, request.row(), request.column(), request.zoomLevel());\n return mapReply;\n}\n\nQString QGeoMappingManagerEngineNokia::getRequestString(const QGeoTiledMapRequest &request) const\n{\n QString requestString = \"http:\/\/\";\n requestString += m_host;\n requestString += \"\/maptiler\/maptile\/newest\/\";\n requestString += mapTypeToStr(request.mapType());\n requestString += '\/';\n requestString += QString::number(request.zoomLevel());\n requestString += '\/';\n requestString += QString::number(request.column());\n requestString += '\/';\n requestString += QString::number(request.row());\n requestString += '\/';\n requestString += sizeToStr(tileSize());\n requestString += '\/';\n requestString += \"png\";\n\n if (!m_token.isEmpty()) {\n requestString += \"?token=\";\n requestString += m_token;\n\n if (!m_referrer.isEmpty()) {\n requestString += \"&referrer=\";\n requestString += m_referrer;\n }\n } else if (!m_referrer.isEmpty()) {\n requestString += \"?referrer=\";\n requestString += m_referrer;\n }\n\n return requestString;\n}\n\nQString QGeoMappingManagerEngineNokia::sizeToStr(const QSize &size)\n{\n if (size.height() >= LARGE_TILE_DIMENSION ||\n size.width() >= LARGE_TILE_DIMENSION)\n return \"256\";\n else\n return \"128\";\n}\n\nQString QGeoMappingManagerEngineNokia::mapTypeToStr(QGeoMapWidget::MapType type)\n{\n if (type == QGeoMapWidget::StreetMap)\n return \"normal.day\";\n else if (type == QGeoMapWidget::SatelliteMapDay ||\n type == QGeoMapWidget::SatelliteMapNight) {\n return \"satellite.day\";\n } else if (type == QGeoMapWidget::TerrainMap)\n return \"terrain.day\";\n else\n return \"normal.day\";\n}\n\n<|endoftext|>"} {"text":"#include \"MainGUI.moc\"\n\n#include \n#include \n\n#include \"..\/assemble.h\"\n\nMainGUI::MainGUI(std::string world_string)\n : bf(NULL) {\n QGroupBox *groupBox = new QGroupBox(\"select world\");\n radio1 = new QRadioButton(tr(\"World 1\"));\n radio2 = new QRadioButton(tr(\"World 2\"));\n radio3 = new QRadioButton(tr(\"World 3\"));\n radio4 = new QRadioButton(tr(\"World 4\"));\n radio5 = new QRadioButton(tr(\"World 5\"));\n QRadioButton* radio6 = new QRadioButton(tr(\"custom\"));\n custom_world = new QLineEdit;\n radio1->setEnabled(nbt::exist_world(1));\n radio2->setEnabled(nbt::exist_world(2));\n radio3->setEnabled(nbt::exist_world(3));\n radio4->setEnabled(nbt::exist_world(4));\n radio5->setEnabled(nbt::exist_world(5));\n QVBoxLayout *vbox = new QVBoxLayout;\n vbox->addWidget(radio1);\n vbox->addWidget(radio2);\n vbox->addWidget(radio3);\n vbox->addWidget(radio4);\n vbox->addWidget(radio5);\n vbox->addWidget(radio6);\n groupBox->setLayout(vbox);\n custom_world->setMaximumWidth(groupBox->sizeHint().width());\n custom_world->setEnabled(false);\n vbox->addWidget(custom_world);\n connect(radio6, SIGNAL(toggled(bool)), custom_world, SLOT(setEnabled(bool)));\n connect(radio6, SIGNAL(clicked()), this, SLOT(load_custom_world()));\n\n QGroupBox* renderBox = new QGroupBox(\"render mode\");\n QRadioButton* render1 = new QRadioButton(\"top down\");\n QRadioButton* render2 = new QRadioButton(\"oblique\");\n QRadioButton* render3 = new QRadioButton(\"isometric\");\n render1->setChecked(true);\n QVBoxLayout *vbox_render = new QVBoxLayout;\n vbox_render->addWidget(render1);\n vbox_render->addWidget(render2);\n vbox_render->addWidget(render3);\n renderBox->setLayout(vbox_render);\n QSignalMapper* render_mapper = new QSignalMapper(this);\n connect(render1, SIGNAL(clicked()), render_mapper, SLOT(map()));\n connect(render2, SIGNAL(clicked()), render_mapper, SLOT(map()));\n connect(render3, SIGNAL(clicked()), render_mapper, SLOT(map()));\n render_mapper->setMapping(render1, 0);\n render_mapper->setMapping(render2, 1);\n render_mapper->setMapping(render3, 2);\n connect(render_mapper, SIGNAL(mapped(int)), this, SLOT(set_render_mode(int)));\n\n QGroupBox* shadowBox = new QGroupBox(\"shadow quality\");\n QRadioButton* shadow1 = new QRadioButton(\"normal\");\n QRadioButton* shadow2 = new QRadioButton(\"high\");\n QRadioButton* shadow3 = new QRadioButton(\"ultra\");\n shadow1->setChecked(true);\n QVBoxLayout *vbox_shadow = new QVBoxLayout;\n vbox_shadow->addWidget(shadow1);\n vbox_shadow->addWidget(shadow2);\n vbox_shadow->addWidget(shadow3);\n shadowBox->setLayout(vbox_shadow);\n QSignalMapper* shadow_mapper = new QSignalMapper(this);\n connect(shadow1, SIGNAL(clicked()), shadow_mapper, SLOT(map()));\n connect(shadow2, SIGNAL(clicked()), shadow_mapper, SLOT(map()));\n connect(shadow3, SIGNAL(clicked()), shadow_mapper, SLOT(map()));\n shadow_mapper->setMapping(shadow1, 0);\n shadow_mapper->setMapping(shadow2, 1);\n shadow_mapper->setMapping(shadow3, 2);\n connect(shadow_mapper, SIGNAL(mapped(int)), this, SLOT(set_shadow_quality(int)));\n\n QGroupBox *lightBox = new QGroupBox(\"sun direction\");\n QRadioButton* light0 = new QRadioButton();\n QRadioButton* light1 = new QRadioButton();\n QRadioButton* light2 = new QRadioButton();\n QRadioButton* light3 = new QRadioButton();\n QRadioButton* light4 = new QRadioButton();\n QRadioButton* light5 = new QRadioButton();\n QRadioButton* light6 = new QRadioButton();\n QRadioButton* light7 = new QRadioButton();\n QGridLayout *light_grid = new QGridLayout;\n light_grid->addWidget(light0, 0, 0);\n light_grid->addWidget(light1, 1, 0);\n light_grid->addWidget(light2, 2, 0);\n light_grid->addWidget(light3, 2, 1);\n light_grid->addWidget(light4, 2, 2);\n light_grid->addWidget(light5, 1, 2);\n light_grid->addWidget(light6, 0, 2);\n light_grid->addWidget(light7, 0, 1);\n lightBox->setLayout(light_grid);\n QSignalMapper* light_mapper = new QSignalMapper(this);\n connect(light0, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light1, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light2, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light3, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light4, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light5, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light6, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light7, SIGNAL(clicked()), light_mapper, SLOT(map()));\n light_mapper->setMapping(light0, 0);\n light_mapper->setMapping(light1, 1);\n light_mapper->setMapping(light2, 2);\n light_mapper->setMapping(light3, 3);\n light_mapper->setMapping(light4, 4);\n light_mapper->setMapping(light5, 5);\n light_mapper->setMapping(light6, 6);\n light_mapper->setMapping(light7, 7);\n connect(light_mapper, SIGNAL(mapped(int)), this, SLOT(set_sun_direction(int)));\n light0->click();\n\n QGroupBox *rotateBox = new QGroupBox(\"rotation\");\n QRadioButton* rotate0 = new QRadioButton();\n QRadioButton* rotate1 = new QRadioButton();\n QRadioButton* rotate2 = new QRadioButton();\n QRadioButton* rotate3 = new QRadioButton();\n QGridLayout *rotate_grid = new QGridLayout;\n rotate_grid->addWidget(rotate0, 0, 1);\n rotate_grid->addWidget(rotate1, 1, 0);\n rotate_grid->addWidget(rotate2, 2, 1);\n rotate_grid->addWidget(rotate3, 1, 2);\n rotateBox->setLayout(rotate_grid);\n QSignalMapper* rotate_mapper = new QSignalMapper(this);\n connect(rotate0, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n connect(rotate1, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n connect(rotate2, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n connect(rotate3, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n rotate_mapper->setMapping(rotate0, 1);\n rotate_mapper->setMapping(rotate1, 0);\n rotate_mapper->setMapping(rotate2, 3);\n rotate_mapper->setMapping(rotate3, 2);\n connect(rotate_mapper, SIGNAL(mapped(int)), this, SLOT(set_rotate(int)));\n rotate0->click();\n\n QSpinBox* relief_strength = new QSpinBox(this);\n connect(relief_strength, SIGNAL(valueChanged(int)), this, SLOT(set_relief_strength(int)));\n relief_strength->setValue(10);\n QSpinBox* shadow_strength = new QSpinBox(this);\n connect(shadow_strength, SIGNAL(valueChanged(int)), this, SLOT(set_shadow_strength(int)));\n shadow_strength->setValue(60);\n QLabel* relief_label = new QLabel(\"relief strength:\");\n QLabel* shadow_label = new QLabel(\"shadow strength:\");\n\n QBoxLayout* global = new QHBoxLayout(this);\n QScrollArea* left_scroll_area = new QScrollArea;\n left_scroll_area->setFrameStyle(QFrame::NoFrame | QFrame::Plain);\n left_scroll_area->setLineWidth(0);\n QBoxLayout* left_side = new QVBoxLayout;\n left_side->addWidget(groupBox);\n left_side->addWidget(renderBox);\n left_side->addWidget(relief_label);\n left_side->addWidget(relief_strength);\n left_side->addWidget(shadow_label);\n left_side->addWidget(shadow_strength);\n left_side->addWidget(shadowBox);\n left_side->addWidget(lightBox);\n left_side->addWidget(rotateBox);\n QCheckBox* night_mode_box = new QCheckBox(\"night mode\");\n left_side->addWidget(night_mode_box);\n connect(night_mode_box, SIGNAL(stateChanged(int)), this, SLOT(set_night_mode(int)));\n left_side->addStretch(1);\n QWidget* left_widget = new QWidget;\n left_widget->setLayout(left_side);\n left_scroll_area->setWidget(left_widget);\n QVBoxLayout* left_side_all = new QVBoxLayout;\n left_side_all->addWidget(left_scroll_area);\n start_button = new QPushButton(\"Start rendering\", this);\n left_side_all->addWidget(start_button);\n left_side_all->setContentsMargins(0, 0, 0, 0);\n QWidget* left_side_all_widget = new QWidget;\n left_side_all_widget->setLayout(left_side_all);\n left_side_all_widget->setFixedWidth(left_side_all_widget->sizeHint().width()\n + left_scroll_area->verticalScrollBar()\n ->sizeHint().width() + 3);\n global->addWidget(left_side_all_widget);\n\n\n mf = new MainForm(&scene, bf);\n global->addWidget(mf);\n\n connect(start_button, SIGNAL(clicked()), this, SLOT(set_new_world()));\n connect(&new_world_setup_watcher, SIGNAL(finished()), this, SLOT(toggle_rendering()));\n connect(&watcher, SIGNAL(finished()), this, SLOT(handle_finished()));\n}\n\nvoid MainGUI::set_relief_strength(int value) {\n set.relief = set.relief_strength = value;\n}\n\nvoid MainGUI::set_shadow_strength(int value) {\n set.shadow = set.shadow_strength = value;\n}\n\nvoid MainGUI::set_sun_direction(int value) {\n value = (value + 1) % 8;\n set.sun_direction = value;\n}\n\nvoid MainGUI::set_render_mode(int value) {\n if (value == 0) {\n set.topview = true;\n set.oblique = false;\n set.isometric = false;\n } else if (value == 1) {\n set.topview = false;\n set.oblique = true;\n set.isometric = false;\n } else if (value == 2) {\n set.topview = false;\n set.oblique = false;\n set.isometric = true;\n }\n}\n\nvoid MainGUI::set_rotate(int value) {\n set.rotate = value;\n}\n\nvoid MainGUI::set_night_mode(int value) {\n set.nightmode = value;\n}\n\nvoid MainGUI::set_shadow_quality(int value) {\n if (value == 0) {\n set.shadow_quality = false;\n set.shadow_quality_ultra = false;\n } else if (value == 1) {\n set.shadow_quality = true;\n set.shadow_quality_ultra = false;\n } else if (value == 2) {\n set.shadow_quality = true;\n set.shadow_quality_ultra = true;\n }\n}\n\nvoid MainGUI::load_custom_world() {\n QString dir = QFileDialog::getExistingDirectory(this, tr(\"Open world\"),\n QString(),\n QFileDialog::ShowDirsOnly);\n if (dir != QString()) {\n custom_world->setText(dir);\n }\n}\n\n\nint MainGUI::current_world() {\n if (radio1->isChecked()) {\n return 1;\n } else if (radio2->isChecked()) {\n return 2;\n } else if (radio3->isChecked()) {\n return 3;\n } else if (radio4->isChecked()) {\n return 4;\n } else if (radio5->isChecked()) {\n return 5;\n } else {\n return 0;\n }\n}\n\nvoid MainGUI::new_bf() {\n if (!current_world()) {\n bf = new nbt(custom_world->text().toStdString());\n } else {\n bf = new nbt(current_world());\n }\n}\n\nvoid MainGUI::set_new_world() {\n if (start_button->text() == \"Start rendering\") {\n if (bf) {\n delete bf;\n bf = NULL;\n }\n if (!current_world() && custom_world->text() == QString()) return;\n start_button->setText(\"Loading world...\");\n start_button->setEnabled(false);\n new_world_setup = QFuture(QtConcurrent::run(this, &MainGUI::new_bf));\n new_world_setup_watcher.setFuture(new_world_setup);\n } else {\n mf->StopPopulateScene();\n start_button->setEnabled(false);\n }\n}\n\nvoid MainGUI::toggle_rendering() {\n if (bf->bad_world) {\n handle_finished();\n return;\n }\n std::cout << bf->string();\n bf->setSettings(set);\n mf->set_nbt(bf);\n scene.clear();\n\n start_button->setText(\"Abort rendering\");\n start_button->setEnabled(true);\n worker = QFuture(QtConcurrent::run(mf, &MainForm::populateScene));\n watcher.setFuture(worker);\n}\n\nvoid MainGUI::handle_finished() {\n start_button->setText(\"Start rendering\");\n start_button->setEnabled(true);\n}\nreorder widgets#include \"MainGUI.moc\"\n\n#include \n#include \n\n#include \"..\/assemble.h\"\n\nMainGUI::MainGUI(std::string world_string)\n : bf(NULL) {\n QGroupBox *groupBox = new QGroupBox(\"select world\");\n radio1 = new QRadioButton(tr(\"World 1\"));\n radio2 = new QRadioButton(tr(\"World 2\"));\n radio3 = new QRadioButton(tr(\"World 3\"));\n radio4 = new QRadioButton(tr(\"World 4\"));\n radio5 = new QRadioButton(tr(\"World 5\"));\n QRadioButton* radio6 = new QRadioButton(tr(\"custom\"));\n custom_world = new QLineEdit;\n radio1->setEnabled(nbt::exist_world(1));\n radio2->setEnabled(nbt::exist_world(2));\n radio3->setEnabled(nbt::exist_world(3));\n radio4->setEnabled(nbt::exist_world(4));\n radio5->setEnabled(nbt::exist_world(5));\n QVBoxLayout *vbox = new QVBoxLayout;\n vbox->addWidget(radio1);\n vbox->addWidget(radio2);\n vbox->addWidget(radio3);\n vbox->addWidget(radio4);\n vbox->addWidget(radio5);\n vbox->addWidget(radio6);\n groupBox->setLayout(vbox);\n custom_world->setMaximumWidth(groupBox->sizeHint().width());\n custom_world->setEnabled(false);\n vbox->addWidget(custom_world);\n connect(radio6, SIGNAL(toggled(bool)), custom_world, SLOT(setEnabled(bool)));\n connect(radio6, SIGNAL(clicked()), this, SLOT(load_custom_world()));\n\n QGroupBox* renderBox = new QGroupBox(\"render mode\");\n QRadioButton* render1 = new QRadioButton(\"top down\");\n QRadioButton* render2 = new QRadioButton(\"oblique\");\n QRadioButton* render3 = new QRadioButton(\"isometric\");\n render1->setChecked(true);\n QVBoxLayout *vbox_render = new QVBoxLayout;\n vbox_render->addWidget(render1);\n vbox_render->addWidget(render2);\n vbox_render->addWidget(render3);\n renderBox->setLayout(vbox_render);\n QSignalMapper* render_mapper = new QSignalMapper(this);\n connect(render1, SIGNAL(clicked()), render_mapper, SLOT(map()));\n connect(render2, SIGNAL(clicked()), render_mapper, SLOT(map()));\n connect(render3, SIGNAL(clicked()), render_mapper, SLOT(map()));\n render_mapper->setMapping(render1, 0);\n render_mapper->setMapping(render2, 1);\n render_mapper->setMapping(render3, 2);\n connect(render_mapper, SIGNAL(mapped(int)), this, SLOT(set_render_mode(int)));\n\n QGroupBox* shadowBox = new QGroupBox(\"shadow quality\");\n QRadioButton* shadow1 = new QRadioButton(\"normal\");\n QRadioButton* shadow2 = new QRadioButton(\"high\");\n QRadioButton* shadow3 = new QRadioButton(\"ultra\");\n shadow1->setChecked(true);\n QVBoxLayout *vbox_shadow = new QVBoxLayout;\n vbox_shadow->addWidget(shadow1);\n vbox_shadow->addWidget(shadow2);\n vbox_shadow->addWidget(shadow3);\n shadowBox->setLayout(vbox_shadow);\n QSignalMapper* shadow_mapper = new QSignalMapper(this);\n connect(shadow1, SIGNAL(clicked()), shadow_mapper, SLOT(map()));\n connect(shadow2, SIGNAL(clicked()), shadow_mapper, SLOT(map()));\n connect(shadow3, SIGNAL(clicked()), shadow_mapper, SLOT(map()));\n shadow_mapper->setMapping(shadow1, 0);\n shadow_mapper->setMapping(shadow2, 1);\n shadow_mapper->setMapping(shadow3, 2);\n connect(shadow_mapper, SIGNAL(mapped(int)), this, SLOT(set_shadow_quality(int)));\n\n QGroupBox *lightBox = new QGroupBox(\"sun direction\");\n QRadioButton* light0 = new QRadioButton();\n QRadioButton* light1 = new QRadioButton();\n QRadioButton* light2 = new QRadioButton();\n QRadioButton* light3 = new QRadioButton();\n QRadioButton* light4 = new QRadioButton();\n QRadioButton* light5 = new QRadioButton();\n QRadioButton* light6 = new QRadioButton();\n QRadioButton* light7 = new QRadioButton();\n QGridLayout *light_grid = new QGridLayout;\n light_grid->addWidget(light0, 0, 0);\n light_grid->addWidget(light1, 1, 0);\n light_grid->addWidget(light2, 2, 0);\n light_grid->addWidget(light3, 2, 1);\n light_grid->addWidget(light4, 2, 2);\n light_grid->addWidget(light5, 1, 2);\n light_grid->addWidget(light6, 0, 2);\n light_grid->addWidget(light7, 0, 1);\n lightBox->setLayout(light_grid);\n QSignalMapper* light_mapper = new QSignalMapper(this);\n connect(light0, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light1, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light2, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light3, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light4, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light5, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light6, SIGNAL(clicked()), light_mapper, SLOT(map()));\n connect(light7, SIGNAL(clicked()), light_mapper, SLOT(map()));\n light_mapper->setMapping(light0, 0);\n light_mapper->setMapping(light1, 1);\n light_mapper->setMapping(light2, 2);\n light_mapper->setMapping(light3, 3);\n light_mapper->setMapping(light4, 4);\n light_mapper->setMapping(light5, 5);\n light_mapper->setMapping(light6, 6);\n light_mapper->setMapping(light7, 7);\n connect(light_mapper, SIGNAL(mapped(int)), this, SLOT(set_sun_direction(int)));\n light0->click();\n\n QGroupBox *rotateBox = new QGroupBox(\"rotation\");\n QRadioButton* rotate0 = new QRadioButton();\n QRadioButton* rotate1 = new QRadioButton();\n QRadioButton* rotate2 = new QRadioButton();\n QRadioButton* rotate3 = new QRadioButton();\n QGridLayout *rotate_grid = new QGridLayout;\n rotate_grid->addWidget(rotate0, 0, 1);\n rotate_grid->addWidget(rotate1, 1, 0);\n rotate_grid->addWidget(rotate2, 2, 1);\n rotate_grid->addWidget(rotate3, 1, 2);\n rotateBox->setLayout(rotate_grid);\n QSignalMapper* rotate_mapper = new QSignalMapper(this);\n connect(rotate0, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n connect(rotate1, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n connect(rotate2, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n connect(rotate3, SIGNAL(clicked()), rotate_mapper, SLOT(map()));\n rotate_mapper->setMapping(rotate0, 1);\n rotate_mapper->setMapping(rotate1, 0);\n rotate_mapper->setMapping(rotate2, 3);\n rotate_mapper->setMapping(rotate3, 2);\n connect(rotate_mapper, SIGNAL(mapped(int)), this, SLOT(set_rotate(int)));\n rotate0->click();\n\n QSpinBox* relief_strength = new QSpinBox(this);\n connect(relief_strength, SIGNAL(valueChanged(int)), this, SLOT(set_relief_strength(int)));\n relief_strength->setValue(10);\n QSpinBox* shadow_strength = new QSpinBox(this);\n connect(shadow_strength, SIGNAL(valueChanged(int)), this, SLOT(set_shadow_strength(int)));\n shadow_strength->setValue(60);\n QLabel* relief_label = new QLabel(\"relief strength:\");\n QLabel* shadow_label = new QLabel(\"shadow strength:\");\n\n QBoxLayout* global = new QHBoxLayout(this);\n QScrollArea* left_scroll_area = new QScrollArea;\n left_scroll_area->setFrameStyle(QFrame::NoFrame | QFrame::Plain);\n left_scroll_area->setLineWidth(0);\n QBoxLayout* left_side = new QVBoxLayout;\n left_side->addWidget(groupBox);\n left_side->addWidget(renderBox);\n left_side->addWidget(shadowBox);\n left_side->addWidget(shadow_label);\n left_side->addWidget(shadow_strength);\n left_side->addWidget(relief_label);\n left_side->addWidget(relief_strength);\n left_side->addWidget(lightBox);\n left_side->addWidget(rotateBox);\n QCheckBox* night_mode_box = new QCheckBox(\"night mode\");\n left_side->addWidget(night_mode_box);\n connect(night_mode_box, SIGNAL(stateChanged(int)), this, SLOT(set_night_mode(int)));\n left_side->addStretch(1);\n QWidget* left_widget = new QWidget;\n left_widget->setLayout(left_side);\n left_scroll_area->setWidget(left_widget);\n QVBoxLayout* left_side_all = new QVBoxLayout;\n left_side_all->addWidget(left_scroll_area);\n start_button = new QPushButton(\"Start rendering\", this);\n left_side_all->addWidget(start_button);\n left_side_all->setContentsMargins(0, 0, 0, 0);\n QWidget* left_side_all_widget = new QWidget;\n left_side_all_widget->setLayout(left_side_all);\n left_side_all_widget->setFixedWidth(left_side_all_widget->sizeHint().width()\n + left_scroll_area->verticalScrollBar()\n ->sizeHint().width() + 3);\n global->addWidget(left_side_all_widget);\n\n\n mf = new MainForm(&scene, bf);\n global->addWidget(mf);\n\n connect(start_button, SIGNAL(clicked()), this, SLOT(set_new_world()));\n connect(&new_world_setup_watcher, SIGNAL(finished()), this, SLOT(toggle_rendering()));\n connect(&watcher, SIGNAL(finished()), this, SLOT(handle_finished()));\n}\n\nvoid MainGUI::set_relief_strength(int value) {\n set.relief = set.relief_strength = value;\n}\n\nvoid MainGUI::set_shadow_strength(int value) {\n set.shadow = set.shadow_strength = value;\n}\n\nvoid MainGUI::set_sun_direction(int value) {\n value = (value + 1) % 8;\n set.sun_direction = value;\n}\n\nvoid MainGUI::set_render_mode(int value) {\n if (value == 0) {\n set.topview = true;\n set.oblique = false;\n set.isometric = false;\n } else if (value == 1) {\n set.topview = false;\n set.oblique = true;\n set.isometric = false;\n } else if (value == 2) {\n set.topview = false;\n set.oblique = false;\n set.isometric = true;\n }\n}\n\nvoid MainGUI::set_rotate(int value) {\n set.rotate = value;\n}\n\nvoid MainGUI::set_night_mode(int value) {\n set.nightmode = value;\n}\n\nvoid MainGUI::set_shadow_quality(int value) {\n if (value == 0) {\n set.shadow_quality = false;\n set.shadow_quality_ultra = false;\n } else if (value == 1) {\n set.shadow_quality = true;\n set.shadow_quality_ultra = false;\n } else if (value == 2) {\n set.shadow_quality = true;\n set.shadow_quality_ultra = true;\n }\n}\n\nvoid MainGUI::load_custom_world() {\n QString dir = QFileDialog::getExistingDirectory(this, tr(\"Open world\"),\n QString(),\n QFileDialog::ShowDirsOnly);\n if (dir != QString()) {\n custom_world->setText(dir);\n }\n}\n\n\nint MainGUI::current_world() {\n if (radio1->isChecked()) {\n return 1;\n } else if (radio2->isChecked()) {\n return 2;\n } else if (radio3->isChecked()) {\n return 3;\n } else if (radio4->isChecked()) {\n return 4;\n } else if (radio5->isChecked()) {\n return 5;\n } else {\n return 0;\n }\n}\n\nvoid MainGUI::new_bf() {\n if (!current_world()) {\n bf = new nbt(custom_world->text().toStdString());\n } else {\n bf = new nbt(current_world());\n }\n}\n\nvoid MainGUI::set_new_world() {\n if (start_button->text() == \"Start rendering\") {\n if (bf) {\n delete bf;\n bf = NULL;\n }\n if (!current_world() && custom_world->text() == QString()) return;\n start_button->setText(\"Loading world...\");\n start_button->setEnabled(false);\n new_world_setup = QFuture(QtConcurrent::run(this, &MainGUI::new_bf));\n new_world_setup_watcher.setFuture(new_world_setup);\n } else {\n mf->StopPopulateScene();\n start_button->setEnabled(false);\n }\n}\n\nvoid MainGUI::toggle_rendering() {\n if (bf->bad_world) {\n handle_finished();\n return;\n }\n std::cout << bf->string();\n bf->setSettings(set);\n mf->set_nbt(bf);\n scene.clear();\n\n start_button->setText(\"Abort rendering\");\n start_button->setEnabled(true);\n worker = QFuture(QtConcurrent::run(mf, &MainForm::populateScene));\n watcher.setFuture(worker);\n}\n\nvoid MainGUI::handle_finished() {\n start_button->setText(\"Start rendering\");\n start_button->setEnabled(true);\n}\n<|endoftext|>"} {"text":"#include \"TalisScene.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nTalisScene::TalisScene():\nScene(\"TalisScene\"), test1(nullptr)\n{\n}\n\n\nTalisScene::~TalisScene()\n{\n}\n\nbool TalisScene::initialize() {\n\tusing namespace fractal;\n\tusing namespace fscene;\n\tusing namespace fmath;\n\tusing namespace fgraphics;\n\tterrain = new SceneObject(\"terrain\");\n\n\tterrain->addComponent(new TerrainComponent());\n\n\taddGameObject(terrain);\n\ttest1 = new SceneObject(\"test1\");\n\ttest1->addComponent(new MeshComponent(LoadOBJ::load(\"meshes\/dragon\")));\n\ttest1->addComponent(new fphysics::PhysicsBodyComponent(new fphysics::PhysicsBody()));\n\ttest1->getComponent()->SetAngularVelocity(Vector3(1.0f, 0.0f, 0.0f));\n\ttest1->getComponent()->SetGravityScale(0.0f);\n\tcamera = new FreeCamera(\"MainCamera\");\n\t\/\/camera->addComponent(new MeshComponent(LoadOBJ::load(\"cyl\")));\n\taddGameObject(test1);\n\taddGameObject(camera);\n\treturn Scene::initialize();\n}\n\nvoid TalisScene::update() {\n\n\tusing namespace fractal;\n\tusing namespace fscene;\n\tusing namespace fmath;\n\tusing namespace fgraphics;\n\tScene::update();\n}\n\nbool TalisScene::shutdown() {\n\treturn Scene::shutdown();\n}\n\nvoid TalisScene::setupInput(fractal::fcore::Input * input)\n{\n\tcamera->setupInput(input);\n}\nname of the object changed#include \"TalisScene.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nTalisScene::TalisScene():\nScene(\"TalisScene\"), test1(nullptr)\n{\n}\n\n\nTalisScene::~TalisScene()\n{\n}\n\nbool TalisScene::initialize() {\n\tusing namespace fractal;\n\tusing namespace fscene;\n\tusing namespace fmath;\n\tusing namespace fgraphics;\n\tterrain = new SceneObject(\"terrain\");\n\n\tterrain->addComponent(new TerrainComponent());\n\n\taddGameObject(terrain);\n\ttest1 = new SceneObject(\"test1\");\n\ttest1->addComponent(new MeshComponent(LoadOBJ::load(\"meshes\/cyl\")));\n\ttest1->addComponent(new fphysics::PhysicsBodyComponent(new fphysics::PhysicsBody()));\n\ttest1->getComponent()->SetAngularVelocity(Vector3(1.0f, 0.0f, 0.0f));\n\ttest1->getComponent()->SetGravityScale(0.0f);\n\tcamera = new FreeCamera(\"MainCamera\");\n\t\/\/camera->addComponent(new MeshComponent(LoadOBJ::load(\"cyl\")));\n\taddGameObject(test1);\n\taddGameObject(camera);\n\treturn Scene::initialize();\n}\n\nvoid TalisScene::update() {\n\n\tusing namespace fractal;\n\tusing namespace fscene;\n\tusing namespace fmath;\n\tusing namespace fgraphics;\n\tScene::update();\n}\n\nbool TalisScene::shutdown() {\n\treturn Scene::shutdown();\n}\n\nvoid TalisScene::setupInput(fractal::fcore::Input * input)\n{\n\tcamera->setupInput(input);\n}\n<|endoftext|>"} {"text":"\/\/=================================================================================================\n\/\/ Copyright (C) 2017 Olivier Mallet - All Rights Reserved \n\/\/=================================================================================================\n\n#ifndef GENETICALGORITHM_HPP\n#define GENETICALGORITHM_HPP\n\nnamespace galgo {\n\n\/\/=================================================================================================\n\ntemplate \nclass GeneticAlgorithm\n{\n static_assert(std::is_same::value || std::is_same::value, \"variable type can only be float or double, please amend.\");\n static_assert(N > 0 && N <= 64, \"number of bits cannot be ouside interval [1,64], please choose an integer within this interval.\");\n\n template \n friend class Population;\n template \n friend class Chromosome;\n\n template \n using Func = std::vector (*)(const std::vector&);\n\nprivate:\n Population pop; \/\/ population of chromosomes\n\npublic:\n std::vector lowerBound; \/\/ parameter(s) lower bound\n std::vector upperBound; \/\/ parameter(s) upper bound\n std::vector initialSet; \/\/ initial set of parameter(s)\n\nprivate:\n mutable std::uniform_int_distribution udistrib; \/\/ generate uniform random unsigned long long integers\n static constexpr uint64_t MAXVAL = MAXVALUE::value - 1; \/\/ maximum unsigned integral value obtained from N bits, evaluated at compile time\n \npublic: \n \/\/ objective function pointer\n Func Objective; \n \/\/ selection method functor initialized to roulette wheel selection \n void (*Selection)(Population&) = RWS; \n \/\/ cross-over method functor initialized to 1-point cross-over \n void (*CrossOver)(const Population&, CHR&, CHR&) = P1XO;\n \/\/ mutation method functor initialized to single-point mutation \n void (*Mutation)(CHR&) = SPM; \n \/\/ adaptation to constraint(s) method \n void (*Adaptation)(Population&) = nullptr; \n \/\/ constraint(s) \n std::vector (*Constraint)(const std::vector&) = nullptr; \n\n T covrate = .50; \/\/ cross-over rate\n T mutrate = .05; \/\/ mutation rate \n T SP = 1.5; \/\/ selective pressure for RSP selection method \n T tolerance = 0.0; \/\/ terminal condition (inactive if equal to zero)\n \n int elitpop = 1; \/\/ elit population size\n int matsize; \/\/ mating pool size, set to popsize by default\n int tntsize = 10; \/\/ tournament size\n int genstep = 10; \/\/ generation step for outputting results\n int precision = 5; \/\/ precision for outputting results\n\n \/\/ constructor\n GeneticAlgorithm(Func objective, int popsize, const std::vector& lowerBound, const std::vector& upperBound, int nbgen, bool output = false);\n \/\/ run genetic algorithm\n void run();\n \/\/ return best chromosome \n const CHR& result() const;\n\nprivate:\n int nbgen; \/\/ number of generations\n int nogen = 0; \/\/ numero of generation\n int nbparam; \/\/ number of parameters to be estimated\n int popsize; \/\/ population size\n bool output; \/\/ control if results must be outputted\n\n \/\/ check inputs validity\n bool check() const ;\n \/\/ print results for each new generation\n void print() const;\n};\n\n\/*-------------------------------------------------------------------------------------------------*\/\n \n\/\/ constructor\ntemplate \nGeneticAlgorithm::GeneticAlgorithm(Func objective, int popsize, const std::vector& lowerBound, const std::vector& upperBound, int nbgen, bool output)\n{\n this->Objective = objective;\n this->nbparam = upperBound.size();\n this->popsize = popsize;\n this->matsize = popsize;\n this->lowerBound = lowerBound;\n this->upperBound = upperBound;\n this->nbgen = nbgen;\n this->output = output;\n \/\/ initializing uniform distribution generating random unsigned integers\n udistrib = std::uniform_int_distribution(0, MAXVAL);\n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n\n\/\/ check inputs validity\ntemplate \nbool GeneticAlgorithm::check() const\n{\n if (!initialSet.empty()) {\n for (int i = 0; i < nbparam; ++i) {\n if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\\n\";\n return false;\n }\n }\n if (initialSet.size() != (unsigned)nbparam) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, initial set of parameters (initialSet) does not have the same dimension than the number of parameters, please adjust.\\n\";\n return false;\n }\n }\n if (lowerBound.size() != upperBound.size()) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\\n\";\n return false;\n }\n for (int i = 0; i < nbparam; ++i) {\n if (lowerBound[i] >= upperBound[i]) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\\n\";\n return false;\n }\n }\n if (SP < 1.0 || SP > 2.0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\\n\";\n return false;\n }\n if (elitpop > popsize || elitpop < 0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\\n\";\n return false;\n }\n if (covrate < 0.0 || covrate > 1.0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\\n\";\n return false;\n }\n if (genstep <= 0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\\n\";\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n \n\/\/ run genetic algorithm\ntemplate \nvoid GeneticAlgorithm::run()\n{\n \/\/ checking inputs validity\n if (!check()) {\n return;\n } \n \n \/\/ setting adaptation method to default if needed\n if (Constraint != nullptr && Adaptation == nullptr) {\n Adaptation = DAC;\n }\n\n \/\/ initializing population\n pop = Population(*this);\n\n if (output) {\n std::cout << \"\\n Running Genetic Algorithm...\\n\";\n std::cout << \" ----------------------------\\n\";\n }\n\n \/\/ creating population\n pop.creation();\n \/\/ initializing best result and previous best result\n T bestResult = pop(0)->getTotal();\n T prevBestResult = bestResult;\n \/\/ outputting results \n if (output) print();\n \n \/\/ starting population evolution\n for (nogen = 1; nogen <= nbgen; ++nogen) {\n \/\/ evolving population\n pop.evolution();\n \/\/ getting best current result\n bestResult = pop(0)->getTotal();\n \/\/ outputting results\n if (output) print();\n \/\/ checking convergence\n if (tolerance != 0.0) {\n if (fabs(bestResult - prevBestResult) < fabs(tolerance)) {\n break;\n }\n prevBestResult = bestResult;\n }\n } \n\n \/\/ outputting contraint value\n if (Constraint != nullptr) {\n \/\/ getting best parameter(s) constraint value(s)\n std::vector cst = pop(0)->getConstraint(); \n if (output) {\n std::cout << \"\\n Constraint(s)\\n\";\n std::cout << \" -------------\\n\";\n for (unsigned i = 0; i < cst.size(); ++i) {\n std::cout << \" C\"; \n if (nbparam > 1) {\n std::cout << std::to_string(i + 1);\n }\n std::cout << \"(x) = \" << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << \"\\n\"; \n }\n std::cout << \"\\n\"; \n }\n } \n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n\n\/\/ return best chromosome\ntemplate \ninline const CHR& GeneticAlgorithm::result() const\n{\n return pop(0);\n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n \n\/\/ print results for each new generation\ntemplate \nvoid GeneticAlgorithm::print() const\n{\n \/\/ getting best parameter(s) from best chromosome\n std::vector bestParam = pop(0)->getParam();\n std::vector bestResult = pop(0)->getResult();\n\n if (nogen % genstep == 0) {\n std::cout << \" Generation = \" << std::setw(std::to_string(nbgen).size()) << nogen << \" |\";\n for (int i = 0; i < nbparam; ++i) {\n\t std::cout << \" X\";\n if (nbparam > 1) {\n std::cout << std::to_string(i + 1);\n }\n std::cout << \" = \" << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << \" |\";\n\t }\n for (unsigned i = 0; i < bestResult.size(); ++i) {\n\t std::cout << \" F\";\n if (bestResult.size() > 1) {\n std::cout << std::to_string(i + 1);\n }\n std::cout << \"(x) = \" << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i];\n if (i < bestResult.size() - 1) {\n std::cout << \" |\";\n } else {\n std::cout << \"\\n\";\n }\n\t }\n \n }\n}\n \n\/\/=================================================================================================\n\n}\n\n#endif\nUpdate GeneticAlgorithm.hpp\/\/=================================================================================================\n\/\/ Copyright (C) 2017 Olivier Mallet - All Rights Reserved \n\/\/=================================================================================================\n\n#ifndef GENETICALGORITHM_HPP\n#define GENETICALGORITHM_HPP\n\nnamespace galgo {\n\n\/\/=================================================================================================\n\ntemplate \nclass GeneticAlgorithm\n{\n static_assert(std::is_same::value || std::is_same::value, \"variable type can only be float or double, please amend.\");\n static_assert(N > 0 && N <= 64, \"number of bits cannot be ouside interval [1,64], please choose an integer within this interval.\");\n\n template \n friend class Population;\n template \n friend class Chromosome;\n\n template \n using Func = std::vector (*)(const std::vector&);\n\nprivate:\n Population pop; \/\/ population of chromosomes\n\npublic:\n std::vector lowerBound; \/\/ parameter(s) lower bound\n std::vector upperBound; \/\/ parameter(s) upper bound\n std::vector initialSet; \/\/ initial set of parameter(s)\n\nprivate:\n mutable std::uniform_int_distribution udistrib; \/\/ generate uniform random unsigned long long integers\n static constexpr uint64_t MAXVAL = MAXVALUE::value - 1; \/\/ maximum unsigned integral value obtained from N bits, evaluated at compile time\n \npublic: \n \/\/ objective function pointer\n Func Objective; \n \/\/ selection method initialized to roulette wheel selection \n void (*Selection)(Population&) = RWS; \n \/\/ cross-over method initialized to 1-point cross-over \n void (*CrossOver)(const Population&, CHR&, CHR&) = P1XO;\n \/\/ mutation method initialized to single-point mutation \n void (*Mutation)(CHR&) = SPM; \n \/\/ adaptation to constraint(s) method \n void (*Adaptation)(Population&) = nullptr; \n \/\/ constraint(s) \n std::vector (*Constraint)(const std::vector&) = nullptr; \n\n T covrate = .50; \/\/ cross-over rate\n T mutrate = .05; \/\/ mutation rate \n T SP = 1.5; \/\/ selective pressure for RSP selection method \n T tolerance = 0.0; \/\/ terminal condition (inactive if equal to zero)\n \n int elitpop = 1; \/\/ elit population size\n int matsize; \/\/ mating pool size, set to popsize by default\n int tntsize = 10; \/\/ tournament size\n int genstep = 10; \/\/ generation step for outputting results\n int precision = 5; \/\/ precision for outputting results\n\n \/\/ constructor\n GeneticAlgorithm(Func objective, int popsize, const std::vector& lowerBound, const std::vector& upperBound, int nbgen, bool output = false);\n \/\/ run genetic algorithm\n void run();\n \/\/ return best chromosome \n const CHR& result() const;\n\nprivate:\n int nbgen; \/\/ number of generations\n int nogen = 0; \/\/ numero of generation\n int nbparam; \/\/ number of parameters to be estimated\n int popsize; \/\/ population size\n bool output; \/\/ control if results must be outputted\n\n \/\/ check inputs validity\n bool check() const ;\n \/\/ print results for each new generation\n void print() const;\n};\n\n\/*-------------------------------------------------------------------------------------------------*\/\n \n\/\/ constructor\ntemplate \nGeneticAlgorithm::GeneticAlgorithm(Func objective, int popsize, const std::vector& lowerBound, const std::vector& upperBound, int nbgen, bool output)\n{\n this->Objective = objective;\n this->nbparam = upperBound.size();\n this->popsize = popsize;\n this->matsize = popsize;\n this->lowerBound = lowerBound;\n this->upperBound = upperBound;\n this->nbgen = nbgen;\n this->output = output;\n \/\/ initializing uniform distribution generating random unsigned integers\n udistrib = std::uniform_int_distribution(0, MAXVAL);\n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n\n\/\/ check inputs validity\ntemplate \nbool GeneticAlgorithm::check() const\n{\n if (!initialSet.empty()) {\n for (int i = 0; i < nbparam; ++i) {\n if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\\n\";\n return false;\n }\n }\n if (initialSet.size() != (unsigned)nbparam) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, initial set of parameters (initialSet) does not have the same dimension than the number of parameters, please adjust.\\n\";\n return false;\n }\n }\n if (lowerBound.size() != upperBound.size()) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\\n\";\n return false;\n }\n for (int i = 0; i < nbparam; ++i) {\n if (lowerBound[i] >= upperBound[i]) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\\n\";\n return false;\n }\n }\n if (SP < 1.0 || SP > 2.0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\\n\";\n return false;\n }\n if (elitpop > popsize || elitpop < 0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\\n\";\n return false;\n }\n if (covrate < 0.0 || covrate > 1.0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\\n\";\n return false;\n }\n if (genstep <= 0) {\n std::cerr << \" Error: in class galgo::GeneticAlgorithm, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\\n\";\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n \n\/\/ run genetic algorithm\ntemplate \nvoid GeneticAlgorithm::run()\n{\n \/\/ checking inputs validity\n if (!check()) {\n return;\n } \n \n \/\/ setting adaptation method to default if needed\n if (Constraint != nullptr && Adaptation == nullptr) {\n Adaptation = DAC;\n }\n\n \/\/ initializing population\n pop = Population(*this);\n\n if (output) {\n std::cout << \"\\n Running Genetic Algorithm...\\n\";\n std::cout << \" ----------------------------\\n\";\n }\n\n \/\/ creating population\n pop.creation();\n \/\/ initializing best result and previous best result\n T bestResult = pop(0)->getTotal();\n T prevBestResult = bestResult;\n \/\/ outputting results \n if (output) print();\n \n \/\/ starting population evolution\n for (nogen = 1; nogen <= nbgen; ++nogen) {\n \/\/ evolving population\n pop.evolution();\n \/\/ getting best current result\n bestResult = pop(0)->getTotal();\n \/\/ outputting results\n if (output) print();\n \/\/ checking convergence\n if (tolerance != 0.0) {\n if (fabs(bestResult - prevBestResult) < fabs(tolerance)) {\n break;\n }\n prevBestResult = bestResult;\n }\n } \n\n \/\/ outputting contraint value\n if (Constraint != nullptr) {\n \/\/ getting best parameter(s) constraint value(s)\n std::vector cst = pop(0)->getConstraint(); \n if (output) {\n std::cout << \"\\n Constraint(s)\\n\";\n std::cout << \" -------------\\n\";\n for (unsigned i = 0; i < cst.size(); ++i) {\n std::cout << \" C\"; \n if (nbparam > 1) {\n std::cout << std::to_string(i + 1);\n }\n std::cout << \"(x) = \" << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << \"\\n\"; \n }\n std::cout << \"\\n\"; \n }\n } \n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n\n\/\/ return best chromosome\ntemplate \ninline const CHR& GeneticAlgorithm::result() const\n{\n return pop(0);\n}\n\n\/*-------------------------------------------------------------------------------------------------*\/\n \n\/\/ print results for each new generation\ntemplate \nvoid GeneticAlgorithm::print() const\n{\n \/\/ getting best parameter(s) from best chromosome\n std::vector bestParam = pop(0)->getParam();\n std::vector bestResult = pop(0)->getResult();\n\n if (nogen % genstep == 0) {\n std::cout << \" Generation = \" << std::setw(std::to_string(nbgen).size()) << nogen << \" |\";\n for (int i = 0; i < nbparam; ++i) {\n\t std::cout << \" X\";\n if (nbparam > 1) {\n std::cout << std::to_string(i + 1);\n }\n std::cout << \" = \" << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << \" |\";\n\t }\n for (unsigned i = 0; i < bestResult.size(); ++i) {\n\t std::cout << \" F\";\n if (bestResult.size() > 1) {\n std::cout << std::to_string(i + 1);\n }\n std::cout << \"(x) = \" << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i];\n if (i < bestResult.size() - 1) {\n std::cout << \" |\";\n } else {\n std::cout << \"\\n\";\n }\n\t }\n \n }\n}\n \n\/\/=================================================================================================\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ @(#)root\/proofplayer:$Id$\n\/\/ Author: Long Tran-Thanh 22\/07\/07\n\n\/*************************************************************************\n * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TPacketizerUnit \/\/\n\/\/ \/\/\n\/\/ This packetizer generates packets of generic units, representing the \/\/\n\/\/ number of times an operation cycle has to be repeated by the worker \/\/\n\/\/ node, e.g. the number of Monte carlo events to be generated. \/\/\n\/\/ Packets sizes are generated taking into account the performance of \/\/\n\/\/ worker nodes, based on the time needed to process previous packets. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"TPacketizerUnit.h\"\n\n#include \"Riostream.h\"\n#include \"TDSet.h\"\n#include \"TError.h\"\n#include \"TEventList.h\"\n#include \"TMap.h\"\n#include \"TMessage.h\"\n#include \"TMonitor.h\"\n#include \"TNtupleD.h\"\n#include \"TObject.h\"\n#include \"TParameter.h\"\n#include \"TPerfStats.h\"\n#include \"TProofDebug.h\"\n#include \"TProof.h\"\n#include \"TProofPlayer.h\"\n#include \"TProofServ.h\"\n#include \"TSlave.h\"\n#include \"TSocket.h\"\n#include \"TStopwatch.h\"\n#include \"TTimer.h\"\n#include \"TUrl.h\"\n#include \"TClass.h\"\n#include \"TMath.h\"\n#include \"TObjString.h\"\n\n\nusing namespace TMath;\n\/\/\n\/\/ The following utility class manage the state of the\n\/\/ work to be performed and the slaves involved in the process.\n\/\/\n\/\/ The list of TSlaveStat(s) keep track of the work (being) done\n\/\/ by each slave\n\/\/\n\n\/\/------------------------------------------------------------------------------\n\nclass TPacketizerUnit::TSlaveStat : public TObject {\n\nfriend class TPacketizerUnit;\n\nprivate:\n TSlave *fSlave; \/\/ corresponding TSlave record\n Long64_t fProcessed; \/\/ number of entries processed\n Long64_t fLastProcessed; \/\/ number of processed entries of the last packet\n Double_t fSpeed; \/\/ estimated current average speed of the processing slave\n Double_t fTimeInstant; \/\/ stores the time instant when the current packet started\n TNtupleD *fCircNtp; \/\/ Keeps circular info for speed calculations\n Long_t fCircLvl; \/\/ Circularity level\n\n\npublic:\n TSlaveStat(TSlave *sl, TList *input);\n ~TSlaveStat();\n\n void GetCurrentTime();\n\n const char *GetName() const { return fSlave->GetName(); }\n Long64_t GetEntriesProcessed() const { return fProcessed; }\n\n void UpdatePerformance(Double_t time);\n};\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::TSlaveStat::TSlaveStat(TSlave *slave, TList *input)\n : fSlave(slave), fProcessed(0), fLastProcessed(0),\n fSpeed(0), fTimeInstant(0), fCircLvl(5)\n{\n \/\/ Main constructor\n\n \/\/ Initialize the circularity ntple for speed calculations\n fCircNtp = new TNtupleD(\"Speed Circ Ntp\", \"Circular process info\",\"tm:ev\");\n TProof::GetParameter(input, \"PROOF_TPacketizerUnitCircularity\", fCircLvl);\n fCircLvl = (fCircLvl > 0) ? fCircLvl : 5;\n fCircNtp->SetCircular(fCircLvl);\n}\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::TSlaveStat::~TSlaveStat()\n{\n \/\/ Destructor\n\n SafeDelete(fCircNtp);\n}\n\n\/\/______________________________________________________________________________\nvoid TPacketizerUnit::TSlaveStat::UpdatePerformance(Double_t time)\n{\n \/\/ Update the circular ntple\n\n Double_t ttot = time;\n Double_t *ar = fCircNtp->GetArgs();\n Int_t ne = fCircNtp->GetEntries();\n if (ne <= 0) {\n \/\/ First call: just fill one ref entry and return\n fCircNtp->Fill(0., 0);\n fSpeed = 0.;\n return;\n }\n \/\/ Fill the entry\n fCircNtp->GetEntry(ne-1);\n ttot = ar[0] + time;\n fCircNtp->Fill(ttot, fProcessed);\n\n \/\/ Calculate the speed\n fCircNtp->GetEntry(0);\n Double_t dtime = (ttot > ar[0]) ? ttot - ar[0] : ne+1 ;\n Long64_t nevts = fProcessed - (Long64_t)ar[1];\n fSpeed = nevts \/ dtime;\n PDB(kPacketizer,2)\n Info(\"UpdatePerformance\", \"time:%f, dtime:%f, nevts:%lld, speed: %f\",\n time, dtime, nevts, fSpeed);\n\n}\n\n\/\/------------------------------------------------------------------------------\n\nClassImp(TPacketizerUnit)\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::TPacketizerUnit(TList *slaves, Long64_t num, TList *input,\n TProofProgressStatus *st)\n : TVirtualPacketizer(input, st)\n{\n \/\/ Constructor\n\n PDB(kPacketizer,1) Info(\"TPacketizerUnit\", \"enter (num %lld)\", num);\n\n \/\/ Init pointer members\n fSlaveStats = 0;\n fPackets = 0;\n\n fTimeLimit = 1;\n TProof::GetParameter(input, \"PROOF_PacketizerTimeLimit\", fTimeLimit);\n PDB(kPacketizer,1)\n Info(\"TPacketizerUnit\", \"time limit is %lf\", fTimeLimit);\n fProcessing = 0;\n\n fStopwatch = new TStopwatch();\n\n fPackets = new TList;\n fPackets->SetOwner();\n\n fSlaveStats = new TMap;\n fSlaveStats->SetOwner(kFALSE);\n\n TSlave *slave;\n TIter si(slaves);\n while ((slave = (TSlave*) si.Next()))\n fSlaveStats->Add(slave, new TSlaveStat(slave, input));\n\n fTotalEntries = num;\n\n fStopwatch->Start();\n PDB(kPacketizer,1) Info(\"TPacketizerUnit\", \"return\");\n}\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::~TPacketizerUnit()\n{\n \/\/ Destructor.\n\n if (fSlaveStats)\n fSlaveStats->DeleteValues();\n SafeDelete(fSlaveStats);\n SafeDelete(fPackets);\n SafeDelete(fStopwatch);\n}\n\n\/\/______________________________________________________________________________\nDouble_t TPacketizerUnit::GetCurrentTime()\n{\n \/\/ Get current time\n\n Double_t retValue = fStopwatch->RealTime();\n fStopwatch->Continue();\n return retValue;\n}\n\n\/\/______________________________________________________________________________\nTDSetElement *TPacketizerUnit::GetNextPacket(TSlave *sl, TMessage *r)\n{\n \/\/ Get next packet\n\n if (!fValid)\n return 0;\n\n \/\/ Find slave\n TSlaveStat *slstat = (TSlaveStat*) fSlaveStats->GetValue(sl);\n R__ASSERT(slstat != 0);\n\n \/\/ Update stats & free old element\n Double_t latency, proctime, proccpu;\n Long64_t bytesRead = -1;\n Long64_t totalEntries = -1;\n Long64_t totev = 0;\n Long64_t numev = -1;\n\n if (!gProofServ || gProofServ->GetProtocol() > 18) {\n TProofProgressStatus *status = 0;\n (*r) >> latency;\n (*r) >> status;\n\n proctime = status ? status->GetProcTime() : -1.;\n proccpu = status ? status->GetCPUTime() : -1.;\n totev = status ? status->GetEntries() : 0;\n bytesRead = status ? status->GetBytesRead() : 0;\n\n delete status;\n } else {\n\n (*r) >> latency >> proctime >> proccpu;\n\n \/\/ only read new info if available\n if (r->BufferSize() > r->Length()) (*r) >> bytesRead;\n if (r->BufferSize() > r->Length()) (*r) >> totalEntries;\n if (r->BufferSize() > r->Length()) (*r) >> totev;\n }\n numev = totev - slstat->fProcessed;\n\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\",\"worker-%s: fProcessed %lld\\t\", sl->GetOrdinal(), GetEntriesProcessed());\n fProcessing = 0;\n\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\",\"worker-%s (%s): %lld %7.3lf %7.3lf %7.3lf %lld\",\n sl->GetOrdinal(), sl->GetName(),\n numev, latency, proctime, proccpu, bytesRead);\n\n if (gPerfStats != 0) {\n gPerfStats->PacketEvent(sl->GetOrdinal(), sl->GetName(), \"\", numev,\n latency, proctime, proccpu, bytesRead);\n }\n\n if (GetEntriesProcessed() == fTotalEntries) {\n \/\/ Send last timer message\n HandleTimer(0);\n SafeDelete(fProgress);\n }\n\n if (fStop) {\n \/\/ Send last timer message\n HandleTimer(0);\n return 0;\n }\n\n\n Long64_t num;\n\n \/\/ Get the current time\n Double_t cTime = GetCurrentTime();\n\n if (slstat->fCircNtp->GetEntries() <= 0) {\n \/\/ The calibration phase\n PDB(kPacketizer,2) Info(\"GetNextPacket\",\" calibration: \"\n \"total entries %lld, workers %d\",\n fTotalEntries, fSlaveStats->GetSize());\n Long64_t avg = fTotalEntries\/(fSlaveStats->GetSize());\n num = (avg > 5) ? 5 : avg;\n\n \/\/ Create a reference entry\n slstat->UpdatePerformance(0.);\n\n } else {\n \/\/ Schedule tasks for workers based on the currently estimated processing speeds\n\n \/\/ Update worker stats and performances\n slstat->fProcessed += slstat->fLastProcessed;\n slstat->UpdatePerformance(proctime);\n\n TMapIter *iter = (TMapIter *)fSlaveStats->MakeIterator();\n TSlave * tmpSlave;\n TSlaveStat * tmpStat;\n\n Double_t sumSpeed = 0;\n Double_t sumBusy = 0;\n\n \/\/ The basic idea is to estimate the optimal finishing time for the process, assuming\n \/\/ that the currently measured processing speeds of the slaves remain the same in the future.\n \/\/ The optTime can be calculated as follows.\n \/\/ Let s_i be the speed of worker i. We assume that worker i will be busy in the\n \/\/ next b_i time instant. Therefore we have the following equation:\n \/\/ SUM((optTime-b_i)*s_i) = (remaining_entries),\n \/\/ Hence optTime can be calculated easily:\n \/\/ optTime = ((remaining_entries) + SUM(b_i*s_i))\/SUM(s_i)\n\n while ((tmpSlave = (TSlave *)iter->Next())) {\n tmpStat = (TSlaveStat *)fSlaveStats->GetValue(tmpSlave);\n \/\/ If the slave doesn't response for a long time, its service rate will be considered as 0\n if ((cTime - tmpStat->fTimeInstant) > 4*fTimeLimit)\n tmpStat->fSpeed = 0;\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\",\n \"worker-%s: speed %lf\", tmpSlave->GetOrdinal(), tmpStat->fSpeed);\n if (tmpStat->fSpeed > 0) {\n \/\/ Calculating the SUM(s_i)\n sumSpeed += tmpStat->fSpeed;\n \/\/ There is nothing to do if slave_i is not calibrated or slave i is the current slave\n if ((tmpStat->fTimeInstant) && (cTime - tmpStat->fTimeInstant > 0)) {\n \/\/ Calculating the SUM(b_i*s_i)\n \/\/ s_i = tmpStat->fSpeed\n \/\/ b_i = tmpStat->fTimeInstant + tmpStat->fLastProcessed\/s_i - cTime)\n \/\/ b_i*s_i = (tmpStat->fTimeInstant - cTime)*s_i + tmpStat->fLastProcessed\n Double_t busyspeed =\n ((tmpStat->fTimeInstant - cTime)*tmpStat->fSpeed + tmpStat->fLastProcessed);\n if (busyspeed > 0)\n sumBusy += busyspeed;\n }\n }\n }\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\", \"worker-%s: sum speed: %lf, sum busy: %f\",\n sl->GetOrdinal(), sumSpeed, sumBusy);\n \/\/ firstly the slave will try to get all of the remaining entries\n if (slstat->fSpeed > 0 &&\n (fTotalEntries - GetEntriesProcessed())\/(slstat->fSpeed) < fTimeLimit) {\n num = (fTotalEntries - GetEntriesProcessed());\n } else {\n if (slstat->fSpeed > 0) {\n \/\/ calculating the optTime\n Double_t optTime = (fTotalEntries - GetEntriesProcessed() + sumBusy)\/sumSpeed;\n \/\/ if optTime is greater than the official time limit, then the slave gets a number\n \/\/ of entries that still fit into the time limit, otherwise it uses the optTime as\n \/\/ a time limit\n num = (optTime > fTimeLimit) ? Nint(fTimeLimit*(slstat->fSpeed))\n : Nint(optTime*(slstat->fSpeed));\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\", \"opTime %lf num %lld\", optTime, num);\n } else {\n Long64_t avg = fTotalEntries\/(fSlaveStats->GetSize());\n num = (avg > 5) ? 5 : avg;\n }\n }\n }\n fProcessing = (num < (fTotalEntries - GetEntriesProcessed())) ? num : (fTotalEntries - GetEntriesProcessed());\n\n \/\/ Set the informations of the current slave\n slstat->fLastProcessed = fProcessing;\n \/\/ Set the start time of the current packet\n slstat->fTimeInstant = cTime;\n\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\", \"worker-%s: num %lld, processing %lld, remaining %lld\",sl->GetOrdinal(),\n num, fProcessing, (fTotalEntries - GetEntriesProcessed() - fProcessing));\n TDSetElement *elem = new TDSetElement(\"\", \"\", \"\", 0, fProcessing);\n elem->SetBit(TDSetElement::kEmpty);\n\n \/\/ Update the total counter\n fProgressStatus->IncEntries(slstat->fLastProcessed);\n\n return elem;\n}\nMake sure that the packet contains at least 1 event\/\/ @(#)root\/proofplayer:$Id$\n\/\/ Author: Long Tran-Thanh 22\/07\/07\n\n\/*************************************************************************\n * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TPacketizerUnit \/\/\n\/\/ \/\/\n\/\/ This packetizer generates packets of generic units, representing the \/\/\n\/\/ number of times an operation cycle has to be repeated by the worker \/\/\n\/\/ node, e.g. the number of Monte carlo events to be generated. \/\/\n\/\/ Packets sizes are generated taking into account the performance of \/\/\n\/\/ worker nodes, based on the time needed to process previous packets. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"TPacketizerUnit.h\"\n\n#include \"Riostream.h\"\n#include \"TDSet.h\"\n#include \"TError.h\"\n#include \"TEventList.h\"\n#include \"TMap.h\"\n#include \"TMessage.h\"\n#include \"TMonitor.h\"\n#include \"TNtupleD.h\"\n#include \"TObject.h\"\n#include \"TParameter.h\"\n#include \"TPerfStats.h\"\n#include \"TProofDebug.h\"\n#include \"TProof.h\"\n#include \"TProofPlayer.h\"\n#include \"TProofServ.h\"\n#include \"TSlave.h\"\n#include \"TSocket.h\"\n#include \"TStopwatch.h\"\n#include \"TTimer.h\"\n#include \"TUrl.h\"\n#include \"TClass.h\"\n#include \"TMath.h\"\n#include \"TObjString.h\"\n\n\nusing namespace TMath;\n\/\/\n\/\/ The following utility class manage the state of the\n\/\/ work to be performed and the slaves involved in the process.\n\/\/\n\/\/ The list of TSlaveStat(s) keep track of the work (being) done\n\/\/ by each slave\n\/\/\n\n\/\/------------------------------------------------------------------------------\n\nclass TPacketizerUnit::TSlaveStat : public TObject {\n\nfriend class TPacketizerUnit;\n\nprivate:\n TSlave *fSlave; \/\/ corresponding TSlave record\n Long64_t fProcessed; \/\/ number of entries processed\n Long64_t fLastProcessed; \/\/ number of processed entries of the last packet\n Double_t fSpeed; \/\/ estimated current average speed of the processing slave\n Double_t fTimeInstant; \/\/ stores the time instant when the current packet started\n TNtupleD *fCircNtp; \/\/ Keeps circular info for speed calculations\n Long_t fCircLvl; \/\/ Circularity level\n\n\npublic:\n TSlaveStat(TSlave *sl, TList *input);\n ~TSlaveStat();\n\n void GetCurrentTime();\n\n const char *GetName() const { return fSlave->GetName(); }\n Long64_t GetEntriesProcessed() const { return fProcessed; }\n\n void UpdatePerformance(Double_t time);\n};\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::TSlaveStat::TSlaveStat(TSlave *slave, TList *input)\n : fSlave(slave), fProcessed(0), fLastProcessed(0),\n fSpeed(0), fTimeInstant(0), fCircLvl(5)\n{\n \/\/ Main constructor\n\n \/\/ Initialize the circularity ntple for speed calculations\n fCircNtp = new TNtupleD(\"Speed Circ Ntp\", \"Circular process info\",\"tm:ev\");\n TProof::GetParameter(input, \"PROOF_TPacketizerUnitCircularity\", fCircLvl);\n fCircLvl = (fCircLvl > 0) ? fCircLvl : 5;\n fCircNtp->SetCircular(fCircLvl);\n}\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::TSlaveStat::~TSlaveStat()\n{\n \/\/ Destructor\n\n SafeDelete(fCircNtp);\n}\n\n\/\/______________________________________________________________________________\nvoid TPacketizerUnit::TSlaveStat::UpdatePerformance(Double_t time)\n{\n \/\/ Update the circular ntple\n\n Double_t ttot = time;\n Double_t *ar = fCircNtp->GetArgs();\n Int_t ne = fCircNtp->GetEntries();\n if (ne <= 0) {\n \/\/ First call: just fill one ref entry and return\n fCircNtp->Fill(0., 0);\n fSpeed = 0.;\n return;\n }\n \/\/ Fill the entry\n fCircNtp->GetEntry(ne-1);\n ttot = ar[0] + time;\n fCircNtp->Fill(ttot, fProcessed);\n\n \/\/ Calculate the speed\n fCircNtp->GetEntry(0);\n Double_t dtime = (ttot > ar[0]) ? ttot - ar[0] : ne+1 ;\n Long64_t nevts = fProcessed - (Long64_t)ar[1];\n fSpeed = nevts \/ dtime;\n PDB(kPacketizer,2)\n Info(\"UpdatePerformance\", \"time:%f, dtime:%f, nevts:%lld, speed: %f\",\n time, dtime, nevts, fSpeed);\n\n}\n\n\/\/------------------------------------------------------------------------------\n\nClassImp(TPacketizerUnit)\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::TPacketizerUnit(TList *slaves, Long64_t num, TList *input,\n TProofProgressStatus *st)\n : TVirtualPacketizer(input, st)\n{\n \/\/ Constructor\n\n PDB(kPacketizer,1) Info(\"TPacketizerUnit\", \"enter (num %lld)\", num);\n\n \/\/ Init pointer members\n fSlaveStats = 0;\n fPackets = 0;\n\n fTimeLimit = 1;\n TProof::GetParameter(input, \"PROOF_PacketizerTimeLimit\", fTimeLimit);\n PDB(kPacketizer,1)\n Info(\"TPacketizerUnit\", \"time limit is %lf\", fTimeLimit);\n fProcessing = 0;\n\n fStopwatch = new TStopwatch();\n\n fPackets = new TList;\n fPackets->SetOwner();\n\n fSlaveStats = new TMap;\n fSlaveStats->SetOwner(kFALSE);\n\n TSlave *slave;\n TIter si(slaves);\n while ((slave = (TSlave*) si.Next()))\n fSlaveStats->Add(slave, new TSlaveStat(slave, input));\n\n fTotalEntries = num;\n\n fStopwatch->Start();\n PDB(kPacketizer,1) Info(\"TPacketizerUnit\", \"return\");\n}\n\n\/\/______________________________________________________________________________\nTPacketizerUnit::~TPacketizerUnit()\n{\n \/\/ Destructor.\n\n if (fSlaveStats)\n fSlaveStats->DeleteValues();\n SafeDelete(fSlaveStats);\n SafeDelete(fPackets);\n SafeDelete(fStopwatch);\n}\n\n\/\/______________________________________________________________________________\nDouble_t TPacketizerUnit::GetCurrentTime()\n{\n \/\/ Get current time\n\n Double_t retValue = fStopwatch->RealTime();\n fStopwatch->Continue();\n return retValue;\n}\n\n\/\/______________________________________________________________________________\nTDSetElement *TPacketizerUnit::GetNextPacket(TSlave *sl, TMessage *r)\n{\n \/\/ Get next packet\n\n if (!fValid)\n return 0;\n\n \/\/ Find slave\n TSlaveStat *slstat = (TSlaveStat*) fSlaveStats->GetValue(sl);\n R__ASSERT(slstat != 0);\n\n \/\/ Update stats & free old element\n Double_t latency, proctime, proccpu;\n Long64_t bytesRead = -1;\n Long64_t totalEntries = -1;\n Long64_t totev = 0;\n Long64_t numev = -1;\n\n if (!gProofServ || gProofServ->GetProtocol() > 18) {\n TProofProgressStatus *status = 0;\n (*r) >> latency;\n (*r) >> status;\n\n proctime = status ? status->GetProcTime() : -1.;\n proccpu = status ? status->GetCPUTime() : -1.;\n totev = status ? status->GetEntries() : 0;\n bytesRead = status ? status->GetBytesRead() : 0;\n\n delete status;\n } else {\n\n (*r) >> latency >> proctime >> proccpu;\n\n \/\/ only read new info if available\n if (r->BufferSize() > r->Length()) (*r) >> bytesRead;\n if (r->BufferSize() > r->Length()) (*r) >> totalEntries;\n if (r->BufferSize() > r->Length()) (*r) >> totev;\n }\n numev = totev - slstat->fProcessed;\n\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\",\"worker-%s: fProcessed %lld\\t\", sl->GetOrdinal(), GetEntriesProcessed());\n fProcessing = 0;\n\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\",\"worker-%s (%s): %lld %7.3lf %7.3lf %7.3lf %lld\",\n sl->GetOrdinal(), sl->GetName(),\n numev, latency, proctime, proccpu, bytesRead);\n\n if (gPerfStats != 0) {\n gPerfStats->PacketEvent(sl->GetOrdinal(), sl->GetName(), \"\", numev,\n latency, proctime, proccpu, bytesRead);\n }\n\n if (GetEntriesProcessed() == fTotalEntries) {\n \/\/ Send last timer message\n HandleTimer(0);\n SafeDelete(fProgress);\n }\n\n if (fStop) {\n \/\/ Send last timer message\n HandleTimer(0);\n return 0;\n }\n\n\n Long64_t num;\n\n \/\/ Get the current time\n Double_t cTime = GetCurrentTime();\n\n if (slstat->fCircNtp->GetEntries() <= 0) {\n \/\/ The calibration phase\n PDB(kPacketizer,2) Info(\"GetNextPacket\",\" calibration: \"\n \"total entries %lld, workers %d\",\n fTotalEntries, fSlaveStats->GetSize());\n Long64_t avg = fTotalEntries\/(fSlaveStats->GetSize());\n num = (avg > 5) ? 5 : avg;\n\n \/\/ Create a reference entry\n slstat->UpdatePerformance(0.);\n\n } else {\n \/\/ Schedule tasks for workers based on the currently estimated processing speeds\n\n \/\/ Update worker stats and performances\n slstat->fProcessed += slstat->fLastProcessed;\n slstat->UpdatePerformance(proctime);\n\n TMapIter *iter = (TMapIter *)fSlaveStats->MakeIterator();\n TSlave * tmpSlave;\n TSlaveStat * tmpStat;\n\n Double_t sumSpeed = 0;\n Double_t sumBusy = 0;\n\n \/\/ The basic idea is to estimate the optimal finishing time for the process, assuming\n \/\/ that the currently measured processing speeds of the slaves remain the same in the future.\n \/\/ The optTime can be calculated as follows.\n \/\/ Let s_i be the speed of worker i. We assume that worker i will be busy in the\n \/\/ next b_i time instant. Therefore we have the following equation:\n \/\/ SUM((optTime-b_i)*s_i) = (remaining_entries),\n \/\/ Hence optTime can be calculated easily:\n \/\/ optTime = ((remaining_entries) + SUM(b_i*s_i))\/SUM(s_i)\n\n while ((tmpSlave = (TSlave *)iter->Next())) {\n tmpStat = (TSlaveStat *)fSlaveStats->GetValue(tmpSlave);\n \/\/ If the slave doesn't response for a long time, its service rate will be considered as 0\n if ((cTime - tmpStat->fTimeInstant) > 4*fTimeLimit)\n tmpStat->fSpeed = 0;\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\",\n \"worker-%s: speed %lf\", tmpSlave->GetOrdinal(), tmpStat->fSpeed);\n if (tmpStat->fSpeed > 0) {\n \/\/ Calculating the SUM(s_i)\n sumSpeed += tmpStat->fSpeed;\n \/\/ There is nothing to do if slave_i is not calibrated or slave i is the current slave\n if ((tmpStat->fTimeInstant) && (cTime - tmpStat->fTimeInstant > 0)) {\n \/\/ Calculating the SUM(b_i*s_i)\n \/\/ s_i = tmpStat->fSpeed\n \/\/ b_i = tmpStat->fTimeInstant + tmpStat->fLastProcessed\/s_i - cTime)\n \/\/ b_i*s_i = (tmpStat->fTimeInstant - cTime)*s_i + tmpStat->fLastProcessed\n Double_t busyspeed =\n ((tmpStat->fTimeInstant - cTime)*tmpStat->fSpeed + tmpStat->fLastProcessed);\n if (busyspeed > 0)\n sumBusy += busyspeed;\n }\n }\n }\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\", \"worker-%s: sum speed: %lf, sum busy: %f\",\n sl->GetOrdinal(), sumSpeed, sumBusy);\n \/\/ firstly the slave will try to get all of the remaining entries\n if (slstat->fSpeed > 0 &&\n (fTotalEntries - GetEntriesProcessed())\/(slstat->fSpeed) < fTimeLimit) {\n num = (fTotalEntries - GetEntriesProcessed());\n } else {\n if (slstat->fSpeed > 0) {\n \/\/ calculating the optTime\n Double_t optTime = (fTotalEntries - GetEntriesProcessed() + sumBusy)\/sumSpeed;\n \/\/ if optTime is greater than the official time limit, then the slave gets a number\n \/\/ of entries that still fit into the time limit, otherwise it uses the optTime as\n \/\/ a time limit\n num = (optTime > fTimeLimit) ? Nint(fTimeLimit*(slstat->fSpeed))\n : Nint(optTime*(slstat->fSpeed));\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\", \"opTime %lf num %lld speed %lf\", optTime, num, slstat->fSpeed);\n } else {\n Long64_t avg = fTotalEntries\/(fSlaveStats->GetSize());\n num = (avg > 5) ? 5 : avg;\n }\n }\n }\n num = (num > 1) ? num : 1;\n fProcessing = (num < (fTotalEntries - GetEntriesProcessed())) ? num : (fTotalEntries - GetEntriesProcessed());\n\n \/\/ Set the informations of the current slave\n slstat->fLastProcessed = fProcessing;\n \/\/ Set the start time of the current packet\n slstat->fTimeInstant = cTime;\n\n PDB(kPacketizer,2)\n Info(\"GetNextPacket\", \"worker-%s: num %lld, processing %lld, remaining %lld\",sl->GetOrdinal(),\n num, fProcessing, (fTotalEntries - GetEntriesProcessed() - fProcessing));\n TDSetElement *elem = new TDSetElement(\"\", \"\", \"\", 0, fProcessing);\n elem->SetBit(TDSetElement::kEmpty);\n\n \/\/ Update the total counter\n fProgressStatus->IncEntries(slstat->fLastProcessed);\n\n return elem;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/developers.google.com\/open-source\/licenses\/bsd\n\n#include \"packager\/media\/event\/vod_media_info_dump_muxer_listener.h\"\n\n#include \n\n#include \"packager\/base\/logging.h\"\n#include \"packager\/media\/base\/muxer_options.h\"\n#include \"packager\/media\/base\/stream_info.h\"\n#include \"packager\/media\/event\/muxer_listener_internal.h\"\n#include \"packager\/media\/file\/file.h\"\n#include \"packager\/mpd\/base\/media_info.pb.h\"\n\nnamespace edash_packager {\nnamespace media {\nnamespace event {\n\nVodMediaInfoDumpMuxerListener::VodMediaInfoDumpMuxerListener(\n const std::string& output_file_name)\n : output_file_name_(output_file_name) {}\n\nVodMediaInfoDumpMuxerListener::~VodMediaInfoDumpMuxerListener() {}\n\nvoid VodMediaInfoDumpMuxerListener::SetContentProtectionSchemeIdUri(\n const std::string& scheme_id_uri) {\n scheme_id_uri_ = scheme_id_uri;\n}\n\nvoid VodMediaInfoDumpMuxerListener::OnMediaStart(\n const MuxerOptions& muxer_options,\n const std::vector& stream_infos,\n uint32_t time_scale,\n ContainerType container_type,\n bool is_encrypted) {\n DCHECK(muxer_options.single_segment);\n media_info_.reset(new MediaInfo());\n if (!internal::GenerateMediaInfo(muxer_options,\n stream_infos,\n time_scale,\n container_type,\n media_info_.get())) {\n LOG(ERROR) << \"Failed to generate MediaInfo from input.\";\n return;\n }\n\n if (is_encrypted) {\n if (!internal::AddContentProtectionElements(\n container_type, scheme_id_uri_, media_info_.get())) {\n LOG(ERROR) << \"Failed to add content protection elements.\";\n return;\n }\n }\n}\n\nvoid VodMediaInfoDumpMuxerListener::OnMediaEnd(bool has_init_range,\n uint64_t init_range_start,\n uint64_t init_range_end,\n bool has_index_range,\n uint64_t index_range_start,\n uint64_t index_range_end,\n float duration_seconds,\n uint64_t file_size) {\n DCHECK(media_info_);\n if (!internal::SetVodInformation(has_init_range,\n init_range_start,\n init_range_end,\n has_index_range,\n index_range_start,\n index_range_end,\n duration_seconds,\n file_size,\n media_info_.get())) {\n LOG(ERROR) << \"Failed to generate VOD information from input.\";\n return;\n }\n SerializeMediaInfoToFile();\n}\n\nvoid VodMediaInfoDumpMuxerListener::OnNewSegment(uint64_t start_time,\n uint64_t duration,\n uint64_t segment_file_size) {\n NOTIMPLEMENTED();\n}\n\nbool VodMediaInfoDumpMuxerListener::SerializeMediaInfoToFile() {\n std::string output_string;\n if (!google::protobuf::TextFormat::PrintToString(*media_info_,\n &output_string)) {\n LOG(ERROR) << \"Failed to serialize MediaInfo to string.\";\n return false;\n }\n\n media::File* file = File::Open(output_file_name_.c_str(), \"w\");\n if (!file) {\n LOG(ERROR) << \"Failed to open \" << output_file_name_;\n return false;\n }\n if (file->Write(output_string.data(), output_string.size()) <= 0) {\n LOG(ERROR) << \"Failed to write MediaInfo to file.\";\n file->Close();\n return false;\n }\n if (!file->Close()) {\n LOG(ERROR) << \"Failed to close \" << output_file_name_;\n return false;\n }\n return true;\n}\n\n} \/\/ namespace event\n} \/\/ namespace media\n} \/\/ namespace edash_packager\nBug fix for VodMediaInfoDumpMuxerListener::OnNewSegment\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/developers.google.com\/open-source\/licenses\/bsd\n\n#include \"packager\/media\/event\/vod_media_info_dump_muxer_listener.h\"\n\n#include \n\n#include \"packager\/base\/logging.h\"\n#include \"packager\/media\/base\/muxer_options.h\"\n#include \"packager\/media\/base\/stream_info.h\"\n#include \"packager\/media\/event\/muxer_listener_internal.h\"\n#include \"packager\/media\/file\/file.h\"\n#include \"packager\/mpd\/base\/media_info.pb.h\"\n\nnamespace edash_packager {\nnamespace media {\nnamespace event {\n\nVodMediaInfoDumpMuxerListener::VodMediaInfoDumpMuxerListener(\n const std::string& output_file_name)\n : output_file_name_(output_file_name) {}\n\nVodMediaInfoDumpMuxerListener::~VodMediaInfoDumpMuxerListener() {}\n\nvoid VodMediaInfoDumpMuxerListener::SetContentProtectionSchemeIdUri(\n const std::string& scheme_id_uri) {\n scheme_id_uri_ = scheme_id_uri;\n}\n\nvoid VodMediaInfoDumpMuxerListener::OnMediaStart(\n const MuxerOptions& muxer_options,\n const std::vector& stream_infos,\n uint32_t time_scale,\n ContainerType container_type,\n bool is_encrypted) {\n DCHECK(muxer_options.single_segment);\n media_info_.reset(new MediaInfo());\n if (!internal::GenerateMediaInfo(muxer_options,\n stream_infos,\n time_scale,\n container_type,\n media_info_.get())) {\n LOG(ERROR) << \"Failed to generate MediaInfo from input.\";\n return;\n }\n\n if (is_encrypted) {\n if (!internal::AddContentProtectionElements(\n container_type, scheme_id_uri_, media_info_.get())) {\n LOG(ERROR) << \"Failed to add content protection elements.\";\n return;\n }\n }\n}\n\nvoid VodMediaInfoDumpMuxerListener::OnMediaEnd(bool has_init_range,\n uint64_t init_range_start,\n uint64_t init_range_end,\n bool has_index_range,\n uint64_t index_range_start,\n uint64_t index_range_end,\n float duration_seconds,\n uint64_t file_size) {\n DCHECK(media_info_);\n if (!internal::SetVodInformation(has_init_range,\n init_range_start,\n init_range_end,\n has_index_range,\n index_range_start,\n index_range_end,\n duration_seconds,\n file_size,\n media_info_.get())) {\n LOG(ERROR) << \"Failed to generate VOD information from input.\";\n return;\n }\n SerializeMediaInfoToFile();\n}\n\nvoid VodMediaInfoDumpMuxerListener::OnNewSegment(uint64_t start_time,\n uint64_t duration,\n uint64_t segment_file_size) {\n}\n\nbool VodMediaInfoDumpMuxerListener::SerializeMediaInfoToFile() {\n std::string output_string;\n if (!google::protobuf::TextFormat::PrintToString(*media_info_,\n &output_string)) {\n LOG(ERROR) << \"Failed to serialize MediaInfo to string.\";\n return false;\n }\n\n media::File* file = File::Open(output_file_name_.c_str(), \"w\");\n if (!file) {\n LOG(ERROR) << \"Failed to open \" << output_file_name_;\n return false;\n }\n if (file->Write(output_string.data(), output_string.size()) <= 0) {\n LOG(ERROR) << \"Failed to write MediaInfo to file.\";\n file->Close();\n return false;\n }\n if (!file->Close()) {\n LOG(ERROR) << \"Failed to close \" << output_file_name_;\n return false;\n }\n return true;\n}\n\n} \/\/ namespace event\n} \/\/ namespace media\n} \/\/ namespace edash_packager\n<|endoftext|>"} {"text":"#include \"parser.h\"\n#include \"platform.h\"\n#include \n\nextern \"C\" void parse(const char* json, command* wifiRC_command);\n\n#ifndef DESKTOP\n#include \"edison_platform.h\"\n#else\n#include \"desktop_platform.h\"\n#endif\n\n#define RC_ADDRESS_BASE \"http:\/\/192.168.1.\"\n#define RC_JSON_ADDRESS_SUFFIX \":8080\/CommandServer\/currentJsonCommand\"\n\nstatic void getAddress(char* address_buffer, int size)\n{\n assert(size == 64);\n\n\/\/Need to do something smarter here like search for servers on the local network\n char buffer[4];\n memset(buffer, '\\0', 4);\n memset(address_buffer, '\\0', 64);\n strcat(address_buffer, RC_ADDRESS_BASE);\n sprintf(buffer, \"%i\", DEV);\n strcat(address_buffer, buffer);\n strcat(address_buffer, RC_JSON_ADDRESS_SUFFIX);\n}\n\n#ifndef DESKTOP\nvoid platform_setup()\n{\n pthread_mutex_init(&gHttpMutex, NULL);\n\n pinMode(LIGHTS_ENABLE_PIN, OUTPUT);\n pinMode(DRIVE_MOTOR_PIN, OUTPUT);\n pinMode(REVERSE_ENGAGE_PIN, OUTPUT);\n pinMode(RIGHT_ENGAGE_PIN, OUTPUT);\n\n while(gStatus != WL_CONNECTED)\n {\n gStatus = WiFi.begin(\"\", \"\");\n delay(DEFAULT_WAIT_TIME_MS);\n }\n}\nconst char* platform_getName()\n{\n return \"Intel Edison\";\n}\nvoid platform_send(void* params)\n{\n http_request(\"POST \/CommandServer\/currentJsonCommand HTTP\/1.1\\nHost: 192.168.1.6:8080\\nAccept: *\/*\\nContent-Length: 15\\nContent-Type: application\/x-www-form-urlencoded\\nConnection: close\\n\\nPLATFORM:EDISON\\n\", NULL, 0);\n}\nchar gResponse[256];\nint platform_getCommand()\n{\n memset(gResponse, '\\0', 256);\n http_request(\"GET \/CommandServer\/currentJsonCommand HTTP\/1.1\\nHost: 192.168.1.6:8080\\nAccept: *\/*\\n\", gResponse, 256);\n\n return IDLE;\n}\nvoid platform_cleanup()\n{\n}\n#else\nvoid platform_setup()\n{\n curl_global_init(CURL_GLOBAL_DEFAULT);\n}\nconst char* platform_getName()\n{\n return \"Desktop\";\n}\nvoid platform_send(void* params)\n{\n CURL* pCURL = curl_easy_init();\n if(pCURL)\n {\n char address_buffer[64];\n getAddress(address_buffer, 64);\n curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer);\n curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, params);\n CURLcode result = curl_easy_perform(pCURL);\n if(result == CURLE_OK)\n {\n }\n curl_easy_cleanup(pCURL);\n }\n}\nint platform_getCommand()\n{\n int command = IDLE;\n CURL* pCURL = curl_easy_init();\n if(pCURL)\n {\n int temp;\n char address_buffer[64];\n getAddress(address_buffer, 64);\n curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer);\n curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_json_function);\n curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp);\n CURLcode result = curl_easy_perform(pCURL);\n if(result == CURLE_OK)\n {\n command = temp;\n }\n curl_easy_cleanup(pCURL);\n }\n\n return command;\n}\nvoid platform_cleanup()\n{\n curl_global_cleanup();\n}\n#endif\n\nParse HttpResponse#include \"parser.h\"\n#include \"platform.h\"\n#include \n\nextern \"C\" void parse(const char* json, command* wifiRC_command);\n\n#ifndef DESKTOP\n#include \"edison_platform.h\"\n#else\n#include \"desktop_platform.h\"\n#endif\n\n#define RC_ADDRESS_BASE \"http:\/\/192.168.1.\"\n#define RC_JSON_ADDRESS_SUFFIX \":8080\/CommandServer\/currentJsonCommand\"\n\nstatic void getAddress(char* address_buffer, int size)\n{\n assert(size == 64);\n\n\/\/Need to do something smarter here like search for servers on the local network\n char buffer[4];\n memset(buffer, '\\0', 4);\n memset(address_buffer, '\\0', 64);\n strcat(address_buffer, RC_ADDRESS_BASE);\n sprintf(buffer, \"%i\", DEV);\n strcat(address_buffer, buffer);\n strcat(address_buffer, RC_JSON_ADDRESS_SUFFIX);\n}\n\n#ifndef DESKTOP\nvoid platform_setup()\n{\n pthread_mutex_init(&gHttpMutex, NULL);\n\n pinMode(LIGHTS_ENABLE_PIN, OUTPUT);\n pinMode(DRIVE_MOTOR_PIN, OUTPUT);\n pinMode(REVERSE_ENGAGE_PIN, OUTPUT);\n pinMode(RIGHT_ENGAGE_PIN, OUTPUT);\n\n while(gStatus != WL_CONNECTED)\n {\n gStatus = WiFi.begin(\"\", \"\");\n delay(DEFAULT_WAIT_TIME_MS);\n }\n}\nconst char* platform_getName()\n{\n return \"Intel Edison\";\n}\nvoid platform_send(void* params)\n{\n http_request(\"POST \/CommandServer\/currentJsonCommand HTTP\/1.1\\nHost: 192.168.1.6:8080\\nAccept: *\/*\\nContent-Length: 15\\nContent-Type: application\/x-www-form-urlencoded\\nConnection: close\\n\\nPLATFORM:EDISON\\n\", NULL, 0);\n}\nchar gJson[128];\nchar gResponse[256];\nint platform_getCommand()\n{\n memset(gJson, '\\0', 128);\n memset(gResponse, '\\0', 256);\n http_request(\"GET \/CommandServer\/currentJsonCommand HTTP\/1.1\\nHost: 192.168.1.6:8080\\nAccept: *\/*\\n\", gResponse, 256);\n\n char* start = NULL;\n char* length = NULL;\n start = strchr(gResponse, '\\n')+1;\n start = strchr(start, '\\n')+1;\n length = strchr(start, ':')+1;\n int size = atoi(length);\n start = strchr(gResponse, '{');\n for(int i = 0; i < size; i++)\n {\n gJson[i] = *start;\n start++;\n }\n\n set_command command;\n parse(start, &command);\n \n return command.get_direction();\n\n}\nvoid platform_cleanup()\n{\n}\n#else\nvoid platform_setup()\n{\n curl_global_init(CURL_GLOBAL_DEFAULT);\n}\nconst char* platform_getName()\n{\n return \"Desktop\";\n}\nvoid platform_send(void* params)\n{\n CURL* pCURL = curl_easy_init();\n if(pCURL)\n {\n char address_buffer[64];\n getAddress(address_buffer, 64);\n curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer);\n curl_easy_setopt(pCURL, CURLOPT_POSTFIELDS, params);\n CURLcode result = curl_easy_perform(pCURL);\n if(result == CURLE_OK)\n {\n }\n curl_easy_cleanup(pCURL);\n }\n}\nint platform_getCommand()\n{\n int command = IDLE;\n CURL* pCURL = curl_easy_init();\n if(pCURL)\n {\n int temp;\n char address_buffer[64];\n getAddress(address_buffer, 64);\n curl_easy_setopt(pCURL, CURLOPT_URL, address_buffer);\n curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_json_function);\n curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp);\n CURLcode result = curl_easy_perform(pCURL);\n if(result == CURLE_OK)\n {\n command = temp;\n }\n curl_easy_cleanup(pCURL);\n }\n\n return command;\n}\nvoid platform_cleanup()\n{\n curl_global_cleanup();\n}\n#endif\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2019 Benoy Bose\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n * and associated documentation files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge, publish, distribute,\n * sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or\n * substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef HOOLANG_OPCODEPREFIXES_HH\n#define HOOLANG_OPCODEPREFIXES_HH\n\n#include \n\nnamespace hooc {\n namespace emitter {\n namespace x86 {\n const uint8_t PREFIX_LOCK = 0xF0;\n const uint8_t PREFIX_REPNE = 0xF2;\n const uint8_t PREFIX_REPNZ = 0xF2;\n const uint8_t PREFIX_REP = 0xF3;\n const uint8_t PREFIX_REPE = 0xF3;\n const uint8_t PREFIX_REPZ = 0xF3;\n\n const uint8_t PREFIX_SEGMENT_CS = 0x2E;\n const uint8_t PREFIX_SEGMENT_SS = 0x36;\n const uint8_t PREFIX_SEGMENT_DS = 0x3E;\n const uint8_t PREFIX_SEGMENT_ES = 0x26;\n const uint8_t PREFIX_SEGMENT_FS = 0x64;\n const uint8_t PREFIX_SEGMENT_GS = 0x65;\n const uint8_t PREFIX_BRANCH_NOT_TAKEN = 0x2E;\n const uint8_t PREFIX_BRANCH_TAKEN = 0x3E;\n\n const uint8_t PREFIX_OPERAND_SIZE_OVERRIDE = 0x66;\n const uint8_t PREFIX_ADDRESS_SIZE_OVERRIDE = 0x67;\n }\n }\n}\n\n#endif \/\/HOOLANG_OPCODEPREFIXES_HH\nOpcode prefix constants are changed to enum values.\/*\n * Copyright 2019 Benoy Bose\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n * and associated documentation files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge, publish, distribute,\n * sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or\n * substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef HOOLANG_OPCODEPREFIXES_HH\n#define HOOLANG_OPCODEPREFIXES_HH\n\n#include \n\nnamespace hooc {\n namespace emitter {\n namespace x86 {\n typedef enum {\n PREFIX_G1_LOCK = 0xF0,\n PREFIX_G1_REPN = 0xF2, \/\/ REPNE, REPNZ\n PREFIX_G1_REP = 0xF3, \/\/ REP, REPE, REPZ\n PREFIX_G2_SEGMENT_CS = 0x2E,\n PREFIX_G2_SEGMENT_SS = 0x36,\n PREFIX_G2_SEGMENT_DS = 0x3E,\n PREFIX_G2_SEGMENT_ES = 0x26,\n PREFIX_G2_SEGMENT_FS = 0x64,\n PREFIX_G2_SEGMENT_GS = 0x65,\n PREFIX_G2_BRANCH_NOT_TAKEN = 0x2E,\n PREFIX_G2_BRANCH_TAKEN = 0x3E,\n PREFIX_G3_OPERAND_SIZE_OVERRIDE = 0x66,\n PREFIX_G4_ADDRESS_SIZE_OVERRIDE = 0x67\n } OpcodePrefix;\n }\n }\n}\n\n#endif \/\/HOOLANG_OPCODEPREFIXES_HH\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n#include \n#include \n\nnamespace gemmbitserial {\n\n\/\/ Utility function to increment-and-align \"in\" to \"af\"\ninline uint64_t alignTo(uint64_t in, uint64_t af) {\n if(in % af != 0) {\n return in + (af - (in % af));\n } else {\n return in;\n }\n}\n\nclass BitSerialMatrix {\npublic:\n \/\/ static member functions for working with BitSerialMatrix\n\n \/* Allocate buffer space for a BitSerialMatrix *\/\n static BitSerialMatrix alloc(uint64_t nbits, uint64_t nrows, uint64_t ncols, bool issigned, uint64_t rowalign = 1, uint64_t colalign = 64) {\n BitSerialMatrix bsm;\n bsm.nbits = nbits;\n bsm.nrows = nrows;\n bsm.ncols = ncols;\n bsm.nrows_a = alignTo(nrows, rowalign);\n bsm.ncols_a = alignTo(ncols, colalign);\n bsm.issigned = issigned;\n uint64_t wordsPerBitplane = bsm.wordsPerBitplane();\n bsm.data = new uint64_t[nbits * wordsPerBitplane];\n return bsm;\n }\n\n \/* Deallocate buffers for a BitSerialMatrix *\/\n static void dealloc(BitSerialMatrix bsm) {\n delete [] bsm.data;\n }\n\npublic:\n \/\/ actual member variables and functions of BitSerialMatrix instances\n bool issigned; \/\/ whether highest order bit pos is negative\n uint64_t nbits; \/\/ bits of precision\n uint64_t nrows; \/\/ number of real (actual) rows\n uint64_t ncols; \/\/ number of real (actual) columns\n uint64_t nrows_a; \/\/ number of allocated rows\n uint64_t ncols_a; \/\/ number of allocated columns\n uint64_t * data; \/\/ data buffer, layout [nbits][nrows_a][ncols_a\/64]\n\n \/\/ print key statistics about BitSerialMatrix to stdout\n void printSummary() {\n std::cout << \"BitSerialMatrix\" << std::endl;\n std::cout << \"Bits of precision: \" << nbits << \" signed: \" << issigned << std::endl;\n std::cout << \"Actual size: \" << nrows << \" x \" << ncols << std::endl;\n std::cout << \"Allocated size: \" << nrows_a << \" x \" << ncols_a << std::endl;\n }\n\n \/\/ number of storage words needed for each row\n inline uint64_t wordsPerRow() const {\n const uint64_t bitsPerWord = sizeof(uint64_t) * 8;\n return ncols_a \/ bitsPerWord;\n }\n\n \/\/ number of storage words needed for each bitplane (bit matrix)\n inline uint64_t wordsPerBitplane() const {\n return nrows_a * wordsPerRow();\n }\n\n \/\/ get given bit. true if set, false if unset.\n inline bool get(uint64_t bit, uint64_t row, uint64_t col) {\n return ((word(bit, row, col) >> bitpos(col)) & 1L) == 1;\n }\n\n \/\/ set all bits to zero\n inline void clearAll() {\n memset(data, 0, nbits * wordsPerBitplane() * sizeof(uint64_t));\n }\n\n \/\/ set given bit to one\n inline void set(uint64_t bit, uint64_t row, uint64_t col) {\n word(bit, row, col) |= (1L << bitpos(col));\n }\n\n \/\/ set given bit to zero\n inline void unset(uint64_t bit, uint64_t row, uint64_t col) {\n word(bit, row, col) &= ~(1L << bitpos(col));\n }\n\n \/\/ access the container word for a given bit\n inline uint64_t & word(uint64_t bit, uint64_t row, uint64_t col) {\n \/\/ right shift by log2(bits per word) to get word index\n uint64_t colw = col >> 6;\n return data[bit * wordsPerBitplane() + row * wordsPerRow() + colw];\n }\n\n \/\/ get a pointer to a particular row\n inline uint64_t * rowptr(uint64_t bit, uint64_t row) {\n return &data[bit * wordsPerBitplane() + row * wordsPerRow()];\n }\n\n \/\/ get a pointer to a particular bit plane\n inline uint64_t * bitplaneptr(uint64_t bit) {\n return &data[bit * wordsPerBitplane()];\n }\n\n uint64_t bitpos(uint64_t col) {\n \/\/ return modulo 64 of col by using a bitmask\n return col & ((1 << 6) - 1);\n }\n\n \/* Imports a regular matrix into this BitSerialMatrix.\n *\/\n template \n void importRegular(T * matrix, bool readColMajor=false) {\n \/\/ TODO add support for transposed reading\n assert(!readColMajor);\n this->clearAll();\n for(uint64_t r = 0; r < this->nrows; r++) {\n for(uint64_t c = 0; c < this->ncols; c++) {\n uint8_t currentElem = (uint8_t) matrix[r * this->ncols + c];\n for(uint64_t b = 0; b < this->nbits; b++) {\n if(currentElem & (1 << b)) {\n this->set(b, r, c);\n }\n }\n }\n }\n }\n\n \/* Convert this BitSerialMatrix back to a regular matrix.\n *\/\n template \n void exportRegular(T * matrix) {\n for(uint64_t r = 0; r < this->nrows; r++) {\n for(uint64_t c = 0; c < this->ncols; c++) {\n uint8_t currentElem = 0;\n for(uint64_t b = 0; b < this->nbits; b++) {\n if(this->get(b, r, c)) {\n currentElem |= 1 << b;\n }\n }\n matrix[r * this->ncols + c] = (T) currentElem;\n }\n }\n }\n};\n\n\/* Utility function to find block size under the following assumptions:\n - size of lhs block + rhs block + result block <= cacheBits\n - no blocking along depth (i.e. only entire rows of dBits bits)\n - lhsMult and rhsMult determine the ratio for lhs and rhs rows in cache\n - returned lhsRows and rhsRows are divisible by lhsMult and rhsMult, respectively\n - each result elem takes bitsPerRes bits\n*\/\nvoid computeBlockSize(float lhsMult, float rhsMult, float cacheBits, float dBits, uint64_t & lhsBlock, uint64_t & rhsBlock) {\n float a = sizeof(int32_t) * lhsMult * rhsMult;\n float b = dBits*(lhsMult + rhsMult);\n float c = -cacheBits;\n float discr = sqrt(b*b - 4 * a * c);\n assert(discr > 0);\n int64_t x0 = floor((-b + discr) \/ (2*a));\n int64_t x1 = floor((-b - discr) \/ (2*a));\n int64_t x = x0 > x1 ? x0 : x1;\n assert(x > 0);\n lhsBlock = lhsMult * x;\n rhsBlock = rhsMult * x;\n};\n\n\nclass GEMMContext {\npublic:\n BitSerialMatrix lhs, rhs;\n uint64_t lhsBlock, rhsBlock;\n int32_t * res;\n\n void printSummary() {\n std::cout << \"GEMMContext\" << std::endl;\n std::cout << \"LHS: \";\n lhs.printSummary();\n std::cout << \"Block size: \" << lhsBlock << std::endl;\n std::cout << \"RHS: \";\n rhs.printSummary();\n std::cout << \"Block size: \" << rhsBlock << std::endl;\n }\n};\n\nvoid deallocGEMMContext(GEMMContext ctx) {\n delete [] ctx.res;\n BitSerialMatrix::dealloc(ctx.lhs);\n BitSerialMatrix::dealloc(ctx.rhs);\n};\n\n\/\/ generic implementations using regular & and __builtin_popcountll\n#include \"arch-generic.hpp\"\n\n\/\/ select the implementations to be used based on architecture\n#if defined(__ARM_NEON) || defined(__aarch64__)\n#warning \"Compiling with ARM NEON\"\n#include \"arch-neon.hpp\"\n\/\/ ARM NEON-specific implementations\n#define gemmBitSerial gemmBitSerial_neon_usingBinary\n\/\/ TODO context def\n#else\n#warning \"Compiling using generic popcount\"\n#define gemmBitSerial gemmBitSerial_generic_usingBinary\n#define allocGEMMContext allocGEMMContext_generic\n#endif\n\n}\nprint actual, allocated and wasted ops#pragma once\n#include \n#include \n#include \n#include \n#include \n\nnamespace gemmbitserial {\n\n\/\/ Utility function to increment-and-align \"in\" to \"af\"\ninline uint64_t alignTo(uint64_t in, uint64_t af) {\n if(in % af != 0) {\n return in + (af - (in % af));\n } else {\n return in;\n }\n}\n\nclass BitSerialMatrix {\npublic:\n \/\/ static member functions for working with BitSerialMatrix\n\n \/* Allocate buffer space for a BitSerialMatrix *\/\n static BitSerialMatrix alloc(uint64_t nbits, uint64_t nrows, uint64_t ncols, bool issigned, uint64_t rowalign = 1, uint64_t colalign = 64) {\n BitSerialMatrix bsm;\n bsm.nbits = nbits;\n bsm.nrows = nrows;\n bsm.ncols = ncols;\n bsm.nrows_a = alignTo(nrows, rowalign);\n bsm.ncols_a = alignTo(ncols, colalign);\n bsm.issigned = issigned;\n uint64_t wordsPerBitplane = bsm.wordsPerBitplane();\n bsm.data = new uint64_t[nbits * wordsPerBitplane];\n return bsm;\n }\n\n \/* Deallocate buffers for a BitSerialMatrix *\/\n static void dealloc(BitSerialMatrix bsm) {\n delete [] bsm.data;\n }\n\npublic:\n \/\/ actual member variables and functions of BitSerialMatrix instances\n bool issigned; \/\/ whether highest order bit pos is negative\n uint64_t nbits; \/\/ bits of precision\n uint64_t nrows; \/\/ number of real (actual) rows\n uint64_t ncols; \/\/ number of real (actual) columns\n uint64_t nrows_a; \/\/ number of allocated rows\n uint64_t ncols_a; \/\/ number of allocated columns\n uint64_t * data; \/\/ data buffer, layout [nbits][nrows_a][ncols_a\/64]\n\n \/\/ print key statistics about BitSerialMatrix to stdout\n void printSummary() {\n std::cout << \"BitSerialMatrix\" << std::endl;\n std::cout << \"Bits of precision: \" << nbits << \" signed: \" << issigned << std::endl;\n std::cout << \"Actual size: \" << nrows << \" x \" << ncols << std::endl;\n std::cout << \"Allocated size: \" << nrows_a << \" x \" << ncols_a << std::endl;\n std::cout << \"Actual ops: \" << 2*nrows*ncols << std::endl;\n std::cout << \"Allocated ops: \" << 2*nrows_a*ncols_a << std::endl;\n std::cout << \"Wasted ops: \" << 2*nrows_a*ncols_a-2*nrows*ncols << std::endl;\n }\n\n \/\/ number of storage words needed for each row\n inline uint64_t wordsPerRow() const {\n const uint64_t bitsPerWord = sizeof(uint64_t) * 8;\n return ncols_a \/ bitsPerWord;\n }\n\n \/\/ number of storage words needed for each bitplane (bit matrix)\n inline uint64_t wordsPerBitplane() const {\n return nrows_a * wordsPerRow();\n }\n\n \/\/ get given bit. true if set, false if unset.\n inline bool get(uint64_t bit, uint64_t row, uint64_t col) {\n return ((word(bit, row, col) >> bitpos(col)) & 1L) == 1;\n }\n\n \/\/ set all bits to zero\n inline void clearAll() {\n memset(data, 0, nbits * wordsPerBitplane() * sizeof(uint64_t));\n }\n\n \/\/ set given bit to one\n inline void set(uint64_t bit, uint64_t row, uint64_t col) {\n word(bit, row, col) |= (1L << bitpos(col));\n }\n\n \/\/ set given bit to zero\n inline void unset(uint64_t bit, uint64_t row, uint64_t col) {\n word(bit, row, col) &= ~(1L << bitpos(col));\n }\n\n \/\/ access the container word for a given bit\n inline uint64_t & word(uint64_t bit, uint64_t row, uint64_t col) {\n \/\/ right shift by log2(bits per word) to get word index\n uint64_t colw = col >> 6;\n return data[bit * wordsPerBitplane() + row * wordsPerRow() + colw];\n }\n\n \/\/ get a pointer to a particular row\n inline uint64_t * rowptr(uint64_t bit, uint64_t row) {\n return &data[bit * wordsPerBitplane() + row * wordsPerRow()];\n }\n\n \/\/ get a pointer to a particular bit plane\n inline uint64_t * bitplaneptr(uint64_t bit) {\n return &data[bit * wordsPerBitplane()];\n }\n\n uint64_t bitpos(uint64_t col) {\n \/\/ return modulo 64 of col by using a bitmask\n return col & ((1 << 6) - 1);\n }\n\n \/* Imports a regular matrix into this BitSerialMatrix.\n *\/\n template \n void importRegular(T * matrix, bool readColMajor=false) {\n \/\/ TODO add support for transposed reading\n assert(!readColMajor);\n this->clearAll();\n for(uint64_t r = 0; r < this->nrows; r++) {\n for(uint64_t c = 0; c < this->ncols; c++) {\n uint8_t currentElem = (uint8_t) matrix[r * this->ncols + c];\n for(uint64_t b = 0; b < this->nbits; b++) {\n if(currentElem & (1 << b)) {\n this->set(b, r, c);\n }\n }\n }\n }\n }\n\n \/* Convert this BitSerialMatrix back to a regular matrix.\n *\/\n template \n void exportRegular(T * matrix) {\n for(uint64_t r = 0; r < this->nrows; r++) {\n for(uint64_t c = 0; c < this->ncols; c++) {\n uint8_t currentElem = 0;\n for(uint64_t b = 0; b < this->nbits; b++) {\n if(this->get(b, r, c)) {\n currentElem |= 1 << b;\n }\n }\n matrix[r * this->ncols + c] = (T) currentElem;\n }\n }\n }\n};\n\n\/* Utility function to find block size under the following assumptions:\n - size of lhs block + rhs block + result block <= cacheBits\n - no blocking along depth (i.e. only entire rows of dBits bits)\n - lhsMult and rhsMult determine the ratio for lhs and rhs rows in cache\n - returned lhsRows and rhsRows are divisible by lhsMult and rhsMult, respectively\n - each result elem takes bitsPerRes bits\n*\/\nvoid computeBlockSize(float lhsMult, float rhsMult, float cacheBits, float dBits, uint64_t & lhsBlock, uint64_t & rhsBlock) {\n float a = sizeof(int32_t) * lhsMult * rhsMult;\n float b = dBits*(lhsMult + rhsMult);\n float c = -cacheBits;\n float discr = sqrt(b*b - 4 * a * c);\n assert(discr > 0);\n int64_t x0 = floor((-b + discr) \/ (2*a));\n int64_t x1 = floor((-b - discr) \/ (2*a));\n int64_t x = x0 > x1 ? x0 : x1;\n assert(x > 0);\n lhsBlock = lhsMult * x;\n rhsBlock = rhsMult * x;\n};\n\n\nclass GEMMContext {\npublic:\n BitSerialMatrix lhs, rhs;\n uint64_t lhsBlock, rhsBlock;\n int32_t * res;\n\n void printSummary() {\n std::cout << \"GEMMContext\" << std::endl;\n std::cout << \"LHS: \";\n lhs.printSummary();\n std::cout << \"Block size: \" << lhsBlock << std::endl;\n std::cout << \"RHS: \";\n rhs.printSummary();\n std::cout << \"Block size: \" << rhsBlock << std::endl;\n }\n};\n\nvoid deallocGEMMContext(GEMMContext ctx) {\n delete [] ctx.res;\n BitSerialMatrix::dealloc(ctx.lhs);\n BitSerialMatrix::dealloc(ctx.rhs);\n};\n\n\/\/ generic implementations using regular & and __builtin_popcountll\n#include \"arch-generic.hpp\"\n\n\/\/ select the implementations to be used based on architecture\n#if defined(__ARM_NEON) || defined(__aarch64__)\n#warning \"Compiling with ARM NEON\"\n#include \"arch-neon.hpp\"\n\/\/ ARM NEON-specific implementations\n#define gemmBitSerial gemmBitSerial_neon_usingBinary\n\/\/ TODO context def\n#else\n#warning \"Compiling using generic popcount\"\n#define gemmBitSerial gemmBitSerial_generic_usingBinary\n#define allocGEMMContext allocGEMMContext_generic\n#endif\n\n}\n<|endoftext|>"} {"text":"#ifndef TPLEXPREFIXTREE_HH\n#define TPLEXPREFIXTREE_HH\n\n#include \n#include \n\n#include \"HashCache.hh\"\n#include \"SimpleHashCache.hh\"\n\n#include \"Hmm.hh\"\n#include \"Vocabulary.hh\"\n\n\/\/ Constructs and maintains the lexical prefix tree.\n\n\/\/ NOTE!\n\/\/ - Assumes that the transitions from the hmm states with identical\n\/\/ mixture models are the same, although with different destinations.\n\/\/ - HMMs must have left-to-right topology, skip states are allowed,\n\/\/ except from the source state, see the next note.\n\/\/ - If there are transitions from HMM source state to other states than to\n\/\/ the first real state and to the sink state, the tree construction might\n\/\/ not work with shared HMM states.\n\n\n\/\/ Node flags\n#define NODE_NORMAL 0x00\n#define NODE_USE_WORD_END_BEAM 0x01\n#define NODE_AFTER_WORD_ID 0x02\n#define NODE_FAN_OUT 0x04\n#define NODE_FAN_OUT_FIRST 0x08\n#define NODE_FAN_IN 0x10\n#define NODE_FAN_IN_FIRST 0x20\n#define NODE_INSERT_WORD_BOUNDARY 0x40\n#define NODE_FAN_IN_CONNECTION 0x80\n#define NODE_LINKED 0x0100\n#define NODE_SILENCE_FIRST 0x0200\n#define NODE_FIRST_STATE_OF_WORD 0x0400\n\n\nclass TPLexPrefixTree {\npublic:\n\n class Node;\n\n class WordHistory {\n public:\n inline WordHistory(int word_id, int lm_id, class WordHistory *prev);\n inline void link() { m_reference_count++; }\n inline static void unlink(class WordHistory *hist);\n inline int get_num_references(void) { return m_reference_count; }\n\n int word_id;\n int lm_id; \/\/ Word ID in LM\n WordHistory *prev_word;\n bool printed; \/\/ TokenPassSearch::print* functions may set this true\n int word_start_frame;\n private:\n int m_reference_count;\n };\n\n class StateHistory {\n public:\n inline StateHistory(int hmm_model, int start_time,\n class StateHistory *prev);\n\n inline void link() { m_reference_count++; }\n inline static void unlink(class StateHistory *hist);\n \n int hmm_model;\n int start_time;\n StateHistory *prev;\n private:\n int m_reference_count;\n };\n\n class PathHistory {\n public:\n inline PathHistory(float ll, float dll, int depth, class PathHistory *p);\n\n inline void link() { m_reference_count++; }\n inline static void unlink(class PathHistory *hist);\n \n float ll;\n float dll;\n int depth;\n PathHistory *prev;\n private:\n int m_reference_count;\n };\n\n class Token {\n public:\n Node *node;\n Token *next_node_token;\n float am_log_prob;\n float lm_log_prob;\n float cur_am_log_prob; \/\/ Used inside nodes\n float cur_lm_log_prob; \/\/ Used for LM lookahead\n float total_log_prob;\n WordHistory *prev_word;\n int word_hist_code; \/\/ Hash code for word history (up to LM order)\n int word_start_frame;\n\n#ifdef PRUNING_MEASUREMENT\n float meas[6];\n#endif\n\n int word_count;\n StateHistory *state_history;\n \n \/\/PathHistory *token_path;\n unsigned char depth;\n unsigned char dur;\n };\n\n class Arc {\n public:\n float log_prob;\n Node *next;\n };\n\n class Node {\n public:\n inline Node() : word_id(-1), state(NULL), token_list(NULL), flags(NODE_NORMAL) { }\n inline Node(int wid) : word_id(wid), state(NULL), token_list(NULL), flags(NODE_NORMAL) { }\n inline Node(int wid, HmmState *s) : word_id(wid), state(s), token_list(NULL), flags(NODE_NORMAL) { }\n int word_id; \/\/ -1 if none\n int node_id;\n HmmState *state;\n Token *token_list;\n std::vector arcs;\n\n unsigned short flags;\n\n std::vector possible_word_id_list;\n SimpleHashCache lm_lookahead_buffer;\n };\n\n struct NodeArcId {\n Node *node;\n int arc_index;\n };\n\n TPLexPrefixTree(std::map &hmm_map, std::vector &hmms);\n inline TPLexPrefixTree::Node *root() { return m_root_node; }\n inline TPLexPrefixTree::Node *start_node() { return m_start_node; }\n inline int words() const { return m_words; }\n\n void set_verbose(int verbose) { m_verbose = verbose; }\n void set_lm_lookahead(int lm_lookahead) { m_lm_lookahead = lm_lookahead; }\n void set_cross_word_triphones(bool cw_triphones) { m_cross_word_triphones = cw_triphones; }\n void set_silence_is_word(bool b) { m_silence_is_word = b; }\n void set_ignore_case(bool b) { m_ignore_case = b; }\n\n void initialize_lex_tree(void);\n void add_word(std::vector &hmm_list, int word_id);\n void finish_tree(void);\n \n void prune_lookahead_buffers(int min_delta, int max_depth);\n void set_lm_lookahead_cache_sizes(int cache_size);\n\n void set_word_boundary_id(int id) { m_word_boundary_id = id; }\n void set_optional_short_silence(bool state) { m_optional_short_silence = state; }\n void set_sentence_boundary(int sentence_end_id);\n\n void clear_node_token_lists(void);\n\n void print_node_info(int node);\n void print_lookahead_info(int node, const Vocabulary &voc);\n \nprivate:\n void expand_lexical_tree(Node *source, Hmm *hmm, HmmTransition &t,\n float cur_trans_log_prob,\n int word_end,\n std::vector &hmm_state_nodes,\n std::vector &sink_nodes,\n std::vector &sink_trans_log_probs,\n unsigned short flags);\n void post_process_lex_branch(Node *node, std::vector *lm_la_list);\n bool post_process_fan_triphone(Node *node, std::vector *lm_la_list,\n bool fan_in);\n\n void create_cross_word_network(void);\n void add_hmm_to_fan_network(int hmm_id,\n bool fan_out);\n void link_fan_out_node_to_fan_in(Node *node, const std::string &key);\n void link_node_to_fan_network(const std::string &key,\n std::vector &source_arcs,\n bool fan_out,\n bool ignore_length,\n float out_transition_log_prob);\n void add_single_hmm_word_for_cross_word_modeling(Hmm *hmm, int word_id);\n void link_fan_in_nodes(void);\n void create_lex_tree_links_from_fan_in(Node *fan_in_node,\n const std::string &key);\n\n void analyze_cross_word_network(void);\n void count_fan_size(Node *node, unsigned short flag,\n int *num_nodes, int *num_arcs);\n void count_prefix_tree_size(Node *node, int *num_nodes,\n int *num_arcs);\n \n void free_cross_word_network_connection_points(void);\n Node* get_short_silence_node(void);\n Node* get_fan_out_entry_node(HmmState *state, const std::string &label);\n Node* get_fan_out_last_node(HmmState *state, const std::string &label);\n Node* get_fan_in_entry_node(HmmState *state, const std::string &label);\n Node* get_fan_in_last_node(HmmState *state, const std::string &label);\n Node* get_fan_state_node(HmmState *state, std::vector *nodes);\n std::vector* get_fan_node_list(\n const std::string &key,\n std::map< std::string, std::vector* > &nmap);\n void add_fan_in_connection_node(Node *node, const std::string &prev_label);\n\n float get_out_transition_log_prob(Node *node);\n \n void prune_lm_la_buffer(int delta_thr, int depth_thr,\n Node *node, int last_size, int cur_depth);\n \nprivate:\n int m_words; \/\/ Largest word_id in the nodes plus one\n Node *m_root_node;\n Node *m_end_node;\n Node *m_start_node;\n Node *m_silence_node;\n Node *m_last_silence_node;\n std::vector node_list;\n int m_verbose;\n int m_lm_lookahead; \/\/ 0=None, 1=Only in first subtree nodes,\n \/\/ 2=Full\n bool m_cross_word_triphones;\n int m_lm_buf_count;\n\n bool m_silence_is_word;\n bool m_ignore_case;\n bool m_optional_short_silence;\n HmmState *m_short_silence_state;\n int m_word_boundary_id;\n\n std::map &m_hmm_map;\n std::vector &m_hmms;\n\n std::map< std::string, std::vector* > m_fan_out_entry_nodes;\n std::map< std::string, std::vector* > m_fan_out_last_nodes;\n std::map< std::string, std::vector* > m_fan_in_entry_nodes;\n std::map< std::string, std::vector* > m_fan_in_last_nodes;\n std::map< std::string, std::vector* > m_fan_in_connection_nodes;\n std::vector m_silence_arcs;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTPLexPrefixTree::WordHistory::WordHistory(int word_id, int lm_id,\n class WordHistory *prev)\n : word_id(word_id),\n lm_id(lm_id),\n prev_word(prev),\n printed(false),\n word_start_frame(0),\n m_reference_count(0)\n{\n if (prev)\n prev->link();\n}\n\nvoid\nTPLexPrefixTree::WordHistory::unlink(class WordHistory *hist)\n{\n if (hist != NULL)\n {\n while (hist->m_reference_count == 1) {\n WordHistory *prev = hist->prev_word;\n delete hist;\n hist = prev;\n if (hist == NULL)\n return;\n }\n hist->m_reference_count--;\n }\n}\n\n\nTPLexPrefixTree::PathHistory::PathHistory(float ll, float dll, int depth,\n class PathHistory *p)\n : ll(ll),\n dll(dll),\n depth(depth),\n prev(p),\n m_reference_count(0)\n{\n if (p)\n p->link();\n}\n\nvoid\nTPLexPrefixTree::PathHistory::unlink(class PathHistory *hist)\n{\n if (hist != NULL)\n {\n while (hist->m_reference_count == 1) {\n PathHistory *prev = hist->prev;\n delete hist;\n hist = prev;\n if (hist == NULL)\n return;\n }\n hist->m_reference_count--;\n }\n}\n\nTPLexPrefixTree::StateHistory::StateHistory(int hmm_model, int start_time,\n class StateHistory *prev)\n : hmm_model(hmm_model),\n start_time(start_time),\n prev(prev),\n m_reference_count(0)\n{\n if (prev)\n prev->link();\n}\n\nvoid\nTPLexPrefixTree::StateHistory::unlink(class StateHistory *hist)\n{\n if (hist != NULL)\n {\n while (hist->m_reference_count == 1) {\n StateHistory *prev = hist->prev;\n delete hist;\n hist = prev;\n if (hist == NULL)\n return;\n }\n hist->m_reference_count--;\n }\n}\n\n#endif \/* TPLEXPREFIXTREE_HH *\/\ninclude cmath#ifndef TPLEXPREFIXTREE_HH\n#define TPLEXPREFIXTREE_HH\n\n#include \n#include \n#include \n\n#include \"HashCache.hh\"\n#include \"SimpleHashCache.hh\"\n\n#include \"Hmm.hh\"\n#include \"Vocabulary.hh\"\n\n\/\/ Constructs and maintains the lexical prefix tree.\n\n\/\/ NOTE!\n\/\/ - Assumes that the transitions from the hmm states with identical\n\/\/ mixture models are the same, although with different destinations.\n\/\/ - HMMs must have left-to-right topology, skip states are allowed,\n\/\/ except from the source state, see the next note.\n\/\/ - If there are transitions from HMM source state to other states than to\n\/\/ the first real state and to the sink state, the tree construction might\n\/\/ not work with shared HMM states.\n\n\n\/\/ Node flags\n#define NODE_NORMAL 0x00\n#define NODE_USE_WORD_END_BEAM 0x01\n#define NODE_AFTER_WORD_ID 0x02\n#define NODE_FAN_OUT 0x04\n#define NODE_FAN_OUT_FIRST 0x08\n#define NODE_FAN_IN 0x10\n#define NODE_FAN_IN_FIRST 0x20\n#define NODE_INSERT_WORD_BOUNDARY 0x40\n#define NODE_FAN_IN_CONNECTION 0x80\n#define NODE_LINKED 0x0100\n#define NODE_SILENCE_FIRST 0x0200\n#define NODE_FIRST_STATE_OF_WORD 0x0400\n\n\nclass TPLexPrefixTree {\npublic:\n\n class Node;\n\n class WordHistory {\n public:\n inline WordHistory(int word_id, int lm_id, class WordHistory *prev);\n inline void link() { m_reference_count++; }\n inline static void unlink(class WordHistory *hist);\n inline int get_num_references(void) { return m_reference_count; }\n\n int word_id;\n int lm_id; \/\/ Word ID in LM\n WordHistory *prev_word;\n bool printed; \/\/ TokenPassSearch::print* functions may set this true\n int word_start_frame;\n private:\n int m_reference_count;\n };\n\n class StateHistory {\n public:\n inline StateHistory(int hmm_model, int start_time,\n class StateHistory *prev);\n\n inline void link() { m_reference_count++; }\n inline static void unlink(class StateHistory *hist);\n \n int hmm_model;\n int start_time;\n StateHistory *prev;\n private:\n int m_reference_count;\n };\n\n class PathHistory {\n public:\n inline PathHistory(float ll, float dll, int depth, class PathHistory *p);\n\n inline void link() { m_reference_count++; }\n inline static void unlink(class PathHistory *hist);\n \n float ll;\n float dll;\n int depth;\n PathHistory *prev;\n private:\n int m_reference_count;\n };\n\n class Token {\n public:\n Node *node;\n Token *next_node_token;\n float am_log_prob;\n float lm_log_prob;\n float cur_am_log_prob; \/\/ Used inside nodes\n float cur_lm_log_prob; \/\/ Used for LM lookahead\n float total_log_prob;\n WordHistory *prev_word;\n int word_hist_code; \/\/ Hash code for word history (up to LM order)\n int word_start_frame;\n\n#ifdef PRUNING_MEASUREMENT\n float meas[6];\n#endif\n\n int word_count;\n StateHistory *state_history;\n \n \/\/PathHistory *token_path;\n unsigned char depth;\n unsigned char dur;\n };\n\n class Arc {\n public:\n float log_prob;\n Node *next;\n };\n\n class Node {\n public:\n inline Node() : word_id(-1), state(NULL), token_list(NULL), flags(NODE_NORMAL) { }\n inline Node(int wid) : word_id(wid), state(NULL), token_list(NULL), flags(NODE_NORMAL) { }\n inline Node(int wid, HmmState *s) : word_id(wid), state(s), token_list(NULL), flags(NODE_NORMAL) { }\n int word_id; \/\/ -1 if none\n int node_id;\n HmmState *state;\n Token *token_list;\n std::vector arcs;\n\n unsigned short flags;\n\n std::vector possible_word_id_list;\n SimpleHashCache lm_lookahead_buffer;\n };\n\n struct NodeArcId {\n Node *node;\n int arc_index;\n };\n\n TPLexPrefixTree(std::map &hmm_map, std::vector &hmms);\n inline TPLexPrefixTree::Node *root() { return m_root_node; }\n inline TPLexPrefixTree::Node *start_node() { return m_start_node; }\n inline int words() const { return m_words; }\n\n void set_verbose(int verbose) { m_verbose = verbose; }\n void set_lm_lookahead(int lm_lookahead) { m_lm_lookahead = lm_lookahead; }\n void set_cross_word_triphones(bool cw_triphones) { m_cross_word_triphones = cw_triphones; }\n void set_silence_is_word(bool b) { m_silence_is_word = b; }\n void set_ignore_case(bool b) { m_ignore_case = b; }\n\n void initialize_lex_tree(void);\n void add_word(std::vector &hmm_list, int word_id);\n void finish_tree(void);\n \n void prune_lookahead_buffers(int min_delta, int max_depth);\n void set_lm_lookahead_cache_sizes(int cache_size);\n\n void set_word_boundary_id(int id) { m_word_boundary_id = id; }\n void set_optional_short_silence(bool state) { m_optional_short_silence = state; }\n void set_sentence_boundary(int sentence_end_id);\n\n void clear_node_token_lists(void);\n\n void print_node_info(int node);\n void print_lookahead_info(int node, const Vocabulary &voc);\n \nprivate:\n void expand_lexical_tree(Node *source, Hmm *hmm, HmmTransition &t,\n float cur_trans_log_prob,\n int word_end,\n std::vector &hmm_state_nodes,\n std::vector &sink_nodes,\n std::vector &sink_trans_log_probs,\n unsigned short flags);\n void post_process_lex_branch(Node *node, std::vector *lm_la_list);\n bool post_process_fan_triphone(Node *node, std::vector *lm_la_list,\n bool fan_in);\n\n void create_cross_word_network(void);\n void add_hmm_to_fan_network(int hmm_id,\n bool fan_out);\n void link_fan_out_node_to_fan_in(Node *node, const std::string &key);\n void link_node_to_fan_network(const std::string &key,\n std::vector &source_arcs,\n bool fan_out,\n bool ignore_length,\n float out_transition_log_prob);\n void add_single_hmm_word_for_cross_word_modeling(Hmm *hmm, int word_id);\n void link_fan_in_nodes(void);\n void create_lex_tree_links_from_fan_in(Node *fan_in_node,\n const std::string &key);\n\n void analyze_cross_word_network(void);\n void count_fan_size(Node *node, unsigned short flag,\n int *num_nodes, int *num_arcs);\n void count_prefix_tree_size(Node *node, int *num_nodes,\n int *num_arcs);\n \n void free_cross_word_network_connection_points(void);\n Node* get_short_silence_node(void);\n Node* get_fan_out_entry_node(HmmState *state, const std::string &label);\n Node* get_fan_out_last_node(HmmState *state, const std::string &label);\n Node* get_fan_in_entry_node(HmmState *state, const std::string &label);\n Node* get_fan_in_last_node(HmmState *state, const std::string &label);\n Node* get_fan_state_node(HmmState *state, std::vector *nodes);\n std::vector* get_fan_node_list(\n const std::string &key,\n std::map< std::string, std::vector* > &nmap);\n void add_fan_in_connection_node(Node *node, const std::string &prev_label);\n\n float get_out_transition_log_prob(Node *node);\n \n void prune_lm_la_buffer(int delta_thr, int depth_thr,\n Node *node, int last_size, int cur_depth);\n \nprivate:\n int m_words; \/\/ Largest word_id in the nodes plus one\n Node *m_root_node;\n Node *m_end_node;\n Node *m_start_node;\n Node *m_silence_node;\n Node *m_last_silence_node;\n std::vector node_list;\n int m_verbose;\n int m_lm_lookahead; \/\/ 0=None, 1=Only in first subtree nodes,\n \/\/ 2=Full\n bool m_cross_word_triphones;\n int m_lm_buf_count;\n\n bool m_silence_is_word;\n bool m_ignore_case;\n bool m_optional_short_silence;\n HmmState *m_short_silence_state;\n int m_word_boundary_id;\n\n std::map &m_hmm_map;\n std::vector &m_hmms;\n\n std::map< std::string, std::vector* > m_fan_out_entry_nodes;\n std::map< std::string, std::vector* > m_fan_out_last_nodes;\n std::map< std::string, std::vector* > m_fan_in_entry_nodes;\n std::map< std::string, std::vector* > m_fan_in_last_nodes;\n std::map< std::string, std::vector* > m_fan_in_connection_nodes;\n std::vector m_silence_arcs;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTPLexPrefixTree::WordHistory::WordHistory(int word_id, int lm_id,\n class WordHistory *prev)\n : word_id(word_id),\n lm_id(lm_id),\n prev_word(prev),\n printed(false),\n word_start_frame(0),\n m_reference_count(0)\n{\n if (prev)\n prev->link();\n}\n\nvoid\nTPLexPrefixTree::WordHistory::unlink(class WordHistory *hist)\n{\n if (hist != NULL)\n {\n while (hist->m_reference_count == 1) {\n WordHistory *prev = hist->prev_word;\n delete hist;\n hist = prev;\n if (hist == NULL)\n return;\n }\n hist->m_reference_count--;\n }\n}\n\n\nTPLexPrefixTree::PathHistory::PathHistory(float ll, float dll, int depth,\n class PathHistory *p)\n : ll(ll),\n dll(dll),\n depth(depth),\n prev(p),\n m_reference_count(0)\n{\n if (p)\n p->link();\n}\n\nvoid\nTPLexPrefixTree::PathHistory::unlink(class PathHistory *hist)\n{\n if (hist != NULL)\n {\n while (hist->m_reference_count == 1) {\n PathHistory *prev = hist->prev;\n delete hist;\n hist = prev;\n if (hist == NULL)\n return;\n }\n hist->m_reference_count--;\n }\n}\n\nTPLexPrefixTree::StateHistory::StateHistory(int hmm_model, int start_time,\n class StateHistory *prev)\n : hmm_model(hmm_model),\n start_time(start_time),\n prev(prev),\n m_reference_count(0)\n{\n if (prev)\n prev->link();\n}\n\nvoid\nTPLexPrefixTree::StateHistory::unlink(class StateHistory *hist)\n{\n if (hist != NULL)\n {\n while (hist->m_reference_count == 1) {\n StateHistory *prev = hist->prev;\n delete hist;\n hist = prev;\n if (hist == NULL)\n return;\n }\n hist->m_reference_count--;\n }\n}\n\n#endif \/* TPLEXPREFIXTREE_HH *\/\n<|endoftext|>"} {"text":"#include \"HedgeLib\/IO\/HedgehogEngine.h\"\n#include \"HedgeLib\/IO\/File.h\"\n#include \"HedgeLib\/Offsets.h\"\n#include \"..\/INBlob.h\"\n\nHL_IMPL_ENDIAN_SWAP_CPP(hl_DHHHeader);\nHL_IMPL_ENDIAN_SWAP(hl_DHHHeader, v)\n{\n hl_SwapUInt32(&v->FileSize);\n hl_SwapUInt32(&v->Version);\n}\n\nHL_IMPL_ENDIAN_SWAP_CPP(hl_DHHStandardHeader);\nHL_IMPL_ENDIAN_SWAP(hl_DHHStandardHeader, v)\n{\n HL_ENDIAN_SWAP(hl_DHHHeader, &v->Header);\n hl_SwapUInt32(&v->DataSize);\n hl_SwapUInt32(&v->DataOffset);\n hl_SwapUInt32(&v->OffsetTableOffset);\n hl_SwapUInt32(&v->EOFOffset);\n}\n\nvoid hl_HHFixOffsets(uint32_t* offTable,\n uint32_t offCount, void* data)\n{\n hl_DataOff32* offPtr = static_cast(data);\n for (uint32_t i = 0; i < offCount; ++i)\n {\n \/\/ Endian swap offset table entry\n hl_SwapUInt32(&(offTable[i]));\n\n \/\/ Get position of next offset\n \/\/ (Data Pointer + Current entry in offset table)\n offPtr = hl_GetAbs(data, offTable[i]);\n\n \/\/ Fix offset\n hl_FixOffset(offPtr, data);\n }\n}\n\nvoid* hl_HHMirageGetDataNode(const struct hl_Blob* blob)\n{\n \/\/ TODO\n return nullptr;\n}\n\nvoid* hl_HHStandardGetData(struct hl_Blob* blob)\n{\n hl_DHHStandardHeader* header = blob->GetData();\n return HL_GETABSV(header, header->DataOffset);\n}\n\nvoid* hl_HHMirageGetData(struct hl_Blob* blob)\n{\n \/\/ TODO\n return nullptr;\n}\n\nvoid* hl_HHGetData(struct hl_Blob* blob)\n{\n \/\/ Mirage Header\n if (hl_HHDetectHeaderType(blob->GetData()) == HL_HHHEADER_TYPE_MIRAGE)\n {\n return hl_HHMirageGetData(blob);\n }\n\n \/\/ Standard Header\n return hl_HHStandardGetData(blob);\n}\n\nenum HL_RESULT hl_HHRead(struct hl_File* file, struct hl_Blob** blob)\n{\n HL_RESULT result;\n file->DoEndianSwap = true;\n\n \/\/ Get file size\n uint32_t fileSize;\n result = file->Read(fileSize);\n if (HL_FAILED(result)) return result;\n\n \/\/ Get header type and go back to beginning of file\n bool isMirage = false; \/\/ \"Friends are nothing but a fleeting illusion\"\n if (fileSize & HL_HHMIRAGE_FLAGS_MASK) \/\/ \"Your mask can't hide how sad and lonely you are!\"\n {\n \/\/ Make sure this is really a Mirage header\n uint32_t version;\n result = file->Read(version);\n if (HL_FAILED(result)) return result;\n\n if (version == HL_HHMIRAGE_SIGNATURE)\n {\n isMirage = true;\n fileSize &= HL_HHMIRAGE_SIZE_MASK;\n }\n\n file->JumpBehind(8);\n }\n else\n {\n file->JumpBehind(4);\n }\n\n \/\/ Read entire file\n *blob = hl_INCreateBlob(HL_BLOB_TYPE_HEDGEHOG_ENGINE, fileSize);\n if (!(*blob)) return HL_ERROR_OUT_OF_MEMORY;\n\n void* fileData = (*blob)->GetData();\n result = file->ReadBytes(fileData, fileSize);\n if (HL_FAILED(result)) return result;\n\n \/\/ Header-specific\n uint32_t* offTable;\n uint32_t offCount;\n void* data;\n\n if (isMirage) \/\/ Mirage Header\n {\n \/\/ TODO\n offTable = nullptr;\n offCount = 0;\n data = nullptr;\n }\n else \/\/ Standard Header\n {\n \/\/ Endian-swap standard header\n hl_DHHStandardHeader* header = static_cast\n (fileData);\n\n HL_ENDIAN_SWAP(hl_DHHStandardHeader, header);\n\n \/\/ Get offset table\n offTable = hl_GetAbs(\n fileData, header->OffsetTableOffset);\n\n hl_SwapUInt32(offTable);\n offCount = *offTable++;\n\n \/\/ Get data pointer\n data = hl_GetAbs(fileData, header->DataOffset);\n }\n\n \/\/ Fix offsets\n hl_HHFixOffsets(offTable, offCount, data);\n return HL_SUCCESS;\n}\n\nenum HL_RESULT hl_HHLoad(const char* filePath, struct hl_Blob** blob)\n{\n \/\/ TODO: Do stuff here instead of just calling hl_HHRead so you\n \/\/ can optimize-out the need to read the file size and backtrack.\n hl_File file = hl_File::OpenRead(std::filesystem::u8path(filePath), true);\n return hl_HHRead(&file, blob);\n}\n\nenum HL_RESULT hl_HHStartWriteStandard(struct hl_File* file, uint32_t version)\n{\n \/\/ Create \"empty\" header\n hl_DHHStandardHeader header = {};\n header.Header.Version = version;\n header.DataOffset = sizeof(hl_DHHStandardHeader);\n\n \/\/ Write header\n file->DoEndianSwap = true;\n HL_RESULT result = file->Write(header);\n\n \/\/ Set origin\n if (HL_OK(result))\n {\n file->Origin = file->Tell();\n }\n\n return result;\n}\n\nenum HL_RESULT hl_HHWriteOffsetTableStandard(const struct hl_File* file,\n const hl_OffsetTable* offTable)\n{\n \/\/ Write offset count\n uint32_t offCount = static_cast(offTable->size());\n HL_RESULT result = file->Write(offCount);\n if (HL_FAILED(result)) return result;\n\n \/\/ Write offsets\n uint32_t off;\n const long* offsets = offTable->data();\n\n for (size_t i = 0; i < offTable->size(); ++i)\n {\n off = static_cast(\n offsets[i] - file->Origin);\n\n result = file->Write(off);\n if (HL_FAILED(result)) return result;\n }\n\n return result;\n}\n\nenum HL_RESULT hl_HHFinishWriteStandard(const struct hl_File* file, long headerPos,\n bool writeEOFThing, const hl_OffsetTable* offTable)\n{\n \/\/ Write offset table\n uint32_t offTablePos = static_cast(file->Tell());\n if (headerPos >= static_cast(offTablePos))\n return HL_ERROR_UNKNOWN; \/\/ TODO: Return a better error\n\n HL_RESULT result = hl_HHWriteOffsetTableStandard(file, offTable);\n if (HL_FAILED(result)) return result;\n\n \/\/ TODO: Write EOF thing if told to\n\n \/\/ Fill-in file size\n uint32_t fileSize = static_cast(file->Tell());\n file->JumpTo(headerPos);\n\n result = file->Write(fileSize);\n if (HL_FAILED(result)) return result;\n\n if (file->JumpAhead(4)) return HL_ERROR_UNKNOWN; \/\/ TODO: Return better error\n\n \/\/ Fill-in data size\n uint32_t dataSize = (offTablePos -\n sizeof(hl_DHHStandardHeader));\n\n result = file->Write(dataSize);\n if (HL_FAILED(result)) return result;\n\n file->JumpAhead(4);\n\n \/\/ Fill-in offset table position\n result = file->Write(offTablePos);\n if (HL_FAILED(result)) return result;\n\n \/\/ TODO: Fill-in EOF position if told to\n return result;\n}\n\nvoid hl_HHFreeBlob(struct hl_Blob* blob)\n{\n#ifdef x64\n \/\/ Get offset table\n std::uint32_t offCount;\n std::uint32_t* offTable;\n void* data;\n\n if (!blob) return;\n\n if (hl_HHDetectHeaderType(blob->GetData<\n hl_DHHHeader>()) == HL_HHHEADER_TYPE_MIRAGE)\n {\n \/\/ TODO\n offCount = 0;\n offTable = nullptr;\n data = nullptr;\n }\n else\n {\n \/\/ Get offset table pointer\n hl_DHHStandardHeader* header = blob->GetData\n ();\n\n offTable = hl_GetAbs(\n header, header->OffsetTableOffset);\n\n \/\/ Get offset table count\n offCount = *offTable++;\n\n \/\/ Get data\n data = hl_GetAbs(header, header->DataOffset);\n }\n\n \/\/ Free all offsets using data in offset table\n for (uint32_t i = 0; i < offCount; ++i)\n {\n hl_x64RemoveAbsPtr32(*hl_GetAbs(\n data, offTable[i]));\n }\n#endif\n \n \/\/ Free data\n std::free(blob);\n}\nMinor bug fix for Hedgehog Engine writing We shouldn't assume headerPos is 0; the user might be writing further into the file.#include \"HedgeLib\/IO\/HedgehogEngine.h\"\n#include \"HedgeLib\/IO\/File.h\"\n#include \"HedgeLib\/Offsets.h\"\n#include \"..\/INBlob.h\"\n\nHL_IMPL_ENDIAN_SWAP_CPP(hl_DHHHeader);\nHL_IMPL_ENDIAN_SWAP(hl_DHHHeader, v)\n{\n hl_SwapUInt32(&v->FileSize);\n hl_SwapUInt32(&v->Version);\n}\n\nHL_IMPL_ENDIAN_SWAP_CPP(hl_DHHStandardHeader);\nHL_IMPL_ENDIAN_SWAP(hl_DHHStandardHeader, v)\n{\n HL_ENDIAN_SWAP(hl_DHHHeader, &v->Header);\n hl_SwapUInt32(&v->DataSize);\n hl_SwapUInt32(&v->DataOffset);\n hl_SwapUInt32(&v->OffsetTableOffset);\n hl_SwapUInt32(&v->EOFOffset);\n}\n\nvoid hl_HHFixOffsets(uint32_t* offTable,\n uint32_t offCount, void* data)\n{\n hl_DataOff32* offPtr = static_cast(data);\n for (uint32_t i = 0; i < offCount; ++i)\n {\n \/\/ Endian swap offset table entry\n hl_SwapUInt32(&(offTable[i]));\n\n \/\/ Get position of next offset\n \/\/ (Data Pointer + Current entry in offset table)\n offPtr = hl_GetAbs(data, offTable[i]);\n\n \/\/ Fix offset\n hl_FixOffset(offPtr, data);\n }\n}\n\nvoid* hl_HHMirageGetDataNode(const struct hl_Blob* blob)\n{\n \/\/ TODO\n return nullptr;\n}\n\nvoid* hl_HHStandardGetData(struct hl_Blob* blob)\n{\n hl_DHHStandardHeader* header = blob->GetData();\n return HL_GETABSV(header, header->DataOffset);\n}\n\nvoid* hl_HHMirageGetData(struct hl_Blob* blob)\n{\n \/\/ TODO\n return nullptr;\n}\n\nvoid* hl_HHGetData(struct hl_Blob* blob)\n{\n \/\/ Mirage Header\n if (hl_HHDetectHeaderType(blob->GetData()) == HL_HHHEADER_TYPE_MIRAGE)\n {\n return hl_HHMirageGetData(blob);\n }\n\n \/\/ Standard Header\n return hl_HHStandardGetData(blob);\n}\n\nenum HL_RESULT hl_HHRead(struct hl_File* file, struct hl_Blob** blob)\n{\n HL_RESULT result;\n file->DoEndianSwap = true;\n\n \/\/ Get file size\n uint32_t fileSize;\n result = file->Read(fileSize);\n if (HL_FAILED(result)) return result;\n\n \/\/ Get header type and go back to beginning of file\n bool isMirage = false; \/\/ \"Friends are nothing but a fleeting illusion\"\n if (fileSize & HL_HHMIRAGE_FLAGS_MASK) \/\/ \"Your mask can't hide how sad and lonely you are!\"\n {\n \/\/ Make sure this is really a Mirage header\n uint32_t version;\n result = file->Read(version);\n if (HL_FAILED(result)) return result;\n\n if (version == HL_HHMIRAGE_SIGNATURE)\n {\n isMirage = true;\n fileSize &= HL_HHMIRAGE_SIZE_MASK;\n }\n\n file->JumpBehind(8);\n }\n else\n {\n file->JumpBehind(4);\n }\n\n \/\/ Read entire file\n *blob = hl_INCreateBlob(HL_BLOB_TYPE_HEDGEHOG_ENGINE, fileSize);\n if (!(*blob)) return HL_ERROR_OUT_OF_MEMORY;\n\n void* fileData = (*blob)->GetData();\n result = file->ReadBytes(fileData, fileSize);\n if (HL_FAILED(result)) return result;\n\n \/\/ Header-specific\n uint32_t* offTable;\n uint32_t offCount;\n void* data;\n\n if (isMirage) \/\/ Mirage Header\n {\n \/\/ TODO\n offTable = nullptr;\n offCount = 0;\n data = nullptr;\n }\n else \/\/ Standard Header\n {\n \/\/ Endian-swap standard header\n hl_DHHStandardHeader* header = static_cast\n (fileData);\n\n HL_ENDIAN_SWAP(hl_DHHStandardHeader, header);\n\n \/\/ Get offset table\n offTable = hl_GetAbs(\n fileData, header->OffsetTableOffset);\n\n hl_SwapUInt32(offTable);\n offCount = *offTable++;\n\n \/\/ Get data pointer\n data = hl_GetAbs(fileData, header->DataOffset);\n }\n\n \/\/ Fix offsets\n hl_HHFixOffsets(offTable, offCount, data);\n return HL_SUCCESS;\n}\n\nenum HL_RESULT hl_HHLoad(const char* filePath, struct hl_Blob** blob)\n{\n \/\/ TODO: Do stuff here instead of just calling hl_HHRead so you\n \/\/ can optimize-out the need to read the file size and backtrack.\n hl_File file = hl_File::OpenRead(std::filesystem::u8path(filePath), true);\n return hl_HHRead(&file, blob);\n}\n\nenum HL_RESULT hl_HHStartWriteStandard(struct hl_File* file, uint32_t version)\n{\n \/\/ Create \"empty\" header\n hl_DHHStandardHeader header = {};\n header.Header.Version = version;\n header.DataOffset = sizeof(hl_DHHStandardHeader);\n\n \/\/ Write header\n file->DoEndianSwap = true;\n HL_RESULT result = file->Write(header);\n\n \/\/ Set origin\n if (HL_OK(result))\n {\n file->Origin = file->Tell();\n }\n\n return result;\n}\n\nenum HL_RESULT hl_HHWriteOffsetTableStandard(const struct hl_File* file,\n const hl_OffsetTable* offTable)\n{\n \/\/ Write offset count\n uint32_t offCount = static_cast(offTable->size());\n HL_RESULT result = file->Write(offCount);\n if (HL_FAILED(result)) return result;\n\n \/\/ Write offsets\n uint32_t off;\n const long* offsets = offTable->data();\n\n for (size_t i = 0; i < offTable->size(); ++i)\n {\n off = static_cast(\n offsets[i] - file->Origin);\n\n result = file->Write(off);\n if (HL_FAILED(result)) return result;\n }\n\n return result;\n}\n\nenum HL_RESULT hl_HHFinishWriteStandard(const struct hl_File* file, long headerPos,\n bool writeEOFThing, const hl_OffsetTable* offTable)\n{\n \/\/ Write offset table\n uint32_t offTablePos = static_cast(file->Tell());\n if (headerPos >= static_cast(offTablePos))\n return HL_ERROR_UNKNOWN; \/\/ TODO: Return a better error\n\n HL_RESULT result = hl_HHWriteOffsetTableStandard(file, offTable);\n if (HL_FAILED(result)) return result;\n\n \/\/ TODO: Write EOF thing if told to\n\n \/\/ Fill-in file size\n uint32_t fileSize = static_cast(file->Tell()) - headerPos;\n file->JumpTo(headerPos);\n\n result = file->Write(fileSize);\n if (HL_FAILED(result)) return result;\n\n if (file->JumpAhead(4)) return HL_ERROR_UNKNOWN; \/\/ TODO: Return better error\n\n \/\/ Fill-in data size\n uint32_t dataSize = (offTablePos -\n sizeof(hl_DHHStandardHeader));\n\n result = file->Write(dataSize);\n if (HL_FAILED(result)) return result;\n\n file->JumpAhead(4);\n\n \/\/ Fill-in offset table position\n result = file->Write(offTablePos);\n if (HL_FAILED(result)) return result;\n\n \/\/ TODO: Fill-in EOF position if told to\n return result;\n}\n\nvoid hl_HHFreeBlob(struct hl_Blob* blob)\n{\n#ifdef x64\n \/\/ Get offset table\n std::uint32_t offCount;\n std::uint32_t* offTable;\n void* data;\n\n if (!blob) return;\n\n if (hl_HHDetectHeaderType(blob->GetData<\n hl_DHHHeader>()) == HL_HHHEADER_TYPE_MIRAGE)\n {\n \/\/ TODO\n offCount = 0;\n offTable = nullptr;\n data = nullptr;\n }\n else\n {\n \/\/ Get offset table pointer\n hl_DHHStandardHeader* header = blob->GetData\n ();\n\n offTable = hl_GetAbs(\n header, header->OffsetTableOffset);\n\n \/\/ Get offset table count\n offCount = *offTable++;\n\n \/\/ Get data\n data = hl_GetAbs(header, header->DataOffset);\n }\n\n \/\/ Free all offsets using data in offset table\n for (uint32_t i = 0; i < offCount; ++i)\n {\n hl_x64RemoveAbsPtr32(*hl_GetAbs(\n data, offTable[i]));\n }\n#endif\n \n \/\/ Free data\n std::free(blob);\n}\n<|endoftext|>"} {"text":"\/\/ $Id: forceFieldComponent.C,v 1.4 2000\/03\/12 22:28:47 oliver Exp $\n\n\n#include \n\nusing namespace std;\n\nnamespace BALL \n{\n\n\t\/\/ default constructor \n\tForceFieldComponent::ForceFieldComponent()\n\t{\n\t\tname_ = \"GenericForceFieldComponent\";\n\t\tforce_field_ = 0;\n\t\tenergy_ = 0;\n\t}\n\n\t\/\/ constructor \n\tForceFieldComponent::ForceFieldComponent(ForceField* force_field)\n\t{\n\t\tforce_field_ = force_field;\n\t\tname_ = \"GenericForceFieldComponent\";\n\t\tenergy_ = 0;\t\n\t}\n\n\t\/\/ copy constructor \n\tForceFieldComponent::ForceFieldComponent(const ForceFieldComponent& force_field_component, bool \/* clone_deep *\/)\n\t{\n\t\tname_ = force_field_component.name_;\n\t\tforce_field_ = force_field_component.force_field_;\n\t\tenergy_ = force_field_component.energy_;\n\t}\n\n\n\t\/\/ destructor\n\tForceFieldComponent::~ForceFieldComponent()\n\t{\n\t}\n\n\t\/\/ setup\n\tbool ForceFieldComponent::setup()\n\t{\n\t\treturn true;\n\t}\n\n\t\/\/ Set the name of the component\n\tvoid ForceFieldComponent::setName(const String& name)\n\t{\n\t\tname_ = name;\n\t}\n\n\t\/\/ Return the name of the component\n\tString ForceFieldComponent::getName( ) const\n\t{\n\t\treturn name_;\n\t}\n\n\t\/\/ Return a pointer to the force field\n\tForceField* ForceFieldComponent::getForceField() const\n\t{\n\t\treturn force_field_;\n\t}\n\n\t\/\/ Set the force field to force_field \n\tvoid ForceFieldComponent::setForceField(ForceField* force_field)\n\t{\n\t\tforce_field_ = force_field;\n\t}\n\n\tfloat ForceFieldComponent::getEnergy() const\n\t{\n\t\treturn energy_;\n\t}\n\n\tfloat ForceFieldComponent::updateEnergy()\n\t{\n\t\treturn 0.0;\n\t}\n\t\n\tvoid ForceFieldComponent::updateForces() \n\t{\n\t}\n\n} \/\/ namespace BALL\nchanged: energies are double precision\/\/ $Id: forceFieldComponent.C,v 1.5 2000\/03\/25 22:51:56 oliver Exp $\n\n\n#include \n\nusing namespace std;\n\nnamespace BALL \n{\n\n\t\/\/ default constructor \n\tForceFieldComponent::ForceFieldComponent()\n\t{\n\t\tname_ = \"GenericForceFieldComponent\";\n\t\tforce_field_ = 0;\n\t\tenergy_ = 0;\n\t}\n\n\t\/\/ constructor \n\tForceFieldComponent::ForceFieldComponent(ForceField* force_field)\n\t{\n\t\tforce_field_ = force_field;\n\t\tname_ = \"GenericForceFieldComponent\";\n\t\tenergy_ = 0;\t\n\t}\n\n\t\/\/ copy constructor \n\tForceFieldComponent::ForceFieldComponent(const ForceFieldComponent& force_field_component, bool \/* clone_deep *\/)\n\t{\n\t\tname_ = force_field_component.name_;\n\t\tforce_field_ = force_field_component.force_field_;\n\t\tenergy_ = force_field_component.energy_;\n\t}\n\n\n\t\/\/ destructor\n\tForceFieldComponent::~ForceFieldComponent()\n\t{\n\t}\n\n\t\/\/ setup\n\tbool ForceFieldComponent::setup()\n\t{\n\t\treturn true;\n\t}\n\n\t\/\/ Set the name of the component\n\tvoid ForceFieldComponent::setName(const String& name)\n\t{\n\t\tname_ = name;\n\t}\n\n\t\/\/ Return the name of the component\n\tString ForceFieldComponent::getName( ) const\n\t{\n\t\treturn name_;\n\t}\n\n\t\/\/ Return a pointer to the force field\n\tForceField* ForceFieldComponent::getForceField() const\n\t{\n\t\treturn force_field_;\n\t}\n\n\t\/\/ Set the force field to force_field \n\tvoid ForceFieldComponent::setForceField(ForceField* force_field)\n\t{\n\t\tforce_field_ = force_field;\n\t}\n\n\tdouble ForceFieldComponent::getEnergy() const\n\t{\n\t\treturn energy_;\n\t}\n\n\tdouble ForceFieldComponent::updateEnergy()\n\t{\n\t\treturn 0.0;\n\t}\n\n\tvoid ForceFieldComponent::updateForces() \n\t{\n\t}\n\n} \/\/ namespace BALL\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2013 - 2014 Andrew Duggan\n * Copyright (C) 2013 - 2014 Synaptics Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hiddevice.h\"\n\n#define RMI4UPDATE_GETOPTS \"hp:ir:w:foam\"\n\n enum rmihidtool_cmd {\n\tRMIHIDTOOL_CMD_INTERACTIVE,\n\tRMIHIDTOOL_CMD_READ,\n\tRMIHIDTOOL_CMD_WRITE,\n\tRMIHIDTOOL_CMD_FW_ID,\n\tRMIHIDTOOL_CMD_PROPS,\n\tRMIHIDTOOL_CMD_ATTN,\n\tRMIHIDTOOL_CMD_PRINT_FUNCTIONS,\n};\n\nstatic int report_attn = 0;\nstatic RMIDevice * g_device = NULL;\n\nvoid print_help(const char *prog_name)\n{\n\tfprintf(stdout, \"Usage: %s [OPTIONS] DEVICEFILE\\n\", prog_name);\n\tfprintf(stdout, \"\\t-h, --help\\t\\t\\t\\tPrint this message\\n\");\n\tfprintf(stdout, \"\\t-p, --protocol [protocol]\\t\\tSet which transport prototocl to use.\\n\");\n\tfprintf(stdout, \"\\t-i, --interactive\\t\\t\\tRun in interactive mode.\\n\");\n\tfprintf(stdout, \"\\t-r, --read [address] [length]\\t\\tRead registers starting at the address.\\n\");\n\tfprintf(stdout, \"\\t-r, --write [address] [length] [data]\\tWrite registers starting at the address.\\n\");\n\tfprintf(stdout, \"\\t-f, --firmware-id\\t\\t\\tPrint the firmware id\\n\");\n\tfprintf(stdout, \"\\t-o, --props\\t\\t\\t\\tPrint device properties\\n\");\n\tfprintf(stdout, \"\\t-a, --attention\\t\\t\\t\\tPrint attention reports until control + c\\n\");\n\tfprintf(stdout, \"\\t-m, --print-functions\\t\\t\\tPrint RMI4 functions for the device.\\n\");\n}\n\nvoid print_cmd_usage()\n{\n\tfprintf(stdout, \"Commands:\\n\");\n\tfprintf(stdout, \"s [0,1,2]: Set RMIMode\\n\");\n\tfprintf(stdout, \"r address size: read size bytes from address\\n\");\n\tfprintf(stdout, \"w address { values }: write bytes to address\\n\");\n\tfprintf(stdout, \"a: Wait for attention\\n\");\n\tfprintf(stdout, \"q: quit\\n\");\n}\n\nint find_token(char * input, char * result, char ** endpp)\n{\n\tint i = 0;\n\tchar * start = input;\n\tchar * end;\n\n\twhile (input[i] == ' ') {\n\t\t++start;\n\t\t++i;\n\t}\n\n\twhile (input[i] != '\\0') {\n\t\tif (input[++i] == ' ')\n\t\t\tbreak;\n\t}\n\tend = &input[i];\n\n\tif (start == end)\n\t\treturn 0;\n\n\t*endpp = end;\n\tstrncpy(result, start, end - start);\n\tresult[end - start] = '\\0';\n\n\treturn 1;\n}\n\nvoid interactive(RMIDevice * device, unsigned char *report)\n{\n\tchar token[256];\n\tchar * start;\n\tchar * end;\n\tint rc;\n\n\tfor (;;) {\n\t\tfprintf(stdout, \"\\n\");\n\t\tprint_cmd_usage();\n\t\tchar input[256];\n\n\t\tif (fgets(input, 256, stdin)) {\n\t\t\tmemset(token, 0, 256);\n\n\t\t\tif (input[0] == 's') {\n\t\t\t\tstart = input + 2;\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tint mode = strtol(token, NULL, 0);\n\t\t\t\tif (mode >= 0 && mode <= 2) {\n\t\t\t\t\tif (device->SetMode(mode)) {\n\t\t\t\t\t\tfprintf(stderr, \"Set RMI Mode to: %d\\n\", mode);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"Set RMI Mode FAILED!\\n\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (input[0] == 'r') {\n\t\t\t\tstart = input + 2;\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tstart = end + 1;\n\t\t\t\tunsigned int addr = strtol(token, NULL, 0);\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tstart = end + 1;\n\t\t\t\tunsigned int len = strtol(token, NULL, 0);\n\t\t\t\tfprintf(stdout, \"Address = 0x%02x Length = %d\\n\", addr, len);\n\n\t\t\t\tmemset(report, 0, 256);\n\t\t\t\trc = device->Read(addr, report, len);\n\t\t\t\tif (rc < 0)\n\t\t\t\t\tfprintf(stderr, \"Failed to read report: %d\\n\", rc);\n\t\t\t\tprint_buffer(report, len);\n\t\t\t} else if (input[0] == 'w') {\n\t\t\t\tint index = 0;\n\t\t\t\tstart = input + 2;\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tstart = end + 1;\n\t\t\t\tunsigned int addr = strtol(token, NULL, 0);\n\t\t\t\tunsigned int len = 0;\n\n\t\t\t\tmemset(report, 0, 256);\n\t\t\t\twhile (find_token(start, token, &end)) {\n\t\t\t\t\tstart = end;\n\t\t\t\t\treport[index++] = strtol(token, NULL, 0);\n\t\t\t\t\t++len;\n\t\t\t\t}\n\n\t\t\t\tif (device->Write(addr, report, len) < 0) {\n\t\t\t\t\tfprintf(stderr, \"Failed to Write Report\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (input[0] == 'a') {\n\t\t\t\tunsigned int bytes = 256;\n\t\t\t\tdevice->GetAttentionReport(NULL,\n\t\t\t\t\t\tRMI_INTERUPT_SOURCES_ALL_MASK,\n\t\t\t\t\t\treport, &bytes);\n\t\t\t\tprint_buffer(report, bytes);\n\t\t\t} else if (input[0] == 'q') {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tprint_cmd_usage();\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void cleanup(int status)\n{\n\tif (report_attn) {\n\t\treport_attn = 0;\n\t\tif (g_device)\n\t\t\tg_device->Cancel();\n\t} else {\n\t\texit(0);\n\t}\n}\n\nint main(int argc, char ** argv)\n{\n\tint rc;\n\tstruct sigaction sig_cleanup_action;\n\tint opt;\n\tint index;\n\tRMIDevice *device;\n\tconst char *protocol = \"HID\";\n\tunsigned char report[256];\n\tchar token[256];\n\tstatic struct option long_options[] = {\n\t\t{\"help\", 0, NULL, 'h'},\n\t\t{\"protocol\", 1, NULL, 'p'},\n\t\t{\"interactive\", 0, NULL, 'i'},\n\t\t{\"read\", 1, NULL, 'r'},\n\t\t{\"write\", 1, NULL, 'w'},\n\t\t{\"firmware-id\", 0, NULL, 'f'},\n\t\t{\"props\", 0, NULL, 'o'},\n\t\t{\"attention\", 0, NULL, 'a'},\n\t\t{\"print-functions\", 0, NULL, 'm'},\n\t\t{0, 0, 0, 0},\n\t};\n\tenum rmihidtool_cmd cmd = RMIHIDTOOL_CMD_INTERACTIVE;\n\tunsigned int addr = 0;\n\tunsigned int len = 0;\n\tchar * data = NULL;\n\tchar * start;\n\tchar * end;\n\tint i = 0;\n\n\tmemset(&sig_cleanup_action, 0, sizeof(struct sigaction));\n\tsig_cleanup_action.sa_handler = cleanup;\n\tsig_cleanup_action.sa_flags = SA_RESTART;\n\tsigaction(SIGINT, &sig_cleanup_action, NULL);\n\n\twhile ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'h':\n\t\t\t\tprint_help(argv[0]);\n\t\t\t\treturn 0;\n\t\t\tcase 'p':\n\t\t\t\tprotocol = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_INTERACTIVE;\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_READ;\n\t\t\t\taddr = strtol(optarg, NULL, 0);\n\t\t\t\tlen = strtol(argv[optind++], NULL, 0);\n\t\t\t\tbreak;\n\t\t\tcase 'w':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_WRITE;\n\t\t\t\taddr = strtol(optarg, NULL, 0);\n\t\t\t\tdata = argv[optind++];\n\t\t\t\tbreak;\n\t\t\tcase 'f':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_FW_ID;\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_PROPS;\n\t\t\t\tbreak;\n\t\t\tcase 'a':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_ATTN;\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_PRINT_FUNCTIONS;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprint_help(argv[0]);\n\t\t\t\treturn 0;\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\n\tif (!strncasecmp(\"hid\", protocol, 3)) {\n\t\tdevice = new HIDDevice();\n\t} else {\n\t\tfprintf(stderr, \"Invalid Protocol: %s\\n\", protocol);\n\t\treturn -1;\n\t}\n\n\tif (optind >= argc) {\n\t\tprint_help(argv[0]);\n\t\treturn -1;\n\t}\n\n\trc = device->Open(argv[optind++]);\n\tif (rc) {\n\t\tfprintf(stderr, \"%s: failed to initialize rmi device (%d): %s\\n\", argv[0], errno,\n\t\t\tstrerror(errno));\n\t\treturn 1;\n\t}\n\n\tg_device = device;\n\n\tswitch (cmd) {\n\t\tcase RMIHIDTOOL_CMD_READ:\n\t\t\tmemset(report, 0, sizeof(report));\n\t\t\trc = device->Read(addr, report, len);\n\t\t\tif (rc < 0)\n\t\t\t\tfprintf(stderr, \"Failed to read report: %d\\n\", rc);\n\n\t\t\tprint_buffer(report, len);\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_WRITE:\n\t\t\ti = 0;\n\t\t\tstart = data;\n\t\t\tmemset(report, 0, sizeof(report));\n\t\t\twhile (find_token(start, token, &end)) {\n\t\t\t\tstart = end;\n\t\t\t\treport[i++] = (unsigned char)strtol(token, NULL, 0);\n\t\t\t\t++len;\n\t\t\t}\n\n\t\t\tif (device->Write(addr, report, len) < 0) {\n\t\t\t\tfprintf(stderr, \"Failed to Write Report\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_FW_ID:\n\t\t\tdevice->ScanPDT();\n\t\t\tdevice->QueryBasicProperties();\n\t\t\tfprintf(stdout, \"firmware id: %lu\\n\", device->GetFirmwareID());\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_PROPS:\n\t\t\tdevice->ScanPDT();\n\t\t\tdevice->QueryBasicProperties();\n\t\t\tdevice->PrintProperties();\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_ATTN:\n\t\t\treport_attn = 1;\n\t\t\twhile(report_attn) {\n\t\t\t\tunsigned int bytes = 256;\n\t\t\t\trc = device->GetAttentionReport(NULL,\n\t\t\t\t\t\tRMI_INTERUPT_SOURCES_ALL_MASK,\n\t\t\t\t\t\treport, &bytes);\n\t\t\t\tif (rc > 0) {\n\t\t\t\t\tprint_buffer(report, bytes);\n\t\t\t\t\tfprintf(stdout, \"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_PRINT_FUNCTIONS:\n\t\t\tdevice->ScanPDT();\n\t\t\tdevice->PrintFunctions();\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_INTERACTIVE:\n\t\tdefault:\n\t\t\tinteractive(device, report);\n\t\t\tbreak;\n\t}\n\n\tdevice->Close();\n\n\treturn 0;\n}\nAdd option to rebind the driver from rmihidtool.\/*\n * Copyright (C) 2013 - 2014 Andrew Duggan\n * Copyright (C) 2013 - 2014 Synaptics Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"hiddevice.h\"\n\n#define RMI4UPDATE_GETOPTS \"hp:ir:w:foamb\"\n\n enum rmihidtool_cmd {\n\tRMIHIDTOOL_CMD_INTERACTIVE,\n\tRMIHIDTOOL_CMD_READ,\n\tRMIHIDTOOL_CMD_WRITE,\n\tRMIHIDTOOL_CMD_FW_ID,\n\tRMIHIDTOOL_CMD_PROPS,\n\tRMIHIDTOOL_CMD_ATTN,\n\tRMIHIDTOOL_CMD_PRINT_FUNCTIONS,\n\tRMIHIDTOOL_CMD_REBIND_DRIVER,\n};\n\nstatic int report_attn = 0;\nstatic RMIDevice * g_device = NULL;\n\nvoid print_help(const char *prog_name)\n{\n\tfprintf(stdout, \"Usage: %s [OPTIONS] DEVICEFILE\\n\", prog_name);\n\tfprintf(stdout, \"\\t-h, --help\\t\\t\\t\\tPrint this message\\n\");\n\tfprintf(stdout, \"\\t-p, --protocol [protocol]\\t\\tSet which transport prototocl to use.\\n\");\n\tfprintf(stdout, \"\\t-i, --interactive\\t\\t\\tRun in interactive mode.\\n\");\n\tfprintf(stdout, \"\\t-r, --read [address] [length]\\t\\tRead registers starting at the address.\\n\");\n\tfprintf(stdout, \"\\t-r, --write [address] [length] [data]\\tWrite registers starting at the address.\\n\");\n\tfprintf(stdout, \"\\t-f, --firmware-id\\t\\t\\tPrint the firmware id\\n\");\n\tfprintf(stdout, \"\\t-o, --props\\t\\t\\t\\tPrint device properties\\n\");\n\tfprintf(stdout, \"\\t-a, --attention\\t\\t\\t\\tPrint attention reports until control + c\\n\");\n\tfprintf(stdout, \"\\t-m, --print-functions\\t\\t\\tPrint RMI4 functions for the device.\\n\");\n\tfprintf(stdout, \"\\t-b, --rebind-driver\\t\\t\\tRebind the driver to force an update of device properties.\\n\");\n}\n\nvoid print_cmd_usage()\n{\n\tfprintf(stdout, \"Commands:\\n\");\n\tfprintf(stdout, \"s [0,1,2]: Set RMIMode\\n\");\n\tfprintf(stdout, \"r address size: read size bytes from address\\n\");\n\tfprintf(stdout, \"w address { values }: write bytes to address\\n\");\n\tfprintf(stdout, \"a: Wait for attention\\n\");\n\tfprintf(stdout, \"q: quit\\n\");\n}\n\nint find_token(char * input, char * result, char ** endpp)\n{\n\tint i = 0;\n\tchar * start = input;\n\tchar * end;\n\n\twhile (input[i] == ' ') {\n\t\t++start;\n\t\t++i;\n\t}\n\n\twhile (input[i] != '\\0') {\n\t\tif (input[++i] == ' ')\n\t\t\tbreak;\n\t}\n\tend = &input[i];\n\n\tif (start == end)\n\t\treturn 0;\n\n\t*endpp = end;\n\tstrncpy(result, start, end - start);\n\tresult[end - start] = '\\0';\n\n\treturn 1;\n}\n\nvoid interactive(RMIDevice * device, unsigned char *report)\n{\n\tchar token[256];\n\tchar * start;\n\tchar * end;\n\tint rc;\n\n\tfor (;;) {\n\t\tfprintf(stdout, \"\\n\");\n\t\tprint_cmd_usage();\n\t\tchar input[256];\n\n\t\tif (fgets(input, 256, stdin)) {\n\t\t\tmemset(token, 0, 256);\n\n\t\t\tif (input[0] == 's') {\n\t\t\t\tstart = input + 2;\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tint mode = strtol(token, NULL, 0);\n\t\t\t\tif (mode >= 0 && mode <= 2) {\n\t\t\t\t\tif (device->SetMode(mode)) {\n\t\t\t\t\t\tfprintf(stderr, \"Set RMI Mode to: %d\\n\", mode);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfprintf(stderr, \"Set RMI Mode FAILED!\\n\");\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (input[0] == 'r') {\n\t\t\t\tstart = input + 2;\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tstart = end + 1;\n\t\t\t\tunsigned int addr = strtol(token, NULL, 0);\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tstart = end + 1;\n\t\t\t\tunsigned int len = strtol(token, NULL, 0);\n\t\t\t\tfprintf(stdout, \"Address = 0x%02x Length = %d\\n\", addr, len);\n\n\t\t\t\tmemset(report, 0, 256);\n\t\t\t\trc = device->Read(addr, report, len);\n\t\t\t\tif (rc < 0)\n\t\t\t\t\tfprintf(stderr, \"Failed to read report: %d\\n\", rc);\n\t\t\t\tprint_buffer(report, len);\n\t\t\t} else if (input[0] == 'w') {\n\t\t\t\tint index = 0;\n\t\t\t\tstart = input + 2;\n\t\t\t\tfind_token(start, token, &end);\n\t\t\t\tstart = end + 1;\n\t\t\t\tunsigned int addr = strtol(token, NULL, 0);\n\t\t\t\tunsigned int len = 0;\n\n\t\t\t\tmemset(report, 0, 256);\n\t\t\t\twhile (find_token(start, token, &end)) {\n\t\t\t\t\tstart = end;\n\t\t\t\t\treport[index++] = strtol(token, NULL, 0);\n\t\t\t\t\t++len;\n\t\t\t\t}\n\n\t\t\t\tif (device->Write(addr, report, len) < 0) {\n\t\t\t\t\tfprintf(stderr, \"Failed to Write Report\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (input[0] == 'a') {\n\t\t\t\tunsigned int bytes = 256;\n\t\t\t\tdevice->GetAttentionReport(NULL,\n\t\t\t\t\t\tRMI_INTERUPT_SOURCES_ALL_MASK,\n\t\t\t\t\t\treport, &bytes);\n\t\t\t\tprint_buffer(report, bytes);\n\t\t\t} else if (input[0] == 'q') {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tprint_cmd_usage();\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void cleanup(int status)\n{\n\tif (report_attn) {\n\t\treport_attn = 0;\n\t\tif (g_device)\n\t\t\tg_device->Cancel();\n\t} else {\n\t\texit(0);\n\t}\n}\n\nint main(int argc, char ** argv)\n{\n\tint rc;\n\tstruct sigaction sig_cleanup_action;\n\tint opt;\n\tint index;\n\tRMIDevice *device;\n\tconst char *protocol = \"HID\";\n\tunsigned char report[256];\n\tchar token[256];\n\tstatic struct option long_options[] = {\n\t\t{\"help\", 0, NULL, 'h'},\n\t\t{\"protocol\", 1, NULL, 'p'},\n\t\t{\"interactive\", 0, NULL, 'i'},\n\t\t{\"read\", 1, NULL, 'r'},\n\t\t{\"write\", 1, NULL, 'w'},\n\t\t{\"firmware-id\", 0, NULL, 'f'},\n\t\t{\"props\", 0, NULL, 'o'},\n\t\t{\"attention\", 0, NULL, 'a'},\n\t\t{\"print-functions\", 0, NULL, 'm'},\n\t\t{\"rebind-driver\", 0, NULL, 'b'},\n\t\t{0, 0, 0, 0},\n\t};\n\tenum rmihidtool_cmd cmd = RMIHIDTOOL_CMD_INTERACTIVE;\n\tunsigned int addr = 0;\n\tunsigned int len = 0;\n\tchar * data = NULL;\n\tchar * start;\n\tchar * end;\n\tint i = 0;\n\n\tmemset(&sig_cleanup_action, 0, sizeof(struct sigaction));\n\tsig_cleanup_action.sa_handler = cleanup;\n\tsig_cleanup_action.sa_flags = SA_RESTART;\n\tsigaction(SIGINT, &sig_cleanup_action, NULL);\n\n\twhile ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'h':\n\t\t\t\tprint_help(argv[0]);\n\t\t\t\treturn 0;\n\t\t\tcase 'p':\n\t\t\t\tprotocol = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_INTERACTIVE;\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_READ;\n\t\t\t\taddr = strtol(optarg, NULL, 0);\n\t\t\t\tlen = strtol(argv[optind++], NULL, 0);\n\t\t\t\tbreak;\n\t\t\tcase 'w':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_WRITE;\n\t\t\t\taddr = strtol(optarg, NULL, 0);\n\t\t\t\tdata = argv[optind++];\n\t\t\t\tbreak;\n\t\t\tcase 'f':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_FW_ID;\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_PROPS;\n\t\t\t\tbreak;\n\t\t\tcase 'a':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_ATTN;\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_PRINT_FUNCTIONS;\n\t\t\t\tbreak;\n\t\t\tcase 'b':\n\t\t\t\tcmd = RMIHIDTOOL_CMD_REBIND_DRIVER;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprint_help(argv[0]);\n\t\t\t\treturn 0;\n\t\t\t\tbreak;\n\n\t\t}\n\t}\n\n\tif (!strncasecmp(\"hid\", protocol, 3)) {\n\t\tdevice = new HIDDevice();\n\t} else {\n\t\tfprintf(stderr, \"Invalid Protocol: %s\\n\", protocol);\n\t\treturn -1;\n\t}\n\n\tif (optind >= argc) {\n\t\tprint_help(argv[0]);\n\t\treturn -1;\n\t}\n\n\trc = device->Open(argv[optind++]);\n\tif (rc) {\n\t\tfprintf(stderr, \"%s: failed to initialize rmi device (%d): %s\\n\", argv[0], errno,\n\t\t\tstrerror(errno));\n\t\treturn 1;\n\t}\n\n\tg_device = device;\n\n\tswitch (cmd) {\n\t\tcase RMIHIDTOOL_CMD_READ:\n\t\t\tmemset(report, 0, sizeof(report));\n\t\t\trc = device->Read(addr, report, len);\n\t\t\tif (rc < 0)\n\t\t\t\tfprintf(stderr, \"Failed to read report: %d\\n\", rc);\n\n\t\t\tprint_buffer(report, len);\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_WRITE:\n\t\t\ti = 0;\n\t\t\tstart = data;\n\t\t\tmemset(report, 0, sizeof(report));\n\t\t\twhile (find_token(start, token, &end)) {\n\t\t\t\tstart = end;\n\t\t\t\treport[i++] = (unsigned char)strtol(token, NULL, 0);\n\t\t\t\t++len;\n\t\t\t}\n\n\t\t\tif (device->Write(addr, report, len) < 0) {\n\t\t\t\tfprintf(stderr, \"Failed to Write Report\\n\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_FW_ID:\n\t\t\tdevice->ScanPDT();\n\t\t\tdevice->QueryBasicProperties();\n\t\t\tfprintf(stdout, \"firmware id: %lu\\n\", device->GetFirmwareID());\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_PROPS:\n\t\t\tdevice->ScanPDT();\n\t\t\tdevice->QueryBasicProperties();\n\t\t\tdevice->PrintProperties();\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_ATTN:\n\t\t\treport_attn = 1;\n\t\t\twhile(report_attn) {\n\t\t\t\tunsigned int bytes = 256;\n\t\t\t\trc = device->GetAttentionReport(NULL,\n\t\t\t\t\t\tRMI_INTERUPT_SOURCES_ALL_MASK,\n\t\t\t\t\t\treport, &bytes);\n\t\t\t\tif (rc > 0) {\n\t\t\t\t\tprint_buffer(report, bytes);\n\t\t\t\t\tfprintf(stdout, \"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_PRINT_FUNCTIONS:\n\t\t\tdevice->ScanPDT();\n\t\t\tdevice->PrintFunctions();\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_REBIND_DRIVER:\n\t\t\tdevice->RebindDriver();\n\t\t\tbreak;\n\t\tcase RMIHIDTOOL_CMD_INTERACTIVE:\n\t\tdefault:\n\t\t\tinteractive(device, report);\n\t\t\tbreak;\n\t}\n\n\tdevice->Close();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \"ModulusRemainder.h\"\n#include \"IROperator.h\"\n#include \"IRPrinter.h\"\n#include \"IR.h\"\n#include \"Simplify.h\"\n\n\/\/ This file is largely a port of parts of src\/analysis.ml\nnamespace Halide {\nnamespace Internal {\n\nclass ComputeModulusRemainder : public IRVisitor {\npublic:\n ModulusRemainder analyze(Expr e);\n\n int modulus, remainder;\n Scope scope;\n\n ComputeModulusRemainder(const Scope *s) {\n scope.set_containing_scope(s);\n }\n\n void visit(const IntImm *);\n void visit(const UIntImm *);\n void visit(const FloatImm *);\n void visit(const StringImm *);\n void visit(const Cast *);\n void visit(const Variable *);\n void visit(const Add *);\n void visit(const Sub *);\n void visit(const Mul *);\n void visit(const Div *);\n void visit(const Mod *);\n void visit(const Min *);\n void visit(const Max *);\n void visit(const EQ *);\n void visit(const NE *);\n void visit(const LT *);\n void visit(const LE *);\n void visit(const GT *);\n void visit(const GE *);\n void visit(const And *);\n void visit(const Or *);\n void visit(const Not *);\n void visit(const Select *);\n void visit(const Load *);\n void visit(const Ramp *);\n void visit(const Broadcast *);\n void visit(const Call *);\n void visit(const Let *);\n void visit(const LetStmt *);\n void visit(const AssertStmt *);\n void visit(const ProducerConsumer *);\n void visit(const For *);\n void visit(const Store *);\n void visit(const Provide *);\n void visit(const Allocate *);\n void visit(const Realize *);\n void visit(const Block *);\n void visit(const IfThenElse *);\n void visit(const Free *);\n void visit(const Evaluate *);\n};\n\nModulusRemainder modulus_remainder(Expr e) {\n ComputeModulusRemainder mr(NULL);\n return mr.analyze(e);\n}\n\nModulusRemainder modulus_remainder(Expr e, const Scope &scope) {\n ComputeModulusRemainder mr(&scope);\n return mr.analyze(e);\n}\n\n\n\nbool reduce_expr_modulo(Expr expr, int modulus, int *remainder) {\n ModulusRemainder result = modulus_remainder(expr);\n\n \/* As an example: If we asked for expr mod 8, and the analysis\n * said that expr = 16*k + 13, then because 16 % 8 == 0, the\n * result is 13 % 8 == 5. But if the analysis says that expr =\n * 6*k + 3, then expr mod 8 could be 1, 3, 5, or 7, so we just\n * return false.\n *\/\n\n if (result.modulus % modulus == 0) {\n *remainder = result.remainder % modulus;\n return true;\n } else {\n return false;\n }\n}\n\nModulusRemainder ComputeModulusRemainder::analyze(Expr e) {\n e.accept(this);\n return ModulusRemainder(modulus, remainder);\n}\n\nnamespace {\nvoid check(Expr e, int m, int r) {\n ModulusRemainder result = modulus_remainder(e);\n if (result.modulus != m || result.remainder != r) {\n std::cerr << \"Test failed for modulus_remainder:\\n\";\n std::cerr << \"Expression: \" << e << \"\\n\";\n std::cerr << \"Correct modulus, remainder = \" << m << \", \" << r << \"\\n\";\n std::cerr << \"Computed modulus, remainder = \"\n << result.modulus << \", \"\n << result.remainder << \"\\n\";\n exit(-1);\n }\n}\n}\n\nvoid modulus_remainder_test() {\n Expr x = Variable::make(Int(32), \"x\");\n Expr y = Variable::make(Int(32), \"y\");\n\n check((30*x + 3) + (40*y + 2), 10, 5);\n check((6*x + 3) * (4*y + 1), 2, 1);\n check(max(30*x - 24, 40*y + 31), 5, 1);\n check(10*x - 33*y, 1, 0);\n check(10*x - 35*y, 5, 0);\n check(123, 0, 123);\n check(Let::make(\"y\", x*3 + 4, y*3 + 4), 9, 7);\n\n std::cout << \"modulus_remainder test passed\\n\";\n}\n\n\nvoid ComputeModulusRemainder::visit(const IntImm *op) {\n \/\/ Equal to op->value modulo anything. We'll use zero as the\n \/\/ modulus to mark this special case. We'd better be able to\n \/\/ handle zero in the rest of the code...\n remainder = op->value;\n modulus = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const UIntImm *op) {\n internal_error << \"modulus_remainder of uint\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const FloatImm *) {\n internal_error << \"modulus_remainder of float\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const StringImm *) {\n internal_error << \"modulus_remainder of string\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Cast *) {\n modulus = 1;\n remainder = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const Variable *op) {\n if (scope.contains(op->name)) {\n ModulusRemainder mod_rem = scope.get(op->name);\n modulus = mod_rem.modulus;\n remainder = mod_rem.remainder;\n } else {\n modulus = 1;\n remainder = 0;\n }\n}\n\nint gcd(int a, int b) {\n if (a < b) std::swap(a, b);\n while (b != 0) {\n int tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\nint lcm(int a, int b) {\n return (a*b)\/gcd(a, b);\n}\n\nint mod(int a, int m) {\n if (m == 0) return a;\n return mod_imp(a, m);\n}\n\nvoid ComputeModulusRemainder::visit(const Add *op) {\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n modulus = gcd(a.modulus, b.modulus);\n remainder = mod(a.remainder + b.remainder, modulus);\n}\n\nvoid ComputeModulusRemainder::visit(const Sub *op) {\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n modulus = gcd(a.modulus, b.modulus);\n remainder = mod(a.remainder - b.remainder, modulus);\n}\n\nvoid ComputeModulusRemainder::visit(const Mul *op) {\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n\n if (a.modulus == 0) {\n \/\/ a is constant\n modulus = a.remainder * b.modulus;\n remainder = a.remainder * b.remainder;\n } else if (b.modulus == 0) {\n \/\/ b is constant\n modulus = b.remainder * a.modulus;\n remainder = a.remainder * b.remainder;\n } else if (a.remainder == 0 && b.remainder == 0) {\n \/\/ multiple times multiple\n modulus = a.modulus * b.modulus;\n remainder = 0;\n } else if (a.remainder == 0) {\n modulus = a.modulus * gcd(b.modulus, b.remainder);\n remainder = 0;\n } else if (b.remainder == 0) {\n modulus = b.modulus * gcd(a.modulus, a.remainder);\n remainder = 0;\n } else {\n \/\/ All our tricks failed. Convert them to the same modulus and multiply\n modulus = gcd(a.modulus, b.modulus);\n a.remainder = mod(a.remainder * b.remainder, modulus);\n }\n}\n\nvoid ComputeModulusRemainder::visit(const Div *) {\n \/\/ We might be able to say something about this if the numerator\n \/\/ modulus is provably a multiple of a constant denominator, but\n \/\/ in this case we should have simplified away the division.\n remainder = 0;\n modulus = 1;\n}\n\nnamespace {\nModulusRemainder unify_alternatives(ModulusRemainder a, ModulusRemainder b) {\n \/\/ We don't know if we're going to get a or b, so we'd better find\n \/\/ a single modulus remainder that works for both.\n\n \/\/ For example:\n \/\/ max(30*_ + 13, 40*_ + 27) ->\n \/\/ max(10*_ + 3, 10*_ + 7) ->\n \/\/ max(2*_ + 1, 2*_ + 1) ->\n \/\/ 2*_ + 1\n\n \/\/ Reduce them to the same modulus and the same remainder\n int modulus = gcd(a.modulus, b.modulus);\n int diff = a.remainder - b.remainder;\n if (diff < 0) diff = -diff;\n modulus = gcd(diff, modulus);\n\n int ra = mod(a.remainder, modulus);\n\n internal_assert(ra == mod(b.remainder, modulus))\n << \"There's a bug inside ModulusRemainder in unify_alternatives\\n\";\n\n return ModulusRemainder(modulus, ra);\n}\n}\n\nvoid ComputeModulusRemainder::visit(const Mod *op) {\n \/\/ We can treat x mod y as x + z*y, where we know nothing about z.\n \/\/ (ax + b) + z (cx + d) ->\n \/\/ ax + b + zcx + dz ->\n \/\/ gcd(a, c, d) * w + b\n\n \/\/ E.g:\n \/\/ (8x + 5) mod (6x + 2) ->\n \/\/ (8x + 5) + z (6x + 2) ->\n \/\/ (8x + 6zx + 2x) + 5 ->\n \/\/ 2(4x + 3zx + x) + 5 ->\n \/\/ 2w + 1\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n modulus = gcd(a.modulus, b.modulus);\n modulus = gcd(modulus, b.remainder);\n remainder = mod(a.remainder, modulus);\n}\n\nvoid ComputeModulusRemainder::visit(const Min *op) {\n ModulusRemainder r = unify_alternatives(analyze(op->a), analyze(op->b));\n modulus = r.modulus;\n remainder = r.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const Max *op) {\n ModulusRemainder r = unify_alternatives(analyze(op->a), analyze(op->b));\n modulus = r.modulus;\n remainder = r.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const EQ *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const NE *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const LT *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const LE *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const GT *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const GE *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const And *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Or *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Not *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Select *op) {\n ModulusRemainder r = unify_alternatives(analyze(op->true_value),\n analyze(op->false_value));\n modulus = r.modulus;\n remainder = r.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const Load *) {\n modulus = 1;\n remainder = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const Ramp *) {\n internal_assert(false) << \"modulus_remainder of vector\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Broadcast *) {\n internal_assert(false) << \"modulus_remainder of vector\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Call *) {\n modulus = 1;\n remainder = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const Let *op) {\n bool value_interesting = op->value.type().is_int();\n\n if (value_interesting) {\n ModulusRemainder val = analyze(op->value);\n scope.push(op->name, val);\n }\n ModulusRemainder val = analyze(op->body);\n if (value_interesting) {\n scope.pop(op->name);\n }\n modulus = val.modulus;\n remainder = val.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const LetStmt *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const AssertStmt *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const ProducerConsumer *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const For *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Store *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Provide *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Allocate *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Realize *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Block *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Free *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const IfThenElse *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Evaluate *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\n}\n}\nFix subtle overflow bug in unify_alternatives#include \"ModulusRemainder.h\"\n#include \"IROperator.h\"\n#include \"IRPrinter.h\"\n#include \"IR.h\"\n#include \"Simplify.h\"\n\n\/\/ This file is largely a port of parts of src\/analysis.ml\nnamespace Halide {\nnamespace Internal {\n\nclass ComputeModulusRemainder : public IRVisitor {\npublic:\n ModulusRemainder analyze(Expr e);\n\n int modulus, remainder;\n Scope scope;\n\n ComputeModulusRemainder(const Scope *s) {\n scope.set_containing_scope(s);\n }\n\n void visit(const IntImm *);\n void visit(const UIntImm *);\n void visit(const FloatImm *);\n void visit(const StringImm *);\n void visit(const Cast *);\n void visit(const Variable *);\n void visit(const Add *);\n void visit(const Sub *);\n void visit(const Mul *);\n void visit(const Div *);\n void visit(const Mod *);\n void visit(const Min *);\n void visit(const Max *);\n void visit(const EQ *);\n void visit(const NE *);\n void visit(const LT *);\n void visit(const LE *);\n void visit(const GT *);\n void visit(const GE *);\n void visit(const And *);\n void visit(const Or *);\n void visit(const Not *);\n void visit(const Select *);\n void visit(const Load *);\n void visit(const Ramp *);\n void visit(const Broadcast *);\n void visit(const Call *);\n void visit(const Let *);\n void visit(const LetStmt *);\n void visit(const AssertStmt *);\n void visit(const ProducerConsumer *);\n void visit(const For *);\n void visit(const Store *);\n void visit(const Provide *);\n void visit(const Allocate *);\n void visit(const Realize *);\n void visit(const Block *);\n void visit(const IfThenElse *);\n void visit(const Free *);\n void visit(const Evaluate *);\n};\n\nModulusRemainder modulus_remainder(Expr e) {\n ComputeModulusRemainder mr(NULL);\n return mr.analyze(e);\n}\n\nModulusRemainder modulus_remainder(Expr e, const Scope &scope) {\n ComputeModulusRemainder mr(&scope);\n return mr.analyze(e);\n}\n\n\n\nbool reduce_expr_modulo(Expr expr, int modulus, int *remainder) {\n ModulusRemainder result = modulus_remainder(expr);\n\n \/* As an example: If we asked for expr mod 8, and the analysis\n * said that expr = 16*k + 13, then because 16 % 8 == 0, the\n * result is 13 % 8 == 5. But if the analysis says that expr =\n * 6*k + 3, then expr mod 8 could be 1, 3, 5, or 7, so we just\n * return false.\n *\/\n\n if (result.modulus % modulus == 0) {\n *remainder = result.remainder % modulus;\n return true;\n } else {\n return false;\n }\n}\n\nModulusRemainder ComputeModulusRemainder::analyze(Expr e) {\n e.accept(this);\n return ModulusRemainder(modulus, remainder);\n}\n\nnamespace {\nvoid check(Expr e, int m, int r) {\n ModulusRemainder result = modulus_remainder(e);\n if (result.modulus != m || result.remainder != r) {\n std::cerr << \"Test failed for modulus_remainder:\\n\";\n std::cerr << \"Expression: \" << e << \"\\n\";\n std::cerr << \"Correct modulus, remainder = \" << m << \", \" << r << \"\\n\";\n std::cerr << \"Computed modulus, remainder = \"\n << result.modulus << \", \"\n << result.remainder << \"\\n\";\n exit(-1);\n }\n}\n}\n\nvoid modulus_remainder_test() {\n Expr x = Variable::make(Int(32), \"x\");\n Expr y = Variable::make(Int(32), \"y\");\n\n check((30*x + 3) + (40*y + 2), 10, 5);\n check((6*x + 3) * (4*y + 1), 2, 1);\n check(max(30*x - 24, 40*y + 31), 5, 1);\n check(10*x - 33*y, 1, 0);\n check(10*x - 35*y, 5, 0);\n check(123, 0, 123);\n check(Let::make(\"y\", x*3 + 4, y*3 + 4), 9, 7);\n\n std::cout << \"modulus_remainder test passed\\n\";\n}\n\n\nvoid ComputeModulusRemainder::visit(const IntImm *op) {\n \/\/ Equal to op->value modulo anything. We'll use zero as the\n \/\/ modulus to mark this special case. We'd better be able to\n \/\/ handle zero in the rest of the code...\n remainder = op->value;\n modulus = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const UIntImm *op) {\n internal_error << \"modulus_remainder of uint\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const FloatImm *) {\n internal_error << \"modulus_remainder of float\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const StringImm *) {\n internal_error << \"modulus_remainder of string\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Cast *) {\n modulus = 1;\n remainder = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const Variable *op) {\n if (scope.contains(op->name)) {\n ModulusRemainder mod_rem = scope.get(op->name);\n modulus = mod_rem.modulus;\n remainder = mod_rem.remainder;\n } else {\n modulus = 1;\n remainder = 0;\n }\n}\n\nint gcd(int a, int b) {\n if (a < b) std::swap(a, b);\n while (b != 0) {\n int64_t tmp = b;\n b = a % b;\n a = tmp;\n }\n return a;\n}\n\nint lcm(int a, int b) {\n return (a*b)\/gcd(a, b);\n}\n\nint mod(int a, int m) {\n if (m == 0) return a;\n return mod_imp(a, m);\n}\n\nvoid ComputeModulusRemainder::visit(const Add *op) {\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n modulus = gcd(a.modulus, b.modulus);\n remainder = mod(a.remainder + b.remainder, modulus);\n}\n\nvoid ComputeModulusRemainder::visit(const Sub *op) {\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n modulus = gcd(a.modulus, b.modulus);\n remainder = mod(a.remainder - b.remainder, modulus);\n}\n\nvoid ComputeModulusRemainder::visit(const Mul *op) {\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n\n if (a.modulus == 0) {\n \/\/ a is constant\n modulus = a.remainder * b.modulus;\n remainder = a.remainder * b.remainder;\n } else if (b.modulus == 0) {\n \/\/ b is constant\n modulus = b.remainder * a.modulus;\n remainder = a.remainder * b.remainder;\n } else if (a.remainder == 0 && b.remainder == 0) {\n \/\/ multiple times multiple\n modulus = a.modulus * b.modulus;\n remainder = 0;\n } else if (a.remainder == 0) {\n modulus = a.modulus * gcd(b.modulus, b.remainder);\n remainder = 0;\n } else if (b.remainder == 0) {\n modulus = b.modulus * gcd(a.modulus, a.remainder);\n remainder = 0;\n } else {\n \/\/ All our tricks failed. Convert them to the same modulus and multiply\n modulus = gcd(a.modulus, b.modulus);\n a.remainder = mod(a.remainder * b.remainder, modulus);\n }\n}\n\nvoid ComputeModulusRemainder::visit(const Div *) {\n \/\/ We might be able to say something about this if the numerator\n \/\/ modulus is provably a multiple of a constant denominator, but\n \/\/ in this case we should have simplified away the division.\n remainder = 0;\n modulus = 1;\n}\n\nnamespace {\nModulusRemainder unify_alternatives(ModulusRemainder a, ModulusRemainder b) {\n \/\/ We don't know if we're going to get a or b, so we'd better find\n \/\/ a single modulus remainder that works for both.\n\n \/\/ For example:\n \/\/ max(30*_ + 13, 40*_ + 27) ->\n \/\/ max(10*_ + 3, 10*_ + 7) ->\n \/\/ max(2*_ + 1, 2*_ + 1) ->\n \/\/ 2*_ + 1\n\n \/\/ Reduce them to the same modulus and the same remainder\n int modulus = gcd(a.modulus, b.modulus);\n int64_t diff = (int64_t)a.remainder - (int64_t)b.remainder;\n if (!Int(32).can_represent(diff)) {\n \/\/ The difference overflows.\n return ModulusRemainder(0, 1);\n }\n if (diff < 0) diff = -diff;\n modulus = gcd((int)diff, modulus);\n\n int ra = mod(a.remainder, modulus);\n\n internal_assert(ra == mod(b.remainder, modulus))\n << \"There's a bug inside ModulusRemainder in unify_alternatives:\\n\"\n << \"a.modulus = \" << a.modulus << \"\\n\"\n << \"a.remainder = \" << a.remainder << \"\\n\"\n << \"b.modulus = \" << b.modulus << \"\\n\"\n << \"b.remainder = \" << b.remainder << \"\\n\"\n << \"diff = \" << diff << \"\\n\"\n << \"unified modulus = \" << modulus << \"\\n\"\n << \"unified remainder = \" << ra << \"\\n\";\n\n\n return ModulusRemainder(modulus, ra);\n}\n}\n\nvoid ComputeModulusRemainder::visit(const Mod *op) {\n \/\/ We can treat x mod y as x + z*y, where we know nothing about z.\n \/\/ (ax + b) + z (cx + d) ->\n \/\/ ax + b + zcx + dz ->\n \/\/ gcd(a, c, d) * w + b\n\n \/\/ E.g:\n \/\/ (8x + 5) mod (6x + 2) ->\n \/\/ (8x + 5) + z (6x + 2) ->\n \/\/ (8x + 6zx + 2x) + 5 ->\n \/\/ 2(4x + 3zx + x) + 5 ->\n \/\/ 2w + 1\n ModulusRemainder a = analyze(op->a);\n ModulusRemainder b = analyze(op->b);\n modulus = gcd(a.modulus, b.modulus);\n modulus = gcd(modulus, b.remainder);\n remainder = mod(a.remainder, modulus);\n}\n\nvoid ComputeModulusRemainder::visit(const Min *op) {\n ModulusRemainder r = unify_alternatives(analyze(op->a), analyze(op->b));\n modulus = r.modulus;\n remainder = r.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const Max *op) {\n ModulusRemainder r = unify_alternatives(analyze(op->a), analyze(op->b));\n modulus = r.modulus;\n remainder = r.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const EQ *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const NE *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const LT *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const LE *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const GT *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const GE *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const And *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Or *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Not *) {\n internal_assert(false) << \"modulus_remainder of bool\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Select *op) {\n ModulusRemainder r = unify_alternatives(analyze(op->true_value),\n analyze(op->false_value));\n modulus = r.modulus;\n remainder = r.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const Load *) {\n modulus = 1;\n remainder = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const Ramp *) {\n internal_assert(false) << \"modulus_remainder of vector\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Broadcast *) {\n internal_assert(false) << \"modulus_remainder of vector\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Call *) {\n modulus = 1;\n remainder = 0;\n}\n\nvoid ComputeModulusRemainder::visit(const Let *op) {\n bool value_interesting = op->value.type().is_int();\n\n if (value_interesting) {\n ModulusRemainder val = analyze(op->value);\n scope.push(op->name, val);\n }\n ModulusRemainder val = analyze(op->body);\n if (value_interesting) {\n scope.pop(op->name);\n }\n modulus = val.modulus;\n remainder = val.remainder;\n}\n\nvoid ComputeModulusRemainder::visit(const LetStmt *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const AssertStmt *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const ProducerConsumer *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const For *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Store *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Provide *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Allocate *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Realize *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Block *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Free *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const IfThenElse *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\nvoid ComputeModulusRemainder::visit(const Evaluate *) {\n internal_assert(false) << \"modulus_remainder of statement\\n\";\n}\n\n}\n}\n<|endoftext|>"} {"text":"#include \"StdAfx.h\"\r\n#include \"SetControlValuesTask.h\"\r\n\r\nSetControlValuesTask::SetControlValuesTask(const htmlayout::dom::element& root, HANDLE evt, std::wstring * perror)\r\n\t: m_root(root)\r\n\t, m_event(evt)\r\n\t, m_perror(perror)\r\n{\r\n\r\n}\r\n\r\nvoid SetControlValuesTask::exec(htmlayout::dom::element elt)\r\n{\r\n\tif (elt.is_valid())\r\n\t{\r\n\t\tconst wchar_t * id = elt.get_attribute(\"id\");\r\n\t\tconst wchar_t * type = elt.get_attribute(\"type\");\r\n\t\tconst wchar_t * control_ptr = elt.get_attribute(\"control_ptr\");\r\n\t\tconst wchar_t * disabled_a = elt.get_attribute(\"disabled\");\r\n\t\tbool disabled = (disabled_a != NULL && wcslen(disabled_a) > 0);\r\n\t\tconst wchar_t * has_value_disabled_a = elt.get_attribute(\"has_value_disabled\");\r\n\t\tbool has_value_disabled = (has_value_disabled_a != NULL && wcslen(has_value_disabled_a) > 0);\r\n\r\n\t\tif (id != NULL && type != NULL && (! disabled || has_value_disabled))\r\n\t\t{\r\n\t\t\tif (0 == wcscmp(type, L\"checkbox\") && elt.get_attribute(\"license\") != NULL)\r\n\t\t\t{\r\n\t\t\t\tControlLicense * p_license = reinterpret_cast(DVLib::wstring2long(control_ptr, 16));\r\n\t\t\t\tif (! InstallUILevelSetting::Instance->IsSilent())\r\n\t\t\t\t{\r\n\t\t\t\t\tif (! elt.get_state(STATE_CHECKED))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTHROW_EX(p_license->accept_message);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::wstring value = elt.get_state(STATE_CHECKED) ? L\"1\" : L\"0\";\r\n\t\t\t\tLOG(L\"--- Setting user-defined license value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"checkbox\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value;\r\n\t\t\t\tif (control_ptr != NULL)\r\n\t\t\t\t{\r\n\t\t\t\t\tControlCheckBox * p_checkbox = reinterpret_cast(DVLib::wstring2long(control_ptr, 16));\r\n\t\t\t\t\tvalue = elt.get_state(STATE_CHECKED) ? p_checkbox->checked_value.GetValue() : p_checkbox->unchecked_value.GetValue();\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue = elt.get_state(STATE_CHECKED) ? L\"1\" : L\"0\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tLOG(L\"--- Setting user-defined checkbox value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"text\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value = elt.get_value().to_string();\r\n\t\t\t\tLOG(L\"--- Setting user-defined edit value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"file-path\") || 0 == wcscmp(type, L\"folder-path\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value = elt.get_value().to_string();\r\n\t\t\t\tif (value.empty()) value = elt.get_attribute(\"novalue\");\r\n\t\t\t\tvalue = DVLib::StripPathTerminator(value);\r\n\t\t\t\tLOG(L\"--- Setting user-defined browse value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ TODO: support widget types: select, dropdown-select, textarea, htmlarea\r\n\t\t}\r\n\r\n\t\tfor(unsigned int child_index = 0; child_index < elt.children_count(); child_index++)\r\n\t\t{\r\n\t\t\texec(elt.child(child_index));\r\n\t\t}\r\n\t}\r\n}\r\n\t\r\nvoid SetControlValuesTask::exec()\r\n{\r\n\ttry\r\n\t{\r\n\t\texec(m_root);\r\n\t}\r\n\tcatch(std::exception& ex)\r\n\t{\r\n\t\tTRYLOG(L\"Error: \" << DVLib::string2wstring(ex.what()));\r\n\t\tif (NULL != m_perror)\r\n\t\t{\r\n\t\t\t* m_perror = DVLib::string2wstring(ex.what());\r\n\t\t}\r\n\t}\r\n\r\n\tCHECK_WIN32_BOOL(SetEvent(m_event),\r\n\t\tL\"SetEvent\");\r\n}\r\nAdd HTML support for radio button user values#include \"StdAfx.h\"\r\n#include \"SetControlValuesTask.h\"\r\n\r\nSetControlValuesTask::SetControlValuesTask(const htmlayout::dom::element& root, HANDLE evt, std::wstring * perror)\r\n\t: m_root(root)\r\n\t, m_event(evt)\r\n\t, m_perror(perror)\r\n{\r\n\r\n}\r\n\r\nvoid SetControlValuesTask::exec(htmlayout::dom::element elt)\r\n{\r\n\tif (elt.is_valid())\r\n\t{\r\n\t\tconst wchar_t * id = elt.get_attribute(\"id\");\r\n\t\tconst wchar_t * type = elt.get_attribute(\"type\");\r\n\t\tconst wchar_t * control_ptr = elt.get_attribute(\"control_ptr\");\r\n\t\tconst wchar_t * disabled_a = elt.get_attribute(\"disabled\");\r\n\t\tbool disabled = (disabled_a != NULL && wcslen(disabled_a) > 0);\r\n\t\tconst wchar_t * has_value_disabled_a = elt.get_attribute(\"has_value_disabled\");\r\n\t\tbool has_value_disabled = (has_value_disabled_a != NULL && wcslen(has_value_disabled_a) > 0);\r\n\r\n\t\tif (id != NULL && type != NULL && (! disabled || has_value_disabled))\r\n\t\t{\r\n\t\t\tif (0 == wcscmp(type, L\"checkbox\") && elt.get_attribute(\"license\") != NULL)\r\n\t\t\t{\r\n\t\t\t\tControlLicense * p_license = reinterpret_cast(DVLib::wstring2long(control_ptr, 16));\r\n\t\t\t\tif (! InstallUILevelSetting::Instance->IsSilent())\r\n\t\t\t\t{\r\n\t\t\t\t\tif (! elt.get_state(STATE_CHECKED))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tTHROW_EX(p_license->accept_message);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tstd::wstring value = elt.get_state(STATE_CHECKED) ? L\"1\" : L\"0\";\r\n\t\t\t\tLOG(L\"--- Setting user-defined license value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"checkbox\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value;\r\n\t\t\t\tif (control_ptr != NULL)\r\n\t\t\t\t{\r\n\t\t\t\t\tControlCheckBox * p_checkbox = reinterpret_cast(DVLib::wstring2long(control_ptr, 16));\r\n\t\t\t\t\tvalue = elt.get_state(STATE_CHECKED) ? p_checkbox->checked_value.GetValue() : p_checkbox->unchecked_value.GetValue();\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue = elt.get_state(STATE_CHECKED) ? L\"1\" : L\"0\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tLOG(L\"--- Setting user-defined checkbox value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"radio\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value;\r\n\t\t\t\t\/\/ Ignore this radio button if it's not checked.\r\n\t\t\t\t\/\/ Only one \"checked\" element for each ID should exist\r\n\t\t\t\tif (elt.get_state(STATE_CHECKED))\r\n\t\t\t\t{\r\n\t\t\t\t\tconst wchar_t * elt_value = elt.get_attribute(\"value\");\r\n\t\t\t\t\tvalue = elt_value != NULL ? elt_value : L\"1\";\r\n\r\n\t\t\t\t\tLOG(L\"--- Setting user-defined radio button value '\" << id << L\"'=\" << value);\r\n\t\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"text\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value = elt.get_value().to_string();\r\n\t\t\t\tLOG(L\"--- Setting user-defined edit value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\t\t\telse if (0 == wcscmp(type, L\"file-path\") || 0 == wcscmp(type, L\"folder-path\"))\r\n\t\t\t{\r\n\t\t\t\tstd::wstring value = elt.get_value().to_string();\r\n\t\t\t\tif (value.empty()) value = elt.get_attribute(\"novalue\");\r\n\t\t\t\tvalue = DVLib::StripPathTerminator(value);\r\n\t\t\t\tLOG(L\"--- Setting user-defined browse value '\" << id << L\"'=\" << value);\r\n\t\t\t\tInstallerSession::Instance->AdditionalControlArgs[id] = value;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ TODO: support widget types: select, dropdown-select, textarea, htmlarea\r\n\t\t}\r\n\r\n\t\tfor(unsigned int child_index = 0; child_index < elt.children_count(); child_index++)\r\n\t\t{\r\n\t\t\texec(elt.child(child_index));\r\n\t\t}\r\n\t}\r\n}\r\n\t\r\nvoid SetControlValuesTask::exec()\r\n{\r\n\ttry\r\n\t{\r\n\t\texec(m_root);\r\n\t}\r\n\tcatch(std::exception& ex)\r\n\t{\r\n\t\tTRYLOG(L\"Error: \" << DVLib::string2wstring(ex.what()));\r\n\t\tif (NULL != m_perror)\r\n\t\t{\r\n\t\t\t* m_perror = DVLib::string2wstring(ex.what());\r\n\t\t}\r\n\t}\r\n\r\n\tCHECK_WIN32_BOOL(SetEvent(m_event),\r\n\t\tL\"SetEvent\");\r\n}\r\n<|endoftext|>"} {"text":"debig<|endoftext|>"} {"text":"Ajokki: print more messages with `std::cout`.<|endoftext|>"} {"text":"#include \"Utility\/Random.h\"\n\n#include \n#include \n#include \n\nnamespace\n{\n struct Seeder\n {\n using result_type = unsigned int;\n template\n void generate(Iterator begin, Iterator end)\n {\n std::random_device rd;\n std::generate(begin, end, [&rd]() { return rd(); });\n }\n };\n}\n\nRandom::Random_Bits_Generator Random::get_new_seeded_random_bit_source() noexcept\n{\n auto seeder = Seeder{};\n return Random_Bits_Generator(seeder);\n}\n\ndouble Random::random_laplace(double width) noexcept\n{\n thread_local static auto generator = get_new_seeded_random_bit_source();\n using ed = std::exponential_distribution;\n thread_local static auto dist = ed{};\n return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0\/width});\n}\n\nuint64_t Random::random_unsigned_int64() noexcept\n{\n return random_integer(std::numeric_limits::min(),\n std::numeric_limits::max());\n}\n\nbool Random::coin_flip() noexcept\n{\n return success_probability(1, 2);\n}\n\nbool Random::success_probability(size_t successes, size_t attempts) noexcept\n{\n assert(attempts > 0);\n return random_integer(size_t{1}, attempts) <= successes;\n}\n\nstd::string Random::random_string(size_t size) noexcept\n{\n std::string s;\n while(s.size() < size)\n {\n s.push_back('a' + char(random_integer(0, 25)));\n }\n return s;\n}\nReplace while-loop with algorithm#include \"Utility\/Random.h\"\n\n#include \n#include \n#include \n\nnamespace\n{\n struct Seeder\n {\n using result_type = unsigned int;\n template\n void generate(Iterator begin, Iterator end)\n {\n std::random_device rd;\n std::generate(begin, end, [&rd]() { return rd(); });\n }\n };\n}\n\nRandom::Random_Bits_Generator Random::get_new_seeded_random_bit_source() noexcept\n{\n auto seeder = Seeder{};\n return Random_Bits_Generator(seeder);\n}\n\ndouble Random::random_laplace(double width) noexcept\n{\n thread_local static auto generator = get_new_seeded_random_bit_source();\n using ed = std::exponential_distribution;\n thread_local static auto dist = ed{};\n return (coin_flip() ? 1 : -1)*dist(generator, ed::param_type{1.0\/width});\n}\n\nuint64_t Random::random_unsigned_int64() noexcept\n{\n return random_integer(std::numeric_limits::min(),\n std::numeric_limits::max());\n}\n\nbool Random::coin_flip() noexcept\n{\n return success_probability(1, 2);\n}\n\nbool Random::success_probability(size_t successes, size_t attempts) noexcept\n{\n assert(attempts > 0);\n return random_integer(size_t{1}, attempts) <= successes;\n}\n\nstd::string Random::random_string(const size_t size) noexcept\n{\n std::string s(size, ' ');\n std::generate(s.begin(), s.end(), []() -> char { return 'a' + char(random_integer(0, 25)); });\n return s;\n}\n<|endoftext|>"} {"text":"Turn on cloud print in about:flags on the Mac.<|endoftext|>"} {"text":"#define _BSD_SOURCE\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ptbox.h\"\n\npt_process *pt_alloc_process(pt_debugger *debugger) {\n return new pt_process(debugger);\n}\n\nvoid pt_free_process(pt_process *process) {\n delete process;\n}\n\npt_process::pt_process(pt_debugger *debugger) :\n pid(0), callback(NULL), context(NULL), debugger(debugger),\n event_proc(NULL), event_context(NULL), _trace_syscalls(true),\n _initialized(false)\n{\n memset(&exec_time, 0, sizeof exec_time);\n memset(handler, 0, sizeof handler);\n debugger->set_process(this);\n}\n\nvoid pt_process::set_callback(pt_handler_callback callback, void *context) {\n this->callback = callback;\n this->context = context;\n}\n\nvoid pt_process::set_event_proc(pt_event_callback callback, void *context) {\n this->event_proc = callback;\n this->event_context = context;\n}\n\nint pt_process::set_handler(int syscall, int handler) {\n if (syscall >= MAX_SYSCALL || syscall < 0)\n return 1;\n this->handler[syscall] = handler;\n return 0;\n}\n\nint pt_process::dispatch(int event, unsigned long param) {\n if (event_proc != NULL)\n return event_proc(event_context, event, param);\n return -1;\n}\n\nint pt_process::spawn(pt_fork_handler child, void *context) {\n pid_t pid = fork();\n if (pid == -1)\n return 1;\n if (pid == 0)\n _exit(child(context));\n this->pid = pid;\n debugger->new_process();\n return 0;\n}\n\nint pt_process::protection_fault(int syscall) {\n dispatch(PTBOX_EVENT_PROTECTION, syscall);\n dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_PROTECTION);\n kill(pid, SIGKILL);\n return PTBOX_EXIT_PROTECTION;\n}\n\nint pt_process::monitor() {\n bool in_syscall = false, first = true;\n struct timespec start, end, delta;\n int status, exit_reason = PTBOX_EXIT_NORMAL;\n siginfo_t si;\n\n while (true) {\n clock_gettime(CLOCK_MONOTONIC, &start);\n wait4(pid, &status, 0, &_rusage);\n clock_gettime(CLOCK_MONOTONIC, &end);\n timespec_sub(&end, &start, &delta);\n timespec_add(&exec_time, &delta, &exec_time);\n int signal = 0;\n\n if (WIFEXITED(status) || WIFSIGNALED(status))\n break;\n\n if (first) {\n dispatch(PTBOX_EVENT_ATTACH, 0);\n \/\/ This is right after SIGSTOP is received:\n ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT);\n }\n\n if (WIFSTOPPED(status)) {\n if (WSTOPSIG(status) == (0x80 | SIGTRAP)) {\n int syscall = debugger->syscall();\n in_syscall ^= true;\n \/\/printf(\"%s syscall %d\\n\", in_syscall ? \"Enter\" : \"Exit\", syscall);\n\n if (!this->_initialized) {\n if (!in_syscall && syscall == debugger->execve_syscall())\n this->_initialized = true;\n } else if (in_syscall) {\n if (syscall < MAX_SYSCALL) {\n switch (handler[syscall]) {\n case PTBOX_HANDLER_ALLOW:\n break;\n case PTBOX_HANDLER_STDOUTERR: {\n int arg0 = debugger->arg0();\n if (arg0 != 1 && arg0 != 2)\n exit_reason = protection_fault(syscall);\n break;\n }\n case PTBOX_HANDLER_CALLBACK:\n if (callback(context, syscall))\n break;\n \/\/printf(\"Killed by callback: %d\\n\", syscall);\n exit_reason = protection_fault(syscall);\n continue;\n default:\n \/\/ Default is to kill, safety first.\n \/\/printf(\"Killed by DISALLOW or None: %d\\n\", syscall);\n exit_reason = protection_fault(syscall);\n continue;\n }\n }\n } else if (debugger->on_return_callback) {\n debugger->on_return_callback(debugger->on_return_context, syscall);\n debugger->on_return_callback = NULL;\n debugger->on_return_context = NULL;\n }\n } else {\n switch (WSTOPSIG(status)) {\n case SIGTRAP:\n switch (status >> 16) {\n case PTRACE_EVENT_EXIT:\n if (exit_reason != PTBOX_EXIT_NORMAL)\n dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_NORMAL);\n }\n break;\n default:\n signal = WSTOPSIG(status);\n }\n if(!first) \/\/ *** Don't set _signal to SIGSTOP if this is the \/first\/ SIGSTOP\n dispatch(PTBOX_EVENT_SIGNAL, WSTOPSIG(status));\n }\n }\n \/\/ Pass NULL as signal in case of our first SIGSTOP because the runtime tends to resend it, making all our\n \/\/ work for naught. Like abort(), it catches the signal, prints something (^Z?) and then resends it.\n \/\/ Doing this prevents a second SIGSTOP from being dispatched to our event handler above. ***\n ptrace(_trace_syscalls ? PTRACE_SYSCALL : PTRACE_CONT, pid, NULL, first ? NULL : (void*) signal);\n first = false;\n }\n dispatch(PTBOX_EVENT_EXITED, exit_reason);\n return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status);\n}\nDocument iffy execve behaviour; #179#define _BSD_SOURCE\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ptbox.h\"\n\npt_process *pt_alloc_process(pt_debugger *debugger) {\n return new pt_process(debugger);\n}\n\nvoid pt_free_process(pt_process *process) {\n delete process;\n}\n\npt_process::pt_process(pt_debugger *debugger) :\n pid(0), callback(NULL), context(NULL), debugger(debugger),\n event_proc(NULL), event_context(NULL), _trace_syscalls(true),\n _initialized(false)\n{\n memset(&exec_time, 0, sizeof exec_time);\n memset(handler, 0, sizeof handler);\n debugger->set_process(this);\n}\n\nvoid pt_process::set_callback(pt_handler_callback callback, void *context) {\n this->callback = callback;\n this->context = context;\n}\n\nvoid pt_process::set_event_proc(pt_event_callback callback, void *context) {\n this->event_proc = callback;\n this->event_context = context;\n}\n\nint pt_process::set_handler(int syscall, int handler) {\n if (syscall >= MAX_SYSCALL || syscall < 0)\n return 1;\n this->handler[syscall] = handler;\n return 0;\n}\n\nint pt_process::dispatch(int event, unsigned long param) {\n if (event_proc != NULL)\n return event_proc(event_context, event, param);\n return -1;\n}\n\nint pt_process::spawn(pt_fork_handler child, void *context) {\n pid_t pid = fork();\n if (pid == -1)\n return 1;\n if (pid == 0)\n _exit(child(context));\n this->pid = pid;\n debugger->new_process();\n return 0;\n}\n\nint pt_process::protection_fault(int syscall) {\n dispatch(PTBOX_EVENT_PROTECTION, syscall);\n dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_PROTECTION);\n kill(pid, SIGKILL);\n return PTBOX_EXIT_PROTECTION;\n}\n\nint pt_process::monitor() {\n bool in_syscall = false, first = true;\n struct timespec start, end, delta;\n int status, exit_reason = PTBOX_EXIT_NORMAL;\n siginfo_t si;\n\n while (true) {\n clock_gettime(CLOCK_MONOTONIC, &start);\n wait4(pid, &status, 0, &_rusage);\n clock_gettime(CLOCK_MONOTONIC, &end);\n timespec_sub(&end, &start, &delta);\n timespec_add(&exec_time, &delta, &exec_time);\n int signal = 0;\n\n if (WIFEXITED(status) || WIFSIGNALED(status))\n break;\n\n if (first) {\n dispatch(PTBOX_EVENT_ATTACH, 0);\n \/\/ This is right after SIGSTOP is received:\n ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXIT);\n }\n\n if (WIFSTOPPED(status)) {\n if (WSTOPSIG(status) == (0x80 | SIGTRAP)) {\n int syscall = debugger->syscall();\n in_syscall ^= true;\n \/\/printf(\"%s syscall %d\\n\", in_syscall ? \"Enter\" : \"Exit\", syscall);\n\n if (!this->_initialized) {\n \/\/ This might seem odd, and you may ask yourself: \"does execve not return if the process hits an\n \/\/ rlimit and gets SIGKILLed?\"\n \/\/\n \/\/ No, it doesn't. See the session below.\n \/\/ $ ulimit -Sv50000\n \/\/ $ strace .\/a.out\n \/\/ execve(\".\/a.out\", [\".\/a.out\"], [\/* 17 vars *\/] \n \/\/ +++ killed by SIGKILL +++\n \/\/ Killed\n \/\/\n \/\/ From this we can see that execve doesn't return () if the process fails to\n \/\/ initialize, so we don't need to wait until the next non-execve syscall to set\n \/\/ _initialized to true - if it exited execve, it's good to go.\n if (!in_syscall && syscall == debugger->execve_syscall())\n this->_initialized = true;\n } else if (in_syscall) {\n if (syscall < MAX_SYSCALL) {\n switch (handler[syscall]) {\n case PTBOX_HANDLER_ALLOW:\n break;\n case PTBOX_HANDLER_STDOUTERR: {\n int arg0 = debugger->arg0();\n if (arg0 != 1 && arg0 != 2)\n exit_reason = protection_fault(syscall);\n break;\n }\n case PTBOX_HANDLER_CALLBACK:\n if (callback(context, syscall))\n break;\n \/\/printf(\"Killed by callback: %d\\n\", syscall);\n exit_reason = protection_fault(syscall);\n continue;\n default:\n \/\/ Default is to kill, safety first.\n \/\/printf(\"Killed by DISALLOW or None: %d\\n\", syscall);\n exit_reason = protection_fault(syscall);\n continue;\n }\n }\n } else if (debugger->on_return_callback) {\n debugger->on_return_callback(debugger->on_return_context, syscall);\n debugger->on_return_callback = NULL;\n debugger->on_return_context = NULL;\n }\n } else {\n switch (WSTOPSIG(status)) {\n case SIGTRAP:\n switch (status >> 16) {\n case PTRACE_EVENT_EXIT:\n if (exit_reason != PTBOX_EXIT_NORMAL)\n dispatch(PTBOX_EVENT_EXITING, PTBOX_EXIT_NORMAL);\n }\n break;\n default:\n signal = WSTOPSIG(status);\n }\n if(!first) \/\/ *** Don't set _signal to SIGSTOP if this is the \/first\/ SIGSTOP\n dispatch(PTBOX_EVENT_SIGNAL, WSTOPSIG(status));\n }\n }\n \/\/ Pass NULL as signal in case of our first SIGSTOP because the runtime tends to resend it, making all our\n \/\/ work for naught. Like abort(), it catches the signal, prints something (^Z?) and then resends it.\n \/\/ Doing this prevents a second SIGSTOP from being dispatched to our event handler above. ***\n ptrace(_trace_syscalls ? PTRACE_SYSCALL : PTRACE_CONT, pid, NULL, first ? NULL : (void*) signal);\n first = false;\n }\n dispatch(PTBOX_EVENT_EXITED, exit_reason);\n return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status);\n}\n<|endoftext|>"} {"text":"class Box\n{\n type = CT_STATIC;\n idc = -1;\n style = ST_CENTER;\n shadow = 2;\n colorBackground[] = { 0.2,0.9,0.5, 0.9};\n colorText[] = {1,1,1,0.9};\n font = \"PuristaLight\";\n sizeEx = 0.03;\n text = \"\";\n};\n\nclass AW_INTRO\n{\n\tidd=-1;\n\tmovingenable=false;\n\t\n\tclass controls \n\t{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GUI EDITOR OUTPUT START (by BACONMOP, v1.063, #Murapy)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Rules_box: RscFrame\n{\n\tidc = 1800;\n\tx = 1;\n\ty = 0;\n\tw = 0.725;\n\th = 1;\n};\nclass Rules_background: Box\n{\n type = CT_STATIC;\n idc = -1;\n style = ST_CENTER;\n shadow = 2;\n colorBackground[] = { 0.1,0.1,0.1,0.9};\n font = \"PuristaLight\";\n sizeEx = 0.03;\n\tx = 1;\n\ty = 0;\n\tw = 0.725;\n\th = 1;\n};\nclass Rules_Header: RscText\n{\n\tidc = 1000;\n\ttext = \"Rules\"; \/\/--- ToDo: Localize;\n\tx = 1.175;\n\ty = 0.02;\n\tw = 0.125;\n\th = 0.08;\n\tSizeEx = 0.05400;\n\tcolorText[] = {.9,.1,.1,.9};\n};\nclass Rule_1: RscText\n{\n\tidc = 1001;\n\ttext = \"1. Hacking and mission exploitation will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.1;\n\tw = 0.6875;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Rule_2: RscText\n{\n\tidc = 1002;\n\ttext = \"2. Intentional team-killing will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.18;\n\tw = 0.6125;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_3: RscText\n{\n\tidc = 1003;\n\ttext = \"3. Excessive, unintentional team-killing may result in a Kick\/Ban. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.28;\n\tw = 0.6875;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Rule_4: RscText\n{\n\tidc = 1004;\n\ttext = \"4. Unnecessary destruction of BLUFOR vehicles will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.36;\n\tw = 0.7;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Rule_5: RscText\n{\n\tidc = 1005;\n\ttext = \"5. Verbal abuse and bullying will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.44;\n\tw = 0.6375;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_6: RscText\n{\n\tidc = 1006;\n\ttext = \"6. Firing a weapon on base may result in a Kick\/Ban. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.52;\n\tw = 0.5875;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_7: RscText\n{\n\tidc = 1007;\n\ttext = \"7. Griefing and obstructive play will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.6;\n\tw = 0.7125;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_8: RscText\n{\n\tidc = 1008;\n\ttext = \"8. Excessive mic spamming will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.68;\n\tw = 0.6;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_9: RscText\n{\n\tidc = 1009;\n\ttext = \"9. A server moderator or admin's word is final.\"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.78;\n\tw = 0.675;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_10: RscText\n{\n\tidc = 1010;\n\ttext = \"10. Landing inside of the HQ may result in a warning or kick. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.88;\n\tw = 0.725;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass AW_Intro_and_TS_picture: RscPicture\n{\n\tidc = 1200;\n\ttext = \"media\\images\\Aw_Intro_Image.paa\";\n\tx = 0;\n\ty = 0;\n\tw = 1;\n\th = 1;\n};\nclass Ok_button: RscButton\n{\n\tidc = 1600;\n\ttext = \"Ok, Cool. Please make this box disappear\"; \/\/--- ToDo: Localize;\n\tx = 0;\n\ty = 1;\n\tw = 1;\n\th = 0.1;\n\taction = \"closedialog 0\";\n};\nclass General_hints: RscFrame\n{\n\tidc = 1801;\n\tx = -0.713889;\n\ty = 0.00208756;\n\tw = 0.7125;\n\th = 1;\n\tcolorBackground[] = {1,1,1,1};\n};\nclass hINTS_background: Box\n{\n type = CT_STATIC;\n idc = -1;\n style = ST_CENTER;\n shadow = 2;\n colorBackground[] = { 0.1,0.1,0.1,0.9};\n font = \"PuristaLight\";\n sizeEx = 0.03;\n\tx = -0.713889;\n\ty = 0.00208756;\n\tw = 0.7125;\n\th = 1;\n};\nclass Genreal_hints_Header: RscText\n{\n\tidc = 1011;\n\ttext = \"Some Hints and Tips\"; \/\/--- ToDo: Localize;\n\tx = -0.525;\n\ty = 0.02;\n\tw = 0.5;\n\th = 0.08;\n\tSizeEx = 0.05400;\n\tcolorText[] = {.9,.1,.1,.9};\n};\nclass Hint_1: RscText\n{\n\tidc = 1012;\n\ttext = \"Support elements should be on standby until called in.\"; \/\/--- ToDo: Localize;\n\tx = -0.65;\n\ty = 0.1;\n\tw = 0.6375;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Hint_2: RscText\n{\n\tidc = 1013;\n\ttext = \"Got a question? Look at our FAQ on the map.\"; \/\/--- ToDo: Localize;\n\tx = -0.625;\n\ty = 0.18;\n\tw = 0.575;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Hint_3: RscText\n{\n\tidc = 1014;\n\ttext = \"Zues players may be on but that doesn't mean they killed you.\"; \/\/--- ToDo: Localize;\n\tx = -0.6875;\n\ty = 0.26;\n\tw = 0.6625;\n\th = 0.06;\n\tSizeEx = 0.03700;\n};\nclass Hint_5: RscText\n{\n\tidc = 1015;\n\ttext = \"Found a bug? Post it on our forums. Ahoyworld.Co.uk\"; \/\/--- ToDo: Localize;\n\tx = -0.65;\n\ty = 0.34;\n\tw = 0.5625;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Hint_6: RscText\n{\n\tidc = 1016;\n\ttext = \"Looking for a squad? Join us on Teamspeak.\"; \/\/--- ToDo: Localize;\n\tx = -0.6125;\n\ty = 0.42;\n\tw = 0.4875;\n\th = 0.06;\n\tSizeEx = 0.03700;\n};\nclass Hint_7: RscText\n{\n\tidc = 1016;\n\ttext = \"Pilots should be on Teamspeak.\"; \/\/--- ToDo: Localize;\n\tx = -0.55;\n\ty = 0.50;\n\tw = 0.4875;\n\th = 0.06;\n\tSizeEx = 0.03700;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GUI EDITOR OUTPUT END\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\n};\n};\n\nУбрать бы этот диалог полностьюclass Box\n{\n type = CT_STATIC;\n idc = -1;\n style = ST_CENTER;\n shadow = 2;\n colorBackground[] = { 0.2,0.9,0.5, 0.9};\n colorText[] = {1,1,1,0.9};\n font = \"PuristaLight\";\n sizeEx = 0.03;\n text = \"\";\n};\n\nclass AW_INTRO\n{\n\tidd=-1;\n\tmovingenable=false;\n\t\n\tclass controls \n\t{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GUI EDITOR OUTPUT START (by BACONMOP, v1.063, #Murapy)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass Rules_box: RscFrame\n{\n\tidc = 1800;\n\tx = 1;\n\ty = 0;\n\tw = 0.725;\n\th = 1;\n};\nclass Rules_background: Box\n{\n type = CT_STATIC;\n idc = -1;\n style = ST_CENTER;\n shadow = 2;\n colorBackground[] = { 0.1,0.1,0.1,0.9};\n font = \"PuristaLight\";\n sizeEx = 0.03;\n\tx = 1;\n\ty = 0;\n\tw = 0.725;\n\th = 1;\n};\nclass Rules_Header: RscText\n{\n\tidc = 1000;\n\ttext = \"Rules\"; \/\/--- ToDo: Localize;\n\tx = 1.175;\n\ty = 0.02;\n\tw = 0.125;\n\th = 0.08;\n\tSizeEx = 0.05400;\n\tcolorText[] = {.9,.1,.1,.9};\n};\nclass Rule_1: RscText\n{\n\tidc = 1001;\n\ttext = \"1. Hacking and mission exploitation will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.1;\n\tw = 0.6875;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Rule_2: RscText\n{\n\tidc = 1002;\n\ttext = \"2. Intentional team-killing will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.18;\n\tw = 0.6125;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_3: RscText\n{\n\tidc = 1003;\n\ttext = \"3. Excessive, unintentional team-killing may result in a Kick\/Ban. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.28;\n\tw = 0.6875;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Rule_4: RscText\n{\n\tidc = 1004;\n\ttext = \"4. Unnecessary destruction of BLUFOR vehicles will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.36;\n\tw = 0.7;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Rule_5: RscText\n{\n\tidc = 1005;\n\ttext = \"5. Verbal abuse and bullying will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.44;\n\tw = 0.6375;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_6: RscText\n{\n\tidc = 1006;\n\ttext = \"6. Firing a weapon on base may result in a Kick\/Ban. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.52;\n\tw = 0.5875;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_7: RscText\n{\n\tidc = 1007;\n\ttext = \"7. Griefing and obstructive play will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.6;\n\tw = 0.7125;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_8: RscText\n{\n\tidc = 1008;\n\ttext = \"8. Excessive mic spamming will not be tolerated. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.68;\n\tw = 0.6;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_9: RscText\n{\n\tidc = 1009;\n\ttext = \"9. A server moderator or admin's word is final.\"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.78;\n\tw = 0.675;\n\th = 0.1;\n\tSizeEx = 0.03700;\n};\nclass Rule_10: RscText\n{\n\tidc = 1010;\n\ttext = \"10. Landing inside of the HQ may result in a warning or kick. \"; \/\/--- ToDo: Localize;\n\tx = 1;\n\ty = 0.88;\n\tw = 0.725;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass AW_Intro_and_TS_picture: RscPicture\n{\n\tidc = 1200;\n\ttext = \"media\\images\\Aw_Intro_Image.paa\";\n\tx = 0;\n\ty = 0;\n\tw = 1;\n\th = 1;\n};\nclass Ok_button: RscButton\n{\n\tidc = 1600;\n\ttext = \"Ok, Cool. Please make this box disappear\"; \/\/--- ToDo: Localize;\n\tx = 0;\n\ty = 1;\n\tw = 1;\n\th = 0.1;\n\taction = \"closedialog 0\";\n};\nclass General_hints: RscFrame\n{\n\tidc = 1801;\n\tx = -0.713889;\n\ty = 0.00208756;\n\tw = 0.7125;\n\th = 1;\n\tcolorBackground[] = {1,1,1,1};\n};\nclass hINTS_background: Box\n{\n type = CT_STATIC;\n idc = -1;\n style = ST_CENTER;\n shadow = 2;\n colorBackground[] = { 0.1,0.1,0.1,0.9};\n font = \"PuristaLight\";\n sizeEx = 0.03;\n\tx = -0.713889;\n\ty = 0.00208756;\n\tw = 0.7125;\n\th = 1;\n};\nclass Genreal_hints_Header: RscText\n{\n\tidc = 1011;\n\ttext = \"Some Hints and Tips\"; \/\/--- ToDo: Localize;\n\tx = -0.525;\n\ty = 0.02;\n\tw = 0.5;\n\th = 0.08;\n\tSizeEx = 0.05400;\n\tcolorText[] = {.9,.1,.1,.9};\n};\nclass Hint_1: RscText\n{\n\tidc = 1012;\n\ttext = \"Support elements should be on standby until called in.\"; \/\/--- ToDo: Localize;\n\tx = -0.65;\n\ty = 0.1;\n\tw = 0.6375;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Hint_2: RscText\n{\n\tidc = 1013;\n\ttext = \"Got a question? Look at our FAQ on the map.\"; \/\/--- ToDo: Localize;\n\tx = -0.625;\n\ty = 0.18;\n\tw = 0.575;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Hint_3: RscText\n{\n\tidc = 1014;\n\ttext = \"Zues players may be on but that doesn't mean they killed you.\"; \/\/--- ToDo: Localize;\n\tx = -0.6875;\n\ty = 0.26;\n\tw = 0.6625;\n\th = 0.06;\n\tSizeEx = 0.03700;\n};\nclass Hint_5: RscText\n{\n\tidc = 1015;\n\ttext = \"Found a bug? Post it on Ahoyworld.Co.uk (or TEHGAM.COM)\"; \/\/--- ToDo: Localize;\n\tx = -0.65;\n\ty = 0.34;\n\tw = 0.5625;\n\th = 0.08;\n\tSizeEx = 0.03700;\n};\nclass Hint_6: RscText\n{\n\tidc = 1016;\n\ttext = \"Looking for a squad? Join us on Teamspeak.\"; \/\/--- ToDo: Localize;\n\tx = -0.6125;\n\ty = 0.42;\n\tw = 0.4875;\n\th = 0.06;\n\tSizeEx = 0.03700;\n};\nclass Hint_7: RscText\n{\n\tidc = 1016;\n\ttext = \"Pilots should be on Teamspeak.\"; \/\/--- ToDo: Localize;\n\tx = -0.55;\n\ty = 0.50;\n\tw = 0.4875;\n\th = 0.06;\n\tSizeEx = 0.03700;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GUI EDITOR OUTPUT END\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\n};\n};\n\n<|endoftext|>"} {"text":"#include \"GHIElectronics_TinyCLR_Devices.h\"\n#include \"GHIElectronics_TinyCLR_InteropUtil.h\"\n\nconst int CummulativeDaysForMonth[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };\n\n#define BASE_YEAR 1601\n#define BASE_YEAR_LEAPYEAR_ADJUST 388\n#define DAYS_IN_NORMAL_YEAR 365\n#define BASE_YEAR_DAYOFWEEK_SHIFT 1\n\n#define IS_LEAP_YEAR(y) (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))\n#define NUMBER_OF_LEAP_YEARS(y) ((((y - 1) \/ 4) - ((y - 1) \/ 100) + ((y - 1) \/ 400)) - BASE_YEAR_LEAPYEAR_ADJUST) \/\/\/ Number of leap years until base year, not including the target year itself.\n#define NUMBER_OF_YEARS(y) (y - BASE_YEAR)\n\n#define YEARS_TO_DAYS(y) ((NUMBER_OF_YEARS(y) * DAYS_IN_NORMAL_YEAR) + NUMBER_OF_LEAP_YEARS(y))\n#define MONTH_TO_DAYS(y, m) (CummulativeDaysForMonth[m - 1] + ((IS_LEAP_YEAR(y) && (m > 2)) ? 1 : 0))\n\n#define TIMEUNIT_TO_MINUTES 600000000\n#define TIMEUNIT_TO_MILLISECONDS 10000\n#define MILLISECONDS_TO_SECONDS 1000\n#define SECONDS_TO_MINUTES 60\n#define MINUTES_TO_HOUR 60\n#define HOURS_TO_DAY 24\n\nstatic inline uint64_t Interop_Rtc_FromSystemTime(const TinyCLR_Rtc_DateTime* systemTime) {\n uint64_t r = YEARS_TO_DAYS(systemTime->Year) + MONTH_TO_DAYS(systemTime->Year, systemTime->Month) + systemTime->DayOfMonth - 1;\n r = (((((r * HOURS_TO_DAY) + systemTime->Hour) * MINUTES_TO_HOUR + systemTime->Minute) * SECONDS_TO_MINUTES + systemTime->Second) * MILLISECONDS_TO_SECONDS + systemTime->Millisecond) * TIMEUNIT_TO_MILLISECONDS;\n\n return r;\n}\n\nstatic inline void Interop_Rtc_ToSystemTime(uint64_t time, TinyCLR_Rtc_DateTime* systemTime) {\n int ytd = 0;\n int mtd = 0;\n\n time \/= TIMEUNIT_TO_MILLISECONDS;\n systemTime->Millisecond = time % MILLISECONDS_TO_SECONDS;\n time \/= MILLISECONDS_TO_SECONDS;\n systemTime->Second = time % SECONDS_TO_MINUTES;\n time \/= SECONDS_TO_MINUTES;\n systemTime->Minute = time % MINUTES_TO_HOUR;\n time \/= MINUTES_TO_HOUR;\n systemTime->Hour = time % HOURS_TO_DAY;\n time \/= HOURS_TO_DAY;\n\n systemTime->DayOfWeek = (time + BASE_YEAR_DAYOFWEEK_SHIFT) % 7;\n systemTime->Year = (uint32_t)(time \/ DAYS_IN_NORMAL_YEAR + BASE_YEAR);\n ytd = YEARS_TO_DAYS(systemTime->Year);\n if (ytd > time) {\n systemTime->Year--;\n ytd = YEARS_TO_DAYS(systemTime->Year);\n }\n\n time -= ytd;\n\n systemTime->Month = (uint32_t)(time \/ 31 + 1);\n mtd = MONTH_TO_DAYS(systemTime->Year, systemTime->Month + 1);\n\n if (time >= mtd) {\n systemTime->Month++;\n }\n\n mtd = MONTH_TO_DAYS(systemTime->Year, systemTime->Month);\n\n systemTime->DayOfMonth = (uint32_t)(time - mtd + 1);\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::GetTime___GHIElectronicsTinyCLRDevicesRtcRtcDateTime(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n TinyCLR_Rtc_DateTime now;\n\n auto result = api->GetTime(api, now);\n\n TinyCLR_Interop_ClrValue obj, ret;\n TinyCLR_Interop_ClrTypeId type;\n\n md.InteropManager->FindType(md.InteropManager, \"GHIElectronics.TinyCLR.Devices\", \"GHIElectronics.TinyCLR.Devices.Rtc\", \"RtcDateTime\", type);\n\n md.InteropManager->CreateObject(md.InteropManager, md.Stack, type, obj);\n\n TinyCLR_Interop_ClrValue year, month, week, dayofweek, dayofmonth, dayofyear, hour, minute, second, milisecond, microsecond, nanosecond;\n\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Year___I4, year);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Month___I4, month);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Week___I4, week);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfYear___I4, dayofweek);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfMonth___I4, dayofmonth);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfWeek___I4, dayofyear);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Hour___I4, hour);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Minute___I4, minute);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Second___I4, second);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Millisecond___I4, milisecond);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Microsecond___I4, microsecond);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Nanosecond___I4, nanosecond);\n\n year.Data.Numeric->I4 = now.Year;\n month.Data.Numeric->I4 = now.Month;\n week.Data.Numeric->I4 = now.Week;\n dayofweek.Data.Numeric->I4 = now.DayOfYear;\n dayofmonth.Data.Numeric->I4 = now.DayOfMonth;\n dayofyear.Data.Numeric->I4 = now.DayOfWeek;\n hour.Data.Numeric->I4 = now.Hour;\n minute.Data.Numeric->I4 = now.Minute;\n second.Data.Numeric->I4 = now.Second;\n milisecond.Data.Numeric->I4 = now.Millisecond;\n microsecond.Data.Numeric->I4 = now.Microsecond;\n nanosecond.Data.Numeric->I4 = now.Nanosecond;\n\n md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);\n\n md.InteropManager->AssignObjectReference(md.InteropManager, ret, obj.Object);\n\n return result;\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::SetTime___VOID__GHIElectronicsTinyCLRDevicesRtcRtcDateTime(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n TinyCLR_Interop_ClrValue arg0;\n\n md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);\n\n TinyCLR_Rtc_DateTime now;\n\n TinyCLR_Interop_ClrValue year, month, week, dayofweek, dayofmonth, dayofyear, hour, minute, second, milisecond, microsecond, nanosecond;\n\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Year___I4, year);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Month___I4, month);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Week___I4, week);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfYear___I4, dayofweek);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfMonth___I4, dayofmonth);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfWeek___I4, dayofyear);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Hour___I4, hour);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Minute___I4, minute);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Second___I4, second);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Millisecond___I4, milisecond);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Microsecond___I4, microsecond);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Nanosecond___I4, nanosecond);\n\n now.Year = year.Data.Numeric->I4;\n now.Month = month.Data.Numeric->I4;\n now.Week = week.Data.Numeric->I4;\n now.DayOfYear = dayofweek.Data.Numeric->I4;\n now.DayOfMonth = dayofmonth.Data.Numeric->I4;\n now.DayOfWeek = dayofyear.Data.Numeric->I4;\n now.Hour = hour.Data.Numeric->I4;\n now.Minute = minute.Data.Numeric->I4;\n now.Second = second.Data.Numeric->I4;\n now.Millisecond = milisecond.Data.Numeric->I4;\n now.Microsecond = microsecond.Data.Numeric->I4;\n now.Nanosecond = nanosecond.Data.Numeric->I4;\n\n return api->SetTime(api, now);\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::Acquire___VOID(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n return api->Acquire(api);\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::Release___VOID(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n return api->Release(api);\n}\nRemove old stuff that isn't used in RTC#include \"GHIElectronics_TinyCLR_Devices.h\"\n#include \"GHIElectronics_TinyCLR_InteropUtil.h\"\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::GetTime___GHIElectronicsTinyCLRDevicesRtcRtcDateTime(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n TinyCLR_Rtc_DateTime now;\n\n auto result = api->GetTime(api, now);\n\n TinyCLR_Interop_ClrValue obj, ret;\n TinyCLR_Interop_ClrTypeId type;\n\n md.InteropManager->FindType(md.InteropManager, \"GHIElectronics.TinyCLR.Devices\", \"GHIElectronics.TinyCLR.Devices.Rtc\", \"RtcDateTime\", type);\n\n md.InteropManager->CreateObject(md.InteropManager, md.Stack, type, obj);\n\n TinyCLR_Interop_ClrValue year, month, week, dayofweek, dayofmonth, dayofyear, hour, minute, second, milisecond, microsecond, nanosecond;\n\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Year___I4, year);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Month___I4, month);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Week___I4, week);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfYear___I4, dayofweek);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfMonth___I4, dayofmonth);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfWeek___I4, dayofyear);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Hour___I4, hour);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Minute___I4, minute);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Second___I4, second);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Millisecond___I4, milisecond);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Microsecond___I4, microsecond);\n md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Nanosecond___I4, nanosecond);\n\n year.Data.Numeric->I4 = now.Year;\n month.Data.Numeric->I4 = now.Month;\n week.Data.Numeric->I4 = now.Week;\n dayofweek.Data.Numeric->I4 = now.DayOfYear;\n dayofmonth.Data.Numeric->I4 = now.DayOfMonth;\n dayofyear.Data.Numeric->I4 = now.DayOfWeek;\n hour.Data.Numeric->I4 = now.Hour;\n minute.Data.Numeric->I4 = now.Minute;\n second.Data.Numeric->I4 = now.Second;\n milisecond.Data.Numeric->I4 = now.Millisecond;\n microsecond.Data.Numeric->I4 = now.Microsecond;\n nanosecond.Data.Numeric->I4 = now.Nanosecond;\n\n md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);\n\n md.InteropManager->AssignObjectReference(md.InteropManager, ret, obj.Object);\n\n return result;\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::SetTime___VOID__GHIElectronicsTinyCLRDevicesRtcRtcDateTime(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n TinyCLR_Interop_ClrValue arg0;\n\n md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, arg0);\n\n TinyCLR_Rtc_DateTime now;\n\n TinyCLR_Interop_ClrValue year, month, week, dayofweek, dayofmonth, dayofyear, hour, minute, second, milisecond, microsecond, nanosecond;\n\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Year___I4, year);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Month___I4, month);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Week___I4, week);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfYear___I4, dayofweek);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfMonth___I4, dayofmonth);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___DayOfWeek___I4, dayofyear);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Hour___I4, hour);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Minute___I4, minute);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Second___I4, second);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Millisecond___I4, milisecond);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Microsecond___I4, microsecond);\n md.InteropManager->GetField(md.InteropManager, arg0.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_RtcDateTime::FIELD___Nanosecond___I4, nanosecond);\n\n now.Year = year.Data.Numeric->I4;\n now.Month = month.Data.Numeric->I4;\n now.Week = week.Data.Numeric->I4;\n now.DayOfYear = dayofweek.Data.Numeric->I4;\n now.DayOfMonth = dayofmonth.Data.Numeric->I4;\n now.DayOfWeek = dayofyear.Data.Numeric->I4;\n now.Hour = hour.Data.Numeric->I4;\n now.Minute = minute.Data.Numeric->I4;\n now.Second = second.Data.Numeric->I4;\n now.Millisecond = milisecond.Data.Numeric->I4;\n now.Microsecond = microsecond.Data.Numeric->I4;\n now.Nanosecond = nanosecond.Data.Numeric->I4;\n\n return api->SetTime(api, now);\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::Acquire___VOID(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n return api->Acquire(api);\n}\n\nTinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Rtc_Provider_RtcControllerApiWrapper::Release___VOID(const TinyCLR_Interop_MethodData md) {\n auto api = reinterpret_cast(TinyCLR_Interop_GetApi(md, FIELD___impl___I));\n\n return api->Release(api);\n}\n<|endoftext|>"} {"text":"\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2019 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\n#ifndef __UNIVERSE_STRUCT_HPP_INCLUDED\n#define __UNIVERSE_STRUCT_HPP_INCLUDED\n\n#include \"code\/ylikuutio\/callback_system\/key_and_callback_struct.hpp\"\n\n\/\/ Include standard headers\n#include \/\/ std::size_t\n#include \/\/ uint32_t etc.\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace yli\n{\n namespace ontology\n {\n struct UniverseStruct\n {\n UniverseStruct()\n : window_title(\"\"),\n window_width(1600),\n window_height(900),\n framebuffer_width(8000),\n framebuffer_height(4500),\n text_size(40),\n font_size(16),\n max_FPS(50000), \/\/ default value max 50000 frames per second.\n speed(5.0f), \/\/ default value 5.0 units \/ second.\n turbo_factor(5.0f), \/\/ default value 5.0 x speed.\n twin_turbo_factor(100.0f), \/\/ default value 100.0 x speed.\n mouse_speed(0.005f),\n gravity(9.81f \/ 60.0f), \/\/ default Earth gravity (9.81 m\/s^2).\n znear(1.0f),\n zfar(5000.0f), \/\/ visibility: from 1 to 5000 units.\n is_headless(false)\n {\n \/\/ constructor.\n }\n\n std::string window_title;\n uint32_t window_width;\n uint32_t window_height;\n uint32_t framebuffer_width;\n uint32_t framebuffer_height;\n std::size_t text_size;\n std::size_t font_size;\n std::size_t max_FPS;\n float speed;\n float turbo_factor;\n float twin_turbo_factor;\n float mouse_speed;\n float gravity;\n float znear;\n float zfar;\n bool is_headless;\n };\n }\n}\n\n#endif\nRemoved unnecessary `#include` line.\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2019 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\n#ifndef __UNIVERSE_STRUCT_HPP_INCLUDED\n#define __UNIVERSE_STRUCT_HPP_INCLUDED\n\n\/\/ Include standard headers\n#include \/\/ std::size_t\n#include \/\/ uint32_t etc.\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace yli\n{\n namespace ontology\n {\n struct UniverseStruct\n {\n UniverseStruct()\n : window_title(\"\"),\n window_width(1600),\n window_height(900),\n framebuffer_width(8000),\n framebuffer_height(4500),\n text_size(40),\n font_size(16),\n max_FPS(50000), \/\/ default value max 50000 frames per second.\n speed(5.0f), \/\/ default value 5.0 units \/ second.\n turbo_factor(5.0f), \/\/ default value 5.0 x speed.\n twin_turbo_factor(100.0f), \/\/ default value 100.0 x speed.\n mouse_speed(0.005f),\n gravity(9.81f \/ 60.0f), \/\/ default Earth gravity (9.81 m\/s^2).\n znear(1.0f),\n zfar(5000.0f), \/\/ visibility: from 1 to 5000 units.\n is_headless(false)\n {\n \/\/ constructor.\n }\n\n std::string window_title;\n uint32_t window_width;\n uint32_t window_height;\n uint32_t framebuffer_width;\n uint32_t framebuffer_height;\n std::size_t text_size;\n std::size_t font_size;\n std::size_t max_FPS;\n float speed;\n float turbo_factor;\n float twin_turbo_factor;\n float mouse_speed;\n float gravity;\n float znear;\n float zfar;\n bool is_headless;\n };\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"PySoundGenerator.hpp\"\r\n\r\n#if PY_MAJOR_VERSION >= 3\r\n\/**\r\n * @brief PySoundGenerator::PySoundGenerator\r\n * @param progName\r\n * @param pyInstructions\r\n *\r\n * The constructor of the PySoundGeneratorclass.\r\n * Sets up the python interpreter, the instructions with\r\n * which it will be fed, the class variables and the break shortcut.\r\n *\/\r\nPySoundGenerator::PySoundGenerator(char* progName, char* pyInstructions){\r\n if(pyInstructions == QString()){\r\n Q_EMIT doneSignal(tr(\"File is empty. Nothing to execute.\"), -1);\r\n return;\r\n }\r\n\r\n Py_SetProgramName(QString(progName).toWCharArray());\r\n Py_Initialize();\r\n ownExcept = QString();\r\n exceptNum = -1;\r\n abortAction = new QAction(this);\r\n abortAction->setShortcut(QKeySequence(\"Ctrl-C\"));\r\n connect(abortAction, SIGNAL(triggered()), this, SLOT(terminated()));\r\n\r\n PyObject* module = PyImport_AddModule(\"__main__\");\r\n sys = PyImport_ImportModule(\"sys\");\r\n PyObject *path = PyObject_GetAttrString(sys, \"path\");\r\n PyList_Append(path, PyString_FromString(\"..\/..\/..\/\"));\r\n PyList_Append(path, PyString_FromString(\".\"));\r\n dict = PyModule_GetDict(module);\r\n if(!dict){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, -1);\r\n return;\r\n }\r\n execute(\"import AudioPython\");\r\n execute(pyInstructions);\r\n execute(\"samples = AudioPython.compute_samples(channels, None)\");\r\n\r\n device = new AudioOutputProcessor();\r\n connect(device, SIGNAL(startWriting()), this, SLOT(setReady()));\r\n ready = true;\r\n device->start();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::~PySoundGenerator\r\n *\r\n * The destructor of the PySoundGenerator class.\r\n * Kills the python interpreter.\r\n *\/\r\nPySoundGenerator::~PySoundGenerator(){\r\n Py_DECREF(sys);\r\n delete abortAction;\r\n Py_Finalize();\r\n device->exit();\r\n \/\/ Wait for the end of QThread before deletion, otherwise it raises an error\r\n while(device->isRunning())\r\n ;\r\n delete device;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::run\r\n *\r\n * The main loop. Calls the user code executing method\r\n * and Q_EMITs a signal when it's done.\r\n *\/\r\nvoid PySoundGenerator::run(){\r\n write();\r\n while(!ready)\r\n QCoreApplication::processEvents();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::write\r\n *\r\n * Gets samples and does error handling. The actual\r\n * main loop, so to say.\r\n *\/\r\nvoid PySoundGenerator::write(){\r\n while(ready){\r\n PyObject* check = execute(\"AudioPython.yield_raw(samples, None)\");\r\n if(!check){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, exceptNum);\r\n break;\r\n }\r\n if(PyBytes_Check(check))\r\n stream(check);\r\n }\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::execute\r\n * @return PyObject* \/ NULL if there was an exception\r\n * in the python interpreter.\r\n *\r\n * executes the python code in the interpreter.\r\n *\/\r\nPyObject* PySoundGenerator::execute(QString instruct){\r\n return PyRun_String(instruct.toLocal8Bit().data(),\r\n Py_file_input, dict, dict);\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::stream\r\n * @param process\r\n *\r\n * writes the generated bytes to the IODevice\r\n *\/\r\nvoid PySoundGenerator::stream(PyObject* data){\r\n ready = device->write(PyBytes_AsString(data), PyBytes_Size(data));\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::updateCode\r\n * @param filename\r\n * @param instructions\r\n * @return true if the name of the program could be changed,\r\n * false otherwise\r\n *\r\n * Updates the code of the currently running Python interpreter.\r\n *\/\r\nbool PySoundGenerator::updateCode(QString filename, QString instructions){\r\n Py_SetProgramName(filename.toWCharArray());\r\n execute(instructions.toLocal8Bit().data());\r\n return true;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::exceptionOccurred\r\n * @return PythonException\r\n *\r\n * Fetches the Python Exception and translates it to a QString\r\n * and an int representing exception and line number.\r\n *\/\r\nvoid PySoundGenerator::exceptionOccurred(){\r\n PyObject *errtype, *errvalue, *traceback;\r\n PyObject *mod;\r\n PyObject *ret, *list, *string;\r\n PyErr_Fetch(&errtype, &errvalue, &traceback);\r\n PyErr_NormalizeException(&errtype, &errvalue, &traceback);\r\n QString exceptionText = QString(PyBytes_AsString(PyObject_Str(errtype)));\r\n exceptionText.append(\": '\");\r\n exceptionText.append(PyBytes_AsString(PyObject_Str(errvalue)));\r\n QRegExp line(\"line [0-9]+\");\r\n if(line.indexIn(exceptionText) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.replace(\" (, \" + text + \")\", \"\");\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n mod = PyImport_ImportModule(\"traceback\");\r\n list = PyObject_CallMethod(mod, (char*)\"format_exception\",\r\n (char*)\"OOO\", errtype, errvalue, traceback);\r\n if(list == 0){\r\n ownExcept = exceptionText;\r\n exceptNum = -1;\r\n return;\r\n }\r\n string = PyBytes_FromString(\"\\n\");\r\n ret = _PyBytes_Join(string, list);\r\n if(line.indexIn(PyBytes_AsString(ret)) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n exceptNum = -1;\r\n }\r\n Py_DECREF(list);\r\n Py_DECREF(string);\r\n Py_DECREF(ret);\r\n }\r\n PyErr_Clear();\r\n ownExcept = exceptionText;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::terminated\r\n *\r\n * SLOT that is called when the user interrupt(CTRL-C) SIGNAL\r\n * is Q_EMITted.\r\n *\/\r\nvoid PySoundGenerator::terminated(){\r\n ownExcept = tr(\"User Terminated.\");\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::setReady\r\n * @param set\r\n *\r\n * Setter for the ready-variable that indicates\r\n * whether writing to the IODevice is allowed.\r\n *\/\r\nvoid PySoundGenerator::setReady(){\r\n ready = true;\r\n write();\r\n}\r\n#else\r\n\/**\r\n * @brief PySoundGenerator::PySoundGenerator\r\n * @param progName\r\n * @param pyInstructions\r\n *\r\n * The constructor of the PySoundGeneratorclass.\r\n * Sets up the python interpreter, the instructions with\r\n * which it will be fed, the class variables and the break shortcut.\r\n *\/\r\nPySoundGenerator::PySoundGenerator(char* progName, char* pyInstructions){\r\n if(pyInstructions == QString()){\r\n Q_EMIT doneSignal(tr(\"File is empty. Nothing to execute.\"), -1);\r\n return;\r\n }\r\n\r\n Py_SetProgramName(progName);\r\n Py_Initialize();\r\n ownExcept = QString();\r\n exceptNum = -1;\r\n abortAction = new QAction(this);\r\n abortAction->setShortcut(QKeySequence(\"Ctrl-C\"));\r\n connect(abortAction, SIGNAL(triggered()), this, SLOT(terminated()));\r\n\r\n PyObject* module = PyImport_AddModule(\"__main__\");\r\n sys = PyImport_ImportModule(\"sys\");\r\n\/\/ PyObject *path = PyObject_GetAttrString(sys, \"path\");\r\n\/\/ PyList_Append(path, PyString_FromString(\"..\/..\/..\/\"));\r\n\/\/ PyList_Append(path, PyString_FromString(\".\"));\r\n dict = PyModule_GetDict(module);\r\n if(!dict){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, -1);\r\n return;\r\n }\r\n execute(\"import AudioPython\");\r\n execute(pyInstructions);\r\n execute(\"samples = AudioPython.compute_samples(channels, None)\");\r\n\r\n\r\n\r\n device = new AudioOutputProcessor();\r\n connect(device, SIGNAL(startWriting()), this, SLOT(setReady()));\r\n ready = true;\r\n device->start();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::~PySoundGenerator\r\n *\r\n * The destructor of the PySoundGenerator class.\r\n * Kills the python interpreter.\r\n *\/\r\nPySoundGenerator::~PySoundGenerator(){\r\n Py_DECREF(sys);\r\n delete abortAction;\r\n Py_Finalize();\r\n device->exit();\r\n \/\/ Wait for the end of QThread before deletion, otherwise it raises an error\r\n while(device->isRunning())\r\n ;\r\n delete device;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::run\r\n *\r\n * The main loop. Calls the user code executing method\r\n * and Q_EMITs a signal when it's done.\r\n *\/\r\nvoid PySoundGenerator::run(){\r\n write();\r\n while(!ready)\r\n QCoreApplication::processEvents();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::write\r\n *\r\n * Gets samples and does error handling. The actual\r\n * main loop, so to say.\r\n *\/\r\nvoid PySoundGenerator::write(){\r\n while(ready){\r\n PyObject* check = execute(\"AudioPython.yield_raw(samples, None)\");\r\n if(!check){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, exceptNum);\r\n break;\r\n }\r\n if(PyBytes_Check(check))\r\n stream(check);\r\n }\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::execute\r\n * @return PyObject* \/ NULL if there was an exception\r\n * in the python interpreter.\r\n *\r\n * executes the python code in the interpreter.\r\n *\/\r\nPyObject* PySoundGenerator::execute(QString instruct){\r\n return PyRun_String(instruct.toLocal8Bit().data(),\r\n Py_file_input, dict, dict);\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::stream\r\n * @param process\r\n *\r\n * writes the generated bytes to the IODevice\r\n *\/\r\nvoid PySoundGenerator::stream(PyObject* data){\r\n ready = device->write(PyBytes_AsString(data), PyBytes_Size(data));\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::updateCode\r\n * @param filename\r\n * @param instructions\r\n * @return true if the name of the program could be changed,\r\n * false otherwise\r\n *\r\n * Updates the code of the currently running Python interpreter.\r\n *\/\r\nbool PySoundGenerator::updateCode(QString filename, QString instructions){\r\n Py_SetProgramName(filename.toLocal8Bit().data());\r\n execute(instructions.toLocal8Bit().data());\r\n return true;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::exceptionOccurred\r\n * @return PythonException\r\n *\r\n * Fetches the Python Exception and translates it to a QString\r\n * and an int representing exception and line number.\r\n *\/\r\nvoid PySoundGenerator::exceptionOccurred(){\r\n PyObject *errtype, *errvalue, *traceback;\r\n PyObject *mod;\r\n PyObject *ret, *list, *string;\r\n PyErr_Fetch(&errtype, &errvalue, &traceback);\r\n PyErr_NormalizeException(&errtype, &errvalue, &traceback);\r\n QString exceptionText = QString(PyString_AsString(PyObject_Str(errtype)));\r\n exceptionText.append(\": '\");\r\n exceptionText.append(PyString_AsString(PyObject_Str(errvalue)));\r\n QRegExp line(\"line [0-9]+\");\r\n if(line.indexIn(exceptionText) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.replace(\" (, \" + text + \")\", \"\");\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n mod = PyImport_ImportModule(\"traceback\");\r\n list = PyObject_CallMethod(mod, (char*)\"format_exception\",\r\n (char*)\"OOO\", errtype, errvalue, traceback);\r\n if(list == 0){\r\n ownExcept = exceptionText;\r\n exceptNum = -1;\r\n return;\r\n }\r\n string = PyString_FromString(\"\\n\");\r\n ret = _PyString_Join(string, list);\r\n if(line.indexIn(PyString_AsString(ret)) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n exceptNum = -1;\r\n }\r\n Py_DECREF(list);\r\n Py_DECREF(string);\r\n Py_DECREF(ret);\r\n }\r\n PyErr_Clear();\r\n ownExcept = exceptionText;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::terminated\r\n *\r\n * SLOT that is called when the user interrupt(CTRL-C) SIGNAL\r\n * is Q_EMITted.\r\n *\/\r\nvoid PySoundGenerator::terminated(){\r\n ownExcept = tr(\"User Terminated.\");\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::setReady\r\n * @param set\r\n *\r\n * Setter for the ready-variable that indicates\r\n * whether writing to the IODevice is allowed.\r\n *\/\r\nvoid PySoundGenerator::setReady(){\r\n ready = true;\r\n write();\r\n}\r\n#endif\r\nUpdated PySoundGenerator#include \"PySoundGenerator.hpp\"\r\n\r\n#if PY_MAJOR_VERSION >= 3\r\n\/**\r\n * @brief PySoundGenerator::PySoundGenerator\r\n * @param progName\r\n * @param pyInstructions\r\n *\r\n * The constructor of the PySoundGeneratorclass.\r\n * Sets up the python interpreter, the instructions with\r\n * which it will be fed, the class variables and the break shortcut.\r\n *\/\r\nPySoundGenerator::PySoundGenerator(char* progName, char* pyInstructions){\r\n if(pyInstructions == QString()){\r\n Q_EMIT doneSignal(tr(\"File is empty. Nothing to execute.\"), -1);\r\n return;\r\n }\r\n\r\n Py_SetProgramName(QString(progName).toWCharArray());\r\n Py_Initialize();\r\n ownExcept = QString();\r\n exceptNum = -1;\r\n abortAction = new QAction(this);\r\n abortAction->setShortcut(QKeySequence(\"Ctrl-C\"));\r\n connect(abortAction, SIGNAL(triggered()), this, SLOT(terminated()));\r\n\r\n PyObject* module = PyImport_AddModule(\"__main__\");\r\n sys = PyImport_ImportModule(\"sys\");\r\n PyObject *path = PyObject_GetAttrString(sys, \"path\");\r\n PyList_Append(path, PyString_FromString(\"..\/..\/..\/\"));\r\n PyList_Append(path, PyString_FromString(\".\"));\r\n dict = PyModule_GetDict(module);\r\n if(!dict){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, -1);\r\n return;\r\n }\r\n execute(\"import AudioPython\");\r\n execute(pyInstructions);\r\n execute(\"samples = AudioPython.compute_samples(channels, None)\");\r\n\r\n device = new AudioOutputProcessor();\r\n connect(device, SIGNAL(startWriting()), this, SLOT(setReady()));\r\n ready = true;\r\n device->start();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::~PySoundGenerator\r\n *\r\n * The destructor of the PySoundGenerator class.\r\n * Kills the python interpreter.\r\n *\/\r\nPySoundGenerator::~PySoundGenerator(){\r\n Py_DECREF(sys);\r\n delete abortAction;\r\n Py_Finalize();\r\n device->exit();\r\n \/\/ Wait for the end of QThread before deletion, otherwise it raises an error\r\n while(device->isRunning())\r\n ;\r\n delete device;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::run\r\n *\r\n * The main loop. Calls the user code executing method\r\n * and Q_EMITs a signal when it's done.\r\n *\/\r\nvoid PySoundGenerator::run(){\r\n write();\r\n while(!ready)\r\n QCoreApplication::processEvents();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::write\r\n *\r\n * Gets samples and does error handling. The actual\r\n * main loop, so to say.\r\n *\/\r\nvoid PySoundGenerator::write(){\r\n while(ready){\r\n PyObject* check = execute(\"AudioPython.yield_raw(samples, None)\");\r\n if(!check){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, exceptNum);\r\n break;\r\n }\r\n if(PyBytes_Check(check))\r\n stream(check);\r\n }\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::execute\r\n * @return PyObject* \/ NULL if there was an exception\r\n * in the python interpreter.\r\n *\r\n * executes the python code in the interpreter.\r\n *\/\r\nPyObject* PySoundGenerator::execute(QString instruct){\r\n return PyRun_String(instruct.toLocal8Bit().data(),\r\n Py_file_input, dict, dict);\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::stream\r\n * @param process\r\n *\r\n * writes the generated bytes to the IODevice\r\n *\/\r\nvoid PySoundGenerator::stream(PyObject* data){\r\n ready = device->write(PyBytes_AsString(data), PyBytes_Size(data));\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::updateCode\r\n * @param filename\r\n * @param instructions\r\n * @return true if the name of the program could be changed,\r\n * false otherwise\r\n *\r\n * Updates the code of the currently running Python interpreter.\r\n *\/\r\nbool PySoundGenerator::updateCode(QString filename, QString instructions){\r\n Py_SetProgramName(filename.toWCharArray());\r\n execute(instructions.toLocal8Bit().data());\r\n return true;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::exceptionOccurred\r\n * @return PythonException\r\n *\r\n * Fetches the Python Exception and translates it to a QString\r\n * and an int representing exception and line number.\r\n *\/\r\nvoid PySoundGenerator::exceptionOccurred(){\r\n PyObject *errtype, *errvalue, *traceback;\r\n PyObject *mod;\r\n PyObject *ret, *list, *string;\r\n PyErr_Fetch(&errtype, &errvalue, &traceback);\r\n PyErr_NormalizeException(&errtype, &errvalue, &traceback);\r\n QString exceptionText = QString(PyBytes_AsString(PyObject_Str(errtype)));\r\n exceptionText.append(\": '\");\r\n exceptionText.append(PyBytes_AsString(PyObject_Str(errvalue)));\r\n QRegExp line(\"line [0-9]+\");\r\n if(line.indexIn(exceptionText) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.replace(\" (, \" + text + \")\", \"\");\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n mod = PyImport_ImportModule(\"traceback\");\r\n list = PyObject_CallMethod(mod, (char*)\"format_exception\",\r\n (char*)\"OOO\", errtype, errvalue, traceback);\r\n if(list == 0){\r\n ownExcept = exceptionText;\r\n exceptNum = -1;\r\n return;\r\n }\r\n string = PyBytes_FromString(\"\\n\");\r\n ret = _PyBytes_Join(string, list);\r\n if(line.indexIn(PyBytes_AsString(ret)) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n exceptNum = -1;\r\n }\r\n Py_DECREF(list);\r\n Py_DECREF(string);\r\n Py_DECREF(ret);\r\n }\r\n PyErr_Clear();\r\n ownExcept = exceptionText;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::terminated\r\n *\r\n * SLOT that is called when the user interrupt(CTRL-C) SIGNAL\r\n * is Q_EMITted.\r\n *\/\r\nvoid PySoundGenerator::terminated(){\r\n ownExcept = tr(\"User Terminated.\");\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::setReady\r\n * @param set\r\n *\r\n * Setter for the ready-variable that indicates\r\n * whether writing to the IODevice is allowed.\r\n *\/\r\nvoid PySoundGenerator::setReady(){\r\n ready = true;\r\n write();\r\n}\r\n#else\r\n\/**\r\n * @brief PySoundGenerator::PySoundGenerator\r\n * @param progName\r\n * @param pyInstructions\r\n *\r\n * The constructor of the PySoundGeneratorclass.\r\n * Sets up the python interpreter, the instructions with\r\n * which it will be fed, the class variables and the break shortcut.\r\n *\/\r\nPySoundGenerator::PySoundGenerator(char* progName, char* pyInstructions){\r\n if(pyInstructions == QString()){\r\n Q_EMIT doneSignal(tr(\"File is empty. Nothing to execute.\"), -1);\r\n return;\r\n }\r\n\r\n Py_SetProgramName(progName);\r\n Py_Initialize();\r\n ownExcept = QString();\r\n exceptNum = -1;\r\n abortAction = new QAction(this);\r\n abortAction->setShortcut(QKeySequence(\"Ctrl-C\"));\r\n connect(abortAction, SIGNAL(triggered()), this, SLOT(terminated()));\r\n\r\n PyObject* module = PyImport_AddModule(\"__main__\");\r\n sys = PyImport_ImportModule(\"sys\");\r\n\/\/ PyObject *path = PyObject_GetAttrString(sys, \"path\");\r\n\/\/ PyList_Append(path, PyString_FromString(\"..\/..\/..\/\"));\r\n\/\/ PyList_Append(path, PyString_FromString(\".\"));\r\n dict = PyModule_GetDict(module);\r\n if(!dict){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, -1);\r\n return;\r\n }\r\n execute(\"import AudioPython\");\r\n execute(\"from AudioPython import *\");\r\n execute(pyInstructions);\r\n execute(\"samples = AudioPython.compute_samples(channels, None)\");\r\n execute(\"gen = AudioPython.yield_raw(samples, None)\");\r\n\r\n\r\n device = new AudioOutputProcessor();\r\n connect(device, SIGNAL(startWriting()), this, SLOT(setReady()));\r\n ready = true;\r\n device->start();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::~PySoundGenerator\r\n *\r\n * The destructor of the PySoundGenerator class.\r\n * Kills the python interpreter.\r\n *\/\r\nPySoundGenerator::~PySoundGenerator(){\r\n Py_DECREF(sys);\r\n delete abortAction;\r\n Py_Finalize();\r\n device->exit();\r\n \/\/ Wait for the end of QThread before deletion, otherwise it raises an error\r\n while(device->isRunning())\r\n ;\r\n delete device;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::run\r\n *\r\n * The main loop. Calls the user code executing method\r\n * and Q_EMITs a signal when it's done.\r\n *\/\r\nvoid PySoundGenerator::run(){\r\n write();\r\n while(!ready)\r\n QCoreApplication::processEvents();\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::write\r\n *\r\n * Gets samples and does error handling. The actual\r\n * main loop, so to say.\r\n *\/\r\nvoid PySoundGenerator::write(){\r\n while(ready){\r\n PyObject* check = execute(\"next(gen)\");\r\n if(!check){\r\n exceptionOccurred();\r\n Q_EMIT doneSignal(ownExcept, exceptNum);\r\n break;\r\n }\r\n if(PyBytes_Check(check))\r\n stream(check);\r\n }\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::execute\r\n * @return PyObject* \/ NULL if there was an exception\r\n * in the python interpreter.\r\n *\r\n * executes the python code in the interpreter.\r\n *\/\r\nPyObject* PySoundGenerator::execute(QString instruct){\r\n return PyRun_String(instruct.toLocal8Bit().data(),\r\n Py_file_input, dict, dict);\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::stream\r\n * @param process\r\n *\r\n * writes the generated bytes to the IODevice\r\n *\/\r\nvoid PySoundGenerator::stream(PyObject* data){\r\n ready = device->write(PyBytes_AsString(data), PyBytes_Size(data));\r\n qDebug() << ready;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::updateCode\r\n * @param filename\r\n * @param instructions\r\n * @return true if the name of the program could be changed,\r\n * false otherwise\r\n *\r\n * Updates the code of the currently running Python interpreter.\r\n *\/\r\nbool PySoundGenerator::updateCode(QString filename, QString instructions){\r\n Py_SetProgramName(filename.toLocal8Bit().data());\r\n execute(instructions.toLocal8Bit().data());\r\n execute(\"samples = AudioPython.compute_samples(channels, None)\");\r\n execute(\"gen = AudioPython.yield_raw(samples, None)\");\r\n return true;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::exceptionOccurred\r\n * @return PythonException\r\n *\r\n * Fetches the Python Exception and translates it to a QString\r\n * and an int representing exception and line number.\r\n *\/\r\nvoid PySoundGenerator::exceptionOccurred(){\r\n PyObject *errtype, *errvalue, *traceback;\r\n PyObject *mod;\r\n PyObject *ret, *list, *string;\r\n PyErr_Fetch(&errtype, &errvalue, &traceback);\r\n PyErr_NormalizeException(&errtype, &errvalue, &traceback);\r\n QString exceptionText = QString(PyString_AsString(PyObject_Str(errtype)));\r\n exceptionText.append(\": '\");\r\n exceptionText.append(PyString_AsString(PyObject_Str(errvalue)));\r\n QRegExp line(\"line [0-9]+\");\r\n if(line.indexIn(exceptionText) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.replace(\" (, \" + text + \")\", \"\");\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n mod = PyImport_ImportModule(\"traceback\");\r\n list = PyObject_CallMethod(mod, (char*)\"format_exception\",\r\n (char*)\"OOO\", errtype, errvalue, traceback);\r\n if(list == 0){\r\n ownExcept = exceptionText;\r\n exceptNum = -1;\r\n return;\r\n }\r\n string = PyString_FromString(\"\\n\");\r\n ret = _PyString_Join(string, list);\r\n if(line.indexIn(PyString_AsString(ret)) != -1){\r\n QString text = line.capturedTexts().at(0);\r\n exceptionText.append(\"' at \" + text);\r\n text.replace(\"line \", \"\");\r\n exceptNum = text.toInt();\r\n } else{\r\n exceptNum = -1;\r\n }\r\n Py_DECREF(list);\r\n Py_DECREF(string);\r\n Py_DECREF(ret);\r\n }\r\n PyErr_Clear();\r\n ownExcept = exceptionText;\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::terminated\r\n *\r\n * SLOT that is called when the user interrupt(CTRL-C) SIGNAL\r\n * is Q_EMITted.\r\n *\/\r\nvoid PySoundGenerator::terminated(){\r\n ownExcept = tr(\"User Terminated.\");\r\n}\r\n\r\n\/**\r\n * @brief PySoundGenerator::setReady\r\n * @param set\r\n *\r\n * Setter for the ready-variable that indicates\r\n * whether writing to the IODevice is allowed.\r\n *\/\r\nvoid PySoundGenerator::setReady(){\r\n ready = true;\r\n write();\r\n}\r\n#endif\r\n<|endoftext|>"} {"text":"#include \"Node.hpp\"\n\nusing namespace raw::root;\n\n\nstruct TypeNamePair {\n Node::Type type;\n const char** aliases;\n size_t nAliases;\n\n TypeNamePair(Node::Type type, ...): type(type), nAliases(0)\n {\n va_list args;\n const char* a;\n\n va_start(args, type);\n while ((a = va_arg(args, const char*)))\n ++nAliases;\n va_end(args);\n\n aliases = new const char*[nAliases];\n\n size_t i = 0;\n va_start(args, type);\n while ((a = va_arg(args, const char*)))\n aliases[i++] = a;\n va_end(args);\n }\n\n ~TypeNamePair()\n {\n delete [] aliases;\n }\n};\n\n\nconst static TypeNamePair typeMaps[] = {\n TypeNamePair(Node::kInt8, \"char\", \"Char_t\", \"Bool_t\", NULL),\n TypeNamePair(Node::kInt32, \"int\", \"Int_t\", NULL),\n TypeNamePair(Node::kUInt32, \"UInt_t\", NULL),\n TypeNamePair(Node::kInt64, \"Long64_t\", NULL),\n TypeNamePair(Node::kFloat, \"float\", \"Float_t\", NULL),\n TypeNamePair(Node::kDouble, \"double\", \"Double_t\", NULL),\n TypeNamePair(Node::kString, \"TString\", NULL)\n};\nconst static size_t nPairs = sizeof(typeMaps) \/ sizeof(TypeNamePair);\n\n\nNode::Type Node::TypeFromStr(const std::string& typeName)\n{\n for (size_t i = 0; i < nPairs; ++i) {\n const TypeNamePair& pair = typeMaps[i];\n for (size_t j = 0; j < pair.nAliases; ++j) {\n if (typeName.compare(pair.aliases[j]) == 0)\n return pair.type;\n }\n }\n return kUnknown;\n}\n\n\nNode::Node(Type type, const std::string& name, const void* addr):\n type (type), name(name), address(addr)\n{\n}\n\n\nNode::Node(const std::string& type, const std::string& name, const void* addr):\n typeName(type), type (TypeFromStr(type)), name(name), address(addr)\n{\n}\n\n\nNode::Node(const std::string& typeName, Type type, const std::string& name, const void* addr):\n typeName(typeName), type (type), name(name), address(addr)\n{\n}\n\n\nNode::Node(const TObject& obj):\n typeName(obj.ClassName()), type(kDictionary), name(obj.GetName()), address(&obj)\n{\n}\n\n\nstd::string Node::getTypeName() const\n{\n return typeName;\n}\n\n\nNode::Type Node::getType() const\n{\n return type;\n}\n\n\nstd::string Node::getName() const\n{\n return name;\n}\n\n\nconst void* Node::getAddress() const\n{\n return address;\n}\n\n\nvoid Node::setType(Type t)\n{\n type = t;\n}\n\n\nbool Node::isBasic() const\n{\n\treturn type > Node::kCollection && type <= Node::kString;\n}\n\n\nstd::ostream& raw::root::operator << (std::ostream& os, Node::Type type)\n{\n switch (type) {\n case Node::kDictionary:\n os << \"dictionary\";\n break;\n case Node::kCollection:\n os << \"collection\";\n break;\n case Node::kInt8: case Node::kInt32: case Node::kInt64:\n os << \"integer\";\n break;\n case Node::kUInt8: case Node::kUInt32: case Node::kUInt64:\n os << \"unsigned\";\n break;\n case Node::kFloat:\n os << \"float\";\n break;\n case Node::kDouble:\n os << \"double\";\n break;\n case Node::kString:\n os << \"string\";\n break;\n case Node::kUnknown:\n os << \"unknown\";\n break;\n default:\n os << (int)(type);\n break;\n }\n return os;\n}\nAdded string and unsigned int to TypeNamePair#include \"Node.hpp\"\n\nusing namespace raw::root;\n\n\nstruct TypeNamePair {\n Node::Type type;\n const char** aliases;\n size_t nAliases;\n\n TypeNamePair(Node::Type type, ...): type(type), nAliases(0)\n {\n va_list args;\n const char* a;\n\n va_start(args, type);\n while ((a = va_arg(args, const char*)))\n ++nAliases;\n va_end(args);\n\n aliases = new const char*[nAliases];\n\n size_t i = 0;\n va_start(args, type);\n while ((a = va_arg(args, const char*)))\n aliases[i++] = a;\n va_end(args);\n }\n\n ~TypeNamePair()\n {\n delete [] aliases;\n }\n};\n\n\nconst static TypeNamePair typeMaps[] = {\n TypeNamePair(Node::kInt8, \"char\", \"Char_t\", \"Bool_t\", NULL),\n TypeNamePair(Node::kInt32, \"int\", \"Int_t\", NULL),\n TypeNamePair(Node::kUInt32, \"unsigned int\", \"UInt_t\", NULL),\n TypeNamePair(Node::kInt64, \"Long64_t\", NULL),\n TypeNamePair(Node::kFloat, \"float\", \"Float_t\", NULL),\n TypeNamePair(Node::kDouble, \"double\", \"Double_t\", NULL),\n TypeNamePair(Node::kString, \"TString\", \"string\", NULL)\n};\nconst static size_t nPairs = sizeof(typeMaps) \/ sizeof(TypeNamePair);\n\n\nNode::Type Node::TypeFromStr(const std::string& typeName)\n{\n for (size_t i = 0; i < nPairs; ++i) {\n const TypeNamePair& pair = typeMaps[i];\n for (size_t j = 0; j < pair.nAliases; ++j) {\n if (typeName.compare(pair.aliases[j]) == 0)\n return pair.type;\n }\n }\n return kUnknown;\n}\n\n\nNode::Node(Type type, const std::string& name, const void* addr):\n type (type), name(name), address(addr)\n{\n}\n\n\nNode::Node(const std::string& type, const std::string& name, const void* addr):\n typeName(type), type (TypeFromStr(type)), name(name), address(addr)\n{\n}\n\n\nNode::Node(const std::string& typeName, Type type, const std::string& name, const void* addr):\n typeName(typeName), type (type), name(name), address(addr)\n{\n}\n\n\nNode::Node(const TObject& obj):\n typeName(obj.ClassName()), type(kDictionary), name(obj.GetName()), address(&obj)\n{\n}\n\n\nstd::string Node::getTypeName() const\n{\n return typeName;\n}\n\n\nNode::Type Node::getType() const\n{\n return type;\n}\n\n\nstd::string Node::getName() const\n{\n return name;\n}\n\n\nconst void* Node::getAddress() const\n{\n return address;\n}\n\n\nvoid Node::setType(Type t)\n{\n type = t;\n}\n\n\nbool Node::isBasic() const\n{\n\treturn type > Node::kCollection && type <= Node::kString;\n}\n\n\nstd::ostream& raw::root::operator << (std::ostream& os, Node::Type type)\n{\n switch (type) {\n case Node::kDictionary:\n os << \"dictionary\";\n break;\n case Node::kCollection:\n os << \"collection\";\n break;\n case Node::kInt8: case Node::kInt32: case Node::kInt64:\n os << \"integer\";\n break;\n case Node::kUInt8: case Node::kUInt32: case Node::kUInt64:\n os << \"unsigned\";\n break;\n case Node::kFloat:\n os << \"float\";\n break;\n case Node::kDouble:\n os << \"double\";\n break;\n case Node::kString:\n os << \"string\";\n break;\n case Node::kUnknown:\n os << \"unknown\";\n break;\n default:\n os << (int)(type);\n break;\n }\n return os;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2009 by Dr. Marc Boris Duerner\n * Copyright (C) 2009 by Tommi Meakitalo\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"cxxtools\/xmlrpc\/client.h\"\n#include \"clientimpl.h\"\n#include \"cxxtools\/xmlrpc\/remoteprocedure.h\"\n#include \"cxxtools\/xml\/xmlerror.h\"\n#include \"cxxtools\/xml\/startelement.h\"\n#include \"cxxtools\/xml\/characters.h\"\n#include \"cxxtools\/xml\/endelement.h\"\n#include \"cxxtools\/http\/replyheader.h\"\n#include \"cxxtools\/selector.h\"\n#include \"cxxtools\/utf8codec.h\"\n#include \"cxxtools\/log.h\"\n\n\nnamespace cxxtools {\n\nnamespace xmlrpc {\n\nClientImpl::ClientImpl()\n: _state(OnBegin)\n, _ts( new Utf8Codec )\n, _reader(_ts)\n, _formatter(_writer)\n, _method(0)\n, _timeout(Selectable::WaitInfinite)\n{\n _writer.useIndent(false);\n _writer.useEndl(false);\n\n _formatter.addAlias(\"bool\", \"boolean\");\n}\n\nClientImpl::~ClientImpl()\n{\n}\n\n\nvoid ClientImpl::beginCall(IDeserializer& r, IRemoteProcedure& method, ISerializer** argv, unsigned argc)\n{\n _method = &method;\n _state = OnBegin;\n\n prepareRequest(method.name(), argv, argc);\n\n beginExecute();\n\n _reader.reset(_ts);\n _scanner.begin(r, _context);\n}\n\n\nvoid ClientImpl::call(IDeserializer& r, IRemoteProcedure& method, ISerializer** argv, unsigned argc)\n{\n _method = &method;\n _state = OnBegin;\n\n prepareRequest(method.name(), argv, argc);\n\n std::istringstream is(execute());\n _ts.attach(is);\n _reader.reset(_ts);\n _scanner.begin(r, _context);\n\n while( _reader.get().type() != cxxtools::xml::Node::EndDocument )\n {\n const cxxtools::xml::Node& node = _reader.get();\n advance(node);\n _reader.next();\n }\n\n \/\/ let xml::ParseError SerializationError, ConversionError propagate\n\n if (_method->failed() )\n {\n _state = OnBegin;\n throw _fault;\n }\n\n _state = OnBegin;\n\n \/\/ _method contains a valid return value now\n}\n\n\nconst IRemoteProcedure* ClientImpl::activeProcedure() const\n{\n return _method;\n}\n\nvoid ClientImpl::cancel()\n{\n _method = 0;\n}\n\nvoid ClientImpl::onReadReplyBegin(std::istream& is)\n{\n _ts.attach(is);\n}\n\nstd::size_t ClientImpl::onReadReply()\n{\n std::size_t n = 0;\n\n try\n {\n while(true)\n {\n std::streamsize m = _ts.buffer().import();\n if( ! m )\n break;\n\n n += m;\n\n while( _reader.advance() ) \/\/ xml::ParseError\n {\n const cxxtools::xml::Node& node = _reader.get();\n advance(node); \/\/ SerializationError, ConversionError\n }\n }\n }\n catch(const xml::XmlError& error)\n {\n _method->setFault(Fault::invalidXmlRpc, error.what());\n throw;\n }\n catch(const SerializationError& error)\n {\n _method->setFault(Fault::invalidMethodParameters, error.what());\n throw;\n }\n catch(const ConversionError& error)\n {\n _method->setFault(Fault::invalidMethodParameters, error.what());\n throw;\n }\n\n return n;\n}\n\n\nvoid ClientImpl::onReplyFinished()\n{\n IRemoteProcedure* method = _method;\n _method = 0;\n method->onFinished();\n}\n\n\nvoid ClientImpl::onErrorOccured(const std::exception& e)\n{\n if (_method)\n {\n \/\/ TODO do not map local exceptions to cxxtools::xmlrpc::Fault\n\n if (!_method->failed())\n _method->setFault(Fault::systemError, e.what());\n\n IRemoteProcedure* method = _method;\n _method = 0;\n method->onFinished();\n }\n else\n {\n throw;\n }\n}\n\n\nvoid ClientImpl::prepareRequest(const std::string& name, ISerializer** argv, unsigned argc)\n{\n _writer.begin( prepareRequest() );\n _writer.writeStartElement( L\"methodCall\" );\n _writer.writeElement( L\"methodName\", cxxtools::String::widen(name) );\n _writer.writeStartElement( L\"params\" );\n\n for(unsigned n = 0; n < argc; ++n)\n {\n _writer.writeStartElement( L\"param\" );\n argv[n]->format(_formatter);\n _writer.writeEndElement();\n }\n\n _writer.writeEndElement();\n _writer.writeEndElement();\n _writer.flush();\n}\n\n\nvoid ClientImpl::advance(const cxxtools::xml::Node& node)\n{\n switch(_state)\n {\n case OnBegin:\n {\n if(node.type() == xml::Node::StartElement)\n {\n const xml::StartElement& se = static_cast(node);\n if( se.name() != L\"methodResponse\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnMethodResponseBegin;\n }\n\n break;\n }\n\n case OnMethodResponseBegin:\n {\n if(node.type() == xml::Node::StartElement) \/\/ or \n {\n const xml::StartElement& se = static_cast(node);\n if( se.name() == L\"params\")\n {\n _state = OnParamsBegin;\n break;\n }\n\n else if( se.name() == L\"fault\")\n {\n _fh.begin(_fault);\n _scanner.begin(_fh, _context);\n _state = OnFaultBegin;\n break;\n }\n\n throw SerializationError(\"invalid XML-RPC methodCall\");\n }\n break;\n }\n\n case OnFaultBegin:\n {\n bool finished = _scanner.advance(node); \/\/ start with \n if(finished)\n {\n \/\/ <\/fault>\n _state = OnFaultEnd;\n }\n\n break;\n }\n\n case OnFaultEnd:\n {\n if(node.type() == xml::Node::EndElement) \/\/ <\/methodResponse>\n {\n const xml::EndElement& ee = static_cast(node);\n if( ee.name() != L\"methodResponse\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _method->setFault(_fault.rc(), _fault.text());\n\n _state = OnFaultResponseEnd;\n }\n break;\n }\n\n case OnFaultResponseEnd:\n {\n _state = OnFaultResponseEnd;\n break;\n }\n\n case OnParamsBegin:\n {\n if(node.type() == xml::Node::StartElement) \/\/ \n {\n const xml::StartElement& se = static_cast(node);\n if( se.name() != L\"param\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnParam;\n }\n\n break;\n }\n\n case OnParam:\n {\n bool finished = _scanner.advance(node); \/\/ start with \n if(finished)\n {\n \/\/ <\/param>\n _state = OnParamEnd;\n }\n\n break;\n }\n\n case OnParamEnd:\n {\n if(node.type() == xml::Node::EndElement) \/\/ <\/params>\n {\n const xml::EndElement& ee = static_cast(node);\n if( ee.name() != L\"params\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnParamsEnd;\n }\n break;\n }\n\n case OnParamsEnd:\n {\n if(node.type() == xml::Node::EndElement) \/\/ <\/methodResponse>\n {\n const xml::EndElement& ee = static_cast(node);\n if( ee.name() != L\"methodResponse\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnMethodResponseEnd;\n }\n break;\n }\n\n case OnMethodResponseEnd:\n {\n _state = OnMethodResponseEnd;\n break;\n }\n }\n}\n\n}\n\n}\nfix bug where syncronous xmlrpc request prevented keep alive in xmlrpc client\/*\n * Copyright (C) 2009 by Dr. Marc Boris Duerner\n * Copyright (C) 2009 by Tommi Meakitalo\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * As a special exception, you may use this file as part of a free\n * software library without restriction. Specifically, if other files\n * instantiate templates or use macros or inline functions from this\n * file, or you compile this file and link it with other files to\n * produce an executable, this file does not by itself cause the\n * resulting executable to be covered by the GNU General Public\n * License. This exception does not however invalidate any other\n * reasons why the executable file might be covered by the GNU Library\n * General Public License.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"cxxtools\/xmlrpc\/client.h\"\n#include \"clientimpl.h\"\n#include \"cxxtools\/xmlrpc\/remoteprocedure.h\"\n#include \"cxxtools\/xml\/xmlerror.h\"\n#include \"cxxtools\/xml\/startelement.h\"\n#include \"cxxtools\/xml\/characters.h\"\n#include \"cxxtools\/xml\/endelement.h\"\n#include \"cxxtools\/http\/replyheader.h\"\n#include \"cxxtools\/selector.h\"\n#include \"cxxtools\/utf8codec.h\"\n#include \"cxxtools\/log.h\"\n\n\nnamespace cxxtools {\n\nnamespace xmlrpc {\n\nClientImpl::ClientImpl()\n: _state(OnBegin)\n, _ts( new Utf8Codec )\n, _reader(_ts)\n, _formatter(_writer)\n, _method(0)\n, _timeout(Selectable::WaitInfinite)\n{\n _writer.useIndent(false);\n _writer.useEndl(false);\n\n _formatter.addAlias(\"bool\", \"boolean\");\n}\n\nClientImpl::~ClientImpl()\n{\n}\n\n\nvoid ClientImpl::beginCall(IDeserializer& r, IRemoteProcedure& method, ISerializer** argv, unsigned argc)\n{\n _method = &method;\n _state = OnBegin;\n\n prepareRequest(method.name(), argv, argc);\n\n beginExecute();\n\n _reader.reset(_ts);\n _scanner.begin(r, _context);\n}\n\n\nvoid ClientImpl::call(IDeserializer& r, IRemoteProcedure& method, ISerializer** argv, unsigned argc)\n{\n _method = &method;\n _state = OnBegin;\n\n prepareRequest(method.name(), argv, argc);\n\n std::istringstream is(execute());\n _ts.attach(is);\n _reader.reset(_ts);\n _scanner.begin(r, _context);\n\n while( _reader.get().type() != cxxtools::xml::Node::EndDocument )\n {\n const cxxtools::xml::Node& node = _reader.get();\n advance(node);\n _reader.next();\n }\n\n \/\/ let xml::ParseError SerializationError, ConversionError propagate\n\n if (_method->failed() )\n {\n _method = 0;\n _state = OnBegin;\n throw _fault;\n }\n\n _method = 0;\n _state = OnBegin;\n\n \/\/ _method contains a valid return value now\n}\n\n\nconst IRemoteProcedure* ClientImpl::activeProcedure() const\n{\n return _method;\n}\n\nvoid ClientImpl::cancel()\n{\n _method = 0;\n}\n\nvoid ClientImpl::onReadReplyBegin(std::istream& is)\n{\n _ts.attach(is);\n}\n\nstd::size_t ClientImpl::onReadReply()\n{\n std::size_t n = 0;\n\n try\n {\n while(true)\n {\n std::streamsize m = _ts.buffer().import();\n if( ! m )\n break;\n\n n += m;\n\n while( _reader.advance() ) \/\/ xml::ParseError\n {\n const cxxtools::xml::Node& node = _reader.get();\n advance(node); \/\/ SerializationError, ConversionError\n }\n }\n }\n catch(const xml::XmlError& error)\n {\n _method->setFault(Fault::invalidXmlRpc, error.what());\n throw;\n }\n catch(const SerializationError& error)\n {\n _method->setFault(Fault::invalidMethodParameters, error.what());\n throw;\n }\n catch(const ConversionError& error)\n {\n _method->setFault(Fault::invalidMethodParameters, error.what());\n throw;\n }\n\n return n;\n}\n\n\nvoid ClientImpl::onReplyFinished()\n{\n IRemoteProcedure* method = _method;\n _method = 0;\n method->onFinished();\n}\n\n\nvoid ClientImpl::onErrorOccured(const std::exception& e)\n{\n if (_method)\n {\n \/\/ TODO do not map local exceptions to cxxtools::xmlrpc::Fault\n\n if (!_method->failed())\n _method->setFault(Fault::systemError, e.what());\n\n IRemoteProcedure* method = _method;\n _method = 0;\n method->onFinished();\n }\n else\n {\n throw;\n }\n}\n\n\nvoid ClientImpl::prepareRequest(const std::string& name, ISerializer** argv, unsigned argc)\n{\n _writer.begin( prepareRequest() );\n _writer.writeStartElement( L\"methodCall\" );\n _writer.writeElement( L\"methodName\", cxxtools::String::widen(name) );\n _writer.writeStartElement( L\"params\" );\n\n for(unsigned n = 0; n < argc; ++n)\n {\n _writer.writeStartElement( L\"param\" );\n argv[n]->format(_formatter);\n _writer.writeEndElement();\n }\n\n _writer.writeEndElement();\n _writer.writeEndElement();\n _writer.flush();\n}\n\n\nvoid ClientImpl::advance(const cxxtools::xml::Node& node)\n{\n switch(_state)\n {\n case OnBegin:\n {\n if(node.type() == xml::Node::StartElement)\n {\n const xml::StartElement& se = static_cast(node);\n if( se.name() != L\"methodResponse\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnMethodResponseBegin;\n }\n\n break;\n }\n\n case OnMethodResponseBegin:\n {\n if(node.type() == xml::Node::StartElement) \/\/ or \n {\n const xml::StartElement& se = static_cast(node);\n if( se.name() == L\"params\")\n {\n _state = OnParamsBegin;\n break;\n }\n\n else if( se.name() == L\"fault\")\n {\n _fh.begin(_fault);\n _scanner.begin(_fh, _context);\n _state = OnFaultBegin;\n break;\n }\n\n throw SerializationError(\"invalid XML-RPC methodCall\");\n }\n break;\n }\n\n case OnFaultBegin:\n {\n bool finished = _scanner.advance(node); \/\/ start with \n if(finished)\n {\n \/\/ <\/fault>\n _state = OnFaultEnd;\n }\n\n break;\n }\n\n case OnFaultEnd:\n {\n if(node.type() == xml::Node::EndElement) \/\/ <\/methodResponse>\n {\n const xml::EndElement& ee = static_cast(node);\n if( ee.name() != L\"methodResponse\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _method->setFault(_fault.rc(), _fault.text());\n\n _state = OnFaultResponseEnd;\n }\n break;\n }\n\n case OnFaultResponseEnd:\n {\n _state = OnFaultResponseEnd;\n break;\n }\n\n case OnParamsBegin:\n {\n if(node.type() == xml::Node::StartElement) \/\/ \n {\n const xml::StartElement& se = static_cast(node);\n if( se.name() != L\"param\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnParam;\n }\n\n break;\n }\n\n case OnParam:\n {\n bool finished = _scanner.advance(node); \/\/ start with \n if(finished)\n {\n \/\/ <\/param>\n _state = OnParamEnd;\n }\n\n break;\n }\n\n case OnParamEnd:\n {\n if(node.type() == xml::Node::EndElement) \/\/ <\/params>\n {\n const xml::EndElement& ee = static_cast(node);\n if( ee.name() != L\"params\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnParamsEnd;\n }\n break;\n }\n\n case OnParamsEnd:\n {\n if(node.type() == xml::Node::EndElement) \/\/ <\/methodResponse>\n {\n const xml::EndElement& ee = static_cast(node);\n if( ee.name() != L\"methodResponse\" )\n throw SerializationError(\"invalid XML-RPC methodCall\");\n\n _state = OnMethodResponseEnd;\n }\n break;\n }\n\n case OnMethodResponseEnd:\n {\n _state = OnMethodResponseEnd;\n break;\n }\n }\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"\/* Copyright (C) 2018 INRA\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_SPARSE_MATRIX_HPP\n#define ORG_VLEPROJECT_BARYONYX_SOLVER_SPARSE_MATRIX_HPP\n\n#include \n\n#include \n#include \n#include \n\n#include \"debug.hpp\"\n#include \"fixed-array.hpp\"\n\nnamespace baryonyx {\n\ntemplate\nclass sparse_matrix\n{\npublic:\n using size_type = std::size_t;\n using index_type = Index;\n\n struct col_value\n {\n col_value() = default;\n\n col_value(int value_, int row_)\n : value(value_)\n , row(row_)\n {}\n\n int value = -1;\n int row = -1;\n };\n\n struct row_value\n {\n row_value() = default;\n\n row_value(int value_, int column_)\n : value(value_)\n , column(column_)\n {}\n\n int value = -1;\n int column = -1;\n };\n\nprotected:\n using vector_access = fixed_array;\n using row_vector_access = fixed_array;\n using col_vector_access = fixed_array;\n\n vector_access m_rows_access;\n vector_access m_cols_access;\n row_vector_access m_rows_values;\n col_vector_access m_cols_values;\n\npublic:\n using row_iterator = typename row_vector_access::iterator;\n using col_iterator = typename col_vector_access::iterator;\n using const_row_iterator = typename row_vector_access::const_iterator;\n using const_col_iterator = typename col_vector_access::const_iterator;\n\n template\n explicit sparse_matrix(const std::vector& csts,\n const int rows,\n const int cols)\n : m_rows_access(rows + 1)\n , m_cols_access(cols + 1)\n {\n int elem = 0;\n\n for (int i = 0, e = rows; i != e; ++i)\n elem += static_cast(csts[i].elements.size());\n\n row_vector_access(elem).swap(m_rows_values);\n col_vector_access(elem).swap(m_cols_values);\n\n \/\/\n \/\/ First, we build a vector of access to all elements in the matrix\n \/\/ different to 0. Then, we sort accessors according to the column id\n \/\/ then we assign a unique identifier for each accessors and then we\n \/\/ sort accessors according to the row id. This code enable the\n \/\/ construction of the r_rows_values with pointers to the\n \/\/ r_cols_values.\n \/\/\n\n struct access\n {\n access() = default;\n\n access(int row_, int col_, function_element fct_)\n : row(row_)\n , col(col_)\n , fct(fct_)\n {}\n\n int row;\n int col;\n int id;\n function_element fct;\n };\n\n std::vector accessors;\n accessors.reserve(elem);\n for (int i = 0; i != rows; ++i)\n for (const auto& fct_elem : csts[i].elements)\n accessors.emplace_back(i, fct_elem.variable_index, fct_elem);\n\n \/\/ std::stable_sort(\n \/\/ accessors.begin(),\n \/\/ accessors.end(),\n \/\/ [](const auto& lhs, const auto& rhs) { return lhs.row < rhs.row;\n \/\/ });\n\n fixed_array rinit(rows, 0);\n int row = accessors[0].row;\n int nb_row = 0;\n for (int i = 0; i != elem; ++i) {\n if (row != accessors[i].row) {\n rinit[row] = nb_row;\n nb_row = 0;\n row = accessors[i].row;\n }\n ++nb_row;\n\n accessors[i].id = i;\n m_rows_values[i] = { i, accessors[i].col };\n }\n\n rinit[row] = nb_row; \/* Be sure to affect the good number of elements\n for this constaints. *\/\n\n for (int i = 0; i != rows; ++i)\n bx_assert(rinit[i] == static_cast(csts[i].elements.size()));\n\n std::stable_sort(\n accessors.begin(),\n accessors.end(),\n [](const auto& lhs, const auto& rhs) { return lhs.col < rhs.col; });\n\n fixed_array cinit(cols, 0);\n int col = accessors[0].col;\n int nb_col = 0;\n\n for (int i = 0; i != elem; ++i) {\n if (col != accessors[i].col) {\n cinit[col] = nb_col;\n nb_col = 0;\n col = accessors[i].col;\n }\n ++nb_col;\n\n m_cols_values[i] = { m_rows_values[accessors[i].id].value,\n accessors[i].row };\n }\n\n cinit[col] = nb_col; \/* Be sure to affect the good number of elements\n for this constaints. *\/\n\n m_rows_access[0] = 0;\n for (int i = 0; i != rows; ++i)\n m_rows_access[i + 1] = m_rows_access[i] + rinit[i];\n\n m_cols_access[0] = 0;\n for (int i = 0; i != cols; ++i)\n m_cols_access[i + 1] = m_cols_access[i] + cinit[i];\n }\n\n std::tuple row(int row) noexcept\n {\n m_check_index(row, 0);\n\n row_iterator begin = m_rows_values.begin() + m_rows_access[row];\n row_iterator end = m_rows_values.begin() + m_rows_access[row + 1];\n\n return std::make_tuple(begin, end);\n }\n\n std::tuple column(int col) noexcept\n {\n m_check_index(0, col);\n\n col_iterator begin = m_cols_values.begin() + m_cols_access[col];\n col_iterator end = m_cols_values.begin() + m_cols_access[col + 1];\n\n return std::make_tuple(begin, end);\n }\n\n std::tuple row(int row) const\n noexcept\n {\n m_check_index(row, 0);\n\n const_row_iterator begin = m_rows_values.begin() + m_rows_access[row];\n const_row_iterator end =\n m_rows_values.begin() + m_rows_access[row + 1];\n\n return std::make_tuple(begin, end);\n }\n\n std::tuple column(int col) const\n noexcept\n {\n m_check_index(0, col);\n\n const_col_iterator begin = m_cols_values.begin() + m_cols_access[col];\n const_col_iterator end =\n m_cols_values.begin() + m_cols_access[col + 1];\n\n return std::make_tuple(begin, end);\n }\n\n size_type size() const noexcept\n {\n return m_rows_values.size();\n }\n\n int length() const noexcept\n {\n return static_cast(size());\n }\n\nprivate:\n void m_check_index(index_type row, index_type col) const noexcept\n {\n bx_expects(col >= 0 &&\n static_cast(col) < (m_cols_access.size() - 1));\n\n bx_expects(row >= 0 &&\n static_cast(row) < (m_rows_access.size() - 1));\n }\n};\n}\n\n#endif\nsparse-matrix: remove the memory friendly access\/* Copyright (C) 2018 INRA\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_SPARSE_MATRIX_HPP\n#define ORG_VLEPROJECT_BARYONYX_SOLVER_SPARSE_MATRIX_HPP\n\n#include \n\n#include \n#include \n#include \n\n#include \"debug.hpp\"\n#include \"fixed-array.hpp\"\n\nnamespace baryonyx {\n\ntemplate\nclass sparse_matrix\n{\npublic:\n using size_type = std::size_t;\n using index_type = Index;\n\n struct col_value\n {\n col_value() = default;\n\n col_value(int value_, int row_)\n : value(value_)\n , row(row_)\n {}\n\n int value = -1;\n int row = -1;\n };\n\n struct row_value\n {\n row_value() = default;\n\n row_value(int value_, int column_)\n : value(value_)\n , column(column_)\n {}\n\n int value = -1;\n int column = -1;\n };\n\nprotected:\n using vector_access = fixed_array;\n using row_vector_access = fixed_array;\n using col_vector_access = fixed_array;\n\n vector_access m_rows_access;\n vector_access m_cols_access;\n row_vector_access m_rows_values;\n col_vector_access m_cols_values;\n\npublic:\n using row_iterator = typename row_vector_access::iterator;\n using col_iterator = typename col_vector_access::iterator;\n using const_row_iterator = typename row_vector_access::const_iterator;\n using const_col_iterator = typename col_vector_access::const_iterator;\n\n template\n explicit sparse_matrix(const std::vector& csts,\n const int rows,\n const int cols)\n : m_rows_access(rows + 1)\n , m_cols_access(cols + 1)\n {\n int elem = 0;\n\n for (int i = 0, e = rows; i != e; ++i)\n elem += static_cast(csts[i].elements.size());\n\n row_vector_access(elem).swap(m_rows_values);\n col_vector_access(elem).swap(m_cols_values);\n\n \/\/\n \/\/ First, we build a vector of access to all elements in the matrix\n \/\/ different to 0. Then, we sort accessors according to the column id\n \/\/ then we assign a unique identifier for each accessors and then we\n \/\/ sort accessors according to the row id. This code enable the\n \/\/ construction of the r_rows_values with pointers to the\n \/\/ r_cols_values.\n \/\/\n\n struct access\n {\n access() = default;\n\n access(int row_, int col_, function_element fct_)\n : row(row_)\n , col(col_)\n , fct(fct_)\n {}\n\n int row;\n int col;\n int id;\n function_element fct;\n };\n\n std::vector accessors;\n accessors.reserve(elem);\n for (int i = 0; i != rows; ++i)\n for (const auto& fct_elem : csts[i].elements)\n accessors.emplace_back(i, fct_elem.variable_index, fct_elem);\n\n fixed_array rinit(rows, 0);\n int row = accessors[0].row;\n int nb_row = 0;\n for (int i = 0; i != elem; ++i) {\n if (row != accessors[i].row) {\n rinit[row] = nb_row;\n nb_row = 0;\n row = accessors[i].row;\n }\n ++nb_row;\n\n accessors[i].id = i;\n m_rows_values[i] = { i, accessors[i].col };\n }\n\n rinit[row] = nb_row; \/* Be sure to affect the good number of elements\n for this constaints. *\/\n\n for (int i = 0; i != rows; ++i)\n bx_assert(rinit[i] == static_cast(csts[i].elements.size()));\n\n \/\/ We sort the accessors to improve memory friendly access.\n\n std::stable_sort(\n accessors.begin(),\n accessors.end(),\n [](const auto& lhs, const auto& rhs) { return lhs.col < rhs.col; });\n\n fixed_array cinit(cols, 0);\n int col = accessors[0].col;\n int nb_col = 0;\n\n for (int i = 0; i != elem; ++i) {\n if (col != accessors[i].col) {\n cinit[col] = nb_col;\n nb_col = 0;\n col = accessors[i].col;\n }\n ++nb_col;\n\n m_cols_values[i] = { m_rows_values[accessors[i].id].value,\n accessors[i].row };\n }\n\n cinit[col] = nb_col; \/* Be sure to affect the good number of elements\n for this constaints. *\/\n\n m_rows_access[0] = 0;\n for (int i = 0; i != rows; ++i)\n m_rows_access[i + 1] = m_rows_access[i] + rinit[i];\n\n m_cols_access[0] = 0;\n for (int i = 0; i != cols; ++i)\n m_cols_access[i + 1] = m_cols_access[i] + cinit[i];\n }\n\n std::tuple row(int row) noexcept\n {\n m_check_index(row, 0);\n\n row_iterator begin = m_rows_values.begin() + m_rows_access[row];\n row_iterator end = m_rows_values.begin() + m_rows_access[row + 1];\n\n return std::make_tuple(begin, end);\n }\n\n std::tuple column(int col) noexcept\n {\n m_check_index(0, col);\n\n col_iterator begin = m_cols_values.begin() + m_cols_access[col];\n col_iterator end = m_cols_values.begin() + m_cols_access[col + 1];\n\n return std::make_tuple(begin, end);\n }\n\n std::tuple row(int row) const\n noexcept\n {\n m_check_index(row, 0);\n\n const_row_iterator begin = m_rows_values.begin() + m_rows_access[row];\n const_row_iterator end =\n m_rows_values.begin() + m_rows_access[row + 1];\n\n return std::make_tuple(begin, end);\n }\n\n std::tuple column(int col) const\n noexcept\n {\n m_check_index(0, col);\n\n const_col_iterator begin = m_cols_values.begin() + m_cols_access[col];\n const_col_iterator end =\n m_cols_values.begin() + m_cols_access[col + 1];\n\n return std::make_tuple(begin, end);\n }\n\n size_type size() const noexcept\n {\n return m_rows_values.size();\n }\n\n int length() const noexcept\n {\n return static_cast(size());\n }\n\nprivate:\n void m_check_index(index_type row, index_type col) const noexcept\n {\n bx_expects(col >= 0 &&\n static_cast(col) < (m_cols_access.size() - 1));\n\n bx_expects(row >= 0 &&\n static_cast(row) < (m_rows_access.size() - 1));\n }\n};\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/Copyright (c) 2021 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"sliceDataStorage.h\"\n#include \"TreeModelVolumes.h\"\n\nnamespace cura\n{\n\nTreeModelVolumes::TreeModelVolumes(const SliceDataStorage& storage, const Settings& settings)\n : machine_border_(calculateMachineBorderCollision(storage.getMachineBorder()))\n , xy_distance_(settings.get(\"support_xy_distance\"))\n , xy_distance_overhang(settings.get(\"support_xy_distance_overhang\"))\n , distance_priority(settings.get(\"support_xy_overrides_z\"))\n , radius_sample_resolution_(settings.get(\"support_tree_collision_resolution\"))\n{\n const coord_t layer_height = settings.get(\"layer_height\");\n const AngleRadians angle = settings.get(\"support_tree_angle\");\n max_move_ = (angle < TAU \/ 4) ? (coord_t)(tan(angle) * layer_height) : std::numeric_limits::max();\n z_distance_layers = round_up_divide(settings.get(\"support_top_distance\"), layer_height) + 1;\n for (std::size_t layer_idx = 0; layer_idx < storage.support.supportLayers.size(); ++layer_idx)\n {\n constexpr bool include_support = false;\n constexpr bool include_prime_tower = true;\n layer_outlines_.push_back(storage.getLayerOutlines(layer_idx, include_support, include_prime_tower));\n }\n}\n\nconst Polygons& TreeModelVolumes::getCollision(coord_t radius, LayerIndex layer_idx) const\n{\n radius = ceilRadius(radius);\n RadiusLayerPair key{radius, layer_idx};\n const auto it = collision_cache_.find(key);\n if (it != collision_cache_.end())\n {\n return it->second;\n }\n else\n {\n return calculateCollision(key);\n }\n}\n\nconst Polygons& TreeModelVolumes::getAvoidance(coord_t radius, LayerIndex layer_idx) const\n{\n radius = ceilRadius(radius);\n RadiusLayerPair key{radius, layer_idx};\n const auto it = avoidance_cache_.find(key);\n if (it != avoidance_cache_.end())\n {\n return it->second;\n }\n else\n {\n return calculateAvoidance(key);\n }\n}\n\nconst Polygons& TreeModelVolumes::getInternalModel(coord_t radius, LayerIndex layer_idx) const\n{\n radius = ceilRadius(radius);\n RadiusLayerPair key{radius, layer_idx};\n const auto it = internal_model_cache_.find(key);\n if (it != internal_model_cache_.end())\n {\n return it->second;\n }\n else\n {\n return calculateInternalModel(key);\n }\n}\n\ncoord_t TreeModelVolumes::ceilRadius(coord_t radius) const\n{\n const auto remainder = radius % radius_sample_resolution_;\n const auto delta = remainder != 0 ? radius_sample_resolution_- remainder : 0;\n return radius + delta;\n}\n\nconst Polygons& TreeModelVolumes::calculateCollision(const RadiusLayerPair& key) const\n{\n const coord_t radius = key.first;\n const LayerIndex layer_idx = key.second;\n\n Polygons collision_areas = machine_border_;\n if(layer_idx < static_cast(layer_outlines_.size()))\n {\n if(distance_priority == SupportDistPriority::XY_OVERRIDES_Z)\n {\n \/\/If X\/Y overrides Z, simply use the X\/Y distance as distance to keep away from the model.\n collision_areas = collision_areas.unionPolygons(layer_outlines_[layer_idx].offset(xy_distance_ + radius, ClipperLib::JoinType::jtRound));\n }\n else if(layer_idx + z_distance_layers < static_cast(layer_outlines_.size()))\n {\n \/\/If Z overrides X\/Y, use X\/Y distance if the surface is vertical, or Min X\/Y distance if not.\n Polygons z_influenced = layer_outlines_[layer_idx + z_distance_layers].difference(layer_outlines_[layer_idx]).offset(xy_distance_); \/\/In-between layers are ignored for performance.\n Polygons collision_not_overhang = layer_outlines_[layer_idx].offset(xy_distance_); \/\/In places where there is no overhang nearby, use the normal X\/Y distance.\n if(!z_influenced.empty())\n {\n collision_not_overhang = collision_not_overhang.difference(z_influenced);\n }\n Polygons collision_model = collision_not_overhang.unionPolygons(layer_outlines_[layer_idx].offset(xy_distance_overhang)); \/\/Apply the minimum distance everywhere else.\n collision_areas = collision_areas.unionPolygons(collision_model.offset(radius));\n }\n }\n const auto ret = collision_cache_.insert({key, std::move(collision_areas)});\n assert(ret.second);\n return ret.first->second;\n}\n\nconst Polygons& TreeModelVolumes::calculateAvoidance(const RadiusLayerPair& key) const\n{\n const auto& radius = key.first;\n const auto& layer_idx = key.second;\n\n if (layer_idx == 0)\n {\n avoidance_cache_[key] = getCollision(radius, 0);\n return avoidance_cache_[key];\n }\n\n \/\/ Avoidance for a given layer depends on all layers beneath it so could have very deep recursion depths if\n \/\/ called at high layer heights. We can limit the reqursion depth to N by checking if the if the layer N\n \/\/ below the current one exists and if not, forcing the calculation of that layer. This may cause another recursion\n \/\/ if the layer at 2N below the current one but we won't exceed our limit unless there are N*N uncalculated layers\n \/\/ below our current one.\n constexpr auto max_recursion_depth = 100;\n \/\/ Check if we would exceed the recursion limit by trying to process this layer\n if (layer_idx >= max_recursion_depth\n && avoidance_cache_.find({radius, layer_idx - max_recursion_depth}) == avoidance_cache_.end())\n {\n \/\/ Force the calculation of the layer `max_recursion_depth` below our current one, ignoring the result.\n getAvoidance(radius, layer_idx - max_recursion_depth);\n }\n auto avoidance_areas = getAvoidance(radius, layer_idx - 1).offset(-max_move_).smooth(5);\n avoidance_areas = avoidance_areas.unionPolygons(getCollision(radius, layer_idx));\n const auto ret = avoidance_cache_.insert({key, std::move(avoidance_areas)});\n assert(ret.second);\n return ret.first->second;\n}\n\nconst Polygons& TreeModelVolumes::calculateInternalModel(const RadiusLayerPair& key) const\n{\n const auto& radius = key.first;\n const auto& layer_idx = key.second;\n\n const auto& internal_areas = getAvoidance(radius, layer_idx).difference(getCollision(radius, layer_idx));\n const auto ret = internal_model_cache_.insert({key, internal_areas});\n assert(ret.second);\n return ret.first->second;\n}\n\nPolygons TreeModelVolumes::calculateMachineBorderCollision(Polygon machine_border)\n{\n Polygons machine_volume_border;\n machine_volume_border.add(machine_border.offset(MM2INT(1000))); \/\/Put a border of 1m around the print volume so that we don't collide.\n machine_border.reverse(); \/\/Makes the polygon negative so that we subtract the actual volume from the collision area.\n machine_volume_border.add(machine_border);\n return machine_volume_border;\n}\n\n}No unnecessary round join types\/\/Copyright (c) 2021 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"sliceDataStorage.h\"\n#include \"TreeModelVolumes.h\"\n\nnamespace cura\n{\n\nTreeModelVolumes::TreeModelVolumes(const SliceDataStorage& storage, const Settings& settings)\n : machine_border_(calculateMachineBorderCollision(storage.getMachineBorder()))\n , xy_distance_(settings.get(\"support_xy_distance\"))\n , xy_distance_overhang(settings.get(\"support_xy_distance_overhang\"))\n , distance_priority(settings.get(\"support_xy_overrides_z\"))\n , radius_sample_resolution_(settings.get(\"support_tree_collision_resolution\"))\n{\n const coord_t layer_height = settings.get(\"layer_height\");\n const AngleRadians angle = settings.get(\"support_tree_angle\");\n max_move_ = (angle < TAU \/ 4) ? (coord_t)(tan(angle) * layer_height) : std::numeric_limits::max();\n z_distance_layers = round_up_divide(settings.get(\"support_top_distance\"), layer_height) + 1;\n for (std::size_t layer_idx = 0; layer_idx < storage.support.supportLayers.size(); ++layer_idx)\n {\n constexpr bool include_support = false;\n constexpr bool include_prime_tower = true;\n layer_outlines_.push_back(storage.getLayerOutlines(layer_idx, include_support, include_prime_tower));\n }\n}\n\nconst Polygons& TreeModelVolumes::getCollision(coord_t radius, LayerIndex layer_idx) const\n{\n radius = ceilRadius(radius);\n RadiusLayerPair key{radius, layer_idx};\n const auto it = collision_cache_.find(key);\n if (it != collision_cache_.end())\n {\n return it->second;\n }\n else\n {\n return calculateCollision(key);\n }\n}\n\nconst Polygons& TreeModelVolumes::getAvoidance(coord_t radius, LayerIndex layer_idx) const\n{\n radius = ceilRadius(radius);\n RadiusLayerPair key{radius, layer_idx};\n const auto it = avoidance_cache_.find(key);\n if (it != avoidance_cache_.end())\n {\n return it->second;\n }\n else\n {\n return calculateAvoidance(key);\n }\n}\n\nconst Polygons& TreeModelVolumes::getInternalModel(coord_t radius, LayerIndex layer_idx) const\n{\n radius = ceilRadius(radius);\n RadiusLayerPair key{radius, layer_idx};\n const auto it = internal_model_cache_.find(key);\n if (it != internal_model_cache_.end())\n {\n return it->second;\n }\n else\n {\n return calculateInternalModel(key);\n }\n}\n\ncoord_t TreeModelVolumes::ceilRadius(coord_t radius) const\n{\n const auto remainder = radius % radius_sample_resolution_;\n const auto delta = remainder != 0 ? radius_sample_resolution_- remainder : 0;\n return radius + delta;\n}\n\nconst Polygons& TreeModelVolumes::calculateCollision(const RadiusLayerPair& key) const\n{\n const coord_t radius = key.first;\n const LayerIndex layer_idx = key.second;\n\n Polygons collision_areas = machine_border_;\n if(layer_idx < static_cast(layer_outlines_.size()))\n {\n if(distance_priority == SupportDistPriority::XY_OVERRIDES_Z)\n {\n \/\/If X\/Y overrides Z, simply use the X\/Y distance as distance to keep away from the model.\n collision_areas = collision_areas.unionPolygons(layer_outlines_[layer_idx].offset(xy_distance_ + radius));\n }\n else if(layer_idx + z_distance_layers < static_cast(layer_outlines_.size()))\n {\n \/\/If Z overrides X\/Y, use X\/Y distance if the surface is vertical, or Min X\/Y distance if not.\n Polygons z_influenced = layer_outlines_[layer_idx + z_distance_layers].difference(layer_outlines_[layer_idx]).offset(xy_distance_); \/\/In-between layers are ignored for performance.\n Polygons collision_not_overhang = layer_outlines_[layer_idx].offset(xy_distance_); \/\/In places where there is no overhang nearby, use the normal X\/Y distance.\n if(!z_influenced.empty())\n {\n collision_not_overhang = collision_not_overhang.difference(z_influenced);\n }\n Polygons collision_model = collision_not_overhang.unionPolygons(layer_outlines_[layer_idx].offset(xy_distance_overhang)); \/\/Apply the minimum distance everywhere else.\n collision_areas = collision_areas.unionPolygons(collision_model.offset(radius));\n }\n }\n const auto ret = collision_cache_.insert({key, std::move(collision_areas)});\n assert(ret.second);\n return ret.first->second;\n}\n\nconst Polygons& TreeModelVolumes::calculateAvoidance(const RadiusLayerPair& key) const\n{\n const auto& radius = key.first;\n const auto& layer_idx = key.second;\n\n if (layer_idx == 0)\n {\n avoidance_cache_[key] = getCollision(radius, 0);\n return avoidance_cache_[key];\n }\n\n \/\/ Avoidance for a given layer depends on all layers beneath it so could have very deep recursion depths if\n \/\/ called at high layer heights. We can limit the reqursion depth to N by checking if the if the layer N\n \/\/ below the current one exists and if not, forcing the calculation of that layer. This may cause another recursion\n \/\/ if the layer at 2N below the current one but we won't exceed our limit unless there are N*N uncalculated layers\n \/\/ below our current one.\n constexpr auto max_recursion_depth = 100;\n \/\/ Check if we would exceed the recursion limit by trying to process this layer\n if (layer_idx >= max_recursion_depth\n && avoidance_cache_.find({radius, layer_idx - max_recursion_depth}) == avoidance_cache_.end())\n {\n \/\/ Force the calculation of the layer `max_recursion_depth` below our current one, ignoring the result.\n getAvoidance(radius, layer_idx - max_recursion_depth);\n }\n auto avoidance_areas = getAvoidance(radius, layer_idx - 1).offset(-max_move_).smooth(5);\n avoidance_areas = avoidance_areas.unionPolygons(getCollision(radius, layer_idx));\n const auto ret = avoidance_cache_.insert({key, std::move(avoidance_areas)});\n assert(ret.second);\n return ret.first->second;\n}\n\nconst Polygons& TreeModelVolumes::calculateInternalModel(const RadiusLayerPair& key) const\n{\n const auto& radius = key.first;\n const auto& layer_idx = key.second;\n\n const auto& internal_areas = getAvoidance(radius, layer_idx).difference(getCollision(radius, layer_idx));\n const auto ret = internal_model_cache_.insert({key, internal_areas});\n assert(ret.second);\n return ret.first->second;\n}\n\nPolygons TreeModelVolumes::calculateMachineBorderCollision(Polygon machine_border)\n{\n Polygons machine_volume_border;\n machine_volume_border.add(machine_border.offset(MM2INT(1000))); \/\/Put a border of 1m around the print volume so that we don't collide.\n machine_border.reverse(); \/\/Makes the polygon negative so that we subtract the actual volume from the collision area.\n machine_volume_border.add(machine_border);\n return machine_volume_border;\n}\n\n}<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n#if !defined(FUNCTIONKEY_HEADER_GUARD_1357924680)\n#define FUNCTIONKEY_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base header file. Must be first.\n#include \n\n\n\n#include \n\n\n\n#include \n\n\n\nclass DOM_Node;\nclass XObject;\nclass XPathExecutionContext;\n\n\n\n\/\/ Implementation of the XSLT function key().\n\/\/\nclass XALAN_XSLT_EXPORT FunctionKey : public Function\n{\npublic:\n\n#if defined(XALAN_NO_NAMESPACES)\n\ttypedef vector XObjectPtrVectorType;\n#else\n\ttypedef std::vector XObjectPtrVectorType;\n#endif \n\n\tFunctionKey();\n\n\tvirtual\n\t~FunctionKey();\n\n\t\/\/ These methods are inherited from XPath\/Function ...\n\n\tvirtual XObject*\n\texecute(\n\t\t\tXPathExecutionContext&\t\t\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\t\tcontext,\n\t\t\tint\t\t\t\t\t\t\t\topPos,\n\t\t\tconst XObjectArgVectorType&\t\targs);\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\n\tvirtual Function*\n#else\n\tvirtual FunctionKey*\n#endif\n\tclone() const;\n\nprivate:\n\n\t\/\/ Not implemented...\n\tFunctionKey&\n\toperator=(const FunctionKey&);\n\n\tbool\n\toperator==(const FunctionKey&) const;\n};\n\n\n\n#endif\t\/\/ FUNCTIONKEY_HEADER_GUARD_1357924680\nRemoved redundant typedef.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n#if !defined(FUNCTIONKEY_HEADER_GUARD_1357924680)\n#define FUNCTIONKEY_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base header file. Must be first.\n#include \n\n\n\n#include \n\n\n\n#include \n\n\n\nclass XObject;\nclass XPathExecutionContext;\n\n\n\n\/\/ Implementation of the XSLT function key().\n\/\/\nclass XALAN_XSLT_EXPORT FunctionKey : public Function\n{\npublic:\n\n\tFunctionKey();\n\n\tvirtual\n\t~FunctionKey();\n\n\t\/\/ These methods are inherited from XPath\/Function ...\n\n\tvirtual XObject*\n\texecute(\n\t\t\tXPathExecutionContext&\t\t\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\t\tcontext,\n\t\t\tint\t\t\t\t\t\t\t\topPos,\n\t\t\tconst XObjectArgVectorType&\t\targs);\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\n\tvirtual Function*\n#else\n\tvirtual FunctionKey*\n#endif\n\tclone() const;\n\nprivate:\n\n\t\/\/ Not implemented...\n\tFunctionKey&\n\toperator=(const FunctionKey&);\n\n\tbool\n\toperator==(const FunctionKey&) const;\n};\n\n\n\n#endif\t\/\/ FUNCTIONKEY_HEADER_GUARD_1357924680\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"vector_tile.pb.h\"\n\n#define XMAX 4096\n#define YMAX 4096\n\nextern \"C\" {\n\t#include \"graphics.h\"\n\t#include \"clip.h\"\n}\n\nstruct line {\n\tint x0;\n\tint y0;\n\tint x1;\n\tint y1;\n};\n\nstruct point {\n\tint x;\n\tint y;\n};\n\n#define MAX_POINTS 10000\nstruct pointlayer {\n\tstruct point *points;\n\tint npoints;\n\tint npalloc;\n\n\tstruct pointlayer *next;\n};\n\nstruct linelayer {\n\tstruct line *lines;\n\tint nlines;\n\tint nlalloc;\n\tunsigned char *used;\n\n\tstruct linelayer *next;\n};\n\nclass env {\npublic:\n\tmapnik::vector::tile tile;\n\tmapnik::vector::tile_layer *layer;\n\tmapnik::vector::tile_feature *feature;\n\n\tint x;\n\tint y;\n\n\tint cmd_idx;\n\tint cmd;\n\tint length;\n\n\tstruct linelayer *linelayers;\n\n\tstruct pointlayer *pointlayers;\n\tstruct pointlayer **used;\n};\n\n#define MOVE_TO 1\n#define LINE_TO 2\n#define CLOSE_PATH 7\n#define CMD_BITS 3\n\nstruct graphics {\n\tint width;\n\tint height;\n\tenv *e;\n};\n\nstruct pointlayer *new_pointlayer() {\n\tstruct pointlayer *p = (struct pointlayer *) malloc(sizeof(struct pointlayer));\n\tp->npalloc = 1024;\n\tp->npoints = 0;\n\tp->points = (struct point *) malloc(p->npalloc * sizeof(struct point));\n\tp->next = NULL;\n\n\treturn p;\n}\n\nstruct linelayer *new_linelayer() {\n\tstruct linelayer *l = (struct linelayer *) malloc(sizeof(struct linelayer));\n\tl->nlalloc = 1024;\n\tl->nlines = 0;\n\tl->lines = (struct line *) malloc(l->nlalloc * sizeof(struct line));\n\tl->next = NULL;\n\tl->used = (unsigned char *) malloc(256 * 256 * sizeof(unsigned char));\n\n\treturn l;\n}\n\nstruct graphics *graphics_init(int width, int height) {\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\tenv *e = new env;\n\n\te->linelayers = new_linelayer();\n\te->pointlayers = new_pointlayer();\n\te->used = (struct pointlayer **) malloc(256 * 256 * sizeof(struct pointlayer *));\n\tint i;\n\tfor (i = 0; i < 256 * 256; i++) {\n\t\te->used[i] = e->pointlayers;\n\t}\n\n\tstruct graphics *g = (struct graphics *) malloc(sizeof(struct graphics));\n\tg->e = e;\n\tg->width = width;\n\tg->height = height;\n\n\treturn g;\n}\n\n\/\/ from mapnik-vector-tile\/src\/vector_tile_compression.hpp\nstatic inline int compress(std::string const& input, std::string & output)\n{\n\tz_stream deflate_s;\n\tdeflate_s.zalloc = Z_NULL;\n\tdeflate_s.zfree = Z_NULL;\n\tdeflate_s.opaque = Z_NULL;\n\tdeflate_s.avail_in = 0;\n\tdeflate_s.next_in = Z_NULL;\n\tdeflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);\n\tdeflate_s.next_in = (Bytef *)input.data();\n\tdeflate_s.avail_in = input.size();\n\tsize_t length = 0;\n\tdo {\n\t\tsize_t increase = input.size() \/ 2 + 1024;\n\t\toutput.resize(length + increase);\n\t\tdeflate_s.avail_out = increase;\n\t\tdeflate_s.next_out = (Bytef *)(output.data() + length);\n\t\tint ret = deflate(&deflate_s, Z_FINISH);\n\t\tif (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {\n\t\t\treturn -1;\n\t\t}\n\t\tlength += (increase - deflate_s.avail_out);\n\t} while (deflate_s.avail_out == 0);\n\tdeflateEnd(&deflate_s);\n\toutput.resize(length);\n\treturn 0;\n}\n\nstatic void op(env *e, int cmd, int x, int y);\n\nvoid out(struct graphics *gc, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask) {\n\tenv *e = gc->e;\n\tint i;\n\n\te->layer = e->tile.add_layers();\n\te->layer->set_name(\"lines\");\n\te->layer->set_version(1);\n\te->layer->set_extent(XMAX);\n\n\tstruct linelayer *l;\n\tfor (l = e->linelayers; l != NULL; l = l->next){\n\t\te->feature = e->layer->add_features();\n\t\te->feature->set_type(mapnik::vector::tile::LineString);\n\n\t\te->x = 0;\n\t\te->y = 0;\n\n\t\te->cmd_idx = -1;\n\t\te->cmd = -1;\n\t\te->length = 0;\n\n\t\tfor (i = 0; i < l->nlines; i++) {\n\t\t\t\/\/ printf(\"draw %d %d to %d %d\\n\", e->lines[i].x0, e->lines[i].y0, e->lines[i].x1, e->lines[i].y1);\n\n\t\t\tif (l->lines[i].x0 != e->x || l->lines[i].y0 != e->y || e->length == 0) {\n\t\t\t\top(e, MOVE_TO, l->lines[i].x0, l->lines[i].y0);\n\t\t\t}\n\n\t\t\top(e, LINE_TO, l->lines[i].x1, l->lines[i].y1);\n\t\t}\n\n\t\tif (e->cmd_idx >= 0) {\n\t\t\t\/\/printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\te->layer = e->tile.add_layers();\n\te->layer->set_name(\"points\");\n\te->layer->set_version(1);\n\te->layer->set_extent(XMAX);\n\n\tstruct pointlayer *p;\n\tfor (p = e->pointlayers; p != NULL; p = p->next) {\n\t\tif (p->npoints != 0) {\n\t\t\te->feature = e->layer->add_features();\n\t\t\te->feature->set_type(mapnik::vector::tile::LineString);\n\n\t\t\te->x = 0;\n\t\t\te->y = 0;\n\n\t\t\te->cmd_idx = -1;\n\t\t\te->cmd = -1;\n\t\t\te->length = 0;\n\n\t\t\tfor (i = 0; i < p->npoints; i++) {\n\t\t\t\top(e, MOVE_TO, p->points[i].x, p->points[i].y);\n\t\t\t\top(e, LINE_TO, p->points[i].x + 1, p->points[i].y);\n\t\t\t}\n\n\t\t\tif (e->cmd_idx >= 0) {\n\t\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tstd::string s;\n\te->tile.SerializeToString(&s);\n\n\tstd::string compressed;\n\tcompress(s, compressed);\n\n\tstd::cout << compressed;\n}\n\nstatic void op(env *e, int cmd, int x, int y) {\n\t\/\/ printf(\"%d %d,%d\\n\", cmd, x, y);\n\t\/\/ printf(\"from cmd %d to %d\\n\", e->cmd, cmd);\n\n\tif (cmd != e->cmd) {\n\t\tif (e->cmd_idx >= 0) {\n\t\t\t\/\/ printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t}\n\n\t\te->cmd = cmd;\n\t\te->length = 0;\n\t\te->cmd_idx = e->feature->geometry_size();\n\n\t\te->feature->add_geometry(0); \/\/ placeholder\n\t}\n\n\tif (cmd == MOVE_TO || cmd == LINE_TO) {\n\t\tint dx = x - e->x;\n\t\tint dy = y - e->y;\n\t\t\/\/ printf(\"new geom: %d %d\\n\", x, y);\n\n\t\te->feature->add_geometry((dx << 1) ^ (dx >> 31));\n\t\te->feature->add_geometry((dy << 1) ^ (dy >> 31));\n\t\t\n\t\te->x = x;\n\t\te->y = y;\n\t\te->length++;\n\t} else if (cmd == CLOSE_PATH) {\n\t\te->length++;\n\t}\n}\n\n\/\/ http:\/\/rosettacode.org\/wiki\/Bitmap\/Bresenham's_line_algorithm#C\nint lineused(struct linelayer *l, int x0, int y0, int x1, int y1) {\n\tint dx = abs(x1 - x0), sx = (x0 < x1) ? 1 : -1;\n\tint dy = abs(y1 - y0), sy = (y0 < y1) ? 1 : -1;\n\tint err = ((dx > dy) ? dx : -dy) \/ 2, e2;\n\n\twhile (1) {\n\t\tif (x0 == x1 && y0 == y1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (x0 >= 0 && y0 >=0 && x0 < 256 && y0 < 256) {\n\t\t\tif (l->used[y0 * 256 + x0]) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\te2 = err;\n\t\tif (e2 > -dx) {\n\t\t\terr -= dy;\n\t\t\tx0 += sx;\n\t\t}\n\t\tif (e2 < dy) {\n\t\t\terr += dx;\n\t\t\ty0 += sy;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n\/\/ http:\/\/rosettacode.org\/wiki\/Bitmap\/Bresenham's_line_algorithm#C\nvoid useline(struct linelayer *l, int x0, int y0, int x1, int y1) {\n\tint dx = abs(x1 - x0), sx = (x0 < x1) ? 1 : -1;\n\tint dy = abs(y1 - y0), sy = (y0 < y1) ? 1 : -1;\n\tint err = ((dx > dy) ? dx : -dy) \/ 2, e2;\n\n\twhile (1) {\n\t\tif (x0 == x1 && y0 == y1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (x0 >= 0 && y0 >=0 && x0 < 256 && y0 < 256) {\n\t\t\tl->used[y0 * 256 + x0] = 1;\n\t\t}\n\n\t\te2 = err;\n\t\tif (e2 > -dx) {\n\t\t\terr -= dy;\n\t\t\tx0 += sx;\n\t\t}\n\t\tif (e2 < dy) {\n\t\t\terr += dx;\n\t\t\ty0 += sy;\n\t\t}\n\t}\n}\n\nint drawClip(double x0, double y0, double x1, double y1, struct graphics *gc, double bright, double hue, int antialias, double thick, struct tilecontext *tc) {\n\tdouble mult = XMAX \/ gc->width;\n\tint accept = clip(&x0, &y0, &x1, &y1, 0, 0, XMAX \/ mult, YMAX \/ mult);\n\n\tif (accept) {\n\t\tint xx0 = x0 * mult;\n\t\tint yy0 = y0 * mult;\n\t\tint xx1 = x1 * mult;\n\t\tint yy1 = y1 * mult;\n\n\t\t\/\/ Guarding against rounding error\n\n\t\tif (xx0 < 0) {\n\t\t\txx0 = 0;\n\t\t}\n\t\tif (xx0 > XMAX - 1) {\n\t\t\txx0 = XMAX - 1;\n\t\t}\n\t\tif (yy0 < 0) {\n\t\t\tyy0 = 0;\n\t\t}\n\t\tif (yy0 > YMAX - 1) {\n\t\t\tyy0 = YMAX - 1;\n\t\t}\n\n\t\tif (xx1 < 0) {\n\t\t\txx1 = 0;\n\t\t}\n\t\tif (xx1 > XMAX - 1) {\n\t\t\txx1 = XMAX - 1;\n\t\t}\n\t\tif (yy1 < 0) {\n\t\t\tyy1 = 0;\n\t\t}\n\t\tif (yy1 > YMAX - 1) {\n\t\t\tyy1 = YMAX - 1;\n\t\t}\n\n\t\tenv *e = gc->e;\n\t\tstruct linelayer *l = e->linelayers;\n\n\t\tif (xx0 != xx1 || yy0 != yy1) {\n\t\t\twhile (l->nlines > MAX_POINTS || lineused(l, x0, y0, x1, y1)) {\n\t\t\t\tif (l->next == NULL) {\n\t\t\t\t\tl->next = new_linelayer();\n\t\t\t\t}\n\t\t\t\tl = l->next;\n\t\t\t}\n\n\t\t\tif (l->nlines + 1 >= l->nlalloc) {\n\t\t\t\tl->nlalloc *= 2;\n\t\t\t\tl->lines = (struct line *) realloc((void *) l->lines, l->nlalloc * sizeof(struct line));\n\t\t\t}\n\n\t\t\tuseline(l, x0, y0, x1, y1);\n\n\t\t\tl->lines[l->nlines].x0 = xx0;\n\t\t\tl->lines[l->nlines].y0 = yy0;\n\t\t\tl->lines[l->nlines].x1 = xx1;\n\t\t\tl->lines[l->nlines].y1 = yy1;\n\n\t\t\tl->nlines++;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid drawPixel(double x, double y, struct graphics *gc, double bright, double hue, struct tilecontext *tc) {\n\tx += .5;\n\ty += .5;\n\n\tdouble mult = XMAX \/ gc->width;\n\tint xx = x * mult;\n\tint yy = y * mult;\n\n\t\/\/ Guarding against rounding error\n\n\tif (xx < 0) {\n\t\txx = 0;\n\t}\n\tif (xx > XMAX - 1) {\n\t\txx = XMAX - 1;\n\t}\n\tif (yy < 0) {\n\t\tyy = 0;\n\t}\n\tif (yy > YMAX - 1) {\n\t\tyy = YMAX - 1;\n\t}\n\n\tenv *e = gc->e;\n\n\tint xu = x * 256 \/ gc->width;\n\tint yu = y * 256 \/ gc->height;\n\tif (xu < 0) {\n\t\txu = 0;\n\t}\n\tif (xu > 255) {\n\t\txu = 255;\n\t}\n\tif (yu < 0) {\n\t\tyu = 0;\n\t}\n\tif (yu > 255) {\n\t\tyu = 255;\n\t}\n\n\tstruct pointlayer *p = e->used[256 * yu + xu];\n\twhile (p->npoints >= MAX_POINTS) {\n\t\tif (p->next == NULL) {\n\t\t\tp->next = new_pointlayer();\n\t\t}\n\t\tp = p->next;\n\t}\n\tif (p->next == NULL) {\n\t\tp->next = new_pointlayer();\n\t}\n\te->used[256 * yu + xu] = p->next;\n\n\tif (p->npoints + 1 >= p->npalloc) {\n\t\tp->npalloc *= 2;\n\t\tp->points = (struct point *) realloc((void *) p->points, p->npalloc * sizeof(struct point));\n\t}\n\n\tp->points[p->npoints].x = xx;\n\tp->points[p->npoints].y = yy;\n\n\tp->npoints++;\n}\n\nvoid drawBrush(double x, double y, struct graphics *gc, double bright, double brush, double hue, int gaussian, struct tilecontext *tc) {\n\tdrawPixel(x - .5, y - .5, gc, bright, hue, tc);\n}\nClip a little beyond tile boundaries to keep joins out of sight.#include \n#include \n#include \n#include \n#include \"vector_tile.pb.h\"\n\n#define XMAX 4096\n#define YMAX 4096\n\nextern \"C\" {\n\t#include \"graphics.h\"\n\t#include \"clip.h\"\n}\n\nstruct line {\n\tint x0;\n\tint y0;\n\tint x1;\n\tint y1;\n};\n\nstruct point {\n\tint x;\n\tint y;\n};\n\n#define MAX_POINTS 10000\nstruct pointlayer {\n\tstruct point *points;\n\tint npoints;\n\tint npalloc;\n\n\tstruct pointlayer *next;\n};\n\nstruct linelayer {\n\tstruct line *lines;\n\tint nlines;\n\tint nlalloc;\n\tunsigned char *used;\n\n\tstruct linelayer *next;\n};\n\nclass env {\npublic:\n\tmapnik::vector::tile tile;\n\tmapnik::vector::tile_layer *layer;\n\tmapnik::vector::tile_feature *feature;\n\n\tint x;\n\tint y;\n\n\tint cmd_idx;\n\tint cmd;\n\tint length;\n\n\tstruct linelayer *linelayers;\n\n\tstruct pointlayer *pointlayers;\n\tstruct pointlayer **used;\n};\n\n#define MOVE_TO 1\n#define LINE_TO 2\n#define CLOSE_PATH 7\n#define CMD_BITS 3\n\nstruct graphics {\n\tint width;\n\tint height;\n\tenv *e;\n};\n\nstruct pointlayer *new_pointlayer() {\n\tstruct pointlayer *p = (struct pointlayer *) malloc(sizeof(struct pointlayer));\n\tp->npalloc = 1024;\n\tp->npoints = 0;\n\tp->points = (struct point *) malloc(p->npalloc * sizeof(struct point));\n\tp->next = NULL;\n\n\treturn p;\n}\n\nstruct linelayer *new_linelayer() {\n\tstruct linelayer *l = (struct linelayer *) malloc(sizeof(struct linelayer));\n\tl->nlalloc = 1024;\n\tl->nlines = 0;\n\tl->lines = (struct line *) malloc(l->nlalloc * sizeof(struct line));\n\tl->next = NULL;\n\tl->used = (unsigned char *) malloc(256 * 256 * sizeof(unsigned char));\n\n\treturn l;\n}\n\nstruct graphics *graphics_init(int width, int height) {\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\tenv *e = new env;\n\n\te->linelayers = new_linelayer();\n\te->pointlayers = new_pointlayer();\n\te->used = (struct pointlayer **) malloc(256 * 256 * sizeof(struct pointlayer *));\n\tint i;\n\tfor (i = 0; i < 256 * 256; i++) {\n\t\te->used[i] = e->pointlayers;\n\t}\n\n\tstruct graphics *g = (struct graphics *) malloc(sizeof(struct graphics));\n\tg->e = e;\n\tg->width = width;\n\tg->height = height;\n\n\treturn g;\n}\n\n\/\/ from mapnik-vector-tile\/src\/vector_tile_compression.hpp\nstatic inline int compress(std::string const& input, std::string & output)\n{\n\tz_stream deflate_s;\n\tdeflate_s.zalloc = Z_NULL;\n\tdeflate_s.zfree = Z_NULL;\n\tdeflate_s.opaque = Z_NULL;\n\tdeflate_s.avail_in = 0;\n\tdeflate_s.next_in = Z_NULL;\n\tdeflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);\n\tdeflate_s.next_in = (Bytef *)input.data();\n\tdeflate_s.avail_in = input.size();\n\tsize_t length = 0;\n\tdo {\n\t\tsize_t increase = input.size() \/ 2 + 1024;\n\t\toutput.resize(length + increase);\n\t\tdeflate_s.avail_out = increase;\n\t\tdeflate_s.next_out = (Bytef *)(output.data() + length);\n\t\tint ret = deflate(&deflate_s, Z_FINISH);\n\t\tif (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {\n\t\t\treturn -1;\n\t\t}\n\t\tlength += (increase - deflate_s.avail_out);\n\t} while (deflate_s.avail_out == 0);\n\tdeflateEnd(&deflate_s);\n\toutput.resize(length);\n\treturn 0;\n}\n\nstatic void op(env *e, int cmd, int x, int y);\n\nvoid out(struct graphics *gc, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask) {\n\tenv *e = gc->e;\n\tint i;\n\n\te->layer = e->tile.add_layers();\n\te->layer->set_name(\"lines\");\n\te->layer->set_version(1);\n\te->layer->set_extent(XMAX);\n\n\tstruct linelayer *l;\n\tfor (l = e->linelayers; l != NULL; l = l->next){\n\t\te->feature = e->layer->add_features();\n\t\te->feature->set_type(mapnik::vector::tile::LineString);\n\n\t\te->x = 0;\n\t\te->y = 0;\n\n\t\te->cmd_idx = -1;\n\t\te->cmd = -1;\n\t\te->length = 0;\n\n\t\tfor (i = 0; i < l->nlines; i++) {\n\t\t\t\/\/ printf(\"draw %d %d to %d %d\\n\", e->lines[i].x0, e->lines[i].y0, e->lines[i].x1, e->lines[i].y1);\n\n\t\t\tif (l->lines[i].x0 != e->x || l->lines[i].y0 != e->y || e->length == 0) {\n\t\t\t\top(e, MOVE_TO, l->lines[i].x0, l->lines[i].y0);\n\t\t\t}\n\n\t\t\top(e, LINE_TO, l->lines[i].x1, l->lines[i].y1);\n\t\t}\n\n\t\tif (e->cmd_idx >= 0) {\n\t\t\t\/\/printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\te->layer = e->tile.add_layers();\n\te->layer->set_name(\"points\");\n\te->layer->set_version(1);\n\te->layer->set_extent(XMAX);\n\n\tstruct pointlayer *p;\n\tfor (p = e->pointlayers; p != NULL; p = p->next) {\n\t\tif (p->npoints != 0) {\n\t\t\te->feature = e->layer->add_features();\n\t\t\te->feature->set_type(mapnik::vector::tile::LineString);\n\n\t\t\te->x = 0;\n\t\t\te->y = 0;\n\n\t\t\te->cmd_idx = -1;\n\t\t\te->cmd = -1;\n\t\t\te->length = 0;\n\n\t\t\tfor (i = 0; i < p->npoints; i++) {\n\t\t\t\top(e, MOVE_TO, p->points[i].x, p->points[i].y);\n\t\t\t\top(e, LINE_TO, p->points[i].x + 1, p->points[i].y);\n\t\t\t}\n\n\t\t\tif (e->cmd_idx >= 0) {\n\t\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tstd::string s;\n\te->tile.SerializeToString(&s);\n\n\tstd::string compressed;\n\tcompress(s, compressed);\n\n\tstd::cout << compressed;\n}\n\nstatic void op(env *e, int cmd, int x, int y) {\n\t\/\/ printf(\"%d %d,%d\\n\", cmd, x, y);\n\t\/\/ printf(\"from cmd %d to %d\\n\", e->cmd, cmd);\n\n\tif (cmd != e->cmd) {\n\t\tif (e->cmd_idx >= 0) {\n\t\t\t\/\/ printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t}\n\n\t\te->cmd = cmd;\n\t\te->length = 0;\n\t\te->cmd_idx = e->feature->geometry_size();\n\n\t\te->feature->add_geometry(0); \/\/ placeholder\n\t}\n\n\tif (cmd == MOVE_TO || cmd == LINE_TO) {\n\t\tint dx = x - e->x;\n\t\tint dy = y - e->y;\n\t\t\/\/ printf(\"new geom: %d %d\\n\", x, y);\n\n\t\te->feature->add_geometry((dx << 1) ^ (dx >> 31));\n\t\te->feature->add_geometry((dy << 1) ^ (dy >> 31));\n\t\t\n\t\te->x = x;\n\t\te->y = y;\n\t\te->length++;\n\t} else if (cmd == CLOSE_PATH) {\n\t\te->length++;\n\t}\n}\n\n\/\/ http:\/\/rosettacode.org\/wiki\/Bitmap\/Bresenham's_line_algorithm#C\nint lineused(struct linelayer *l, int x0, int y0, int x1, int y1) {\n\tint dx = abs(x1 - x0), sx = (x0 < x1) ? 1 : -1;\n\tint dy = abs(y1 - y0), sy = (y0 < y1) ? 1 : -1;\n\tint err = ((dx > dy) ? dx : -dy) \/ 2, e2;\n\n\twhile (1) {\n\t\tif (x0 == x1 && y0 == y1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (x0 >= 0 && y0 >=0 && x0 < 256 && y0 < 256) {\n\t\t\tif (l->used[y0 * 256 + x0]) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\te2 = err;\n\t\tif (e2 > -dx) {\n\t\t\terr -= dy;\n\t\t\tx0 += sx;\n\t\t}\n\t\tif (e2 < dy) {\n\t\t\terr += dx;\n\t\t\ty0 += sy;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n\/\/ http:\/\/rosettacode.org\/wiki\/Bitmap\/Bresenham's_line_algorithm#C\nvoid useline(struct linelayer *l, int x0, int y0, int x1, int y1) {\n\tint dx = abs(x1 - x0), sx = (x0 < x1) ? 1 : -1;\n\tint dy = abs(y1 - y0), sy = (y0 < y1) ? 1 : -1;\n\tint err = ((dx > dy) ? dx : -dy) \/ 2, e2;\n\n\twhile (1) {\n\t\tif (x0 == x1 && y0 == y1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (x0 >= 0 && y0 >=0 && x0 < 256 && y0 < 256) {\n\t\t\tl->used[y0 * 256 + x0] = 1;\n\t\t}\n\n\t\te2 = err;\n\t\tif (e2 > -dx) {\n\t\t\terr -= dy;\n\t\t\tx0 += sx;\n\t\t}\n\t\tif (e2 < dy) {\n\t\t\terr += dx;\n\t\t\ty0 += sy;\n\t\t}\n\t}\n}\n\nint drawClip(double x0, double y0, double x1, double y1, struct graphics *gc, double bright, double hue, int antialias, double thick, struct tilecontext *tc) {\n\tdouble mult = XMAX \/ gc->width;\n\tint accept = clip(&x0, &y0, &x1, &y1, -1, -1, XMAX \/ mult + 1, YMAX \/ mult + 1);\n\n\tif (accept) {\n\t\tint xx0 = x0 * mult;\n\t\tint yy0 = y0 * mult;\n\t\tint xx1 = x1 * mult;\n\t\tint yy1 = y1 * mult;\n\n\t\tenv *e = gc->e;\n\t\tstruct linelayer *l = e->linelayers;\n\n\t\tif (xx0 != xx1 || yy0 != yy1) {\n\t\t\twhile (l->nlines > MAX_POINTS || lineused(l, x0, y0, x1, y1)) {\n\t\t\t\tif (l->next == NULL) {\n\t\t\t\t\tl->next = new_linelayer();\n\t\t\t\t}\n\t\t\t\tl = l->next;\n\t\t\t}\n\n\t\t\tif (l->nlines + 1 >= l->nlalloc) {\n\t\t\t\tl->nlalloc *= 2;\n\t\t\t\tl->lines = (struct line *) realloc((void *) l->lines, l->nlalloc * sizeof(struct line));\n\t\t\t}\n\n\t\t\tuseline(l, x0, y0, x1, y1);\n\n\t\t\tl->lines[l->nlines].x0 = xx0;\n\t\t\tl->lines[l->nlines].y0 = yy0;\n\t\t\tl->lines[l->nlines].x1 = xx1;\n\t\t\tl->lines[l->nlines].y1 = yy1;\n\n\t\t\tl->nlines++;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid drawPixel(double x, double y, struct graphics *gc, double bright, double hue, struct tilecontext *tc) {\n\tx += .5;\n\ty += .5;\n\n\tdouble mult = XMAX \/ gc->width;\n\tint xx = x * mult;\n\tint yy = y * mult;\n\n\tenv *e = gc->e;\n\n\tint xu = x * 256 \/ gc->width;\n\tint yu = y * 256 \/ gc->height;\n\tif (xu < 0) {\n\t\txu = 0;\n\t}\n\tif (xu > 255) {\n\t\txu = 255;\n\t}\n\tif (yu < 0) {\n\t\tyu = 0;\n\t}\n\tif (yu > 255) {\n\t\tyu = 255;\n\t}\n\n\tstruct pointlayer *p = e->used[256 * yu + xu];\n\twhile (p->npoints >= MAX_POINTS) {\n\t\tif (p->next == NULL) {\n\t\t\tp->next = new_pointlayer();\n\t\t}\n\t\tp = p->next;\n\t}\n\tif (p->next == NULL) {\n\t\tp->next = new_pointlayer();\n\t}\n\te->used[256 * yu + xu] = p->next;\n\n\tif (p->npoints + 1 >= p->npalloc) {\n\t\tp->npalloc *= 2;\n\t\tp->points = (struct point *) realloc((void *) p->points, p->npalloc * sizeof(struct point));\n\t}\n\n\tp->points[p->npoints].x = xx;\n\tp->points[p->npoints].y = yy;\n\n\tp->npoints++;\n}\n\nvoid drawBrush(double x, double y, struct graphics *gc, double bright, double brush, double hue, int gaussian, struct tilecontext *tc) {\n\tdrawPixel(x - .5, y - .5, gc, bright, hue, tc);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"vector_tile.pb.h\"\n\n#define XMAX 4096\n#define YMAX 4096\n\nextern \"C\" {\n\t#include \"graphics.h\"\n\t#include \"clip.h\"\n}\n\nstruct line {\n\tint x0;\n\tint y0;\n\tint x1;\n\tint y1;\n};\n\nint linecmp(const void *v1, const void *v2) {\n\tconst struct line *l1 = (const struct line *) v1;\n\tconst struct line *l2 = (const struct line *) v2;\n\n\tif (l1->x0 != l2->x0) {\n\t\treturn l1->x0 - l2->x0;\n\t}\n\tif (l1->y0 != l2->y0) {\n\t\treturn l1->y0 - l2->y0;\n\t}\n\n\tif (l1->x1 != l2->x1) {\n\t\treturn l1->x1 - l2->x1;\n\t}\n\n\treturn l1->y1 - l2->y1;\n}\n\nint startcmp(const void *v1, const void *v2) {\n\tconst struct line *l1 = (const struct line *) v1;\n\tconst struct line *l2 = (const struct line *) v2;\n\n\tif (l1->x0 != l2->x0) {\n\t\treturn l1->x0 - l2->x0;\n\t}\n\n\treturn l1->y0 - l2->y0;\n}\n\nclass env {\npublic:\n\tmapnik::vector::tile tile;\n\tmapnik::vector::tile_layer *layer;\n\tmapnik::vector::tile_feature *feature;\n\n\tint x;\n\tint y;\n\n\tint cmd_idx;\n\tint cmd;\n\tint length;\n\n\tstruct line *lines;\n\tint nlines;\n\tint nlalloc;\n};\n\n#define MOVE_TO 1\n#define LINE_TO 2\n#define CLOSE_PATH 7\n#define CMD_BITS 3\n\ndouble *graphics_init() {\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\tenv *e = new env;\n\n\te->nlalloc = 1024;\n\te->nlines = 0;\n\te->lines = (struct line *) malloc(e->nlalloc * sizeof(struct line));\n\n\treturn (double *) e;\n}\n\n\/\/ from mapnik-vector-tile\/src\/vector_tile_compression.hpp\nstatic inline int compress(std::string const& input, std::string & output)\n{\n\tz_stream deflate_s;\n\tdeflate_s.zalloc = Z_NULL;\n\tdeflate_s.zfree = Z_NULL;\n\tdeflate_s.opaque = Z_NULL;\n\tdeflate_s.avail_in = 0;\n\tdeflate_s.next_in = Z_NULL;\n\tdeflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);\n\tdeflate_s.next_in = (Bytef *)input.data();\n\tdeflate_s.avail_in = input.size();\n\tsize_t length = 0;\n\tdo {\n\t\tsize_t increase = input.size() \/ 2 + 1024;\n\t\toutput.resize(length + increase);\n\t\tdeflate_s.avail_out = increase;\n\t\tdeflate_s.next_out = (Bytef *)(output.data() + length);\n\t\tint ret = deflate(&deflate_s, Z_FINISH);\n\t\tif (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {\n\t\t\treturn -1;\n\t\t}\n\t\tlength += (increase - deflate_s.avail_out);\n\t} while (deflate_s.avail_out == 0);\n\tdeflateEnd(&deflate_s);\n\toutput.resize(length);\n\treturn 0;\n}\n\nstatic void op(env *e, int cmd, int x, int y);\n\nvoid out(double *src, double *cx, double *cy, int width, int height, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask) {\n\tenv *e = (env *) src;\n\n\tqsort(e->lines, e->nlines, sizeof(struct line), linecmp);\n\n\te->layer = e->tile.add_layers();\n\te->layer->set_name(\"world\");\n\te->layer->set_version(1);\n\te->layer->set_extent(4096);\n\n\te->feature = e->layer->add_features();\n\te->feature->set_type(mapnik::vector::tile::LineString);\n\n\te->x = 0;\n\te->y = 0;\n\n\te->cmd_idx = -1;\n\te->cmd = -1;\n\te->length = 0;\n\n\tint i;\n\tfor (i = 0; i < e->nlines; i++) {\n\t\t\/\/ printf(\"draw %d %d to %d %d\\n\", e->lines[i].x0, e->lines[i].y0, e->lines[i].x1, e->lines[i].y1);\n\n\t\tif (e->lines[i].x0 != e->x || e->lines[i].y0 != e->y || e->length == 0) {\n\t\t\top(e, MOVE_TO, e->lines[i].x0, e->lines[i].y0);\n\t\t}\n\n\t\top(e, LINE_TO, e->lines[i].x1, e->lines[i].y1);\n\n\t\tstruct line l2;\n\t\tl2.x0 = e->lines[i].x1;\n\t\tl2.y0 = e->lines[i].y1;\n\n\t\twhile (i < e->nlines) {\n\t\t\t\/\/ printf(\"looking for %d,%d\\n\", l2.x0, l2.y0);\n\t\t\t\/\/ printf(\"searching %d\\n\", e->nlines - i);\n\n\t\t\tstruct line *next = (struct line *) bsearch(&l2, e->lines + i, e->nlines - i,\n\t\t\t\t\t\tsizeof(struct line), startcmp);\n\n\t\t\tif (next != NULL) {\n\t\t\t\t\/\/ printf(\"found %d,%d to %d,%d at %d\\n\", next->x0, next->y0, next->x1, next->y1, (int) (next - e->lines));\n\n\t\t\t\top(e, LINE_TO, next->x1, next->y1);\n\n\t\t\t\tl2.x0 = next->x1;\n\t\t\t\tl2.y0 = next->y1;\n\n\t\t\t\tint n = next - e->lines;\n\n\t\t\t\tmemmove(e->lines + n, e->lines + n + 1, (e->nlines - (n + 1)) * sizeof(struct line));\n\t\t\t\te->nlines--;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (e->cmd_idx >= 0) {\n\t\t\/\/printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t(e->length << CMD_BITS) |\n\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t}\n\n\tstd::string s;\n\te->tile.SerializeToString(&s);\n\n\tstd::string compressed;\n\tcompress(s, compressed);\n\n\tstd::cout << compressed;\n}\n\nstatic void op(env *e, int cmd, int x, int y) {\n\t\/\/ printf(\"%d %d,%d\\n\", cmd, x, y);\n\t\/\/ printf(\"from cmd %d to %d\\n\", e->cmd, cmd);\n\n\tif (cmd != e->cmd) {\n\t\tif (e->cmd_idx >= 0) {\n\t\t\t\/\/ printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t}\n\n\t\te->cmd = cmd;\n\t\te->length = 0;\n\t\te->cmd_idx = e->feature->geometry_size();\n\n\t\te->feature->add_geometry(0); \/\/ placeholder\n\t}\n\n\tif (cmd == MOVE_TO || cmd == LINE_TO) {\n\t\tint dx = x - e->x;\n\t\tint dy = y - e->y;\n\t\t\/\/ printf(\"new geom: %d %d\\n\", x, y);\n\n\t\te->feature->add_geometry((dx << 1) ^ (dx >> 31));\n\t\te->feature->add_geometry((dy << 1) ^ (dy >> 31));\n\t\t\n\t\te->x = x;\n\t\te->y = y;\n\t\te->length++;\n\t} else if (cmd == CLOSE_PATH) {\n\t\te->length++;\n\t}\n}\n\nint drawClip(double x0, double y0, double x1, double y1, double *image, double *cx, double *cy, double bright, double hue, int antialias, double thick) {\n\tint accept = clip(&x0, &y0, &x1, &y1, 0, 0, XMAX \/ 16.0, YMAX \/ 16.0);\n\n\tif (accept) {\n\t\tint xx0 = x0 * 16;\n\t\tint yy0 = y0 * 16;\n\t\tint xx1 = x1 * 16;\n\t\tint yy1 = y1 * 16;\n\n\t\t\/\/ Guarding against rounding error\n\n\t\tif (xx0 < 0) {\n\t\t\txx0 = 0;\n\t\t}\n\t\tif (xx0 > 4095) {\n\t\t\txx0 = 4095;\n\t\t}\n\t\tif (yy0 < 0) {\n\t\t\tyy0 = 0;\n\t\t}\n\t\tif (yy0 > 4095) {\n\t\t\tyy0 = 4095;\n\t\t}\n\n\t\tif (xx1 < 0) {\n\t\t\txx1 = 0;\n\t\t}\n\t\tif (xx1 > 4095) {\n\t\t\txx1 = 4095;\n\t\t}\n\t\tif (yy1 < 0) {\n\t\t\tyy1 = 0;\n\t\t}\n\t\tif (yy1 > 4095) {\n\t\t\tyy1 = 4095;\n\t\t}\n\n\t\tenv *e = (env *) image;\n\n\t\tif (xx0 != xx1 || yy0 != yy1) {\n\t\t\tif (e->nlines + 1 >= e->nlalloc) {\n\t\t\t\te->nlalloc *= 2;\n\t\t\t\te->lines = (struct line *) realloc((void *) e->lines, e->nlalloc * sizeof(struct line));\n\t\t\t}\n\n\t\t\te->lines[e->nlines].x0 = xx0;\n\t\t\te->lines[e->nlines].y0 = yy0;\n\t\t\te->lines[e->nlines].x1 = xx1;\n\t\t\te->lines[e->nlines].y1 = yy1;\n\n\t\t\te->nlines++;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid drawPixel(double x, double y, double *image, double *cx, double *cy, double bright, double hue) {\n\n}\n\nvoid drawBrush(double x, double y, double *image, double *cx, double *cy, double bright, double brush, double hue) {\n\n}\nTurn off chaining.#include \n#include \n#include \n#include \n#include \"vector_tile.pb.h\"\n\n#define XMAX 4096\n#define YMAX 4096\n\nextern \"C\" {\n\t#include \"graphics.h\"\n\t#include \"clip.h\"\n}\n\nstruct line {\n\tint x0;\n\tint y0;\n\tint x1;\n\tint y1;\n};\n\nint linecmp(const void *v1, const void *v2) {\n\tconst struct line *l1 = (const struct line *) v1;\n\tconst struct line *l2 = (const struct line *) v2;\n\n\tif (l1->x0 != l2->x0) {\n\t\treturn l1->x0 - l2->x0;\n\t}\n\tif (l1->y0 != l2->y0) {\n\t\treturn l1->y0 - l2->y0;\n\t}\n\n\tif (l1->x1 != l2->x1) {\n\t\treturn l1->x1 - l2->x1;\n\t}\n\n\treturn l1->y1 - l2->y1;\n}\n\nint startcmp(const void *v1, const void *v2) {\n\tconst struct line *l1 = (const struct line *) v1;\n\tconst struct line *l2 = (const struct line *) v2;\n\n\tif (l1->x0 != l2->x0) {\n\t\treturn l1->x0 - l2->x0;\n\t}\n\n\treturn l1->y0 - l2->y0;\n}\n\nclass env {\npublic:\n\tmapnik::vector::tile tile;\n\tmapnik::vector::tile_layer *layer;\n\tmapnik::vector::tile_feature *feature;\n\n\tint x;\n\tint y;\n\n\tint cmd_idx;\n\tint cmd;\n\tint length;\n\n\tstruct line *lines;\n\tint nlines;\n\tint nlalloc;\n};\n\n#define MOVE_TO 1\n#define LINE_TO 2\n#define CLOSE_PATH 7\n#define CMD_BITS 3\n\ndouble *graphics_init() {\n\tGOOGLE_PROTOBUF_VERIFY_VERSION;\n\n\tenv *e = new env;\n\n\te->nlalloc = 1024;\n\te->nlines = 0;\n\te->lines = (struct line *) malloc(e->nlalloc * sizeof(struct line));\n\n\treturn (double *) e;\n}\n\n\/\/ from mapnik-vector-tile\/src\/vector_tile_compression.hpp\nstatic inline int compress(std::string const& input, std::string & output)\n{\n\tz_stream deflate_s;\n\tdeflate_s.zalloc = Z_NULL;\n\tdeflate_s.zfree = Z_NULL;\n\tdeflate_s.opaque = Z_NULL;\n\tdeflate_s.avail_in = 0;\n\tdeflate_s.next_in = Z_NULL;\n\tdeflateInit(&deflate_s, Z_DEFAULT_COMPRESSION);\n\tdeflate_s.next_in = (Bytef *)input.data();\n\tdeflate_s.avail_in = input.size();\n\tsize_t length = 0;\n\tdo {\n\t\tsize_t increase = input.size() \/ 2 + 1024;\n\t\toutput.resize(length + increase);\n\t\tdeflate_s.avail_out = increase;\n\t\tdeflate_s.next_out = (Bytef *)(output.data() + length);\n\t\tint ret = deflate(&deflate_s, Z_FINISH);\n\t\tif (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) {\n\t\t\treturn -1;\n\t\t}\n\t\tlength += (increase - deflate_s.avail_out);\n\t} while (deflate_s.avail_out == 0);\n\tdeflateEnd(&deflate_s);\n\toutput.resize(length);\n\treturn 0;\n}\n\nstatic void op(env *e, int cmd, int x, int y);\n\nvoid out(double *src, double *cx, double *cy, int width, int height, int transparency, double gamma, int invert, int color, int color2, int saturate, int mask) {\n\tenv *e = (env *) src;\n\n#ifdef CHAIN\n\tqsort(e->lines, e->nlines, sizeof(struct line), linecmp);\n#endif\n\n\te->layer = e->tile.add_layers();\n\te->layer->set_name(\"world\");\n\te->layer->set_version(1);\n\te->layer->set_extent(4096);\n\n\te->feature = e->layer->add_features();\n\te->feature->set_type(mapnik::vector::tile::LineString);\n\n\te->x = 0;\n\te->y = 0;\n\n\te->cmd_idx = -1;\n\te->cmd = -1;\n\te->length = 0;\n\n\tint i;\n\tfor (i = 0; i < e->nlines; i++) {\n\t\t\/\/ printf(\"draw %d %d to %d %d\\n\", e->lines[i].x0, e->lines[i].y0, e->lines[i].x1, e->lines[i].y1);\n\n\t\tif (e->lines[i].x0 != e->x || e->lines[i].y0 != e->y || e->length == 0) {\n\t\t\top(e, MOVE_TO, e->lines[i].x0, e->lines[i].y0);\n\t\t}\n\n\t\top(e, LINE_TO, e->lines[i].x1, e->lines[i].y1);\n\n#ifdef CHAIN\n\t\tstruct line l2;\n\t\tl2.x0 = e->lines[i].x1;\n\t\tl2.y0 = e->lines[i].y1;\n\n\t\twhile (i < e->nlines) {\n\t\t\t\/\/ printf(\"looking for %d,%d\\n\", l2.x0, l2.y0);\n\t\t\t\/\/ printf(\"searching %d\\n\", e->nlines - i);\n\n\t\t\tstruct line *next = (struct line *) bsearch(&l2, e->lines + i, e->nlines - i,\n\t\t\t\t\t\tsizeof(struct line), startcmp);\n\n\t\t\tif (next != NULL) {\n\t\t\t\t\/\/ printf(\"found %d,%d to %d,%d at %d\\n\", next->x0, next->y0, next->x1, next->y1, (int) (next - e->lines));\n\n\t\t\t\top(e, LINE_TO, next->x1, next->y1);\n\n\t\t\t\tl2.x0 = next->x1;\n\t\t\t\tl2.y0 = next->y1;\n\n\t\t\t\tint n = next - e->lines;\n\n\t\t\t\tmemmove(e->lines + n, e->lines + n + 1, (e->nlines - (n + 1)) * sizeof(struct line));\n\t\t\t\te->nlines--;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n#endif\n\t}\n\n\tif (e->cmd_idx >= 0) {\n\t\t\/\/printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t(e->length << CMD_BITS) |\n\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t}\n\n\tstd::string s;\n\te->tile.SerializeToString(&s);\n\n\tstd::string compressed;\n\tcompress(s, compressed);\n\n\tstd::cout << compressed;\n}\n\nstatic void op(env *e, int cmd, int x, int y) {\n\t\/\/ printf(\"%d %d,%d\\n\", cmd, x, y);\n\t\/\/ printf(\"from cmd %d to %d\\n\", e->cmd, cmd);\n\n\tif (cmd != e->cmd) {\n\t\tif (e->cmd_idx >= 0) {\n\t\t\t\/\/ printf(\"old command: %d %d\\n\", e->cmd, e->length);\n\t\t\te->feature->set_geometry(e->cmd_idx, \n\t\t\t\t(e->length << CMD_BITS) |\n\t\t\t\t(e->cmd & ((1 << CMD_BITS) - 1)));\n\t\t}\n\n\t\te->cmd = cmd;\n\t\te->length = 0;\n\t\te->cmd_idx = e->feature->geometry_size();\n\n\t\te->feature->add_geometry(0); \/\/ placeholder\n\t}\n\n\tif (cmd == MOVE_TO || cmd == LINE_TO) {\n\t\tint dx = x - e->x;\n\t\tint dy = y - e->y;\n\t\t\/\/ printf(\"new geom: %d %d\\n\", x, y);\n\n\t\te->feature->add_geometry((dx << 1) ^ (dx >> 31));\n\t\te->feature->add_geometry((dy << 1) ^ (dy >> 31));\n\t\t\n\t\te->x = x;\n\t\te->y = y;\n\t\te->length++;\n\t} else if (cmd == CLOSE_PATH) {\n\t\te->length++;\n\t}\n}\n\nint drawClip(double x0, double y0, double x1, double y1, double *image, double *cx, double *cy, double bright, double hue, int antialias, double thick) {\n\tint accept = clip(&x0, &y0, &x1, &y1, 0, 0, XMAX \/ 16.0, YMAX \/ 16.0);\n\n\tif (accept) {\n\t\tint xx0 = x0 * 16;\n\t\tint yy0 = y0 * 16;\n\t\tint xx1 = x1 * 16;\n\t\tint yy1 = y1 * 16;\n\n\t\t\/\/ Guarding against rounding error\n\n\t\tif (xx0 < 0) {\n\t\t\txx0 = 0;\n\t\t}\n\t\tif (xx0 > 4095) {\n\t\t\txx0 = 4095;\n\t\t}\n\t\tif (yy0 < 0) {\n\t\t\tyy0 = 0;\n\t\t}\n\t\tif (yy0 > 4095) {\n\t\t\tyy0 = 4095;\n\t\t}\n\n\t\tif (xx1 < 0) {\n\t\t\txx1 = 0;\n\t\t}\n\t\tif (xx1 > 4095) {\n\t\t\txx1 = 4095;\n\t\t}\n\t\tif (yy1 < 0) {\n\t\t\tyy1 = 0;\n\t\t}\n\t\tif (yy1 > 4095) {\n\t\t\tyy1 = 4095;\n\t\t}\n\n\t\tenv *e = (env *) image;\n\n\t\tif (xx0 != xx1 || yy0 != yy1) {\n\t\t\tif (e->nlines + 1 >= e->nlalloc) {\n\t\t\t\te->nlalloc *= 2;\n\t\t\t\te->lines = (struct line *) realloc((void *) e->lines, e->nlalloc * sizeof(struct line));\n\t\t\t}\n\n\t\t\te->lines[e->nlines].x0 = xx0;\n\t\t\te->lines[e->nlines].y0 = yy0;\n\t\t\te->lines[e->nlines].x1 = xx1;\n\t\t\te->lines[e->nlines].y1 = yy1;\n\n\t\t\te->nlines++;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid drawPixel(double x, double y, double *image, double *cx, double *cy, double bright, double hue) {\n\n}\n\nvoid drawBrush(double x, double y, double *image, double *cx, double *cy, double bright, double brush, double hue) {\n\n}\n<|endoftext|>"} {"text":"\/\/ SciTE - Scintilla based Text Editor\n\/** @file StyleDefinition.cxx\n ** Implementation of style aggregate.\n **\/\n\/\/ Copyright 2013 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"Scintilla.h\"\n\n#include \"GUI.h\"\n#include \"SString.h\"\n#include \"StringHelpers.h\"\n#include \"StyleDefinition.h\"\n\nStyleDefinition::StyleDefinition(const char *definition) :\n\t\tsizeFractional(10.0), size(10), fore(\"#000000\"), back(\"#FFFFFF\"),\n\t\tweight(SC_WEIGHT_NORMAL), italics(false), eolfilled(false), underlined(false),\n\t\tcaseForce(SC_CASE_MIXED),\n\t\tvisible(true), changeable(true),\n\t\tspecified(sdNone) {\n\tParseStyleDefinition(definition);\n}\n\nbool StyleDefinition::ParseStyleDefinition(const char *definition) {\n\tif (definition == NULL || *definition == '\\0') {\n\t\treturn false;\n\t}\n\tchar *val = StringDup(definition);\n\tchar *opt = val;\n\twhile (opt) {\n\t\t\/\/ Find attribute separator\n\t\tchar *cpComma = strchr(opt, ',');\n\t\tif (cpComma) {\n\t\t\t\/\/ If found, we terminate the current attribute (opt) string\n\t\t\t*cpComma = '\\0';\n\t\t}\n\t\t\/\/ Find attribute name\/value separator\n\t\tchar *colon = strchr(opt, ':');\n\t\tif (colon) {\n\t\t\t\/\/ If found, we terminate the current attribute name and point on the value\n\t\t\t*colon++ = '\\0';\n\t\t}\n\t\tif (0 == strcmp(opt, \"italics\")) {\n\t\t\tspecified = static_cast(specified | sdItalics);\n\t\t\titalics = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notitalics\")) {\n\t\t\tspecified = static_cast(specified | sdItalics);\n\t\t\titalics = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"bold\")) {\n\t\t\tspecified = static_cast(specified | sdWeight);\n\t\t\tweight = SC_WEIGHT_BOLD;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notbold\")) {\n\t\t\tspecified = static_cast(specified | sdWeight);\n\t\t\tweight = SC_WEIGHT_NORMAL;\n\t\t}\n\t\tif ((0 == strcmp(opt, \"weight\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdWeight);\n\t\t\tweight = atoi(colon);\n\t\t}\n\t\tif ((0 == strcmp(opt, \"font\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdFont);\n\t\t\tfont = colon;\n\t\t\tstd::replace(font.begin(), font.end(), '|', ',');\n\t\t}\n\t\tif ((0 == strcmp(opt, \"fore\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdFore);\n\t\t\tfore = colon;\n\t\t}\n\t\tif ((0 == strcmp(opt, \"back\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdBack);\n\t\t\tback = colon;\n\t\t}\n\t\tif ((0 == strcmp(opt, \"size\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdSize);\n\t\t\tsizeFractional = static_cast(atof(colon));\n\t\t\tsize = static_cast(sizeFractional);\n\t\t}\n\t\tif (0 == strcmp(opt, \"eolfilled\")) {\n\t\t\tspecified = static_cast(specified | sdEOLFilled);\n\t\t\teolfilled = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"noteolfilled\")) {\n\t\t\tspecified = static_cast(specified | sdEOLFilled);\n\t\t\teolfilled = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"underlined\")) {\n\t\t\tspecified = static_cast(specified | sdUnderlined);\n\t\t\tunderlined = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notunderlined\")) {\n\t\t\tspecified = static_cast(specified | sdUnderlined);\n\t\t\tunderlined = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"case\")) {\n\t\t\tspecified = static_cast(specified | sdCaseForce);\n\t\t\tcaseForce = SC_CASE_MIXED;\n\t\t\tif (colon) {\n\t\t\t\tif (*colon == 'u')\n\t\t\t\t\tcaseForce = SC_CASE_UPPER;\n\t\t\t\telse if (*colon == 'l')\n\t\t\t\t\tcaseForce = SC_CASE_LOWER;\n\t\t\t}\n\t\t}\n\t\tif (0 == strcmp(opt, \"visible\")) {\n\t\t\tspecified = static_cast(specified | sdVisible);\n\t\t\tvisible = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notvisible\")) {\n\t\t\tspecified = static_cast(specified | sdVisible);\n\t\t\tvisible = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"changeable\")) {\n\t\t\tspecified = static_cast(specified | sdChangeable);\n\t\t\tchangeable = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notchangeable\")) {\n\t\t\tspecified = static_cast(specified | sdChangeable);\n\t\t\tchangeable = false;\n\t\t}\n\t\tif (cpComma)\n\t\t\topt = cpComma + 1;\n\t\telse\n\t\t\topt = 0;\n\t}\n\tdelete []val;\n\treturn true;\n}\n\nlong StyleDefinition::ForeAsLong() const {\n\treturn ColourFromString(fore);\n}\n\nlong StyleDefinition::BackAsLong() const {\n\treturn ColourFromString(back);\n}\n\nint StyleDefinition::FractionalSize() const {\n\treturn static_cast(sizeFractional * SC_FONT_SIZE_MULTIPLIER);\n}\n\nbool StyleDefinition::IsBold() const {\n\treturn weight > SC_WEIGHT_NORMAL;\n}\n\nint IntFromHexDigit(int ch) {\n\tif ((ch >= '0') && (ch <= '9')) {\n\t\treturn ch - '0';\n\t} else if (ch >= 'A' && ch <= 'F') {\n\t\treturn ch - 'A' + 10;\n\t} else if (ch >= 'a' && ch <= 'f') {\n\t\treturn ch - 'a' + 10;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nint IntFromHexByte(const char *hexByte) {\n\treturn IntFromHexDigit(hexByte[0]) * 16 + IntFromHexDigit(hexByte[1]);\n}\n\nColour ColourFromString(const std::string &s) {\n\tif (s.length()) {\n\t\tint r = IntFromHexByte(s.c_str() + 1);\n\t\tint g = IntFromHexByte(s.c_str() + 3);\n\t\tint b = IntFromHexByte(s.c_str() + 5);\n\t\treturn ColourRGB(r, g, b);\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nIndicatorDefinition::IndicatorDefinition(const char *definition) :\n\tstyle(INDIC_PLAIN), colour(0), fillAlpha(30), outlineAlpha(50), under(false) {\n\tParseIndicatorDefinition(definition);\n}\n\nbool IndicatorDefinition::ParseIndicatorDefinition(const char *definition) {\n\tif (definition == NULL || *definition == '\\0') {\n\t\treturn false;\n\t}\n\tstruct {\n\t\tconst char *name;\n\t\tint value;\n\t} indicStyleNames[] = {\n\t\t{ \"plain\", INDIC_PLAIN },\n\t\t{ \"squiggle\", INDIC_SQUIGGLE },\n\t\t{ \"tt\", INDIC_TT },\n\t\t{ \"diagonal\", INDIC_DIAGONAL },\n\t\t{ \"strike\", INDIC_STRIKE },\n\t\t{ \"hidden\", INDIC_HIDDEN },\n\t\t{ \"box\", INDIC_BOX },\n\t\t{ \"roundbox\", INDIC_ROUNDBOX },\n\t\t{ \"straightbox\", INDIC_STRAIGHTBOX },\n\t\t{ \"dash\", INDIC_DASH },\n\t\t{ \"dots\", INDIC_DOTS },\n\t\t{ \"squigglelow\", INDIC_SQUIGGLELOW },\n\t\t{ \"dotbox\", INDIC_DOTBOX },\n\t\t{ \"squigglepixmap\", INDIC_SQUIGGLEPIXMAP },\n\t\t{ \"compositionthick\", INDIC_COMPOSITIONTHICK },\n\t};\n\n\tstd::string val(definition);\n\tLowerCaseAZ(val);\n\tchar *opt = &val[0];\n\twhile (opt) {\n\t\t\/\/ Find attribute separator\n\t\tchar *cpComma = strchr(opt, ',');\n\t\tif (cpComma) {\n\t\t\t\/\/ If found, we terminate the current attribute (opt) string\n\t\t\t*cpComma = '\\0';\n\t\t}\n\t\t\/\/ Find attribute name\/value separator\n\t\tchar *colon = strchr(opt, ':');\n\t\tif (colon) {\n\t\t\t\/\/ If found, we terminate the current attribute name and point on the value\n\t\t\t*colon++ = '\\0';\n\t\t}\n\t\tif (colon && (0 == strcmp(opt, \"style\"))) {\n\t\t\tbool found = false;\n\t\t\tfor (size_t i=0;iUse std::vector to encapsulate definition and avoid possibility of leak.\/\/ SciTE - Scintilla based Text Editor\n\/** @file StyleDefinition.cxx\n ** Implementation of style aggregate.\n **\/\n\/\/ Copyright 2013 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"Scintilla.h\"\n\n#include \"GUI.h\"\n#include \"SString.h\"\n#include \"StringHelpers.h\"\n#include \"StyleDefinition.h\"\n\nStyleDefinition::StyleDefinition(const char *definition) :\n\t\tsizeFractional(10.0), size(10), fore(\"#000000\"), back(\"#FFFFFF\"),\n\t\tweight(SC_WEIGHT_NORMAL), italics(false), eolfilled(false), underlined(false),\n\t\tcaseForce(SC_CASE_MIXED),\n\t\tvisible(true), changeable(true),\n\t\tspecified(sdNone) {\n\tParseStyleDefinition(definition);\n}\n\nbool StyleDefinition::ParseStyleDefinition(const char *definition) {\n\tif (definition == NULL || *definition == '\\0') {\n\t\treturn false;\n\t}\n\tstd::vector valHolder(definition, definition + strlen(definition)+1);\n\tchar *val = &valHolder[0];\n\tchar *opt = val;\n\twhile (opt) {\n\t\t\/\/ Find attribute separator\n\t\tchar *cpComma = strchr(opt, ',');\n\t\tif (cpComma) {\n\t\t\t\/\/ If found, we terminate the current attribute (opt) string\n\t\t\t*cpComma = '\\0';\n\t\t}\n\t\t\/\/ Find attribute name\/value separator\n\t\tchar *colon = strchr(opt, ':');\n\t\tif (colon) {\n\t\t\t\/\/ If found, we terminate the current attribute name and point on the value\n\t\t\t*colon++ = '\\0';\n\t\t}\n\t\tif (0 == strcmp(opt, \"italics\")) {\n\t\t\tspecified = static_cast(specified | sdItalics);\n\t\t\titalics = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notitalics\")) {\n\t\t\tspecified = static_cast(specified | sdItalics);\n\t\t\titalics = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"bold\")) {\n\t\t\tspecified = static_cast(specified | sdWeight);\n\t\t\tweight = SC_WEIGHT_BOLD;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notbold\")) {\n\t\t\tspecified = static_cast(specified | sdWeight);\n\t\t\tweight = SC_WEIGHT_NORMAL;\n\t\t}\n\t\tif ((0 == strcmp(opt, \"weight\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdWeight);\n\t\t\tweight = atoi(colon);\n\t\t}\n\t\tif ((0 == strcmp(opt, \"font\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdFont);\n\t\t\tfont = colon;\n\t\t\tstd::replace(font.begin(), font.end(), '|', ',');\n\t\t}\n\t\tif ((0 == strcmp(opt, \"fore\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdFore);\n\t\t\tfore = colon;\n\t\t}\n\t\tif ((0 == strcmp(opt, \"back\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdBack);\n\t\t\tback = colon;\n\t\t}\n\t\tif ((0 == strcmp(opt, \"size\")) && colon) {\n\t\t\tspecified = static_cast(specified | sdSize);\n\t\t\tsizeFractional = static_cast(atof(colon));\n\t\t\tsize = static_cast(sizeFractional);\n\t\t}\n\t\tif (0 == strcmp(opt, \"eolfilled\")) {\n\t\t\tspecified = static_cast(specified | sdEOLFilled);\n\t\t\teolfilled = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"noteolfilled\")) {\n\t\t\tspecified = static_cast(specified | sdEOLFilled);\n\t\t\teolfilled = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"underlined\")) {\n\t\t\tspecified = static_cast(specified | sdUnderlined);\n\t\t\tunderlined = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notunderlined\")) {\n\t\t\tspecified = static_cast(specified | sdUnderlined);\n\t\t\tunderlined = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"case\")) {\n\t\t\tspecified = static_cast(specified | sdCaseForce);\n\t\t\tcaseForce = SC_CASE_MIXED;\n\t\t\tif (colon) {\n\t\t\t\tif (*colon == 'u')\n\t\t\t\t\tcaseForce = SC_CASE_UPPER;\n\t\t\t\telse if (*colon == 'l')\n\t\t\t\t\tcaseForce = SC_CASE_LOWER;\n\t\t\t}\n\t\t}\n\t\tif (0 == strcmp(opt, \"visible\")) {\n\t\t\tspecified = static_cast(specified | sdVisible);\n\t\t\tvisible = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notvisible\")) {\n\t\t\tspecified = static_cast(specified | sdVisible);\n\t\t\tvisible = false;\n\t\t}\n\t\tif (0 == strcmp(opt, \"changeable\")) {\n\t\t\tspecified = static_cast(specified | sdChangeable);\n\t\t\tchangeable = true;\n\t\t}\n\t\tif (0 == strcmp(opt, \"notchangeable\")) {\n\t\t\tspecified = static_cast(specified | sdChangeable);\n\t\t\tchangeable = false;\n\t\t}\n\t\tif (cpComma)\n\t\t\topt = cpComma + 1;\n\t\telse\n\t\t\topt = 0;\n\t}\n\treturn true;\n}\n\nlong StyleDefinition::ForeAsLong() const {\n\treturn ColourFromString(fore);\n}\n\nlong StyleDefinition::BackAsLong() const {\n\treturn ColourFromString(back);\n}\n\nint StyleDefinition::FractionalSize() const {\n\treturn static_cast(sizeFractional * SC_FONT_SIZE_MULTIPLIER);\n}\n\nbool StyleDefinition::IsBold() const {\n\treturn weight > SC_WEIGHT_NORMAL;\n}\n\nint IntFromHexDigit(int ch) {\n\tif ((ch >= '0') && (ch <= '9')) {\n\t\treturn ch - '0';\n\t} else if (ch >= 'A' && ch <= 'F') {\n\t\treturn ch - 'A' + 10;\n\t} else if (ch >= 'a' && ch <= 'f') {\n\t\treturn ch - 'a' + 10;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nint IntFromHexByte(const char *hexByte) {\n\treturn IntFromHexDigit(hexByte[0]) * 16 + IntFromHexDigit(hexByte[1]);\n}\n\nColour ColourFromString(const std::string &s) {\n\tif (s.length()) {\n\t\tint r = IntFromHexByte(s.c_str() + 1);\n\t\tint g = IntFromHexByte(s.c_str() + 3);\n\t\tint b = IntFromHexByte(s.c_str() + 5);\n\t\treturn ColourRGB(r, g, b);\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nIndicatorDefinition::IndicatorDefinition(const char *definition) :\n\tstyle(INDIC_PLAIN), colour(0), fillAlpha(30), outlineAlpha(50), under(false) {\n\tParseIndicatorDefinition(definition);\n}\n\nbool IndicatorDefinition::ParseIndicatorDefinition(const char *definition) {\n\tif (definition == NULL || *definition == '\\0') {\n\t\treturn false;\n\t}\n\tstruct {\n\t\tconst char *name;\n\t\tint value;\n\t} indicStyleNames[] = {\n\t\t{ \"plain\", INDIC_PLAIN },\n\t\t{ \"squiggle\", INDIC_SQUIGGLE },\n\t\t{ \"tt\", INDIC_TT },\n\t\t{ \"diagonal\", INDIC_DIAGONAL },\n\t\t{ \"strike\", INDIC_STRIKE },\n\t\t{ \"hidden\", INDIC_HIDDEN },\n\t\t{ \"box\", INDIC_BOX },\n\t\t{ \"roundbox\", INDIC_ROUNDBOX },\n\t\t{ \"straightbox\", INDIC_STRAIGHTBOX },\n\t\t{ \"dash\", INDIC_DASH },\n\t\t{ \"dots\", INDIC_DOTS },\n\t\t{ \"squigglelow\", INDIC_SQUIGGLELOW },\n\t\t{ \"dotbox\", INDIC_DOTBOX },\n\t\t{ \"squigglepixmap\", INDIC_SQUIGGLEPIXMAP },\n\t\t{ \"compositionthick\", INDIC_COMPOSITIONTHICK },\n\t};\n\n\tstd::string val(definition);\n\tLowerCaseAZ(val);\n\tchar *opt = &val[0];\n\twhile (opt) {\n\t\t\/\/ Find attribute separator\n\t\tchar *cpComma = strchr(opt, ',');\n\t\tif (cpComma) {\n\t\t\t\/\/ If found, we terminate the current attribute (opt) string\n\t\t\t*cpComma = '\\0';\n\t\t}\n\t\t\/\/ Find attribute name\/value separator\n\t\tchar *colon = strchr(opt, ':');\n\t\tif (colon) {\n\t\t\t\/\/ If found, we terminate the current attribute name and point on the value\n\t\t\t*colon++ = '\\0';\n\t\t}\n\t\tif (colon && (0 == strcmp(opt, \"style\"))) {\n\t\t\tbool found = false;\n\t\t\tfor (size_t i=0;i"} {"text":"#pragma once\n\n#include \"..\/data\/array.hpp\"\n#include \n\nnamespace datavis {\n\nclass DataSource : public QObject\n{\npublic:\n DataSource(const QString & filePath, QObject * parent = 0);\n\n QString path() const { return m_path; }\n array * data() { return & m_data; }\n const array * data() const { return & m_data; }\n\nprivate:\n QString m_path;\n array m_data;\n};\n\n}\nDataSource: add constructor that doesn't load from file#pragma once\n\n#include \"..\/data\/array.hpp\"\n#include \n\nnamespace datavis {\n\nclass DataSource : public QObject\n{\npublic:\n DataSource(const QString & filePath, QObject * parent = 0);\n DataSource(const vector & size): m_data(size) {}\n QString path() const { return m_path; }\n array * data() { return & m_data; }\n const array * data() const { return & m_data; }\n\nprivate:\n QString m_path;\n array m_data;\n};\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0. The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n#include \"TextEditHandler.h\"\n\n#include \n#include \n\n\n\/********************************************************************\n * CTextEditHandler class declaration\n *\n * This class implements textedit handler. It provides such functions like:\n * bold, italic and underline\n *\n *******************************************************************\/\n\n\/********************************************************************\n * CTextEditHandler - constructor of the class\n *\n *\n *******************************************************************\/\nCTextEditHandler::CTextEditHandler(QObject* parent):\n QObject(parent), m_pEdit(NULL),\n m_bIsBold(false), m_bIsItalic(false), m_bIsUnderline(false)\n{\n Init();\n}\n\n\n\/********************************************************************\n * ~CTextEditHandler - destructor of the class\n *\n *\n *******************************************************************\/\nCTextEditHandler::~CTextEditHandler()\n{\n if (NULL != m_pEdit)\n {\n delete m_pEdit;\n m_pEdit = NULL;\n }\n}\n\n\n\/********************************************************************\n * Init function makes some default operations\n *\n *\n *******************************************************************\/\nvoid CTextEditHandler::Init()\n{\n m_pEdit = new QTextEdit(NULL);\n m_pEdit->setText(\"\");\n}\n\n\n\/********************************************************************\n * bold function makes selected text bold\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::bold(const QString& _text, int _nPos, int _nPosEnd)\n{\n setTextAndCursor(CTextEditHandler::BoldRole, _text, _nPos, _nPosEnd);\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * italic function makes selected text italic\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::italic(const QString& _text, int _nPos, int _nPosEnd)\n{\n setTextAndCursor(CTextEditHandler::ItalicRole, _text, _nPos, _nPosEnd);\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * underline function makes selected text underline\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::underline(const QString& _text, int _nPos, int _nPosEnd)\n{\n setTextAndCursor(CTextEditHandler::UnderlineRole, _text, _nPos, _nPosEnd);\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * setTextAndCursor function set new text and move cursor to the new\n * position\n *\n *******************************************************************\/\nvoid CTextEditHandler::setTextAndCursor(int role, const QString& _text, int _nPos, int _nPosEnd)\n{\n m_pEdit->setText(_text);\n\n QTextCursor cursor = m_pEdit->textCursor();\n\n if (_nPos == _nPosEnd) \/\/no selection\n {\n cursor.setPosition(_nPos);\n if (!cursor.hasSelection())\n {\n cursor.select(QTextCursor::WordUnderCursor);\n }\n }\n else\n {\n cursor.setPosition(_nPos);\n cursor.setPosition(_nPosEnd, QTextCursor::KeepAnchor);\n }\n\n QString strSelection = cursor.selection().toHtml();\n QTextCharFormat fmt;\n\n if (CTextEditHandler::BoldRole == role)\n {\n m_bIsBold = (-1 != strSelection.indexOf(\"font-weight:\")) ? false : true;\n fmt.setFontWeight(m_bIsBold ? QFont::Bold : QFont::Normal);\n }\n else if (CTextEditHandler::ItalicRole == role)\n {\n m_bIsItalic = (-1 != strSelection.indexOf(\"font-style:italic\")) ? false : true;\n fmt.setFontItalic(m_bIsItalic);\n }\n else if (CTextEditHandler::UnderlineRole == role)\n {\n m_bIsUnderline = (-1 != strSelection.indexOf(\"text-decoration: underline;\")) ? false : true;\n fmt.setFontUnderline(m_bIsUnderline);\n }\n\n cursor.mergeCharFormat(fmt);\n m_pEdit->mergeCurrentCharFormat(fmt);\n}\n\n\n\/********************************************************************\n * toPlainText function converts Rich to Plain text\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::toPlainText(const QString& _text)\n{\n m_pEdit->setText(_text);\n return m_pEdit->toPlainText();\n}\n\n\n\/********************************************************************\n * setFontFamily function set new font family to the text\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::setFontFamily(const QString& _text, int _nPos, int _nPosEnd, const QString& _fontFamily)\n{\n m_pEdit->setText(_text);\n\n QTextCursor cursor = m_pEdit->textCursor();\n\n if (_nPos == _nPosEnd) \/\/no selection\n {\n cursor.setPosition(_nPos);\n if (!cursor.hasSelection())\n {\n cursor.select(QTextCursor::WordUnderCursor);\n }\n }\n else\n {\n cursor.setPosition(_nPos);\n cursor.setPosition(_nPosEnd, QTextCursor::KeepAnchor);\n }\n\n QTextCharFormat fmt;\n fmt.setFontFamily(_fontFamily);\n cursor.mergeCharFormat(fmt);\n m_pEdit->mergeCurrentCharFormat(fmt);\n\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * setFontSize function set new font size to the text\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::setFontSize(const QString& _text, int _nPos, int _nPosEnd, int _nPointSize)\n{\n m_pEdit->setText(_text);\n\n QTextCursor cursor = m_pEdit->textCursor();\n\n if (_nPos == _nPosEnd) \/\/no selection\n {\n cursor.setPosition(_nPos);\n if (!cursor.hasSelection())\n {\n cursor.select(QTextCursor::WordUnderCursor);\n }\n }\n else\n {\n cursor.setPosition(_nPos);\n cursor.setPosition(_nPosEnd, QTextCursor::KeepAnchor);\n }\n\n QTextCharFormat fmt;\n fmt.setFontPointSize(_nPointSize);\n cursor.mergeCharFormat(fmt);\n m_pEdit->mergeCurrentCharFormat(fmt);\n\n return m_pEdit->toPlainText();\n}\n\n\ntest again\/*\n * Copyright 2011 Intel Corporation.\n *\n * This program is licensed under the terms and conditions of the\n * Apache License, version 2.0. The full text of the Apache License is at \t\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\/\n\n#include \"TextEditHandler.h\"\n\n#include \n#include \n\n\n\/********************************************************************\n * CTextEditHandler class declaration\n *\n * This class implements textedit handler. It provides such functions like:\n * bold, italic and underline\n *\n *******************************************************************\/\n\n\/********************************************************************\n * CTextEditHandler - constructor of the class\n *\n *\n *******************************************************************\/\nCTextEditHandler::CTextEditHandler(QObject* parent):\n QObject(parent), m_pEdit(NULL),\n m_bIsBold(false), m_bIsItalic(false), m_bIsUnderline(false)\n{\n Init();\n}\n\n\n\/********************************************************************\n * ~CTextEditHandler - destructor of the class\n *\n *\n *******************************************************************\/\nCTextEditHandler::~CTextEditHandler()\n{\n if (NULL != m_pEdit)\n {\n delete m_pEdit;\n m_pEdit = NULL;\n }\n}\n\n\n\/********************************************************************\n * Init function makes some default operations\n *\n *\n *******************************************************************\/\nvoid CTextEditHandler::Init()\n{\n m_pEdit = new QTextEdit(NULL);\n m_pEdit->setText(\"\");\n}\n\n\n\/********************************************************************\n * bold function makes selected text bold\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::bold(const QString& _text, int _nPos, int _nPosEnd)\n{\n setTextAndCursor(CTextEditHandler::BoldRole, _text, _nPos, _nPosEnd);\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * italic function makes selected text italic\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::italic(const QString& _text, int _nPos, int _nPosEnd)\n{\n setTextAndCursor(CTextEditHandler::ItalicRole, _text, _nPos, _nPosEnd);\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * underline function makes selected text underline\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::underline(const QString& _text, int _nPos, int _nPosEnd)\n{\n setTextAndCursor(CTextEditHandler::UnderlineRole, _text, _nPos, _nPosEnd);\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * setTextAndCursor function set new text and move cursor to the new\n * position\n *\n *******************************************************************\/\nvoid CTextEditHandler::setTextAndCursor(int role, const QString& _text, int _nPos, int _nPosEnd)\n{\n m_pEdit->setText(_text);\n\n QTextCursor cursor = m_pEdit->textCursor();\n\n if (_nPos == _nPosEnd) \/\/no selection\n {\n cursor.setPosition(_nPos);\n if (!cursor.hasSelection())\n {\n cursor.select(QTextCursor::WordUnderCursor);\n }\n }\n else\n {\n cursor.setPosition(_nPos);\n cursor.setPosition(_nPosEnd, QTextCursor::KeepAnchor);\n }\n\n QString strSelection = cursor.selection().toHtml();\n QTextCharFormat fmt;\n\n if (CTextEditHandler::BoldRole == role)\n {\n m_bIsBold = (-1 != strSelection.indexOf(\"font-weight:\")) ? false : true;\n fmt.setFontWeight(m_bIsBold ? QFont::Bold : QFont::Normal);\n }\n else if (CTextEditHandler::ItalicRole == role)\n {\n m_bIsItalic = (-1 != strSelection.indexOf(\"font-style:italic\")) ? false : true;\n fmt.setFontItalic(m_bIsItalic);\n }\n else if (CTextEditHandler::UnderlineRole == role)\n {\n m_bIsUnderline = (-1 != strSelection.indexOf(\"text-decoration: underline;\")) ? false : true;\n fmt.setFontUnderline(m_bIsUnderline);\n }\n\n cursor.mergeCharFormat(fmt);\n m_pEdit->mergeCurrentCharFormat(fmt);\n}\n\n\n\/********************************************************************\n * toPlainText function converts Rich to Plain text\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::toPlainText(const QString& _text)\n{\n m_pEdit->setText(_text);\n return m_pEdit->toPlainText();\n}\n\n\n\/********************************************************************\n * setFontFamily function set new font family to the text\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::setFontFamily(const QString& _text, int _nPos, int _nPosEnd, const QString& _fontFamily)\n{\n m_pEdit->setText(_text);\n\n QTextCursor cursor = m_pEdit->textCursor();\n\n if (_nPos == _nPosEnd) \/\/no selection\n {\n cursor.setPosition(_nPos);\n if (!cursor.hasSelection())\n {\n cursor.select(QTextCursor::WordUnderCursor);\n }\n }\n else\n {\n cursor.setPosition(_nPos);\n cursor.setPosition(_nPosEnd, QTextCursor::KeepAnchor);\n }\n\n QTextCharFormat fmt;\n fmt.setFontFamily(_fontFamily);\n cursor.mergeCharFormat(fmt);\n m_pEdit->mergeCurrentCharFormat(fmt);\n\n return m_pEdit->toHtml();\n}\n\n\n\/********************************************************************\n * setFontSize function set new font size to the text\n *\n *\n *******************************************************************\/\nQString CTextEditHandler::setFontSize(const QString& _text, int _nPos, int _nPosEnd, int _nPointSize)\n{\n m_pEdit->setText(_text);\n\n QTextCursor cursor = m_pEdit->textCursor();\n\n if (_nPos == _nPosEnd) \/\/no selection\n {\n cursor.setPosition(_nPos);\n if (!cursor.hasSelection())\n {\n cursor.select(QTextCursor::WordUnderCursor);\n }\n }\n else\n {\n cursor.setPosition(_nPos);\n cursor.setPosition(_nPosEnd, QTextCursor::KeepAnchor);\n }\n\n QTextCharFormat fmt;\n fmt.setFontPointSize(_nPointSize);\n cursor.mergeCharFormat(fmt);\n m_pEdit->mergeCurrentCharFormat(fmt);\n\n return m_pEdit->toPlainText();\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009-present, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_COMMON_IMPL_CENTROID_H_\n#define PCL_COMMON_IMPL_CENTROID_H_\n\n#include \"pcl\/ros\/conversions.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::compute3DCentroid (const pcl::PointCloud &cloud, Eigen::Vector4f ¢roid)\n{\n \/\/ Initialize to 0\n centroid.setZero ();\n if (cloud.points.empty ()) \n return;\n \/\/ For each point in the cloud\n int cp = 0;\n\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n for (size_t i = 0; i < cloud.points.size (); ++i)\n centroid += cloud.points[i].getVector4fMap ();\n centroid[3] = 0;\n centroid \/= cloud.points.size ();\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[i].x) || \n !pcl_isfinite (cloud.points[i].y) || \n !pcl_isfinite (cloud.points[i].z))\n continue;\n\n centroid += cloud.points[i].getVector4fMap ();\n cp++;\n }\n centroid[3] = 0;\n centroid \/= cp;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::compute3DCentroid (const pcl::PointCloud &cloud, const std::vector &indices,\n Eigen::Vector4f ¢roid)\n{\n \/\/ Initialize to 0\n centroid.setZero ();\n if (indices.empty ()) \n return;\n \/\/ For each point in the cloud\n int cp = 0;\n\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n for (size_t i = 0; i < indices.size (); ++i)\n centroid += cloud.points[indices[i]].getVector4fMap ();\n centroid[3] = 0;\n centroid \/= indices.size ();\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n for (size_t i = 0; i < indices.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[indices[i]].x) || \n !pcl_isfinite (cloud.points[indices[i]].y) || \n !pcl_isfinite (cloud.points[indices[i]].z))\n continue;\n\n centroid += cloud.points[indices[i]].getVector4fMap ();\n cp++;\n }\n centroid[3] = 0;\n centroid \/= cp;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::compute3DCentroid (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices, Eigen::Vector4f ¢roid)\n{\n return (pcl::compute3DCentroid (cloud, indices.indices, centroid));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrix (const pcl::PointCloud &cloud,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n \/\/ Initialize to 0\n covariance_matrix.setZero ();\n\n if (cloud.points.empty ())\n return;\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n Eigen::Vector4f pt = cloud.points[i].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[i].x) || \n !pcl_isfinite (cloud.points[i].y) || \n !pcl_isfinite (cloud.points[i].z))\n continue;\n\n Eigen::Vector4f pt = cloud.points[i].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n covariance_matrix (1, 0) = covariance_matrix (0, 1);\n covariance_matrix (2, 0) = covariance_matrix (0, 2);\n covariance_matrix (2, 1) = covariance_matrix (1, 2);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrixNormalized (const pcl::PointCloud &cloud,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n pcl::computeCovarianceMatrix (cloud, centroid, covariance_matrix);\n covariance_matrix \/= cloud.points.size ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrix (const pcl::PointCloud &cloud, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n \/\/ Initialize to 0\n covariance_matrix.setZero ();\n\n if (indices.empty ())\n return;\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < indices.size (); ++i)\n {\n Eigen::Vector4f pt = cloud.points[indices[i]].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < indices.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[indices[i]].x) || \n !pcl_isfinite (cloud.points[indices[i]].y) || \n !pcl_isfinite (cloud.points[indices[i]].z))\n continue;\n\n Eigen::Vector4f pt = cloud.points[indices[i]].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n covariance_matrix (1, 0) = covariance_matrix (0, 1);\n covariance_matrix (2, 0) = covariance_matrix (0, 2);\n covariance_matrix (2, 1) = covariance_matrix (1, 2);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrix (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n return (pcl::computeCovarianceMatrix (cloud, indices.indices, centroid));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrixNormalized (const pcl::PointCloud &cloud, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n pcl::computeCovarianceMatrix (cloud, indices, centroid, covariance_matrix);\n covariance_matrix \/= indices.size ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrixNormalized (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n return (pcl::computeCovarianceMatrix (cloud, indices.indices, centroid, covariance_matrix));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const Eigen::Vector4f ¢roid,\n pcl::PointCloud &cloud_out)\n{\n cloud_out = cloud_in;\n\n \/\/ Subtract the centroid from cloud_in\n for (size_t i = 0; i < cloud_in.points.size (); ++i)\n cloud_out.points[i].getVector4fMap () -= centroid;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n pcl::PointCloud &cloud_out)\n{\n cloud_out.header = cloud_in.header;\n cloud_out.is_dense = cloud_in.is_dense;\n if (indices.size () == cloud_in.points.size ())\n {\n cloud_out.width = cloud_in.width;\n cloud_out.height = cloud_in.height;\n }\n else\n {\n cloud_out.width = indices.size ();\n cloud_out.height = 1;\n }\n cloud_out.points.resize (indices.size ());\n\n \/\/ Subtract the centroid from cloud_in\n for (size_t i = 0; i < indices.size (); ++i)\n cloud_out.points[i].getVector4fMap () = cloud_in.points[indices[i]].getVector4fMap () - \n centroid;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const Eigen::Vector4f ¢roid,\n Eigen::MatrixXf &cloud_out)\n{\n size_t npts = cloud_in.points.size ();\n\n cloud_out = Eigen::MatrixXf::Zero (4, npts); \/\/ keep the data aligned\n\n for (size_t i = 0; i < npts; ++i)\n \/\/ One column at a time\n cloud_out.block<4, 1> (0, i) = cloud_in.points[i].getVector4fMap () - centroid;\n \n \/\/ Make sure we zero the 4th dimension out (1 row, N columns)\n cloud_out.block (3, 0, 1, npts).setZero ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::MatrixXf &cloud_out)\n{\n size_t npts = indices.size ();\n\n cloud_out = Eigen::MatrixXf::Zero (4, npts); \/\/ keep the data aligned\n\n for (size_t i = 0; i < npts; ++i)\n \/\/ One column at a time\n cloud_out.block<4, 1> (0, i) = cloud_in.points[indices[i]].getVector4fMap () - centroid;\n\n \/\/ Make sure we zero the 4th dimension out (1 row, N columns)\n cloud_out.block (3, 0, 1, npts).setZero ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeNDCentroid (const pcl::PointCloud &cloud, Eigen::VectorXf ¢roid)\n{\n typedef typename pcl::traits::fieldList::type FieldList;\n\n \/\/ Get the size of the fields\n centroid.setZero (boost::mpl::size::value);\n\n if (cloud.points.empty ())\n return;\n \/\/ Iterate over each point\n int size = cloud.points.size ();\n for (int i = 0; i < size; ++i)\n {\n \/\/ Iterate over each dimension\n pcl::for_each_type (NdCentroidFunctor (cloud.points[i], centroid));\n }\n centroid \/= size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeNDCentroid (const pcl::PointCloud &cloud, const std::vector &indices,\n Eigen::VectorXf ¢roid)\n{\n typedef typename pcl::traits::fieldList::type FieldList;\n\n \/\/ Get the size of the fields\n centroid.setZero (boost::mpl::size::value);\n\n if (indices.empty ()) \n return;\n \/\/ Iterate over each point\n int nr_points = indices.size ();\n for (int i = 0; i < nr_points; ++i)\n {\n \/\/ Iterate over each dimension\n pcl::for_each_type (NdCentroidFunctor (cloud.points[indices[i]], centroid));\n }\n centroid \/= nr_points;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeNDCentroid (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices, Eigen::VectorXf ¢roid)\n{\n return (pcl::computeNDCentroid (cloud, indices.indices, centroid));\n}\n\n#endif \/\/#ifndef PCL_COMMON_IMPL_CENTROID_H_\n\nFix: add missing header boost\/mpl\/size\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009-present, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_COMMON_IMPL_CENTROID_H_\n#define PCL_COMMON_IMPL_CENTROID_H_\n\n#include \"pcl\/ros\/conversions.h\"\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::compute3DCentroid (const pcl::PointCloud &cloud, Eigen::Vector4f ¢roid)\n{\n \/\/ Initialize to 0\n centroid.setZero ();\n if (cloud.points.empty ()) \n return;\n \/\/ For each point in the cloud\n int cp = 0;\n\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n for (size_t i = 0; i < cloud.points.size (); ++i)\n centroid += cloud.points[i].getVector4fMap ();\n centroid[3] = 0;\n centroid \/= cloud.points.size ();\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[i].x) || \n !pcl_isfinite (cloud.points[i].y) || \n !pcl_isfinite (cloud.points[i].z))\n continue;\n\n centroid += cloud.points[i].getVector4fMap ();\n cp++;\n }\n centroid[3] = 0;\n centroid \/= cp;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::compute3DCentroid (const pcl::PointCloud &cloud, const std::vector &indices,\n Eigen::Vector4f ¢roid)\n{\n \/\/ Initialize to 0\n centroid.setZero ();\n if (indices.empty ()) \n return;\n \/\/ For each point in the cloud\n int cp = 0;\n\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n for (size_t i = 0; i < indices.size (); ++i)\n centroid += cloud.points[indices[i]].getVector4fMap ();\n centroid[3] = 0;\n centroid \/= indices.size ();\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n for (size_t i = 0; i < indices.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[indices[i]].x) || \n !pcl_isfinite (cloud.points[indices[i]].y) || \n !pcl_isfinite (cloud.points[indices[i]].z))\n continue;\n\n centroid += cloud.points[indices[i]].getVector4fMap ();\n cp++;\n }\n centroid[3] = 0;\n centroid \/= cp;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::compute3DCentroid (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices, Eigen::Vector4f ¢roid)\n{\n return (pcl::compute3DCentroid (cloud, indices.indices, centroid));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrix (const pcl::PointCloud &cloud,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n \/\/ Initialize to 0\n covariance_matrix.setZero ();\n\n if (cloud.points.empty ())\n return;\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n Eigen::Vector4f pt = cloud.points[i].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[i].x) || \n !pcl_isfinite (cloud.points[i].y) || \n !pcl_isfinite (cloud.points[i].z))\n continue;\n\n Eigen::Vector4f pt = cloud.points[i].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n covariance_matrix (1, 0) = covariance_matrix (0, 1);\n covariance_matrix (2, 0) = covariance_matrix (0, 2);\n covariance_matrix (2, 1) = covariance_matrix (1, 2);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrixNormalized (const pcl::PointCloud &cloud,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n pcl::computeCovarianceMatrix (cloud, centroid, covariance_matrix);\n covariance_matrix \/= cloud.points.size ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrix (const pcl::PointCloud &cloud, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n \/\/ Initialize to 0\n covariance_matrix.setZero ();\n\n if (indices.empty ())\n return;\n \/\/ If the data is dense, we don't need to check for NaN\n if (cloud.is_dense)\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < indices.size (); ++i)\n {\n Eigen::Vector4f pt = cloud.points[indices[i]].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n \/\/ For each point in the cloud\n for (size_t i = 0; i < indices.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!pcl_isfinite (cloud.points[indices[i]].x) || \n !pcl_isfinite (cloud.points[indices[i]].y) || \n !pcl_isfinite (cloud.points[indices[i]].z))\n continue;\n\n Eigen::Vector4f pt = cloud.points[indices[i]].getVector4fMap () - centroid;\n\n covariance_matrix (1, 1) += pt.y () * pt.y ();\n covariance_matrix (1, 2) += pt.y () * pt.z ();\n\n covariance_matrix (2, 2) += pt.z () * pt.z ();\n\n pt *= pt.x ();\n covariance_matrix (0, 0) += pt.x ();\n covariance_matrix (0, 1) += pt.y ();\n covariance_matrix (0, 2) += pt.z ();\n }\n }\n covariance_matrix (1, 0) = covariance_matrix (0, 1);\n covariance_matrix (2, 0) = covariance_matrix (0, 2);\n covariance_matrix (2, 1) = covariance_matrix (1, 2);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrix (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n return (pcl::computeCovarianceMatrix (cloud, indices.indices, centroid));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrixNormalized (const pcl::PointCloud &cloud, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n pcl::computeCovarianceMatrix (cloud, indices, centroid, covariance_matrix);\n covariance_matrix \/= indices.size ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeCovarianceMatrixNormalized (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::Matrix3f &covariance_matrix)\n{\n return (pcl::computeCovarianceMatrix (cloud, indices.indices, centroid, covariance_matrix));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const Eigen::Vector4f ¢roid,\n pcl::PointCloud &cloud_out)\n{\n cloud_out = cloud_in;\n\n \/\/ Subtract the centroid from cloud_in\n for (size_t i = 0; i < cloud_in.points.size (); ++i)\n cloud_out.points[i].getVector4fMap () -= centroid;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n pcl::PointCloud &cloud_out)\n{\n cloud_out.header = cloud_in.header;\n cloud_out.is_dense = cloud_in.is_dense;\n if (indices.size () == cloud_in.points.size ())\n {\n cloud_out.width = cloud_in.width;\n cloud_out.height = cloud_in.height;\n }\n else\n {\n cloud_out.width = indices.size ();\n cloud_out.height = 1;\n }\n cloud_out.points.resize (indices.size ());\n\n \/\/ Subtract the centroid from cloud_in\n for (size_t i = 0; i < indices.size (); ++i)\n cloud_out.points[i].getVector4fMap () = cloud_in.points[indices[i]].getVector4fMap () - \n centroid;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const Eigen::Vector4f ¢roid,\n Eigen::MatrixXf &cloud_out)\n{\n size_t npts = cloud_in.points.size ();\n\n cloud_out = Eigen::MatrixXf::Zero (4, npts); \/\/ keep the data aligned\n\n for (size_t i = 0; i < npts; ++i)\n \/\/ One column at a time\n cloud_out.block<4, 1> (0, i) = cloud_in.points[i].getVector4fMap () - centroid;\n \n \/\/ Make sure we zero the 4th dimension out (1 row, N columns)\n cloud_out.block (3, 0, 1, npts).setZero ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::demeanPointCloud (const pcl::PointCloud &cloud_in, \n const std::vector &indices,\n const Eigen::Vector4f ¢roid, \n Eigen::MatrixXf &cloud_out)\n{\n size_t npts = indices.size ();\n\n cloud_out = Eigen::MatrixXf::Zero (4, npts); \/\/ keep the data aligned\n\n for (size_t i = 0; i < npts; ++i)\n \/\/ One column at a time\n cloud_out.block<4, 1> (0, i) = cloud_in.points[indices[i]].getVector4fMap () - centroid;\n\n \/\/ Make sure we zero the 4th dimension out (1 row, N columns)\n cloud_out.block (3, 0, 1, npts).setZero ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeNDCentroid (const pcl::PointCloud &cloud, Eigen::VectorXf ¢roid)\n{\n typedef typename pcl::traits::fieldList::type FieldList;\n\n \/\/ Get the size of the fields\n centroid.setZero (boost::mpl::size::value);\n\n if (cloud.points.empty ())\n return;\n \/\/ Iterate over each point\n int size = cloud.points.size ();\n for (int i = 0; i < size; ++i)\n {\n \/\/ Iterate over each dimension\n pcl::for_each_type (NdCentroidFunctor (cloud.points[i], centroid));\n }\n centroid \/= size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeNDCentroid (const pcl::PointCloud &cloud, const std::vector &indices,\n Eigen::VectorXf ¢roid)\n{\n typedef typename pcl::traits::fieldList::type FieldList;\n\n \/\/ Get the size of the fields\n centroid.setZero (boost::mpl::size::value);\n\n if (indices.empty ()) \n return;\n \/\/ Iterate over each point\n int nr_points = indices.size ();\n for (int i = 0; i < nr_points; ++i)\n {\n \/\/ Iterate over each dimension\n pcl::for_each_type (NdCentroidFunctor (cloud.points[indices[i]], centroid));\n }\n centroid \/= nr_points;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate inline void\npcl::computeNDCentroid (const pcl::PointCloud &cloud, \n const pcl::PointIndices &indices, Eigen::VectorXf ¢roid)\n{\n return (pcl::computeNDCentroid (cloud, indices.indices, centroid));\n}\n\n#endif \/\/#ifndef PCL_COMMON_IMPL_CENTROID_H_\n\n<|endoftext|>"} {"text":"\/\/ -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-\n\n\/* This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 2\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Authors:\n * Caner Candan \n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost::mpi;\nusing namespace boost;\n\ntypedef dim::core::Bit EOT;\n\nclass SimulatedOp : public eoMonOp\n{\npublic:\n SimulatedOp(size_t timeout) : _timeout(timeout) {}\n\n \/\/\/ The class name.\n virtual std::string className() const { return \"SimulatedOp\"; }\n\n bool operator()(EOT&)\n {\n\tstd::this_thread::sleep_for(std::chrono::milliseconds( _timeout ));\n\treturn true;\n }\n\nprivate:\n size_t _timeout;\n};\n\nclass SimulatedEval : public eoEvalFunc\n{\npublic:\n SimulatedEval(typename EOT::Fitness fit) : _fit(fit) {}\n\n \/\/\/ The class name.\n virtual string className() const { return \"SimulatedEval\"; }\n\n void operator()(EOT& sol)\n {\n\tsol.fitness( sol.fitness() + _fit );\n }\n\nprivate:\n typename EOT::Fitness _fit;\n};\n\nclass FitnessInit : public eoUF\n{\npublic:\n void operator()(EOT& sol)\n {\n\tsol.fitness( 0 );\n }\n};\n\nint main (int argc, char *argv[])\n{\n \/*************************\n * Initialisation de MPI *\n *************************\/\n\n environment env(argc, argv, MPI_THREAD_MULTIPLE, true);\n communicator world;\n\n \/****************************\n * Il faut au moins 4 nœuds *\n ****************************\/\n\n const size_t ALL = world.size();\n const size_t RANK = world.rank();\n\n \/\/ if ( ALL < 4 )\n \/\/ \t{\n \/\/ \t if ( 0 == RANK )\n \/\/ \t\t{\n \/\/ \t\t cerr << \"Needs at least 4 processes to be launched!\" << endl;\n \/\/ \t\t}\n \/\/ \t return 0;\n \/\/ \t}\n\n \/************************\n * Initialisation de EO *\n ************************\/\n\n eoParser parser(argc, argv);\n eoState state; \/\/ keeps all things allocated\n\n \/*****************************\n * Definition des paramètres *\n *****************************\/\n\n \/\/ a\n double alpha = parser.createParam(double(0.8), \"alpha\", \"Alpha\", 'a', \"Islands Model\").value();\n \/\/ b\n double beta = parser.createParam(double(0.99), \"beta\", \"Beta\", 'b', \"Islands Model\").value();\n \/\/ p\n \/*size_t probaMin = *\/parser.createParam(size_t(10), \"probaMin\", \"Minimum probability to stay in the same island\", 'p', \"Islands Model\").value();\n \/\/ d\n size_t probaSame = parser.createParam(size_t(100\/ALL), \"probaSame\", \"Probability for an individual to stay in the same island\", 'd', \"Islands Model\").value();\n \/\/ r\n \/*size_t reward = *\/parser.createParam(size_t(2), \"reward\", \"reward\", 'r', \"Islands Model\")\/*.value()*\/;\n \/*size_t penalty = *\/parser.createParam(size_t(1), \"penalty\", \"penalty\", 0, \"Islands Model\")\/*.value()*\/;\n \/\/ I\n bool initG = parser.createParam(bool(true), \"initG\", \"initG\", 'I', \"Islands Model\").value();\n\n \/*********************************\n * Déclaration des composants EO *\n *********************************\/\n\n \/*unsigned chromSize = *\/parser.getORcreateParam(unsigned(0), \"chromSize\", \"The length of the bitstrings\", 'n',\"Problem\")\/*.value()*\/;\n eoInit& init = dim::do_make::genotype(parser, state, EOT(), 0);\n\n size_t timeout = pow(10, RANK);\n \/\/ size_t timeout = 10000;\n\n eoEvalFunc* ptEval = NULL;\n ptEval = new SimulatedEval(1);\n state.storeFunctor(ptEval);\n\n \/\/ eoEvalFunc* ptEval = NULL;\n \/\/ if ( 0 == RANK )\n \/\/ \t{\n \/\/ \t ptEval = new SimulatedEval(1);\n \/\/ \t}\n \/\/ else if ( 1 == RANK )\n \/\/ \t{\n \/\/ \t ptEval = new SimulatedEval(5);\n \/\/ \t}\n \/\/ else if ( 2 == RANK )\n \/\/ \t{\n \/\/ \t ptEval = new SimulatedEval(10);\n \/\/ \t}\n \/\/ else if ( 3 == RANK )\n \/\/ \t{\n \/\/ \t ptEval = new SimulatedEval(15);\n \/\/ \t}\n \/\/ state.storeFunctor(ptEval);\n\n eoEvalFuncCounter eval(*ptEval);\n\n \/*unsigned popSize = *\/parser.getORcreateParam(unsigned(100), \"popSize\", \"Population Size\", 'P', \"Evolution Engine\")\/*.value()*\/;\n dim::core::Pop& pop = dim::do_make::detail::pop(parser, state, init);\n\n \/*double targetFitness = *\/parser.getORcreateParam(double(1000), \"targetFitness\", \"Stop when fitness reaches\",'T', \"Stopping criterion\")\/*.value()*\/;\n \/*unsigned maxGen = *\/parser.getORcreateParam(unsigned(0), \"maxGen\", \"Maximum number of generations () = none)\",'G',\"Stopping criterion\")\/*.value()*\/;\n dim::continuator::Base& continuator = dim::do_make::continuator(parser, state, eval);\n\n dim::core::IslandData data;\n\n dim::utils::CheckPoint& checkpoint = dim::do_make::checkpoint(parser, state, continuator, data);\n\n \/**************\n * EO routine *\n **************\/\n\n make_parallel(parser);\n make_verbose(parser);\n make_help(parser);\n\n \/****************************************\n * Distribution des opérateurs aux iles *\n ****************************************\/\n\n eoMonOp* ptMon = NULL;\n ptMon = new SimulatedOp(timeout);\n state.storeFunctor(ptMon);\n\n \/\/ if ( 0 == RANK )\n \/\/ \t{\n \/\/ \t ptMon = new SimulatedOp(1);\n \/\/ \t}\n \/\/ else if ( 1 == RANK )\n \/\/ \t{\n \/\/ \t ptMon = new SimulatedOp(5);\n \/\/ \t}\n \/\/ else if ( 2 == RANK )\n \/\/ \t{\n \/\/ \t ptMon = new SimulatedOp(10);\n \/\/ \t}\n \/\/ else if ( 3 == RANK )\n \/\/ \t{\n \/\/ \t ptMon = new SimulatedOp(15);\n \/\/ \t}\n \/\/ state.storeFunctor(ptMon);\n\n \/\/ \/**********************************\n \/\/ * Déclaration des composants DIM *\n \/\/ **********************************\/\n\n dim::core::ThreadsRunner< dim::core::Pop&, dim::core::IslandData& > tr;\n\n dim::evolver::Easy evolver( \/*eval*\/*ptEval, *ptMon );\n dim::feedbacker::async::Easy feedbacker;\n dim::vectorupdater::Easy updater(alpha, beta);\n dim::memorizer::Easy memorizer;\n dim::migrator::async::Easy migrator;\n dim::algo::Easy island( evolver, feedbacker, updater, memorizer, migrator, checkpoint );\n\n tr.addHandler(feedbacker).addHandler(migrator).add(island);\n\n \/***************\n * Rock & Roll *\n ***************\/\n\n \/******************************************************************************\n * Création de la matrice de transition et distribution aux iles des vecteurs *\n ******************************************************************************\/\n\n dim::core::MigrationMatrix probabilities( ALL );\n dim::core::InitMatrix initmatrix( initG, probaSame );\n\n if ( 0 == RANK )\n \t{\n \t initmatrix( probabilities );\n \t std::cout << probabilities;\n \t data.proba = probabilities(RANK);\n\n \t for (size_t i = 1; i < ALL; ++i)\n \t\t{\n \t\t world.send( i, 100, probabilities(i) );\n \t\t}\n \t}\n else\n \t{\n \t world.recv( 0, 100, data.proba );\n \t}\n\n \/******************************************\n * Get the population size of all islands *\n ******************************************\/\n\n world.barrier();\n dim::utils::print_sum(pop);\n\n FitnessInit fitInit;\n\n apply(fitInit, pop);\n\n tr( pop, data );\n\n world.abort(0);\n\n return 0 ;\n}\n* ..\/..\/..\/application\/simulation\/threaded.cpp: replaced default value of alpha and beta + changed reward values and temporisation to a uniform way for test purpose\/\/ -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-\n\n\/* This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 2\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Authors:\n * Caner Candan \n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost::mpi;\nusing namespace boost;\n\ntypedef dim::core::Bit EOT;\n\nclass SimulatedOp : public eoMonOp\n{\npublic:\n SimulatedOp(size_t timeout) : _timeout(timeout) {}\n\n \/\/\/ The class name.\n virtual std::string className() const { return \"SimulatedOp\"; }\n\n bool operator()(EOT&)\n {\n\tstd::this_thread::sleep_for(std::chrono::milliseconds( _timeout ));\n\treturn true;\n }\n\nprivate:\n size_t _timeout;\n};\n\nclass SimulatedEval : public eoEvalFunc\n{\npublic:\n SimulatedEval(typename EOT::Fitness fit) : _fit(fit) {}\n\n \/\/\/ The class name.\n virtual string className() const { return \"SimulatedEval\"; }\n\n void operator()(EOT& sol)\n {\n\tsol.fitness( sol.fitness() + _fit );\n }\n\nprivate:\n typename EOT::Fitness _fit;\n};\n\nclass FitnessInit : public eoUF\n{\npublic:\n void operator()(EOT& sol)\n {\n\tsol.fitness( 0 );\n }\n};\n\nint main (int argc, char *argv[])\n{\n \/*************************\n * Initialisation de MPI *\n *************************\/\n\n environment env(argc, argv, MPI_THREAD_MULTIPLE, true);\n communicator world;\n\n \/****************************\n * Il faut au moins 4 nœuds *\n ****************************\/\n\n const size_t ALL = world.size();\n const size_t RANK = world.rank();\n\n \/\/ if ( ALL < 4 )\n \/\/ \t{\n \/\/ \t if ( 0 == RANK )\n \/\/ \t\t{\n \/\/ \t\t cerr << \"Needs at least 4 processes to be launched!\" << endl;\n \/\/ \t\t}\n \/\/ \t return 0;\n \/\/ \t}\n\n \/************************\n * Initialisation de EO *\n ************************\/\n\n eoParser parser(argc, argv);\n eoState state; \/\/ keeps all things allocated\n\n \/*****************************\n * Definition des paramètres *\n *****************************\/\n\n \/\/ a\n \/\/ double alpha = parser.createParam(double(0.8), \"alpha\", \"Alpha\", 'a', \"Islands Model\").value();\n double alpha = parser.createParam(double(0.2), \"alpha\", \"Alpha\", 'a', \"Islands Model\").value();\n \/\/ b\n \/\/ double beta = parser.createParam(double(0.99), \"beta\", \"Beta\", 'b', \"Islands Model\").value();\n double beta = parser.createParam(double(0.01), \"beta\", \"Beta\", 'b', \"Islands Model\").value();\n \/\/ p\n \/*size_t probaMin = *\/parser.createParam(size_t(10), \"probaMin\", \"Minimum probability to stay in the same island\", 'p', \"Islands Model\").value();\n \/\/ d\n size_t probaSame = parser.createParam(size_t(100\/ALL), \"probaSame\", \"Probability for an individual to stay in the same island\", 'd', \"Islands Model\").value();\n \/\/ r\n \/*size_t reward = *\/parser.createParam(size_t(2), \"reward\", \"reward\", 'r', \"Islands Model\")\/*.value()*\/;\n \/*size_t penalty = *\/parser.createParam(size_t(1), \"penalty\", \"penalty\", 0, \"Islands Model\")\/*.value()*\/;\n \/\/ I\n bool initG = parser.createParam(bool(true), \"initG\", \"initG\", 'I', \"Islands Model\").value();\n\n \/*********************************\n * Déclaration des composants EO *\n *********************************\/\n\n \/*unsigned chromSize = *\/parser.getORcreateParam(unsigned(0), \"chromSize\", \"The length of the bitstrings\", 'n',\"Problem\")\/*.value()*\/;\n eoInit& init = dim::do_make::genotype(parser, state, EOT(), 0);\n\n \/\/ size_t timeout = pow(10, RANK);\n \/\/ size_t timeout = RANK+1;\n \/\/ size_t timeout = 1;\n\n \/\/ eoEvalFunc* ptEval = NULL;\n \/\/ ptEval = new SimulatedEval(1);\n \/\/ state.storeFunctor(ptEval);\n\n eoEvalFunc* ptEval = NULL;\n if ( 0 == RANK )\n \t{\n \t ptEval = new SimulatedEval(1);\n \t}\n else if ( 1 == RANK )\n \t{\n \t ptEval = new SimulatedEval(1);\n \t}\n else if ( 2 == RANK )\n \t{\n \t ptEval = new SimulatedEval(1);\n \t}\n else if ( 3 == RANK )\n \t{\n \t ptEval = new SimulatedEval(1);\n \t}\n state.storeFunctor(ptEval);\n\n eoEvalFuncCounter eval(*ptEval);\n\n \/*unsigned popSize = *\/parser.getORcreateParam(unsigned(100), \"popSize\", \"Population Size\", 'P', \"Evolution Engine\")\/*.value()*\/;\n dim::core::Pop& pop = dim::do_make::detail::pop(parser, state, init);\n\n \/*double targetFitness = *\/parser.getORcreateParam(double(1000), \"targetFitness\", \"Stop when fitness reaches\",'T', \"Stopping criterion\")\/*.value()*\/;\n \/*unsigned maxGen = *\/parser.getORcreateParam(unsigned(0), \"maxGen\", \"Maximum number of generations () = none)\",'G',\"Stopping criterion\")\/*.value()*\/;\n dim::continuator::Base& continuator = dim::do_make::continuator(parser, state, eval);\n\n dim::core::IslandData data;\n\n dim::utils::CheckPoint& checkpoint = dim::do_make::checkpoint(parser, state, continuator, data);\n\n \/**************\n * EO routine *\n **************\/\n\n make_parallel(parser);\n make_verbose(parser);\n make_help(parser);\n\n \/****************************************\n * Distribution des opérateurs aux iles *\n ****************************************\/\n\n eoMonOp* ptMon = NULL;\n \/\/ ptMon = new SimulatedOp(timeout);\n \/\/ state.storeFunctor(ptMon);\n\n if ( 0 == RANK )\n \t{\n \t ptMon = new SimulatedOp(1);\n \t}\n else if ( 1 == RANK )\n \t{\n \t ptMon = new SimulatedOp(1);\n \t}\n else if ( 2 == RANK )\n \t{\n \t ptMon = new SimulatedOp(1);\n \t}\n else if ( 3 == RANK )\n \t{\n \t ptMon = new SimulatedOp(1);\n \t}\n state.storeFunctor(ptMon);\n\n \/\/ \/**********************************\n \/\/ * Déclaration des composants DIM *\n \/\/ **********************************\/\n\n dim::core::ThreadsRunner< dim::core::Pop&, dim::core::IslandData& > tr;\n\n dim::evolver::Easy evolver( \/*eval*\/*ptEval, *ptMon );\n dim::feedbacker::async::Easy feedbacker;\n dim::vectorupdater::Easy updater(alpha, beta);\n dim::memorizer::Easy memorizer;\n dim::migrator::async::Easy migrator;\n dim::algo::Easy island( evolver, feedbacker, updater, memorizer, migrator, checkpoint );\n\n tr.addHandler(feedbacker).addHandler(migrator).add(island);\n\n \/***************\n * Rock & Roll *\n ***************\/\n\n \/******************************************************************************\n * Création de la matrice de transition et distribution aux iles des vecteurs *\n ******************************************************************************\/\n\n dim::core::MigrationMatrix probabilities( ALL );\n dim::core::InitMatrix initmatrix( initG, probaSame );\n\n if ( 0 == RANK )\n \t{\n \t initmatrix( probabilities );\n \t std::cout << probabilities;\n \t data.proba = probabilities(RANK);\n\n \t for (size_t i = 1; i < ALL; ++i)\n \t\t{\n \t\t world.send( i, 100, probabilities(i) );\n \t\t}\n \t}\n else\n \t{\n \t world.recv( 0, 100, data.proba );\n \t}\n\n \/******************************************\n * Get the population size of all islands *\n ******************************************\/\n\n world.barrier();\n dim::utils::print_sum(pop);\n\n FitnessInit fitInit;\n\n apply(fitInit, pop);\n\n tr( pop, data );\n\n world.abort(0);\n\n return 0 ;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ReportComponentHandler.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 18:10:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n\n#ifndef RPT_REPORTCOMPONENTHANDLER_HXX\n#include \"ReportComponentHandler.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include \n#endif\n#ifndef REPORTDESIGN_SHARED_UISTRINGS_HRC\n#include \"uistrings.hrc\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_INSPECTION_PROPERTYCONTROLTYPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REPORT_XREPORTDEFINITION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REPORT_XSECTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_INSPECTION_XNUMERICCONTROL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_MEASUREUNIT_HPP_\n#include \n#endif\n#ifndef _VCL_FLDUNIT_HXX\n#include \n#endif\n#ifndef RPTUI_METADATA_HXX_\n#include \"metadata.hxx\"\n#endif\n\n\/\/........................................................................\nnamespace rptui\n{\n\/\/........................................................................\nusing namespace ::com::sun::star;\n\/\/ using namespace comphelper;\n\nReportComponentHandler::ReportComponentHandler(uno::Reference< uno::XComponentContext > const & context)\n :ReportComponentHandler_Base(m_aMutex)\n ,m_xContext(context)\n ,m_pInfoService( new OPropertyInfoService() )\n{\n try\n {\n m_xFormComponentHandler.set(m_xContext->getServiceManager()->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.form.inspection.FormComponentPropertyHandler\")),m_xContext),uno::UNO_QUERY_THROW);\n\n }catch(uno::Exception)\n {\n }\n}\n\n\/\/------------------------------------------------------------------------\n::rtl::OUString SAL_CALL ReportComponentHandler::getImplementationName( ) throw(uno::RuntimeException)\n{\n return getImplementationName_Static();\n}\n\n\/\/------------------------------------------------------------------------\nsal_Bool SAL_CALL ReportComponentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException)\n{\n return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static());\n}\n\n\/\/------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupportedServiceNames( ) throw(uno::RuntimeException)\n{\n return getSupportedServiceNames_static();\n}\n\n\/\/------------------------------------------------------------------------\n::rtl::OUString ReportComponentHandler::getImplementationName_Static( ) throw(uno::RuntimeException)\n{\n return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.report.ReportComponentHandler\"));\n}\n\n\/\/------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > ReportComponentHandler::getSupportedServiceNames_static( ) throw(uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aSupported(1);\n aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.report.inspection.ReportComponentHandler\"));\n return aSupported;\n}\n\n\/\/------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL ReportComponentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext )\n{\n return *(new ReportComponentHandler( _rxContext ));\n}\n\/\/ overload WeakComponentImplHelperBase::disposing()\n\/\/ This function is called upon disposing the component,\n\/\/ if your component needs special work when it becomes\n\/\/ disposed, do it here.\nvoid SAL_CALL ReportComponentHandler::disposing()\n{\n ::comphelper::disposeComponent(m_xFormComponentHandler);\n}\nvoid SAL_CALL ReportComponentHandler::addEventListener(const uno::Reference< lang::XEventListener > & xListener) throw (uno::RuntimeException)\n{\n m_xFormComponentHandler->addEventListener(xListener);\n}\n\nvoid SAL_CALL ReportComponentHandler::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw (uno::RuntimeException)\n{\n m_xFormComponentHandler->removeEventListener(aListener);\n}\n\n\/\/ inspection::XPropertyHandler:\n\n\/********************************************************************************\/\nvoid SAL_CALL ReportComponentHandler::inspect(const uno::Reference< uno::XInterface > & Component) throw (uno::RuntimeException, lang::NullPointerException)\n{\n try\n {\n uno::Reference< container::XNameContainer > xNameCont(Component,uno::UNO_QUERY);\n const ::rtl::OUString sFormComponent(RTL_CONSTASCII_USTRINGPARAM(\"FormComponent\"));\n if ( xNameCont->hasByName(sFormComponent) )\n xNameCont->getByName(sFormComponent) >>= m_xFormComponent;\n const ::rtl::OUString sRowSet(RTL_CONSTASCII_USTRINGPARAM(\"RowSet\"));\n if ( xNameCont->hasByName(sRowSet) )\n {\n uno::Reference xProp(m_xFormComponentHandler,uno::UNO_QUERY);\n xProp->setPropertyValue(sRowSet,xNameCont->getByName(sRowSet));\n }\n }\n catch(uno::Exception)\n {\n throw lang::NullPointerException();\n }\n if ( m_xFormComponent.is() )\n {\n m_xFormComponentHandler->inspect(m_xFormComponent);\n }\n}\n\nuno::Any SAL_CALL ReportComponentHandler::getPropertyValue(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->getPropertyValue(PropertyName);\n}\n\nvoid SAL_CALL ReportComponentHandler::setPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & Value) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n m_xFormComponentHandler->setPropertyValue(PropertyName, Value);\n}\n\nbeans::PropertyState SAL_CALL ReportComponentHandler::getPropertyState(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->getPropertyState(PropertyName);\n}\n\ninspection::LineDescriptor SAL_CALL ReportComponentHandler::describePropertyLine(const ::rtl::OUString & PropertyName, const uno::Reference< inspection::XPropertyControlFactory > & ControlFactory) throw (beans::UnknownPropertyException, lang::NullPointerException,uno::RuntimeException)\n{\n return m_xFormComponentHandler->describePropertyLine(PropertyName, ControlFactory);\n}\n\nuno::Any SAL_CALL ReportComponentHandler::convertToPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & ControlValue) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->convertToPropertyValue(PropertyName, ControlValue);\n}\n\nuno::Any SAL_CALL ReportComponentHandler::convertToControlValue(const ::rtl::OUString & PropertyName, const uno::Any & PropertyValue, const uno::Type & ControlValueType) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->convertToControlValue(PropertyName, PropertyValue, ControlValueType);\n}\n\nvoid SAL_CALL ReportComponentHandler::addPropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & Listener) throw (uno::RuntimeException, lang::NullPointerException)\n{\n m_xFormComponentHandler->addPropertyChangeListener(Listener);\n}\n\nvoid SAL_CALL ReportComponentHandler::removePropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & _rxListener) throw (uno::RuntimeException)\n{\n m_xFormComponentHandler->removePropertyChangeListener(_rxListener);\n}\n\nuno::Sequence< beans::Property > SAL_CALL ReportComponentHandler::getSupportedProperties() throw (uno::RuntimeException)\n{\n ::std::vector< beans::Property > aNewProps;\n m_pInfoService->getExcludeProperties( aNewProps, m_xFormComponentHandler );\n\n return aNewProps.empty() ? uno::Sequence< beans::Property > () : uno::Sequence< beans::Property > (&(*aNewProps.begin()),aNewProps.size());\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupersededProperties() throw (uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aRet;\n return aRet;\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getActuatingProperties() throw (uno::RuntimeException)\n{\n return m_xFormComponentHandler->getActuatingProperties();\n}\n\n::sal_Bool SAL_CALL ReportComponentHandler::isComposable( const ::rtl::OUString& _rPropertyName ) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_pInfoService->isComposable( _rPropertyName, m_xFormComponentHandler );\n}\n\ninspection::InteractiveSelectionResult SAL_CALL ReportComponentHandler::onInteractivePropertySelection(const ::rtl::OUString & PropertyName, ::sal_Bool Primary, uno::Any & out_Data, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI) throw (uno::RuntimeException, beans::UnknownPropertyException, lang::NullPointerException)\n{\n return m_xFormComponentHandler->onInteractivePropertySelection(PropertyName, Primary, out_Data, InspectorUI);\n}\n\nvoid SAL_CALL ReportComponentHandler::actuatingPropertyChanged(const ::rtl::OUString & ActuatingPropertyName, const uno::Any & NewValue, const uno::Any & OldValue, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI, ::sal_Bool FirstTimeInit) throw (uno::RuntimeException, lang::NullPointerException)\n{\n m_xFormComponentHandler->actuatingPropertyChanged(ActuatingPropertyName, NewValue, OldValue, InspectorUI, FirstTimeInit);\n}\n\n::sal_Bool SAL_CALL ReportComponentHandler::suspend(::sal_Bool Suspend) throw (uno::RuntimeException)\n{\n return m_xFormComponentHandler->suspend(Suspend);\n}\n\n\/\/........................................................................\n} \/\/ namespace rptui\n\/\/........................................................................\n\nINTEGRATION: CWS changefileheader (1.3.8); FILE MERGED 2008\/04\/01 15:23:44 thb 1.3.8.3: #i85898# Stripping all external header guards 2008\/04\/01 12:33:15 thb 1.3.8.2: #i85898# Stripping all external header guards 2008\/03\/31 13:32:19 rt 1.3.8.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ReportComponentHandler.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n#include \"ReportComponentHandler.hxx\"\n#include \n#include \n#ifndef REPORTDESIGN_SHARED_UISTRINGS_HRC\n#include \"uistrings.hrc\"\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"metadata.hxx\"\n\n\/\/........................................................................\nnamespace rptui\n{\n\/\/........................................................................\nusing namespace ::com::sun::star;\n\/\/ using namespace comphelper;\n\nReportComponentHandler::ReportComponentHandler(uno::Reference< uno::XComponentContext > const & context)\n :ReportComponentHandler_Base(m_aMutex)\n ,m_xContext(context)\n ,m_pInfoService( new OPropertyInfoService() )\n{\n try\n {\n m_xFormComponentHandler.set(m_xContext->getServiceManager()->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.form.inspection.FormComponentPropertyHandler\")),m_xContext),uno::UNO_QUERY_THROW);\n\n }catch(uno::Exception)\n {\n }\n}\n\n\/\/------------------------------------------------------------------------\n::rtl::OUString SAL_CALL ReportComponentHandler::getImplementationName( ) throw(uno::RuntimeException)\n{\n return getImplementationName_Static();\n}\n\n\/\/------------------------------------------------------------------------\nsal_Bool SAL_CALL ReportComponentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException)\n{\n return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static());\n}\n\n\/\/------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupportedServiceNames( ) throw(uno::RuntimeException)\n{\n return getSupportedServiceNames_static();\n}\n\n\/\/------------------------------------------------------------------------\n::rtl::OUString ReportComponentHandler::getImplementationName_Static( ) throw(uno::RuntimeException)\n{\n return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.report.ReportComponentHandler\"));\n}\n\n\/\/------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > ReportComponentHandler::getSupportedServiceNames_static( ) throw(uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aSupported(1);\n aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.report.inspection.ReportComponentHandler\"));\n return aSupported;\n}\n\n\/\/------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL ReportComponentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext )\n{\n return *(new ReportComponentHandler( _rxContext ));\n}\n\/\/ overload WeakComponentImplHelperBase::disposing()\n\/\/ This function is called upon disposing the component,\n\/\/ if your component needs special work when it becomes\n\/\/ disposed, do it here.\nvoid SAL_CALL ReportComponentHandler::disposing()\n{\n ::comphelper::disposeComponent(m_xFormComponentHandler);\n}\nvoid SAL_CALL ReportComponentHandler::addEventListener(const uno::Reference< lang::XEventListener > & xListener) throw (uno::RuntimeException)\n{\n m_xFormComponentHandler->addEventListener(xListener);\n}\n\nvoid SAL_CALL ReportComponentHandler::removeEventListener(const uno::Reference< lang::XEventListener > & aListener) throw (uno::RuntimeException)\n{\n m_xFormComponentHandler->removeEventListener(aListener);\n}\n\n\/\/ inspection::XPropertyHandler:\n\n\/********************************************************************************\/\nvoid SAL_CALL ReportComponentHandler::inspect(const uno::Reference< uno::XInterface > & Component) throw (uno::RuntimeException, lang::NullPointerException)\n{\n try\n {\n uno::Reference< container::XNameContainer > xNameCont(Component,uno::UNO_QUERY);\n const ::rtl::OUString sFormComponent(RTL_CONSTASCII_USTRINGPARAM(\"FormComponent\"));\n if ( xNameCont->hasByName(sFormComponent) )\n xNameCont->getByName(sFormComponent) >>= m_xFormComponent;\n const ::rtl::OUString sRowSet(RTL_CONSTASCII_USTRINGPARAM(\"RowSet\"));\n if ( xNameCont->hasByName(sRowSet) )\n {\n uno::Reference xProp(m_xFormComponentHandler,uno::UNO_QUERY);\n xProp->setPropertyValue(sRowSet,xNameCont->getByName(sRowSet));\n }\n }\n catch(uno::Exception)\n {\n throw lang::NullPointerException();\n }\n if ( m_xFormComponent.is() )\n {\n m_xFormComponentHandler->inspect(m_xFormComponent);\n }\n}\n\nuno::Any SAL_CALL ReportComponentHandler::getPropertyValue(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->getPropertyValue(PropertyName);\n}\n\nvoid SAL_CALL ReportComponentHandler::setPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & Value) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n m_xFormComponentHandler->setPropertyValue(PropertyName, Value);\n}\n\nbeans::PropertyState SAL_CALL ReportComponentHandler::getPropertyState(const ::rtl::OUString & PropertyName) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->getPropertyState(PropertyName);\n}\n\ninspection::LineDescriptor SAL_CALL ReportComponentHandler::describePropertyLine(const ::rtl::OUString & PropertyName, const uno::Reference< inspection::XPropertyControlFactory > & ControlFactory) throw (beans::UnknownPropertyException, lang::NullPointerException,uno::RuntimeException)\n{\n return m_xFormComponentHandler->describePropertyLine(PropertyName, ControlFactory);\n}\n\nuno::Any SAL_CALL ReportComponentHandler::convertToPropertyValue(const ::rtl::OUString & PropertyName, const uno::Any & ControlValue) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->convertToPropertyValue(PropertyName, ControlValue);\n}\n\nuno::Any SAL_CALL ReportComponentHandler::convertToControlValue(const ::rtl::OUString & PropertyName, const uno::Any & PropertyValue, const uno::Type & ControlValueType) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_xFormComponentHandler->convertToControlValue(PropertyName, PropertyValue, ControlValueType);\n}\n\nvoid SAL_CALL ReportComponentHandler::addPropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & Listener) throw (uno::RuntimeException, lang::NullPointerException)\n{\n m_xFormComponentHandler->addPropertyChangeListener(Listener);\n}\n\nvoid SAL_CALL ReportComponentHandler::removePropertyChangeListener(const uno::Reference< beans::XPropertyChangeListener > & _rxListener) throw (uno::RuntimeException)\n{\n m_xFormComponentHandler->removePropertyChangeListener(_rxListener);\n}\n\nuno::Sequence< beans::Property > SAL_CALL ReportComponentHandler::getSupportedProperties() throw (uno::RuntimeException)\n{\n ::std::vector< beans::Property > aNewProps;\n m_pInfoService->getExcludeProperties( aNewProps, m_xFormComponentHandler );\n\n return aNewProps.empty() ? uno::Sequence< beans::Property > () : uno::Sequence< beans::Property > (&(*aNewProps.begin()),aNewProps.size());\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getSupersededProperties() throw (uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aRet;\n return aRet;\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL ReportComponentHandler::getActuatingProperties() throw (uno::RuntimeException)\n{\n return m_xFormComponentHandler->getActuatingProperties();\n}\n\n::sal_Bool SAL_CALL ReportComponentHandler::isComposable( const ::rtl::OUString& _rPropertyName ) throw (uno::RuntimeException, beans::UnknownPropertyException)\n{\n return m_pInfoService->isComposable( _rPropertyName, m_xFormComponentHandler );\n}\n\ninspection::InteractiveSelectionResult SAL_CALL ReportComponentHandler::onInteractivePropertySelection(const ::rtl::OUString & PropertyName, ::sal_Bool Primary, uno::Any & out_Data, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI) throw (uno::RuntimeException, beans::UnknownPropertyException, lang::NullPointerException)\n{\n return m_xFormComponentHandler->onInteractivePropertySelection(PropertyName, Primary, out_Data, InspectorUI);\n}\n\nvoid SAL_CALL ReportComponentHandler::actuatingPropertyChanged(const ::rtl::OUString & ActuatingPropertyName, const uno::Any & NewValue, const uno::Any & OldValue, const uno::Reference< inspection::XObjectInspectorUI > & InspectorUI, ::sal_Bool FirstTimeInit) throw (uno::RuntimeException, lang::NullPointerException)\n{\n m_xFormComponentHandler->actuatingPropertyChanged(ActuatingPropertyName, NewValue, OldValue, InspectorUI, FirstTimeInit);\n}\n\n::sal_Bool SAL_CALL ReportComponentHandler::suspend(::sal_Bool Suspend) throw (uno::RuntimeException)\n{\n return m_xFormComponentHandler->suspend(Suspend);\n}\n\n\/\/........................................................................\n} \/\/ namespace rptui\n\/\/........................................................................\n\n<|endoftext|>"} {"text":"#ifndef SOLAIRE_CONTAINER_HPP\n#define SOLAIRE_CONTAINER_HPP\n\n\/\/Copyright 2015 Adam Smith\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\n\n\/\/ Contact :\n\/\/ Email : solairelibrary@mail.com\n\/\/ GitHub repository : https:\/\/github.com\/SolaireLibrary\/SolaireCPP\n\n\/*!\n\t\\file Container.hpp\n\t\\brief\n\t\\author\n\tCreated\t\t\t: Adam Smith\n\tLast modified\t: Adam Smith\n\t\\date\n\tCreated\t\t\t: 3rd December 2015\n\tLast Modified\t: 10th January 2016\n*\/\n\n#include \n#include \"Solaire\/Core\/Iterator.hpp\"\n#include \"Solaire\/Core\/Allocator.hpp\"\n\nnamespace Solaire {\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE StaticContainer {\n public:\n template\n friend class StaticContainer;\n\n typedef T Type;\n typedef T* Pointer;\n typedef T& Reference;\n protected:\n virtual Pointer SOLAIRE_EXPORT_CALL getPtr(int32_t) throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL begin_() throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL end_() throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL rbegin_() throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL rend_() throw() = 0;\n\n SOLAIRE_FORCE_INLINE const Type* getPtr(const int32_t aIndex) const throw() {\n return const_cast*>(this)->getPtr(aIndex);\n }\n public:\n virtual SOLAIRE_EXPORT_CALL ~StaticContainer() throw() {}\n\n virtual bool SOLAIRE_EXPORT_CALL isContiguous() const throw() = 0;\n virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;\n virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;\n\n SOLAIRE_FORCE_INLINE Reference operator[](const int32_t aIndex) throw() {\n return *getPtr(aIndex);\n }\n\n SOLAIRE_FORCE_INLINE const Reference operator[](const int32_t aIndex) const throw() {\n return *const_cast*>(this)->getPtr(aIndex);\n }\n\n SOLAIRE_FORCE_INLINE STLIterator begin() throw() {\n return STLIterator(begin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator end() throw() {\n return STLIterator(end_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator begin() const throw() {\n return STLIterator(const_cast*>(this)->begin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator end() const throw() {\n return STLIterator(const_cast*>(this)->end_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rbegin() throw() {\n return STLIterator(rbegin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rend() throw() {\n return STLIterator(rend_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rbegin() const throw() {\n return STLIterator(const_cast*>(this)->rbegin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rend() const throw() {\n return STLIterator(const_cast*>(this)->rend_());\n }\n\n SOLAIRE_FORCE_INLINE operator StaticContainer&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const StaticContainer&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\n inline bool operator==(const StaticContainer& aOther) const throw() {\n const int32_t length = size();\n if(length != aOther.size()) return false;\n if(std::is_fundamental::value && isContiguous() && aOther.isContiguous()) {\n return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) == 0;\n }else {\n for(int32_t i = 0; i < length; ++i) {\n if(getPtr(i) != aOther.getPtr(i)) return false;\n }\n return true;\n }\n }\n\n inline bool operator!=(const StaticContainer& aOther) const throw() {\n const int32_t length = size();\n if(length != aOther.size()) return true;\n if(std::is_fundamental::value && isContiguous() && aOther.isContiguous()) {\n return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) != 0;\n }else {\n for(int32_t i = 0; i < length; ++i) {\n if(getPtr(i) != aOther.getPtr(i)) return true;\n }\n return false;\n }\n }\n\n SOLAIRE_FORCE_INLINE int32_t findFirstOf(const T& aValue) const throw() {\n return findNextOf(0, aValue);\n }\n\n inline int32_t findNextOf(const int32_t aIndex, const T& aValue) const throw() {\n const int32_t length = size();\n if(isContiguous()) {\n const T* const ptr = const_cast*>(this)->getPtr(0);\n for(int32_t i = aIndex; i < length; ++i) {\n if(ptr[i] == aValue) return i;\n }\n }else {\n for(int32_t i = aIndex; i < length; ++i) {\n if(*const_cast*>(this)->getPtr(i) == aValue) return i;\n }\n }\n\n return length;\n }\n\n inline int32_t findLastOf(const T& aValue) const throw() {\n const int32_t end = size();\n int32_t i = findFirstOf(aValue);\n int32_t j = i;\n\n while(i != end) {\n j = i;\n i = findNextOf(i + 1, aValue);\n }\n\n return j;\n }\n\n template\n SOLAIRE_FORCE_INLINE int32_t findFirstIf(const F aCondition) const throw() {\n return findNextIf(0, aCondition);\n }\n\n template\n inline int32_t findNextIf(const int32_t aIndex, const F aCondition) const throw() {\n const int32_t length = size();\n if(isContiguous()) {\n const T* const ptr = const_cast*>(this)->getPtr(0);\n for(int32_t i = aIndex; i < length; ++i) {\n if(aCondition(ptr[i])) return i;\n }\n }else {\n for(int32_t i = aIndex; i < length; ++i) {\n if(aCondition(*const_cast*>(this)->getPtr(i))) return i;\n }\n }\n\n return length;\n }\n\n template\n inline int32_t findLastIf(const F aCondition) const throw() {\n const int32_t end = size();\n int32_t i = findFirstIf(aCondition);\n int32_t j = i;\n\n while(i != end) {\n j = i;\n i = findNextIf(i + 1, aCondition);\n }\n\n return j;\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE Stack : public StaticContainer {\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~Stack() throw() {}\n\t\tvirtual T& SOLAIRE_EXPORT_CALL pushBack(const T&) throw() = 0;\n\t\tvirtual T SOLAIRE_EXPORT_CALL popBack() throw() = 0;\n\t\tvirtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;\n\n\t\tSOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL back() throw() {\n\t\t\treturn StaticContainer::operator[](StaticContainer::size() - 1);\n\t\t}\n\n\t\tSOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL back() const throw() {\n\t\t\treturn StaticContainer::operator[](StaticContainer::size() - 1);\n\t\t}\n\n SOLAIRE_FORCE_INLINE operator Stack&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const Stack&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE Deque : public Stack {\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~Deque() throw() {}\n\n\t\tvirtual T& SOLAIRE_EXPORT_CALL pushFront(const T&) throw() = 0;\n\t\tvirtual T SOLAIRE_EXPORT_CALL popFront() throw() = 0;\n\n\t\tSOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL front() throw() {\n\t\t\treturn StaticContainer::operator[](0);\n\t\t}\n\n\t\tSOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL front() const throw() {\n\t\t\treturn StaticContainer::operator[](0);\n\t\t}\n\n SOLAIRE_FORCE_INLINE operator Deque&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const Deque&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE List : public Deque {\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~List() throw() {}\n\n\t\tvirtual T& SOLAIRE_EXPORT_CALL insertBefore(const int32_t, const T&) throw() = 0;\n\t\tvirtual T& SOLAIRE_EXPORT_CALL insertAfter(const int32_t, const T&) throw() = 0;\n\t\tvirtual bool SOLAIRE_EXPORT_CALL erase(const int32_t) throw() = 0;\n\n SOLAIRE_FORCE_INLINE operator List&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const List&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE Map {\n public:\n typedef K KeyType;\n typedef K* KeyPointer;\n typedef K& KeyReference;\n typedef std::pair Entry;\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~Map() throw() {}\n\n\t\tvirtual T& SOLAIRE_EXPORT_CALL emplace(const K&, const T&) throw() = 0;\n\t\tvirtual const T& SOLAIRE_EXPORT_CALL get(const K&) const throw() = 0;\n\t\tvirtual T& SOLAIRE_EXPORT_CALL get(const K&) throw() = 0;\n\t\tvirtual bool SOLAIRE_EXPORT_CALL contains(const K&) const throw() = 0;\n\t\tvirtual bool SOLAIRE_EXPORT_CALL erase(const K&) throw() = 0;\n\n\t\tvirtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;\n virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;\n virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;\n virtual SharedAllocation> getEntries() const throw() = 0;\n\t};\n\n}\n\n\n#endif\nConst Iterator fix#ifndef SOLAIRE_CONTAINER_HPP\n#define SOLAIRE_CONTAINER_HPP\n\n\/\/Copyright 2015 Adam Smith\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\n\n\/\/ Contact :\n\/\/ Email : solairelibrary@mail.com\n\/\/ GitHub repository : https:\/\/github.com\/SolaireLibrary\/SolaireCPP\n\n\/*!\n\t\\file Container.hpp\n\t\\brief\n\t\\author\n\tCreated\t\t\t: Adam Smith\n\tLast modified\t: Adam Smith\n\t\\date\n\tCreated\t\t\t: 3rd December 2015\n\tLast Modified\t: 10th January 2016\n*\/\n\n#include \n#include \"Solaire\/Core\/Iterator.hpp\"\n#include \"Solaire\/Core\/Allocator.hpp\"\n\nnamespace Solaire {\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE StaticContainer {\n public:\n template\n friend class StaticContainer;\n\n typedef T Type;\n typedef T* Pointer;\n typedef T& Reference;\n protected:\n virtual Pointer SOLAIRE_EXPORT_CALL getPtr(int32_t) throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL begin_() throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL end_() throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL rbegin_() throw() = 0;\n virtual SharedAllocation> SOLAIRE_EXPORT_CALL rend_() throw() = 0;\n\n SOLAIRE_FORCE_INLINE const Type* getPtr(const int32_t aIndex) const throw() {\n return const_cast*>(this)->getPtr(aIndex);\n }\n public:\n virtual SOLAIRE_EXPORT_CALL ~StaticContainer() throw() {}\n\n virtual bool SOLAIRE_EXPORT_CALL isContiguous() const throw() = 0;\n virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;\n virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;\n\n SOLAIRE_FORCE_INLINE Reference operator[](const int32_t aIndex) throw() {\n return *getPtr(aIndex);\n }\n\n SOLAIRE_FORCE_INLINE const Reference operator[](const int32_t aIndex) const throw() {\n return *const_cast*>(this)->getPtr(aIndex);\n }\n\n SOLAIRE_FORCE_INLINE STLIterator begin() throw() {\n return STLIterator(begin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator end() throw() {\n return STLIterator(end_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator begin() const throw() {\n StaticContainer* const p1 = const_cast*>(this);\n StaticContainer* const p2 = reinterpret_cast*>(p1);\n return STLIterator(p2->begin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator end() const throw() {\n StaticContainer* const p1 = const_cast*>(this);\n StaticContainer* const p2 = reinterpret_cast*>(p1);\n return STLIterator(p2->end_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rbegin() throw() {\n return STLIterator(rbegin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rend() throw() {\n return STLIterator(rend_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rbegin() const throw() {\n return STLIterator(const_cast*>(this)->rbegin_());\n }\n\n SOLAIRE_FORCE_INLINE STLIterator rend() const throw() {\n return STLIterator(const_cast*>(this)->rend_());\n }\n\n SOLAIRE_FORCE_INLINE operator StaticContainer&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const StaticContainer&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\n inline bool operator==(const StaticContainer& aOther) const throw() {\n const int32_t length = size();\n if(length != aOther.size()) return false;\n if(std::is_fundamental::value && isContiguous() && aOther.isContiguous()) {\n return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) == 0;\n }else {\n for(int32_t i = 0; i < length; ++i) {\n if(getPtr(i) != aOther.getPtr(i)) return false;\n }\n return true;\n }\n }\n\n inline bool operator!=(const StaticContainer& aOther) const throw() {\n const int32_t length = size();\n if(length != aOther.size()) return true;\n if(std::is_fundamental::value && isContiguous() && aOther.isContiguous()) {\n return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) != 0;\n }else {\n for(int32_t i = 0; i < length; ++i) {\n if(getPtr(i) != aOther.getPtr(i)) return true;\n }\n return false;\n }\n }\n\n SOLAIRE_FORCE_INLINE int32_t findFirstOf(const T& aValue) const throw() {\n return findNextOf(0, aValue);\n }\n\n inline int32_t findNextOf(const int32_t aIndex, const T& aValue) const throw() {\n const int32_t length = size();\n if(isContiguous()) {\n const T* const ptr = const_cast*>(this)->getPtr(0);\n for(int32_t i = aIndex; i < length; ++i) {\n if(ptr[i] == aValue) return i;\n }\n }else {\n for(int32_t i = aIndex; i < length; ++i) {\n if(*const_cast*>(this)->getPtr(i) == aValue) return i;\n }\n }\n\n return length;\n }\n\n inline int32_t findLastOf(const T& aValue) const throw() {\n const int32_t end = size();\n int32_t i = findFirstOf(aValue);\n int32_t j = i;\n\n while(i != end) {\n j = i;\n i = findNextOf(i + 1, aValue);\n }\n\n return j;\n }\n\n template\n SOLAIRE_FORCE_INLINE int32_t findFirstIf(const F aCondition) const throw() {\n return findNextIf(0, aCondition);\n }\n\n template\n inline int32_t findNextIf(const int32_t aIndex, const F aCondition) const throw() {\n const int32_t length = size();\n if(isContiguous()) {\n const T* const ptr = const_cast*>(this)->getPtr(0);\n for(int32_t i = aIndex; i < length; ++i) {\n if(aCondition(ptr[i])) return i;\n }\n }else {\n for(int32_t i = aIndex; i < length; ++i) {\n if(aCondition(*const_cast*>(this)->getPtr(i))) return i;\n }\n }\n\n return length;\n }\n\n template\n inline int32_t findLastIf(const F aCondition) const throw() {\n const int32_t end = size();\n int32_t i = findFirstIf(aCondition);\n int32_t j = i;\n\n while(i != end) {\n j = i;\n i = findNextIf(i + 1, aCondition);\n }\n\n return j;\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE Stack : public StaticContainer {\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~Stack() throw() {}\n\t\tvirtual T& SOLAIRE_EXPORT_CALL pushBack(const T&) throw() = 0;\n\t\tvirtual T SOLAIRE_EXPORT_CALL popBack() throw() = 0;\n\t\tvirtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;\n\n\t\tSOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL back() throw() {\n\t\t\treturn StaticContainer::operator[](StaticContainer::size() - 1);\n\t\t}\n\n\t\tSOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL back() const throw() {\n\t\t\treturn StaticContainer::operator[](StaticContainer::size() - 1);\n\t\t}\n\n SOLAIRE_FORCE_INLINE operator Stack&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const Stack&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE Deque : public Stack {\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~Deque() throw() {}\n\n\t\tvirtual T& SOLAIRE_EXPORT_CALL pushFront(const T&) throw() = 0;\n\t\tvirtual T SOLAIRE_EXPORT_CALL popFront() throw() = 0;\n\n\t\tSOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL front() throw() {\n\t\t\treturn StaticContainer::operator[](0);\n\t\t}\n\n\t\tSOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL front() const throw() {\n\t\t\treturn StaticContainer::operator[](0);\n\t\t}\n\n SOLAIRE_FORCE_INLINE operator Deque&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const Deque&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE List : public Deque {\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~List() throw() {}\n\n\t\tvirtual T& SOLAIRE_EXPORT_CALL insertBefore(const int32_t, const T&) throw() = 0;\n\t\tvirtual T& SOLAIRE_EXPORT_CALL insertAfter(const int32_t, const T&) throw() = 0;\n\t\tvirtual bool SOLAIRE_EXPORT_CALL erase(const int32_t) throw() = 0;\n\n SOLAIRE_FORCE_INLINE operator List&() throw() {\n return *reinterpret_cast*>(this);\n }\n\n SOLAIRE_FORCE_INLINE operator const List&() const throw() {\n return *reinterpret_cast*>(this);\n }\n\t};\n\n\ttemplate\n\tSOLAIRE_EXPORT_INTERFACE Map {\n public:\n typedef K KeyType;\n typedef K* KeyPointer;\n typedef K& KeyReference;\n typedef std::pair Entry;\n\tpublic:\n\t\tvirtual SOLAIRE_EXPORT_CALL ~Map() throw() {}\n\n\t\tvirtual T& SOLAIRE_EXPORT_CALL emplace(const K&, const T&) throw() = 0;\n\t\tvirtual const T& SOLAIRE_EXPORT_CALL get(const K&) const throw() = 0;\n\t\tvirtual T& SOLAIRE_EXPORT_CALL get(const K&) throw() = 0;\n\t\tvirtual bool SOLAIRE_EXPORT_CALL contains(const K&) const throw() = 0;\n\t\tvirtual bool SOLAIRE_EXPORT_CALL erase(const K&) throw() = 0;\n\n\t\tvirtual void SOLAIRE_EXPORT_CALL clear() throw() = 0;\n virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0;\n virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0;\n virtual SharedAllocation> getEntries() const throw() = 0;\n\t};\n\n}\n\n\n#endif\n<|endoftext|>"} {"text":"#ifndef SOLAIRE_ENCODER_HPP\n#define SOLAIRE_ENCODER_HPP\n\n\/\/Copyright 2015 Adam Smith\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\n\n\/\/ Contact :\n\/\/ Email : solairelibrary@mail.com\n\/\/ GitHub repository : https:\/\/github.com\/SolaireLibrary\/SolaireCPP\n\n\/*!\n\t\\file Encoder.hpp\n\t\\brief\n\t\\author\n\tCreated\t\t\t: Adam Smith\n\tLast modified\t: Adam Smith\n\t\\version 1.0\n\t\\date\n\tCreated\t\t\t: 16th January 2016\n\tLast Modified\t: 16th January 2016\n*\/\n\n#include \"Solaire\/Data\/ArrayList.hpp\"\n#include \"Solaire\/Encode\/GenericValue.hpp\"\n\nnamespace Solaire {\n\n\ttemplate\n\tstruct Encoder {\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator&, const GenericValue&) throw();\n\t static GenericValue encode(Allocator&, const T&) throw();\n\t};\n\n\ttemplate\n\tstatic typename Encoder::DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) {\n\t return Encoder::decode(aAllocator, aValue);\n\t}\n\n\ttemplate\n\tstatic GenericValue decode(Allocator& aAllocator, const T& aValue) {\n\t return Encoder::encode(aAllocator, aValue);\n\t}\n\n\t\/\/\/\/\n\n template<>\n\tstruct Encoder{\n\t typedef char DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return aValue.getChar();\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const char aValue) throw() {\n return GenericValue(aValue);\n\t }\n\t};\n\n template<>\n\tstruct Encoder{\n\t typedef bool DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return aValue.getBool();\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const bool aValue) throw() {\n return GenericValue(aValue);\n\t }\n\t};\n\n template\n\tstruct Encoder::value ||\n std::is_same::value ||\n std::is_same::value ||\n std::is_same::value\n >::type>{\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return static_cast(aValue.getUnsigned());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {\n return GenericValue(static_cast(aValue));\n\t }\n\t};\n\n template\n\tstruct Encoder::value ||\n std::is_same::value ||\n std::is_same::value ||\n std::is_same::value\n >::type>{\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return static_cast(aValue.getSigned());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {\n return GenericValue(static_cast(aValue));\n\t }\n\t};\n\n template\n\tstruct Encoder::value ||\n std::is_same::value\n >::type>{\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return static_cast(aValue.getDouble());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {\n return GenericValue(static_cast(aValue));\n\t }\n\t};\n\n\t\/\/\/\/\n\n\ttemplate\n\tstruct Encoder>{\n\t typedef ArrayList DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n ArrayList container(aAllocator);\n if(aValue.isArray()){\n const GenericArray& array_ = aValue.getArray();\n const int32_t size = array_.size();\n for(int32_t i = 0; i < size; ++i) {\n container.pushBack(Encoder::decode(aAllocator, array_[i]));\n }\n }\n return container;\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const StaticContainer& aContainer) throw() {\n GenericValue value;\n const GenericArray& array_ = value.setArray();\n const int32_t size = aContainer.size();\n for(int32_t i = 0; i < size; ++i) {\n array_.pushBack(Encoder::encode(aAllocator, aContainer[i]));\n }\n return value;\n\t }\n\t};\n}\n\n#endif\nString Encoder#ifndef SOLAIRE_ENCODER_HPP\n#define SOLAIRE_ENCODER_HPP\n\n\/\/Copyright 2015 Adam Smith\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\n\n\/\/ Contact :\n\/\/ Email : solairelibrary@mail.com\n\/\/ GitHub repository : https:\/\/github.com\/SolaireLibrary\/SolaireCPP\n\n\/*!\n\t\\file Encoder.hpp\n\t\\brief\n\t\\author\n\tCreated\t\t\t: Adam Smith\n\tLast modified\t: Adam Smith\n\t\\version 1.0\n\t\\date\n\tCreated\t\t\t: 16th January 2016\n\tLast Modified\t: 16th January 2016\n*\/\n\n#include \"Solaire\/Data\/ArrayList.hpp\"\n#include \"Solaire\/Encode\/GenericValue.hpp\"\n\nnamespace Solaire {\n\n\ttemplate\n\tstruct Encoder {\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator&, const GenericValue&) throw();\n\t static GenericValue encode(Allocator&, const T&) throw();\n\t};\n\n\ttemplate\n\tstatic typename Encoder::DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) {\n\t return Encoder::decode(aAllocator, aValue);\n\t}\n\n\ttemplate\n\tstatic GenericValue decode(Allocator& aAllocator, const T& aValue) {\n\t return Encoder::encode(aAllocator, aValue);\n\t}\n\n\t\/\/\/\/\n\n template<>\n\tstruct Encoder{\n\t typedef char DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return aValue.getChar();\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const char aValue) throw() {\n return GenericValue(aValue);\n\t }\n\t};\n\n template<>\n\tstruct Encoder{\n\t typedef bool DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return aValue.getBool();\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const bool aValue) throw() {\n return GenericValue(aValue);\n\t }\n\t};\n\n template\n\tstruct Encoder::value ||\n std::is_same::value ||\n std::is_same::value ||\n std::is_same::value\n >::type>{\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return static_cast(aValue.getUnsigned());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {\n return GenericValue(static_cast(aValue));\n\t }\n\t};\n\n template\n\tstruct Encoder::value ||\n std::is_same::value ||\n std::is_same::value ||\n std::is_same::value\n >::type>{\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return static_cast(aValue.getSigned());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {\n return GenericValue(static_cast(aValue));\n\t }\n\t};\n\n template\n\tstruct Encoder::value ||\n std::is_same::value\n >::type>{\n\t typedef T DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return static_cast(aValue.getDouble());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const T aValue) throw() {\n return GenericValue(static_cast(aValue));\n\t }\n\t};\n\n template<>\n\tstruct Encoder>{\n\t typedef CString DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n return CString(aValue.getString());\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const StringConstant& aValue) throw() {\n GenericValue value;\n \/\/! \\todo Assign string\n \/\/value.setString() = aValue;\n return value;\n\t }\n\t};\n\n\t\/\/\/\/\n\n\ttemplate\n\tstruct Encoder>{\n\t typedef ArrayList DecodeType;\n\n\t static DecodeType decode(Allocator& aAllocator, const GenericValue& aValue) throw() {\n ArrayList container(aAllocator);\n if(aValue.isArray()){\n const GenericArray& array_ = aValue.getArray();\n const int32_t size = array_.size();\n for(int32_t i = 0; i < size; ++i) {\n container.pushBack(Encoder::decode(aAllocator, array_[i]));\n }\n }\n return container;\n\t }\n\n\t static GenericValue encode(Allocator& aAllocator, const StaticContainer& aContainer) throw() {\n GenericValue value;\n const GenericArray& array_ = value.setArray();\n const int32_t size = aContainer.size();\n for(int32_t i = 0; i < size; ++i) {\n array_.pushBack(Encoder::encode(aAllocator, aContainer[i]));\n }\n return value;\n\t }\n\t};\n}\n\n#endif\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2010 Red Hat, Inc., Caolán McNamara \n * (initial developer)\n * Copyright (C) 2011 Markus Mohrhard \n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\n\nclass DBAccessTest : public test::BootstrapFixture, public unotest::MacrosTest\n{\npublic:\n DBAccessTest();\n\n void createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath);\n\n virtual void setUp();\n virtual void tearDown();\n\n void test();\n\n CPPUNIT_TEST_SUITE(DBAccessTest);\n CPPUNIT_TEST(test);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n rtl::OUString m_aBaseString;\n};\n\n\nvoid DBAccessTest::createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath)\n{\n rtl::OUString aSep(RTL_CONSTASCII_USTRINGPARAM(\"\/\"));\n rtl::OUStringBuffer aBuffer( getSrcRootURL() );\n aBuffer.append(m_aBaseString);\n aBuffer.append(aSep).append(aFileBase).append(aFileExtension);\n rFilePath = aBuffer.makeStringAndClear();\n}\n\nDBAccessTest::DBAccessTest()\n : m_aBaseString(RTL_CONSTASCII_USTRINGPARAM(\"\/dbaccess\/qa\/extras\/testdocuments\"))\n{\n}\n\nvoid DBAccessTest::test()\n{\n const rtl::OUString aFileNameBase(RTL_CONSTASCII_USTRINGPARAM(\"testdb.\"));\n const rtl::OUString aFileExtension(RTL_CONSTASCII_USTRINGPARAM(\"odb\"));\n rtl::OUString aFileName;\n createFileURL(aFileNameBase, aFileExtension, aFileName);\n uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileName);\n CPPUNIT_ASSERT(xComponent.is());\n}\n\nvoid DBAccessTest::setUp()\n{\n test::BootstrapFixture::setUp();\n\n \/\/ This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,\n \/\/ which is a private symbol to us, gets called\n mxDesktop = Reference( getMultiServiceFactory()->createInstance(\n rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.frame.Desktop\" ))), UNO_QUERY );\n CPPUNIT_ASSERT(mxDesktop.is());\n}\n\nvoid DBAccessTest::tearDown()\n{\n test::BootstrapFixture::tearDown();\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(DBAccessTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ndisable new test on win and mac since it is a test with UI\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2010 Red Hat, Inc., Caolán McNamara \n * (initial developer)\n * Copyright (C) 2011 Markus Mohrhard \n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\n\nclass DBAccessTest : public test::BootstrapFixture, public unotest::MacrosTest\n{\npublic:\n DBAccessTest();\n\n void createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath);\n\n virtual void setUp();\n virtual void tearDown();\n\n void test();\n\n CPPUNIT_TEST_SUITE(DBAccessTest);\n#if !defined(MACOSX) && !defined(WNT)\n CPPUNIT_TEST(test);\n#endif\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n rtl::OUString m_aBaseString;\n};\n\n\nvoid DBAccessTest::createFileURL(const rtl::OUString& aFileBase, const rtl::OUString& aFileExtension, rtl::OUString& rFilePath)\n{\n rtl::OUString aSep(RTL_CONSTASCII_USTRINGPARAM(\"\/\"));\n rtl::OUStringBuffer aBuffer( getSrcRootURL() );\n aBuffer.append(m_aBaseString);\n aBuffer.append(aSep).append(aFileBase).append(aFileExtension);\n rFilePath = aBuffer.makeStringAndClear();\n}\n\nDBAccessTest::DBAccessTest()\n : m_aBaseString(RTL_CONSTASCII_USTRINGPARAM(\"\/dbaccess\/qa\/extras\/testdocuments\"))\n{\n}\n\nvoid DBAccessTest::test()\n{\n const rtl::OUString aFileNameBase(RTL_CONSTASCII_USTRINGPARAM(\"testdb.\"));\n const rtl::OUString aFileExtension(RTL_CONSTASCII_USTRINGPARAM(\"odb\"));\n rtl::OUString aFileName;\n createFileURL(aFileNameBase, aFileExtension, aFileName);\n uno::Reference< lang::XComponent > xComponent = loadFromDesktop(aFileName);\n CPPUNIT_ASSERT(xComponent.is());\n}\n\nvoid DBAccessTest::setUp()\n{\n test::BootstrapFixture::setUp();\n\n \/\/ This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,\n \/\/ which is a private symbol to us, gets called\n mxDesktop = Reference( getMultiServiceFactory()->createInstance(\n rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.frame.Desktop\" ))), UNO_QUERY );\n CPPUNIT_ASSERT(mxDesktop.is());\n}\n\nvoid DBAccessTest::tearDown()\n{\n test::BootstrapFixture::tearDown();\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(DBAccessTest);\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: Object.cxx,v $\n *\n * $Revision: 1.18 $\n *\n * last change: $Author: hr $ $Date: 2004-11-09 12:12:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _CONNECTIVITY_JAVA_LANG_OBJJECT_HXX_\n#include \"java\/lang\/Class.hxx\"\n#endif\n#include \"connectivity\/CommonTools.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include \n#endif\n#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_\n#include \"java\/tools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_\n#include \"java\/sql\/SQLException.hxx\"\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include \n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include \n#endif\n#include \n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\nusing namespace connectivity;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\n\/\/ using namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::lang;\n\n\n\/\/ -----------------------------------------------------------------------------\n::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM2(const ::rtl::Reference< jvmaccess::VirtualMachine >& _rVM = ::rtl::Reference< jvmaccess::VirtualMachine >(),\n sal_Bool _bSet = sal_False)\n{\n static ::rtl::Reference< jvmaccess::VirtualMachine > s_VM;\n if ( _rVM.is() || _bSet )\n s_VM = _rVM;\n return s_VM;\n}\n\/\/ -----------------------------------------------------------------------------\n::rtl::Reference< jvmaccess::VirtualMachine > java_lang_Object::getVM(const Reference& _rxFactory)\n{\n ::rtl::Reference< jvmaccess::VirtualMachine > xVM = getJavaVM2();\n if ( !xVM.is() && _rxFactory.is() )\n xVM = getJavaVM2(::connectivity::getJavaVM(_rxFactory));\n\n return xVM;\n}\n\/\/ -----------------------------------------------------------------------------\ntypedef ::std::map TGuardMap;\nTGuardMap& lcl_getGuardMap()\n{\n static TGuardMap s_sMap;\n return s_sMap;\n}\n\/\/ -----------------------------------------------------------------------------\nTGuard getVMGuard()\n{\n TGuardMap& s_sMap = lcl_getGuardMap();\n\n oslThreadIdentifier id = osl_getThreadIdentifier(NULL);\n TGuardMap::iterator aFind = s_sMap.find(id);\n if ( aFind == s_sMap.end() )\n aFind = s_sMap.insert(TGuardMap::value_type(id,TGuard(new jvmaccess::VirtualMachine::AttachGuard(java_lang_Object::getVM())))).first;\n return aFind->second;\n}\n\/\/ -----------------------------------------------------------------------------\nSDBThreadAttach::SDBThreadAttach()\n : pEnv(NULL)\n{\n m_aGuard = getVMGuard();\n if ( m_aGuard.get() )\n pEnv = m_aGuard->getEnvironment();\n}\n\/\/ -----------------------------------------------------------------------------\nSDBThreadAttach::~SDBThreadAttach()\n{\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32& getJavaVMRefCount()\n{\n static sal_Int32 s_nRefCount = 0;\n return s_nRefCount;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SDBThreadAttach::addRef()\n{\n getJavaVMRefCount()++;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SDBThreadAttach::releaseRef()\n{\n getJavaVMRefCount()--;\n if ( getJavaVMRefCount() == 0 )\n {\n TGuardMap& s_sMap = lcl_getGuardMap();\n s_sMap.clear();\n getJavaVM2(::rtl::Reference< jvmaccess::VirtualMachine >(),sal_True);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ statische Variablen der Klasse:\njclass java_lang_Object::theClass = 0;\n\njclass java_lang_Object::getMyClass()\n{\n if( !theClass )\n {\n SDBThreadAttach t;\n\n if( !t.pEnv ) return (jclass)NULL;\n jclass tempClass = t.pEnv->FindClass( \"java\/lang\/Object\" );\n theClass = (jclass)t.pEnv->NewGlobalRef( tempClass );\n t.pEnv->DeleteLocalRef( tempClass );\n }\n return theClass;\n}\n\/\/ der eigentliche Konstruktor\njava_lang_Object::java_lang_Object(const Reference& _rxFactory)\n : object( 0 ),m_xFactory(_rxFactory)\n{\n}\n\n\/\/ der protected-Konstruktor fuer abgeleitete Klassen\njava_lang_Object::java_lang_Object( JNIEnv * pXEnv, jobject myObj )\n : object( NULL )\n{\n if( pXEnv && myObj )\n object = pXEnv->NewGlobalRef( myObj );\n}\n\njava_lang_Object::~java_lang_Object()\n{\n if( object )\n {\n SDBThreadAttach t;\n if( t.pEnv )\n t.pEnv->DeleteGlobalRef( object );\n }\n}\nvoid java_lang_Object::clearObject(JNIEnv& rEnv)\n{\n if( object )\n {\n rEnv.DeleteGlobalRef( object );\n object = NULL;\n }\n}\n\nvoid java_lang_Object::clearObject()\n{\n if( object )\n {\n SDBThreadAttach t;\n if( t.pEnv )\n t.pEnv->DeleteGlobalRef( object );\n object = NULL;\n }\n}\n\/\/ der protected-Konstruktor fuer abgeleitete Klassen\nvoid java_lang_Object::saveRef( JNIEnv * pXEnv, jobject myObj )\n{\n OSL_ENSURE( myObj, \"object in c++ -> Java Wrapper\" );\n if( pXEnv && myObj )\n object = pXEnv->NewGlobalRef( myObj );\n}\n\n\njava_lang_Class * java_lang_Object::getClass()\n{\n jobject out;\n SDBThreadAttach t;\n if( t.pEnv )\n {\n \/\/ temporaere Variable initialisieren\n static char * cSignature = \"()Ljava\/lang\/Class;\";\n static char * cMethodName = \"getClass\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,\"Unknown method id!\");\n if( mID )\n {\n out = t.pEnv->CallObjectMethodA( object, mID, NULL );\n ThrowSQLException(t.pEnv,NULL);\n return new java_lang_Class( t.pEnv, out );\n } \/\/mID\n } \/\/pEnv\n return NULL;\n}\n\n::rtl::OUString java_lang_Object::toString()\n{\n\n SDBThreadAttach t;\n ::rtl::OUString aStr;\n if( t.pEnv )\n {\n \/\/ temporaere Variable initialisieren\n static char * cSignature = \"()Ljava\/lang\/String;\";\n static char * cMethodName = \"toString\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,\"Unknown method id!\");\n if( mID )\n {\n jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);\n ThrowSQLException(t.pEnv,NULL);\n aStr = JavaString2String(t.pEnv,out);\n } \/\/mID\n } \/\/pEnv\n return aStr;\n}\n\/\/ --------------------------------------------------------------------------------\nvoid java_lang_Object::ThrowSQLException(JNIEnv * pEnv,const Reference< XInterface> & _rContext) throw(SQLException, RuntimeException)\n{\n jthrowable jThrow = NULL;\n if(pEnv && (jThrow = pEnv->ExceptionOccurred()))\n {\n pEnv->ExceptionClear();\/\/ we have to clear the exception here because we want to handle it itself\n if(pEnv->IsInstanceOf(jThrow,java_sql_SQLException_BASE::getMyClass()))\n {\n java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,jThrow);\n SQLException e( pException->getMessage(),\n _rContext,\n pException->getSQLState(),\n pException->getErrorCode(),\n Any()\n );\n delete pException;\n throw e;\n }\n else if(pEnv->IsInstanceOf(jThrow,java_lang_Throwable::getMyClass()))\n {\n java_lang_Throwable *pThrow = new java_lang_Throwable(pEnv,jThrow);\n ::rtl::OUString aMsg = pThrow->getMessage();\n if(!aMsg.getLength())\n aMsg = pThrow->getLocalizedMessage();\n if(!aMsg.getLength())\n aMsg = pThrow->toString();\n delete pThrow;\n throw SQLException(aMsg,_rContext,::rtl::OUString(),-1,Any());\n }\n else\n pEnv->DeleteLocalRef( jThrow );\n }\n}\n\n\nINTEGRATION: CWS dba22 (1.18.16); FILE MERGED 2005\/01\/14 12:35:22 oj 1.18.16.3: #i39671# attachguard for every call 2005\/01\/10 06:29:19 oj 1.18.16.2: compile error under linux 2005\/01\/04 11:45:21 oj 1.18.16.1: #i39671# erase guard when no longer needed\/*************************************************************************\n *\n * $RCSfile: Object.cxx,v $\n *\n * $Revision: 1.19 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 16:42:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _CONNECTIVITY_JAVA_LANG_OBJJECT_HXX_\n#include \"java\/lang\/Class.hxx\"\n#endif\n#include \"connectivity\/CommonTools.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include \n#endif\n#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_\n#include \"java\/tools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_\n#include \"java\/sql\/SQLException.hxx\"\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include \n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include \n#endif\n#include \n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\nusing namespace connectivity;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\n\/\/ using namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::lang;\n\n\n\/\/ -----------------------------------------------------------------------------\n::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM2(const ::rtl::Reference< jvmaccess::VirtualMachine >& _rVM = ::rtl::Reference< jvmaccess::VirtualMachine >(),\n sal_Bool _bSet = sal_False)\n{\n static ::rtl::Reference< jvmaccess::VirtualMachine > s_VM;\n if ( _rVM.is() || _bSet )\n s_VM = _rVM;\n return s_VM;\n}\n\/\/ -----------------------------------------------------------------------------\n::rtl::Reference< jvmaccess::VirtualMachine > java_lang_Object::getVM(const Reference& _rxFactory)\n{\n ::rtl::Reference< jvmaccess::VirtualMachine > xVM = getJavaVM2();\n if ( !xVM.is() && _rxFactory.is() )\n xVM = getJavaVM2(::connectivity::getJavaVM(_rxFactory));\n\n return xVM;\n}\n\/\/ -----------------------------------------------------------------------------\nSDBThreadAttach::SDBThreadAttach()\n : m_aGuard(java_lang_Object::getVM())\n , pEnv(NULL)\n{\n pEnv = m_aGuard.getEnvironment();\n OSL_ENSURE(pEnv,\"Environment is nULL!\");\n}\n\/\/ -----------------------------------------------------------------------------\nSDBThreadAttach::~SDBThreadAttach()\n{\n}\n\/\/ -----------------------------------------------------------------------------\noslInterlockedCount& getJavaVMRefCount()\n{\n static oslInterlockedCount s_nRefCount = 0;\n return s_nRefCount;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SDBThreadAttach::addRef()\n{\n osl_incrementInterlockedCount(&getJavaVMRefCount());\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SDBThreadAttach::releaseRef()\n{\n osl_decrementInterlockedCount(&getJavaVMRefCount());\n if ( getJavaVMRefCount() == 0 )\n {\n getJavaVM2(::rtl::Reference< jvmaccess::VirtualMachine >(),sal_True);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ statische Variablen der Klasse:\njclass java_lang_Object::theClass = 0;\n\njclass java_lang_Object::getMyClass()\n{\n if( !theClass )\n {\n SDBThreadAttach t;\n\n if( !t.pEnv ) return (jclass)NULL;\n jclass tempClass = t.pEnv->FindClass( \"java\/lang\/Object\" );\n theClass = (jclass)t.pEnv->NewGlobalRef( tempClass );\n t.pEnv->DeleteLocalRef( tempClass );\n }\n return theClass;\n}\n\/\/ der eigentliche Konstruktor\njava_lang_Object::java_lang_Object(const Reference& _rxFactory)\n : object( 0 ),m_xFactory(_rxFactory)\n{\n SDBThreadAttach::addRef();\n}\n\n\/\/ der protected-Konstruktor fuer abgeleitete Klassen\njava_lang_Object::java_lang_Object( JNIEnv * pXEnv, jobject myObj )\n : object( NULL )\n{\n SDBThreadAttach::addRef();\n if( pXEnv && myObj )\n object = pXEnv->NewGlobalRef( myObj );\n}\n\njava_lang_Object::~java_lang_Object()\n{\n if( object )\n {\n SDBThreadAttach t;\n if( t.pEnv )\n t.pEnv->DeleteGlobalRef( object );\n object = NULL;\n }\n SDBThreadAttach::releaseRef();\n}\nvoid java_lang_Object::clearObject(JNIEnv& rEnv)\n{\n if( object )\n {\n rEnv.DeleteGlobalRef( object );\n object = NULL;\n }\n}\n\nvoid java_lang_Object::clearObject()\n{\n if( object )\n {\n SDBThreadAttach t;\n if( t.pEnv )\n t.pEnv->DeleteGlobalRef( object );\n object = NULL;\n }\n}\n\/\/ der protected-Konstruktor fuer abgeleitete Klassen\nvoid java_lang_Object::saveRef( JNIEnv * pXEnv, jobject myObj )\n{\n OSL_ENSURE( myObj, \"object in c++ -> Java Wrapper\" );\n if( pXEnv && myObj )\n object = pXEnv->NewGlobalRef( myObj );\n}\n\n\njava_lang_Class * java_lang_Object::getClass()\n{\n jobject out;\n SDBThreadAttach t;\n if( t.pEnv )\n {\n \/\/ temporaere Variable initialisieren\n static char * cSignature = \"()Ljava\/lang\/Class;\";\n static char * cMethodName = \"getClass\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,\"Unknown method id!\");\n if( mID )\n {\n out = t.pEnv->CallObjectMethodA( object, mID, NULL );\n ThrowSQLException(t.pEnv,NULL);\n return new java_lang_Class( t.pEnv, out );\n } \/\/mID\n } \/\/pEnv\n return NULL;\n}\n\n::rtl::OUString java_lang_Object::toString()\n{\n\n SDBThreadAttach t;\n ::rtl::OUString aStr;\n if( t.pEnv )\n {\n \/\/ temporaere Variable initialisieren\n static char * cSignature = \"()Ljava\/lang\/String;\";\n static char * cMethodName = \"toString\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,\"Unknown method id!\");\n if( mID )\n {\n jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);\n ThrowSQLException(t.pEnv,NULL);\n aStr = JavaString2String(t.pEnv,out);\n } \/\/mID\n } \/\/pEnv\n return aStr;\n}\n\/\/ --------------------------------------------------------------------------------\nvoid java_lang_Object::ThrowSQLException(JNIEnv * pEnv,const Reference< XInterface> & _rContext) throw(SQLException, RuntimeException)\n{\n jthrowable jThrow = NULL;\n if(pEnv && (jThrow = pEnv->ExceptionOccurred()))\n {\n pEnv->ExceptionClear();\/\/ we have to clear the exception here because we want to handle it itself\n if(pEnv->IsInstanceOf(jThrow,java_sql_SQLException_BASE::getMyClass()))\n {\n java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,jThrow);\n SQLException e( pException->getMessage(),\n _rContext,\n pException->getSQLState(),\n pException->getErrorCode(),\n Any()\n );\n delete pException;\n throw e;\n }\n else if(pEnv->IsInstanceOf(jThrow,java_lang_Throwable::getMyClass()))\n {\n java_lang_Throwable *pThrow = new java_lang_Throwable(pEnv,jThrow);\n ::rtl::OUString aMsg = pThrow->getMessage();\n if(!aMsg.getLength())\n aMsg = pThrow->getLocalizedMessage();\n if(!aMsg.getLength())\n aMsg = pThrow->toString();\n delete pThrow;\n throw SQLException(aMsg,_rContext,::rtl::OUString(),-1,Any());\n }\n else\n pEnv->DeleteLocalRef( jThrow );\n }\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: String.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:13:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_\n#include \"java\/lang\/String.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_\n#include \"java\/tools.hxx\"\n#endif\nusing namespace connectivity;\n\/\/**************************************************************\n\/\/************ Class: java.lang.String\n\/\/**************************************************************\n\njclass java_lang_String::theClass = 0;\n\njava_lang_String::~java_lang_String()\n{}\n\njclass java_lang_String::getMyClass()\n{\n \/\/ die Klasse muss nur einmal geholt werden, daher statisch\n if( !theClass ){\n SDBThreadAttach t;\n if( !t.pEnv ) return (jclass)NULL;\n jclass tempClass = t.pEnv->FindClass(\"java\/lang\/String\");\n OSL_ENSURE(tempClass,\"Java : FindClass nicht erfolgreich!\");\n jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );\n t.pEnv->DeleteLocalRef( tempClass );\n saveClassRef( globClass );\n }\n return theClass;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid java_lang_String::saveClassRef( jclass pClass )\n{\n if( pClass==NULL )\n return;\n \/\/ der uebergebe Klassen-Handle ist schon global, daher einfach speichern\n theClass = pClass;\n}\n\/\/--------------------------------------------------------------------------\njava_lang_String::java_lang_String( const ::rtl::OUString& _par0 ): java_lang_Object( NULL, (jobject)NULL )\n{\n SDBThreadAttach t;\n if( !t.pEnv )\n return;\n jvalue args[1];\n \/\/ Parameter konvertieren\n args[0].l = convertwchar_tToJavaString(t.pEnv,_par0);\n \/\/ Java-Call fuer den Konstruktor absetzen\n \/\/ temporaere Variable initialisieren\n static char * cSignature = \"(Ljava\/lang\/String;)V\";\n jobject tempObj;\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), \"\", cSignature );OSL_ENSURE(mID,\"Unknown method id!\");\n tempObj = t.pEnv->NewObjectA( getMyClass(), mID, args );\n saveRef( t.pEnv, tempObj );\n t.pEnv->DeleteLocalRef( tempObj );\n t.pEnv->DeleteLocalRef((jstring)args[0].l);\n}\n\/\/--------------------------------------------------------------------------\njava_lang_String::operator ::rtl::OUString()\n{\n SDBThreadAttach t;\n if(!t.pEnv)\n return ::rtl::OUString();\n return JavaString2String(t.pEnv,(jstring)object);\n}\n\nINTEGRATION: CWS warnings01 (1.6.30); FILE MERGED 2005\/11\/21 10:07:50 fs 1.6.30.1: #i57457# warning-free code on unx*\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: String.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 01:36:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_JAVA_LANG_STRING_HXX_\n#include \"java\/lang\/String.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_\n#include \"java\/tools.hxx\"\n#endif\nusing namespace connectivity;\n\/\/**************************************************************\n\/\/************ Class: java.lang.String\n\/\/**************************************************************\n\njclass java_lang_String::theClass = 0;\n\njava_lang_String::~java_lang_String()\n{}\n\njclass java_lang_String::getMyClass()\n{\n \/\/ die Klasse muss nur einmal geholt werden, daher statisch\n if( !theClass ){\n SDBThreadAttach t;\n if( !t.pEnv ) return (jclass)NULL;\n jclass tempClass = t.pEnv->FindClass(\"java\/lang\/String\");\n OSL_ENSURE(tempClass,\"Java : FindClass nicht erfolgreich!\");\n jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );\n t.pEnv->DeleteLocalRef( tempClass );\n saveClassRef( globClass );\n }\n return theClass;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid java_lang_String::saveClassRef( jclass pClass )\n{\n if( pClass==NULL )\n return;\n \/\/ der uebergebe Klassen-Handle ist schon global, daher einfach speichern\n theClass = pClass;\n}\n\/\/--------------------------------------------------------------------------\njava_lang_String::java_lang_String( const ::rtl::OUString& _par0 ): java_lang_Object( NULL, (jobject)NULL )\n{\n SDBThreadAttach t;\n if( !t.pEnv )\n return;\n jvalue args[1];\n \/\/ Parameter konvertieren\n args[0].l = convertwchar_tToJavaString(t.pEnv,_par0);\n \/\/ Java-Call fuer den Konstruktor absetzen\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(Ljava\/lang\/String;)V\";\n jobject tempObj;\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), \"\", cSignature );OSL_ENSURE(mID,\"Unknown method id!\");\n tempObj = t.pEnv->NewObjectA( getMyClass(), mID, args );\n saveRef( t.pEnv, tempObj );\n t.pEnv->DeleteLocalRef( tempObj );\n t.pEnv->DeleteLocalRef((jstring)args[0].l);\n}\n\/\/--------------------------------------------------------------------------\njava_lang_String::operator ::rtl::OUString()\n{\n SDBThreadAttach t;\n if(!t.pEnv)\n return ::rtl::OUString();\n return JavaString2String(t.pEnv,(jstring)object);\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: TSkipDeletedSet.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-03-02 12:35:45 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_SKIPDELETEDSSET_HXX\n#define CONNECTIVITY_SKIPDELETEDSSET_HXX\n\n#ifndef CONNECTIVITY_TRESULTSETHELPER_HXX\n#include \"TResultSetHelper.hxx\"\n#endif\n\n#ifndef _RTL_ALLOC_H_\n#include \n#endif\n#include \n#include \n\nnamespace connectivity\n{\n \/**\n the class OSkipDeletedSet supports a general method to skip deleted rows\n *\/\n class OSkipDeletedSet\n {\n typedef ::std::map TInt2IntMap;\n TInt2IntMap m_aBookmarks; \/\/ map from postion to logical position\n ::std::vector m_aBookmarksPositions;\/\/ vector of iterators to position map, the order is the logical position\n IResultSetHelper* m_pHelper; \/\/ used for moving in the resultset\n\n sal_Bool moveAbsolute(sal_Int32 _nOffset,sal_Bool _bRetrieveData);\n public:\n OSkipDeletedSet(IResultSetHelper* _pHelper);\n ~OSkipDeletedSet();\n\n inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW( () )\n { return ::rtl_allocateMemory( nSize ); }\n inline static void * SAL_CALL operator new( size_t nSize,void* _pHint ) SAL_THROW( () )\n { return _pHint; }\n inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW( () )\n { ::rtl_freeMemory( pMem ); }\n inline static void SAL_CALL operator delete( void * pMem,void* _pHint ) SAL_THROW( () )\n { }\n\n \/**\n skipDeleted moves the resultset to the position defined by the parameters\n it garantees that the row isn't deleted\n @param\n IResultSetHelper::Movement _eCursorPosition in which direction the resultset should be moved\n sal_Int32 _nOffset the position relativ to the movement\n sal_Bool _bRetrieveData is true when the current row should be filled which data\n @return\n true when the movement was successful otherwise false\n *\/\n sal_Bool skipDeleted(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, sal_Bool _bRetrieveData);\n \/**\n clear the map and the vector used in this class\n *\/\n void clear();\n \/**\n getMappedPosition returns the mapped position of a logical position\n @param\n sal_Int32 _nPos the logical position\n\n @return the mapped position\n *\/\n sal_Int32 getMappedPosition(sal_Int32 _nPos) const;\n \/**\n insertNewPosition adds a new position to the map\n @param\n sal_Int32 _nPos the logical position\n *\/\n void insertNewPosition(sal_Int32 _nPos);\n \/**\n deletePosition deletes this position from the map and decrement all following positions\n @param\n sal_Int32 _nPos the logical position\n *\/\n void deletePosition(sal_Int32 _nPos);\n \/**\n getLastPosition returns the last position\n @return the last position\n *\/\n sal_Int32 getLastPosition() const { return m_aBookmarksPositions.size(); }\n };\n}\n#endif \/\/ CONNECTIVITY_SKIPDELETEDSSET_HXX\n\nINTEGRATION: CWS ooo19126 (1.4.162); FILE MERGED 2005\/09\/05 17:24:50 rt 1.4.162.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TSkipDeletedSet.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:40:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_SKIPDELETEDSSET_HXX\n#define CONNECTIVITY_SKIPDELETEDSSET_HXX\n\n#ifndef CONNECTIVITY_TRESULTSETHELPER_HXX\n#include \"TResultSetHelper.hxx\"\n#endif\n\n#ifndef _RTL_ALLOC_H_\n#include \n#endif\n#include \n#include \n\nnamespace connectivity\n{\n \/**\n the class OSkipDeletedSet supports a general method to skip deleted rows\n *\/\n class OSkipDeletedSet\n {\n typedef ::std::map TInt2IntMap;\n TInt2IntMap m_aBookmarks; \/\/ map from postion to logical position\n ::std::vector m_aBookmarksPositions;\/\/ vector of iterators to position map, the order is the logical position\n IResultSetHelper* m_pHelper; \/\/ used for moving in the resultset\n\n sal_Bool moveAbsolute(sal_Int32 _nOffset,sal_Bool _bRetrieveData);\n public:\n OSkipDeletedSet(IResultSetHelper* _pHelper);\n ~OSkipDeletedSet();\n\n inline static void * SAL_CALL operator new( size_t nSize ) SAL_THROW( () )\n { return ::rtl_allocateMemory( nSize ); }\n inline static void * SAL_CALL operator new( size_t nSize,void* _pHint ) SAL_THROW( () )\n { return _pHint; }\n inline static void SAL_CALL operator delete( void * pMem ) SAL_THROW( () )\n { ::rtl_freeMemory( pMem ); }\n inline static void SAL_CALL operator delete( void * pMem,void* _pHint ) SAL_THROW( () )\n { }\n\n \/**\n skipDeleted moves the resultset to the position defined by the parameters\n it garantees that the row isn't deleted\n @param\n IResultSetHelper::Movement _eCursorPosition in which direction the resultset should be moved\n sal_Int32 _nOffset the position relativ to the movement\n sal_Bool _bRetrieveData is true when the current row should be filled which data\n @return\n true when the movement was successful otherwise false\n *\/\n sal_Bool skipDeleted(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, sal_Bool _bRetrieveData);\n \/**\n clear the map and the vector used in this class\n *\/\n void clear();\n \/**\n getMappedPosition returns the mapped position of a logical position\n @param\n sal_Int32 _nPos the logical position\n\n @return the mapped position\n *\/\n sal_Int32 getMappedPosition(sal_Int32 _nPos) const;\n \/**\n insertNewPosition adds a new position to the map\n @param\n sal_Int32 _nPos the logical position\n *\/\n void insertNewPosition(sal_Int32 _nPos);\n \/**\n deletePosition deletes this position from the map and decrement all following positions\n @param\n sal_Int32 _nPos the logical position\n *\/\n void deletePosition(sal_Int32 _nPos);\n \/**\n getLastPosition returns the last position\n @return the last position\n *\/\n sal_Int32 getLastPosition() const { return m_aBookmarksPositions.size(); }\n };\n}\n#endif \/\/ CONNECTIVITY_SKIPDELETEDSSET_HXX\n\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_SEARCH_IMPL_ORGANIZED_NEIGHBOR_SEARCH_H_\n#define PCL_SEARCH_IMPL_ORGANIZED_NEIGHBOR_SEARCH_H_\n\n#include \"pcl\/search\/organized.h\"\n#include \n#include \"pcl\/common\/time.h\"\n#include \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::radiusSearch (int index,\n const double radius,\n std::vector &k_indices,\n std::vector &k_sqr_distances,\n unsigned int max_nn) const\n{\n const PointT& searchPoint = input_->points [index];\n return (radiusSearch (searchPoint, radius, k_indices, k_sqr_distances, max_nn));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::radiusSearch (const PointT &p_q,\n const double radius,\n std::vector &k_indices,\n std::vector &k_sqr_distances,\n unsigned int max_nn) const\n{\n if (projection_matrix_.coeffRef (0) == 0)\n {\n PCL_ERROR (\"[pcl::%s::radiusSearch] Invalid projection matrix. Probably input dataset was not organized!\\n\", getName ().c_str ());\n return (0);\n }\n\n \/\/ NAN test\n if (!pcl_isfinite (p_q.x) || !pcl_isfinite (p_q.y) || !pcl_isfinite (p_q.z))\n return (0);\n\n \/\/ search window\n unsigned left, right, top, bottom;\n \/\/unsigned x, y, idx;\n float squared_distance, squared_radius;\n\n k_indices.clear ();\n k_sqr_distances.clear ();\n\n squared_radius = radius * radius;\n\n this->getProjectedRadiusSearchBox (p_q, squared_radius, left, right, top, bottom);\n\n \/\/ iterate over search box\n if (max_nn == 0 || max_nn >= (unsigned int)input_->points.size ())\n max_nn = input_->points.size ();\n\n k_indices.reserve (max_nn);\n k_sqr_distances.reserve (max_nn);\n\n unsigned yEnd = (bottom + 1) * input_->width + right + 1;\n register unsigned idx = top * input_->width + left;\n unsigned skip = input_->width - right + left - 1;\n unsigned xEnd = idx - left + right + 1;\n\n for (; xEnd != yEnd; idx += skip, xEnd += input_->width)\n {\n for (; idx < xEnd; ++idx)\n {\n squared_distance = (input_->points[idx].getVector3fMap () - p_q.getVector3fMap ()).squaredNorm ();\n if (squared_distance <= squared_radius)\n {\n k_indices.push_back (idx);\n k_sqr_distances.push_back (squared_distance);\n \/\/ already done ?\n if (k_indices.size () == max_nn)\n return max_nn;\n }\n }\n }\n return (k_indices.size ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::nearestKSearch (const pcl::PointCloud &cloud,\n int index,\n int k,\n std::vector &k_indices,\n std::vector &k_sqr_distances) const\n{\n return (nearestKSearch (index, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::nearestKSearch (int index,\n int k,\n std::vector &k_indices,\n std::vector &k_distances) const\n{\n PCL_ERROR (\"[pcl::search::OrganizedNeighbor::nearestKSearch] Method not implemented!\\n\");\n return (0);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::search::OrganizedNeighbor::getProjectedRadiusSearchBox (const PointT& point,\n float squared_radius,\n unsigned &minX,\n unsigned &maxX,\n unsigned &minY,\n unsigned &maxY) const\n{\n Eigen::Vector3f q = KR_ * point.getVector3fMap () + projection_matrix_.block <3, 1> (0, 3);\n\n float a = squared_radius * KR_KRT_.coeff (8) - q [2] * q [2];\n float b = squared_radius * KR_KRT_.coeff (7) - q [1] * q [2];\n float c = squared_radius * KR_KRT_.coeff (4) - q [1] * q [1];\n\n \/\/ a and c are multiplied by two already => - 4ac -> - ac\n float det = b * b - a * c;\n if (det < 0)\n {\n minY = 0;\n maxY = input_->height - 1;\n }\n else\n {\n minY = (unsigned) std::max (0, (int) floor ((b + sqrt (det)) \/ a));\n maxY = (unsigned) std::min ((int) input_->height - 1, (int) ceil ((b - sqrt (det)) \/ a));\n }\n\n b = squared_radius * KR_KRT_.coeff (6) - q [0] * q [2];\n c = squared_radius * KR_KRT_.coeff (0) - q [0] * q [0];\n\n det = b * b - a * c;\n if (det < 0)\n {\n minX = 0;\n maxX = input_->width - 1;\n }\n else\n {\n minX = (unsigned) std::max (0, (int) floor ((b + sqrt (det)) \/ a));\n maxX = (unsigned) std::min ((int)input_->width - 1, (int) ceil ((b - sqrt (det)) \/ a));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate template void\npcl::search::OrganizedNeighbor::makeSymmetric (MatrixType& matrix, bool use_upper_triangular) const\n{\n if (use_upper_triangular)\n {\n matrix.coeffRef (4) = matrix.coeff (1);\n matrix.coeffRef (8) = matrix.coeff (2);\n matrix.coeffRef (9) = matrix.coeff (6);\n matrix.coeffRef (12) = matrix.coeff (3);\n matrix.coeffRef (13) = matrix.coeff (7);\n matrix.coeffRef (14) = matrix.coeff (11);\n }\n else\n {\n matrix.coeffRef (1) = matrix.coeff (4);\n matrix.coeffRef (2) = matrix.coeff (8);\n matrix.coeffRef (6) = matrix.coeff (9);\n matrix.coeffRef (3) = matrix.coeff (12);\n matrix.coeffRef (7) = matrix.coeff (13);\n matrix.coeffRef (11) = matrix.coeff (14);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::search::OrganizedNeighbor::estimateProjectionMatrix ()\n{\n \/\/ internally we calculate with double but store the result into float matrices.\n typedef double Scalar;\n projection_matrix_.setZero ();\n if (input_->height == 1 || input_->width == 1)\n {\n PCL_ERROR (\"[pcl::%s::estimateProjectionMatrix] Input dataset is not organized!\\n\", getName ().c_str ());\n return;\n }\n\n \/\/ we just want to use every 16th column and row -> skip = 2^4\n const unsigned int skip = input_->width >> 4;\n Eigen::Matrix A = Eigen::Matrix::Zero ();\n Eigen::Matrix B = Eigen::Matrix::Zero ();\n Eigen::Matrix C = Eigen::Matrix::Zero ();\n Eigen::Matrix D = Eigen::Matrix::Zero ();\n\n for (unsigned yIdx = 0, idx = 0; yIdx < input_->height; yIdx += skip, idx += input_->width * (skip-1))\n {\n for (unsigned xIdx = 0; xIdx < input_->width; xIdx += skip, idx += skip)\n {\n const PointT& point = input_->points[idx];\n if (isFinite (point))\n {\n Scalar xx = point.x * point.x;\n Scalar xy = point.x * point.y;\n Scalar xz = point.x * point.z;\n Scalar yy = point.y * point.y;\n Scalar yz = point.y * point.z;\n Scalar zz = point.z * point.z;\n Scalar xx_yy = xIdx * xIdx + yIdx * yIdx;\n\n A.coeffRef (0) += xx;\n A.coeffRef (1) += xy;\n A.coeffRef (2) += xz;\n A.coeffRef (3) += point.x;\n\n A.coeffRef (5) += yy;\n A.coeffRef (6) += yz;\n A.coeffRef (7) += point.y;\n\n A.coeffRef (10) += zz;\n A.coeffRef (11) += point.z;\n A.coeffRef (15) += 1.0;\n\n B.coeffRef (0) -= xx * xIdx;\n B.coeffRef (1) -= xy * xIdx;\n B.coeffRef (2) -= xz * xIdx;\n B.coeffRef (3) -= point.x * xIdx;\n\n B.coeffRef (5) -= yy * xIdx;\n B.coeffRef (6) -= yz * xIdx;\n B.coeffRef (7) -= point.y * xIdx;\n\n B.coeffRef (10) -= zz * xIdx;\n B.coeffRef (11) -= point.z * xIdx;\n\n B.coeffRef (15) -= xIdx;\n\n C.coeffRef (0) -= xx * yIdx;\n C.coeffRef (1) -= xy * yIdx;\n C.coeffRef (2) -= xz * yIdx;\n C.coeffRef (3) -= point.x * yIdx;\n\n C.coeffRef (5) -= yy * yIdx;\n C.coeffRef (6) -= yz * yIdx;\n C.coeffRef (7) -= point.y * yIdx;\n\n C.coeffRef (10) -= zz * yIdx;\n C.coeffRef (11) -= point.z * yIdx;\n\n C.coeffRef (15) -= yIdx;\n\n D.coeffRef (0) += xx * xx_yy;\n D.coeffRef (1) += xy * xx_yy;\n D.coeffRef (2) += xz * xx_yy;\n D.coeffRef (3) += point.x * xx_yy;\n\n D.coeffRef (5) += yy * xx_yy;\n D.coeffRef (6) += yz * xx_yy;\n D.coeffRef (7) += point.y * xx_yy;\n\n D.coeffRef (10) += zz * xx_yy;\n D.coeffRef (11) += point.z * xx_yy;\n\n D.coeffRef (15) += xx_yy;\n }\n }\n }\n\n makeSymmetric(A);\n makeSymmetric(B);\n makeSymmetric(C);\n makeSymmetric(D);\n\n Eigen::Matrix X = Eigen::Matrix::Zero ();\n X.topLeftCorner<4,4> () = A;\n X.block<4,4> (0, 8) = B;\n X.block<4,4> (8, 0) = B;\n X.block<4,4> (4, 4) = A;\n X.block<4,4> (4, 8) = C;\n X.block<4,4> (8, 4) = C;\n X.block<4,4> (8, 8) = D;\n\n Eigen::SelfAdjointEigenSolver > ei_symm(X);\n Eigen::Matrix eigen_vectors = ei_symm.eigenvectors();\n\n \/\/ check whether the residual MSE is low. If its high, the cloud was not captured from a projective device.\n Eigen::Matrix residual_sqr = eigen_vectors.col (0).transpose () * X * eigen_vectors.col (0);\n if ( residual_sqr.coeff (0) > eps_ * A.coeff (15))\n {\n PCL_ERROR (\"[pcl::%s::radiusSearch] Input dataset is not from a projective device!\\n\", getName ().c_str ());\n return;\n }\n\n projection_matrix_.coeffRef (0) = eigen_vectors.coeff (0);\n projection_matrix_.coeffRef (1) = eigen_vectors.coeff (12);\n projection_matrix_.coeffRef (2) = eigen_vectors.coeff (24);\n projection_matrix_.coeffRef (3) = eigen_vectors.coeff (36);\n projection_matrix_.coeffRef (4) = eigen_vectors.coeff (48);\n projection_matrix_.coeffRef (5) = eigen_vectors.coeff (60);\n projection_matrix_.coeffRef (6) = eigen_vectors.coeff (72);\n projection_matrix_.coeffRef (7) = eigen_vectors.coeff (84);\n projection_matrix_.coeffRef (8) = eigen_vectors.coeff (96);\n projection_matrix_.coeffRef (9) = eigen_vectors.coeff (108);\n projection_matrix_.coeffRef (10) = eigen_vectors.coeff (120);\n projection_matrix_.coeffRef (11) = eigen_vectors.coeff (132);\n\n if (projection_matrix_.coeff (0) < 0)\n projection_matrix_ *= -1.0;\n\n \/\/ get left 3x3 sub matrix, which contains K * R, with K = camera matrix = [[fx s cx] [0 fy cy] [0 0 1]]\n \/\/ and R being the rotation matrix\n KR_ = projection_matrix_.topLeftCorner <3, 3> ();\n\n \/\/ precalculate KR * KR^T needed by calculations during nn-search\n KR_KRT_ = KR_ * KR_.transpose ();\n}\n\n#define PCL_INSTANTIATE_OrganizedNeighbor(T) template class PCL_EXPORTS pcl::search::OrganizedNeighbor;\n\n#endif\nsmall bugfix in organized neighbor search\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_SEARCH_IMPL_ORGANIZED_NEIGHBOR_SEARCH_H_\n#define PCL_SEARCH_IMPL_ORGANIZED_NEIGHBOR_SEARCH_H_\n\n#include \"pcl\/search\/organized.h\"\n#include \n#include \"pcl\/common\/time.h\"\n#include \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::radiusSearch (int index,\n const double radius,\n std::vector &k_indices,\n std::vector &k_sqr_distances,\n unsigned int max_nn) const\n{\n const PointT& searchPoint = input_->points [index];\n return (radiusSearch (searchPoint, radius, k_indices, k_sqr_distances, max_nn));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::radiusSearch (const PointT &p_q,\n const double radius,\n std::vector &k_indices,\n std::vector &k_sqr_distances,\n unsigned int max_nn) const\n{\n if (projection_matrix_.coeffRef (0) == 0)\n {\n PCL_ERROR (\"[pcl::%s::radiusSearch] Invalid projection matrix. Probably input dataset was not organized!\\n\", getName ().c_str ());\n return (0);\n }\n\n \/\/ NAN test\n if (!pcl_isfinite (p_q.x) || !pcl_isfinite (p_q.y) || !pcl_isfinite (p_q.z))\n return (0);\n\n \/\/ search window\n unsigned left, right, top, bottom;\n \/\/unsigned x, y, idx;\n float squared_distance, squared_radius;\n\n k_indices.clear ();\n k_sqr_distances.clear ();\n\n squared_radius = radius * radius;\n\n this->getProjectedRadiusSearchBox (p_q, squared_radius, left, right, top, bottom);\n\n \/\/ iterate over search box\n if (max_nn == 0 || max_nn >= (unsigned int)input_->points.size ())\n max_nn = input_->points.size ();\n\n k_indices.reserve (max_nn);\n k_sqr_distances.reserve (max_nn);\n\n unsigned yEnd = (bottom + 1) * input_->width + right + 1;\n register unsigned idx = top * input_->width + left;\n unsigned skip = input_->width - right + left - 1;\n unsigned xEnd = idx - left + right + 1;\n\n for (; xEnd != yEnd; idx += skip, xEnd += input_->width)\n {\n for (; idx < xEnd; ++idx)\n {\n squared_distance = (input_->points[idx].getVector3fMap () - p_q.getVector3fMap ()).squaredNorm ();\n if (squared_distance <= squared_radius)\n {\n k_indices.push_back (idx);\n k_sqr_distances.push_back (squared_distance);\n \/\/ already done ?\n if (k_indices.size () == max_nn)\n return max_nn;\n }\n }\n }\n return (k_indices.size ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::nearestKSearch (const pcl::PointCloud &cloud,\n int index,\n int k,\n std::vector &k_indices,\n std::vector &k_sqr_distances) const\n{\n return (nearestKSearch (index, k, k_indices, k_sqr_distances));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate int\npcl::search::OrganizedNeighbor::nearestKSearch (int index,\n int k,\n std::vector &k_indices,\n std::vector &k_distances) const\n{\n PCL_ERROR (\"[pcl::search::OrganizedNeighbor::nearestKSearch] Method not implemented!\\n\");\n return (0);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::search::OrganizedNeighbor::getProjectedRadiusSearchBox (const PointT& point,\n float squared_radius,\n unsigned &minX,\n unsigned &maxX,\n unsigned &minY,\n unsigned &maxY) const\n{\n Eigen::Vector3f q = KR_ * point.getVector3fMap () + projection_matrix_.block <3, 1> (0, 3);\n\n float a = squared_radius * KR_KRT_.coeff (8) - q [2] * q [2];\n float b = squared_radius * KR_KRT_.coeff (7) - q [1] * q [2];\n float c = squared_radius * KR_KRT_.coeff (4) - q [1] * q [1];\n int min, max;\n \/\/ a and c are multiplied by two already => - 4ac -> - ac\n float det = b * b - a * c;\n if (det < 0)\n {\n minY = 0;\n maxY = input_->height - 1;\n }\n else\n {\n min = std::min ((int) floor ((b - sqrt (det)) \/ a), (int) floor ((b + sqrt (det)) \/ a));\n max = std::max ((int) ceil ((b - sqrt (det)) \/ a), (int) ceil ((b + sqrt (det)) \/ a));\n minY = (unsigned) std::min ((int) input_->height - 1, std::max (0, min));\n maxY = (unsigned) std::max (std::min ((int) input_->height - 1, max), 0);\n }\n\n b = squared_radius * KR_KRT_.coeff (6) - q [0] * q [2];\n c = squared_radius * KR_KRT_.coeff (0) - q [0] * q [0];\n\n det = b * b - a * c;\n if (det < 0)\n {\n minX = 0;\n maxX = input_->width - 1;\n }\n else\n {\n min = std::min ((int) floor ((b - sqrt (det)) \/ a), (int) floor ((b + sqrt (det)) \/ a));\n max = std::max ((int) ceil ((b - sqrt (det)) \/ a), (int) ceil ((b + sqrt (det)) \/ a));\n minX = (unsigned) std::min ((int)input_->width - 1, std::max (0, min));\n maxX = (unsigned) std::max (std::min ((int)input_->width - 1, max), 0);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate template void\npcl::search::OrganizedNeighbor::makeSymmetric (MatrixType& matrix, bool use_upper_triangular) const\n{\n if (use_upper_triangular)\n {\n matrix.coeffRef (4) = matrix.coeff (1);\n matrix.coeffRef (8) = matrix.coeff (2);\n matrix.coeffRef (9) = matrix.coeff (6);\n matrix.coeffRef (12) = matrix.coeff (3);\n matrix.coeffRef (13) = matrix.coeff (7);\n matrix.coeffRef (14) = matrix.coeff (11);\n }\n else\n {\n matrix.coeffRef (1) = matrix.coeff (4);\n matrix.coeffRef (2) = matrix.coeff (8);\n matrix.coeffRef (6) = matrix.coeff (9);\n matrix.coeffRef (3) = matrix.coeff (12);\n matrix.coeffRef (7) = matrix.coeff (13);\n matrix.coeffRef (11) = matrix.coeff (14);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::search::OrganizedNeighbor::estimateProjectionMatrix ()\n{\n \/\/ internally we calculate with double but store the result into float matrices.\n typedef double Scalar;\n projection_matrix_.setZero ();\n if (input_->height == 1 || input_->width == 1)\n {\n PCL_ERROR (\"[pcl::%s::estimateProjectionMatrix] Input dataset is not organized!\\n\", getName ().c_str ());\n return;\n }\n\n \/\/ we just want to use every 16th column and row -> skip = 2^4\n const unsigned int skip = input_->width >> 4;\n Eigen::Matrix A = Eigen::Matrix::Zero ();\n Eigen::Matrix B = Eigen::Matrix::Zero ();\n Eigen::Matrix C = Eigen::Matrix::Zero ();\n Eigen::Matrix D = Eigen::Matrix::Zero ();\n\n for (unsigned yIdx = 0, idx = 0; yIdx < input_->height; yIdx += skip, idx += input_->width * (skip-1))\n {\n for (unsigned xIdx = 0; xIdx < input_->width; xIdx += skip, idx += skip)\n {\n const PointT& point = input_->points[idx];\n if (isFinite (point))\n {\n Scalar xx = point.x * point.x;\n Scalar xy = point.x * point.y;\n Scalar xz = point.x * point.z;\n Scalar yy = point.y * point.y;\n Scalar yz = point.y * point.z;\n Scalar zz = point.z * point.z;\n Scalar xx_yy = xIdx * xIdx + yIdx * yIdx;\n\n A.coeffRef (0) += xx;\n A.coeffRef (1) += xy;\n A.coeffRef (2) += xz;\n A.coeffRef (3) += point.x;\n\n A.coeffRef (5) += yy;\n A.coeffRef (6) += yz;\n A.coeffRef (7) += point.y;\n\n A.coeffRef (10) += zz;\n A.coeffRef (11) += point.z;\n A.coeffRef (15) += 1.0;\n\n B.coeffRef (0) -= xx * xIdx;\n B.coeffRef (1) -= xy * xIdx;\n B.coeffRef (2) -= xz * xIdx;\n B.coeffRef (3) -= point.x * xIdx;\n\n B.coeffRef (5) -= yy * xIdx;\n B.coeffRef (6) -= yz * xIdx;\n B.coeffRef (7) -= point.y * xIdx;\n\n B.coeffRef (10) -= zz * xIdx;\n B.coeffRef (11) -= point.z * xIdx;\n\n B.coeffRef (15) -= xIdx;\n\n C.coeffRef (0) -= xx * yIdx;\n C.coeffRef (1) -= xy * yIdx;\n C.coeffRef (2) -= xz * yIdx;\n C.coeffRef (3) -= point.x * yIdx;\n\n C.coeffRef (5) -= yy * yIdx;\n C.coeffRef (6) -= yz * yIdx;\n C.coeffRef (7) -= point.y * yIdx;\n\n C.coeffRef (10) -= zz * yIdx;\n C.coeffRef (11) -= point.z * yIdx;\n\n C.coeffRef (15) -= yIdx;\n\n D.coeffRef (0) += xx * xx_yy;\n D.coeffRef (1) += xy * xx_yy;\n D.coeffRef (2) += xz * xx_yy;\n D.coeffRef (3) += point.x * xx_yy;\n\n D.coeffRef (5) += yy * xx_yy;\n D.coeffRef (6) += yz * xx_yy;\n D.coeffRef (7) += point.y * xx_yy;\n\n D.coeffRef (10) += zz * xx_yy;\n D.coeffRef (11) += point.z * xx_yy;\n\n D.coeffRef (15) += xx_yy;\n }\n }\n }\n\n makeSymmetric(A);\n makeSymmetric(B);\n makeSymmetric(C);\n makeSymmetric(D);\n\n Eigen::Matrix X = Eigen::Matrix::Zero ();\n X.topLeftCorner<4,4> () = A;\n X.block<4,4> (0, 8) = B;\n X.block<4,4> (8, 0) = B;\n X.block<4,4> (4, 4) = A;\n X.block<4,4> (4, 8) = C;\n X.block<4,4> (8, 4) = C;\n X.block<4,4> (8, 8) = D;\n\n Eigen::SelfAdjointEigenSolver > ei_symm(X);\n Eigen::Matrix eigen_vectors = ei_symm.eigenvectors();\n\n \/\/ check whether the residual MSE is low. If its high, the cloud was not captured from a projective device.\n Eigen::Matrix residual_sqr = eigen_vectors.col (0).transpose () * X * eigen_vectors.col (0);\n if ( residual_sqr.coeff (0) > eps_ * A.coeff (15))\n {\n PCL_ERROR (\"[pcl::%s::radiusSearch] Input dataset is not from a projective device!\\n\", getName ().c_str ());\n return;\n }\n\n projection_matrix_.coeffRef (0) = eigen_vectors.coeff (0);\n projection_matrix_.coeffRef (1) = eigen_vectors.coeff (12);\n projection_matrix_.coeffRef (2) = eigen_vectors.coeff (24);\n projection_matrix_.coeffRef (3) = eigen_vectors.coeff (36);\n projection_matrix_.coeffRef (4) = eigen_vectors.coeff (48);\n projection_matrix_.coeffRef (5) = eigen_vectors.coeff (60);\n projection_matrix_.coeffRef (6) = eigen_vectors.coeff (72);\n projection_matrix_.coeffRef (7) = eigen_vectors.coeff (84);\n projection_matrix_.coeffRef (8) = eigen_vectors.coeff (96);\n projection_matrix_.coeffRef (9) = eigen_vectors.coeff (108);\n projection_matrix_.coeffRef (10) = eigen_vectors.coeff (120);\n projection_matrix_.coeffRef (11) = eigen_vectors.coeff (132);\n\n if (projection_matrix_.coeff (0) < 0)\n projection_matrix_ *= -1.0;\n\n \/\/ get left 3x3 sub matrix, which contains K * R, with K = camera matrix = [[fx s cx] [0 fy cy] [0 0 1]]\n \/\/ and R being the rotation matrix\n KR_ = projection_matrix_.topLeftCorner <3, 3> ();\n\n \/\/ precalculate KR * KR^T needed by calculations during nn-search\n KR_KRT_ = KR_ * KR_.transpose ();\n}\n\n#define PCL_INSTANTIATE_OrganizedNeighbor(T) template class PCL_EXPORTS pcl::search::OrganizedNeighbor;\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"fusionrunner.h\"\n#include \"eventlogger.h\"\n#include \"fusionspec.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \nLOG_SETUP(\".searchcorespi.index.fusionrunner\");\n\nusing search::FixedSourceSelector;\nusing search::TuneFileAttributes;\nusing search::TuneFileIndexing;\nusing search::common::FileHeaderContext;\nusing search::common::SerialNumFileHeaderContext;\nusing search::index::Schema;\nusing search::queryeval::ISourceSelector;\nusing search::diskindex::SelectorArray;\nusing search::SerialNum;\nusing std::vector;\nusing vespalib::string;\nusing vespalib::JSONStringer;\n\nnamespace searchcorespi::index {\n\nFusionRunner::FusionRunner(const string &base_dir,\n const Schema &schema,\n const TuneFileAttributes &tuneFileAttributes,\n const FileHeaderContext &fileHeaderContext)\n : _diskLayout(base_dir),\n _schema(schema),\n _tuneFileAttributes(tuneFileAttributes),\n _fileHeaderContext(fileHeaderContext)\n{ }\n\nFusionRunner::~FusionRunner() {\n}\n\nnamespace {\n\nvoid readSelectorArray(const string &selector_name, SelectorArray &selector_array,\n const vector &id_map, uint32_t base_id) {\n FixedSourceSelector::UP selector =\n FixedSourceSelector::load(selector_name);\n if (base_id != selector->getBaseId()) {\n selector = selector->cloneAndSubtract(\"tmp_for_fusion\", base_id - selector->getBaseId());\n }\n\n const uint32_t num_docs = selector->getDocIdLimit();\n selector_array.reserve(num_docs);\n auto it = selector->createIterator();\n for (uint32_t i = 0; i < num_docs; ++i) {\n search::queryeval::Source source = it->getSource(i);\n assert(source < id_map.size());\n selector_array.push_back(id_map[source]);\n }\n}\n\nbool\nwriteFusionSelector(const IndexDiskLayout &diskLayout, uint32_t fusion_id,\n uint32_t highest_doc_id,\n const TuneFileAttributes &tuneFileAttributes,\n const FileHeaderContext &fileHeaderContext)\n{\n const search::queryeval::Source default_source = 0;\n FixedSourceSelector fusion_selector(default_source, \"fusion_selector\");\n fusion_selector.setSource(highest_doc_id, default_source);\n fusion_selector.setBaseId(fusion_id);\n string selector_name = IndexDiskLayout::getSelectorFileName(diskLayout.getFusionDir(fusion_id));\n if (!fusion_selector.extractSaveInfo(selector_name)->save(tuneFileAttributes, fileHeaderContext)) {\n LOG(warning, \"Unable to write source selector data for fusion.%u.\", fusion_id);\n return false;\n }\n return true;\n}\n} \/\/ namespace\n\nuint32_t\nFusionRunner::fuse(const FusionSpec &fusion_spec,\n SerialNum lastSerialNum,\n IIndexMaintainerOperations &operations)\n{\n const vector &ids = fusion_spec.flush_ids;\n if (ids.empty()) {\n return 0;\n }\n const uint32_t fusion_id = ids.back();\n const string fusion_dir = _diskLayout.getFusionDir(fusion_id);\n\n vector sources;\n vector id_map(fusion_id + 1);\n if (fusion_spec.last_fusion_id != 0) {\n id_map[0] = sources.size();\n sources.push_back(_diskLayout.getFusionDir(fusion_spec.last_fusion_id));\n }\n for (size_t i = 0; i < ids.size(); ++i) {\n id_map[ids[i] - fusion_spec.last_fusion_id] = sources.size();\n sources.push_back(_diskLayout.getFlushDir(ids[i]));\n }\n\n if (LOG_WOULD_LOG(event)) {\n EventLogger::diskFusionStart(sources, fusion_dir);\n }\n FastOS_Time timer;\n timer.SetNow();\n\n const string selector_name = IndexDiskLayout::getSelectorFileName(_diskLayout.getFlushDir(fusion_id));\n SelectorArray selector_array;\n readSelectorArray(selector_name, selector_array, id_map, fusion_spec.last_fusion_id);\n\n if (!operations.runFusion(_schema, fusion_dir, sources, selector_array, lastSerialNum)) {\n return 0;\n }\n\n const uint32_t highest_doc_id = selector_array.size() - 1;\n SerialNumFileHeaderContext fileHeaderContext(_fileHeaderContext, lastSerialNum);\n if (!writeFusionSelector(_diskLayout, fusion_id, highest_doc_id, _tuneFileAttributes, fileHeaderContext)) {\n return 0;\n }\n\n if (LOG_WOULD_LOG(event)) {\n EventLogger::diskFusionComplete(fusion_dir, (int64_t)timer.MilliSecsToNow());\n }\n return fusion_id;\n}\n\n}\nAdd workaround for source selector corruption.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"fusionrunner.h\"\n#include \"eventlogger.h\"\n#include \"fusionspec.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \nLOG_SETUP(\".searchcorespi.index.fusionrunner\");\n\nusing search::FixedSourceSelector;\nusing search::TuneFileAttributes;\nusing search::TuneFileIndexing;\nusing search::common::FileHeaderContext;\nusing search::common::SerialNumFileHeaderContext;\nusing search::index::Schema;\nusing search::queryeval::ISourceSelector;\nusing search::diskindex::SelectorArray;\nusing search::SerialNum;\nusing std::vector;\nusing vespalib::string;\nusing vespalib::JSONStringer;\n\nnamespace searchcorespi::index {\n\nFusionRunner::FusionRunner(const string &base_dir,\n const Schema &schema,\n const TuneFileAttributes &tuneFileAttributes,\n const FileHeaderContext &fileHeaderContext)\n : _diskLayout(base_dir),\n _schema(schema),\n _tuneFileAttributes(tuneFileAttributes),\n _fileHeaderContext(fileHeaderContext)\n{ }\n\nFusionRunner::~FusionRunner() {\n}\n\nnamespace {\n\nvoid readSelectorArray(const string &selector_name, SelectorArray &selector_array,\n const vector &id_map, uint32_t base_id) {\n FixedSourceSelector::UP selector =\n FixedSourceSelector::load(selector_name);\n if (base_id != selector->getBaseId()) {\n selector = selector->cloneAndSubtract(\"tmp_for_fusion\", base_id - selector->getBaseId());\n }\n\n const uint32_t num_docs = selector->getDocIdLimit();\n selector_array.reserve(num_docs);\n auto it = selector->createIterator();\n for (uint32_t i = 0; i < num_docs; ++i) {\n search::queryeval::Source source = it->getSource(i);\n \/\/ Workaround for source selector corruption.\n \/\/ Treat out of range source as last source.\n if (source >= id_map.size()) {\n source = id_map.size() - 1;\n }\n assert(source < id_map.size());\n selector_array.push_back(id_map[source]);\n }\n}\n\nbool\nwriteFusionSelector(const IndexDiskLayout &diskLayout, uint32_t fusion_id,\n uint32_t highest_doc_id,\n const TuneFileAttributes &tuneFileAttributes,\n const FileHeaderContext &fileHeaderContext)\n{\n const search::queryeval::Source default_source = 0;\n FixedSourceSelector fusion_selector(default_source, \"fusion_selector\");\n fusion_selector.setSource(highest_doc_id, default_source);\n fusion_selector.setBaseId(fusion_id);\n string selector_name = IndexDiskLayout::getSelectorFileName(diskLayout.getFusionDir(fusion_id));\n if (!fusion_selector.extractSaveInfo(selector_name)->save(tuneFileAttributes, fileHeaderContext)) {\n LOG(warning, \"Unable to write source selector data for fusion.%u.\", fusion_id);\n return false;\n }\n return true;\n}\n} \/\/ namespace\n\nuint32_t\nFusionRunner::fuse(const FusionSpec &fusion_spec,\n SerialNum lastSerialNum,\n IIndexMaintainerOperations &operations)\n{\n const vector &ids = fusion_spec.flush_ids;\n if (ids.empty()) {\n return 0;\n }\n const uint32_t fusion_id = ids.back();\n const string fusion_dir = _diskLayout.getFusionDir(fusion_id);\n\n vector sources;\n vector id_map(fusion_id + 1);\n if (fusion_spec.last_fusion_id != 0) {\n id_map[0] = sources.size();\n sources.push_back(_diskLayout.getFusionDir(fusion_spec.last_fusion_id));\n }\n for (size_t i = 0; i < ids.size(); ++i) {\n id_map[ids[i] - fusion_spec.last_fusion_id] = sources.size();\n sources.push_back(_diskLayout.getFlushDir(ids[i]));\n }\n\n if (LOG_WOULD_LOG(event)) {\n EventLogger::diskFusionStart(sources, fusion_dir);\n }\n FastOS_Time timer;\n timer.SetNow();\n\n const string selector_name = IndexDiskLayout::getSelectorFileName(_diskLayout.getFlushDir(fusion_id));\n SelectorArray selector_array;\n readSelectorArray(selector_name, selector_array, id_map, fusion_spec.last_fusion_id);\n\n if (!operations.runFusion(_schema, fusion_dir, sources, selector_array, lastSerialNum)) {\n return 0;\n }\n\n const uint32_t highest_doc_id = selector_array.size() - 1;\n SerialNumFileHeaderContext fileHeaderContext(_fileHeaderContext, lastSerialNum);\n if (!writeFusionSelector(_diskLayout, fusion_id, highest_doc_id, _tuneFileAttributes, fileHeaderContext)) {\n return 0;\n }\n\n if (LOG_WOULD_LOG(event)) {\n EventLogger::diskFusionComplete(fusion_dir, (int64_t)timer.MilliSecsToNow());\n }\n return fusion_id;\n}\n\n}\n<|endoftext|>"} {"text":"\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"startWidget.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"mainWindow\/mainWindow.h\"\n#include \"styledButton.h\"\n#include \"circleWidget.h\"\n#include \"brandManager\/brandManager.h\"\n\nusing namespace qReal;\n\nStartWidget::StartWidget(MainWindow *mainWindow, ProjectManager *projectManager)\n\t: mMainWindow(mainWindow)\n\t, mProjectManager(projectManager)\n\t, mProjectListSize(5) \/\/ TODO: Why 5?\n\t, mNewProjectButton(nullptr)\n\t, mOpenProjectButton(nullptr)\n\t, mOpenInterpreterButton(nullptr)\n\t, mCreateInterpreterButton(nullptr)\n{\n\tsetStyleSheet(BrandManager::styles()->startTabSubstrateBackgroundStyle());\n\tQWidget * const mainWidget = createMainWidget();\n\n\tQHBoxLayout * const mainLayout = new QHBoxLayout;\n\tmainLayout->addStretch(1);\n\tmainLayout->addWidget(mainWidget, 10);\n\tmainLayout->addStretch(1);\n\tsetLayout(mainLayout);\n}\n\nQWidget *StartWidget::createMainWidget()\n{\n\tQWidget * const result = new QWidget;\n\tresult->setStyleSheet(BrandManager::styles()->startTabBackgroundStyle());\n\n\tQWidget * const header = createHeader();\n\tmRecentProjectsWidget = createRecentProjectsWidget();\n\tQWidget * const projectsManagement = createProjectsManagementWidget();\n\n\tQVBoxLayout * mainLayout = new QVBoxLayout;\n\tQHBoxLayout * contentsLayout = new QHBoxLayout;\n\n\tmainLayout->addWidget(header);\n\tmainLayout->addLayout(contentsLayout);\n\tmainLayout->setStretch(1, 10);\n\tif (mRecentProjectsWidget) {\n\t\tcontentsLayout->addWidget(mRecentProjectsWidget);\n\t}\n\n\tcontentsLayout->addWidget(projectsManagement);\n\tcontentsLayout->setStretch(0, 10);\n\tcontentsLayout->setStretch(1, 20);\n\n\tresult->setLayout(mainLayout);\n\tresult->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);\n\treturn result;\n}\n\nQWidget *StartWidget::createHeader()\n{\n\tQLabel * const appName = new QLabel(BrandManager::applicationName());\n\tappName->setStyleSheet(BrandManager::styles()->startTabLabelLevel1Style());\n\n\tQLabel * const appLogo = new QLabel;\n\tappLogo->setFixedSize(200, 100);\n\tappLogo->setScaledContents(false);\n\tappLogo->setPixmap(QPixmap::fromImage(BrandManager::applicationLogo()).scaled(appLogo->size()\n\t\t\t, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n\n\tQHBoxLayout * const headerLayout = new QHBoxLayout;\n\theaderLayout->addWidget(appName);\n\theaderLayout->addStretch();\n\theaderLayout->addWidget(appLogo);\n\n\tQWidget * const header = new QWidget;\n\theader->setStyleSheet(BrandManager::styles()->startTabHeaderBackgroundStyle());\n\theader->setLayout(headerLayout);\n\n\treturn header;\n}\n\nQWidget *StartWidget::createRecentProjectsWidget()\n{\n\tconst QString recentProjects = SettingsManager::value(\"recentProjects\").toString();\n\tif (recentProjects.isEmpty() || mMainWindow->editorManager().editors().isEmpty()) {\n\t\treturn nullptr;\n\t}\n\n\tQWidget * const result = new QWidget;\n\tresult->setStyleSheet(BrandManager::styles()->startTabRecentProjectsBackgroundStyle());\n\tresult->setLayout(createRecentProjectsList(recentProjects));\n\treturn result;\n}\n\nQWidget *StartWidget::createProjectsManagementWidget()\n{\n\tmProjectsManagementLayout = new QBoxLayout(QBoxLayout::TopToBottom);\n\tmProjectsManagementLayout->addStretch();\n\n\tmOpenProjectButton = new StyledButton(tr(\"Open existing project\")\n\t\t\t, \":\/mainWindow\/images\/startTab\/open.svg\");\n\tconnect(mOpenProjectButton, &QPushButton::clicked, this, &StartWidget::openExistingProject);\n\tmProjectsManagementLayout->addWidget(mOpenProjectButton);\n\n\tconst Id theOnlyDiagram = mMainWindow->editorManager().theOnlyDiagram();\n\tif (!theOnlyDiagram.isNull()) {\n\t\tconst Id editor = mMainWindow->editorManager().editors()[0];\n\t\tconst QString diagramIdString = mMainWindow->editorManager().diagramNodeNameString(editor, theOnlyDiagram);\n\n\t\tmNewProjectButton = new StyledButton(tr(\"New project\"), \":\/mainWindow\/images\/startTab\/new.svg\");\n\t\tmProjectsManagementLayout->addWidget(mNewProjectButton);\n\n\t\tQSignalMapper *newProjectMapper = new QSignalMapper(this);\n\t\tnewProjectMapper->setMapping(mNewProjectButton, diagramIdString);\n\t\tconnect(mNewProjectButton, SIGNAL(clicked()), newProjectMapper, SLOT(map()));\n\t\tconnect(newProjectMapper, SIGNAL(mapped(QString)), this, SLOT(createProjectWithDiagram(QString)));\n\t} else {\n\t\tif (!mMainWindow->editorManager().editors().isEmpty()) {\n\t\t\tQWidget * const pluginsWidget = createPluginsList();\n\t\t\tmProjectsManagementLayout->addWidget(pluginsWidget, 1);\n\t\t} else {\n\t\t\tmOpenProjectButton->hide();\n\t\t}\n\t}\n\n\tmOpenInterpreterButton = new StyledButton(tr(\"Open interpreted diagram\")\n\t\t\t, \":\/mainWindow\/images\/startTab\/openInterpreted.svg\");\n\tmCreateInterpreterButton = new StyledButton(tr(\"Create interpreted diagram\")\n\t\t\t, \":\/mainWindow\/images\/startTab\/createInterpreted.svg\");\n\tconnect(mOpenInterpreterButton, SIGNAL(clicked()), this, SLOT(openInterpretedDiagram()));\n\tconnect(mCreateInterpreterButton, SIGNAL(clicked()), this, SLOT(createInterpretedDiagram()));\n\n\tmProjectsManagementLayout->addWidget(mCreateInterpreterButton);\n\tmProjectsManagementLayout->addWidget(mOpenInterpreterButton);\n\tmProjectsManagementLayout->addStretch();\n\n\tQWidget * const result = new QWidget;\n\tresult->setLayout(mProjectsManagementLayout);\n\tresult->setStyleSheet(BrandManager::styles()->startTabProjectsManagementBackgroundStyle());\n\treturn result;\n}\n\nvoid StartWidget::openRecentProject(const QString &fileName)\n{\n\tmProjectManager->open(fileName);\n}\n\nvoid StartWidget::openExistingProject()\n{\n\tmProjectManager->suggestToOpenExisting();\n}\n\nvoid StartWidget::createProjectWithDiagram(const QString &idString)\n{\n\tmMainWindow->createProject(idString);\n}\n\nQLayout *StartWidget::createRecentProjectsList(const QString &recentProjects)\n{\n\tQVBoxLayout * const mainLayout = new QVBoxLayout;\n\tQVBoxLayout * const recentProjectsLayout = new QVBoxLayout;\n\trecentProjectsLayout->setContentsMargins(0, 0, 0, 0);\n\n\tQLabel * const recentProjectsLabel = new QLabel(tr(\"Recent projects\"));\n\trecentProjectsLabel->setWordWrap(true);\n\trecentProjectsLabel->setStyleSheet(BrandManager::styles()->startTabLabelLevel2Style());\n\n\tQWidget * const spacer = new QWidget;\n\tspacer->setFixedHeight(10);\n\n\tmainLayout->addWidget(recentProjectsLabel);\n\tmainLayout->addWidget(spacer);\n\tmainLayout->addLayout(recentProjectsLayout);\n\n\tmainLayout->addStretch(0);\n\n\tQSignalMapper * const projectNameMapper = new QSignalMapper(this);\n\tconnect(projectNameMapper, SIGNAL(mapped(QString)), this, SLOT(openRecentProject(QString)));\n\n\tint i = 0;\n\tfor (const QString &project : recentProjects.split(\";\", QString::SkipEmptyParts)) {\n\t\tconst QString name = project.split(\"\/\").last().split(\"\\\\\").last();\n\t\tQPushButton * const projectItem = new StyledButton(name);\n\t\tprojectItem->setToolTip(project);\n\t\trecentProjectsLayout->addWidget(projectItem);\n\n\t\tprojectNameMapper->setMapping(projectItem, project);\n\t\tconnect(projectItem, SIGNAL(clicked()), projectNameMapper, SLOT(map()));\n\n\t\t++i;\n\t\tif (i >= mProjectListSize) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn mainLayout;\n}\n\nQWidget *StartWidget::createPluginsList()\n{\n\tQWidget * const circleWidget = new CircleWidget(QSize(70, 70), \":\/mainWindow\/images\/startTab\/new.svg\");\n\tcircleWidget->setStyleSheet(BrandManager::styles()->startTabButtonStyle());\n\n\tQVBoxLayout * const innerLayout = new QVBoxLayout;\n\tinnerLayout->addStretch();\n\tforeach (const Id &editor, mMainWindow->editorManager().editors()) {\n\t\tconst Id editorTmpId = Id::loadFromString(\"qrm:\/\" + editor.editor());\n\t\tforeach (const Id &diagram, mMainWindow->editorManager().diagrams(editorTmpId)) {\n\t\t\tQWidget * const pluginWidget = createPluginButton(editor, diagram, circleWidget);\n\t\t\tinnerLayout->addWidget(pluginWidget);\n\t\t}\n\t}\n\n\tinnerLayout->addStretch();\n\tinnerLayout->setContentsMargins(0, 0, 0, 0);\n\tinnerLayout->setMargin(0);\n\tinnerLayout->setSpacing(0);\n\n\tQWidget *innerWidget = new QWidget;\n\tinnerWidget->setLayout(innerLayout);\n\n\tQScrollArea *scrollArea = new QScrollArea;\n\tscrollArea->setFrameShape(QFrame::NoFrame);\n\tscrollArea->setWidgetResizable(true);\n\tscrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n\tscrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n\tscrollArea->setWidget(innerWidget);\n\n\tQHBoxLayout * const mainLayout = new QHBoxLayout;\n\tmainLayout->addWidget(circleWidget, Qt::AlignCenter);\n\tmainLayout->addWidget(scrollArea);\n\tmainLayout->setStretch(0, 0);\n\tmainLayout->setStretch(1, 10);\n\tmainLayout->setMargin(0);\n\n\tQWidget * const result = new QWidget;\n\tresult->setLayout(mainLayout);\n\n\treturn result;\n}\n\nQWidget *StartWidget::createPluginButton(const Id &editor, const Id &diagram, QWidget * const bindedImage)\n{\n\tconst EditorManagerInterface &editorManagerInterface = mMainWindow->editorManager();\n\n\tconst QString diagramName = editorManagerInterface.diagramName(editor.editor(), diagram.diagram());\n\tconst QString diagramNodeName = editorManagerInterface.diagramNodeName(editor.editor(), diagram.diagram());\n\n\tif (diagramNodeName.isEmpty()) {\n\t\treturn nullptr;\n\t}\n\n\tStyledButton * const result = new StyledButton(tr(\"Create \") + diagramName);\n\tresult->bindHighlightedOnHover(bindedImage);\n\tresult->setFocusPolicy(Qt::StrongFocus);\n\tresult->setStyleSheet(BrandManager::styles()->startTabButtonStyle());\n\tresult->setToolTip(tr(\"Editor: \") + editor.editor() + tr(\"; Diagram: \") + diagram.diagram());\n\n\tQSignalMapper *pluginMapper = new QSignalMapper(result);\n\tpluginMapper->setMapping(result, \"qrm:\/\" + editor.editor() + \"\/\" + diagram.diagram() + \"\/\" + diagramNodeName);\n\tconnect(result, SIGNAL(clicked()), pluginMapper, SLOT(map()));\n\tconnect(pluginMapper, SIGNAL(mapped(QString)), mMainWindow, SLOT(createDiagram(QString)));\n\n\treturn result;\n}\n\nvoid StartWidget::openInterpretedDiagram()\n{\n\thide();\n\tconst QString fileName = mProjectManager->openFileName(tr(\"Select file with metamodel to open\"));\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\n\tif (!fileName.isEmpty()) {\n\t\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(fileName));\n\t\tQStringList interpreterDiagramsList;\n\t\tforeach (const Id &editor, editorManagerProxy.editors()) {\n\t\t\tforeach (const Id &diagram, editorManagerProxy.diagrams(editor)) {\n\t\t\t\tconst QString diagramNodeName = editorManagerProxy.diagramNodeName(editor.editor(), diagram.diagram());\n\t\t\t\tif (diagramNodeName.isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tinterpreterDiagramsList.append(\"qrm:\/\" + editor.editor() + \"\/\"\n\t\t\t\t\t\t+ diagram.diagram() + \"\/\" + diagramNodeName);\n\t\t\t}\n\t\t}\n\n\t\tmMainWindow->initInterpretedPlugins();\n\n\t\tforeach (const QString &interpreterIdString, interpreterDiagramsList) {\n\t\t\t\/\/ TODO: ???\n\t\t\tmMainWindow->models().repoControlApi().exterminate();\n\t\t\tmMainWindow->models().reinit();\n\t\t\tmMainWindow->loadPlugins();\n\t\t\tmMainWindow->createDiagram(interpreterIdString);\n\t\t}\n\t} else {\n\t\tshow();\n\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nvoid StartWidget::createInterpretedDiagram()\n{\n\thide();\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(\"\"));\n\tbool ok = false;\n\tQString name = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t, QLineEdit::Normal, \"\", &ok);\n\twhile (ok && name.isEmpty()) {\n\t\tname = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t\t, QLineEdit::Normal, \"\", &ok);\n\t}\n\n\tif (ok) {\n\t\tQPair editorAndDiagram = editorManagerProxy.createEditorAndDiagram(name);\n\t\tmMainWindow->addEditorElementsToPalette(editorAndDiagram.first, editorAndDiagram.second);\n\t\tmMainWindow->models().repoControlApi().exterminate();\n\t\tmMainWindow->models().reinit();\n\t\tmMainWindow->loadPlugins();\n\t\tmMainWindow->initInterpretedPlugins();\n\t} else {\n\t\tshow();\n\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nvoid StartWidget::setVisibleForInterpreterButton(const bool visible)\n{\n\tif (!visible) {\n\t\t\/\/\/ @todo: For some reason setVisible on interpreter buttons still leaves them visible.\n\t\t\/\/\/ This surely can be fixed and then setVisible(visible) call must be restored,\n\t\t\/\/\/ but for now working it arround...\n\t\tdelete mOpenInterpreterButton;\n\t\tdelete mCreateInterpreterButton;\n\t\tmOpenInterpreterButton = nullptr;\n\t\tmCreateInterpreterButton = nullptr;\n\t}\n\n\tconst int editorsCount = mMainWindow->editorManager().editors().count();\n\tQList toCentralize;\n\tbool needLayoutHorizontally = false;\n\tif (visible) {\n\t\tneedLayoutHorizontally = editorsCount == 0;\n\t\ttoCentralize << mCreateInterpreterButton << mOpenInterpreterButton;\n\t} else {\n\t\tneedLayoutHorizontally = editorsCount == 1 && !mRecentProjectsWidget;\n\t\ttoCentralize << mNewProjectButton << mOpenProjectButton;\n\t}\n\n\tif (needLayoutHorizontally) {\n\t\tfor (QPushButton * const button : toCentralize) {\n\t\t\tcentralizeButton(button);\n\t\t}\n\n\t\tmProjectsManagementLayout->setDirection(QBoxLayout::LeftToRight);\n\t}\n}\n\nvoid StartWidget::centralizeButton(QPushButton * const styledButton)\n{\n\tif (!styledButton) {\n\t\treturn;\n\t}\n\n\tQBoxLayout * const layout = static_cast(styledButton->layout());\n\tlayout->setDirection(QBoxLayout::TopToBottom);\n\tQWidget * const icon = layout->itemAt(0)->widget();\n\tQLabel * const label = static_cast(layout->itemAt(1)->widget());\n\tlabel->setAlignment(Qt::AlignHCenter);\n\tlayout->setAlignment(icon, Qt::AlignHCenter | Qt::AlignBottom);\n\tlayout->setAlignment(label, Qt::AlignHCenter | Qt::AlignTop);\n\tlayout->activate();\n\tlayout->update();\n\tstyledButton->update();\n\n\tmProjectsManagementLayout->setAlignment(styledButton, Qt::AlignVCenter);\n\tconst int index = mProjectsManagementLayout->indexOf(styledButton);\n\tmProjectsManagementLayout->setStretch(index, 10000);\n}\n\nvoid StartWidget::paintEvent(QPaintEvent *event)\n{\n\tQ_UNUSED(event);\n\n\tQStyleOption styleOption;\n\tstyleOption.initFrom(this);\n\tQPainter painter(this);\n\tstyle()->drawPrimitive(QStyle::PE_Widget, &styleOption, &painter, this);\n}\nFixed segfaults after creating diagrams of two different types first from start widget and then from editors dialog\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"startWidget.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"mainWindow\/mainWindow.h\"\n#include \"styledButton.h\"\n#include \"circleWidget.h\"\n#include \"brandManager\/brandManager.h\"\n\nusing namespace qReal;\n\nStartWidget::StartWidget(MainWindow *mainWindow, ProjectManager *projectManager)\n\t: mMainWindow(mainWindow)\n\t, mProjectManager(projectManager)\n\t, mProjectListSize(5) \/\/ TODO: Why 5?\n\t, mNewProjectButton(nullptr)\n\t, mOpenProjectButton(nullptr)\n\t, mOpenInterpreterButton(nullptr)\n\t, mCreateInterpreterButton(nullptr)\n{\n\tsetStyleSheet(BrandManager::styles()->startTabSubstrateBackgroundStyle());\n\tQWidget * const mainWidget = createMainWidget();\n\n\tQHBoxLayout * const mainLayout = new QHBoxLayout;\n\tmainLayout->addStretch(1);\n\tmainLayout->addWidget(mainWidget, 10);\n\tmainLayout->addStretch(1);\n\tsetLayout(mainLayout);\n}\n\nQWidget *StartWidget::createMainWidget()\n{\n\tQWidget * const result = new QWidget;\n\tresult->setStyleSheet(BrandManager::styles()->startTabBackgroundStyle());\n\n\tQWidget * const header = createHeader();\n\tmRecentProjectsWidget = createRecentProjectsWidget();\n\tQWidget * const projectsManagement = createProjectsManagementWidget();\n\n\tQVBoxLayout * mainLayout = new QVBoxLayout;\n\tQHBoxLayout * contentsLayout = new QHBoxLayout;\n\n\tmainLayout->addWidget(header);\n\tmainLayout->addLayout(contentsLayout);\n\tmainLayout->setStretch(1, 10);\n\tif (mRecentProjectsWidget) {\n\t\tcontentsLayout->addWidget(mRecentProjectsWidget);\n\t}\n\n\tcontentsLayout->addWidget(projectsManagement);\n\tcontentsLayout->setStretch(0, 10);\n\tcontentsLayout->setStretch(1, 20);\n\n\tresult->setLayout(mainLayout);\n\tresult->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);\n\treturn result;\n}\n\nQWidget *StartWidget::createHeader()\n{\n\tQLabel * const appName = new QLabel(BrandManager::applicationName());\n\tappName->setStyleSheet(BrandManager::styles()->startTabLabelLevel1Style());\n\n\tQLabel * const appLogo = new QLabel;\n\tappLogo->setFixedSize(200, 100);\n\tappLogo->setScaledContents(false);\n\tappLogo->setPixmap(QPixmap::fromImage(BrandManager::applicationLogo()).scaled(appLogo->size()\n\t\t\t, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n\n\tQHBoxLayout * const headerLayout = new QHBoxLayout;\n\theaderLayout->addWidget(appName);\n\theaderLayout->addStretch();\n\theaderLayout->addWidget(appLogo);\n\n\tQWidget * const header = new QWidget;\n\theader->setStyleSheet(BrandManager::styles()->startTabHeaderBackgroundStyle());\n\theader->setLayout(headerLayout);\n\n\treturn header;\n}\n\nQWidget *StartWidget::createRecentProjectsWidget()\n{\n\tconst QString recentProjects = SettingsManager::value(\"recentProjects\").toString();\n\tif (recentProjects.isEmpty() || mMainWindow->editorManager().editors().isEmpty()) {\n\t\treturn nullptr;\n\t}\n\n\tQWidget * const result = new QWidget;\n\tresult->setStyleSheet(BrandManager::styles()->startTabRecentProjectsBackgroundStyle());\n\tresult->setLayout(createRecentProjectsList(recentProjects));\n\treturn result;\n}\n\nQWidget *StartWidget::createProjectsManagementWidget()\n{\n\tmProjectsManagementLayout = new QBoxLayout(QBoxLayout::TopToBottom);\n\tmProjectsManagementLayout->addStretch();\n\n\tmOpenProjectButton = new StyledButton(tr(\"Open existing project\")\n\t\t\t, \":\/mainWindow\/images\/startTab\/open.svg\");\n\tconnect(mOpenProjectButton, &QPushButton::clicked, this, &StartWidget::openExistingProject);\n\tmProjectsManagementLayout->addWidget(mOpenProjectButton);\n\n\tconst Id theOnlyDiagram = mMainWindow->editorManager().theOnlyDiagram();\n\tif (!theOnlyDiagram.isNull()) {\n\t\tconst Id editor = mMainWindow->editorManager().editors()[0];\n\t\tconst QString diagramIdString = mMainWindow->editorManager().diagramNodeNameString(editor, theOnlyDiagram);\n\n\t\tmNewProjectButton = new StyledButton(tr(\"New project\"), \":\/mainWindow\/images\/startTab\/new.svg\");\n\t\tmProjectsManagementLayout->addWidget(mNewProjectButton);\n\n\t\tQSignalMapper *newProjectMapper = new QSignalMapper(this);\n\t\tnewProjectMapper->setMapping(mNewProjectButton, diagramIdString);\n\t\tconnect(mNewProjectButton, SIGNAL(clicked()), newProjectMapper, SLOT(map()));\n\t\tconnect(newProjectMapper, SIGNAL(mapped(QString)), this, SLOT(createProjectWithDiagram(QString)));\n\t} else {\n\t\tif (!mMainWindow->editorManager().editors().isEmpty()) {\n\t\t\tQWidget * const pluginsWidget = createPluginsList();\n\t\t\tmProjectsManagementLayout->addWidget(pluginsWidget, 1);\n\t\t} else {\n\t\t\tmOpenProjectButton->hide();\n\t\t}\n\t}\n\n\tmOpenInterpreterButton = new StyledButton(tr(\"Open interpreted diagram\")\n\t\t\t, \":\/mainWindow\/images\/startTab\/openInterpreted.svg\");\n\tmCreateInterpreterButton = new StyledButton(tr(\"Create interpreted diagram\")\n\t\t\t, \":\/mainWindow\/images\/startTab\/createInterpreted.svg\");\n\tconnect(mOpenInterpreterButton, SIGNAL(clicked()), this, SLOT(openInterpretedDiagram()));\n\tconnect(mCreateInterpreterButton, SIGNAL(clicked()), this, SLOT(createInterpretedDiagram()));\n\n\tmProjectsManagementLayout->addWidget(mCreateInterpreterButton);\n\tmProjectsManagementLayout->addWidget(mOpenInterpreterButton);\n\tmProjectsManagementLayout->addStretch();\n\n\tQWidget * const result = new QWidget;\n\tresult->setLayout(mProjectsManagementLayout);\n\tresult->setStyleSheet(BrandManager::styles()->startTabProjectsManagementBackgroundStyle());\n\treturn result;\n}\n\nvoid StartWidget::openRecentProject(const QString &fileName)\n{\n\tmProjectManager->open(fileName);\n}\n\nvoid StartWidget::openExistingProject()\n{\n\tmProjectManager->suggestToOpenExisting();\n}\n\nvoid StartWidget::createProjectWithDiagram(const QString &idString)\n{\n\tmMainWindow->createProject(idString);\n}\n\nQLayout *StartWidget::createRecentProjectsList(const QString &recentProjects)\n{\n\tQVBoxLayout * const mainLayout = new QVBoxLayout;\n\tQVBoxLayout * const recentProjectsLayout = new QVBoxLayout;\n\trecentProjectsLayout->setContentsMargins(0, 0, 0, 0);\n\n\tQLabel * const recentProjectsLabel = new QLabel(tr(\"Recent projects\"));\n\trecentProjectsLabel->setWordWrap(true);\n\trecentProjectsLabel->setStyleSheet(BrandManager::styles()->startTabLabelLevel2Style());\n\n\tQWidget * const spacer = new QWidget;\n\tspacer->setFixedHeight(10);\n\n\tmainLayout->addWidget(recentProjectsLabel);\n\tmainLayout->addWidget(spacer);\n\tmainLayout->addLayout(recentProjectsLayout);\n\n\tmainLayout->addStretch(0);\n\n\tQSignalMapper * const projectNameMapper = new QSignalMapper(this);\n\tconnect(projectNameMapper, SIGNAL(mapped(QString)), this, SLOT(openRecentProject(QString)));\n\n\tint i = 0;\n\tfor (const QString &project : recentProjects.split(\";\", QString::SkipEmptyParts)) {\n\t\tconst QString name = project.split(\"\/\").last().split(\"\\\\\").last();\n\t\tQPushButton * const projectItem = new StyledButton(name);\n\t\tprojectItem->setToolTip(project);\n\t\trecentProjectsLayout->addWidget(projectItem);\n\n\t\tprojectNameMapper->setMapping(projectItem, project);\n\t\tconnect(projectItem, SIGNAL(clicked()), projectNameMapper, SLOT(map()));\n\n\t\t++i;\n\t\tif (i >= mProjectListSize) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn mainLayout;\n}\n\nQWidget *StartWidget::createPluginsList()\n{\n\tQWidget * const circleWidget = new CircleWidget(QSize(70, 70), \":\/mainWindow\/images\/startTab\/new.svg\");\n\tcircleWidget->setStyleSheet(BrandManager::styles()->startTabButtonStyle());\n\n\tQVBoxLayout * const innerLayout = new QVBoxLayout;\n\tinnerLayout->addStretch();\n\tforeach (const Id &editor, mMainWindow->editorManager().editors()) {\n\t\tconst Id editorTmpId = Id::loadFromString(\"qrm:\/\" + editor.editor());\n\t\tforeach (const Id &diagram, mMainWindow->editorManager().diagrams(editorTmpId)) {\n\t\t\tQWidget * const pluginWidget = createPluginButton(editor, diagram, circleWidget);\n\t\t\tinnerLayout->addWidget(pluginWidget);\n\t\t}\n\t}\n\n\tinnerLayout->addStretch();\n\tinnerLayout->setContentsMargins(0, 0, 0, 0);\n\tinnerLayout->setMargin(0);\n\tinnerLayout->setSpacing(0);\n\n\tQWidget *innerWidget = new QWidget;\n\tinnerWidget->setLayout(innerLayout);\n\n\tQScrollArea *scrollArea = new QScrollArea;\n\tscrollArea->setFrameShape(QFrame::NoFrame);\n\tscrollArea->setWidgetResizable(true);\n\tscrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n\tscrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n\tscrollArea->setWidget(innerWidget);\n\n\tQHBoxLayout * const mainLayout = new QHBoxLayout;\n\tmainLayout->addWidget(circleWidget, Qt::AlignCenter);\n\tmainLayout->addWidget(scrollArea);\n\tmainLayout->setStretch(0, 0);\n\tmainLayout->setStretch(1, 10);\n\tmainLayout->setMargin(0);\n\n\tQWidget * const result = new QWidget;\n\tresult->setLayout(mainLayout);\n\n\treturn result;\n}\n\nQWidget *StartWidget::createPluginButton(const Id &editor, const Id &diagram, QWidget * const bindedImage)\n{\n\tconst EditorManagerInterface &editorManagerInterface = mMainWindow->editorManager();\n\n\tconst QString diagramName = editorManagerInterface.diagramName(editor.editor(), diagram.diagram());\n\tconst QString diagramNodeName = editorManagerInterface.diagramNodeName(editor.editor(), diagram.diagram());\n\n\tif (diagramNodeName.isEmpty()) {\n\t\treturn nullptr;\n\t}\n\n\tStyledButton * const result = new StyledButton(tr(\"Create \") + diagramName);\n\tresult->bindHighlightedOnHover(bindedImage);\n\tresult->setFocusPolicy(Qt::StrongFocus);\n\tresult->setStyleSheet(BrandManager::styles()->startTabButtonStyle());\n\tresult->setToolTip(tr(\"Editor: \") + editor.editor() + tr(\"; Diagram: \") + diagram.diagram());\n\n\tQSignalMapper *pluginMapper = new QSignalMapper(result);\n\tpluginMapper->setMapping(result, \"qrm:\/\" + editor.editor() + \"\/\" + diagram.diagram() + \"\/\" + diagramNodeName);\n\tconnect(result, SIGNAL(clicked()), pluginMapper, SLOT(map()));\n\tconnect(pluginMapper, SIGNAL(mapped(QString)), mMainWindow, SLOT(createProject(QString)));\n\n\treturn result;\n}\n\nvoid StartWidget::openInterpretedDiagram()\n{\n\thide();\n\tconst QString fileName = mProjectManager->openFileName(tr(\"Select file with metamodel to open\"));\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\n\tif (!fileName.isEmpty()) {\n\t\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(fileName));\n\t\tQStringList interpreterDiagramsList;\n\t\tforeach (const Id &editor, editorManagerProxy.editors()) {\n\t\t\tforeach (const Id &diagram, editorManagerProxy.diagrams(editor)) {\n\t\t\t\tconst QString diagramNodeName = editorManagerProxy.diagramNodeName(editor.editor(), diagram.diagram());\n\t\t\t\tif (diagramNodeName.isEmpty()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tinterpreterDiagramsList.append(\"qrm:\/\" + editor.editor() + \"\/\"\n\t\t\t\t\t\t+ diagram.diagram() + \"\/\" + diagramNodeName);\n\t\t\t}\n\t\t}\n\n\t\tmMainWindow->initInterpretedPlugins();\n\n\t\tforeach (const QString &interpreterIdString, interpreterDiagramsList) {\n\t\t\t\/\/ TODO: ???\n\t\t\tmMainWindow->models().repoControlApi().exterminate();\n\t\t\tmMainWindow->models().reinit();\n\t\t\tmMainWindow->loadPlugins();\n\t\t\tmMainWindow->createDiagram(interpreterIdString);\n\t\t}\n\t} else {\n\t\tshow();\n\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nvoid StartWidget::createInterpretedDiagram()\n{\n\thide();\n\tProxyEditorManager &editorManagerProxy = mMainWindow->editorManagerProxy();\n\teditorManagerProxy.setProxyManager(new InterpreterEditorManager(\"\"));\n\tbool ok = false;\n\tQString name = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t, QLineEdit::Normal, \"\", &ok);\n\twhile (ok && name.isEmpty()) {\n\t\tname = QInputDialog::getText(this, tr(\"Enter the diagram name:\"), tr(\"diagram name:\")\n\t\t\t\t, QLineEdit::Normal, \"\", &ok);\n\t}\n\n\tif (ok) {\n\t\tQPair editorAndDiagram = editorManagerProxy.createEditorAndDiagram(name);\n\t\tmMainWindow->addEditorElementsToPalette(editorAndDiagram.first, editorAndDiagram.second);\n\t\tmMainWindow->models().repoControlApi().exterminate();\n\t\tmMainWindow->models().reinit();\n\t\tmMainWindow->loadPlugins();\n\t\tmMainWindow->initInterpretedPlugins();\n\t} else {\n\t\tshow();\n\t\teditorManagerProxy.setProxyManager(new EditorManager());\n\t}\n}\n\nvoid StartWidget::setVisibleForInterpreterButton(const bool visible)\n{\n\tif (!visible) {\n\t\t\/\/\/ @todo: For some reason setVisible on interpreter buttons still leaves them visible.\n\t\t\/\/\/ This surely can be fixed and then setVisible(visible) call must be restored,\n\t\t\/\/\/ but for now working it arround...\n\t\tdelete mOpenInterpreterButton;\n\t\tdelete mCreateInterpreterButton;\n\t\tmOpenInterpreterButton = nullptr;\n\t\tmCreateInterpreterButton = nullptr;\n\t}\n\n\tconst int editorsCount = mMainWindow->editorManager().editors().count();\n\tQList toCentralize;\n\tbool needLayoutHorizontally = false;\n\tif (visible) {\n\t\tneedLayoutHorizontally = editorsCount == 0;\n\t\ttoCentralize << mCreateInterpreterButton << mOpenInterpreterButton;\n\t} else {\n\t\tneedLayoutHorizontally = editorsCount == 1 && !mRecentProjectsWidget;\n\t\ttoCentralize << mNewProjectButton << mOpenProjectButton;\n\t}\n\n\tif (needLayoutHorizontally) {\n\t\tfor (QPushButton * const button : toCentralize) {\n\t\t\tcentralizeButton(button);\n\t\t}\n\n\t\tmProjectsManagementLayout->setDirection(QBoxLayout::LeftToRight);\n\t}\n}\n\nvoid StartWidget::centralizeButton(QPushButton * const styledButton)\n{\n\tif (!styledButton) {\n\t\treturn;\n\t}\n\n\tQBoxLayout * const layout = static_cast(styledButton->layout());\n\tlayout->setDirection(QBoxLayout::TopToBottom);\n\tQWidget * const icon = layout->itemAt(0)->widget();\n\tQLabel * const label = static_cast(layout->itemAt(1)->widget());\n\tlabel->setAlignment(Qt::AlignHCenter);\n\tlayout->setAlignment(icon, Qt::AlignHCenter | Qt::AlignBottom);\n\tlayout->setAlignment(label, Qt::AlignHCenter | Qt::AlignTop);\n\tlayout->activate();\n\tlayout->update();\n\tstyledButton->update();\n\n\tmProjectsManagementLayout->setAlignment(styledButton, Qt::AlignVCenter);\n\tconst int index = mProjectsManagementLayout->indexOf(styledButton);\n\tmProjectsManagementLayout->setStretch(index, 10000);\n}\n\nvoid StartWidget::paintEvent(QPaintEvent *event)\n{\n\tQ_UNUSED(event);\n\n\tQStyleOption styleOption;\n\tstyleOption.initFrom(this);\n\tQPainter painter(this);\n\tstyle()->drawPrimitive(QStyle::PE_Widget, &styleOption, &painter, this);\n}\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"QOSPRayWindow.h\"\n#include \"modules\/opengl\/util.h\"\n\n#ifdef __APPLE__\n #include \n#else\n #include \n#endif\n\nstd::ostream &operator<<(std::ostream &o, const Viewport &viewport)\n{\n o << \"-vp \" << viewport.from.x << \" \" << viewport.from.y << \" \" << viewport.from.z\n << \" -vi \" << viewport.at.x << \" \" << viewport.at.y << \" \" << viewport.at.z\n << \" -vu \" << viewport.up.x << \" \" << viewport.up.y << \" \" << viewport.up.z\n << std::endl;\n\n return o;\n}\n\n\nQOSPRayWindow::QOSPRayWindow(QMainWindow *parent, \n OSPRenderer renderer, \n bool showFrameRate,\n std::string writeFramesFilename)\n : parent(parent), \n showFrameRate(showFrameRate), \n frameCount(0), \n renderingEnabled(false), \n rotationRate(0.f), \n benchmarkWarmUpFrames(0), \n benchmarkFrames(0), \n frameBuffer(NULL), \n renderer(NULL), \n camera(NULL),\n maxDepthTexture(NULL),\n writeFramesFilename(writeFramesFilename)\n{\n \/\/ assign renderer\n if(!renderer)\n throw std::runtime_error(\"QOSPRayWindow: must be constructed with an existing renderer\");\n\n this->renderer = renderer;\n\n \/\/ setup camera\n camera = ospNewCamera(\"perspective\");\n\n if(!camera)\n throw std::runtime_error(\"QOSPRayWindow: could not create camera type 'perspective'\");\n\n ospCommit(camera);\n\n ospSetObject(renderer, \"camera\", camera);\n\n \/\/ connect signals and slots\n connect(&renderTimer, SIGNAL(timeout()), this, SLOT(updateGL()));\n connect(&renderRestartTimer, SIGNAL(timeout()), &renderTimer, SLOT(start()));\n}\n\nQOSPRayWindow::~QOSPRayWindow()\n{\n \/\/ free the frame buffer and camera\n \/\/ we don't own the renderer!\n if(frameBuffer)\n ospFreeFrameBuffer(frameBuffer);\n\n if(camera)\n ospRelease(camera);\n}\n\nvoid QOSPRayWindow::setRenderingEnabled(bool renderingEnabled)\n{\n this->renderingEnabled = renderingEnabled;\n\n \/\/ trigger render if true\n if(renderingEnabled == true)\n renderTimer.start();\n else\n renderTimer.stop();\n}\n\nvoid QOSPRayWindow::setRotationRate(float rotationRate)\n{\n this->rotationRate = rotationRate;\n}\n\nvoid QOSPRayWindow::setBenchmarkParameters(int benchmarkWarmUpFrames, int benchmarkFrames)\n{\n this->benchmarkWarmUpFrames = benchmarkWarmUpFrames;\n this->benchmarkFrames = benchmarkFrames;\n}\n\nvoid QOSPRayWindow::setWorldBounds(const ospcommon::box3f &worldBounds)\n{\n this->worldBounds = worldBounds;\n\n \/\/ set viewport look at point to center of world bounds\n viewport.at = center(worldBounds);\n\n \/\/ set viewport from point relative to center of world bounds\n viewport.from = viewport.at - 1.5f * length(worldBounds.size()) * viewport.frame.l.vy;\n\n updateGL();\n}\n\nvoid QOSPRayWindow::paintGL()\n{\n if(!renderingEnabled || !frameBuffer || !renderer)\n return;\n\n \/\/ if we're benchmarking and we've completed the required number of warm-up frames, start the timer\n if(benchmarkFrames > 0 && frameCount == benchmarkWarmUpFrames) {\n std::cout << \"starting benchmark timer\" << std::endl;\n benchmarkTimer.start();\n }\n\n \/\/ update OSPRay camera if viewport has been modified\n if(viewport.modified) {\n const ospcommon::vec3f dir = viewport.at - viewport.from;\n ospSetVec3f(camera,\"pos\" ,(const osp::vec3f&)viewport.from);\n ospSetVec3f(camera,\"dir\" ,(const osp::vec3f&)dir);\n ospSetVec3f(camera,\"up\", (const osp::vec3f&)viewport.up);\n ospSetf(camera,\"aspect\", viewport.aspect);\n ospSetf(camera,\"fovy\", viewport.fovY);\n\n ospCommit(camera);\n\n viewport.modified = false;\n }\n\n renderFrameTimer.start();\n\n \/\/ we have OpenGL components if any slots are connected to the renderGLComponents() signal\n \/\/ if so, render these first and then composite the OSPRay-rendered content on top\n bool haveOpenGLComponents = receivers(SIGNAL(renderGLComponents())) > 0;\n\n if (haveOpenGLComponents) {\n\n \/\/ setup OpenGL view to match current view and render all OpenGL components\n renderGL();\n\n \/\/ generate max depth texture for early ray termination\n if (maxDepthTexture)\n ospRelease(maxDepthTexture);\n\n maxDepthTexture = ospray::opengl::getOSPDepthTextureFromOpenGLPerspective();\n ospSetObject(renderer, \"maxDepthTexture\", maxDepthTexture);\n\n \/\/ disable OSPRay background rendering since we're compositing\n ospSet1i(renderer, \"backgroundEnabled\", 0);\n\n ospCommit(renderer);\n\n \/\/ disable OpenGL depth testing and enable blending for compositing\n glDisable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n }\n else {\n\n \/\/ unset any maximum depth texture and enable OSPRay background rendering\n ospSetObject(renderer, \"maxDepthTexture\", NULL);\n ospSet1i(renderer, \"backgroundEnabled\", 1);\n ospCommit(renderer);\n\n \/\/ disable OpenGL blending\n glDisable(GL_BLEND);\n }\n\n ospRenderFrame(frameBuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);\n double framesPerSecond = 1000.0 \/ renderFrameTimer.elapsed();\n char title[1024]; sprintf(title, \"OSPRay Volume Viewer (%.4f fps)\", framesPerSecond);\n if (showFrameRate == true) parent->setWindowTitle(title);\n\n uint32_t *mappedFrameBuffer = (unsigned int *) ospMapFrameBuffer(frameBuffer);\n\n glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, mappedFrameBuffer);\n if (writeFramesFilename.length()) writeFrameBufferToFile(mappedFrameBuffer);\n\n ospUnmapFrameBuffer(mappedFrameBuffer, frameBuffer);\n\n \/\/ automatic rotation\n if(rotationRate != 0.f) {\n resetAccumulationBuffer();\n rotateCenter(rotationRate, 0.f);\n }\n\n \/\/ increment frame counter\n frameCount++;\n\n \/\/ quit if we're benchmarking and have exceeded the needed number of frames\n if(benchmarkFrames > 0 && frameCount >= benchmarkWarmUpFrames + benchmarkFrames) {\n\n float elapsedSeconds = float(benchmarkTimer.elapsed()) \/ 1000.f;\n\n std::cout << \"benchmark: \" << elapsedSeconds << \" elapsed seconds ==> \" << float(benchmarkFrames) \/ elapsedSeconds << \" fps\" << std::endl;\n\n QCoreApplication::quit();\n }\n}\n\nvoid QOSPRayWindow::resizeGL(int width, int height)\n{\n windowSize = ospcommon::vec2i(width, height);\n\n \/\/ reallocate OSPRay framebuffer for new size\n if(frameBuffer)\n ospFreeFrameBuffer(frameBuffer);\n\n frameBuffer = ospNewFrameBuffer((const osp::vec2i&)windowSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n resetAccumulationBuffer();\n\n \/\/ update viewport aspect ratio\n viewport.aspect = float(width) \/ float(height);\n viewport.modified = true;\n\n \/\/ update OpenGL viewport and force redraw\n glViewport(0, 0, width, height);\n updateGL();\n}\n\nvoid QOSPRayWindow::mousePressEvent(QMouseEvent * event)\n{\n lastMousePosition = event->pos();\n}\n\nvoid QOSPRayWindow::mouseReleaseEvent(QMouseEvent * event)\n{\n lastMousePosition = event->pos();\n\n \/\/ restart continuous rendering immediately\n renderTimer.start();\n}\n\nvoid QOSPRayWindow::mouseMoveEvent(QMouseEvent * event)\n{\n \/\/ pause continuous rendering during interaction and cancel any render restart timers.\n \/\/ this keeps interaction more responsive (especially with low frame rates).\n renderTimer.stop();\n renderRestartTimer.stop();\n\n resetAccumulationBuffer();\n\n int dx = event->x() - lastMousePosition.x();\n int dy = event->y() - lastMousePosition.y();\n\n if(event->buttons() & Qt::LeftButton) {\n\n \/\/ camera rotation about center point\n const float rotationSpeed = 0.003f;\n\n float du = dx * rotationSpeed;\n float dv = dy * rotationSpeed;\n\n rotateCenter(du, dv);\n }\n else if(event->buttons() & Qt::MidButton) {\n\n \/\/ camera strafe of from \/ at point\n const float strafeSpeed = 0.001f * length(worldBounds.size());\n\n float du = dx * strafeSpeed;\n float dv = dy * strafeSpeed;\n\n strafe(du, dv);\n }\n else if(event->buttons() & Qt::RightButton) {\n\n \/\/ camera distance from center point\n const float motionSpeed = 0.012f;\n\n float forward = dy * motionSpeed * length(worldBounds.size());\n float oldDistance = length(viewport.at - viewport.from);\n float newDistance = oldDistance - forward;\n\n if(newDistance < 1e-3f)\n return;\n\n viewport.from = viewport.at - newDistance * viewport.frame.l.vy;\n viewport.frame.p = viewport.from;\n\n viewport.modified = true;\n }\n\n lastMousePosition = event->pos();\n\n updateGL();\n\n \/\/ after a 0.5s delay, restart continuous rendering.\n renderRestartTimer.setSingleShot(true);\n renderRestartTimer.start(500);\n}\n\nvoid QOSPRayWindow::rotateCenter(float du, float dv)\n{\n const ospcommon::vec3f pivot = viewport.at;\n\n ospcommon::affine3f xfm = ospcommon::affine3f::translate(pivot)\n * ospcommon::affine3f::rotate(viewport.frame.l.vx, -dv)\n * ospcommon::affine3f::rotate(viewport.frame.l.vz, -du)\n * ospcommon::affine3f::translate(-pivot);\n\n viewport.frame = xfm * viewport.frame;\n viewport.from = xfmPoint(xfm, viewport.from);\n viewport.at = xfmPoint(xfm, viewport.at);\n viewport.snapUp();\n\n viewport.modified = true;\n}\n\nvoid QOSPRayWindow::strafe(float du, float dv)\n{\n ospcommon::affine3f xfm = ospcommon::affine3f::translate(dv * viewport.frame.l.vz)\n * ospcommon::affine3f::translate(-du * viewport.frame.l.vx);\n\n viewport.frame = xfm * viewport.frame;\n viewport.from = xfmPoint(xfm, viewport.from);\n viewport.at = xfmPoint(xfm, viewport.at);\n viewport.modified = true;\n\n viewport.modified = true;\n}\n\nvoid QOSPRayWindow::renderGL()\n{\n \/\/ setup OpenGL state to match OSPRay view\n const ospcommon::vec3f bgColor = ospcommon::vec3f(1.f);\n glClearColor(bgColor.x, bgColor.y, bgColor.z, 1.f);\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n float zNear = 0.1f;\n float zFar = 100000.f;\n gluPerspective(viewport.fovY, viewport.aspect, zNear, zFar);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n gluLookAt(viewport.from.x, viewport.from.y, viewport.from.z,\n viewport.at.x, viewport.at.y, viewport.at.z,\n viewport.up.x, viewport.up.y, viewport.up.z);\n\n \/\/ emit signal to render all OpenGL components; the slots will execute in the order they were registered\n emit(renderGLComponents());\n}\n\nvoid QOSPRayWindow::writeFrameBufferToFile(const uint32_t *pixelData)\n{\n static uint32_t frameNumber = 0;\n char filename[1024];\n sprintf(filename, \"%s_%05u.ppm\", writeFramesFilename.c_str(), frameNumber++);\n FILE *file = fopen(filename, \"wb\"); if (!file) { std::cerr << \"unable to write to file '\" << filename << \"'\" << std::endl; return; }\n\n fprintf(file, \"P6\\n%i %i\\n255\\n\", windowSize.x, windowSize.y);\n unsigned char out[3 * windowSize.x];\n for (int y=0 ; y < windowSize.y ; y++) {\n const unsigned char *in = (const unsigned char *) &pixelData[(windowSize.y - 1 - y) * windowSize.x];\n for (int x=0 ; x < windowSize.x ; x++) {\n out[3 * x + 0] = in[4 * x + 0];\n out[3 * x + 1] = in[4 * x + 1];\n out[3 * x + 2] = in[4 * x + 2];\n }\n fwrite(&out, 3 * windowSize.x, sizeof(char), file);\n }\n fprintf(file, \"\\n\");\n fclose(file);\n}\nFix screenshot view position info to match new argument syntax\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"QOSPRayWindow.h\"\n#include \"modules\/opengl\/util.h\"\n\n#ifdef __APPLE__\n #include \n#else\n #include \n#endif\n\nstd::ostream &operator<<(std::ostream &o, const Viewport &viewport)\n{\n o << \"--vp \" << viewport.from.x << \" \" << viewport.from.y << \" \" << viewport.from.z\n << \" --vi \" << viewport.at.x << \" \" << viewport.at.y << \" \" << viewport.at.z\n << \" --vu \" << viewport.up.x << \" \" << viewport.up.y << \" \" << viewport.up.z\n << std::endl;\n\n return o;\n}\n\n\nQOSPRayWindow::QOSPRayWindow(QMainWindow *parent, \n OSPRenderer renderer, \n bool showFrameRate,\n std::string writeFramesFilename)\n : parent(parent), \n showFrameRate(showFrameRate), \n frameCount(0), \n renderingEnabled(false), \n rotationRate(0.f), \n benchmarkWarmUpFrames(0), \n benchmarkFrames(0), \n frameBuffer(NULL), \n renderer(NULL), \n camera(NULL),\n maxDepthTexture(NULL),\n writeFramesFilename(writeFramesFilename)\n{\n \/\/ assign renderer\n if(!renderer)\n throw std::runtime_error(\"QOSPRayWindow: must be constructed with an existing renderer\");\n\n this->renderer = renderer;\n\n \/\/ setup camera\n camera = ospNewCamera(\"perspective\");\n\n if(!camera)\n throw std::runtime_error(\"QOSPRayWindow: could not create camera type 'perspective'\");\n\n ospCommit(camera);\n\n ospSetObject(renderer, \"camera\", camera);\n\n \/\/ connect signals and slots\n connect(&renderTimer, SIGNAL(timeout()), this, SLOT(updateGL()));\n connect(&renderRestartTimer, SIGNAL(timeout()), &renderTimer, SLOT(start()));\n}\n\nQOSPRayWindow::~QOSPRayWindow()\n{\n \/\/ free the frame buffer and camera\n \/\/ we don't own the renderer!\n if(frameBuffer)\n ospFreeFrameBuffer(frameBuffer);\n\n if(camera)\n ospRelease(camera);\n}\n\nvoid QOSPRayWindow::setRenderingEnabled(bool renderingEnabled)\n{\n this->renderingEnabled = renderingEnabled;\n\n \/\/ trigger render if true\n if(renderingEnabled == true)\n renderTimer.start();\n else\n renderTimer.stop();\n}\n\nvoid QOSPRayWindow::setRotationRate(float rotationRate)\n{\n this->rotationRate = rotationRate;\n}\n\nvoid QOSPRayWindow::setBenchmarkParameters(int benchmarkWarmUpFrames, int benchmarkFrames)\n{\n this->benchmarkWarmUpFrames = benchmarkWarmUpFrames;\n this->benchmarkFrames = benchmarkFrames;\n}\n\nvoid QOSPRayWindow::setWorldBounds(const ospcommon::box3f &worldBounds)\n{\n this->worldBounds = worldBounds;\n\n \/\/ set viewport look at point to center of world bounds\n viewport.at = center(worldBounds);\n\n \/\/ set viewport from point relative to center of world bounds\n viewport.from = viewport.at - 1.5f * length(worldBounds.size()) * viewport.frame.l.vy;\n\n updateGL();\n}\n\nvoid QOSPRayWindow::paintGL()\n{\n if(!renderingEnabled || !frameBuffer || !renderer)\n return;\n\n \/\/ if we're benchmarking and we've completed the required number of warm-up frames, start the timer\n if(benchmarkFrames > 0 && frameCount == benchmarkWarmUpFrames) {\n std::cout << \"starting benchmark timer\" << std::endl;\n benchmarkTimer.start();\n }\n\n \/\/ update OSPRay camera if viewport has been modified\n if(viewport.modified) {\n const ospcommon::vec3f dir = viewport.at - viewport.from;\n ospSetVec3f(camera,\"pos\" ,(const osp::vec3f&)viewport.from);\n ospSetVec3f(camera,\"dir\" ,(const osp::vec3f&)dir);\n ospSetVec3f(camera,\"up\", (const osp::vec3f&)viewport.up);\n ospSetf(camera,\"aspect\", viewport.aspect);\n ospSetf(camera,\"fovy\", viewport.fovY);\n\n ospCommit(camera);\n\n viewport.modified = false;\n }\n\n renderFrameTimer.start();\n\n \/\/ we have OpenGL components if any slots are connected to the renderGLComponents() signal\n \/\/ if so, render these first and then composite the OSPRay-rendered content on top\n bool haveOpenGLComponents = receivers(SIGNAL(renderGLComponents())) > 0;\n\n if (haveOpenGLComponents) {\n\n \/\/ setup OpenGL view to match current view and render all OpenGL components\n renderGL();\n\n \/\/ generate max depth texture for early ray termination\n if (maxDepthTexture)\n ospRelease(maxDepthTexture);\n\n maxDepthTexture = ospray::opengl::getOSPDepthTextureFromOpenGLPerspective();\n ospSetObject(renderer, \"maxDepthTexture\", maxDepthTexture);\n\n \/\/ disable OSPRay background rendering since we're compositing\n ospSet1i(renderer, \"backgroundEnabled\", 0);\n\n ospCommit(renderer);\n\n \/\/ disable OpenGL depth testing and enable blending for compositing\n glDisable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n }\n else {\n\n \/\/ unset any maximum depth texture and enable OSPRay background rendering\n ospSetObject(renderer, \"maxDepthTexture\", NULL);\n ospSet1i(renderer, \"backgroundEnabled\", 1);\n ospCommit(renderer);\n\n \/\/ disable OpenGL blending\n glDisable(GL_BLEND);\n }\n\n ospRenderFrame(frameBuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);\n double framesPerSecond = 1000.0 \/ renderFrameTimer.elapsed();\n char title[1024]; sprintf(title, \"OSPRay Volume Viewer (%.4f fps)\", framesPerSecond);\n if (showFrameRate == true) parent->setWindowTitle(title);\n\n uint32_t *mappedFrameBuffer = (unsigned int *) ospMapFrameBuffer(frameBuffer);\n\n glDrawPixels(windowSize.x, windowSize.y, GL_RGBA, GL_UNSIGNED_BYTE, mappedFrameBuffer);\n if (writeFramesFilename.length()) writeFrameBufferToFile(mappedFrameBuffer);\n\n ospUnmapFrameBuffer(mappedFrameBuffer, frameBuffer);\n\n \/\/ automatic rotation\n if(rotationRate != 0.f) {\n resetAccumulationBuffer();\n rotateCenter(rotationRate, 0.f);\n }\n\n \/\/ increment frame counter\n frameCount++;\n\n \/\/ quit if we're benchmarking and have exceeded the needed number of frames\n if(benchmarkFrames > 0 && frameCount >= benchmarkWarmUpFrames + benchmarkFrames) {\n\n float elapsedSeconds = float(benchmarkTimer.elapsed()) \/ 1000.f;\n\n std::cout << \"benchmark: \" << elapsedSeconds << \" elapsed seconds ==> \" << float(benchmarkFrames) \/ elapsedSeconds << \" fps\" << std::endl;\n\n QCoreApplication::quit();\n }\n}\n\nvoid QOSPRayWindow::resizeGL(int width, int height)\n{\n windowSize = ospcommon::vec2i(width, height);\n\n \/\/ reallocate OSPRay framebuffer for new size\n if(frameBuffer)\n ospFreeFrameBuffer(frameBuffer);\n\n frameBuffer = ospNewFrameBuffer((const osp::vec2i&)windowSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM);\n\n resetAccumulationBuffer();\n\n \/\/ update viewport aspect ratio\n viewport.aspect = float(width) \/ float(height);\n viewport.modified = true;\n\n \/\/ update OpenGL viewport and force redraw\n glViewport(0, 0, width, height);\n updateGL();\n}\n\nvoid QOSPRayWindow::mousePressEvent(QMouseEvent * event)\n{\n lastMousePosition = event->pos();\n}\n\nvoid QOSPRayWindow::mouseReleaseEvent(QMouseEvent * event)\n{\n lastMousePosition = event->pos();\n\n \/\/ restart continuous rendering immediately\n renderTimer.start();\n}\n\nvoid QOSPRayWindow::mouseMoveEvent(QMouseEvent * event)\n{\n \/\/ pause continuous rendering during interaction and cancel any render restart timers.\n \/\/ this keeps interaction more responsive (especially with low frame rates).\n renderTimer.stop();\n renderRestartTimer.stop();\n\n resetAccumulationBuffer();\n\n int dx = event->x() - lastMousePosition.x();\n int dy = event->y() - lastMousePosition.y();\n\n if(event->buttons() & Qt::LeftButton) {\n\n \/\/ camera rotation about center point\n const float rotationSpeed = 0.003f;\n\n float du = dx * rotationSpeed;\n float dv = dy * rotationSpeed;\n\n rotateCenter(du, dv);\n }\n else if(event->buttons() & Qt::MidButton) {\n\n \/\/ camera strafe of from \/ at point\n const float strafeSpeed = 0.001f * length(worldBounds.size());\n\n float du = dx * strafeSpeed;\n float dv = dy * strafeSpeed;\n\n strafe(du, dv);\n }\n else if(event->buttons() & Qt::RightButton) {\n\n \/\/ camera distance from center point\n const float motionSpeed = 0.012f;\n\n float forward = dy * motionSpeed * length(worldBounds.size());\n float oldDistance = length(viewport.at - viewport.from);\n float newDistance = oldDistance - forward;\n\n if(newDistance < 1e-3f)\n return;\n\n viewport.from = viewport.at - newDistance * viewport.frame.l.vy;\n viewport.frame.p = viewport.from;\n\n viewport.modified = true;\n }\n\n lastMousePosition = event->pos();\n\n updateGL();\n\n \/\/ after a 0.5s delay, restart continuous rendering.\n renderRestartTimer.setSingleShot(true);\n renderRestartTimer.start(500);\n}\n\nvoid QOSPRayWindow::rotateCenter(float du, float dv)\n{\n const ospcommon::vec3f pivot = viewport.at;\n\n ospcommon::affine3f xfm = ospcommon::affine3f::translate(pivot)\n * ospcommon::affine3f::rotate(viewport.frame.l.vx, -dv)\n * ospcommon::affine3f::rotate(viewport.frame.l.vz, -du)\n * ospcommon::affine3f::translate(-pivot);\n\n viewport.frame = xfm * viewport.frame;\n viewport.from = xfmPoint(xfm, viewport.from);\n viewport.at = xfmPoint(xfm, viewport.at);\n viewport.snapUp();\n\n viewport.modified = true;\n}\n\nvoid QOSPRayWindow::strafe(float du, float dv)\n{\n ospcommon::affine3f xfm = ospcommon::affine3f::translate(dv * viewport.frame.l.vz)\n * ospcommon::affine3f::translate(-du * viewport.frame.l.vx);\n\n viewport.frame = xfm * viewport.frame;\n viewport.from = xfmPoint(xfm, viewport.from);\n viewport.at = xfmPoint(xfm, viewport.at);\n viewport.modified = true;\n\n viewport.modified = true;\n}\n\nvoid QOSPRayWindow::renderGL()\n{\n \/\/ setup OpenGL state to match OSPRay view\n const ospcommon::vec3f bgColor = ospcommon::vec3f(1.f);\n glClearColor(bgColor.x, bgColor.y, bgColor.z, 1.f);\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n\n float zNear = 0.1f;\n float zFar = 100000.f;\n gluPerspective(viewport.fovY, viewport.aspect, zNear, zFar);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n gluLookAt(viewport.from.x, viewport.from.y, viewport.from.z,\n viewport.at.x, viewport.at.y, viewport.at.z,\n viewport.up.x, viewport.up.y, viewport.up.z);\n\n \/\/ emit signal to render all OpenGL components; the slots will execute in the order they were registered\n emit(renderGLComponents());\n}\n\nvoid QOSPRayWindow::writeFrameBufferToFile(const uint32_t *pixelData)\n{\n static uint32_t frameNumber = 0;\n char filename[1024];\n sprintf(filename, \"%s_%05u.ppm\", writeFramesFilename.c_str(), frameNumber++);\n FILE *file = fopen(filename, \"wb\"); if (!file) { std::cerr << \"unable to write to file '\" << filename << \"'\" << std::endl; return; }\n\n fprintf(file, \"P6\\n%i %i\\n255\\n\", windowSize.x, windowSize.y);\n unsigned char out[3 * windowSize.x];\n for (int y=0 ; y < windowSize.y ; y++) {\n const unsigned char *in = (const unsigned char *) &pixelData[(windowSize.y - 1 - y) * windowSize.x];\n for (int x=0 ; x < windowSize.x ; x++) {\n out[3 * x + 0] = in[4 * x + 0];\n out[3 * x + 1] = in[4 * x + 1];\n out[3 * x + 2] = in[4 * x + 2];\n }\n fwrite(&out, 3 * windowSize.x, sizeof(char), file);\n }\n fprintf(file, \"\\n\");\n fclose(file);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ file : backtrace.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/yaggler\/yaggler\/tools\/backtrace.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 13\/02\/2015 17:02:08\n\/\/\n\/\/\n\/\/ Copyright (c) 2014-2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_1145625880472195080_2067372013__BACKTRACE_HPP__\n# define __N_1145625880472195080_2067372013__BACKTRACE_HPP__\n\n#ifdef __linux__\n#include \n#include \n#include \n#include \n#endif\n\n#include \"logger\/logger.hpp\"\n\nnamespace neam\n{\n namespace cr\n {\n \/\/\/ \\brief print the current callstack\n \/\/\/ (and demangle functions name, and print a lovely addr2line command that you can use to get the line number)\n \/\/\/ \\param[in] backtrace_size the depth of the backtrace: the number of entries to print\n \/\/\/ \\param[in] skip the number of entries to skip from printing. (the N first entries to skip).\n \/\/\/ \\note currently only on LINUX\n static inline void print_callstack(size_t backtrace_size = 25, size_t skip = 1, bool has_logger_lock = false)\n {\n#ifdef __linux__\n char **strings;\n void *bt[backtrace_size + skip];\n\n int num = backtrace(bt, backtrace_size + skip);\n strings = backtrace_symbols(bt, num);\n\n auto logger = neam::cr::out(has_logger_lock);\n logger.warn(\"#############[ B A C K T R A C E ]#############\"); \n logger.debug(\"## most recent call first:\"); \n\n for (int j = skip; j < num; ++j)\n {\n \/\/ extract the symbol from the string\n int i = 0;\n int k = 0;\n for (; strings[j][i] && strings[j][i] != '('; ++i);\n if (strings[j][i]) ++i;\n for (; strings[j][i + k] && strings[j][i + k] != '+' && strings[j][i + k] != ')'; ++k);\n char *mangled = strndup(strings[j] + i, k);\n\n \/\/ demangle the symbol\n int status;\n char buffer[1024];\n size_t len = 1024;\n char *realname = abi::__cxa_demangle(mangled, buffer, &len, &status);\n if (status)\n realname = mangled;\n\n \/\/ print\n logger.warn(\" [{}]: {}\\t{}\", num - j, realname, strings[j]);\n\n \/\/ and free\n free(mangled);\n }\n\n \/\/ print the indexes\n std::vector addr;\n addr.reserve(num);\n for (int j = skip; j < num; ++j)\n {\n \/\/ extract the address from the string\n int i = 0;\n int k = 0;\n for (; strings[j][i] && strings[j][i] != '['; ++i);\n if (strings[j][i]) ++i;\n for (; strings[j][i + k] && strings[j][i + k] != ']'; ++k);\n char *fnc_addr = strndup(strings[j] + i, k);\n\n addr.push_back(fnc_addr);\n }\n\n logger.debug(\"## addr2line -e {} -fipsC {}\", program_invocation_name, fmt::join(addr, \" \"));\n\n for (auto it : addr)\n {\n free(it);\n }\n\n logger.warn(\"########[ B A C K T R A C E E N D ]########\");\n\n free(strings);\n#endif\n }\n }\n} \/\/ namespace neam\n\n#endif \/*__N_1145625880472195080_2067372013__BACKTRACE_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on;\n\nMake the addr2line info a warn not a debug\/\/\n\/\/ file : backtrace.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/yaggler\/yaggler\/tools\/backtrace.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 13\/02\/2015 17:02:08\n\/\/\n\/\/\n\/\/ Copyright (c) 2014-2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_1145625880472195080_2067372013__BACKTRACE_HPP__\n# define __N_1145625880472195080_2067372013__BACKTRACE_HPP__\n\n#ifdef __linux__\n#include \n#include \n#include \n#include \n#endif\n\n#include \"logger\/logger.hpp\"\n\nnamespace neam\n{\n namespace cr\n {\n \/\/\/ \\brief print the current callstack\n \/\/\/ (and demangle functions name, and print a lovely addr2line command that you can use to get the line number)\n \/\/\/ \\param[in] backtrace_size the depth of the backtrace: the number of entries to print\n \/\/\/ \\param[in] skip the number of entries to skip from printing. (the N first entries to skip).\n \/\/\/ \\note currently only on LINUX\n static inline void print_callstack(size_t backtrace_size = 25, size_t skip = 1, bool has_logger_lock = false)\n {\n#ifdef __linux__\n char **strings;\n void *bt[backtrace_size + skip];\n\n int num = backtrace(bt, backtrace_size + skip);\n strings = backtrace_symbols(bt, num);\n\n auto logger = neam::cr::out(has_logger_lock);\n logger.warn(\"#############[ B A C K T R A C E ]#############\"); \n logger.warn(\"## most recent call first:\"); \n\n for (int j = skip; j < num; ++j)\n {\n \/\/ extract the symbol from the string\n int i = 0;\n int k = 0;\n for (; strings[j][i] && strings[j][i] != '('; ++i);\n if (strings[j][i]) ++i;\n for (; strings[j][i + k] && strings[j][i + k] != '+' && strings[j][i + k] != ')'; ++k);\n char *mangled = strndup(strings[j] + i, k);\n\n \/\/ demangle the symbol\n int status;\n char buffer[1024];\n size_t len = 1024;\n char *realname = abi::__cxa_demangle(mangled, buffer, &len, &status);\n if (status)\n realname = mangled;\n\n \/\/ print\n logger.warn(\" [{}]: {}\\t{}\", num - j, realname, strings[j]);\n\n \/\/ and free\n free(mangled);\n }\n\n \/\/ print the indexes\n std::vector addr;\n addr.reserve(num);\n for (int j = skip; j < num; ++j)\n {\n \/\/ extract the address from the string\n int i = 0;\n int k = 0;\n for (; strings[j][i] && strings[j][i] != '['; ++i);\n if (strings[j][i]) ++i;\n for (; strings[j][i + k] && strings[j][i + k] != ']'; ++k);\n char *fnc_addr = strndup(strings[j] + i, k);\n\n addr.push_back(fnc_addr);\n }\n\n logger.warn(\"## addr2line -e {} -fipsC {}\", program_invocation_name, fmt::join(addr, \" \"));\n\n for (auto it : addr)\n {\n free(it);\n }\n\n logger.warn(\"########[ B A C K T R A C E E N D ]########\");\n\n free(strings);\n#endif\n }\n }\n} \/\/ namespace neam\n\n#endif \/*__N_1145625880472195080_2067372013__BACKTRACE_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on;\n\n<|endoftext|>"} {"text":"\/*\n * Add contact dialog\n *\n * Copyright (C) 2011 David Edmundson \n * Copyright (C) 2012 George Kiagiadakis \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"add-contact-dialog.h\"\n#include \"ui_add-contact-dialog.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace KTp {\n\n\/** A filter which only lists connections which accept adding contacts*\/\nclass KTP_NO_EXPORT SubscribableAccountsModel : public QSortFilterProxyModel\n{\npublic:\n SubscribableAccountsModel(QObject *parent);\n virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;\n};\n\nSubscribableAccountsModel::SubscribableAccountsModel(QObject *parent)\n : QSortFilterProxyModel(parent)\n{\n}\n\nbool SubscribableAccountsModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const\n{\n AccountsModelItem* item = sourceModel()->index(source_row, 0, source_parent).data(AccountsModel::ItemRole).value();\n\n if (item) {\n Tp::AccountPtr account = item->account();\n\n \/\/if there's no connection we can't add contacts as we have no contactmanager\n if (! account->connection()) {\n return false;\n }\n\n \/\/only show items which can add a contact (i.e hide accounts like IRC which are online but there's no point listing)\n if (! account->connection()->contactManager()->canRequestPresenceSubscription()){\n return false;\n }\n }\n return true;\n}\n\n\nstruct KTP_NO_EXPORT AddContactDialog::Private\n{\n Private() :\n ui(new Ui::AddContactDialog),\n acceptInProgress(false)\n {}\n\n Ui::AddContactDialog *ui;\n bool acceptInProgress;\n};\n\nAddContactDialog::AddContactDialog(AccountsModel *accountModel, QWidget *parent) :\n KDialog(parent),\n d(new Private)\n{\n QWidget *widget = new QWidget(this);\n d->ui->setupUi(widget);\n setMainWidget(widget);\n\n SubscribableAccountsModel *filteredModel = new SubscribableAccountsModel(this);\n filteredModel->setSourceModel(accountModel);\n d->ui->accountCombo->setModel(filteredModel);\n\n d->ui->screenNameLineEdit->setFocus();\n}\n\nAddContactDialog::~AddContactDialog()\n{\n delete d->ui;\n delete d;\n}\n\nvoid AddContactDialog::accept()\n{\n Tp::AccountPtr account;\n QVariant itemData = d->ui->accountCombo->itemData(d->ui->accountCombo->currentIndex(), AccountsModel::ItemRole);\n AccountsModelItem* item = itemData.value();\n if (item) {\n account = item->account();\n }\n\n if (account.isNull()) {\n KMessageBox::sorry(this, i18n(\"Seems like you forgot to select an account. \"\n \"Also, do not forget to connect it first.\"));\n } else if (account->connection().isNull()) {\n KMessageBox::sorry(this, i18n(\"The requested account has disconnected \"\n \"and so the contact could not be added.\"));\n } else if (d->ui->screenNameLineEdit->text().isEmpty()) {\n KMessageBox::sorry(this, i18n(\"You did not specify the name of the contact to add.\"));\n } else {\n QStringList identifiers = QStringList() << d->ui->screenNameLineEdit->text();\n kDebug() << \"Requesting contacts for identifiers:\" << identifiers;\n\n Tp::PendingContacts *pendingContacts = account->connection()->contactManager()->contactsForIdentifiers(identifiers);\n connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(_k_onContactsForIdentifiersFinished(Tp::PendingOperation*)));\n\n setInProgress(true);\n }\n}\n\nvoid AddContactDialog::closeEvent(QCloseEvent *e)\n{\n \/\/ ignore close event if we are in the middle of an operation\n if (!d->acceptInProgress) {\n KDialog::closeEvent(e);\n }\n}\n\nvoid AddContactDialog::_k_onContactsForIdentifiersFinished(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Failed to retrieve a contact for the given identifier\"\n << op->errorName() << op->errorMessage();\n KMessageBox::sorry(this, i18n(\"Failed to construct a contact with the given name.\"));\n setInProgress(false);\n } else {\n kDebug() << \"Requesting presence subscription\";\n\n Tp::PendingContacts *pc = qobject_cast(op);\n connect(pc->manager()->requestPresenceSubscription(pc->contacts()),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation*)));\n }\n}\n\nvoid AddContactDialog::_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Failed to request presence subscription\"\n << op->errorName() << op->errorMessage();\n KMessageBox::sorry(this, i18n(\"Failed to request presence subscription \"\n \"from the requested contact.\"));\n setInProgress(false);\n } else {\n QDialog::accept();\n }\n}\n\nvoid AddContactDialog::setInProgress(bool inProgress)\n{\n d->acceptInProgress = inProgress;\n mainWidget()->setEnabled(!inProgress);\n button(KDialog::Ok)->setEnabled(!inProgress);\n button(KDialog::Cancel)->setEnabled(!inProgress);\n}\n\n} \/\/namespace KTp\n\n#include \"add-contact-dialog.moc\"\nAddContactDialog: Make some strings more user-friendly\/*\n * Add contact dialog\n *\n * Copyright (C) 2011 David Edmundson \n * Copyright (C) 2012 George Kiagiadakis \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"add-contact-dialog.h\"\n#include \"ui_add-contact-dialog.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace KTp {\n\n\/** A filter which only lists connections which accept adding contacts*\/\nclass KTP_NO_EXPORT SubscribableAccountsModel : public QSortFilterProxyModel\n{\npublic:\n SubscribableAccountsModel(QObject *parent);\n virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;\n};\n\nSubscribableAccountsModel::SubscribableAccountsModel(QObject *parent)\n : QSortFilterProxyModel(parent)\n{\n}\n\nbool SubscribableAccountsModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const\n{\n AccountsModelItem* item = sourceModel()->index(source_row, 0, source_parent).data(AccountsModel::ItemRole).value();\n\n if (item) {\n Tp::AccountPtr account = item->account();\n\n \/\/if there's no connection we can't add contacts as we have no contactmanager\n if (! account->connection()) {\n return false;\n }\n\n \/\/only show items which can add a contact (i.e hide accounts like IRC which are online but there's no point listing)\n if (! account->connection()->contactManager()->canRequestPresenceSubscription()){\n return false;\n }\n }\n return true;\n}\n\n\nstruct KTP_NO_EXPORT AddContactDialog::Private\n{\n Private() :\n ui(new Ui::AddContactDialog),\n acceptInProgress(false)\n {}\n\n Ui::AddContactDialog *ui;\n bool acceptInProgress;\n};\n\nAddContactDialog::AddContactDialog(AccountsModel *accountModel, QWidget *parent) :\n KDialog(parent),\n d(new Private)\n{\n QWidget *widget = new QWidget(this);\n d->ui->setupUi(widget);\n setMainWidget(widget);\n\n SubscribableAccountsModel *filteredModel = new SubscribableAccountsModel(this);\n filteredModel->setSourceModel(accountModel);\n d->ui->accountCombo->setModel(filteredModel);\n\n d->ui->screenNameLineEdit->setFocus();\n}\n\nAddContactDialog::~AddContactDialog()\n{\n delete d->ui;\n delete d;\n}\n\nvoid AddContactDialog::accept()\n{\n Tp::AccountPtr account;\n QVariant itemData = d->ui->accountCombo->itemData(d->ui->accountCombo->currentIndex(), AccountsModel::ItemRole);\n AccountsModelItem* item = itemData.value();\n if (item) {\n account = item->account();\n }\n\n if (account.isNull()) {\n KMessageBox::sorry(this, i18n(\"No account selected.\"));\n } else if (account->connection().isNull()) {\n KMessageBox::sorry(this, i18n(\"The requested account has been disconnected \"\n \"and so the contact could not be added.\"));\n } else if (d->ui->screenNameLineEdit->text().isEmpty()) {\n KMessageBox::sorry(this, i18n(\"You did not specify the name of the contact to add.\"));\n } else {\n QStringList identifiers = QStringList() << d->ui->screenNameLineEdit->text();\n kDebug() << \"Requesting contacts for identifiers:\" << identifiers;\n\n Tp::PendingContacts *pendingContacts = account->connection()->contactManager()->contactsForIdentifiers(identifiers);\n connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)),\n this, SLOT(_k_onContactsForIdentifiersFinished(Tp::PendingOperation*)));\n\n setInProgress(true);\n }\n}\n\nvoid AddContactDialog::closeEvent(QCloseEvent *e)\n{\n \/\/ ignore close event if we are in the middle of an operation\n if (!d->acceptInProgress) {\n KDialog::closeEvent(e);\n }\n}\n\nvoid AddContactDialog::_k_onContactsForIdentifiersFinished(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Failed to retrieve a contact for the given identifier\"\n << op->errorName() << op->errorMessage();\n KMessageBox::sorry(this, i18n(\"Failed to create new contact.\"));\n setInProgress(false);\n } else {\n kDebug() << \"Requesting presence subscription\";\n\n Tp::PendingContacts *pc = qobject_cast(op);\n connect(pc->manager()->requestPresenceSubscription(pc->contacts()),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation*)));\n }\n}\n\nvoid AddContactDialog::_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op)\n{\n if (op->isError()) {\n kWarning() << \"Failed to request presence subscription\"\n << op->errorName() << op->errorMessage();\n KMessageBox::sorry(this, i18n(\"Failed to request presence subscription \"\n \"from the requested contact.\"));\n setInProgress(false);\n } else {\n QDialog::accept();\n }\n}\n\nvoid AddContactDialog::setInProgress(bool inProgress)\n{\n d->acceptInProgress = inProgress;\n mainWidget()->setEnabled(!inProgress);\n button(KDialog::Ok)->setEnabled(!inProgress);\n button(KDialog::Cancel)->setEnabled(!inProgress);\n}\n\n} \/\/namespace KTp\n\n#include \"add-contact-dialog.moc\"\n<|endoftext|>"} {"text":"\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration),\n* All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: acscomponentTestImpl.cpp,v 1.8 2006\/09\/01 02:20:54 cparedes Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* rcirami 2003-09-18 created\n\n*\/\n\n#include \n\nstatic char *rcsId=\"@(#) $Id: acscomponentTestImpl.cpp,v 1.8 2006\/09\/01 02:20:54 cparedes Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n#include \n\nextern CORBA::ORB_var orb;\n\n\/\/This must be used instead of \"using ....\" because of VxWorks\n using namespace acscomponent;\n\n\nACSComponentTestClassImpl::ACSComponentTestClassImpl(\n\t\t\t\t\t\t const ACE_CString &name,\n\t\t\t\t\t\t maci::ContainerServices *cs) :\n ACSComponentImpl(name,cs)\n{\n \n ACS_SHORT_LOG((LM_INFO,\"::ACSComponentTestClassImpl::ACSComponentTestClassImpl\"));\n \n}\n\nACSComponentTestClassImpl::~ACSComponentTestClassImpl()\n{\n \n ACS_SHORT_LOG((LM_INFO,\"::ACSComponentTestClassImpl::~ACSComponentTestClassImpl\"));\n \n}\n\nvoid ACSComponentTestClassImpl::shutdown ()\n throw (CORBA::SystemException )\n{\n ACS_SHORT_LOG((LM_INFO, \"acscomponentTestImpl Shutdown\")); \n orb->shutdown (true);\n}\n\n\/* --------------- [ MACI DLL support functions ] -----------------*\/\n\n\/\/MACI_DLL_SUPPORT_FUNCTIONS(ACSComponentTestClassImpl)\n\n\/* ----------------------------------------------------------------*\/\n\n\n\nRemoved the shutdown of the orb in the shutdown method of the component (the orb variable is extern and was shutted down twice: by the component and by the process instantiating the component)\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration),\n* All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: acscomponentTestImpl.cpp,v 1.9 2006\/09\/26 10:26:13 acaproni Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* rcirami 2003-09-18 created\n\n*\/\n\n#include \n\nstatic char *rcsId=\"@(#) $Id: acscomponentTestImpl.cpp,v 1.9 2006\/09\/26 10:26:13 acaproni Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n#include \n\nextern CORBA::ORB_var orb;\n\n\/\/This must be used instead of \"using ....\" because of VxWorks\n using namespace acscomponent;\n\n\nACSComponentTestClassImpl::ACSComponentTestClassImpl(\n\t\t\t\t\t\t const ACE_CString &name,\n\t\t\t\t\t\t maci::ContainerServices *cs) :\n ACSComponentImpl(name,cs)\n{\n \n ACS_SHORT_LOG((LM_INFO,\"::ACSComponentTestClassImpl::ACSComponentTestClassImpl\"));\n \n}\n\nACSComponentTestClassImpl::~ACSComponentTestClassImpl()\n{\n \n ACS_SHORT_LOG((LM_INFO,\"::ACSComponentTestClassImpl::~ACSComponentTestClassImpl\"));\n \n}\n\nvoid ACSComponentTestClassImpl::shutdown ()\n throw (CORBA::SystemException )\n{\n ACS_SHORT_LOG((LM_INFO, \"acscomponentTestImpl Shutdown\")); \n }\n\n\/* --------------- [ MACI DLL support functions ] -----------------*\/\n\n\/\/MACI_DLL_SUPPORT_FUNCTIONS(ACSComponentTestClassImpl)\n\n\/* ----------------------------------------------------------------*\/\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rsctree.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 13:35:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _RSCTREE_HXX\n#define _RSCTREE_HXX\n\n#ifndef _LINK_HXX\n#include \n#endif\n\n#ifndef _RSCTOOLS_HXX\n#include \n#endif\n\n\/****************** C L A S S E S ****************************************\/\nclass BiNode\n{\nprotected:\n BiNode* pLeft; \/\/ left subtree\n BiNode* pRight; \/\/ right subtree\n\npublic:\n\n \/\/ Wandelt eine doppelt verkettete Liste in\n \/\/ einen binaeren Baum um\n BiNode * ChangeDLListBTree( BiNode * pList );\n\n BiNode();\n virtual ~BiNode();\n\n\n \/\/ Wandelt einen binaeren Baum in eine doppelt\n \/\/ verkettete Liste um\n BiNode* ChangeBTreeDLList();\n\n BiNode * Left() const { return pLeft ; };\n BiNode * Right() const{ return pRight ; };\n void EnumNodes( Link aLink ) const;\n};\n\n\/*************************************************************************\/\nclass NameNode : public BiNode\n{\n void SubOrderTree( NameNode * pOrderNode );\n\nprotected:\n \/\/ pCmp ist Zeiger auf Namen\n NameNode* Search( const void * pCmp ) const;\n\npublic:\n NameNode* Left() const { return (NameNode *)pLeft ; };\n NameNode* Right() const{ return (NameNode *)pRight ; };\n NameNode* Search( const NameNode * pName ) const;\n \/\/ insert a new node in the b-tree\n BOOL Insert( NameNode * pTN, sal_uInt32 * nDepth );\n BOOL Insert( NameNode* pTN );\n virtual COMPARE Compare( const NameNode * ) const;\n virtual COMPARE Compare( const void * ) const;\n NameNode* SearchParent( const NameNode * ) const;\n \/\/ return ist neue Root\n NameNode* Remove( NameNode * );\n void OrderTree();\n BOOL IsOrderTree() const;\n\n};\n\n\/*************************************************************************\/\nclass IdNode : public NameNode\n{\n virtual COMPARE Compare( const NameNode * ) const;\n virtual COMPARE Compare( const void * ) const;\n\npublic:\n\n IdNode* Search( sal_uInt32 nTypName ) const;\n virtual sal_uInt32 GetId() const;\n};\n\n\/*************************************************************************\/\nclass StringNode : public NameNode\n{\n virtual COMPARE Compare( const NameNode * ) const;\n virtual COMPARE Compare( const void * ) const;\n\nprotected:\n ByteString aName;\n\npublic:\n StringNode(){};\n StringNode( const ByteString & rStr ) { aName = rStr; }\n\n StringNode* Search( const char * ) const;\n ByteString GetName() const { return aName; }\n};\n\n#endif \/\/ _RSCTREE_HXX\nINTEGRATION: CWS warnings01 (1.4.8); FILE MERGED 2005\/10\/27 13:55:55 pl 1.4.8.1: #i55991# removed warnings for solaris platform\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rsctree.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 05:45:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _RSCTREE_HXX\n#define _RSCTREE_HXX\n\n#ifndef _LINK_HXX\n#include \n#endif\n\n#ifndef _RSCTOOLS_HXX\n#include \n#endif\n\n\/****************** C L A S S E S ****************************************\/\nclass BiNode\n{\nprotected:\n BiNode* pLeft; \/\/ left subtree\n BiNode* pRight; \/\/ right subtree\n\npublic:\n\n \/\/ Wandelt eine doppelt verkettete Liste in\n \/\/ einen binaeren Baum um\n BiNode * ChangeDLListBTree( BiNode * pList );\n\n BiNode();\n virtual ~BiNode();\n\n\n \/\/ Wandelt einen binaeren Baum in eine doppelt\n \/\/ verkettete Liste um\n BiNode* ChangeBTreeDLList();\n\n BiNode * Left() const { return pLeft ; };\n BiNode * Right() const{ return pRight ; };\n void EnumNodes( Link aLink ) const;\n};\n\n\/*************************************************************************\/\nclass NameNode : public BiNode\n{\n void SubOrderTree( NameNode * pOrderNode );\n\nprotected:\n \/\/ pCmp ist Zeiger auf Namen\n NameNode* Search( const void * pCmp ) const;\n\npublic:\n NameNode* Left() const { return (NameNode *)pLeft ; };\n NameNode* Right() const{ return (NameNode *)pRight ; };\n NameNode* Search( const NameNode * pName ) const;\n \/\/ insert a new node in the b-tree\n BOOL Insert( NameNode * pTN, sal_uInt32 * nDepth );\n BOOL Insert( NameNode* pTN );\n virtual COMPARE Compare( const NameNode * ) const;\n virtual COMPARE Compare( const void * ) const;\n NameNode* SearchParent( const NameNode * ) const;\n \/\/ return ist neue Root\n NameNode* Remove( NameNode * );\n void OrderTree();\n BOOL IsOrderTree() const;\n\n};\n\n\/*************************************************************************\/\nclass IdNode : public NameNode\n{\n virtual COMPARE Compare( const NameNode * ) const;\n virtual COMPARE Compare( const void * ) const;\nprotected:\n using NameNode::Search;\n\npublic:\n\n IdNode* Search( sal_uInt32 nTypName ) const;\n virtual sal_uInt32 GetId() const;\n};\n\n\/*************************************************************************\/\nclass StringNode : public NameNode\n{\n virtual COMPARE Compare( const NameNode * ) const;\n virtual COMPARE Compare( const void * ) const;\n\nprotected:\n using NameNode::Search;\n\n ByteString aName;\n\npublic:\n StringNode(){};\n StringNode( const ByteString & rStr ) { aName = rStr; }\n\n StringNode* Search( const char * ) const;\n ByteString GetName() const { return aName; }\n};\n\n#endif \/\/ _RSCTREE_HXX\n<|endoftext|>"} {"text":"\/*!\n \\copyright (c) RDO-Team, 2011\n \\file calc_relevant.inl\n \\authors \n \\authors (rdo@rk9.bmstu.ru)\n \\date 16.04.2011\n \\brief RDOCalc \n \\indent 4T\n*\/\n\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/runtime\/rdo_runtime.h\"\n#include \"simulator\/runtime\/rdo_activity.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_RUNTIME_NAMESPACE\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOSetRelResParamCalc\n\/\/ --------------------------------------------------------------------------------\ntemplate \ninline RDOSetRelResParamCalc::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)\n\t: m_relResID(relResID)\n\t, m_paramID (paramID )\n\t, m_pCalc (pCalc )\n{\n\tm_value = 1;\n\tif (m_pCalc)\n\t{\n\t\tsetSrcInfo(m_pCalc->src_info());\n\t}\n}\n\ntemplate \ninline RDOSetRelResParamCalc::~RDOSetRelResParamCalc()\n{}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->setResParamVal(resID, m_paramID, m_pCalc->calcValue(pRuntime));\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->getResParamValRaw(resID, m_paramID) \/= m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);\n\treturn m_value;\n}\n\nCLOSE_RDO_RUNTIME_NAMESPACE\n - калк возвращает значение параметра\/*!\n \\copyright (c) RDO-Team, 2011\n \\file calc_relevant.inl\n \\authors \n \\authors (rdo@rk9.bmstu.ru)\n \\date 16.04.2011\n \\brief RDOCalc \n \\indent 4T\n*\/\n\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/runtime\/rdo_runtime.h\"\n#include \"simulator\/runtime\/rdo_activity.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_RUNTIME_NAMESPACE\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOSetRelResParamCalc\n\/\/ --------------------------------------------------------------------------------\ntemplate \ninline RDOSetRelResParamCalc::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)\n\t: m_relResID(relResID)\n\t, m_paramID (paramID )\n\t, m_pCalc (pCalc )\n{\n\tm_value = 1;\n\tif (m_pCalc)\n\t{\n\t\tsetSrcInfo(m_pCalc->src_info());\n\t}\n}\n\ntemplate \ninline RDOSetRelResParamCalc::~RDOSetRelResParamCalc()\n{}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\tm_value = m_pCalc->calcValue(pRuntime);\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->setResParamVal(resID, m_paramID, m_value);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tm_value = pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tm_value = pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tm_value = pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tm_value = pRuntime->getResParamValRaw(resID, m_paramID) \/= m_pCalc->calcValue(pRuntime);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tm_value = pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);\n\treturn m_value;\n}\n\ntemplate <>\ninline REF(RDOValue) RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tm_value = pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);\n\treturn m_value;\n}\n\nCLOSE_RDO_RUNTIME_NAMESPACE\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/renderer\/p2p\/ipc_network_manager.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/sys_byteorder.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace content {\n\nIpcNetworkManager::IpcNetworkManager(P2PSocketDispatcher* socket_dispatcher)\n : socket_dispatcher_(socket_dispatcher),\n start_count_(0),\n network_list_received_(false),\n weak_factory_(this) {\n socket_dispatcher_->AddNetworkListObserver(this);\n}\n\nIpcNetworkManager::~IpcNetworkManager() {\n DCHECK(!start_count_);\n socket_dispatcher_->RemoveNetworkListObserver(this);\n}\n\nvoid IpcNetworkManager::StartUpdating() {\n if (network_list_received_) {\n \/\/ Post a task to avoid reentrancy.\n base::MessageLoop::current()->PostTask(\n FROM_HERE,\n base::Bind(&IpcNetworkManager::SendNetworksChangedSignal,\n weak_factory_.GetWeakPtr()));\n }\n ++start_count_;\n}\n\nvoid IpcNetworkManager::StopUpdating() {\n DCHECK_GT(start_count_, 0);\n --start_count_;\n}\n\nvoid IpcNetworkManager::OnNetworkListChanged(\n const net::NetworkInterfaceList& list) {\n\n \/\/ Update flag if network list received for the first time.\n if (!network_list_received_)\n network_list_received_ = true;\n\n std::vector networks;\n for (net::NetworkInterfaceList::const_iterator it = list.begin();\n it != list.end(); it++) {\n uint32 address;\n if (it->address.size() != net::kIPv4AddressSize)\n continue;\n memcpy(&address, &it->address[0], sizeof(uint32));\n address = talk_base::NetworkToHost32(address);\n talk_base::Network* network = new talk_base::Network(\n it->name, it->name, talk_base::IPAddress(address), 32);\n network->AddIP(talk_base::IPAddress(address));\n networks.push_back(network);\n }\n\n bool changed = false;\n MergeNetworkList(networks, &changed);\n if (changed)\n SignalNetworksChanged();\n}\n\nvoid IpcNetworkManager::SendNetworksChangedSignal() {\n SignalNetworksChanged();\n}\n\n} \/\/ namespace content\nPush IPv6 addresses to libjingle PortAllocator.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/renderer\/p2p\/ipc_network_manager.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/sys_byteorder.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace content {\n\nIpcNetworkManager::IpcNetworkManager(P2PSocketDispatcher* socket_dispatcher)\n : socket_dispatcher_(socket_dispatcher),\n start_count_(0),\n network_list_received_(false),\n weak_factory_(this) {\n socket_dispatcher_->AddNetworkListObserver(this);\n}\n\nIpcNetworkManager::~IpcNetworkManager() {\n DCHECK(!start_count_);\n socket_dispatcher_->RemoveNetworkListObserver(this);\n}\n\nvoid IpcNetworkManager::StartUpdating() {\n if (network_list_received_) {\n \/\/ Post a task to avoid reentrancy.\n base::MessageLoop::current()->PostTask(\n FROM_HERE,\n base::Bind(&IpcNetworkManager::SendNetworksChangedSignal,\n weak_factory_.GetWeakPtr()));\n }\n ++start_count_;\n}\n\nvoid IpcNetworkManager::StopUpdating() {\n DCHECK_GT(start_count_, 0);\n --start_count_;\n}\n\nvoid IpcNetworkManager::OnNetworkListChanged(\n const net::NetworkInterfaceList& list) {\n\n \/\/ Update flag if network list received for the first time.\n if (!network_list_received_)\n network_list_received_ = true;\n\n \/\/ Note: 32 and 64 are the arbitrary(kind of) prefix length used to\n \/\/ differentiate IPv4 and IPv6 addresses.\n \/\/ talk_base::Network uses these prefix_length to compare network\n \/\/ interfaces discovered.\n std::vector networks;\n for (net::NetworkInterfaceList::const_iterator it = list.begin();\n it != list.end(); it++) {\n if (it->address.size() == net::kIPv4AddressSize) {\n uint32 address;\n memcpy(&address, &it->address[0], sizeof(uint32));\n address = talk_base::NetworkToHost32(address);\n talk_base::Network* network = new talk_base::Network(\n it->name, it->name, talk_base::IPAddress(address), 32);\n network->AddIP(talk_base::IPAddress(address));\n networks.push_back(network);\n } else if (it->address.size() == net::kIPv6AddressSize) {\n in6_addr address;\n memcpy(&address, &it->address[0], sizeof(in6_addr));\n talk_base::IPAddress ip6_addr(address);\n if (!talk_base::IPIsPrivate(ip6_addr)) {\n talk_base::Network* network = new talk_base::Network(\n it->name, it->name, ip6_addr, 64);\n network->AddIP(ip6_addr);\n networks.push_back(network);\n }\n }\n }\n\n bool changed = false;\n MergeNetworkList(networks, &changed);\n if (changed)\n SignalNetworksChanged();\n}\n\nvoid IpcNetworkManager::SendNetworksChangedSignal() {\n SignalNetworksChanged();\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"xwalk\/runtime\/browser\/image_util.h\"\n#include \"xwalk\/runtime\/browser\/runtime.h\"\n#include \"xwalk\/runtime\/browser\/runtime_registry.h\"\n#include \"xwalk\/runtime\/common\/xwalk_notification_types.h\"\n#include \"xwalk\/test\/base\/in_process_browser_test.h\"\n#include \"xwalk\/test\/base\/xwalk_test_utils.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/navigation_entry.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_observer.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/public\/test\/test_utils.h\"\n#include \"net\/base\/net_util.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \/\/ NOLINT(build\/include_order)\n#endif\n\nusing xwalk::NativeAppWindow;\nusing xwalk::Runtime;\nusing xwalk::RuntimeRegistry;\nusing xwalk::RuntimeList;\nusing content::WebContents;\nusing testing::_;\n\n\/\/ A mock observer to listen runtime registry changes.\nclass MockRuntimeRegistryObserver : public xwalk::RuntimeRegistryObserver {\n public:\n MockRuntimeRegistryObserver() {}\n virtual ~MockRuntimeRegistryObserver() {}\n\n MOCK_METHOD1(OnRuntimeAdded, void(Runtime* runtime));\n MOCK_METHOD1(OnRuntimeRemoved, void(Runtime* runtime));\n MOCK_METHOD1(OnRuntimeAppIconChanged, void(Runtime* runtime));\n\n private:\n DISALLOW_COPY_AND_ASSIGN(MockRuntimeRegistryObserver);\n};\n\n\/\/ An observer used to verify app icon change.\nclass FaviconChangedObserver : public xwalk::RuntimeRegistryObserver {\n public:\n explicit FaviconChangedObserver(const base::FilePath& icon_file)\n : icon_file_(icon_file) {\n }\n\n virtual ~FaviconChangedObserver() {}\n\n virtual void OnRuntimeAdded(Runtime* runtime) OVERRIDE {}\n\n virtual void OnRuntimeRemoved(Runtime* runtime) OVERRIDE {}\n\n virtual void OnRuntimeAppIconChanged(Runtime* runtime) OVERRIDE {\n const base::FilePath::StringType kPNGFormat(FILE_PATH_LITERAL(\".png\"));\n const base::FilePath::StringType kICOFormat(FILE_PATH_LITERAL(\".ico\"));\n\n gfx::Image image;\n image = xwalk_utils::LoadImageFromFilePath(icon_file_);\n\n EXPECT_FALSE(image.IsEmpty());\n gfx::Image icon = runtime->app_icon();\n EXPECT_FALSE(icon.IsEmpty());\n EXPECT_EQ(image.Size(), icon.Size());\n\n \/\/ Quit the message loop.\n MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());\n }\n\n private:\n const base::FilePath& icon_file_;\n};\n\n\/\/ Observer for NOTIFICATION_FULLSCREEN_CHANGED notifications.\nclass FullscreenNotificationObserver\n : public content::WindowedNotificationObserver {\n public:\n FullscreenNotificationObserver() : WindowedNotificationObserver(\n xwalk::NOTIFICATION_FULLSCREEN_CHANGED,\n content::NotificationService::AllSources()) {}\n private:\n DISALLOW_COPY_AND_ASSIGN(FullscreenNotificationObserver);\n};\n\nclass XWalkRuntimeTest : public InProcessBrowserTest {\n public:\n XWalkRuntimeTest() {}\n virtual ~XWalkRuntimeTest() {\n original_runtimes_.clear();\n notification_observer_.reset();\n }\n\n void Relaunch(const CommandLine& new_command_line) {\n base::LaunchProcess(new_command_line, base::LaunchOptions(), NULL);\n }\n\n \/\/ SetUpOnMainThread is called after BrowserMainRunner was initialized and\n \/\/ just before RunTestOnMainThread (aka. TestBody).\n virtual void SetUpOnMainThread() OVERRIDE {\n notification_observer_.reset(\n new content::WindowedNotificationObserver(\n xwalk::NOTIFICATION_RUNTIME_OPENED,\n content::NotificationService::AllSources()));\n const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();\n for (RuntimeList::const_iterator it = runtimes.begin();\n it != runtimes.end(); ++it)\n original_runtimes_.push_back(*it);\n }\n\n \/\/ Block UI thread until a new Runtime instance is created.\n Runtime* WaitForSingleNewRuntime() {\n notification_observer_->Wait();\n const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();\n for (RuntimeList::const_iterator it = runtimes.begin();\n it != runtimes.end(); ++it) {\n RuntimeList::iterator target =\n std::find(original_runtimes_.begin(), original_runtimes_.end(), *it);\n \/\/ Not found means a new one.\n if (target == original_runtimes_.end()) {\n original_runtimes_.push_back(*it);\n return *it;\n }\n }\n return NULL;\n }\n\n private:\n RuntimeList original_runtimes_;\n scoped_ptr notification_observer_;\n};\n\n\/\/ FIXME(hmin): Since currently the browser process is not shared by multiple\n\/\/ app launch, this test is disabled to avoid floody launches.\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, DISABLED_SecondLaunch) {\n MockRuntimeRegistryObserver observer;\n RuntimeRegistry::Get()->AddObserver(&observer);\n Relaunch(GetCommandLineForRelaunch());\n\n Runtime* second_runtime = NULL;\n EXPECT_TRUE(second_runtime == WaitForSingleNewRuntime());\n EXPECT_CALL(observer, OnRuntimeAdded(second_runtime)).Times(1);\n ASSERT_EQ(2u, RuntimeRegistry::Get()->runtimes().size());\n\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CreateAndCloseRuntime) {\n MockRuntimeRegistryObserver observer;\n RuntimeRegistry::Get()->AddObserver(&observer);\n \/\/ At least one Runtime instance is created at startup.\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n ASSERT_EQ(1, len);\n\n \/\/ Create a new Runtime instance.\n GURL url(test_server()->GetURL(\"test.html\"));\n EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);\n Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);\n EXPECT_TRUE(url == new_runtime->web_contents()->GetURL());\n EXPECT_EQ(new_runtime, WaitForSingleNewRuntime());\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());\n\n \/\/ Close the newly created Runtime instance.\n EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);\n new_runtime->Close();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());\n\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LoadURLAndClose) {\n GURL url(test_server()->GetURL(\"test.html\"));\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n runtime()->LoadURL(url);\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());\n runtime()->Close();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CloseNativeWindow) {\n GURL url(test_server()->GetURL(\"test.html\"));\n Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n new_runtime->window()->Close();\n content::RunAllPendingInMessageLoop();\n \/\/ Closing native window will lead to close Runtime instance.\n EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LaunchWithFullscreenWindow) {\n MockRuntimeRegistryObserver observer;\n RuntimeRegistry::Get()->AddObserver(&observer);\n \/\/ At least one Runtime instance is created at startup.\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n ASSERT_EQ(1, len);\n \/\/ Original Runtime should has non fullscreen window.\n EXPECT_TRUE(false == runtime()->window()->IsFullscreen());\n\n \/\/ Add \"--fullscreen\" launch argument.\n CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n cmd_line->AppendSwitch(\"fullscreen\");\n\n \/\/ Create a new Runtime instance.\n FullscreenNotificationObserver fullscreen_observer;\n GURL url(test_server()->GetURL(\"test.html\"));\n EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);\n Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());\n fullscreen_observer.Wait();\n EXPECT_TRUE(true == new_runtime->window()->IsFullscreen());\n\n \/\/ Close the newly created Runtime instance.\n EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);\n new_runtime->Close();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());\n\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, HTML5FullscreenAPI) {\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(), base::FilePath().AppendASCII(\"fullscreen.html\"));\n xwalk_test_utils::NavigateToURL(runtime(), url);\n EXPECT_TRUE(false == runtime()->window()->IsFullscreen());\n\n FullscreenNotificationObserver enter_observer;\n runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(\n string16(),\n ASCIIToUTF16(\"doFullscreenClick();\"));\n content::RunAllPendingInMessageLoop();\n enter_observer.Wait();\n \/\/ Calling doFullscreenClick defined in fullscreen.html leads to enter into\n \/\/ fullscreen window state, so it's expected to be fullscreen.\n EXPECT_TRUE(true == runtime()->window()->IsFullscreen());\n\n FullscreenNotificationObserver exit_observer;\n runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(\n string16(),\n ASCIIToUTF16(\"doExitFullscreenClick();\"));\n content::RunAllPendingInMessageLoop();\n exit_observer.Wait();\n \/\/ Calling doExitFullscreenClick defined in fullscreen.html leads to exit\n \/\/ fullscreen window state, so it's expected to be not fullscreen.\n EXPECT_TRUE(false == runtime()->window()->IsFullscreen());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, GetWindowTitle) {\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(), base::FilePath().AppendASCII(\"title.html\"));\n string16 title = ASCIIToUTF16(\"Dummy Title\");\n content::TitleWatcher title_watcher(runtime()->web_contents(), title);\n xwalk_test_utils::NavigateToURL(runtime(), url);\n EXPECT_EQ(title, title_watcher.WaitAndGetTitle());\n\n NativeAppWindow* window = runtime()->window();\n#if defined(TOOLKIT_GTK)\n const char* window_title = gtk_window_get_title(window->GetNativeWindow());\n EXPECT_EQ(title, ASCIIToUTF16(window_title));\n#elif defined(TOOLKIT_VIEWS)\n const int len = title.length() + 1; \/\/ NULL-terminated string.\n string16 window_title;\n ::GetWindowText(window->GetNativeWindow(),\n WriteInto(&window_title, len), len);\n EXPECT_EQ(title, window_title);\n#endif \/\/ defined(TOOLKIT_GTK)\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, OpenLinkInNewRuntime) {\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(), base::FilePath().AppendASCII(\"new_target.html\"));\n xwalk_test_utils::NavigateToURL(runtime(), url);\n runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(\n string16(),\n ASCIIToUTF16(\"doClick();\"));\n content::RunAllPendingInMessageLoop();\n \/\/ Calling doClick defined in new_target.html leads to open a href in a new\n \/\/ target window, and so it is expected to create a new Runtime instance.\n Runtime* second = WaitForSingleNewRuntime();\n EXPECT_TRUE(NULL != second);\n EXPECT_NE(runtime(), second);\n EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_ICO) {\n base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath(FILE_PATH_LITERAL(\"16x16.ico\"))));\n\n FaviconChangedObserver observer(icon_file);\n RuntimeRegistry::Get()->AddObserver(&observer);\n\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath().AppendASCII(\"favicon_ico.html\"));\n\n xwalk_test_utils::NavigateToURL(runtime(), url);\n content::RunMessageLoop();\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_PNG) {\n base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath(FILE_PATH_LITERAL(\"48x48.png\"))));\n\n FaviconChangedObserver observer(icon_file);\n RuntimeRegistry::Get()->AddObserver(&observer);\n\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath().AppendASCII(\"favicon_png.html\"));\n\n xwalk_test_utils::NavigateToURL(runtime(), url);\n content::RunMessageLoop();\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\nAura: fix the runtime browser test.\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"xwalk\/runtime\/browser\/image_util.h\"\n#include \"xwalk\/runtime\/browser\/runtime.h\"\n#include \"xwalk\/runtime\/browser\/runtime_registry.h\"\n#include \"xwalk\/runtime\/common\/xwalk_notification_types.h\"\n#include \"xwalk\/test\/base\/in_process_browser_test.h\"\n#include \"xwalk\/test\/base\/xwalk_test_utils.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/navigation_entry.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_observer.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/public\/test\/test_utils.h\"\n#include \"net\/base\/net_util.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \/\/ NOLINT(build\/include_order)\n#endif\n\n#if defined(USE_AURA)\n#include \"ui\/aura\/window.h\"\n#endif\n\nusing xwalk::NativeAppWindow;\nusing xwalk::Runtime;\nusing xwalk::RuntimeRegistry;\nusing xwalk::RuntimeList;\nusing content::WebContents;\nusing testing::_;\n\n\/\/ A mock observer to listen runtime registry changes.\nclass MockRuntimeRegistryObserver : public xwalk::RuntimeRegistryObserver {\n public:\n MockRuntimeRegistryObserver() {}\n virtual ~MockRuntimeRegistryObserver() {}\n\n MOCK_METHOD1(OnRuntimeAdded, void(Runtime* runtime));\n MOCK_METHOD1(OnRuntimeRemoved, void(Runtime* runtime));\n MOCK_METHOD1(OnRuntimeAppIconChanged, void(Runtime* runtime));\n\n private:\n DISALLOW_COPY_AND_ASSIGN(MockRuntimeRegistryObserver);\n};\n\n\/\/ An observer used to verify app icon change.\nclass FaviconChangedObserver : public xwalk::RuntimeRegistryObserver {\n public:\n explicit FaviconChangedObserver(const base::FilePath& icon_file)\n : icon_file_(icon_file) {\n }\n\n virtual ~FaviconChangedObserver() {}\n\n virtual void OnRuntimeAdded(Runtime* runtime) OVERRIDE {}\n\n virtual void OnRuntimeRemoved(Runtime* runtime) OVERRIDE {}\n\n virtual void OnRuntimeAppIconChanged(Runtime* runtime) OVERRIDE {\n const base::FilePath::StringType kPNGFormat(FILE_PATH_LITERAL(\".png\"));\n const base::FilePath::StringType kICOFormat(FILE_PATH_LITERAL(\".ico\"));\n\n gfx::Image image;\n image = xwalk_utils::LoadImageFromFilePath(icon_file_);\n\n EXPECT_FALSE(image.IsEmpty());\n gfx::Image icon = runtime->app_icon();\n EXPECT_FALSE(icon.IsEmpty());\n EXPECT_EQ(image.Size(), icon.Size());\n\n \/\/ Quit the message loop.\n MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());\n }\n\n private:\n const base::FilePath& icon_file_;\n};\n\n\/\/ Observer for NOTIFICATION_FULLSCREEN_CHANGED notifications.\nclass FullscreenNotificationObserver\n : public content::WindowedNotificationObserver {\n public:\n FullscreenNotificationObserver() : WindowedNotificationObserver(\n xwalk::NOTIFICATION_FULLSCREEN_CHANGED,\n content::NotificationService::AllSources()) {}\n private:\n DISALLOW_COPY_AND_ASSIGN(FullscreenNotificationObserver);\n};\n\nclass XWalkRuntimeTest : public InProcessBrowserTest {\n public:\n XWalkRuntimeTest() {}\n virtual ~XWalkRuntimeTest() {\n original_runtimes_.clear();\n notification_observer_.reset();\n }\n\n void Relaunch(const CommandLine& new_command_line) {\n base::LaunchProcess(new_command_line, base::LaunchOptions(), NULL);\n }\n\n \/\/ SetUpOnMainThread is called after BrowserMainRunner was initialized and\n \/\/ just before RunTestOnMainThread (aka. TestBody).\n virtual void SetUpOnMainThread() OVERRIDE {\n notification_observer_.reset(\n new content::WindowedNotificationObserver(\n xwalk::NOTIFICATION_RUNTIME_OPENED,\n content::NotificationService::AllSources()));\n const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();\n for (RuntimeList::const_iterator it = runtimes.begin();\n it != runtimes.end(); ++it)\n original_runtimes_.push_back(*it);\n }\n\n \/\/ Block UI thread until a new Runtime instance is created.\n Runtime* WaitForSingleNewRuntime() {\n notification_observer_->Wait();\n const RuntimeList& runtimes = RuntimeRegistry::Get()->runtimes();\n for (RuntimeList::const_iterator it = runtimes.begin();\n it != runtimes.end(); ++it) {\n RuntimeList::iterator target =\n std::find(original_runtimes_.begin(), original_runtimes_.end(), *it);\n \/\/ Not found means a new one.\n if (target == original_runtimes_.end()) {\n original_runtimes_.push_back(*it);\n return *it;\n }\n }\n return NULL;\n }\n\n private:\n RuntimeList original_runtimes_;\n scoped_ptr notification_observer_;\n};\n\n\/\/ FIXME(hmin): Since currently the browser process is not shared by multiple\n\/\/ app launch, this test is disabled to avoid floody launches.\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, DISABLED_SecondLaunch) {\n MockRuntimeRegistryObserver observer;\n RuntimeRegistry::Get()->AddObserver(&observer);\n Relaunch(GetCommandLineForRelaunch());\n\n Runtime* second_runtime = NULL;\n EXPECT_TRUE(second_runtime == WaitForSingleNewRuntime());\n EXPECT_CALL(observer, OnRuntimeAdded(second_runtime)).Times(1);\n ASSERT_EQ(2u, RuntimeRegistry::Get()->runtimes().size());\n\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CreateAndCloseRuntime) {\n MockRuntimeRegistryObserver observer;\n RuntimeRegistry::Get()->AddObserver(&observer);\n \/\/ At least one Runtime instance is created at startup.\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n ASSERT_EQ(1, len);\n\n \/\/ Create a new Runtime instance.\n GURL url(test_server()->GetURL(\"test.html\"));\n EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);\n Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);\n EXPECT_TRUE(url == new_runtime->web_contents()->GetURL());\n EXPECT_EQ(new_runtime, WaitForSingleNewRuntime());\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());\n\n \/\/ Close the newly created Runtime instance.\n EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);\n new_runtime->Close();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());\n\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LoadURLAndClose) {\n GURL url(test_server()->GetURL(\"test.html\"));\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n runtime()->LoadURL(url);\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());\n runtime()->Close();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, CloseNativeWindow) {\n GURL url(test_server()->GetURL(\"test.html\"));\n Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n new_runtime->window()->Close();\n content::RunAllPendingInMessageLoop();\n \/\/ Closing native window will lead to close Runtime instance.\n EXPECT_EQ(len - 1, RuntimeRegistry::Get()->runtimes().size());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, LaunchWithFullscreenWindow) {\n MockRuntimeRegistryObserver observer;\n RuntimeRegistry::Get()->AddObserver(&observer);\n \/\/ At least one Runtime instance is created at startup.\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n ASSERT_EQ(1, len);\n \/\/ Original Runtime should has non fullscreen window.\n EXPECT_TRUE(false == runtime()->window()->IsFullscreen());\n\n \/\/ Add \"--fullscreen\" launch argument.\n CommandLine* cmd_line = CommandLine::ForCurrentProcess();\n cmd_line->AppendSwitch(\"fullscreen\");\n\n \/\/ Create a new Runtime instance.\n FullscreenNotificationObserver fullscreen_observer;\n GURL url(test_server()->GetURL(\"test.html\"));\n EXPECT_CALL(observer, OnRuntimeAdded(_)).Times(1);\n Runtime* new_runtime = Runtime::Create(runtime()->runtime_context(), url);\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());\n fullscreen_observer.Wait();\n EXPECT_TRUE(true == new_runtime->window()->IsFullscreen());\n\n \/\/ Close the newly created Runtime instance.\n EXPECT_CALL(observer, OnRuntimeRemoved(new_runtime)).Times(1);\n new_runtime->Close();\n content::RunAllPendingInMessageLoop();\n EXPECT_EQ(len, RuntimeRegistry::Get()->runtimes().size());\n\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, HTML5FullscreenAPI) {\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(), base::FilePath().AppendASCII(\"fullscreen.html\"));\n xwalk_test_utils::NavigateToURL(runtime(), url);\n EXPECT_TRUE(false == runtime()->window()->IsFullscreen());\n\n FullscreenNotificationObserver enter_observer;\n runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(\n string16(),\n ASCIIToUTF16(\"doFullscreenClick();\"));\n content::RunAllPendingInMessageLoop();\n enter_observer.Wait();\n \/\/ Calling doFullscreenClick defined in fullscreen.html leads to enter into\n \/\/ fullscreen window state, so it's expected to be fullscreen.\n EXPECT_TRUE(true == runtime()->window()->IsFullscreen());\n\n FullscreenNotificationObserver exit_observer;\n runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(\n string16(),\n ASCIIToUTF16(\"doExitFullscreenClick();\"));\n content::RunAllPendingInMessageLoop();\n exit_observer.Wait();\n \/\/ Calling doExitFullscreenClick defined in fullscreen.html leads to exit\n \/\/ fullscreen window state, so it's expected to be not fullscreen.\n EXPECT_TRUE(false == runtime()->window()->IsFullscreen());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, GetWindowTitle) {\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(), base::FilePath().AppendASCII(\"title.html\"));\n string16 title = ASCIIToUTF16(\"Dummy Title\");\n content::TitleWatcher title_watcher(runtime()->web_contents(), title);\n xwalk_test_utils::NavigateToURL(runtime(), url);\n EXPECT_EQ(title, title_watcher.WaitAndGetTitle());\n\n NativeAppWindow* window = runtime()->window();\n#if defined(TOOLKIT_GTK)\n const char* window_title = gtk_window_get_title(window->GetNativeWindow());\n EXPECT_EQ(title, ASCIIToUTF16(window_title));\n#elif defined(TOOLKIT_VIEWS) && defined(OS_WIN)\n const int len = title.length() + 1; \/\/ NULL-terminated string.\n string16 window_title;\n ::GetWindowText(window->GetNativeWindow(),\n WriteInto(&window_title, len), len);\n EXPECT_EQ(title, window_title);\n#elif defined(USE_AURA)\n string16 window_title = window->GetNativeWindow()->title();\n EXPECT_EQ(title, window_title);\n#endif \/\/ defined(TOOLKIT_GTK)\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, OpenLinkInNewRuntime) {\n size_t len = RuntimeRegistry::Get()->runtimes().size();\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(), base::FilePath().AppendASCII(\"new_target.html\"));\n xwalk_test_utils::NavigateToURL(runtime(), url);\n runtime()->web_contents()->GetRenderViewHost()->ExecuteJavascriptInWebFrame(\n string16(),\n ASCIIToUTF16(\"doClick();\"));\n content::RunAllPendingInMessageLoop();\n \/\/ Calling doClick defined in new_target.html leads to open a href in a new\n \/\/ target window, and so it is expected to create a new Runtime instance.\n Runtime* second = WaitForSingleNewRuntime();\n EXPECT_TRUE(NULL != second);\n EXPECT_NE(runtime(), second);\n EXPECT_EQ(len + 1, RuntimeRegistry::Get()->runtimes().size());\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_ICO) {\n base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath(FILE_PATH_LITERAL(\"16x16.ico\"))));\n\n FaviconChangedObserver observer(icon_file);\n RuntimeRegistry::Get()->AddObserver(&observer);\n\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath().AppendASCII(\"favicon_ico.html\"));\n\n xwalk_test_utils::NavigateToURL(runtime(), url);\n content::RunMessageLoop();\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n\nIN_PROC_BROWSER_TEST_F(XWalkRuntimeTest, FaviconTest_PNG) {\n base::FilePath icon_file(xwalk_test_utils::GetTestFilePath(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath(FILE_PATH_LITERAL(\"48x48.png\"))));\n\n FaviconChangedObserver observer(icon_file);\n RuntimeRegistry::Get()->AddObserver(&observer);\n\n GURL url = xwalk_test_utils::GetTestURL(\n base::FilePath(FILE_PATH_LITERAL(\"favicon\")),\n base::FilePath().AppendASCII(\"favicon_png.html\"));\n\n xwalk_test_utils::NavigateToURL(runtime(), url);\n content::RunMessageLoop();\n RuntimeRegistry::Get()->RemoveObserver(&observer);\n}\n<|endoftext|>"} {"text":"\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/xml\/ListOfUnsupportedAnnotations.cpp,v $\n\/\/ $Revision: 1.1 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2012\/05\/25 12:13:29 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2012 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/*\n * ListOfUnsupportedAnnotations.cpp\n *\n * Created on: May 24, 2012\n * Author: shoops\n *\/\n\n#include \"copasi.h\"\n\n#include \"CExpat.h\"\n#include \"CCopasiXMLParser.h\"\n#include \"CCopasiXMLInterface.h\"\n\n#define START_ELEMENT -1\n#define UNKNOWN_ELEMENT -2\n\nCCopasiXMLParser::UnsupportedAnnotationElement::UnsupportedAnnotationElement(CCopasiXMLParser & parser,\n SCopasiXMLParserCommon & common):\n CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),\n mName(),\n mXML(),\n mLevel(0),\n mElementEmpty()\n{}\n\n\/\/ virtual\nCCopasiXMLParser::UnsupportedAnnotationElement::~UnsupportedAnnotationElement()\n{}\n\n\/\/ virtual\nvoid CCopasiXMLParser::UnsupportedAnnotationElement::start(const XML_Char *pszName,\n const XML_Char **papszAttrs)\n{\n mCurrentElement++; \/* We should always be on the next element *\/\n const XML_Char ** ppAttrs;\n\n if (mLevel) mCurrentElement = Content;\n\n switch (mCurrentElement)\n {\n case UnsupportedAnnotation:\n\n if (strcmp(pszName, \"UnsupportedAnnotation\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,\n pszName, \"UnsupportedAnnotation\", mParser.getCurrentLineNumber());\n\n mName = mParser.getAttributeValue(\"name\", papszAttrs);\n mXML.str(\"\");\n mLevel = 0;\n mParser.enableCharacterDataHandler();\n mElementEmpty.push(false);\n break;\n\n case Content:\n\n if (mElementEmpty.top() == true)\n {\n mXML << \">\";\n mElementEmpty.top() = false;\n }\n\n mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);\n mXML << \"<\" << pszName;\n\n for (ppAttrs = papszAttrs; *ppAttrs && **ppAttrs; ppAttrs += 2)\n mXML << \" \" << *ppAttrs << \"=\\\"\"\n << CCopasiXMLInterface::encode(*(ppAttrs + 1), CCopasiXMLInterface::attribute) << \"\\\"\";\n\n mLevel++;\n mElementEmpty.push(true);\n\n mParser.enableCharacterDataHandler();\n break;\n\n default:\n mLastKnownElement = mCurrentElement - 1;\n mCurrentElement = UNKNOWN_ELEMENT;\n mParser.pushElementHandler(&mParser.mUnknownElement);\n mParser.onStartElement(pszName, papszAttrs);\n break;\n }\n\n return;\n}\n\n\/\/ virtual\nvoid CCopasiXMLParser::UnsupportedAnnotationElement::end(const XML_Char *pszName)\n{\n std::string XML;\n\n switch (mCurrentElement)\n {\n case UnsupportedAnnotation:\n\n if (strcmp(pszName, \"UnsupportedAnnotation\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"UnsupportedAnnotation\", mParser.getCurrentLineNumber());\n\n mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);\n\n XML = mXML.str();\n\n {\n \/\/ remove leading whitepsaces\n std::string::size_type pos = XML.find_first_not_of(\"\\x0a\\x0d\\t \");\n\n if (pos != 0) XML.erase(0, pos);\n\n \/\/ remove trailing whitepsace\n pos = XML.find_last_not_of(\"\\x0a\\x0d\\t \");\n\n if (pos < XML.length())\n XML = XML.substr(0, pos + 1);\n }\n\n mXML.str(XML);\n\n mParser.popElementHandler();\n mCurrentElement = START_ELEMENT;\n mElementEmpty.pop();\n\n deleteCurrentHandler();\n\n \/* Tell the parent element we are done. *\/\n mParser.onEndElement(pszName);\n break;\n\n case Content:\n XML = mParser.getCharacterData();\n\n \/\/ Check whether and how we need to close the element\n if (mElementEmpty.top() == true)\n {\n if (XML != \"\")\n {\n mElementEmpty.top() = false;\n mXML << \">\";\n }\n else\n mXML << \" \/>\";\n }\n\n if (XML != \"\")\n mXML << CCopasiXMLInterface::encode(XML, CCopasiXMLInterface::character);\n\n if (mElementEmpty.top() == false)\n mXML << \"<\/\" << pszName << \">\";\n\n mElementEmpty.pop();\n mElementEmpty.top() = false;\n mLevel--;\n\n if (!mLevel) mCurrentElement = UnsupportedAnnotation;\n\n mParser.enableCharacterDataHandler();\n break;\n\n case UNKNOWN_ELEMENT:\n mCurrentElement = mLastKnownElement;\n break;\n\n default:\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"???\", mParser.getCurrentLineNumber());\n break;\n }\n\n return;\n}\n\nconst std::string & CCopasiXMLParser::UnsupportedAnnotationElement::getName() const\n{\n return mName;\n}\n\nstd::string CCopasiXMLParser::UnsupportedAnnotationElement::getXML() const\n{\n return mXML.str();\n}\n\nCCopasiXMLParser::ListOfUnsupportedAnnotationsElement::ListOfUnsupportedAnnotationsElement(CCopasiXMLParser & parser,\n SCopasiXMLParserCommon & common):\n CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),\n mUnsupportedAnnotations(),\n mpUnsupportedAnnotationElement(NULL)\n{}\n\n\/\/ virtual\nCCopasiXMLParser::ListOfUnsupportedAnnotationsElement::~ListOfUnsupportedAnnotationsElement()\n{\n pdelete(mpUnsupportedAnnotationElement);\n}\n\n\/\/ virtual\nvoid CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::start(const XML_Char *pszName,\n const XML_Char **papszAttrs)\n{\n mpCurrentHandler = NULL;\n mCurrentElement = mLastKnownElement;\n\n while (mpCurrentHandler == NULL)\n {\n mCurrentElement++; \/* We should always be on the next element *\/\n\n switch (mCurrentElement)\n {\n case ListOfUnsupportedAnnotations:\n\n if (strcmp(pszName, \"ListOfUnsupportedAnnotations\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,\n pszName, \"ListOfUnsupportedAnnotations\", mParser.getCurrentLineNumber());\n\n mLastKnownElement = ListOfUnsupportedAnnotations;\n mUnsupportedAnnotations.clear();\n\n return;\n\n case UnsupportedAnnotation:\n\n if (!strcmp(pszName, \"UnsupportedAnnotation\"))\n {\n \/* If we do not have a ModelParameterSet element handler we create one. *\/\n if (!mpUnsupportedAnnotationElement)\n mpUnsupportedAnnotationElement = new UnsupportedAnnotationElement(mParser, mCommon);\n\n mpCurrentHandler = mpUnsupportedAnnotationElement;\n }\n\n break;\n\n default:\n mCurrentElement = UNKNOWN_ELEMENT;\n mpCurrentHandler = &mParser.mUnknownElement;\n break;\n }\n }\n\n mParser.pushElementHandler(mpCurrentHandler);\n\n if (mpCurrentHandler != &mParser.mUnknownElement)\n {\n mLastKnownElement = mCurrentElement;\n }\n\n mParser.onStartElement(pszName, papszAttrs);\n}\n\n\/\/ virtual\nvoid CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::end(const XML_Char *pszName)\n{\n switch (mCurrentElement)\n {\n case ListOfUnsupportedAnnotations:\n\n if (strcmp(pszName, \"ListOfUnsupportedAnnotations\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"ListOfUnsupportedAnnotations\", mParser.getCurrentLineNumber());\n\n mParser.popElementHandler();\n mCurrentElement = START_ELEMENT;\n\n \/* Tell the parent element we are done. *\/\n mParser.onEndElement(pszName);\n break;\n\n case UnsupportedAnnotation:\n\n if (strcmp(pszName, \"UnsupportedAnnotation\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"UnsupportedAnnotation\", mParser.getCurrentLineNumber());\n\n if (mpUnsupportedAnnotationElement != NULL)\n {\n mUnsupportedAnnotations[mpUnsupportedAnnotationElement->getName()] =\n mpUnsupportedAnnotationElement->getXML();\n }\n\n mCurrentElement = ListOfUnsupportedAnnotations;\n break;\n\n case UNKNOWN_ELEMENT:\n mCurrentElement = mLastKnownElement;\n break;\n\n default:\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"???\", mParser.getCurrentLineNumber());\n break;\n }\n\n return;\n}\n\nconst CAnnotation::UnsupportedAnnotation & CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::getUnsupportedAnnotations() const\n{\n return mUnsupportedAnnotations;\n}\n- first attempt of fixing the issue of reading unsupported annotations\/\/ Copyright (C) 2012 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/*\n * ListOfUnsupportedAnnotations.cpp\n *\n * Created on: May 24, 2012\n * Author: shoops\n *\/\n\n#include \"copasi.h\"\n\n#include \"CExpat.h\"\n#include \"CCopasiXMLParser.h\"\n#include \"CCopasiXMLInterface.h\"\n\n#define START_ELEMENT -1\n#define UNKNOWN_ELEMENT -2\n\nCCopasiXMLParser::UnsupportedAnnotationElement::UnsupportedAnnotationElement(CCopasiXMLParser & parser,\n SCopasiXMLParserCommon & common):\n CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),\n mName(),\n mXML(),\n mLevel(0),\n mElementEmpty()\n{}\n\n\/\/ virtual\nCCopasiXMLParser::UnsupportedAnnotationElement::~UnsupportedAnnotationElement()\n{}\n\n\/\/ virtual\nvoid CCopasiXMLParser::UnsupportedAnnotationElement::start(const XML_Char *pszName,\n const XML_Char **papszAttrs)\n{\n mCurrentElement++; \/* We should always be on the next element *\/\n const XML_Char ** ppAttrs;\n\n if (mLevel) mCurrentElement = Content;\n\n switch (mCurrentElement)\n {\n case UnsupportedAnnotation:\n\n if (strcmp(pszName, \"UnsupportedAnnotation\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,\n pszName, \"UnsupportedAnnotation\", mParser.getCurrentLineNumber());\n\n mName = mParser.getAttributeValue(\"name\", papszAttrs);\n mXML.str(\"\");\n mLevel = 0;\n mParser.enableCharacterDataHandler();\n mElementEmpty.push(false);\n break;\n\n case Content:\n\n if (mElementEmpty.top() == true)\n {\n mXML << \">\";\n mElementEmpty.top() = false;\n }\n\n mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);\n mXML << \"<\" << pszName;\n\n for (ppAttrs = papszAttrs; *ppAttrs && **ppAttrs; ppAttrs += 2)\n mXML << \" \" << *ppAttrs << \"=\\\"\"\n << CCopasiXMLInterface::encode(*(ppAttrs + 1), CCopasiXMLInterface::attribute) << \"\\\"\";\n\n mLevel++;\n mElementEmpty.push(true);\n\n mParser.enableCharacterDataHandler();\n break;\n\n default:\n mLastKnownElement = mCurrentElement - 1;\n mCurrentElement = UNKNOWN_ELEMENT;\n mParser.pushElementHandler(&mParser.mUnknownElement);\n mParser.onStartElement(pszName, papszAttrs);\n break;\n }\n\n return;\n}\n\n\/\/ virtual\nvoid CCopasiXMLParser::UnsupportedAnnotationElement::end(const XML_Char *pszName)\n{\n std::string XML;\n\n switch (mCurrentElement)\n {\n case UnsupportedAnnotation:\n\n if (strcmp(pszName, \"UnsupportedAnnotation\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"UnsupportedAnnotation\", mParser.getCurrentLineNumber());\n\n mXML << CCopasiXMLInterface::encode(mParser.getCharacterData(), CCopasiXMLInterface::character);\n\n XML = mXML.str();\n\n {\n \/\/ remove leading whitepsaces\n std::string::size_type pos = XML.find_first_not_of(\"\\x0a\\x0d\\t \");\n\n if (pos != 0) XML.erase(0, pos);\n\n \/\/ remove trailing whitepsace\n pos = XML.find_last_not_of(\"\\x0a\\x0d\\t \");\n\n if (pos < XML.length())\n XML = XML.substr(0, pos + 1);\n }\n\n mXML.str(XML);\n\n mParser.popElementHandler();\n mCurrentElement = START_ELEMENT;\n mElementEmpty.pop();\n\n deleteCurrentHandler();\n\n \/* Tell the parent element we are done. *\/\n mParser.onEndElement(pszName);\n break;\n\n case Content:\n XML = mParser.getCharacterData();\n\n \/\/ Check whether and how we need to close the element\n if (mElementEmpty.top() == true)\n {\n if (XML != \"\")\n {\n mElementEmpty.top() = false;\n mXML << \">\";\n }\n else\n mXML << \" \/>\";\n }\n\n if (XML != \"\")\n mXML << CCopasiXMLInterface::encode(XML, CCopasiXMLInterface::character);\n\n if (mElementEmpty.top() == false)\n mXML << \"<\/\" << pszName << \">\";\n\n mElementEmpty.pop();\n mElementEmpty.top() = false;\n mLevel--;\n\n if (!mLevel) mCurrentElement = UnsupportedAnnotation;\n\n mParser.enableCharacterDataHandler();\n break;\n\n case UNKNOWN_ELEMENT:\n mCurrentElement = mLastKnownElement;\n break;\n\n default:\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"???\", mParser.getCurrentLineNumber());\n break;\n }\n\n return;\n}\n\nconst std::string & CCopasiXMLParser::UnsupportedAnnotationElement::getName() const\n{\n return mName;\n}\n\nstd::string CCopasiXMLParser::UnsupportedAnnotationElement::getXML() const\n{\n return mXML.str();\n}\n\nCCopasiXMLParser::ListOfUnsupportedAnnotationsElement::ListOfUnsupportedAnnotationsElement(CCopasiXMLParser & parser,\n SCopasiXMLParserCommon & common):\n CXMLElementHandler< CCopasiXMLParser, SCopasiXMLParserCommon >(parser, common),\n mUnsupportedAnnotations(),\n mpUnsupportedAnnotationElement(NULL)\n{}\n\n\/\/ virtual\nCCopasiXMLParser::ListOfUnsupportedAnnotationsElement::~ListOfUnsupportedAnnotationsElement()\n{\n pdelete(mpUnsupportedAnnotationElement);\n}\n\n\/\/ virtual\nvoid CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::start(const XML_Char *pszName,\n const XML_Char **papszAttrs)\n{\n mpCurrentHandler = NULL;\n mCurrentElement = mLastKnownElement;\n\n while (mpCurrentHandler == NULL)\n {\n mCurrentElement++; \/* We should always be on the next element *\/\n\n switch (mCurrentElement)\n {\n case ListOfUnsupportedAnnotations:\n\n if (strcmp(pszName, \"ListOfUnsupportedAnnotations\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 10,\n pszName, \"ListOfUnsupportedAnnotations\", mParser.getCurrentLineNumber());\n\n mLastKnownElement = ListOfUnsupportedAnnotations;\n mUnsupportedAnnotations.clear();\n\n return;\n\n case UnsupportedAnnotation:\n\n if (!strcmp(pszName, \"UnsupportedAnnotation\"))\n {\n \/* If we do not have a ModelParameterSet element handler we create one. *\/\n if (!mpUnsupportedAnnotationElement)\n mpUnsupportedAnnotationElement = new UnsupportedAnnotationElement(mParser, mCommon);\n\n mpCurrentHandler = mpUnsupportedAnnotationElement;\n }\n\n break;\n\n default:\n mCurrentElement = UNKNOWN_ELEMENT;\n mpCurrentHandler = &mParser.mUnknownElement;\n break;\n }\n }\n\n mParser.pushElementHandler(mpCurrentHandler);\n\n if (mpCurrentHandler != &mParser.mUnknownElement)\n {\n mLastKnownElement = mCurrentElement;\n }\n\n mParser.onStartElement(pszName, papszAttrs);\n}\n\n\/\/ virtual\nvoid CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::end(const XML_Char *pszName)\n{\n switch (mCurrentElement)\n {\n case ListOfUnsupportedAnnotations:\n\n if (strcmp(pszName, \"ListOfUnsupportedAnnotations\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"ListOfUnsupportedAnnotations\", mParser.getCurrentLineNumber());\n\n mParser.popElementHandler();\n mCurrentElement = START_ELEMENT;\n\n \/* Tell the parent element we are done. *\/\n mParser.onEndElement(pszName);\n break;\n\n case UnsupportedAnnotation:\n\n if (strcmp(pszName, \"UnsupportedAnnotation\"))\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"UnsupportedAnnotation\", mParser.getCurrentLineNumber());\n\n if (mpUnsupportedAnnotationElement != NULL)\n {\n mUnsupportedAnnotations[mpUnsupportedAnnotationElement->getName()] =\n mpUnsupportedAnnotationElement->getXML();\n }\n\n mLastKnownElement = ListOfUnsupportedAnnotations;\n mCurrentElement = ListOfUnsupportedAnnotations;\n break;\n\n case UNKNOWN_ELEMENT:\n mCurrentElement = mLastKnownElement;\n break;\n\n default:\n CCopasiMessage(CCopasiMessage::EXCEPTION, MCXML + 11,\n pszName, \"???\", mParser.getCurrentLineNumber());\n break;\n }\n\n return;\n}\n\nconst CAnnotation::UnsupportedAnnotation & CCopasiXMLParser::ListOfUnsupportedAnnotationsElement::getUnsupportedAnnotations() const\n{\n return mUnsupportedAnnotations;\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/\/ \\class AliMUONGlobalTriggerBoard\n\/\/\/ Global trigger implementation:\n\/\/\/ - inputs are regional responses\n\/\/\/ - output is a 12-bit word\n\/\/\/ - 4 bits per trigger level\n\/\/\/\n\/\/\/ \\author Rachid Guernane (LPCCFd), \n\/\/\/ Corrected by Christian Finck (Subatech)\n\/\/-----------------------------------------------------------------------------\n\n#include \"AliMUONGlobalTriggerBoard.h\"\n#include \"AliLog.h\"\n#include \"TBits.h\"\n\n#include \n\n\/\/\/ \\cond CLASSIMP\nClassImp(AliMUONGlobalTriggerBoard)\n\/\/\/ \\endcond\n\n\/\/___________________________________________\nAliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(): AliMUONTriggerBoard()\n{\n\/\/\/ Default constructor\n\n for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;\n for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;\n for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;\n}\n\n\/\/___________________________________________\nAliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(const char *name, Int_t a) : AliMUONTriggerBoard(name, a)\n{\n\/\/\/ Standard constructor\n\n for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;\n for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;\n for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;\n}\n\n\/\/___________________________________________\nAliMUONGlobalTriggerBoard::~AliMUONGlobalTriggerBoard()\n{\n\/\/\/ Destructor\n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::Mask(Int_t index, UInt_t mask)\n{\n \/\/\/ mask global trigger board input index with value mask\n if ( index >= 0 && index < 4 ) \n {\n fMask[index]=mask;\n }\n else\n {\n AliError(Form(\"Index %d out of bounds (max %d)\",index,3));\n } \n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::Response()\n{\n \/\/\/ compute the global trigger board\n \/\/\/ response according to the algo() method\n\/\/ output from global trigger algorithm\n\/\/ [+, -, US, LS] * [Hpt, Lpt]\n\/\/ transformed to [usHpt, usLpt, lsHpt, lsLpt, sHpt, sLpt] according\n\/\/ to Global Trigger Unit user manual\n\n Int_t t[16];\n\n BuildGlobalInput();\n MaskGlobalInput();\n\n for (Int_t i = 0; i < 16; ++i) \n {\n t[i] = fRegionalResponse[i];\n }\n \n \n Int_t rank = 8;\n\n for (Int_t i=0;i<4;i++)\n {\n Int_t ip = 0;\n \n for (Int_t j=0;j> 4) << (4*iReg);\n } else { \/\/ left\n \/\/ Lpt word\n fGlobalInput[1] |= (regRespInv & 0x0F) << (4*(iReg-8));\n \/\/ Hpt word\n fGlobalInput[3] |= ((regRespInv & 0xF0) >> 4) << (4*(iReg-8));\n }\n\n }\n\n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::MaskGlobalInput()\n{\n \/\/\/ Apply masks to global input and recalculate regional inputs before\n \/\/\/ applying the global response\n\n UShort_t regRespInv;\n TBits rs(8), rsi(8);\n\n \/\/ global input with masks applied\n UInt_t gitmp[4];\n\n for (Int_t i = 0; i < 4; i++) {\n gitmp[i] = fGlobalInput[i];\n gitmp[i] &= fMask[i];\n }\n\n for (Int_t iReg = 0; iReg < 16; iReg++) {\n fRegionalResponse[iReg] = 0;\n if (iReg < 8) { \/\/ right\n \/\/ Lpt\n fRegionalResponse[iReg] |= (gitmp[0] >> (4*iReg)) & 0xF;\n \/\/ Hpt\n fRegionalResponse[iReg] |= ((gitmp[2] >> (4*iReg)) & 0xF) << 4;\n } else { \/\/ left\n \/\/ Lpt\n fRegionalResponse[iReg] |= (gitmp[1] >> (4*(iReg-8))) & 0xF;\n \/\/ Hpt\n fRegionalResponse[iReg] |= ((gitmp[3] >> (4*(iReg-8))) & 0xF) << 4;\n }\n \/\/ invert bits in regional response ?\n rs.Set(8,&fRegionalResponse[iReg]);\n for (Int_t i = 0; i < 4; i++) {\n rsi[2*i] = rs[2*i+1];\n rsi[2*i+1] = rs[2*i];\n }\n regRespInv = 0;\n rsi.Get(®RespInv);\n \/\/ uncomment if ... YES\n \/\/fRegionalResponse[iReg] = regRespInv;\n }\n\n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::Scan(Option_t*) const\n{\n \/\/\/ print global trigger output \n TBits w(7); w.Set(7,&fResponse);\n\n\/\/ TRG[1:0]\n\/\/ 00 noth\n\/\/ 01 negative track\n\/\/ 10 positive track\n\/\/ 11 undef\n\n Int_t iS[2] = {0,0};\n\n iS[0] = (Int_t)w.TestBitNumber(1);\n iS[1] = (Int_t)w.TestBitNumber(2);\n\n Int_t iPU[2] = {w[5],w[6]};\n Int_t iPL[2] = {w[3],w[4]};\n\n printf(\"============================================\\n\");\n printf(\" Global Trigger output Low pt High pt\\n\");\n printf(\" number of Single :\\t\");\n for (Int_t i=0; i<2; i++) printf(\"%i\\t\",iS[i]);\n printf(\"\\n\");\n printf(\" number of UnlikeSign pair :\\t\"); \n for (Int_t i=0; i<2; i++) printf(\"%i\\t\",iPU[i]);\n printf(\"\\n\");\n printf(\" number of LikeSign pair :\\t\"); \n for (Int_t i=0; i<2; i++) printf(\"%i\\t\",iPL[i]);\n printf(\"\\n\");\n printf(\"===================================================\\n\");\n printf(\"\\n\");\n}\n\nInvert bits in regional response according to hardware\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/\/ \\class AliMUONGlobalTriggerBoard\n\/\/\/ Global trigger implementation:\n\/\/\/ - inputs are regional responses\n\/\/\/ - output is a 12-bit word\n\/\/\/ - 4 bits per trigger level\n\/\/\/\n\/\/\/ \\author Rachid Guernane (LPCCFd), \n\/\/\/ Corrected by Christian Finck (Subatech)\n\/\/-----------------------------------------------------------------------------\n\n#include \"AliMUONGlobalTriggerBoard.h\"\n#include \"AliLog.h\"\n#include \"TBits.h\"\n\n#include \n\n\/\/\/ \\cond CLASSIMP\nClassImp(AliMUONGlobalTriggerBoard)\n\/\/\/ \\endcond\n\n\/\/___________________________________________\nAliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(): AliMUONTriggerBoard()\n{\n\/\/\/ Default constructor\n\n for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;\n for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;\n for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;\n}\n\n\/\/___________________________________________\nAliMUONGlobalTriggerBoard::AliMUONGlobalTriggerBoard(const char *name, Int_t a) : AliMUONTriggerBoard(name, a)\n{\n\/\/\/ Standard constructor\n\n for (Int_t i=0;i<16;i++) fRegionalResponse[i] = 0;\n for (Int_t i=0;i< 4;i++) fGlobalInput[i] = 0;\n for (Int_t i=0;i< 4;i++) fMask[i] = 0xffffffff;\n}\n\n\/\/___________________________________________\nAliMUONGlobalTriggerBoard::~AliMUONGlobalTriggerBoard()\n{\n\/\/\/ Destructor\n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::Mask(Int_t index, UInt_t mask)\n{\n \/\/\/ mask global trigger board input index with value mask\n if ( index >= 0 && index < 4 ) \n {\n fMask[index]=mask;\n }\n else\n {\n AliError(Form(\"Index %d out of bounds (max %d)\",index,3));\n } \n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::Response()\n{\n \/\/\/ compute the global trigger board\n \/\/\/ response according to the algo() method\n\/\/ output from global trigger algorithm\n\/\/ [+, -, US, LS] * [Hpt, Lpt]\n\/\/ transformed to [usHpt, usLpt, lsHpt, lsLpt, sHpt, sLpt] according\n\/\/ to Global Trigger Unit user manual\n\n Int_t t[16];\n\n BuildGlobalInput();\n MaskGlobalInput();\n\n for (Int_t i = 0; i < 16; ++i) \n {\n t[i] = fRegionalResponse[i];\n }\n \n \n Int_t rank = 8;\n\n for (Int_t i=0;i<4;i++)\n {\n Int_t ip = 0;\n \n for (Int_t j=0;j> 4) << (4*iReg);\n } else { \/\/ left\n \/\/ Lpt word\n fGlobalInput[1] |= (regRespInv & 0x0F) << (4*(iReg-8));\n \/\/ Hpt word\n fGlobalInput[3] |= ((regRespInv & 0xF0) >> 4) << (4*(iReg-8));\n }\n\n }\n\n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::MaskGlobalInput()\n{\n \/\/\/ Apply masks to global input and recalculate regional inputs before\n \/\/\/ applying the global response\n\n UShort_t regRespInv;\n TBits rs(8), rsi(8);\n\n UInt_t gitmp[4];\n for (Int_t i = 0; i < 4; i++) {\n fGlobalInput[i] &= fMask[i];\n gitmp[i] = fGlobalInput[i];\n }\n\n for (Int_t iReg = 0; iReg < 16; iReg++) {\n fRegionalResponse[iReg] = 0;\n if (iReg < 8) { \/\/ right\n \/\/ Lpt\n fRegionalResponse[iReg] |= (gitmp[0] >> (4*iReg)) & 0xF;\n \/\/ Hpt\n fRegionalResponse[iReg] |= ((gitmp[2] >> (4*iReg)) & 0xF) << 4;\n } else { \/\/ left\n \/\/ Lpt\n fRegionalResponse[iReg] |= (gitmp[1] >> (4*(iReg-8))) & 0xF;\n \/\/ Hpt\n fRegionalResponse[iReg] |= ((gitmp[3] >> (4*(iReg-8))) & 0xF) << 4;\n }\n \/\/ invert \"pair\" bits in regional response\n \/\/ [+, -, US, LS] becomes [+, -, LS, US]\n rs.Set(8,&fRegionalResponse[iReg]);\n for (Int_t i = 0; i < 4; i++) {\n if (i%2 == 0) {\n\trsi[2*i] = rs[2*i+1];\n\trsi[2*i+1] = rs[2*i];\n } else {\n\trsi[2*i] = rs[2*i];\n\trsi[2*i+1] = rs[2*i+1];\n }\n }\n regRespInv = 0;\n rsi.Get(®RespInv);\n fRegionalResponse[iReg] = regRespInv;\n }\n\n}\n\n\/\/___________________________________________\nvoid AliMUONGlobalTriggerBoard::Scan(Option_t*) const\n{\n \/\/\/ print global trigger output \n TBits w(7); w.Set(7,&fResponse);\n\n\/\/ TRG[1:0]\n\/\/ 00 noth\n\/\/ 01 negative track\n\/\/ 10 positive track\n\/\/ 11 undef\n\n Int_t iS[2] = {0,0};\n\n iS[0] = (Int_t)w.TestBitNumber(1);\n iS[1] = (Int_t)w.TestBitNumber(2);\n\n Int_t iPU[2] = {w[5],w[6]};\n Int_t iPL[2] = {w[3],w[4]};\n\n printf(\"============================================\\n\");\n printf(\" Global Trigger output Low pt High pt\\n\");\n printf(\" number of Single :\\t\");\n for (Int_t i=0; i<2; i++) printf(\"%i\\t\",iS[i]);\n printf(\"\\n\");\n printf(\" number of UnlikeSign pair :\\t\"); \n for (Int_t i=0; i<2; i++) printf(\"%i\\t\",iPU[i]);\n printf(\"\\n\");\n printf(\" number of LikeSign pair :\\t\"); \n for (Int_t i=0; i<2; i++) printf(\"%i\\t\",iPL[i]);\n printf(\"\\n\");\n printf(\"===================================================\\n\");\n printf(\"\\n\");\n}\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ RenderFunctions.cpp\n\/\/\n\/\/ Created by Soso Limited on 7\/13\/15.\n\/\/\n\/\/\n\n#include \"RenderFunctions.h\"\n\n#include \"Transform.h\"\n#include \"Circle.h\"\n#include \"RenderLayer.h\"\n#include \"entityx\/Entity.h\"\n#include \"cinder\/gl\/gl.h\"\n\nusing namespace soso;\nusing namespace cinder;\n\nvoid soso::renderAllEntitiesAsCircles(entityx::EntityManager &entities)\n{\n gl::ScopedDepth depth(true, true);\n\n entityx::ComponentHandle transform;\n for (auto __unused e : entities.entities_with_components(transform)) {\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(transform->worldTransform());\n gl::drawSolidCircle(vec2(0), 12.0f);\n }\n}\n\nvoid soso::renderCircles(entityx::EntityManager &entities)\n{\n gl::ScopedDepth depth(true, true);\n\n entityx::ComponentHandle transform;\n entityx::ComponentHandle circle;\n\n auto billboard_xf = [] (Transform::Handle transform) {\n auto q = inverse(normalize(quat_cast(transform->worldTransform())));\n return transform->worldTransform() * glm::mat4_cast(q);\n };\n\n gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));\n for (auto __unused e : entities.entities_with_components(transform, circle)) {\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(billboard_xf(transform));\n gl::color(circle->color);\n\n gl::drawSolidCircle(vec2(0), circle->radius);\n }\n}\n\nvoid soso::renderCirclesDepthSorted(entityx::EntityManager &entities)\n{\n struct RenderInfo {\n ci::vec3 position;\n float scale;\n float radius = 1.0f;\n ci::Color color;\n\n };\n std::vector circles;\n\n auto insertion_point = [&circles] (float depth) {\n auto iter = circles.begin();\n while (iter != circles.end() && depth < iter->position.z) {\n ++iter;\n }\n return iter;\n };\n\n entityx::ComponentHandle transform;\n entityx::ComponentHandle circle;\n\n for (auto __unused e : entities.entities_with_components(transform, circle)) {\n auto pos = vec3(transform->worldTransform() * vec4(0, 0, 0, 1));\n auto scale = length(vec3(transform->worldTransform() * vec4(1, 0, 0, 0)));\n circles.insert(insertion_point(pos.z), RenderInfo{pos, scale, circle->radius, circle->color});\n }\n\n gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));\n for (auto &c : circles) {\n gl::ScopedModelMatrix mat;\n gl::translate(c.position);\n gl::scale(vec3(c.scale));\n gl::color(c.color);\n\n gl::drawSolidCircle(vec2(0), c.radius);\n }\n\n}\n\nvoid soso::renderCirclesHierarchically(entityx::EntityManager &entities)\n{\n entityx::ComponentHandle transform;\n entityx::ComponentHandle circle;\n auto xf = mat4(1);\n\n const auto billboard_xf = [] (const Transform &transform) {\n auto q = inverse(normalize(quat_cast(transform.localTransform())));\n return transform.localTransform() * glm::mat4_cast(q);\n };\n\n using function = std::function;\n function draw_recursively = [&billboard_xf, &draw_recursively] (Transform::Handle transform) {\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(transform->localTransform());\n\n auto circle = transform->entity().component();\n if (circle)\n {\n \/\/ billboard the circles (mostly works)\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(glm::mat4_cast(inverse(normalize(quat_cast(transform->worldTransform())))));\n gl::color(circle->color);\n gl::drawSolidCircle(vec2(0), circle->radius);\n }\n\n for (auto &child: transform->children())\n {\n draw_recursively(child);\n }\n };\n\n gl::ScopedColor color(Color::white());\n gl::ScopedDepth depth(false);\n for (auto __unused e : entities.entities_with_components(transform, circle)) {\n if (transform->isRoot())\n {\n draw_recursively(transform);\n }\n }\n}\n\nvoid soso::renderCirclesByLayer(entityx::EntityManager &entities)\n{\n \/\/ Data types for collecting render information into layers.\n struct DataPoint\n {\n mat4 transform;\n Color color;\n float radius;\n };\n\n using RenderData = std::vector;\n using RenderDataRef = std::unique_ptr;\n struct RenderDataLayer {\n RenderDataLayer(int layer)\n : layer(layer)\n {}\n int layer = 0;\n RenderDataRef render_data = std::make_unique();\n };\n\n \/\/ Our layers for rendering\n std::vector layers;\n\n \/\/ Returns the requested render layer, creating it if necessary.\n auto get_layer = [&layers] (int layer) -> RenderData& {\n for (auto &l : layers) {\n if (l.layer == layer) {\n return *l.render_data;\n }\n }\n layers.emplace_back(RenderDataLayer(layer));\n return *layers.back().render_data;\n };\n\n \/\/ Billboards a transform matrix.\n auto billboard_xf = [] (Transform::Handle transform) {\n auto q = inverse(normalize(quat_cast(transform->worldTransform())));\n return transform->worldTransform() * glm::mat4_cast(q);\n };\n\n \/\/ Recursive function to properly capture render layer changes.\n using function = std::function;\n function gather_recursively = [&gather_recursively, &get_layer, &billboard_xf] (Transform::Handle transform, int layer) {\n\n auto rlc = entityx::ComponentHandle();\n auto circle = entityx::ComponentHandle();\n auto e = transform->entity();\n e.unpack(rlc, circle);\n\n if (rlc)\n {\n if (rlc->relative())\n {\n layer += rlc->layer();\n }\n else\n {\n layer = rlc->layer();\n }\n }\n\n if (circle)\n {\n get_layer(layer).push_back({ billboard_xf(transform), circle->color, circle->radius });\n }\n\n for (auto &c : transform->children())\n {\n gather_recursively(c, layer);\n }\n };\n\n entityx::ComponentHandle transform;\n for (auto __unused e : entities.entities_with_components(transform))\n {\n \/\/ gather trees for rendering\n if (transform->isRoot())\n {\n gather_recursively(transform, 0);\n }\n }\n\n \/\/ In case we encountered layers out of order, put them into order.\n std::sort(layers.begin(), layers.end(), [] (const RenderDataLayer &lhs, const RenderDataLayer &rhs) {\n return lhs.layer < rhs.layer;\n });\n\n \/\/ Draw everything we gathered, by layer.\n gl::ScopedModelMatrix mat;\n gl::ScopedColor color(Color::white());\n for (auto &layer : layers)\n {\n for (auto &data : *layer.render_data)\n {\n gl::setModelMatrix(data.transform);\n gl::color(data.color);\n gl::drawSolidCircle(vec2(0), data.radius);\n }\n }\n}\nUpdate use of gl::ScopedDepth.\/\/\n\/\/ RenderFunctions.cpp\n\/\/\n\/\/ Created by Soso Limited on 7\/13\/15.\n\/\/\n\/\/\n\n#include \"RenderFunctions.h\"\n\n#include \"Transform.h\"\n#include \"Circle.h\"\n#include \"RenderLayer.h\"\n#include \"entityx\/Entity.h\"\n#include \"cinder\/gl\/gl.h\"\n\nusing namespace soso;\nusing namespace cinder;\n\nvoid soso::renderAllEntitiesAsCircles(entityx::EntityManager &entities)\n{\n gl::ScopedDepth depth(true);\n\n entityx::ComponentHandle transform;\n for (auto __unused e : entities.entities_with_components(transform)) {\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(transform->worldTransform());\n gl::drawSolidCircle(vec2(0), 12.0f);\n }\n}\n\nvoid soso::renderCircles(entityx::EntityManager &entities)\n{\n gl::ScopedDepth depth(true);\n\n entityx::ComponentHandle transform;\n entityx::ComponentHandle circle;\n\n auto billboard_xf = [] (Transform::Handle transform) {\n auto q = inverse(normalize(quat_cast(transform->worldTransform())));\n return transform->worldTransform() * glm::mat4_cast(q);\n };\n\n gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));\n for (auto __unused e : entities.entities_with_components(transform, circle)) {\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(billboard_xf(transform));\n gl::color(circle->color);\n\n gl::drawSolidCircle(vec2(0), circle->radius);\n }\n}\n\nvoid soso::renderCirclesDepthSorted(entityx::EntityManager &entities)\n{\n struct RenderInfo {\n ci::vec3 position;\n float scale;\n float radius = 1.0f;\n ci::Color color;\n\n };\n std::vector circles;\n\n auto insertion_point = [&circles] (float depth) {\n auto iter = circles.begin();\n while (iter != circles.end() && depth < iter->position.z) {\n ++iter;\n }\n return iter;\n };\n\n entityx::ComponentHandle transform;\n entityx::ComponentHandle circle;\n\n for (auto __unused e : entities.entities_with_components(transform, circle)) {\n auto pos = vec3(transform->worldTransform() * vec4(0, 0, 0, 1));\n auto scale = length(vec3(transform->worldTransform() * vec4(1, 0, 0, 0)));\n circles.insert(insertion_point(pos.z), RenderInfo{pos, scale, circle->radius, circle->color});\n }\n\n gl::ScopedColor color(Color(1.0f, 1.0f, 1.0f));\n for (auto &c : circles) {\n gl::ScopedModelMatrix mat;\n gl::translate(c.position);\n gl::scale(vec3(c.scale));\n gl::color(c.color);\n\n gl::drawSolidCircle(vec2(0), c.radius);\n }\n\n}\n\nvoid soso::renderCirclesHierarchically(entityx::EntityManager &entities)\n{\n entityx::ComponentHandle transform;\n entityx::ComponentHandle circle;\n auto xf = mat4(1);\n\n const auto billboard_xf = [] (const Transform &transform) {\n auto q = inverse(normalize(quat_cast(transform.localTransform())));\n return transform.localTransform() * glm::mat4_cast(q);\n };\n\n using function = std::function;\n function draw_recursively = [&billboard_xf, &draw_recursively] (Transform::Handle transform) {\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(transform->localTransform());\n\n auto circle = transform->entity().component();\n if (circle)\n {\n \/\/ billboard the circles (mostly works)\n gl::ScopedModelMatrix mat;\n gl::multModelMatrix(glm::mat4_cast(inverse(normalize(quat_cast(transform->worldTransform())))));\n gl::color(circle->color);\n gl::drawSolidCircle(vec2(0), circle->radius);\n }\n\n for (auto &child: transform->children())\n {\n draw_recursively(child);\n }\n };\n\n gl::ScopedColor color(Color::white());\n gl::ScopedDepth depth(false);\n for (auto __unused e : entities.entities_with_components(transform, circle)) {\n if (transform->isRoot())\n {\n draw_recursively(transform);\n }\n }\n}\n\nvoid soso::renderCirclesByLayer(entityx::EntityManager &entities)\n{\n \/\/ Data types for collecting render information into layers.\n struct DataPoint\n {\n mat4 transform;\n Color color;\n float radius;\n };\n\n using RenderData = std::vector;\n using RenderDataRef = std::unique_ptr;\n struct RenderDataLayer {\n RenderDataLayer(int layer)\n : layer(layer)\n {}\n int layer = 0;\n RenderDataRef render_data = std::make_unique();\n };\n\n \/\/ Our layers for rendering\n std::vector layers;\n\n \/\/ Returns the requested render layer, creating it if necessary.\n auto get_layer = [&layers] (int layer) -> RenderData& {\n for (auto &l : layers) {\n if (l.layer == layer) {\n return *l.render_data;\n }\n }\n layers.emplace_back(RenderDataLayer(layer));\n return *layers.back().render_data;\n };\n\n \/\/ Billboards a transform matrix.\n auto billboard_xf = [] (Transform::Handle transform) {\n auto q = inverse(normalize(quat_cast(transform->worldTransform())));\n return transform->worldTransform() * glm::mat4_cast(q);\n };\n\n \/\/ Recursive function to properly capture render layer changes.\n using function = std::function;\n function gather_recursively = [&gather_recursively, &get_layer, &billboard_xf] (Transform::Handle transform, int layer) {\n\n auto rlc = entityx::ComponentHandle();\n auto circle = entityx::ComponentHandle();\n auto e = transform->entity();\n e.unpack(rlc, circle);\n\n if (rlc)\n {\n if (rlc->relative())\n {\n layer += rlc->layer();\n }\n else\n {\n layer = rlc->layer();\n }\n }\n\n if (circle)\n {\n get_layer(layer).push_back({ billboard_xf(transform), circle->color, circle->radius });\n }\n\n for (auto &c : transform->children())\n {\n gather_recursively(c, layer);\n }\n };\n\n entityx::ComponentHandle transform;\n for (auto __unused e : entities.entities_with_components(transform))\n {\n \/\/ gather trees for rendering\n if (transform->isRoot())\n {\n gather_recursively(transform, 0);\n }\n }\n\n \/\/ In case we encountered layers out of order, put them into order.\n std::sort(layers.begin(), layers.end(), [] (const RenderDataLayer &lhs, const RenderDataLayer &rhs) {\n return lhs.layer < rhs.layer;\n });\n\n \/\/ Draw everything we gathered, by layer.\n gl::ScopedModelMatrix mat;\n gl::ScopedColor color(Color::white());\n for (auto &layer : layers)\n {\n for (auto &data : *layer.render_data)\n {\n gl::setModelMatrix(data.transform);\n gl::color(data.color);\n gl::drawSolidCircle(vec2(0), data.radius);\n }\n }\n}\n<|endoftext|>"} {"text":"\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in http:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n\/* Plane-based Map (PbMap) library\n * Construction of plane-based maps and localization in it from RGBD Images.\n * Writen by Eduardo Fernandez-Moral. See docs for mrpt-pbmap<\/a>\n *\/\n#include \/\/ precomp. hdr\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mrpt::system;\nusing namespace mrpt::pbmap;\n\nstring path(\"\/home\/edu\/Libraries\/mrpt-svn\/share\/mrpt\/datasets\/pbmap-demos\/\");\n\nvoid printHelp()\n{\n\tcout << \".\/pbmap_test reads a set of pairs pointCloud+Pose to build a \"\n\t\t\t\"PbMap\\n\";\n}\n\nvoid testPbMapConstruction(const string& config_file)\n{\n\tprintHelp();\n\n\t\/\/ Reconstructed PointCloud\n\tpcl::PointCloud globalCloud;\n\n\tPbMapMaker pbmap_maker(config_file);\n\n\t\/\/ Read in the cloud data\n\tpcl::PCDReader reader;\n\n\tunsigned N = 3; \/\/ Read the 5 sample pairs pointClouds+Pose\n\tstring cloudFile, poseFile;\n\tfor (unsigned i = 0; i <= N; i++)\n\t{\n\t\t\/\/ Read frame\n\t\tframeRGBDandPose cloudAndPose;\n\t\tcloudAndPose.cloudPtr.reset(new pcl::PointCloud);\n\t\tcloudFile = mrpt::format(\"pointcloud%i.pcd\", i);\n\t\tASSERT_FILE_EXISTS_(path + cloudFile)\n\t\treader.read(path + cloudFile, *cloudAndPose.cloudPtr);\n\n\t\t\/\/ Read pose\n\t\tmrpt::io::CFileGZInputStream serialized_pose;\n\t\tposeFile = path + mrpt::format(\"pose%i.mat\", i);\n\n\t\tif (serialized_pose.open(poseFile))\n\t\t{\n\t\t\tserialized_pose.ReadBufferFixEndianness(\n\t\t\t\t&cloudAndPose.pose(0), 16);\n\t\t}\n\t\telse\n\t\t\tcout << \"Error: cannot open \" << poseFile << \"\\n\";\n\t\tserialized_pose.close();\n\n\t\t\/\/ Detect planes and build PbMap\n\t\tpbmap_maker.frameQueue.push_back(cloudAndPose);\n\n\t\tpcl::PointCloud::Ptr alignedCloudPtr(\n\t\t\tnew pcl::PointCloud);\n\t\tpcl::transformPointCloud(\n\t\t\t*cloudAndPose.cloudPtr, *alignedCloudPtr, cloudAndPose.pose);\n\t\tglobalCloud += *alignedCloudPtr;\n\n\t\tstd::this_thread::sleep_for(1000ms); \/\/ sleep to visualize the map\n\t\t\/\/ creation from the keyframes in\n\t\t\/\/ slow motion\n\t}\n\n\t\/\/ Serialize PbMap\n\tmrpt::io::CFileGZOutputStream serialize_pbmap(\"test.pbmap\");\n\tserialize_pbmap << pbmap_maker.getPbMap();\n\tserialize_pbmap.close();\n\n\t\/\/ Save reconstructed point cloud\n\tpcl::io::savePCDFile(\"reconstructed_cloud.pcd\", globalCloud);\n\n\tdouble total_area = 0.0;\n\tfor (unsigned i = 0; i < pbmap_maker.getPbMap().vPlanes.size(); i++)\n\t\ttotal_area += pbmap_maker.getPbMap().vPlanes[i].areaHull;\n\tcout << \"This PbMap contains \" << pbmap_maker.getPbMap().vPlanes.size()\n\t\t << \" planes, covering a total area of \" << total_area << \" m2\" << endl;\n\n\tstd::this_thread::sleep_for(10000ms);\n}\n\nint main(int argc, char** argv)\n{\n\ttry\n\t{\n\t\tbool showHelp = argc > 1 && !os::_strcmp(argv[1], \"--help\");\n\n\t\t\/\/ Process arguments:\n\t\tif (argc < 2 || showHelp)\n\t\t{\n\t\t\tprintf(\"Usage: %s \\n\\n\", argv[0]);\n\t\t\tif (!showHelp)\n\t\t\t{\n\t\t\t\tmrpt::system::pause();\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}\n\n\t\tconst string INI_FILENAME = string(argv[1]);\n\n\t\ttestPbMapConstruction(INI_FILENAME);\n\n\t\treturn 0;\n\t}\n\tcatch (exception& e)\n\t{\n\t\tcout << \"MRPT exception caught: \" << e.what() << endl;\n\t\treturn -1;\n\t}\n\tcatch (...)\n\t{\n\t\tprintf(\"Another exception!!\");\n\t\treturn -1;\n\t}\n}\nMissing ';' after ASSERT_FILE_EXISTS_\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in http:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n\/* Plane-based Map (PbMap) library\n * Construction of plane-based maps and localization in it from RGBD Images.\n * Writen by Eduardo Fernandez-Moral. See docs for mrpt-pbmap<\/a>\n *\/\n#include \/\/ precomp. hdr\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mrpt::system;\nusing namespace mrpt::pbmap;\n\nstring path(\"\/home\/edu\/Libraries\/mrpt-svn\/share\/mrpt\/datasets\/pbmap-demos\/\");\n\nvoid printHelp()\n{\n\tcout << \".\/pbmap_test reads a set of pairs pointCloud+Pose to build a \"\n\t\t\t\"PbMap\\n\";\n}\n\nvoid testPbMapConstruction(const string& config_file)\n{\n\tprintHelp();\n\n\t\/\/ Reconstructed PointCloud\n\tpcl::PointCloud globalCloud;\n\n\tPbMapMaker pbmap_maker(config_file);\n\n\t\/\/ Read in the cloud data\n\tpcl::PCDReader reader;\n\n\tunsigned N = 3; \/\/ Read the 5 sample pairs pointClouds+Pose\n\tstring cloudFile, poseFile;\n\tfor (unsigned i = 0; i <= N; i++)\n\t{\n\t\t\/\/ Read frame\n\t\tframeRGBDandPose cloudAndPose;\n\t\tcloudAndPose.cloudPtr.reset(new pcl::PointCloud);\n\t\tcloudFile = mrpt::format(\"pointcloud%i.pcd\", i);\n\t\tASSERT_FILE_EXISTS_(path + cloudFile);\n\t\treader.read(path + cloudFile, *cloudAndPose.cloudPtr);\n\n\t\t\/\/ Read pose\n\t\tmrpt::io::CFileGZInputStream serialized_pose;\n\t\tposeFile = path + mrpt::format(\"pose%i.mat\", i);\n\n\t\tif (serialized_pose.open(poseFile))\n\t\t{\n\t\t\tserialized_pose.ReadBufferFixEndianness(\n\t\t\t\t&cloudAndPose.pose(0), 16);\n\t\t}\n\t\telse\n\t\t\tcout << \"Error: cannot open \" << poseFile << \"\\n\";\n\t\tserialized_pose.close();\n\n\t\t\/\/ Detect planes and build PbMap\n\t\tpbmap_maker.frameQueue.push_back(cloudAndPose);\n\n\t\tpcl::PointCloud::Ptr alignedCloudPtr(\n\t\t\tnew pcl::PointCloud);\n\t\tpcl::transformPointCloud(\n\t\t\t*cloudAndPose.cloudPtr, *alignedCloudPtr, cloudAndPose.pose);\n\t\tglobalCloud += *alignedCloudPtr;\n\n\t\tstd::this_thread::sleep_for(1000ms); \/\/ sleep to visualize the map\n\t\t\/\/ creation from the keyframes in\n\t\t\/\/ slow motion\n\t}\n\n\t\/\/ Serialize PbMap\n\tmrpt::io::CFileGZOutputStream serialize_pbmap(\"test.pbmap\");\n\tserialize_pbmap << pbmap_maker.getPbMap();\n\tserialize_pbmap.close();\n\n\t\/\/ Save reconstructed point cloud\n\tpcl::io::savePCDFile(\"reconstructed_cloud.pcd\", globalCloud);\n\n\tdouble total_area = 0.0;\n\tfor (unsigned i = 0; i < pbmap_maker.getPbMap().vPlanes.size(); i++)\n\t\ttotal_area += pbmap_maker.getPbMap().vPlanes[i].areaHull;\n\tcout << \"This PbMap contains \" << pbmap_maker.getPbMap().vPlanes.size()\n\t\t << \" planes, covering a total area of \" << total_area << \" m2\" << endl;\n\n\tstd::this_thread::sleep_for(10000ms);\n}\n\nint main(int argc, char** argv)\n{\n\ttry\n\t{\n\t\tbool showHelp = argc > 1 && !os::_strcmp(argv[1], \"--help\");\n\n\t\t\/\/ Process arguments:\n\t\tif (argc < 2 || showHelp)\n\t\t{\n\t\t\tprintf(\"Usage: %s \\n\\n\", argv[0]);\n\t\t\tif (!showHelp)\n\t\t\t{\n\t\t\t\tmrpt::system::pause();\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}\n\n\t\tconst string INI_FILENAME = string(argv[1]);\n\n\t\ttestPbMapConstruction(INI_FILENAME);\n\n\t\treturn 0;\n\t}\n\tcatch (exception& e)\n\t{\n\t\tcout << \"MRPT exception caught: \" << e.what() << endl;\n\t\treturn -1;\n\t}\n\tcatch (...)\n\t{\n\t\tprintf(\"Another exception!!\");\n\t\treturn -1;\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: XMLExportSharedData.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 12:50:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_XMLEXPORTSHAREDDATA_HXX\n#define SC_XMLEXPORTSHAREDDATA_HXX\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include \n#endif\n\n#ifndef __SGI_STL_VECTOR\n#include \n#endif\n#ifndef __SGI_STL_LIST\n#include \n#endif\n\nstruct ScMyDrawPage\n{\n com::sun::star::uno::Reference xDrawPage;\n sal_Bool bHasForms;\n\n ScMyDrawPage() : bHasForms(sal_False) {}\n};\n\ntypedef std::list< com::sun::star::uno::Reference > ScMyTableXShapes;\ntypedef std::vector ScMyTableShapes;\ntypedef std::vector ScMyDrawPages;\n\nclass ScMyShapesContainer;\nclass ScMyDetectiveObjContainer;\nstruct ScMyShape;\nclass ScMyNoteShapesContainer;\n\nclass ScMySharedData\n{\n std::vector nLastColumns;\n std::vector nLastRows;\n ScMyTableShapes* pTableShapes;\n ScMyDrawPages* pDrawPages;\n ScMyShapesContainer* pShapesContainer;\n ScMyDetectiveObjContainer* pDetectiveObjContainer;\n ScMyNoteShapesContainer* pNoteShapes;\n sal_Int32 nTableCount;\npublic:\n ScMySharedData(const sal_Int32 nTableCount);\n ~ScMySharedData();\n\n void SetLastColumn(const sal_Int32 nTable, const sal_Int32 nCol);\n void SetLastRow(const sal_Int32 nTable, const sal_Int32 nRow);\n sal_Int32 GetLastColumn(const sal_Int32 nTable);\n sal_Int32 GetLastRow(const sal_Int32 nTable);\n void AddDrawPage(const ScMyDrawPage& aDrawPage, const sal_Int32 nTable);\n void SetDrawPageHasForms(const sal_Int32 nTable, sal_Bool bHasForms);\n com::sun::star::uno::Reference GetDrawPage(const sal_Int32 nTable);\n sal_Bool HasDrawPage() { return pDrawPages != NULL; }\n sal_Bool HasForm(const sal_Int32 nTable, com::sun::star::uno::Reference& xDrawPage);\n void AddNewShape(const ScMyShape& aMyShape);\n void SortShapesContainer();\n ScMyShapesContainer* GetShapesContainer() { return pShapesContainer; }\n sal_Bool HasShapes();\n void AddTableShape(const sal_Int32 nTable, const com::sun::star::uno::Reference& xShape);\n ScMyTableShapes* GetTableShapes() { return pTableShapes; }\n ScMyDetectiveObjContainer* GetDetectiveObjContainer() { return pDetectiveObjContainer; }\n void AddNoteObj(const com::sun::star::uno::Reference& xShape, const ScAddress& rPos);\n void SortNoteShapes();\n ScMyNoteShapesContainer* GetNoteShapes() { return pNoteShapes; }\n};\n\n#endif\n\nINTEGRATION: CWS ooo19126 (1.7.116); FILE MERGED 2005\/09\/05 15:03:25 rt 1.7.116.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XMLExportSharedData.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:56:35 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_XMLEXPORTSHAREDDATA_HXX\n#define SC_XMLEXPORTSHAREDDATA_HXX\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include \n#endif\n\n#ifndef __SGI_STL_VECTOR\n#include \n#endif\n#ifndef __SGI_STL_LIST\n#include \n#endif\n\nstruct ScMyDrawPage\n{\n com::sun::star::uno::Reference xDrawPage;\n sal_Bool bHasForms;\n\n ScMyDrawPage() : bHasForms(sal_False) {}\n};\n\ntypedef std::list< com::sun::star::uno::Reference > ScMyTableXShapes;\ntypedef std::vector ScMyTableShapes;\ntypedef std::vector ScMyDrawPages;\n\nclass ScMyShapesContainer;\nclass ScMyDetectiveObjContainer;\nstruct ScMyShape;\nclass ScMyNoteShapesContainer;\n\nclass ScMySharedData\n{\n std::vector nLastColumns;\n std::vector nLastRows;\n ScMyTableShapes* pTableShapes;\n ScMyDrawPages* pDrawPages;\n ScMyShapesContainer* pShapesContainer;\n ScMyDetectiveObjContainer* pDetectiveObjContainer;\n ScMyNoteShapesContainer* pNoteShapes;\n sal_Int32 nTableCount;\npublic:\n ScMySharedData(const sal_Int32 nTableCount);\n ~ScMySharedData();\n\n void SetLastColumn(const sal_Int32 nTable, const sal_Int32 nCol);\n void SetLastRow(const sal_Int32 nTable, const sal_Int32 nRow);\n sal_Int32 GetLastColumn(const sal_Int32 nTable);\n sal_Int32 GetLastRow(const sal_Int32 nTable);\n void AddDrawPage(const ScMyDrawPage& aDrawPage, const sal_Int32 nTable);\n void SetDrawPageHasForms(const sal_Int32 nTable, sal_Bool bHasForms);\n com::sun::star::uno::Reference GetDrawPage(const sal_Int32 nTable);\n sal_Bool HasDrawPage() { return pDrawPages != NULL; }\n sal_Bool HasForm(const sal_Int32 nTable, com::sun::star::uno::Reference& xDrawPage);\n void AddNewShape(const ScMyShape& aMyShape);\n void SortShapesContainer();\n ScMyShapesContainer* GetShapesContainer() { return pShapesContainer; }\n sal_Bool HasShapes();\n void AddTableShape(const sal_Int32 nTable, const com::sun::star::uno::Reference& xShape);\n ScMyTableShapes* GetTableShapes() { return pTableShapes; }\n ScMyDetectiveObjContainer* GetDetectiveObjContainer() { return pDetectiveObjContainer; }\n void AddNoteObj(const com::sun::star::uno::Reference& xShape, const ScAddress& rPos);\n void SortNoteShapes();\n ScMyNoteShapesContainer* GetNoteShapes() { return pNoteShapes; }\n};\n\n#endif\n\n<|endoftext|>"} {"text":"#include \"Gillespie_TwoStrain_Network_Sim.h\"\n\nint main(int argc,char *argv[]) {\n if(argc != 5) {\n printf(\"Wrong Number of Arguments\\n\");\n exit(0);\n }\n\n \/\/double alpha1 = argv[1]-0.0;\n double alpha1, alpha2, beta1, beta2, gamma1, gamma2, phi1, phi2;\n alpha1 = alpha2 = atof( argv[1] );\n beta1 = 0.35;\n beta2 = atof( argv[2] );\n gamma1 = gamma2 = 1.0\/5.0;\n phi1 = phi2 = atof( argv[4]);\n int intro_time;\n intro_time = atoi( argv[3] );\n\n int num_reps = 1000;\n\n Network net = Network(\"gillespie toy\", Network::Undirected);\n net.populate(10000);\n vector degrees(10000, 5);\n net.rand_connect_explicit(degrees);\n for(int i =1; i <= num_reps; i++){\n Gillespie_TwoStrain_Network_Sim sim(&net, alpha1, alpha2, gamma1, gamma2, beta1, beta2, phi1, phi2, intro_time);\n cout << \"Simulation number: \" << i << endl;\n sim.reset();\n sim.rand_infect(5, 1);\n sim.run_simulation(10000.0);\n }\n return 0;\n}\n\n\nuniform network#include \"Gillespie_TwoStrain_Network_Sim.h\"\n\nint main(int argc,char *argv[]) {\n if(argc != 5) {\n printf(\"Wrong Number of Arguments\\n\");\n exit(0);\n }\n\n \/\/double alpha1 = argv[1]-0.0;\n double alpha1, alpha2, beta1, beta2, gamma1, gamma2, phi1, phi2;\n alpha1 = alpha2 = atof( argv[1] );\n beta1 = 0.35;\n beta2 = atof( argv[2] );\n gamma1 = gamma2 = 1.0\/5.0;\n phi1 = phi2 = atof( argv[4]);\n int intro_time;\n intro_time = atoi( argv[3] );\n\n int num_reps = 1000;\n\n Network net = Network(\"gillespie toy\", Network::Undirected);\n net.populate(10000);\n vector degrees(10000, 4);\n net.rand_connect_explicit(degrees);\n for(int i =1; i <= num_reps; i++){\n Gillespie_TwoStrain_Network_Sim sim(&net, alpha1, alpha2, gamma1, gamma2, beta1, beta2, phi1, phi2, intro_time);\n cout << \"Simulation number: \" << i << endl;\n sim.reset();\n sim.rand_infect(5, 1);\n sim.run_simulation(10000.0);\n }\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"#include \"OccTest.hpp\"\n\n#include \"MechanicsFwd.hpp\"\n#include \"OccContactShape.hpp\"\n#include \"OccContactFace.hpp\"\n#include \"OccContactEdge.hpp\"\n#include \"ContactShapeDistance.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nCPPUNIT_TEST_SUITE_REGISTRATION(OccTest);\n\nvoid OccTest::setUp()\n{\n}\n\nvoid OccTest::tearDown()\n{\n}\n\nvoid OccTest::exportBRepAsString()\n{\n\n BRepPrimAPI_MakeSphere mksphere(1.0);\n\n OccContactShape sphere(mksphere.Shape());\n\n std::string s1 = sphere.exportBRepToString();\n\n std::stringstream out;\n\n BRepTools::Write(mksphere.Shape(), out);\n\n CPPUNIT_ASSERT(out.str() == s1);\n\n}\n\nvoid OccTest::computeUVBounds()\n{\n\n TopExp_Explorer exp;\n BRepPrimAPI_MakeSphere mksphere(1.0);\n\n OccContactShape sphere_shape = OccContactShape(mksphere.Shape());\n\n OccContactFace sphere_face(sphere_shape, 0);\n\n sphere_face.computeUVBounds();\n\n CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[0] - 6.28319) < 1e-4);\n CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[1] - 1.5708) < 1e-4);\n\n CPPUNIT_ASSERT(std::abs(sphere_face.binf1[0] - 0.) < 1e-4);\n CPPUNIT_ASSERT(std::abs(sphere_face.binf1[1] + 1.5708) < 1e-4);\n\n std::cout << sphere_face.bsup1[0] << \",\" << sphere_face.bsup1[1] << std::endl;\n std::cout << sphere_face.binf1[0] << \",\" << sphere_face.binf1[1] << std::endl;\n\n}\n\n\n#include \n#include \n#include \nvoid OccTest::move()\n{\n BRepPrimAPI_MakeSphere mksphere(1.0);\n\n TopExp_Explorer exp;\n\n exp.Init(mksphere.Shape(), TopAbs_SHELL);\n\n TopoDS_Shell shell = TopoDS::Shell(exp.Current().Composed(mksphere.Shape().Orientation()));\n\n exp.Init(shell, TopAbs_FACE);\n\n TopoDS_Face face = TopoDS::Face(exp.Current().Composed(shell.Orientation()));\n\n OccContactShape sphere(mksphere.Shape());\n OccContactFace sphere_contact(sphere, 0);\n\n SP::SiconosVector position(new SiconosVector(7));\n SP::SiconosVector velocity(new SiconosVector(6));\n SP::SimpleMatrix inertia(new SimpleMatrix(3,3));\n position->zero();\n (*position)(0) = 1.;\n (*position)(1) = 2.;\n (*position)(2) = 3.;\n\n \/* unit quaternion from 4,5,6,7 *\/\n (*position)(3) = 0.35634832254989918;\n (*position)(4) = 0.44543540318737401;\n (*position)(5) = 0.53452248382484879;\n (*position)(6) = 0.62360956446232352;\n\n velocity->zero();\n inertia->eye();\n\n SP::OccBody body(new OccBody(position, velocity, 1, inertia));\n\n body->addContactShape(createSPtrOccContactShape(sphere_contact));\n\n gp_XYZ translat = body->contactShape(0).data().Location().Transformation().\n TranslationPart();\n\n std::cout << translat.X() << \",\" << translat.Y() << \",\" << translat.Z()\n << std::endl;\n\n CPPUNIT_ASSERT(translat.X() == 1.);\n CPPUNIT_ASSERT(translat.Y() == 2.);\n CPPUNIT_ASSERT(translat.Z() == 3.);\n\n gp_Quaternion rotat = body->contactShape(0).data().Location().Transformation().\n GetRotation();\n\n CPPUNIT_ASSERT(abs(rotat.X() - 0.44543540318737401) < 1e-9);\n CPPUNIT_ASSERT(abs(rotat.Y() - 0.53452248382484879) < 1e-9);\n CPPUNIT_ASSERT(abs(rotat.Z() - 0.62360956446232352) < 1e-9);\n CPPUNIT_ASSERT(abs(rotat.W() - 0.35634832254989918) < 1e-9);\n\n}\n\nvoid OccTest::distance()\n{\n const double pi = boost::math::constants::pi();\n\n BRepPrimAPI_MakeSphere mksphere1(1, pi);\n BRepPrimAPI_MakeSphere mksphere2(1, pi);\n\n OccContactShape sphere1(mksphere1.Shape());\n OccContactShape sphere2(mksphere2.Shape());\n\n OccContactFace sphere1_contact(sphere1, 0);\n OccContactFace sphere2_contact(sphere2, 0);\n\n SP::SiconosVector position1(new SiconosVector(7));\n SP::SiconosVector position2(new SiconosVector(7));\n SP::SiconosVector velocity(new SiconosVector(6));\n SP::SimpleMatrix inertia(new SimpleMatrix(3,3));\n position1->zero();\n (*position1)(0) = 0.;\n (*position1)(1) = 0.;\n (*position1)(2) = 0.;\n\n (*position1)(3) = 1;\n\n position2->zero();\n (*position2)(0) = 3.;\n (*position2)(1) = 0.;\n (*position2)(2) = 0.;\n\n (*position2)(3) = cos(pi\/2.);\n (*position2)(5) = sin(pi\/2.);\n\n velocity->zero();\n inertia->eye();\n\n SP::OccBody body1(new OccBody(position1, velocity, 1, inertia));\n SP::OccBody body2(new OccBody(position2, velocity, 1, inertia));\n\n body1->addContactShape(createSPtrOccContactShape(sphere1_contact));\n body2->addContactShape(createSPtrOccContactShape(sphere2_contact));\n\n\n std::cout << \"umin1:\" << body1->contactShape(0).binf1[0] << std::endl;\n std::cout << \"umax1:\" << body1->contactShape(0).bsup1[0] << std::endl;\n std::cout << \"vmin1:\" << body1->contactShape(0).binf1[1] << std::endl;\n std::cout << \"vmax1:\" << body1->contactShape(0).bsup1[1] << std::endl;\n\n std::cout << \"umin2:\" << body2->contactShape(0).binf1[0] << std::endl;\n std::cout << \"umax2:\" << body2->contactShape(0).bsup1[0] << std::endl;\n std::cout << \"vmin2:\" << body2->contactShape(0).binf1[1] << std::endl;\n std::cout << \"vmax2:\" << body2->contactShape(0).bsup1[1] << std::endl;\n\n gp_XYZ translat1 = body1->contactShape(0).data().Location().Transformation().\n TranslationPart();\n\n std::cout << translat1.X() << \",\" << translat1.Y() << \",\" << translat1.Z()\n << std::endl;\n\n\n gp_XYZ translat2 = body2->contactShape(0).data().Location().Transformation().\n TranslationPart();\n\n std::cout << translat2.X() << \",\" << translat2.Y() << \",\" << translat2.Z()\n << std::endl;\n\n SP::ContactShapeDistance pdist =\n body1->contactShape(0).distance(body2->contactShape(0));\n\n ContactShapeDistance& dist = *pdist;\n\n std::cout << dist.value << std::endl;\n\n std::cout << dist.x1 << \",\" << dist.y1 << \",\" << dist.z1 << std::endl;\n\n std::cout << dist.x2 << \",\" << dist.y2 << \",\" << dist.z2 << std::endl;\n\n std::cout << dist.nx << \",\" << dist.ny << \",\" << dist.nz << std::endl;\n\n CPPUNIT_ASSERT(abs(dist.value - 1.0) < 1e-9);\n\n}\nRemove some warnings#include \"OccTest.hpp\"\n\n#include \"MechanicsFwd.hpp\"\n#include \"OccContactShape.hpp\"\n#include \"OccContactFace.hpp\"\n#include \"OccContactEdge.hpp\"\n#include \"ContactShapeDistance.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nCPPUNIT_TEST_SUITE_REGISTRATION(OccTest);\n\nvoid OccTest::setUp()\n{\n}\n\nvoid OccTest::tearDown()\n{\n}\n\nvoid OccTest::exportBRepAsString()\n{\n\n BRepPrimAPI_MakeSphere mksphere(1.0);\n\n OccContactShape sphere(mksphere.Shape());\n\n std::string s1 = sphere.exportBRepToString();\n\n std::stringstream out;\n\n BRepTools::Write(mksphere.Shape(), out);\n\n CPPUNIT_ASSERT(out.str() == s1);\n\n}\n\nvoid OccTest::computeUVBounds()\n{\n\n TopExp_Explorer exp;\n BRepPrimAPI_MakeSphere mksphere(1.0);\n\n OccContactShape sphere_shape = OccContactShape(mksphere.Shape());\n\n OccContactFace sphere_face(sphere_shape, 0);\n\n sphere_face.computeUVBounds();\n\n CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[0] - 6.28319) < 1e-4);\n CPPUNIT_ASSERT(std::abs(sphere_face.bsup1[1] - 1.5708) < 1e-4);\n\n CPPUNIT_ASSERT(std::abs(sphere_face.binf1[0] - 0.) < 1e-4);\n CPPUNIT_ASSERT(std::abs(sphere_face.binf1[1] + 1.5708) < 1e-4);\n\n std::cout << sphere_face.bsup1[0] << \",\" << sphere_face.bsup1[1] << std::endl;\n std::cout << sphere_face.binf1[0] << \",\" << sphere_face.binf1[1] << std::endl;\n\n}\n\n\n#include \n#include \n#include \nvoid OccTest::move()\n{\n BRepPrimAPI_MakeSphere mksphere(1.0);\n\n TopExp_Explorer exp;\n\n exp.Init(mksphere.Shape(), TopAbs_SHELL);\n\n TopoDS_Shell shell = TopoDS::Shell(exp.Current().Composed(mksphere.Shape().Orientation()));\n\n exp.Init(shell, TopAbs_FACE);\n\n TopoDS_Face face = TopoDS::Face(exp.Current().Composed(shell.Orientation()));\n\n OccContactShape sphere(mksphere.Shape());\n OccContactFace sphere_contact(sphere, 0);\n\n SP::SiconosVector position(new SiconosVector(7));\n SP::SiconosVector velocity(new SiconosVector(6));\n SP::SimpleMatrix inertia(new SimpleMatrix(3,3));\n position->zero();\n (*position)(0) = 1.;\n (*position)(1) = 2.;\n (*position)(2) = 3.;\n\n \/* unit quaternion from 4,5,6,7 *\/\n (*position)(3) = 0.35634832254989918;\n (*position)(4) = 0.44543540318737401;\n (*position)(5) = 0.53452248382484879;\n (*position)(6) = 0.62360956446232352;\n\n velocity->zero();\n inertia->eye();\n\n SP::OccBody body(new OccBody(position, velocity, 1, inertia));\n\n body->addContactShape(createSPtrOccContactShape(sphere_contact));\n\n gp_XYZ translat = body->contactShape(0).data().Location().Transformation().\n TranslationPart();\n\n std::cout << translat.X() << \",\" << translat.Y() << \",\" << translat.Z()\n << std::endl;\n\n CPPUNIT_ASSERT(translat.X() == 1.);\n CPPUNIT_ASSERT(translat.Y() == 2.);\n CPPUNIT_ASSERT(translat.Z() == 3.);\n\n gp_Quaternion rotat = body->contactShape(0).data().Location().Transformation().\n GetRotation();\n\n CPPUNIT_ASSERT(std::abs(rotat.X() - 0.44543540318737401) < 1e-9);\n CPPUNIT_ASSERT(std::abs(rotat.Y() - 0.53452248382484879) < 1e-9);\n CPPUNIT_ASSERT(std::abs(rotat.Z() - 0.62360956446232352) < 1e-9);\n CPPUNIT_ASSERT(std::abs(rotat.W() - 0.35634832254989918) < 1e-9);\n\n}\n\nvoid OccTest::distance()\n{\n const double pi = boost::math::constants::pi();\n\n BRepPrimAPI_MakeSphere mksphere1(1, pi);\n BRepPrimAPI_MakeSphere mksphere2(1, pi);\n\n OccContactShape sphere1(mksphere1.Shape());\n OccContactShape sphere2(mksphere2.Shape());\n\n OccContactFace sphere1_contact(sphere1, 0);\n OccContactFace sphere2_contact(sphere2, 0);\n\n SP::SiconosVector position1(new SiconosVector(7));\n SP::SiconosVector position2(new SiconosVector(7));\n SP::SiconosVector velocity(new SiconosVector(6));\n SP::SimpleMatrix inertia(new SimpleMatrix(3,3));\n position1->zero();\n (*position1)(0) = 0.;\n (*position1)(1) = 0.;\n (*position1)(2) = 0.;\n\n (*position1)(3) = 1;\n\n position2->zero();\n (*position2)(0) = 3.;\n (*position2)(1) = 0.;\n (*position2)(2) = 0.;\n\n (*position2)(3) = cos(pi\/2.);\n (*position2)(5) = sin(pi\/2.);\n\n velocity->zero();\n inertia->eye();\n\n SP::OccBody body1(new OccBody(position1, velocity, 1, inertia));\n SP::OccBody body2(new OccBody(position2, velocity, 1, inertia));\n\n body1->addContactShape(createSPtrOccContactShape(sphere1_contact));\n body2->addContactShape(createSPtrOccContactShape(sphere2_contact));\n\n\n std::cout << \"umin1:\" << body1->contactShape(0).binf1[0] << std::endl;\n std::cout << \"umax1:\" << body1->contactShape(0).bsup1[0] << std::endl;\n std::cout << \"vmin1:\" << body1->contactShape(0).binf1[1] << std::endl;\n std::cout << \"vmax1:\" << body1->contactShape(0).bsup1[1] << std::endl;\n\n std::cout << \"umin2:\" << body2->contactShape(0).binf1[0] << std::endl;\n std::cout << \"umax2:\" << body2->contactShape(0).bsup1[0] << std::endl;\n std::cout << \"vmin2:\" << body2->contactShape(0).binf1[1] << std::endl;\n std::cout << \"vmax2:\" << body2->contactShape(0).bsup1[1] << std::endl;\n\n gp_XYZ translat1 = body1->contactShape(0).data().Location().Transformation().\n TranslationPart();\n\n std::cout << translat1.X() << \",\" << translat1.Y() << \",\" << translat1.Z()\n << std::endl;\n\n\n gp_XYZ translat2 = body2->contactShape(0).data().Location().Transformation().\n TranslationPart();\n\n std::cout << translat2.X() << \",\" << translat2.Y() << \",\" << translat2.Z()\n << std::endl;\n\n SP::ContactShapeDistance pdist =\n body1->contactShape(0).distance(body2->contactShape(0));\n\n ContactShapeDistance& dist = *pdist;\n\n std::cout << dist.value << std::endl;\n\n std::cout << dist.x1 << \",\" << dist.y1 << \",\" << dist.z1 << std::endl;\n\n std::cout << dist.x2 << \",\" << dist.y2 << \",\" << dist.z2 << std::endl;\n\n std::cout << dist.nx << \",\" << dist.ny << \",\" << dist.nz << std::endl;\n\n CPPUNIT_ASSERT(std::abs(dist.value - 1.0) < 1e-9);\n\n}\n<|endoftext|>"} {"text":"\n#include \"MainWidget1.h\"\n#include \n\nMainWidget1::MainWidget1(QWidget* parent)\n : QWidget(parent)\n{\n MainButton_1 = new QPushButton(\"MainButton_1\", this);\n setFixedSize(500, 500);\n setWindowTitle(\"MainWindow\");\n MainButton_1->setFixedSize(200, 100);\n connect(MainButton_1, &QPushButton::clicked, this, &MainWidget1::sub_Send);\n\n setWindowIcon(QIcon(\"\/home\/sf\/pose.jpg\"));\n setWindowTitle(\"sss\");\n\n this->setAutoFillBackground(true);\n QPixmap pixmap;\n bool bb = pixmap.load(\".\/pose.jpg\"); \/\/设定图片\n Q_ASSERT(bb == true);\n QPalette palette = this->palette(); \/\/创建一个调色板对象\n palette.setBrush(this->backgroundRole(), QBrush(pixmap)); \/\/用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上\n this->setPalette(palette);\n}\nvoid MainWidget1::sub_Send(void)\n{\n \/\/ emit Send_Open();\n MainButton_1->setText(\"aaaaa中文 中文aassa\");\n}\n\nvoid MainWidget1::paintEvent(QPaintEvent* p)\n\n{\n#if 0\n QPixmap pixmap;\n bool bb = pixmap.load(\".\/pose.jpg\"); \/\/设定图片\n Q_ASSERT(bb == true);\n \/\/ QPalette palette = this->palette(); \/\/创建一个调色板对象\n \/\/ palette.setBrush(this->backgroundRole(), QBrush(pixmap)); \/\/用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上\n \/\/ connect(this,&MainWidget::Send_Open,&w2,&Sec_Widget::Cao_1);\n QPainter painter(this);\n\n painter.drawPixmap(0, 0, 500, 500, pixmap);\n\n painter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));\n painter.drawLine(0, 28, this->width(), 28);\n painter.drawLine(1006, 28, 1006, this->height());\n#endif\n}cplussharp vscode qttest QLabel绘制\n#include \"MainWidget1.h\"\n#include \n#include \n\nMainWidget1::MainWidget1(QWidget* parent)\n : QWidget(parent)\n{\n MainButton_1 = new QPushButton(\"MainButton_1\", this);\n \/\/ setFixedSize(500, 500);\n setWindowTitle(\"MainWindow\");\n MainButton_1->setFixedSize(200, 100);\n connect(MainButton_1, &QPushButton::clicked, this, &MainWidget1::sub_Send);\n\n setWindowIcon(QIcon(\"\/home\/sf\/pose.jpg\"));\n setWindowTitle(\"sss\");\n\n QLabel* qlabel = new QLabel(this);\n qlabel->setPixmap(QPixmap(\".\/pose.jpg\"));\n qlabel->setScaledContents(true);\n qlabel->setFixedSize(100, 100);\n qlabel->move(400, 400);\n\n this->setAutoFillBackground(true);\n QPixmap pixmap;\n bool bb = pixmap.load(\".\/pose.jpg\"); \/\/设定图片\n Q_ASSERT(bb == true);\n QPalette palette = this->palette(); \/\/创建一个调色板对象\n palette.setBrush(this->backgroundRole(), QBrush(pixmap)); \/\/用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上\n \/\/ this->setPalette(palette);\n}\nvoid MainWidget1::sub_Send(void)\n{\n \/\/ emit Send_Open();\n MainButton_1->setText(\"aaaaa中文 中文aassa\");\n}\n\nvoid MainWidget1::paintEvent(QPaintEvent* p)\n\n{\n#if 1\n QPixmap pixmap;\n bool bb = pixmap.load(\".\/pose.jpg\"); \/\/设定图片\n Q_ASSERT(bb == true);\n \/\/ QPalette palette = this->palette(); \/\/创建一个调色板对象\n \/\/ palette.setBrush(this->backgroundRole(), QBrush(pixmap)); \/\/用调色板的画笔把映射到pixmap上的图片画到frame.backgroundRole()这个背景上\n \/\/ connect(this,&MainWidget::Send_Open,&w2,&Sec_Widget::Cao_1);\n QPainter painter(this);\n\n painter.drawPixmap(0, 0, this->width(), this->height(), pixmap);\n\n \/\/ painter.setPen(QPen(Qt::blue, 2, Qt::SolidLine, Qt::RoundCap));\n \/\/ painter.drawLine(0, 28, this->width(), 28);\n \/\/ painter.drawLine(1006, 28, 1006, this->height());\n#endif\n}<|endoftext|>"} {"text":"\/** \\file augment_canones_references.cc\n * \\brief A tool for adding numerical canon law references to MARC-21 datasets.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2019, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"BibleUtil.h\"\n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"MARC.h\"\n#include \"MiscUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\nenum Codex { CIC1917, CIC1983, CCEO };\n\n\nCodex DetermineCodex(const std::string &subfield_codex, const std::string &subfield_year, const std::string &ppn) {\n if (::strcasecmp(subfield_codex.c_str(), \"Codex canonum ecclesiarum orientalium\") == 0)\n return CCEO;\n\n if (unlikely(subfield_year.empty()))\n LOG_ERROR(\"missing year for Codex Iuris Canonici! (PPN: \" + ppn + \")\");\n if (subfield_year == \"1917\")\n return CIC1917;\n else if (subfield_year == \"1983\")\n return CIC1983;\n\n LOG_ERROR(\"bad year for Codex Iuris Canonici \\\"\" + subfield_year + \"\\\"! (PPN: \" + ppn + \")\");\n}\n\n\n\/\/ To understand this code read https:\/\/github.com\/ubtue\/tuefind\/wiki\/Codices\nstd::string FieldToCanonLawCode(const std::string &ppn, const Codex codex, const std::string &subfield_part) {\n unsigned range_start, range_end;\n if (subfield_part.empty()) {\n range_start = 0;\n range_end = 99999999;\n } else if (not MiscUtil::ParseCanonLawRanges(subfield_part, &range_start, &range_end))\n LOG_ERROR(\"don't know how to parse codex parts \\\"\" + subfield_part + \"\\\"! (PPN: \" + ppn + \")\");\n\n switch (codex) {\n case CIC1917:\n return StringUtil::ToString(100000000 + range_start) + \"_\" + StringUtil::ToString(100000000 + range_end);\n case CIC1983:\n return StringUtil::ToString(200000000 + range_start) + \"_\" + StringUtil::ToString(200000000 + range_end);\n case CCEO:\n return StringUtil::ToString(300000000 + range_start) + \"_\" + StringUtil::ToString(300000000 + range_end);\n default:\n LOG_ERROR(\"unknown codex: \" + std::to_string(codex));\n }\n}\n\n\nstd::string CodexToPrefix(const Codex codex) {\n switch (codex) {\n case CIC1917:\n return \"CIC17\";\n case CIC1983:\n return \"CIC83\";\n case CCEO:\n return \"CCEO\";\n default:\n LOG_ERROR(\"unknown codex: \" + std::to_string(codex));\n }\n}\n\n\nvoid LoadAuthorityData(MARC::Reader * const reader,\n std::unordered_map * const authority_ppns_to_canon_law_codes_map)\n{\n const auto aliases_file(FileUtil::OpenOutputFileOrDie(UBTools::GetTuelibPath() + \"canon_law_aliases.map\"));\n\n unsigned total_count(0);\n while (auto record = reader->read()) {\n ++total_count;\n\n const auto _110_field(record.findTag(\"110\"));\n if (_110_field == record.end() or ::strcasecmp(_110_field->getFirstSubfieldWithCode('a').c_str(), \"Katholische Kirche\") != 0)\n continue;\n\n const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t'));\n if (::strcasecmp(t_subfield.c_str(),\"Codex Iuris Canonici\") != 0\n and ::strcasecmp(t_subfield.c_str(), \"Codex canonum ecclesiarum orientalium\") != 0)\n continue;\n\n const Codex codex(DetermineCodex(t_subfield, _110_field->getFirstSubfieldWithCode('f'), record.getControlNumber()));\n const auto canon_law_code(FieldToCanonLawCode(record.getControlNumber(), codex, _110_field->getFirstSubfieldWithCode('p')));\n (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = canon_law_code;\n\n for (const auto &_140_field : record.getTagRange(\"410\")) {\n const auto p_subfield(_140_field.getFirstSubfieldWithCode('p'));\n if (not p_subfield.empty())\n (*aliases_file) << CodexToPrefix(codex) << ' ' << TextUtil::UTF8ToLower(p_subfield) << '=' << canon_law_code << '\\n';\n }\n }\n\n LOG_INFO(\"found \" + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + \" canon law records among \"\n + std::to_string(total_count) + \" authority records.\");\n}\n\n\nvoid CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field, std::vector * const authority_ppns) {\n for (const auto &field : record.getTagRange(linking_field)) {\n const MARC::Subfields subfields(field.getSubfields());\n for (const auto &subfield : subfields) {\n if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, \"(DE-576)\"))\n authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen(\"(DE-576)\")));\n }\n }\n}\n\n\nvoid ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer,\n const std::unordered_map &authority_ppns_to_canon_law_codes_map)\n{\n static const std::vector CANONES_GND_LINKING_TAGS{ \"689\", \"655\" };\n\n unsigned total_count(0), augmented_count(0);\n std::map reference_counts;\n\n while (auto record = reader->read()) {\n ++total_count;\n\n bool augmented_record(false);\n for (const auto &linking_tag : CANONES_GND_LINKING_TAGS) {\n std::vector authority_ppns;\n CollectAuthorityPPNs(record, linking_tag, &authority_ppns);\n\n if (not authority_ppns.empty()) {\n for (const auto &authority_ppn : authority_ppns) {\n const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn));\n if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) {\n record.insertField(\"CAL\", { { 'a', ppn_and_canon_law_code->second } });\n augmented_record = true;\n ++reference_counts[linking_tag];\n }\n }\n }\n }\n\n if (not augmented_record) {\n \/\/ check if the codex data is embedded directly in the 689 field\n \/\/ apparently, 689$t is repeatable and the first instance (always?) appears to be 'Katholische Kirche'\n std::vector ranges_to_insert;\n for (const auto &_689_field : record.getTagRange(\"689\")) {\n if (_689_field.getFirstSubfieldWithCode('a') != \"Katholische Kirche\")\n continue;\n\n std::string subfield_codex, subfield_year, subfield_part;\n for (const auto &subfield : _689_field.getSubfields()) {\n if (subfield.code_ == 't' and subfield.value_ != \"Katholische Kirche\")\n subfield_codex = subfield.value_;\n else if (subfield.code_ == 'f')\n subfield_year = subfield.value_;\n else if (subfield.code_ == 'p')\n subfield_part = subfield.value_;\n }\n\n if (not subfield_codex.empty() and not subfield_year.empty() and not subfield_part.empty()) {\n const Codex codex(DetermineCodex(subfield_codex, subfield_year, record.getControlNumber()));\n ranges_to_insert.emplace_back(FieldToCanonLawCode(record.getControlNumber(), codex, subfield_part));\n augmented_record = true;\n ++reference_counts[\"689*\"];\n }\n }\n\n for (const auto &range : ranges_to_insert)\n record.insertField(\"CAL\", { { 'a', range } });\n }\n\n if (augmented_record)\n ++augmented_count;\n\n writer->write(record);\n }\n\n LOG_INFO(\"augmented \" + std::to_string(augmented_count) + \" of \" + std::to_string(total_count) + \" records.\");\n LOG_INFO(\"found \" + std::to_string(reference_counts[\"689\"]) + \" references in field 689\");\n LOG_INFO(\"found \" + std::to_string(reference_counts[\"689*\"]) + \" direct references in field 689\");\n LOG_INFO(\"found \" + std::to_string(reference_counts[\"655\"]) + \" references in field 655\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char **argv) {\n if (argc != 4)\n ::Usage(\"ixtheo_titles authority_records augmented_ixtheo_titles\");\n\n const std::string title_input_filename(argv[1]);\n const std::string authority_filename(argv[2]);\n const std::string title_output_filename(argv[3]);\n if (unlikely(title_input_filename == title_output_filename))\n LOG_ERROR(\"Title input file name equals title output file name!\");\n if (unlikely(title_input_filename == authority_filename))\n LOG_ERROR(\"Title input file name equals authority file name!\");\n if (unlikely(title_output_filename == authority_filename))\n LOG_ERROR(\"Title output file name equals authority file name!\");\n\n auto authority_reader(MARC::Reader::Factory(authority_filename));\n std::unordered_map authority_ppns_to_canon_law_codes_map;\n LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map);\n\n auto title_reader(MARC::Reader::Factory(title_input_filename));\n auto title_writer(MARC::Writer::Factory(title_output_filename));\n ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map);\n\n return EXIT_SUCCESS;\n}\nWe now use only a single field per record for canon-law ranges.\/** \\file augment_canones_references.cc\n * \\brief A tool for adding numerical canon law references to MARC-21 datasets.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2019, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"BibleUtil.h\"\n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"MARC.h\"\n#include \"MiscUtil.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\nenum Codex { CIC1917, CIC1983, CCEO };\n\n\nCodex DetermineCodex(const std::string &subfield_codex, const std::string &subfield_year, const std::string &ppn) {\n if (::strcasecmp(subfield_codex.c_str(), \"Codex canonum ecclesiarum orientalium\") == 0)\n return CCEO;\n\n if (unlikely(subfield_year.empty()))\n LOG_ERROR(\"missing year for Codex Iuris Canonici! (PPN: \" + ppn + \")\");\n if (subfield_year == \"1917\")\n return CIC1917;\n else if (subfield_year == \"1983\")\n return CIC1983;\n\n LOG_ERROR(\"bad year for Codex Iuris Canonici \\\"\" + subfield_year + \"\\\"! (PPN: \" + ppn + \")\");\n}\n\n\n\/\/ To understand this code read https:\/\/github.com\/ubtue\/tuefind\/wiki\/Codices\nstd::string FieldToCanonLawCode(const std::string &ppn, const Codex codex, const std::string &subfield_part) {\n unsigned range_start, range_end;\n if (subfield_part.empty()) {\n range_start = 0;\n range_end = 99999999;\n } else if (not MiscUtil::ParseCanonLawRanges(subfield_part, &range_start, &range_end))\n LOG_ERROR(\"don't know how to parse codex parts \\\"\" + subfield_part + \"\\\"! (PPN: \" + ppn + \")\");\n\n switch (codex) {\n case CIC1917:\n return StringUtil::ToString(100000000 + range_start) + \"_\" + StringUtil::ToString(100000000 + range_end);\n case CIC1983:\n return StringUtil::ToString(200000000 + range_start) + \"_\" + StringUtil::ToString(200000000 + range_end);\n case CCEO:\n return StringUtil::ToString(300000000 + range_start) + \"_\" + StringUtil::ToString(300000000 + range_end);\n default:\n LOG_ERROR(\"unknown codex: \" + std::to_string(codex));\n }\n}\n\n\nstd::string CodexToPrefix(const Codex codex) {\n switch (codex) {\n case CIC1917:\n return \"CIC17\";\n case CIC1983:\n return \"CIC83\";\n case CCEO:\n return \"CCEO\";\n default:\n LOG_ERROR(\"unknown codex: \" + std::to_string(codex));\n }\n}\n\n\nvoid LoadAuthorityData(MARC::Reader * const reader,\n std::unordered_map * const authority_ppns_to_canon_law_codes_map)\n{\n const auto aliases_file(FileUtil::OpenOutputFileOrDie(UBTools::GetTuelibPath() + \"canon_law_aliases.map\"));\n\n unsigned total_count(0);\n while (auto record = reader->read()) {\n ++total_count;\n\n const auto _110_field(record.findTag(\"110\"));\n if (_110_field == record.end() or ::strcasecmp(_110_field->getFirstSubfieldWithCode('a').c_str(), \"Katholische Kirche\") != 0)\n continue;\n\n const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t'));\n if (::strcasecmp(t_subfield.c_str(),\"Codex Iuris Canonici\") != 0\n and ::strcasecmp(t_subfield.c_str(), \"Codex canonum ecclesiarum orientalium\") != 0)\n continue;\n\n const Codex codex(DetermineCodex(t_subfield, _110_field->getFirstSubfieldWithCode('f'), record.getControlNumber()));\n const auto canon_law_code(FieldToCanonLawCode(record.getControlNumber(), codex, _110_field->getFirstSubfieldWithCode('p')));\n (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = canon_law_code;\n\n for (const auto &_140_field : record.getTagRange(\"410\")) {\n const auto p_subfield(_140_field.getFirstSubfieldWithCode('p'));\n if (not p_subfield.empty())\n (*aliases_file) << CodexToPrefix(codex) << ' ' << TextUtil::UTF8ToLower(p_subfield) << '=' << canon_law_code << '\\n';\n }\n }\n\n LOG_INFO(\"found \" + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + \" canon law records among \"\n + std::to_string(total_count) + \" authority records.\");\n}\n\n\nvoid CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field, std::vector * const authority_ppns) {\n for (const auto &field : record.getTagRange(linking_field)) {\n const MARC::Subfields subfields(field.getSubfields());\n for (const auto &subfield : subfields) {\n if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, \"(DE-576)\"))\n authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen(\"(DE-576)\")));\n }\n }\n}\n\n\nvoid ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer,\n const std::unordered_map &authority_ppns_to_canon_law_codes_map)\n{\n static const std::vector CANONES_GND_LINKING_TAGS{ \"689\", \"655\" };\n\n unsigned total_count(0), augmented_count(0);\n std::map reference_counts;\n\n while (auto record = reader->read()) {\n ++total_count;\n\n bool augmented_record(false);\n for (const auto &linking_tag : CANONES_GND_LINKING_TAGS) {\n std::vector authority_ppns;\n CollectAuthorityPPNs(record, linking_tag, &authority_ppns);\n\n if (not authority_ppns.empty()) {\n for (const auto &authority_ppn : authority_ppns) {\n const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn));\n if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) {\n record.insertField(\"CAL\", { { 'a', ppn_and_canon_law_code->second } });\n augmented_record = true;\n ++reference_counts[linking_tag];\n }\n }\n }\n }\n\n if (not augmented_record) {\n \/\/ check if the codex data is embedded directly in the 689 field\n \/\/ apparently, 689$t is repeatable and the first instance (always?) appears to be 'Katholische Kirche'\n std::vector ranges_to_insert;\n for (const auto &_689_field : record.getTagRange(\"689\")) {\n if (_689_field.getFirstSubfieldWithCode('a') != \"Katholische Kirche\")\n continue;\n\n std::string subfield_codex, subfield_year, subfield_part;\n for (const auto &subfield : _689_field.getSubfields()) {\n if (subfield.code_ == 't' and subfield.value_ != \"Katholische Kirche\")\n subfield_codex = subfield.value_;\n else if (subfield.code_ == 'f')\n subfield_year = subfield.value_;\n else if (subfield.code_ == 'p')\n subfield_part = subfield.value_;\n }\n\n if (not subfield_codex.empty() and not subfield_year.empty() and not subfield_part.empty()) {\n const Codex codex(DetermineCodex(subfield_codex, subfield_year, record.getControlNumber()));\n ranges_to_insert.emplace_back(FieldToCanonLawCode(record.getControlNumber(), codex, subfield_part));\n augmented_record = true;\n ++reference_counts[\"689*\"];\n }\n }\n\n if (not ranges_to_insert.empty())\n record.insertField(\"CAL\", { { 'a', StringUtil::Join(ranges_to_insert, ',') } });\n }\n\n if (augmented_record)\n ++augmented_count;\n\n writer->write(record);\n }\n\n LOG_INFO(\"augmented \" + std::to_string(augmented_count) + \" of \" + std::to_string(total_count) + \" records.\");\n LOG_INFO(\"found \" + std::to_string(reference_counts[\"689\"]) + \" references in field 689\");\n LOG_INFO(\"found \" + std::to_string(reference_counts[\"689*\"]) + \" direct references in field 689\");\n LOG_INFO(\"found \" + std::to_string(reference_counts[\"655\"]) + \" references in field 655\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char **argv) {\n if (argc != 4)\n ::Usage(\"ixtheo_titles authority_records augmented_ixtheo_titles\");\n\n const std::string title_input_filename(argv[1]);\n const std::string authority_filename(argv[2]);\n const std::string title_output_filename(argv[3]);\n if (unlikely(title_input_filename == title_output_filename))\n LOG_ERROR(\"Title input file name equals title output file name!\");\n if (unlikely(title_input_filename == authority_filename))\n LOG_ERROR(\"Title input file name equals authority file name!\");\n if (unlikely(title_output_filename == authority_filename))\n LOG_ERROR(\"Title output file name equals authority file name!\");\n\n auto authority_reader(MARC::Reader::Factory(authority_filename));\n std::unordered_map authority_ppns_to_canon_law_codes_map;\n LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map);\n\n auto title_reader(MARC::Reader::Factory(title_input_filename));\n auto title_writer(MARC::Writer::Factory(title_output_filename));\n ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map);\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin\n * 2012 by Matthias Noack, Zuse Institute Berlin\n *\n * Licensed under the BSD License, see LICENSE file for details.\n *\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"libxtreemfs\/stripe_translator.h\"\n#include \"libxtreemfs\/uuid_container.h\"\n#include \"libxtreemfs\/uuid_item.h\"\n#include \"libxtreemfs\/container_uuid_iterator.h\"\n#include \"libxtreemfs\/simple_uuid_iterator.h\"\n#include \"libxtreemfs\/xtreemfs_exception.h\"\n#include \"util\/logging.h\"\n#include \"xtreemfs\/GlobalTypes.pb.h\"\n\nusing namespace std;\nusing namespace xtreemfs::util;\n\nnamespace xtreemfs {\n\n\/\/ factory function, works fine with all default constructible iterator types\ntemplate\nUUIDIterator* CreateUUIDIterator() {\n return new IteratorType();\n}\n\n\/\/ functor to encapsulate different uuid adding mechanisms\ntemplate\nstruct UUIDAdder;\n\ntemplate<>\nstruct UUIDAdder {\n void operator()(UUIDIterator* it, string uuid) {\n static_cast(it)->AddUUID(uuid);\n }\n};\n\ntemplate<>\nstruct UUIDAdder {\n void operator()(UUIDIterator* it, string uuid) {\n created_items_.push_back(new UUIDItem(uuid));\n \/\/ safe downcast here\n static_cast(it)->AddUUIDItem(created_items_.back());\n }\n\n typedef vector ItemPtrList;\n\n ~UUIDAdder() {\n for (ItemPtrList::iterator it = created_items_.begin();\n it != created_items_.end();\n ++it) {\n delete *it;\n }\n created_items_.clear();\n }\n private:\n vector created_items_;\n};\n\n\ntemplate\nclass UUIDIteratorTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n initialize_logger(LEVEL_WARN);\n\n uuid_iterator_.reset(CreateUUIDIterator());\n }\n\n virtual void TearDown() {\n shutdown_logger();\n }\n\n boost::scoped_ptr uuid_iterator_;\n UUIDAdder adder_;\n};\n\n#if GTEST_HAS_TYPED_TEST\n\nusing testing::Types;\n\ntypedef Types Implementations;\n\nTYPED_TEST_CASE(UUIDIteratorTest, Implementations);\n\nTYPED_TEST(UUIDIteratorTest, ListWithOneUUID) {\n string uuid1 = \"uuid1\";\n string current_uuid;\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n \/\/ If there is only one UUID and it fails, there is no other choice and it\n \/\/ should be always returned.\n for (int i = 0; i < 2; i++) {\n this->uuid_iterator_->MarkUUIDAsFailed(current_uuid);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n }\n}\n\nTYPED_TEST(UUIDIteratorTest, ClearLeavesEmptyList) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->adder_(this->uuid_iterator_.get(), uuid2);\n\n \/\/ Clear the list.\n this->uuid_iterator_->Clear();\n\n \/\/ There should be no element left and GetUUID should fail.\n string current_uuid;\n EXPECT_THROW({this->uuid_iterator_->GetUUID(¤t_uuid);},\n UUIDIteratorListIsEmpyException);\n}\n\nTYPED_TEST(UUIDIteratorTest, ResetAfterEndOfList) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string current_uuid;\n\n \/\/ Fill iterator with two UUIDs.\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n this->adder_(this->uuid_iterator_.get(), uuid2);\n \/\/ No entry is marked as failed yet, the first UUID is still available.\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n \/\/ Mark the current entry (uuid1) as failed. uuid2 now current?\n this->uuid_iterator_->MarkUUIDAsFailed(uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n\n \/\/ Mark uuid1 again as failed - should have no consequences.\n this->uuid_iterator_->MarkUUIDAsFailed(uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n\n \/\/ Also mark uuid2 as failed now. Now all entries have failed. As we did reach\n \/\/ the end of the list, the status of all entries should be reset and set to\n \/\/ the first entry in the list.\n this->uuid_iterator_->MarkUUIDAsFailed(uuid2);\n for (list::iterator it\n = this->uuid_iterator_->uuids_.begin();\n it != this->uuid_iterator_->uuids_.end();\n ++it) {\n EXPECT_FALSE((*it)->IsFailed());\n }\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n}\n\nTYPED_TEST(UUIDIteratorTest, SetCurrentUUID) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n string current_uuid;\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->adder_(this->uuid_iterator_.get(), uuid2);\n this->adder_(this->uuid_iterator_.get(), uuid3);\n\n \/\/ First UUID is current.\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n \/\/ Set third as current one.\n this->uuid_iterator_->SetCurrentUUID(uuid3);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid3, current_uuid);\n\n \/\/ Fail the third (and last one): current UUID should be the first again.\n this->uuid_iterator_->MarkUUIDAsFailed(uuid3);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n for (list::iterator it\n = this->uuid_iterator_->uuids_.begin();\n it != this->uuid_iterator_->uuids_.end();\n ++it) {\n EXPECT_FALSE((*it)->IsFailed());\n }\n EXPECT_EQ(uuid1, current_uuid);\n}\n\nTYPED_TEST(UUIDIteratorTest, DebugString) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n\n EXPECT_EQ(\"[ ]\", this->uuid_iterator_->DebugString());\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n EXPECT_EQ(\"[ [ uuid1, 0] ]\", this->uuid_iterator_->DebugString());\n\n this->adder_(this->uuid_iterator_.get(), uuid2);\n EXPECT_EQ(\"[ [ uuid1, 0], [ uuid2, 0] ]\", this->uuid_iterator_->DebugString());\n\n this->adder_(this->uuid_iterator_.get(), uuid3);\n EXPECT_EQ(\"[ [ uuid1, 0], [ uuid2, 0], [ uuid3, 0] ]\", this->uuid_iterator_->DebugString());\n}\n\n#endif \/\/ GTEST_HAS_TYPED_TEST\n\n\/\/ Tests for SimpleUUIDIterator\n\nclass SimpleUUIDIteratorTest : public UUIDIteratorTest {\n public:\n void SetUp() {\n UUIDIteratorTest::SetUp();\n simple_uuid_iterator_ =\n static_cast(uuid_iterator_.get());\n }\n protected:\n SimpleUUIDIterator* simple_uuid_iterator_;\n};\n\nTEST_F(SimpleUUIDIteratorTest, LaterAddsDoNotBreakIterator) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n string current_uuid;\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->adder_(this->uuid_iterator_.get(), uuid2);\n\n \/\/ Mark first uuid as failed and the second takes over.\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n uuid_iterator_->MarkUUIDAsFailed(uuid1);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n\n \/\/ Add a third uuid which should be the next element if the second does fail.\n this->adder_(this->uuid_iterator_.get(), uuid3);\n uuid_iterator_->MarkUUIDAsFailed(uuid2);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid3, current_uuid);\n\n \/\/ After all uuids have failed, the first will be returned again.\n uuid_iterator_->MarkUUIDAsFailed(uuid3);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n}\n\n\nTEST_F(SimpleUUIDIteratorTest, SetCurrentUUIDAddsUnknownUUID) {\n string uuid1 = \"uuid1\";\n string current_uuid;\n\n \/\/ UUID1 not added so far. Setting it will automatically add it.\n uuid_iterator_->SetCurrentUUID(uuid1);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n}\n\nTEST_F(SimpleUUIDIteratorTest, ClearAndAddUUID) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n string current_uuid;\n\n EXPECT_EQ(0, simple_uuid_iterator_->uuids_.size());\n\n simple_uuid_iterator_->ClearAndAddUUID(uuid1);\n simple_uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());\n\n simple_uuid_iterator_->ClearAndAddUUID(uuid2);\n simple_uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());\n\n simple_uuid_iterator_->ClearAndAddUUID(uuid3);\n simple_uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid3, current_uuid);\n EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());\n}\n\n\/\/ Tests for ContainerUUIDIterator\n\nclass ContainerUUIDIteratorTest\n : public UUIDIteratorTest {};\n\nTEST_F(ContainerUUIDIteratorTest, CreateContainerAndGetUUID) {\n \/\/ Create container from XLocList\n pbrpc::XLocSet xlocs;\n pbrpc::StripingPolicyType type = pbrpc::STRIPING_POLICY_RAID0;\n const int replicaCount = 3;\n stringstream sstream;\n\n for (int i = 0; i < replicaCount; ++i) {\n pbrpc::Replica* replica = xlocs.add_replicas();\n const int stripe_width = i + 2;\n\n for (int j = 0; j < stripe_width; ++j) {\n sstream.str(\"\");\n sstream << \"uuid\" << i << j;\n replica->add_osd_uuids(sstream.str());\n replica->mutable_striping_policy()->set_type(type);\n replica->mutable_striping_policy()->set_stripe_size(128); \/\/ kb\n replica->mutable_striping_policy()->set_width(stripe_width);\n }\n }\n\n \/\/ get all striping policies\n StripeTranslator::PolicyContainer striping_policies;\n for (uint32_t i = 0; i < xlocs.replicas_size(); ++i) {\n striping_policies.push_back(&(xlocs.replicas(i).striping_policy()));\n }\n\n boost::scoped_ptr uuid_container(new UUIDContainer(xlocs));\n\n \/\/ NOTE: We assume that all replicas use the same striping policy type and\n \/\/ that all replicas use the same stripe size.\n boost::scoped_ptr translator(new StripeTranslatorRaid0());\n \/\/ Map offset to corresponding OSDs.\n std::vector operations;\n off_t read_offsets[] = {0, 128 * 1024};\n\n for (int i = 0; i < sizeof(read_offsets); ++i) {\n operations.clear();\n translator->TranslateReadRequest(NULL,\n 128 * 1024,\n read_offsets[i],\n striping_policies,\n &operations);\n\n \/\/ Create a UUIDIterator for a specific set of offsets\n boost::scoped_ptr uuid_iterator(\n new ContainerUUIDIterator(uuid_container.get(),\n operations[0].osd_offsets));\n\n \/\/ check results\n string actual;\n for (int j = 0; j < replicaCount; ++j) {\n uuid_iterator->GetUUID(&actual);\n uuid_iterator->MarkUUIDAsFailed(actual);\n sstream.str(\"\");\n sstream << \"uuid\" << j << operations[0].osd_offsets[j];\n EXPECT_EQ(sstream.str(), actual);\n }\n }\n}\n\n} \/\/ namespace xtreemfs\nclient: Fixed compilation problem of UUIDIteratorTest on older systems.\/*\n * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin\n * 2012 by Matthias Noack, Zuse Institute Berlin\n *\n * Licensed under the BSD License, see LICENSE file for details.\n *\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"libxtreemfs\/stripe_translator.h\"\n#include \"libxtreemfs\/uuid_container.h\"\n#include \"libxtreemfs\/uuid_item.h\"\n#include \"libxtreemfs\/container_uuid_iterator.h\"\n#include \"libxtreemfs\/simple_uuid_iterator.h\"\n#include \"libxtreemfs\/xtreemfs_exception.h\"\n#include \"util\/logging.h\"\n#include \"xtreemfs\/GlobalTypes.pb.h\"\n\nusing namespace std;\nusing namespace xtreemfs::util;\n\nnamespace xtreemfs {\n\n\/\/ factory function, works fine with all default constructible iterator types\ntemplate\nUUIDIterator* CreateUUIDIterator() {\n return new IteratorType();\n}\n\n\/\/ functor to encapsulate different uuid adding mechanisms\ntemplate\nstruct UUIDAdder;\n\ntemplate<>\nstruct UUIDAdder {\n void operator()(UUIDIterator* it, string uuid) {\n static_cast(it)->AddUUID(uuid);\n }\n};\n\ntemplate<>\nstruct UUIDAdder {\n void operator()(UUIDIterator* it, string uuid) {\n created_items_.push_back(new UUIDItem(uuid));\n \/\/ safe downcast here\n static_cast(it)->AddUUIDItem(created_items_.back());\n }\n\n typedef vector ItemPtrList;\n\n ~UUIDAdder() {\n for (ItemPtrList::iterator it = created_items_.begin();\n it != created_items_.end();\n ++it) {\n delete *it;\n }\n created_items_.clear();\n }\n private:\n vector created_items_;\n};\n\n\ntemplate\nclass UUIDIteratorTest : public ::testing::Test {\n protected:\n virtual void SetUp() {\n initialize_logger(LEVEL_WARN);\n\n uuid_iterator_.reset(CreateUUIDIterator());\n }\n\n virtual void TearDown() {\n shutdown_logger();\n }\n\n boost::scoped_ptr uuid_iterator_;\n UUIDAdder adder_;\n};\n\n#if GTEST_HAS_TYPED_TEST\n\nusing testing::Types;\n\ntypedef Types Implementations;\n\nTYPED_TEST_CASE(UUIDIteratorTest, Implementations);\n\nTYPED_TEST(UUIDIteratorTest, ListWithOneUUID) {\n string uuid1 = \"uuid1\";\n string current_uuid;\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n \/\/ If there is only one UUID and it fails, there is no other choice and it\n \/\/ should be always returned.\n for (int i = 0; i < 2; i++) {\n this->uuid_iterator_->MarkUUIDAsFailed(current_uuid);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n }\n}\n\nTYPED_TEST(UUIDIteratorTest, ClearLeavesEmptyList) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->adder_(this->uuid_iterator_.get(), uuid2);\n\n \/\/ Clear the list.\n this->uuid_iterator_->Clear();\n\n \/\/ There should be no element left and GetUUID should fail.\n string current_uuid;\n EXPECT_THROW({this->uuid_iterator_->GetUUID(¤t_uuid);},\n UUIDIteratorListIsEmpyException);\n}\n\nTYPED_TEST(UUIDIteratorTest, ResetAfterEndOfList) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string current_uuid;\n\n \/\/ Fill iterator with two UUIDs.\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n this->adder_(this->uuid_iterator_.get(), uuid2);\n \/\/ No entry is marked as failed yet, the first UUID is still available.\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n \/\/ Mark the current entry (uuid1) as failed. uuid2 now current?\n this->uuid_iterator_->MarkUUIDAsFailed(uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n\n \/\/ Mark uuid1 again as failed - should have no consequences.\n this->uuid_iterator_->MarkUUIDAsFailed(uuid1);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n\n \/\/ Also mark uuid2 as failed now. Now all entries have failed. As we did reach\n \/\/ the end of the list, the status of all entries should be reset and set to\n \/\/ the first entry in the list.\n this->uuid_iterator_->MarkUUIDAsFailed(uuid2);\n for (list::iterator it\n = this->uuid_iterator_->uuids_.begin();\n it != this->uuid_iterator_->uuids_.end();\n ++it) {\n EXPECT_FALSE((*it)->IsFailed());\n }\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n}\n\nTYPED_TEST(UUIDIteratorTest, SetCurrentUUID) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n string current_uuid;\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->adder_(this->uuid_iterator_.get(), uuid2);\n this->adder_(this->uuid_iterator_.get(), uuid3);\n\n \/\/ First UUID is current.\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n\n \/\/ Set third as current one.\n this->uuid_iterator_->SetCurrentUUID(uuid3);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid3, current_uuid);\n\n \/\/ Fail the third (and last one): current UUID should be the first again.\n this->uuid_iterator_->MarkUUIDAsFailed(uuid3);\n this->uuid_iterator_->GetUUID(¤t_uuid);\n for (list::iterator it\n = this->uuid_iterator_->uuids_.begin();\n it != this->uuid_iterator_->uuids_.end();\n ++it) {\n EXPECT_FALSE((*it)->IsFailed());\n }\n EXPECT_EQ(uuid1, current_uuid);\n}\n\nTYPED_TEST(UUIDIteratorTest, DebugString) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n\n EXPECT_EQ(\"[ ]\", this->uuid_iterator_->DebugString());\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n EXPECT_EQ(\"[ [ uuid1, 0] ]\", this->uuid_iterator_->DebugString());\n\n this->adder_(this->uuid_iterator_.get(), uuid2);\n EXPECT_EQ(\"[ [ uuid1, 0], [ uuid2, 0] ]\", this->uuid_iterator_->DebugString());\n\n this->adder_(this->uuid_iterator_.get(), uuid3);\n EXPECT_EQ(\"[ [ uuid1, 0], [ uuid2, 0], [ uuid3, 0] ]\", this->uuid_iterator_->DebugString());\n}\n\n#endif \/\/ GTEST_HAS_TYPED_TEST\n\n\/\/ Tests for SimpleUUIDIterator\n\nclass SimpleUUIDIteratorTest : public UUIDIteratorTest {\n public:\n void SetUp() {\n UUIDIteratorTest::SetUp();\n simple_uuid_iterator_ =\n static_cast(uuid_iterator_.get());\n }\n protected:\n SimpleUUIDIterator* simple_uuid_iterator_;\n};\n\nTEST_F(SimpleUUIDIteratorTest, LaterAddsDoNotBreakIterator) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n string current_uuid;\n\n this->adder_(this->uuid_iterator_.get(), uuid1);\n this->adder_(this->uuid_iterator_.get(), uuid2);\n\n \/\/ Mark first uuid as failed and the second takes over.\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n uuid_iterator_->MarkUUIDAsFailed(uuid1);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n\n \/\/ Add a third uuid which should be the next element if the second does fail.\n this->adder_(this->uuid_iterator_.get(), uuid3);\n uuid_iterator_->MarkUUIDAsFailed(uuid2);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid3, current_uuid);\n\n \/\/ After all uuids have failed, the first will be returned again.\n uuid_iterator_->MarkUUIDAsFailed(uuid3);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n}\n\n\nTEST_F(SimpleUUIDIteratorTest, SetCurrentUUIDAddsUnknownUUID) {\n string uuid1 = \"uuid1\";\n string current_uuid;\n\n \/\/ UUID1 not added so far. Setting it will automatically add it.\n uuid_iterator_->SetCurrentUUID(uuid1);\n uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n}\n\nTEST_F(SimpleUUIDIteratorTest, ClearAndAddUUID) {\n string uuid1 = \"uuid1\";\n string uuid2 = \"uuid2\";\n string uuid3 = \"uuid3\";\n string current_uuid;\n\n EXPECT_EQ(0, simple_uuid_iterator_->uuids_.size());\n\n simple_uuid_iterator_->ClearAndAddUUID(uuid1);\n simple_uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid1, current_uuid);\n EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());\n\n simple_uuid_iterator_->ClearAndAddUUID(uuid2);\n simple_uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid2, current_uuid);\n EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());\n\n simple_uuid_iterator_->ClearAndAddUUID(uuid3);\n simple_uuid_iterator_->GetUUID(¤t_uuid);\n EXPECT_EQ(uuid3, current_uuid);\n EXPECT_EQ(1, simple_uuid_iterator_->uuids_.size());\n}\n\n\/\/ Tests for ContainerUUIDIterator\n\nclass ContainerUUIDIteratorTest\n : public UUIDIteratorTest {};\n\nTEST_F(ContainerUUIDIteratorTest, CreateContainerAndGetUUID) {\n \/\/ Create container from XLocList\n pbrpc::XLocSet xlocs;\n pbrpc::StripingPolicyType type = pbrpc::STRIPING_POLICY_RAID0;\n const int replicaCount = 3;\n stringstream sstream;\n\n for (int i = 0; i < replicaCount; ++i) {\n pbrpc::Replica* replica = xlocs.add_replicas();\n const int stripe_width = i + 2;\n\n for (int j = 0; j < stripe_width; ++j) {\n sstream.str(\"\");\n sstream << \"uuid\" << i << j;\n replica->add_osd_uuids(sstream.str());\n replica->mutable_striping_policy()->set_type(type);\n replica->mutable_striping_policy()->set_stripe_size(128); \/\/ kb\n replica->mutable_striping_policy()->set_width(stripe_width);\n }\n }\n\n \/\/ get all striping policies\n StripeTranslator::PolicyContainer striping_policies;\n for (uint32_t i = 0; i < xlocs.replicas_size(); ++i) {\n striping_policies.push_back(&(xlocs.replicas(i).striping_policy()));\n }\n\n boost::scoped_ptr uuid_container(new UUIDContainer(xlocs));\n\n \/\/ NOTE: We assume that all replicas use the same striping policy type and\n \/\/ that all replicas use the same stripe size.\n boost::scoped_ptr translator(new StripeTranslatorRaid0());\n \/\/ Map offset to corresponding OSDs.\n std::vector operations;\n off_t read_offsets[] = {0, 128 * 1024};\n\n for (int i = 0; i < sizeof(read_offsets); ++i) {\n operations.clear();\n translator->TranslateReadRequest(NULL,\n 128 * 1024,\n read_offsets[i],\n striping_policies,\n &operations);\n\n \/\/ Create a UUIDIterator for a specific set of offsets\n boost::scoped_ptr uuid_iterator(\n new ContainerUUIDIterator(uuid_container.get(),\n operations[0].osd_offsets));\n\n \/\/ check results\n string actual;\n for (int j = 0; j < replicaCount; ++j) {\n uuid_iterator->GetUUID(&actual);\n uuid_iterator->MarkUUIDAsFailed(actual);\n sstream.str(\"\");\n sstream << \"uuid\" << j << operations[0].osd_offsets[j];\n EXPECT_EQ(sstream.str(), actual);\n }\n }\n}\n\n} \/\/ namespace xtreemfs\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) 2013 Mateusz Łoskot \n\/\/ Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n\/\/\n\/\/ This file is part of Qt Creator Boost.Build plugin project.\n\/\/\n\/\/ This is free software; you can redistribute and\/or modify it under\n\/\/ the terms of the GNU Lesser General Public License, Version 2.1\n\/\/ as published by the Free Software Foundation.\n\/\/ See the LICENSE.txt file for more information.\n\/\/\n#include \"bbopenprojectwizard.hpp\"\n#include \"bbproject.hpp\"\n#include \"bbprojectmanagerconstants.hpp\"\n#include \"bbutility.hpp\"\n#include \"filesselectionwizardpage.hpp\"\n\/\/ Qt Creator\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace BoostBuildProjectManager {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nOpenProjectWizard::OpenProjectWizard(Project const* const project)\n : project_(project)\n , projectOpened_(false)\n{\n \/\/ Project instance has been created, but it's only partially initialised and\n \/\/ rest of the initialisation takes place after this wizard completes.\n Q_ASSERT(project_);\n\n setDisplayName(tr(\"Open %1 Project\").arg(BBPM_C(BOOSTBUILD)));\n setId(BBPM_C(PROJECT_WIZARD_ID));\n setWizardKind(ProjectWizard); \/\/ affects dir vs file path and sub-projects handling\n\n \/\/ TODO: do we need categories or flags?\n}\n\nbool OpenProjectWizard::run(QString const& platform, QVariantMap const& extraValues)\n{\n QVariantMap extraValuesCopy(extraValues);\n\n \/\/ Project name should be passed by caller, but,\n \/\/ since we have Project instance handy, double-check.\n if (!extraValuesCopy.contains(BBPM_C(P_KEY_PROJECTNAME)))\n extraValuesCopy.insert(BBPM_C(P_KEY_PROJECTNAME), project_->displayName());\n\n projectOpened_ = false;\n outputValues_.clear();\n\n runWizard(project_->projectFilePath(), 0, platform, extraValuesCopy);\n\n return projectOpened_;\n}\n\nQWizard*\nOpenProjectWizard::createWizardDialog(QWidget* parent\n , Core::WizardDialogParameters const& parameters) const\n{\n\n OpenProjectWizardDialog* wizard(new OpenProjectWizardDialog(parent\n , parameters.defaultPath(), parameters.extraValues()\n , const_cast(this)->outputValues_));\n\n foreach (QWizardPage* p, parameters.extensionPages())\n BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(p));\n\n return wizard;\n}\n\nCore::GeneratedFiles\nOpenProjectWizard::generateFiles(QWizard const* wizard, QString* errorMessage) const\n{\n Q_UNUSED(errorMessage)\n Q_ASSERT(project_);\n\n OpenProjectWizardDialog const* openWizard\n = qobject_cast(wizard);\n\n QDir const projectDir(openWizard->path());\n\n \/\/ Set up MIME filters for C\/C++ headers\n QStringList headerFilters;\n QStringList const headerMimeTypes = QStringList()\n << QLatin1String(\"text\/x-chdr\") << QLatin1String(\"text\/x-c++hdr\");\n foreach (QString const& headerMime, headerMimeTypes)\n {\n Core::MimeType mime = Core::MimeDatabase::findByType(headerMime);\n foreach (Core::MimeGlobPattern const& gp, mime.globPatterns())\n headerFilters.append(gp.pattern());\n }\n\n \/\/ Generate list of include paths.\n \/\/ If any C\/C++ headers in any directory from paths, add it to include paths,\n \/\/ used for C\/C++ parsing only.\n QStringList includePaths;\n QStringList const paths = openWizard->selectedPaths();\n foreach (QString const& path, paths)\n {\n QFileInfo const fileInfo(path);\n QDir const thisDir(fileInfo.absoluteFilePath());\n if (!thisDir.entryList(headerFilters, QDir::Files).isEmpty())\n {\n QString const relative = projectDir.relativeFilePath(thisDir.path());\n includePaths.append(relative.isEmpty() ? QLatin1String(\".\") : relative);\n }\n }\n\n \/\/ Generate list of sources\n QStringList sources = openWizard->selectedFiles();\n Utility::makeRelativePaths(projectDir.absolutePath(), sources);\n\n Core::GeneratedFile generatedFilesFile(project_->filesFilePath());\n generatedFilesFile.setContents(sources.join(QLatin1String(\"\\n\")));\n\n Core::GeneratedFile generatedIncludesFile(project_->includesFilePath());\n generatedIncludesFile.setContents(includePaths.join(QLatin1String(\"\\n\")));\n\n Core::GeneratedFiles files;\n files.append(generatedFilesFile);\n files.append(generatedIncludesFile);\n return files;\n}\n\nbool\nOpenProjectWizard::postGenerateFiles(QWizard const* wizard\n , Core::GeneratedFiles const& files, QString* errorMessage)\n{\n Q_UNUSED(wizard);\n\n projectOpened_\n = ProjectExplorer::CustomProjectWizard::postGenerateOpen(files, errorMessage);\n\n return projectOpened_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nOpenProjectWizardDialog::OpenProjectWizardDialog(QWidget* parent\n , QString const& projectFile\n , QVariantMap const& extraValues, QVariantMap& outputValues)\n : Utils::Wizard(parent)\n , outputValues_(outputValues)\n , extraValues_(extraValues)\n , projectFile_(projectFile)\n{\n setWindowTitle(tr(\"Open %1 Project\").arg(BBPM_C(BOOSTBUILD)));\n\n pathsPage_ = new PathsSelectionWizardPage(this);\n pathsPage_->setTitle(tr(\"Project Name and Paths\"));\n int const pathsPageId = addPage(pathsPage_);\n wizardProgress()->item(pathsPageId)->setTitle(tr(\"Location\"));\n\n filesPage_ = new FilesSelectionWizardPage(this);\n filesPage_->setTitle(tr(\"File Selection\"));\n int const filesPageId = addPage(filesPage_);\n wizardProgress()->item(filesPageId)->setTitle(tr(\"Files\"));\n}\n\n\nQString OpenProjectWizardDialog::path() const\n{\n QFileInfo const projectFileInfo(projectFile());\n QTC_ASSERT(projectFileInfo.isFile(), return QString());\n\n return projectFileInfo.absoluteDir().absolutePath();\n}\n\nQString OpenProjectWizardDialog::projectFile() const\n{\n return projectFile_;\n}\n\nQString OpenProjectWizardDialog::projectName() const\n{\n return pathsPage_->projectName();\n}\n\nQString OpenProjectWizardDialog::defaultProjectName() const\n{\n return extraValues_.value(BBPM_C(P_KEY_PROJECTNAME)).toString();\n}\n\nQStringList OpenProjectWizardDialog::selectedFiles() const\n{\n return filesPage_->selectedFiles();\n}\n\nQStringList OpenProjectWizardDialog::selectedPaths() const\n{\n return filesPage_->selectedPaths();\n}\n\nvoid OpenProjectWizardDialog::setProjectName(QString const& name)\n{\n outputValues_.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPathsSelectionWizardPage::PathsSelectionWizardPage(OpenProjectWizardDialog* wizard)\n : QWizardPage(wizard)\n , wizard_(wizard)\n{\n QFormLayout *fl = new QFormLayout();\n setLayout(fl);\n\n QLabel* pathLabel = new QLabel(this);\n pathLabel->setText(tr(\"Opening the following Jamfile as a project:\"));\n fl->addRow(pathLabel);\n\n QLineEdit* pathLine = new QLineEdit(this);\n pathLine->setReadOnly(true);\n pathLine->setDisabled(true);\n pathLine->setText(wizard_->path());\n fl->addRow(pathLine);\n\n QString projectName(Utility::parseJamfileProjectName(wizard_->projectFile()));\n if (projectName.isEmpty())\n projectName = wizard_->defaultProjectName();\n\n nameLineEdit_ = new QLineEdit(this);\n connect(nameLineEdit_, &QLineEdit::textChanged\n , wizard_, &OpenProjectWizardDialog::setProjectName);\n nameLineEdit_->setText(projectName);\n fl->addRow(tr(\"Project name:\"), nameLineEdit_);\n\n QLabel* defaultsLabel = new QLabel(this);\n defaultsLabel->setText(tr(\"Default Boost.Build runtime locations:\"));\n fl->addRow(defaultsLabel);\n\n QLineEdit* workingLine = new QLineEdit(this);\n workingLine->setReadOnly(true);\n workingLine->setDisabled(true);\n workingLine->setText(Project::defaultWorkingDirectory(wizard_->path()));\n fl->addRow(tr(\"Working directory:\"), workingLine);\n\n QLineEdit* buildLine = new QLineEdit(this);\n buildLine->setReadOnly(true);\n buildLine->setDisabled(true);\n buildLine->setText(Project::defaultBuildDirectory(wizard_->path()));\n fl->addRow(tr(\"Build directory:\"), buildLine);\n\n \/\/ TODO: indicate if we can find Boost.Build executable?\n\n QString const info(tr(\n \"This allows you to use Qt Creator as an IDE to edit and navigate C++ code, \"\n \"run %1 command, work through compilation issues, \"\n \"configure executable targets to run and debug.\")\n .arg(QLatin1String(Constants::BOOSTBUILD)));\n QLabel* infoLabel = new QLabel(this);\n infoLabel->setWordWrap(true);\n infoLabel->setText(info);\n fl->addRow(infoLabel);\n}\n\nQString PathsSelectionWizardPage::projectName() const\n{\n return nameLineEdit_->text();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace BoostBuildProjectManager\nFix project path and projectFile location mismatch\/\/\n\/\/ Copyright (C) 2013 Mateusz Łoskot \n\/\/ Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n\/\/\n\/\/ This file is part of Qt Creator Boost.Build plugin project.\n\/\/\n\/\/ This is free software; you can redistribute and\/or modify it under\n\/\/ the terms of the GNU Lesser General Public License, Version 2.1\n\/\/ as published by the Free Software Foundation.\n\/\/ See the LICENSE.txt file for more information.\n\/\/\n#include \"bbopenprojectwizard.hpp\"\n#include \"bbproject.hpp\"\n#include \"bbprojectmanagerconstants.hpp\"\n#include \"bbutility.hpp\"\n#include \"filesselectionwizardpage.hpp\"\n\/\/ Qt Creator\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace BoostBuildProjectManager {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nOpenProjectWizard::OpenProjectWizard(Project const* const project)\n : project_(project)\n , projectOpened_(false)\n{\n \/\/ Project instance has been created, but it's only partially initialised and\n \/\/ rest of the initialisation takes place after this wizard completes.\n Q_ASSERT(project_);\n\n setDisplayName(tr(\"Open %1 Project\").arg(BBPM_C(BOOSTBUILD)));\n setId(BBPM_C(PROJECT_WIZARD_ID));\n setWizardKind(ProjectWizard); \/\/ affects dir vs file path and sub-projects handling\n\n \/\/ TODO: do we need categories or flags?\n}\n\nbool OpenProjectWizard::run(QString const& platform, QVariantMap const& extraValues)\n{\n QVariantMap extraValuesCopy(extraValues);\n\n \/\/ Project name should be passed by caller, but,\n \/\/ since we have Project instance handy, double-check.\n if (!extraValuesCopy.contains(BBPM_C(P_KEY_PROJECTNAME)))\n extraValuesCopy.insert(BBPM_C(P_KEY_PROJECTNAME), project_->displayName());\n\n projectOpened_ = false;\n outputValues_.clear();\n\n runWizard(project_->projectFilePath(), 0, platform, extraValuesCopy);\n\n return projectOpened_;\n}\n\nQWizard*\nOpenProjectWizard::createWizardDialog(QWidget* parent\n , Core::WizardDialogParameters const& parameters) const\n{\n\n OpenProjectWizardDialog* wizard(new OpenProjectWizardDialog(parent\n , parameters.defaultPath(), parameters.extraValues()\n , const_cast(this)->outputValues_));\n\n foreach (QWizardPage* p, parameters.extensionPages())\n BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(p));\n\n return wizard;\n}\n\nCore::GeneratedFiles\nOpenProjectWizard::generateFiles(QWizard const* wizard, QString* errorMessage) const\n{\n Q_UNUSED(errorMessage)\n Q_ASSERT(project_);\n\n OpenProjectWizardDialog const* openWizard\n = qobject_cast(wizard);\n\n QDir const projectDir(openWizard->path());\n\n \/\/ Set up MIME filters for C\/C++ headers\n QStringList headerFilters;\n QStringList const headerMimeTypes = QStringList()\n << QLatin1String(\"text\/x-chdr\") << QLatin1String(\"text\/x-c++hdr\");\n foreach (QString const& headerMime, headerMimeTypes)\n {\n Core::MimeType mime = Core::MimeDatabase::findByType(headerMime);\n foreach (Core::MimeGlobPattern const& gp, mime.globPatterns())\n headerFilters.append(gp.pattern());\n }\n\n \/\/ Generate list of include paths.\n \/\/ If any C\/C++ headers in any directory from paths, add it to include paths,\n \/\/ used for C\/C++ parsing only.\n QStringList includePaths;\n QStringList const paths = openWizard->selectedPaths();\n foreach (QString const& path, paths)\n {\n QFileInfo const fileInfo(path);\n QDir const thisDir(fileInfo.absoluteFilePath());\n if (!thisDir.entryList(headerFilters, QDir::Files).isEmpty())\n {\n QString const relative = projectDir.relativeFilePath(thisDir.path());\n includePaths.append(relative.isEmpty() ? QLatin1String(\".\") : relative);\n }\n }\n\n \/\/ Generate list of sources\n QStringList sources = openWizard->selectedFiles();\n Utility::makeRelativePaths(projectDir.absolutePath(), sources);\n\n Core::GeneratedFile generatedFilesFile(project_->filesFilePath());\n generatedFilesFile.setContents(sources.join(QLatin1String(\"\\n\")));\n\n Core::GeneratedFile generatedIncludesFile(project_->includesFilePath());\n generatedIncludesFile.setContents(includePaths.join(QLatin1String(\"\\n\")));\n\n Core::GeneratedFiles files;\n files.append(generatedFilesFile);\n files.append(generatedIncludesFile);\n return files;\n}\n\nbool\nOpenProjectWizard::postGenerateFiles(QWizard const* wizard\n , Core::GeneratedFiles const& files, QString* errorMessage)\n{\n Q_UNUSED(wizard);\n\n projectOpened_\n = ProjectExplorer::CustomProjectWizard::postGenerateOpen(files, errorMessage);\n\n return projectOpened_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nOpenProjectWizardDialog::OpenProjectWizardDialog(QWidget* parent\n , QString const& projectFile\n , QVariantMap const& extraValues, QVariantMap& outputValues)\n : Utils::Wizard(parent)\n , outputValues_(outputValues)\n , extraValues_(extraValues)\n , projectFile_(projectFile)\n{\n setWindowTitle(tr(\"Open %1 Project\").arg(BBPM_C(BOOSTBUILD)));\n\n pathsPage_ = new PathsSelectionWizardPage(this);\n pathsPage_->setTitle(tr(\"Project Name and Paths\"));\n int const pathsPageId = addPage(pathsPage_);\n wizardProgress()->item(pathsPageId)->setTitle(tr(\"Location\"));\n\n filesPage_ = new FilesSelectionWizardPage(this);\n filesPage_->setTitle(tr(\"File Selection\"));\n int const filesPageId = addPage(filesPage_);\n wizardProgress()->item(filesPageId)->setTitle(tr(\"Files\"));\n}\n\n\nQString OpenProjectWizardDialog::path() const\n{\n QFileInfo const projectFileInfo(projectFile());\n QTC_ASSERT(projectFileInfo.isFile(), return QString());\n\n return projectFileInfo.absoluteDir().absolutePath();\n}\n\nQString OpenProjectWizardDialog::projectFile() const\n{\n return projectFile_;\n}\n\nQString OpenProjectWizardDialog::projectName() const\n{\n return pathsPage_->projectName();\n}\n\nQString OpenProjectWizardDialog::defaultProjectName() const\n{\n return extraValues_.value(BBPM_C(P_KEY_PROJECTNAME)).toString();\n}\n\nQStringList OpenProjectWizardDialog::selectedFiles() const\n{\n return filesPage_->selectedFiles();\n}\n\nQStringList OpenProjectWizardDialog::selectedPaths() const\n{\n return filesPage_->selectedPaths();\n}\n\nvoid OpenProjectWizardDialog::setProjectName(QString const& name)\n{\n outputValues_.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPathsSelectionWizardPage::PathsSelectionWizardPage(OpenProjectWizardDialog* wizard)\n : QWizardPage(wizard)\n , wizard_(wizard)\n{\n QFormLayout *fl = new QFormLayout();\n setLayout(fl);\n\n QLabel* pathLabel = new QLabel(this);\n pathLabel->setText(tr(\"Opening the following Jamfile as a project:\"));\n fl->addRow(pathLabel);\n\n QLineEdit* pathLine = new QLineEdit(this);\n pathLine->setReadOnly(true);\n pathLine->setDisabled(true);\n pathLine->setText(wizard_->projectFile());\n fl->addRow(pathLine);\n\n QString projectName(Utility::parseJamfileProjectName(wizard_->projectFile()));\n if (projectName.isEmpty())\n projectName = wizard_->defaultProjectName();\n\n nameLineEdit_ = new QLineEdit(this);\n connect(nameLineEdit_, &QLineEdit::textChanged\n , wizard_, &OpenProjectWizardDialog::setProjectName);\n nameLineEdit_->setText(projectName);\n fl->addRow(tr(\"Project name:\"), nameLineEdit_);\n\n QLabel* defaultsLabel = new QLabel(this);\n defaultsLabel->setText(tr(\"Default Boost.Build runtime locations:\"));\n fl->addRow(defaultsLabel);\n\n QLineEdit* workingLine = new QLineEdit(this);\n workingLine->setReadOnly(true);\n workingLine->setDisabled(true);\n workingLine->setText(Project::defaultWorkingDirectory(wizard_->projectFile()));\n fl->addRow(tr(\"Working directory:\"), workingLine);\n\n QLineEdit* buildLine = new QLineEdit(this);\n buildLine->setReadOnly(true);\n buildLine->setDisabled(true);\n buildLine->setText(Project::defaultBuildDirectory(wizard_->projectFile()));\n fl->addRow(tr(\"Build directory:\"), buildLine);\n\n \/\/ TODO: indicate if we can find Boost.Build executable?\n\n QString const info(tr(\n \"This allows you to use Qt Creator as an IDE to edit and navigate C++ code, \"\n \"run %1 command, work through compilation issues, \"\n \"configure executable targets to run and debug.\")\n .arg(QLatin1String(Constants::BOOSTBUILD)));\n QLabel* infoLabel = new QLabel(this);\n infoLabel->setWordWrap(true);\n infoLabel->setText(info);\n fl->addRow(infoLabel);\n}\n\nQString PathsSelectionWizardPage::projectName() const\n{\n return nameLineEdit_->text();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace BoostBuildProjectManager\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: gconflayer.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-03-30 15:05:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards OOurce License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free OOftware; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free OOftware Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free OOftware\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards OOurce License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * OOurce License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * OOftware provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE OOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the OOftware.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef GCONFLAYER_HXX_\n#include \"gconflayer.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_PROPERTYINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERCONTENTDESCIBER_HPP_\n#include \n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif \/\/ _RTL_USTRBUF_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\/\/==============================================================================\n\nGconfLayer::GconfLayer(\n const rtl::OUString& sComponent,\n const KeyMappingTable& aKeyMap,\n const rtl::OUString& sTimestamp,\n const TSMappingTable& aTSMap,\n const uno::Reference& xFactory)\n : mComponent(sComponent), mKeyMap(aKeyMap),\n mTimestamp(sTimestamp), mTSMap(aTSMap),\n mFactory(xFactory)\n{\n\n}\n\/\/------------------------------------------------------------------------------\nvoid GconfLayer::convertGconfValue(\n const GConfValue* aValue,\n uno::Any* aOOValue,\n const rtl::OUString& aOOType)\n{\n sal_Bool bCorrectType = sal_True;\n switch (aValue->type)\n {\n case GCONF_VALUE_STRING:\n {\n if(aOOType != rtl::OUString::createFromAscii(\"string\"))\n {\n bCorrectType = sal_False;\n }\n else\n {\n rtl::OUString aVal(\n rtl::OUString::createFromAscii(gconf_value_get_string(aValue)));\n *aOOValue <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_INT:\n {\n if(aOOType != rtl::OUString::createFromAscii(\"int\") &&\n aOOType != rtl::OUString::createFromAscii(\"integer\"))\n {\n bCorrectType = sal_False;\n }\n else\n {\n sal_Int32 aVal = gconf_value_get_int(aValue);\n *aOOValue <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_FLOAT:\n {\n if(aOOType != rtl::OUString::createFromAscii(\"double\") )\n {\n bCorrectType = sal_False;\n }\n else\n {\n double aVal = gconf_value_get_float(aValue);\n *aOOValue <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_BOOL:\n {\n if(aOOType != rtl::OUString::createFromAscii(\"boolean\"))\n {\n bCorrectType = sal_False;\n }\n else\n {\n sal_Bool aVal = gconf_value_get_bool(aValue);\n *aOOValue <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_LIST:\n \/\/TODO\n break;\n case GCONF_VALUE_PAIR:\n \/\/TODO\n break;\n case GCONF_VALUE_INVALID:\n break;\n\n default:\n break;\n }\n if (!bCorrectType)\n throw backend::MalformedDataException(\n rtl::OUString::createFromAscii(\"Gconfbe:GconfLayer: GconfType does not match StarOffice Type\"),\n *this, uno::Any());\n\n\n}\n\/\/------------------------------------------------------------------------------\n\nvoid SAL_CALL GconfLayer::readData(\n const uno::Reference& xHandler)\n throw ( backend::MalformedDataException,\n lang::NullPointerException,\n lang::WrappedTargetException,\n uno::RuntimeException)\n{\n std::vector aPropList;\n \/\/Look up in map all keys asociated with requested OOffice Component\n \/\/and retrieve values from Gconf\n typedef KeyMappingTable::const_iterator BFIter;\n typedef std::pair BFRange;\n\n\n\n BFRange aRange = mKeyMap.equal_range(mComponent);\n GError* aError = NULL;\n GConfClient* aClient = NULL;\n if (aRange.first != mKeyMap.end())\n {\n aClient = GconfBackend::getGconfClient();\n }\n\n while (aRange.first != aRange.second)\n {\n BFIter cur = aRange.first++;\n\n \/\/Need to read data using Gconf api here\n\n GConfValue* aGconfValue = NULL;\n rtl::OString sKeyValue = rtl::OUStringToOString(cur->second.mGconfName, RTL_TEXTENCODING_ASCII_US);\n aGconfValue = gconf_client_get( aClient, sKeyValue.getStr(),&aError);\n\n if (aError == NULL)\n {\n\n \/\/Fill in the ProperyInfo Struct\n backend::PropertyInfo aPropInfo;\n\n aPropInfo.Name = cur->second.mOOName;\n aPropInfo.Type = cur->second.mOOType;\n aPropInfo.Protected = cur->second.mbProtected;\n convertGconfValue(aGconfValue, &aPropInfo.Value,aPropInfo.Type );\n\n\n aPropList.push_back(aPropInfo);\n gconf_value_free(aGconfValue);\n }\n else\n {\n rtl::OString aErrorStr(aError->message);\n \/\/Do nothing for now - real impl can decide whether to throw exception\n OSL_TRACE(\"GconfLayer cannot read data for Gconfkey:%s with message:%s\",\n sKeyValue.getStr(), aError->message);\n }\n\n }\n if ( !aPropList.empty())\n {\n\n uno::Sequence aPropInfoList(aPropList.size());\n for( sal_Int32 i = 0; i < aPropList.size(); i++)\n {\n aPropInfoList[i] = aPropList[i];\n }\n\n \/\/Create instance of LayerContentDescriber Service\n rtl::OUString const k_sLayerDescriberService (RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.comp.configuration.backend.LayerDescriber\"));\n\n typedef uno::Reference LayerDescriber;\n LayerDescriber xLayerDescriber = LayerDescriber::query(\n mFactory->createInstance(k_sLayerDescriberService));\n\n if (xLayerDescriber.is())\n {\n xLayerDescriber->describeLayer(xHandler, aPropInfoList);\n }\n else\n {\n OSL_TRACE(\"Could not create com.sun.star.configuration.backend.LayerContentDescriber Service\");\n }\n }\n\n}\n\/\/------------------------------------------------------------------------------\n\n rtl::OUString SAL_CALL GconfLayer::getTimestamp(void)\n throw (uno::RuntimeException)\n{\n TSMappingTable::const_iterator aTSIter;\n aTSIter = mTSMap.find(mComponent);\n if (aTSIter != mTSMap.end())\n {\n mTimestamp= aTSIter->second;\n }\n\n return mTimestamp;\n}\n\/\/------------------------------------------------------------------------------\nINTEGRATION: CWS syssettings02 (1.2.50); FILE MERGED 2004\/09\/03 07:13:32 obr 1.2.50.2: #i20364#,#i20369# removed debug output 2004\/09\/03 06:16:04 obr 1.2.50.1: #i20364#,#i20369# gconf platform configuration backend now buildable\/*************************************************************************\n *\n * $RCSfile: gconflayer.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-09-17 13:01:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards OOurce License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free OOftware; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free OOftware Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free OOftware\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards OOurce License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * OOurce License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * OOftware provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE OOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the OOftware.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef GCONFLAYER_HXX_\n#include \"gconflayer.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_PROPERTYINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERCONTENTDESCIBER_HPP_\n#include \n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif \/\/ _RTL_USTRBUF_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\n#include \n\n\/\/==============================================================================\n\nGconfLayer::GconfLayer(\n const rtl::OUString& aComponent,\n const rtl::OUString& aTimestamp,\n const uno::Reference& xContext)\n : m_aComponent(aComponent), m_aTimestamp(aTimestamp)\n{\n \/\/Create instance of LayerContentDescriber Service\n rtl::OUString const k_sLayerDescriberService(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.comp.configuration.backend.LayerDescriber\"));\n\n typedef uno::Reference LayerDescriber;\n uno::Reference< lang::XMultiComponentFactory > xServiceManager = xContext->getServiceManager();\n if( xServiceManager.is() )\n {\n m_xLayerContentDescriber = LayerDescriber::query(\n xServiceManager->createInstanceWithContext(k_sLayerDescriberService, xContext));\n }\n else\n {\n OSL_TRACE(\"Could not retrieve ServiceManager\");\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/*\nuno::Any GconfLayer::convertGconfValue(const GConfValue* aValue, const rtl::OUString& aOOType)\n{\n uno::Any aRetVal;\n\n sal_Bool bCorrectType = sal_True;\n switch (aValue->type)\n {\n case GCONF_VALUE_STRING:\n {\n if(aOOType != rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"string\")))\n {\n bCorrectType = sal_False;\n }\n else\n {\n rtl::OString aVal(gconf_value_get_string(aValue));\n aRetVal <<= OStringToOUString(aVal, RTL_TEXTENCODING_UTF-8);\n }\n break;\n }\n case GCONF_VALUE_INT:\n {\n if( aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"int\") ) &&\n aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"integer\") ) )\n {\n bCorrectType = sal_False;\n }\n else\n {\n sal_Int32 aVal = gconf_value_get_int(aValue);\n aRetVal <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_FLOAT:\n {\n if(aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"double\") ) )\n {\n bCorrectType = sal_False;\n }\n else\n {\n double aVal = gconf_value_get_float(aValue);\n aRetVal <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_BOOL:\n {\n if(aOOType != rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"boolean\") ) )\n {\n bCorrectType = sal_False;\n }\n else\n {\n sal_Bool aVal = gconf_value_get_bool(aValue);\n aRetVal <<= aVal;\n }\n break;\n }\n case GCONF_VALUE_LIST:\n \/\/TODO\n break;\n case GCONF_VALUE_PAIR:\n \/\/TODO\n break;\n case GCONF_VALUE_INVALID:\n break;\n\n default:\n break;\n }\n\n if (!bCorrectType)\n throw backend::MalformedDataException( rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"Gconfbe:GconfLayer: GconfType does not match StarOffice Type\")\n ), *this, uno::Any());\n\n\n}\n\n*\/\n\n\/\/------------------------------------------------------------------------------\n\nvoid SAL_CALL GconfLayer::readData( const uno::Reference& xHandler)\n throw ( backend::MalformedDataException, lang::NullPointerException,\n lang::WrappedTargetException, uno::RuntimeException)\n{\n\n if( m_xLayerContentDescriber.is() )\n {\n uno::Sequence aPropInfoList(5);\n sal_Int32 nProperties = 0;\n\n GError* aError;\n GConfClient* aClient = GconfBackend::getGconfClient();\n GConfValue* aGconfValue;\n\n if( m_aComponent.equalsAscii(\"org.openoffice.Inet\" ) )\n {\n aError = NULL;\n aGconfValue = gconf_client_get(aClient, \"\/system\/proxy\/mode\" , &aError);\n\n if( aError == NULL )\n {\n rtl::OString aMode(gconf_value_get_string(aGconfValue));\n\n if( aMode.equals(\"manual\") )\n {\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Inet\/Settings\/ooInetProxyType\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"int\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny( (sal_Int32) 1 );\n\n aError = NULL;\n aGconfValue = gconf_client_get(aClient, \"\/system\/http_proxy\/host\" , &aError);\n\n if( aError == NULL ) {\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Inet\/Settings\/ooInetHTTPProxyName\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"string\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny( OStringToOUString(\n rtl::OString( gconf_value_get_string(aGconfValue) ),\n RTL_TEXTENCODING_UTF8 ) );\n }\n\n aError = NULL;\n aGconfValue = gconf_client_get(aClient, \"\/system\/http_proxy\/port\" , &aError);\n\n if( aError == NULL ) {\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Inet\/Settings\/ooInetHTTPProxyPort\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"int\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny(\n (sal_Int32) gconf_value_get_int(aGconfValue) );\n }\n\n aError = NULL;\n aGconfValue = gconf_client_get(aClient, \"\/system\/proxy\/ftp_host\" , &aError);\n\n if( aError == NULL ) {\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Inet\/Settings\/ooInetFTPProxyName\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"string\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny( OStringToOUString(\n rtl::OString( gconf_value_get_string(aGconfValue) ),\n RTL_TEXTENCODING_UTF8 ) );\n }\n\n aError = NULL;\n aGconfValue = gconf_client_get(aClient, \"\/system\/proxy\/ftp_port\" , &aError);\n\n if( aError == NULL ) {\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Inet\/Settings\/ooInetFTPProxyPort\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"int\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny(\n (sal_Int32) gconf_value_get_int(aGconfValue) );\n }\n }\n else if( aMode.equals(\"none\") )\n {\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Inet\/Settings\/ooInetProxyType\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"int\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny( (sal_Int32) 0 );\n }\n }\n }\n else if( m_aComponent.equalsAscii(\"org.openoffice.Office.Common\" ) )\n {\n aError = NULL;\n aGconfValue = gconf_client_get(aClient, \"\/desktop\/gnome\/url-handlers\/mailto\/command\" , &aError);\n\n if( aError == NULL ) {\n sal_Int32 nIndex = 0;\n aPropInfoList[nProperties].Name = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"org.openoffice.Office.Common\/ExternalMailer\/Program\") );\n aPropInfoList[nProperties].Type = rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM( \"string\" ) );\n aPropInfoList[nProperties].Protected = sal_False;\n aPropInfoList[nProperties++].Value = uno::makeAny( OStringToOUString(\n rtl::OString( gconf_value_get_string(aGconfValue) ).getToken(0, ' ', nIndex),\n RTL_TEXTENCODING_UTF8 ) );\n }\n }\n\n aPropInfoList.realloc(nProperties);\n\n m_xLayerContentDescriber->describeLayer(xHandler, aPropInfoList);\n }\n else\n {\n OSL_TRACE(\"Could not create com.sun.star.configuration.backend.LayerContentDescriber Service\");\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\nrtl::OUString SAL_CALL GconfLayer::getTimestamp(void)\n throw (uno::RuntimeException)\n{\n return m_aTimestamp;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/gtk_theme_preview_infobar_delegate.h\"\n\n#include \"chrome\/browser\/profile.h\"\n\nGtkThemeInstalledInfoBarDelegate::GtkThemeInstalledInfoBarDelegate(\n TabContents* tab_contents,\n const std::string& name,\n const std::string& previous_theme,\n bool previous_use_gtk_theme)\n : ThemeInstalledInfoBarDelegate(tab_contents, name, previous_theme),\n previous_use_gtk_theme_(previous_use_gtk_theme) {\n}\n\nbool GtkThemeInstalledInfoBarDelegate::Cancel() {\n if (previous_use_gtk_theme_) {\n profile()->SetNativeTheme();\n return true;\n } else {\n return ThemeInstalledInfoBarDelegate::Cancel();\n }\n}\nwhee\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/gtk_theme_installed_infobar_delegate.h\"\n\n#include \"chrome\/browser\/profile.h\"\n\nGtkThemeInstalledInfoBarDelegate::GtkThemeInstalledInfoBarDelegate(\n TabContents* tab_contents,\n const std::string& name,\n const std::string& previous_theme,\n bool previous_use_gtk_theme)\n : ThemeInstalledInfoBarDelegate(tab_contents, name, previous_theme),\n previous_use_gtk_theme_(previous_use_gtk_theme) {\n}\n\nbool GtkThemeInstalledInfoBarDelegate::Cancel() {\n if (previous_use_gtk_theme_) {\n profile()->SetNativeTheme();\n return true;\n } else {\n return ThemeInstalledInfoBarDelegate::Cancel();\n }\n}\n<|endoftext|>"} {"text":"#ifndef GUARD_MLOPEN_GEMM_DRIVER_HPP\n#define GUARD_MLOPEN_GEMM_DRIVER_HPP\n\n#ifndef WIN32 \/\/ so Linux and APPLE\n#include \n#include \n#include \"driver.hpp\"\n#include \"InputFlags.hpp\"\n#include \n#include \n#include \n#include \n#include \n\ntemplate\nclass GemmDriver : public Driver \n{\n public:\n GemmDriver() : Driver() {}\n\n int AddCmdLineArgs();\n int ParseCmdLineArgs(int argc, char *argv[]);\n InputFlags & GetInputFlags() { return inflags; }\n\n int GetandSetData();\n std::vector GetInputTensorLengthsFromCmdLine();\n\n int AllocateBuffersAndCopy();\n\n int RunForwardGPU();\n\n int RunBackwardGPU();\n\n int VerifyBackward();\n int VerifyForward();\n ~GemmDriver() {}\n\n private:\n InputFlags inflags;\n\n std::unique_ptr a_dev;\n std::unique_ptr b_dev;\n std::unique_ptr c_dev;\n\n std::vector a;\n std::vector b;\n std::vector c;\n std::vector chost;\n\n int M, N, K; \/\/ Netlib BLAS dims, user inputs\n bool transA, transB;\n T alpha, beta;\n\n int lda, ldb;\n};\n\ntemplate\nint GemmDriver::AddCmdLineArgs() {\n inflags.AddInputFlag(\"forw\", 'F', \"1\", \"Run only Forward Gemm (Default=1)\", \"int\");\n inflags.AddInputFlag(\"batchsize\", 'b', \"1\", \"batch size for Gemm (Default=1)\", \"int\");\n inflags.AddInputFlag(\"a_h\", 'm', \"256\", \"Height of A matrix (Default=256)\", \"int\");\n inflags.AddInputFlag(\"a_w\", 'k', \"256\", \"Width of A matrix (Default=256)\", \"int\");\n inflags.AddInputFlag(\"b_w\", 'n', \"256\", \"Width of B matrix (Default=256)\", \"int\");\n inflags.AddInputFlag(\"alpha\", 'A', \"1.0\", \"Gemm alpha (Default=1.0)\", \"double\");\n inflags.AddInputFlag(\"beta\", 'B', \"0.0\", \"Gemm beta (Default=0.0)\", \"double\");\n inflags.AddInputFlag(\"transA\", 'u', \"0\", \"Transpose A matrix (Default=0)\", \"int\");\n inflags.AddInputFlag(\"transB\", 'v', \"0\", \"Transpose B matrix (Default=0)\", \"int\");\n inflags.AddInputFlag(\"iter\", 'i', \"10\", \"Number of Iterations (Default=10)\", \"int\");\n inflags.AddInputFlag(\"verify\", 'V', \"0\", \"Verify Each Layer (Default=1)\", \"int\");\n inflags.AddInputFlag(\"time\", 't', \"0\", \"Time Each Layer (Default=0)\", \"int\");\n\n return 0;\n}\n\ntemplate\nint GemmDriver::ParseCmdLineArgs(int argc, char *argv[]) {\n inflags.Parse(argc, argv); \n\n if(inflags.GetValueInt(\"time\") == 1) {\n mlopenEnableProfiling(GetHandle(), true);\n }\n return 0; \n}\n\ntemplate\nint GemmDriver::GetandSetData() {\n\n M = inflags.GetValueInt(\"a_h\");\n K = inflags.GetValueInt(\"a_w\");\n N = inflags.GetValueInt(\"b_w\");\n\n transA = inflags.GetValueInt(\"transA\");\n transB = inflags.GetValueInt(\"transB\");\n\n alpha = inflags.GetValueDouble(\"alpha\");\n beta = inflags.GetValueDouble(\"beta\");\n\n lda = transA == 0 ? K : M;\n ldb = transB == 0 ? N : K;\n\n return(0);\n}\n\ntemplate\nint GemmDriver::AllocateBuffersAndCopy() {\n\n size_t a_sz = M*K; \n size_t b_sz = K*N;\n size_t c_sz = M*N; \n\n cl_context ctx;\n\n clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);\n\n a_dev = std::unique_ptr( new GPUMem(ctx, a_sz, sizeof(T)));\n b_dev = std::unique_ptr( new GPUMem(ctx, b_sz, sizeof(T)));\n c_dev = std::unique_ptr( new GPUMem(ctx, c_sz, sizeof(T)));\n\n a = std::vector(a_sz);\n b = std::vector(b_sz);\n c = std::vector(c_sz, 0.);\n chost = std::vector(c_sz, 0.);\n\n for (int i = 0; i < a_sz; i++) {\n a[i] = (T)((double)rand() * (1.0 \/ RAND_MAX));\n }\n\n for (int i = 0; i ToGPU(q, a.data());\n status |= b_dev->ToGPU(q, b.data());\n status |= c_dev->ToGPU(q, c.data());\n\n if(status != CL_SUCCESS) \n printf(\"Error copying data to GPU\\n\");\n\n return mlopenStatusSuccess;\n}\n\ntemplate\nint GemmDriver::RunForwardGPU() {\n\n#if MLOPEN_USE_TINYGEMM\n mlopenGemm(GetHandle(),\n false, \/\/ isDataColMajor\n transA, transB,\n M, N, K,\n &alpha,\n a_dev->GetMem(), lda, \n b_dev->GetMem(), ldb,\n &beta,\n c_dev->GetMem(), N);\n\n if(inflags.GetValueInt(\"time\") == 1) {\n float time = 0.0;\n mlopenGetKernelTime(GetHandle(), &time);\n printf(\"GPU Kernel Time Gemm Elapsed: %f ms\\n\", time);\n }\n\n c_dev->FromGPU(GetStream(), c.data());\n#else \n std::cerr<<\"GEMM is not supported\\n\";\n#endif\n return mlopenStatusSuccess;\n}\n\ntemplate\nint GemmDriver::RunBackwardGPU() {\n return(0);\n}\n\ntemplate\nint GemmDriver::VerifyForward() {\n return 0;\n}\n\ntemplate\nint GemmDriver::VerifyBackward() {\n return 0;\n}\n\n#endif\n\n#endif \/\/ GUARD_MLOPEN_GEMM_DRIVER_HPP\nremoved #if#ifndef GUARD_MLOPEN_GEMM_DRIVER_HPP\n#define GUARD_MLOPEN_GEMM_DRIVER_HPP\n\n#include \n#include \n#include \"driver.hpp\"\n#include \"InputFlags.hpp\"\n#include \n#include \n#include \n#include \n#include \n\ntemplate\nclass GemmDriver : public Driver \n{\n public:\n GemmDriver() : Driver() {}\n\n int AddCmdLineArgs();\n int ParseCmdLineArgs(int argc, char *argv[]);\n InputFlags & GetInputFlags() { return inflags; }\n\n int GetandSetData();\n std::vector GetInputTensorLengthsFromCmdLine();\n\n int AllocateBuffersAndCopy();\n\n int RunForwardGPU();\n\n int RunBackwardGPU();\n\n int VerifyBackward();\n int VerifyForward();\n ~GemmDriver() {}\n\n private:\n InputFlags inflags;\n\n std::unique_ptr a_dev;\n std::unique_ptr b_dev;\n std::unique_ptr c_dev;\n\n std::vector a;\n std::vector b;\n std::vector c;\n std::vector chost;\n\n int M, N, K; \/\/ Netlib BLAS dims, user inputs\n bool transA, transB;\n T alpha, beta;\n\n int lda, ldb;\n};\n\ntemplate\nint GemmDriver::AddCmdLineArgs() {\n inflags.AddInputFlag(\"forw\", 'F', \"1\", \"Run only Forward Gemm (Default=1)\", \"int\");\n inflags.AddInputFlag(\"batchsize\", 'b', \"1\", \"batch size for Gemm (Default=1)\", \"int\");\n inflags.AddInputFlag(\"a_h\", 'm', \"256\", \"Height of A matrix (Default=256)\", \"int\");\n inflags.AddInputFlag(\"a_w\", 'k', \"256\", \"Width of A matrix (Default=256)\", \"int\");\n inflags.AddInputFlag(\"b_w\", 'n', \"256\", \"Width of B matrix (Default=256)\", \"int\");\n inflags.AddInputFlag(\"alpha\", 'A', \"1.0\", \"Gemm alpha (Default=1.0)\", \"double\");\n inflags.AddInputFlag(\"beta\", 'B', \"0.0\", \"Gemm beta (Default=0.0)\", \"double\");\n inflags.AddInputFlag(\"transA\", 'u', \"0\", \"Transpose A matrix (Default=0)\", \"int\");\n inflags.AddInputFlag(\"transB\", 'v', \"0\", \"Transpose B matrix (Default=0)\", \"int\");\n inflags.AddInputFlag(\"iter\", 'i', \"10\", \"Number of Iterations (Default=10)\", \"int\");\n inflags.AddInputFlag(\"verify\", 'V', \"0\", \"Verify Each Layer (Default=1)\", \"int\");\n inflags.AddInputFlag(\"time\", 't', \"0\", \"Time Each Layer (Default=0)\", \"int\");\n\n return 0;\n}\n\ntemplate\nint GemmDriver::ParseCmdLineArgs(int argc, char *argv[]) {\n inflags.Parse(argc, argv); \n\n if(inflags.GetValueInt(\"time\") == 1) {\n mlopenEnableProfiling(GetHandle(), true);\n }\n return 0; \n}\n\ntemplate\nint GemmDriver::GetandSetData() {\n\n M = inflags.GetValueInt(\"a_h\");\n K = inflags.GetValueInt(\"a_w\");\n N = inflags.GetValueInt(\"b_w\");\n\n transA = inflags.GetValueInt(\"transA\");\n transB = inflags.GetValueInt(\"transB\");\n\n alpha = inflags.GetValueDouble(\"alpha\");\n beta = inflags.GetValueDouble(\"beta\");\n\n lda = transA == 0 ? K : M;\n ldb = transB == 0 ? N : K;\n\n return(0);\n}\n\ntemplate\nint GemmDriver::AllocateBuffersAndCopy() {\n\n size_t a_sz = M*K; \n size_t b_sz = K*N;\n size_t c_sz = M*N; \n\n cl_context ctx;\n\n clGetCommandQueueInfo(q, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);\n\n a_dev = std::unique_ptr( new GPUMem(ctx, a_sz, sizeof(T)));\n b_dev = std::unique_ptr( new GPUMem(ctx, b_sz, sizeof(T)));\n c_dev = std::unique_ptr( new GPUMem(ctx, c_sz, sizeof(T)));\n\n a = std::vector(a_sz);\n b = std::vector(b_sz);\n c = std::vector(c_sz, 0.);\n chost = std::vector(c_sz, 0.);\n\n for (int i = 0; i < a_sz; i++) {\n a[i] = (T)((double)rand() * (1.0 \/ RAND_MAX));\n }\n\n for (int i = 0; i ToGPU(q, a.data());\n status |= b_dev->ToGPU(q, b.data());\n status |= c_dev->ToGPU(q, c.data());\n\n if(status != CL_SUCCESS) \n printf(\"Error copying data to GPU\\n\");\n\n return mlopenStatusSuccess;\n}\n\ntemplate\nint GemmDriver::RunForwardGPU() {\n\n#if MLOPEN_USE_TINYGEMM\n mlopenGemm(GetHandle(),\n false, \/\/ isDataColMajor\n transA, transB,\n M, N, K,\n &alpha,\n a_dev->GetMem(), lda, \n b_dev->GetMem(), ldb,\n &beta,\n c_dev->GetMem(), N);\n\n if(inflags.GetValueInt(\"time\") == 1) {\n float time = 0.0;\n mlopenGetKernelTime(GetHandle(), &time);\n printf(\"GPU Kernel Time Gemm Elapsed: %f ms\\n\", time);\n }\n\n c_dev->FromGPU(GetStream(), c.data());\n#else \n std::cerr<<\"GEMM is not supported\\n\";\n#endif\n return mlopenStatusSuccess;\n}\n\ntemplate\nint GemmDriver::RunBackwardGPU() {\n return(0);\n}\n\ntemplate\nint GemmDriver::VerifyForward() {\n return 0;\n}\n\ntemplate\nint GemmDriver::VerifyBackward() {\n return 0;\n}\n\n#endif \/\/ GUARD_MLOPEN_GEMM_DRIVER_HPP\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"scene_subdiv_mesh.h\"\n#include \"scene.h\"\n#include \"subdiv\/patch_eval.h\"\n#include \"subdiv\/patch_eval_simd.h\"\n\nnamespace embree\n{\n SubdivMeshAVX::SubdivMeshAVX(Scene* parent, RTCGeometryFlags flags, size_t numFaces, size_t numEdges, size_t numVertices, \n size_t numCreases, size_t numCorners, size_t numHoles, size_t numTimeSteps)\n : SubdivMesh(parent,flags,numFaces,numEdges,numVertices,numCreases,numCorners,numHoles,numTimeSteps) {}\n \n void SubdivMeshAVX::interpolate(unsigned primID, float u, float v, RTCBufferType buffer, float* P, float* dPdu, float* dPdv, size_t numFloats) \n {\n#if defined(DEBUG) \/\/ FIXME: use function pointers and also throw error in release mode\n if ((parent->aflags & RTC_INTERPOLATE) == 0) \n throw_RTCError(RTC_INVALID_OPERATION,\"rtcInterpolate can only get called when RTC_INTERPOLATE is enabled for the scene\");\n#endif\n\n \/* calculate base pointer and stride *\/\n assert((buffer >= RTC_VERTEX_BUFFER0 && buffer <= RTC_VERTEX_BUFFER1) ||\n (buffer >= RTC_USER_VERTEX_BUFFER0 && buffer <= RTC_USER_VERTEX_BUFFER1));\n const char* src = nullptr; \n size_t stride = 0;\n size_t bufID = buffer&0xFFFF;\n std::vector* baseEntry = nullptr;\n if (buffer >= RTC_USER_VERTEX_BUFFER0) {\n src = userbuffers[buffer&0xFFFF]->getPtr();\n stride = userbuffers[buffer&0xFFFF]->getStride();\n baseEntry = &user_buffer_tags[bufID];\n } else {\n src = vertices[buffer&0xFFFF].getPtr();\n stride = vertices[buffer&0xFFFF].getStride();\n baseEntry = &vertex_buffer_tags[bufID];\n }\n\n auto alloc = [](size_t bytes) { return SharedLazyTessellationCache::malloc(bytes); };\n \n for (size_t i=0,slot=0; i= numFloats)\n {\n vfloat4 Pt, dPdut, dPdvt; \n isa::PatchEval(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+i*sizeof(float),stride,u,v,P ? &Pt : nullptr, dPdu ? &dPdut : nullptr, dPdv ? &dPdvt : nullptr);\n\n if (P ) for (size_t j=i; j(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+i*sizeof(float),stride,u,v,P ? &Pt : nullptr, dPdu ? &dPdut : nullptr, dPdv ? &dPdvt : nullptr);\n \n if (P ) for (size_t j=i; j\n void SubdivMeshAVX::interpolateHelper(const vbool& valid1, const vint& primID, const vfloat& uu, const vfloat& vv, size_t numUVs, \n RTCBufferType buffer, float* P, float* dPdu, float* dPdv, size_t numFloats)\n {\n \/* calculate base pointer and stride *\/\n assert((buffer >= RTC_VERTEX_BUFFER0 && buffer <= RTC_VERTEX_BUFFER1) ||\n (buffer >= RTC_USER_VERTEX_BUFFER0 && buffer <= RTC_USER_VERTEX_BUFFER1));\n const char* src = nullptr; \n size_t stride = 0;\n size_t bufID = buffer&0xFFFF;\n std::vector* baseEntry = nullptr;\n if (buffer >= RTC_USER_VERTEX_BUFFER0) {\n src = userbuffers[bufID]->getPtr();\n stride = userbuffers[bufID]->getStride();\n baseEntry = &user_buffer_tags[bufID];\n } else {\n src = vertices[bufID].getPtr();\n stride = vertices[bufID].getStride();\n baseEntry = &vertex_buffer_tags[bufID];\n }\n\n foreach_unique(valid1,primID,[&](const vbool& valid1, const int primID) \n {\n for (size_t j=0,slot=0; j= numFloats)\n {\n const size_t M = min(size_t(4),numFloats-j);\n isa::PatchEvalSimd(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+j*sizeof(float),stride,valid1,uu,vv,\n P ? P+j*numUVs : nullptr,dPdu ? dPdu+j*numUVs : nullptr,dPdv ? dPdv+j*numUVs : nullptr,numUVs,M);\n j+=4;\n }\n else\n {\n const size_t M = min(size_t(8),numFloats-j);\n isa::PatchEvalSimd(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+j*sizeof(float),stride,valid1,uu,vv,\n P ? P+j*numUVs : nullptr,dPdu ? dPdu+j*numUVs : nullptr,dPdv ? dPdv+j*numUVs : nullptr,numUVs,M);\n j+=8;\n }\n }\n });\n }\n\n void SubdivMeshAVX::interpolateN(const void* valid_i, const unsigned* primIDs, const float* u, const float* v, size_t numUVs, \n RTCBufferType buffer, float* P, float* dPdu, float* dPdv, size_t numFloats)\n {\n#if defined(DEBUG) \/\/ FIXME: use function pointers and also throw error in release mode\n if ((parent->aflags & RTC_INTERPOLATE) == 0) \n throw_RTCError(RTC_INVALID_OPERATION,\"rtcInterpolate can only get called when RTC_INTERPOLATE is enabled for the scene\");\n#endif\n\n const int* valid = (const int*) valid_i;\n \n for (size_t i=0; i= numUVs)\n {\n vbool4 valid1 = vint4(i)+vint4(step) < vint4(numUVs);\n if (valid) valid1 &= vint4::loadu(&valid[i]) == vint4(-1);\n if (none(valid1)) continue;\n interpolateHelper(valid1,vint4::loadu(&primIDs[i]),vfloat4::loadu(&u[i]),vfloat4::loadu(&v[i]),numUVs,buffer, P ? P+i : nullptr, dPdu ? dPdu+i : nullptr, dPdv ? dPdv+i : nullptr,numFloats);\n i+=4;\n }\n else\n {\n vbool8 valid1 = vint8(i)+vint8(step) < vint8(numUVs);\n if (valid) valid1 &= vint8::loadu(&valid[i]) == vint8(-1);\n if (none(valid1)) continue;\n interpolateHelper(valid1,vint8::loadu(&primIDs[i]),vfloat8::loadu(&u[i]),vfloat8::loadu(&v[i]),numUVs,buffer, P ? P+i : nullptr, dPdu ? dPdu+i : nullptr, dPdv ? dPdv+i : nullptr,numFloats);\n i+=8;\n }\n }\n AVX_ZERO_UPPER();\n }\n}\nremoved fixme in scene_subdiv_mesh_avx.cpp\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"scene_subdiv_mesh.h\"\n#include \"scene.h\"\n#include \"subdiv\/patch_eval.h\"\n#include \"subdiv\/patch_eval_simd.h\"\n\nnamespace embree\n{\n SubdivMeshAVX::SubdivMeshAVX(Scene* parent, RTCGeometryFlags flags, size_t numFaces, size_t numEdges, size_t numVertices, \n size_t numCreases, size_t numCorners, size_t numHoles, size_t numTimeSteps)\n : SubdivMesh(parent,flags,numFaces,numEdges,numVertices,numCreases,numCorners,numHoles,numTimeSteps) {}\n \n void SubdivMeshAVX::interpolate(unsigned primID, float u, float v, RTCBufferType buffer, float* P, float* dPdu, float* dPdv, size_t numFloats) \n {\n#if defined(DEBUG)\n if ((parent->aflags & RTC_INTERPOLATE) == 0) \n throw_RTCError(RTC_INVALID_OPERATION,\"rtcInterpolate can only get called when RTC_INTERPOLATE is enabled for the scene\");\n#endif\n\n \/* calculate base pointer and stride *\/\n assert((buffer >= RTC_VERTEX_BUFFER0 && buffer <= RTC_VERTEX_BUFFER1) ||\n (buffer >= RTC_USER_VERTEX_BUFFER0 && buffer <= RTC_USER_VERTEX_BUFFER1));\n const char* src = nullptr; \n size_t stride = 0;\n size_t bufID = buffer&0xFFFF;\n std::vector* baseEntry = nullptr;\n if (buffer >= RTC_USER_VERTEX_BUFFER0) {\n src = userbuffers[buffer&0xFFFF]->getPtr();\n stride = userbuffers[buffer&0xFFFF]->getStride();\n baseEntry = &user_buffer_tags[bufID];\n } else {\n src = vertices[buffer&0xFFFF].getPtr();\n stride = vertices[buffer&0xFFFF].getStride();\n baseEntry = &vertex_buffer_tags[bufID];\n }\n\n auto alloc = [](size_t bytes) { return SharedLazyTessellationCache::malloc(bytes); };\n \n for (size_t i=0,slot=0; i= numFloats)\n {\n vfloat4 Pt, dPdut, dPdvt; \n isa::PatchEval(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+i*sizeof(float),stride,u,v,P ? &Pt : nullptr, dPdu ? &dPdut : nullptr, dPdv ? &dPdvt : nullptr);\n\n if (P ) for (size_t j=i; j(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+i*sizeof(float),stride,u,v,P ? &Pt : nullptr, dPdu ? &dPdut : nullptr, dPdv ? &dPdvt : nullptr);\n \n if (P ) for (size_t j=i; j\n void SubdivMeshAVX::interpolateHelper(const vbool& valid1, const vint& primID, const vfloat& uu, const vfloat& vv, size_t numUVs, \n RTCBufferType buffer, float* P, float* dPdu, float* dPdv, size_t numFloats)\n {\n \/* calculate base pointer and stride *\/\n assert((buffer >= RTC_VERTEX_BUFFER0 && buffer <= RTC_VERTEX_BUFFER1) ||\n (buffer >= RTC_USER_VERTEX_BUFFER0 && buffer <= RTC_USER_VERTEX_BUFFER1));\n const char* src = nullptr; \n size_t stride = 0;\n size_t bufID = buffer&0xFFFF;\n std::vector* baseEntry = nullptr;\n if (buffer >= RTC_USER_VERTEX_BUFFER0) {\n src = userbuffers[bufID]->getPtr();\n stride = userbuffers[bufID]->getStride();\n baseEntry = &user_buffer_tags[bufID];\n } else {\n src = vertices[bufID].getPtr();\n stride = vertices[bufID].getStride();\n baseEntry = &vertex_buffer_tags[bufID];\n }\n\n foreach_unique(valid1,primID,[&](const vbool& valid1, const int primID) \n {\n for (size_t j=0,slot=0; j= numFloats)\n {\n const size_t M = min(size_t(4),numFloats-j);\n isa::PatchEvalSimd(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+j*sizeof(float),stride,valid1,uu,vv,\n P ? P+j*numUVs : nullptr,dPdu ? dPdu+j*numUVs : nullptr,dPdv ? dPdv+j*numUVs : nullptr,numUVs,M);\n j+=4;\n }\n else\n {\n const size_t M = min(size_t(8),numFloats-j);\n isa::PatchEvalSimd(baseEntry->at(interpolationSlot(primID,slot,stride)),parent->commitCounterSubdiv,\n getHalfEdge(primID),src+j*sizeof(float),stride,valid1,uu,vv,\n P ? P+j*numUVs : nullptr,dPdu ? dPdu+j*numUVs : nullptr,dPdv ? dPdv+j*numUVs : nullptr,numUVs,M);\n j+=8;\n }\n }\n });\n }\n\n void SubdivMeshAVX::interpolateN(const void* valid_i, const unsigned* primIDs, const float* u, const float* v, size_t numUVs, \n RTCBufferType buffer, float* P, float* dPdu, float* dPdv, size_t numFloats)\n {\n#if defined(DEBUG)\n if ((parent->aflags & RTC_INTERPOLATE) == 0) \n throw_RTCError(RTC_INVALID_OPERATION,\"rtcInterpolate can only get called when RTC_INTERPOLATE is enabled for the scene\");\n#endif\n\n const int* valid = (const int*) valid_i;\n \n for (size_t i=0; i= numUVs)\n {\n vbool4 valid1 = vint4(i)+vint4(step) < vint4(numUVs);\n if (valid) valid1 &= vint4::loadu(&valid[i]) == vint4(-1);\n if (none(valid1)) continue;\n interpolateHelper(valid1,vint4::loadu(&primIDs[i]),vfloat4::loadu(&u[i]),vfloat4::loadu(&v[i]),numUVs,buffer, P ? P+i : nullptr, dPdu ? dPdu+i : nullptr, dPdv ? dPdv+i : nullptr,numFloats);\n i+=4;\n }\n else\n {\n vbool8 valid1 = vint8(i)+vint8(step) < vint8(numUVs);\n if (valid) valid1 &= vint8::loadu(&valid[i]) == vint8(-1);\n if (none(valid1)) continue;\n interpolateHelper(valid1,vint8::loadu(&primIDs[i]),vfloat8::loadu(&u[i]),vfloat8::loadu(&v[i]),numUVs,buffer, P ? P+i : nullptr, dPdu ? dPdu+i : nullptr, dPdv ? dPdv+i : nullptr,numFloats);\n i+=8;\n }\n }\n AVX_ZERO_UPPER();\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/chrome_paths.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nnamespace chrome {\n\nbool GetGearsPluginPathFromCommandLine(FilePath* path) {\n#ifndef NDEBUG\n \/\/ for debugging, support a cmd line based override\n std::wstring plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValue(\n switches::kGearsPluginPathOverride);\n \/\/ TODO(tc): After GetSwitchNativeValue lands, we don't need to use\n \/\/ FromWStringHack.\n *path = FilePath::FromWStringHack(plugin_path);\n return !plugin_path.empty();\n#else\n return false;\n#endif\n}\n\nbool PathProvider(int key, FilePath* result) {\n \/\/ Some keys are just aliases...\n switch (key) {\n case chrome::DIR_APP:\n return PathService::Get(base::DIR_MODULE, result);\n case chrome::DIR_LOGS:\n#ifndef NDEBUG\n return PathService::Get(chrome::DIR_USER_DATA, result);\n#else\n return PathService::Get(base::DIR_EXE, result);\n#endif\n case chrome::FILE_RESOURCE_MODULE:\n return PathService::Get(base::FILE_MODULE, result);\n }\n\n \/\/ Assume that we will not need to create the directory if it does not exist.\n \/\/ This flag can be set to true for the cases where we want to create it.\n bool create_dir = false;\n\n FilePath cur;\n switch (key) {\n case chrome::DIR_USER_DATA:\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_USER_DOCUMENTS:\n if (!GetUserDocumentsDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_DEFAULT_DOWNLOADS:\n if (!GetUserDownloadsDirectory(&cur))\n return false;\n break;\n case chrome::DIR_CRASH_DUMPS:\n \/\/ The crash reports are always stored relative to the default user data\n \/\/ directory. This avoids the problem of having to re-initialize the\n \/\/ exception handler after parsing command line options, which may\n \/\/ override the location of the app's profile directory.\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"Crash Reports\"));\n create_dir = true;\n break;\n case chrome::DIR_USER_DESKTOP:\n if (!GetUserDesktop(&cur))\n return false;\n break;\n case chrome::DIR_RESOURCES:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"resources\"));\n create_dir = true;\n break;\n case chrome::DIR_INSPECTOR:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"resources\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"inspector\"));\n break;\n case chrome::DIR_THEMES:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"themes\"));\n create_dir = true;\n break;\n case chrome::DIR_LOCALES:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n#if defined(OS_MACOSX)\n \/\/ On Mac, locale files are in Contents\/Resources, a sibling of the\n \/\/ App dir.\n cur = cur.DirName();\n cur = cur.Append(FILE_PATH_LITERAL(\"Resources\"));\n#else\n cur = cur.Append(FILE_PATH_LITERAL(\"locales\"));\n#endif\n create_dir = true;\n break;\n case chrome::DIR_APP_DICTIONARIES:\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"Dictionaries\"));\n create_dir = true;\n break;\n case chrome::FILE_LOCAL_STATE:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(chrome::kLocalStateFilename);\n break;\n case chrome::FILE_RECORDED_SCRIPT:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"script.log\"));\n break;\n case chrome::FILE_GEARS_PLUGIN:\n if (!GetGearsPluginPathFromCommandLine(&cur)) {\n#if defined(OS_WIN)\n \/\/ Search for gears.dll alongside chrome.dll first. This new model\n \/\/ allows us to package gears.dll with the Chrome installer and update\n \/\/ it while Chrome is running.\n if (!PathService::Get(base::DIR_MODULE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n\n if (!file_util::PathExists(cur)) {\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"plugins\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n }\n#else\n \/\/ No gears.dll on non-Windows systems.\n return false;\n#endif\n }\n break;\n \/\/ The following are only valid in the development environment, and\n \/\/ will fail if executed from an installed executable (because the\n \/\/ generated path won't exist).\n case chrome::DIR_TEST_DATA:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"data\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::DIR_TEST_TOOLS:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"tools\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::FILE_PYTHON_RUNTIME:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"third_party\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"python_24\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"python.exe\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::FILE_TEST_SERVER:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"net\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"tools\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"testserver\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"testserver.py\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n default:\n return false;\n }\n\n if (create_dir && !file_util::PathExists(cur) &&\n !file_util::CreateDirectory(cur))\n return false;\n\n *result = cur;\n return true;\n}\n\n\/\/ This cannot be done as a static initializer sadly since Visual Studio will\n\/\/ eliminate this object file if there is no direct entry point into it.\nvoid RegisterPathProvider() {\n PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);\n}\n\n} \/\/ namespace chrome\nlinux: keep dictionaries in the user data dir.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/chrome_paths.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nnamespace chrome {\n\nbool GetGearsPluginPathFromCommandLine(FilePath* path) {\n#ifndef NDEBUG\n \/\/ for debugging, support a cmd line based override\n std::wstring plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValue(\n switches::kGearsPluginPathOverride);\n \/\/ TODO(tc): After GetSwitchNativeValue lands, we don't need to use\n \/\/ FromWStringHack.\n *path = FilePath::FromWStringHack(plugin_path);\n return !plugin_path.empty();\n#else\n return false;\n#endif\n}\n\nbool PathProvider(int key, FilePath* result) {\n \/\/ Some keys are just aliases...\n switch (key) {\n case chrome::DIR_APP:\n return PathService::Get(base::DIR_MODULE, result);\n case chrome::DIR_LOGS:\n#ifndef NDEBUG\n return PathService::Get(chrome::DIR_USER_DATA, result);\n#else\n return PathService::Get(base::DIR_EXE, result);\n#endif\n case chrome::FILE_RESOURCE_MODULE:\n return PathService::Get(base::FILE_MODULE, result);\n }\n\n \/\/ Assume that we will not need to create the directory if it does not exist.\n \/\/ This flag can be set to true for the cases where we want to create it.\n bool create_dir = false;\n\n FilePath cur;\n switch (key) {\n case chrome::DIR_USER_DATA:\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_USER_DOCUMENTS:\n if (!GetUserDocumentsDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_DEFAULT_DOWNLOADS:\n if (!GetUserDownloadsDirectory(&cur))\n return false;\n break;\n case chrome::DIR_CRASH_DUMPS:\n \/\/ The crash reports are always stored relative to the default user data\n \/\/ directory. This avoids the problem of having to re-initialize the\n \/\/ exception handler after parsing command line options, which may\n \/\/ override the location of the app's profile directory.\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"Crash Reports\"));\n create_dir = true;\n break;\n case chrome::DIR_USER_DESKTOP:\n if (!GetUserDesktop(&cur))\n return false;\n break;\n case chrome::DIR_RESOURCES:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"resources\"));\n create_dir = true;\n break;\n case chrome::DIR_INSPECTOR:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"resources\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"inspector\"));\n break;\n case chrome::DIR_THEMES:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"themes\"));\n create_dir = true;\n break;\n case chrome::DIR_LOCALES:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n#if defined(OS_MACOSX)\n \/\/ On Mac, locale files are in Contents\/Resources, a sibling of the\n \/\/ App dir.\n cur = cur.DirName();\n cur = cur.Append(FILE_PATH_LITERAL(\"Resources\"));\n#else\n cur = cur.Append(FILE_PATH_LITERAL(\"locales\"));\n#endif\n create_dir = true;\n break;\n case chrome::DIR_APP_DICTIONARIES:\n#if defined(OS_LINUX)\n \/\/ We can't write into the EXE dir on Linux, so keep dictionaries\n \/\/ alongside the safe browsing database in the user data dir.\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n#else\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n#endif\n cur = cur.Append(FILE_PATH_LITERAL(\"Dictionaries\"));\n create_dir = true;\n break;\n case chrome::FILE_LOCAL_STATE:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(chrome::kLocalStateFilename);\n break;\n case chrome::FILE_RECORDED_SCRIPT:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"script.log\"));\n break;\n case chrome::FILE_GEARS_PLUGIN:\n if (!GetGearsPluginPathFromCommandLine(&cur)) {\n#if defined(OS_WIN)\n \/\/ Search for gears.dll alongside chrome.dll first. This new model\n \/\/ allows us to package gears.dll with the Chrome installer and update\n \/\/ it while Chrome is running.\n if (!PathService::Get(base::DIR_MODULE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n\n if (!file_util::PathExists(cur)) {\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"plugins\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n }\n#else\n \/\/ No gears.dll on non-Windows systems.\n return false;\n#endif\n }\n break;\n \/\/ The following are only valid in the development environment, and\n \/\/ will fail if executed from an installed executable (because the\n \/\/ generated path won't exist).\n case chrome::DIR_TEST_DATA:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"data\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::DIR_TEST_TOOLS:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"tools\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::FILE_PYTHON_RUNTIME:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"third_party\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"python_24\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"python.exe\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::FILE_TEST_SERVER:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"net\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"tools\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"testserver\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"testserver.py\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n default:\n return false;\n }\n\n if (create_dir && !file_util::PathExists(cur) &&\n !file_util::CreateDirectory(cur))\n return false;\n\n *result = cur;\n return true;\n}\n\n\/\/ This cannot be done as a static initializer sadly since Visual Studio will\n\/\/ eliminate this object file if there is no direct entry point into it.\nvoid RegisterPathProvider() {\n PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);\n}\n\n} \/\/ namespace chrome\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/plugin_group.h\"\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\n#if defined(OS_MACOSX)\n\/\/ Plugin Groups for Mac.\n\/\/ Plugins are listed here as soon as vulnerabilities and solutions\n\/\/ (new versions) are published.\n\/\/ TODO(panayiotis): Track Java as soon as it's supported on Chrome Mac.\n\/\/ TODO(panayiotis): Get the Real Player version on Mac, somehow.\nstatic const PluginGroupDefinition kGroupDefinitions[] = {\n { \"Quicktime\", \"QuickTime Plug-in\", \"\", \"\", \"7.6.6\",\n \"http:\/\/www.apple.com\/quicktime\/download\/\" },\n { \"Flash\", \"Shockwave Flash\", \"\", \"\", \"10.1.53\",\n \"http:\/\/get.adobe.com\/flashplayer\/\" },\n { \"Silverlight 3\", \"Silverlight\", \"0\", \"4\", \"3.0.50106.0\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Silverlight 4\", \"Silverlight\", \"4\", \"5\", \"\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Flip4Mac\", \"Flip4Mac\", \"\", \"\", \"2.2.1\",\n \"http:\/\/www.telestream.net\/flip4mac-wmv\/overview.htm\" },\n { \"Shockwave\", \"Shockwave for Director\", \"\", \"\", \"11.5.7.609\",\n \"http:\/\/www.adobe.com\/shockwave\/download\/\" }\n};\n\n#elif defined(OS_WIN)\n\/\/ TODO(panayiotis): We should group \"RealJukebox NS Plugin\" with the rest of\n\/\/ the RealPlayer files.\nstatic const PluginGroupDefinition kGroupDefinitions[] = {\n { \"Quicktime\", \"QuickTime Plug-in\", \"\", \"\", \"7.6.6\",\n \"http:\/\/www.apple.com\/quicktime\/download\/\" },\n { \"Java 6\", \"Java\", \"\", \"6\", \"6.0.200\",\n \"http:\/\/www.java.com\/\" },\n { \"Adobe Reader 9\", \"Adobe Acrobat\", \"9\", \"10\", \"9.3.3\",\n \"http:\/\/get.adobe.com\/reader\/\" },\n { \"Adobe Reader 8\", \"Adobe Acrobat\", \"0\", \"9\", \"8.2.3\",\n \"http:\/\/get.adobe.com\/reader\/\" },\n { \"Flash\", \"Shockwave Flash\", \"\", \"\", \"10.1.53\",\n \"http:\/\/get.adobe.com\/flashplayer\/\" },\n { \"Silverlight 3\", \"Silverlight\", \"0\", \"4\", \"3.0.50106.0\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Silverlight 4\", \"Silverlight\", \"4\", \"5\", \"\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Shockwave\", \"Shockwave for Director\", \"\", \"\", \"11.5.7.609\",\n \"http:\/\/www.adobe.com\/shockwave\/download\/\" },\n { \"DivX Player\", \"DivX Web Player\", \"\", \"\", \"1.4.3.4\",\n \"http:\/\/download.divx.com\/divx\/autoupdate\/player\/DivXWebPlayerInstaller.exe\" },\n \/\/ These are here for grouping, no vulnerabilies known.\n { \"Windows Media Player\", \"Windows Media Player\", \"\", \"\", \"\", \"\" },\n { \"Microsoft Office\", \"Microsoft Office\", \"\", \"\", \"\", \"\" },\n \/\/ TODO(panayiotis): The vulnerable versions are\n \/\/ (v >= 6.0.12.1040 && v <= 6.0.12.1663)\n \/\/ || v == 6.0.12.1698 || v == 6.0.12.1741\n { \"RealPlayer\", \"RealPlayer\", \"\", \"\", \"\",\n \"http:\/\/www.adobe.com\/shockwave\/download\/\" },\n};\n\n#else\nstatic const PluginGroupDefinition kGroupDefinitions[] = {};\n#endif\n\n\/*static*\/\nstd::set* PluginGroup::policy_disabled_puglins_;\n\n\/*static*\/\nconst PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() {\n return kGroupDefinitions;\n}\n\n\/*static*\/\nsize_t PluginGroup::GetPluginGroupDefinitionsSize() {\n \/\/ TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays.\n return ARRAYSIZE_UNSAFE(kGroupDefinitions);\n}\n\n\/*static*\/\nvoid PluginGroup::SetPolicyDisabledPluginSet(const std::set& set) {\n if (!policy_disabled_puglins_) {\n policy_disabled_puglins_ = new std::set();\n *policy_disabled_puglins_ = set;\n }\n}\n\n\/*static*\/\nbool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) {\n return policy_disabled_puglins_ &&\n policy_disabled_puglins_->find(plugin_name) !=\n policy_disabled_puglins_->end();\n}\n\n\/*static*\/\nbool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) {\n std::vector plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);\n for (std::vector::const_iterator it = plugins.begin();\n it != plugins.end();\n ++it) {\n if (FilePath::CompareEqualIgnoreCase(it->path.value(),\n plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) {\n return true;\n }\n }\n return false;\n}\n\nPluginGroup::PluginGroup(const string16& group_name,\n const string16& name_matcher,\n const std::string& version_range_low,\n const std::string& version_range_high,\n const std::string& min_version,\n const std::string& update_url) {\n group_name_ = group_name;\n name_matcher_ = name_matcher;\n version_range_low_str_ = version_range_low;\n if (!version_range_low.empty()) {\n version_range_low_.reset(\n Version::GetVersionFromString(version_range_low));\n }\n version_range_high_str_ = version_range_high;\n if (!version_range_high.empty()) {\n version_range_high_.reset(\n Version::GetVersionFromString(version_range_high));\n }\n min_version_str_ = min_version;\n if (!min_version.empty()) {\n min_version_.reset(Version::GetVersionFromString(min_version));\n }\n update_url_ = update_url;\n enabled_ = false;\n max_version_.reset(Version::GetVersionFromString(\"0\"));\n}\n\nPluginGroup* PluginGroup::FromPluginGroupDefinition(\n const PluginGroupDefinition& definition) {\n return new PluginGroup(ASCIIToUTF16(definition.name),\n ASCIIToUTF16(definition.name_matcher),\n definition.version_matcher_low,\n definition.version_matcher_high,\n definition.min_version,\n definition.update_url);\n}\n\nPluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) {\n \/\/ Create a matcher from the name of this plugin.\n return new PluginGroup(wpi.name, wpi.name,\n \"\", \"\", \"\", \"\");\n}\n\nPluginGroup* PluginGroup::FindHardcodedPluginGroup(const WebPluginInfo& info) {\n static std::vector >* hardcoded_plugin_groups = NULL;\n if (!hardcoded_plugin_groups) {\n std::vector >* groups =\n new std::vector >();\n const PluginGroupDefinition* definitions = GetPluginGroupDefinitions();\n for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) {\n PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition(\n definitions[i]);\n groups->push_back(linked_ptr(definition_group));\n }\n hardcoded_plugin_groups = groups;\n }\n\n \/\/ See if this plugin matches any of the hardcoded groups.\n PluginGroup* hardcoded_group = FindGroupMatchingPlugin(\n *hardcoded_plugin_groups, info);\n if (hardcoded_group) {\n \/\/ Make a copy.\n return hardcoded_group->Copy();\n } else {\n \/\/ Not found in our hardcoded list, create a new one.\n return PluginGroup::FromWebPluginInfo(info);\n }\n}\n\nPluginGroup* PluginGroup::FindGroupMatchingPlugin(\n std::vector >& plugin_groups,\n const WebPluginInfo& plugin) {\n for (std::vector >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n if ((*it)->Match(plugin)) {\n return it->get();\n }\n }\n return NULL;\n}\n\nbool PluginGroup::Match(const WebPluginInfo& plugin) const {\n if (name_matcher_.empty()) {\n return false;\n }\n\n \/\/ Look for the name matcher anywhere in the plugin name.\n if (plugin.name.find(name_matcher_) == string16::npos) {\n return false;\n }\n\n if (version_range_low_.get() == NULL ||\n version_range_high_.get() == NULL) {\n return true;\n }\n\n \/\/ There's a version range, we must be in it.\n scoped_ptr plugin_version(\n Version::GetVersionFromString(UTF16ToWide(plugin.version)));\n if (plugin_version.get() == NULL) {\n \/\/ No version could be extracted, assume we don't match the range.\n return false;\n }\n\n \/\/ We match if we are in the range: [low, high)\n return (version_range_low_->CompareTo(*plugin_version) <= 0 &&\n version_range_high_->CompareTo(*plugin_version) > 0);\n}\n\nvoid PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) {\n web_plugin_infos_.push_back(plugin);\n \/\/ The position of this plugin relative to the global list of plugins.\n web_plugin_positions_.push_back(position);\n description_ = plugin.desc;\n\n \/\/ A group is enabled if any of the files are enabled.\n if (plugin.enabled) {\n enabled_ = true;\n }\n\n \/\/ update max_version_. Remove spaces and ')' from the version string,\n \/\/ Replace any instances of 'r', ',' or '(' with a dot.\n std::wstring version = UTF16ToWide(plugin.version);\n RemoveChars(version, L\") \", &version);\n std::replace(version.begin(), version.end(), 'r', '.');\n std::replace(version.begin(), version.end(), ',', '.');\n std::replace(version.begin(), version.end(), '(', '.');\n\n scoped_ptr plugin_version(\n Version::GetVersionFromString(version));\n if (plugin_version.get() != NULL) {\n if (plugin_version->CompareTo(*(max_version_)) > 0) {\n max_version_.reset(plugin_version.release());\n }\n }\n}\n\nDictionaryValue* PluginGroup::GetSummary() const {\n DictionaryValue* result = new DictionaryValue();\n result->SetString(\"name\", group_name_);\n result->SetBoolean(\"enabled\", enabled_);\n return result;\n}\n\nDictionaryValue* PluginGroup::GetDataForUI() const {\n DictionaryValue* result = new DictionaryValue();\n result->SetString(\"name\", group_name_);\n result->SetString(\"description\", description_);\n result->SetString(\"version\", max_version_->GetString());\n result->SetString(\"update_url\", update_url_);\n result->SetBoolean(\"critical\", IsVulnerable());\n\n bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(group_name_);\n if (group_disabled_by_policy) {\n result->SetString(\"enabledMode\", \"disabledByPolicy\");\n } else {\n result->SetString(\"enabledMode\", enabled_ ? \"enabled\" : \"disabledByUser\");\n }\n\n ListValue* plugin_files = new ListValue();\n for (size_t i = 0; i < web_plugin_infos_.size(); ++i) {\n const WebPluginInfo& web_plugin = web_plugin_infos_[i];\n int priority = web_plugin_positions_[i];\n DictionaryValue* plugin_file = new DictionaryValue();\n plugin_file->SetString(\"name\", web_plugin.name);\n plugin_file->SetString(\"description\", web_plugin.desc);\n plugin_file->SetString(\"path\", web_plugin.path.value());\n plugin_file->SetString(\"version\", web_plugin.version);\n bool plugin_disabled_by_policy = group_disabled_by_policy ||\n IsPluginNameDisabledByPolicy(web_plugin.name);\n if (plugin_disabled_by_policy) {\n result->SetString(\"enabledMode\", \"disabledByPolicy\");\n } else {\n result->SetString(\"enabledMode\",\n web_plugin.enabled ? \"enabled\" : \"disabledByUser\");\n }\n plugin_file->SetInteger(\"priority\", priority);\n\n ListValue* mime_types = new ListValue();\n for (std::vector::const_iterator type_it =\n web_plugin.mime_types.begin();\n type_it != web_plugin.mime_types.end();\n ++type_it) {\n DictionaryValue* mime_type = new DictionaryValue();\n mime_type->SetString(\"mimeType\", type_it->mime_type);\n mime_type->SetString(\"description\", type_it->description);\n\n ListValue* file_extensions = new ListValue();\n for (std::vector::const_iterator ext_it =\n type_it->file_extensions.begin();\n ext_it != type_it->file_extensions.end();\n ++ext_it) {\n file_extensions->Append(new StringValue(*ext_it));\n }\n mime_type->Set(\"fileExtensions\", file_extensions);\n\n mime_types->Append(mime_type);\n }\n plugin_file->Set(\"mimeTypes\", mime_types);\n\n plugin_files->Append(plugin_file);\n }\n result->Set(\"plugin_files\", plugin_files);\n\n return result;\n}\n\n\/\/ Returns true if the latest version of this plugin group is vulnerable.\nbool PluginGroup::IsVulnerable() const {\n if (min_version_.get() == NULL || max_version_->GetString() == \"0\") {\n return false;\n }\n return max_version_->CompareTo(*min_version_) < 0;\n}\n\nvoid PluginGroup::Enable(bool enable) {\n for (std::vector::const_iterator it =\n web_plugin_infos_.begin();\n it != web_plugin_infos_.end(); ++it) {\n if (enable && !IsPluginNameDisabledByPolicy(it->name)) {\n NPAPI::PluginList::Singleton()->EnablePlugin(FilePath(it->path));\n } else {\n NPAPI::PluginList::Singleton()->DisablePlugin(FilePath(it->path));\n }\n }\n}\n\nAdd Java plugin group on Mac.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/plugin_group.h\"\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\n#if defined(OS_MACOSX)\n\/\/ Plugin Groups for Mac.\n\/\/ Plugins are listed here as soon as vulnerabilities and solutions\n\/\/ (new versions) are published.\n\/\/ TODO(panayiotis): Get the Real Player version on Mac, somehow.\nstatic const PluginGroupDefinition kGroupDefinitions[] = {\n { \"Quicktime\", \"QuickTime Plug-in\", \"\", \"\", \"7.6.6\",\n \"http:\/\/www.apple.com\/quicktime\/download\/\" },\n { \"Java\", \"Java\", \"\", \"\", \"\",\n \"http:\/\/support.apple.com\/kb\/HT1338\" },\n { \"Flash\", \"Shockwave Flash\", \"\", \"\", \"10.1.53\",\n \"http:\/\/get.adobe.com\/flashplayer\/\" },\n { \"Silverlight 3\", \"Silverlight\", \"0\", \"4\", \"3.0.50106.0\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Silverlight 4\", \"Silverlight\", \"4\", \"5\", \"\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Flip4Mac\", \"Flip4Mac\", \"\", \"\", \"2.2.1\",\n \"http:\/\/www.telestream.net\/flip4mac-wmv\/overview.htm\" },\n { \"Shockwave\", \"Shockwave for Director\", \"\", \"\", \"11.5.7.609\",\n \"http:\/\/www.adobe.com\/shockwave\/download\/\" }\n};\n\n#elif defined(OS_WIN)\n\/\/ TODO(panayiotis): We should group \"RealJukebox NS Plugin\" with the rest of\n\/\/ the RealPlayer files.\nstatic const PluginGroupDefinition kGroupDefinitions[] = {\n { \"Quicktime\", \"QuickTime Plug-in\", \"\", \"\", \"7.6.6\",\n \"http:\/\/www.apple.com\/quicktime\/download\/\" },\n { \"Java 6\", \"Java\", \"\", \"6\", \"6.0.200\",\n \"http:\/\/www.java.com\/\" },\n { \"Adobe Reader 9\", \"Adobe Acrobat\", \"9\", \"10\", \"9.3.3\",\n \"http:\/\/get.adobe.com\/reader\/\" },\n { \"Adobe Reader 8\", \"Adobe Acrobat\", \"0\", \"9\", \"8.2.3\",\n \"http:\/\/get.adobe.com\/reader\/\" },\n { \"Flash\", \"Shockwave Flash\", \"\", \"\", \"10.1.53\",\n \"http:\/\/get.adobe.com\/flashplayer\/\" },\n { \"Silverlight 3\", \"Silverlight\", \"0\", \"4\", \"3.0.50106.0\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Silverlight 4\", \"Silverlight\", \"4\", \"5\", \"\",\n \"http:\/\/go.microsoft.com\/fwlink\/?LinkID=185927\" },\n { \"Shockwave\", \"Shockwave for Director\", \"\", \"\", \"11.5.7.609\",\n \"http:\/\/www.adobe.com\/shockwave\/download\/\" },\n { \"DivX Player\", \"DivX Web Player\", \"\", \"\", \"1.4.3.4\",\n \"http:\/\/download.divx.com\/divx\/autoupdate\/player\/DivXWebPlayerInstaller.exe\" },\n \/\/ These are here for grouping, no vulnerabilies known.\n { \"Windows Media Player\", \"Windows Media Player\", \"\", \"\", \"\", \"\" },\n { \"Microsoft Office\", \"Microsoft Office\", \"\", \"\", \"\", \"\" },\n \/\/ TODO(panayiotis): The vulnerable versions are\n \/\/ (v >= 6.0.12.1040 && v <= 6.0.12.1663)\n \/\/ || v == 6.0.12.1698 || v == 6.0.12.1741\n { \"RealPlayer\", \"RealPlayer\", \"\", \"\", \"\",\n \"http:\/\/www.adobe.com\/shockwave\/download\/\" },\n};\n\n#else\nstatic const PluginGroupDefinition kGroupDefinitions[] = {};\n#endif\n\n\/*static*\/\nstd::set* PluginGroup::policy_disabled_puglins_;\n\n\/*static*\/\nconst PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() {\n return kGroupDefinitions;\n}\n\n\/*static*\/\nsize_t PluginGroup::GetPluginGroupDefinitionsSize() {\n \/\/ TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays.\n return ARRAYSIZE_UNSAFE(kGroupDefinitions);\n}\n\n\/*static*\/\nvoid PluginGroup::SetPolicyDisabledPluginSet(const std::set& set) {\n if (!policy_disabled_puglins_) {\n policy_disabled_puglins_ = new std::set();\n *policy_disabled_puglins_ = set;\n }\n}\n\n\/*static*\/\nbool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) {\n return policy_disabled_puglins_ &&\n policy_disabled_puglins_->find(plugin_name) !=\n policy_disabled_puglins_->end();\n}\n\n\/*static*\/\nbool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) {\n std::vector plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);\n for (std::vector::const_iterator it = plugins.begin();\n it != plugins.end();\n ++it) {\n if (FilePath::CompareEqualIgnoreCase(it->path.value(),\n plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) {\n return true;\n }\n }\n return false;\n}\n\nPluginGroup::PluginGroup(const string16& group_name,\n const string16& name_matcher,\n const std::string& version_range_low,\n const std::string& version_range_high,\n const std::string& min_version,\n const std::string& update_url) {\n group_name_ = group_name;\n name_matcher_ = name_matcher;\n version_range_low_str_ = version_range_low;\n if (!version_range_low.empty()) {\n version_range_low_.reset(\n Version::GetVersionFromString(version_range_low));\n }\n version_range_high_str_ = version_range_high;\n if (!version_range_high.empty()) {\n version_range_high_.reset(\n Version::GetVersionFromString(version_range_high));\n }\n min_version_str_ = min_version;\n if (!min_version.empty()) {\n min_version_.reset(Version::GetVersionFromString(min_version));\n }\n update_url_ = update_url;\n enabled_ = false;\n max_version_.reset(Version::GetVersionFromString(\"0\"));\n}\n\nPluginGroup* PluginGroup::FromPluginGroupDefinition(\n const PluginGroupDefinition& definition) {\n return new PluginGroup(ASCIIToUTF16(definition.name),\n ASCIIToUTF16(definition.name_matcher),\n definition.version_matcher_low,\n definition.version_matcher_high,\n definition.min_version,\n definition.update_url);\n}\n\nPluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) {\n \/\/ Create a matcher from the name of this plugin.\n return new PluginGroup(wpi.name, wpi.name,\n \"\", \"\", \"\", \"\");\n}\n\nPluginGroup* PluginGroup::FindHardcodedPluginGroup(const WebPluginInfo& info) {\n static std::vector >* hardcoded_plugin_groups = NULL;\n if (!hardcoded_plugin_groups) {\n std::vector >* groups =\n new std::vector >();\n const PluginGroupDefinition* definitions = GetPluginGroupDefinitions();\n for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) {\n PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition(\n definitions[i]);\n groups->push_back(linked_ptr(definition_group));\n }\n hardcoded_plugin_groups = groups;\n }\n\n \/\/ See if this plugin matches any of the hardcoded groups.\n PluginGroup* hardcoded_group = FindGroupMatchingPlugin(\n *hardcoded_plugin_groups, info);\n if (hardcoded_group) {\n \/\/ Make a copy.\n return hardcoded_group->Copy();\n } else {\n \/\/ Not found in our hardcoded list, create a new one.\n return PluginGroup::FromWebPluginInfo(info);\n }\n}\n\nPluginGroup* PluginGroup::FindGroupMatchingPlugin(\n std::vector >& plugin_groups,\n const WebPluginInfo& plugin) {\n for (std::vector >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n if ((*it)->Match(plugin)) {\n return it->get();\n }\n }\n return NULL;\n}\n\nbool PluginGroup::Match(const WebPluginInfo& plugin) const {\n if (name_matcher_.empty()) {\n return false;\n }\n\n \/\/ Look for the name matcher anywhere in the plugin name.\n if (plugin.name.find(name_matcher_) == string16::npos) {\n return false;\n }\n\n if (version_range_low_.get() == NULL ||\n version_range_high_.get() == NULL) {\n return true;\n }\n\n \/\/ There's a version range, we must be in it.\n scoped_ptr plugin_version(\n Version::GetVersionFromString(UTF16ToWide(plugin.version)));\n if (plugin_version.get() == NULL) {\n \/\/ No version could be extracted, assume we don't match the range.\n return false;\n }\n\n \/\/ We match if we are in the range: [low, high)\n return (version_range_low_->CompareTo(*plugin_version) <= 0 &&\n version_range_high_->CompareTo(*plugin_version) > 0);\n}\n\nvoid PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) {\n web_plugin_infos_.push_back(plugin);\n \/\/ The position of this plugin relative to the global list of plugins.\n web_plugin_positions_.push_back(position);\n description_ = plugin.desc;\n\n \/\/ A group is enabled if any of the files are enabled.\n if (plugin.enabled) {\n enabled_ = true;\n }\n\n \/\/ update max_version_. Remove spaces and ')' from the version string,\n \/\/ Replace any instances of 'r', ',' or '(' with a dot.\n std::wstring version = UTF16ToWide(plugin.version);\n RemoveChars(version, L\") \", &version);\n std::replace(version.begin(), version.end(), 'r', '.');\n std::replace(version.begin(), version.end(), ',', '.');\n std::replace(version.begin(), version.end(), '(', '.');\n\n scoped_ptr plugin_version(\n Version::GetVersionFromString(version));\n if (plugin_version.get() != NULL) {\n if (plugin_version->CompareTo(*(max_version_)) > 0) {\n max_version_.reset(plugin_version.release());\n }\n }\n}\n\nDictionaryValue* PluginGroup::GetSummary() const {\n DictionaryValue* result = new DictionaryValue();\n result->SetString(\"name\", group_name_);\n result->SetBoolean(\"enabled\", enabled_);\n return result;\n}\n\nDictionaryValue* PluginGroup::GetDataForUI() const {\n DictionaryValue* result = new DictionaryValue();\n result->SetString(\"name\", group_name_);\n result->SetString(\"description\", description_);\n result->SetString(\"version\", max_version_->GetString());\n result->SetString(\"update_url\", update_url_);\n result->SetBoolean(\"critical\", IsVulnerable());\n\n bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(group_name_);\n if (group_disabled_by_policy) {\n result->SetString(\"enabledMode\", \"disabledByPolicy\");\n } else {\n result->SetString(\"enabledMode\", enabled_ ? \"enabled\" : \"disabledByUser\");\n }\n\n ListValue* plugin_files = new ListValue();\n for (size_t i = 0; i < web_plugin_infos_.size(); ++i) {\n const WebPluginInfo& web_plugin = web_plugin_infos_[i];\n int priority = web_plugin_positions_[i];\n DictionaryValue* plugin_file = new DictionaryValue();\n plugin_file->SetString(\"name\", web_plugin.name);\n plugin_file->SetString(\"description\", web_plugin.desc);\n plugin_file->SetString(\"path\", web_plugin.path.value());\n plugin_file->SetString(\"version\", web_plugin.version);\n bool plugin_disabled_by_policy = group_disabled_by_policy ||\n IsPluginNameDisabledByPolicy(web_plugin.name);\n if (plugin_disabled_by_policy) {\n result->SetString(\"enabledMode\", \"disabledByPolicy\");\n } else {\n result->SetString(\"enabledMode\",\n web_plugin.enabled ? \"enabled\" : \"disabledByUser\");\n }\n plugin_file->SetInteger(\"priority\", priority);\n\n ListValue* mime_types = new ListValue();\n for (std::vector::const_iterator type_it =\n web_plugin.mime_types.begin();\n type_it != web_plugin.mime_types.end();\n ++type_it) {\n DictionaryValue* mime_type = new DictionaryValue();\n mime_type->SetString(\"mimeType\", type_it->mime_type);\n mime_type->SetString(\"description\", type_it->description);\n\n ListValue* file_extensions = new ListValue();\n for (std::vector::const_iterator ext_it =\n type_it->file_extensions.begin();\n ext_it != type_it->file_extensions.end();\n ++ext_it) {\n file_extensions->Append(new StringValue(*ext_it));\n }\n mime_type->Set(\"fileExtensions\", file_extensions);\n\n mime_types->Append(mime_type);\n }\n plugin_file->Set(\"mimeTypes\", mime_types);\n\n plugin_files->Append(plugin_file);\n }\n result->Set(\"plugin_files\", plugin_files);\n\n return result;\n}\n\n\/\/ Returns true if the latest version of this plugin group is vulnerable.\nbool PluginGroup::IsVulnerable() const {\n if (min_version_.get() == NULL || max_version_->GetString() == \"0\") {\n return false;\n }\n return max_version_->CompareTo(*min_version_) < 0;\n}\n\nvoid PluginGroup::Enable(bool enable) {\n for (std::vector::const_iterator it =\n web_plugin_infos_.begin();\n it != web_plugin_infos_.end(); ++it) {\n if (enable && !IsPluginNameDisabledByPolicy(it->name)) {\n NPAPI::PluginList::Singleton()->EnablePlugin(FilePath(it->path));\n } else {\n NPAPI::PluginList::Singleton()->DisablePlugin(FilePath(it->path));\n }\n }\n}\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Sam on 9\/25\/2017.\n\/\/\n\n#include \"..\/include\/Game\/Core\/Game.h\"\n#include \"..\/include\/Game\/Core\/Player.h\"\n#include \"..\/include\/Network\/Server.h\"\n#include \"..\/include\/Game\/Python\/Factory.h\"\n#include \"..\/include\/Game\/Core\/Card.h\"\n#include \"..\/include\/Game\/Core\/Mana.h\"\n#include \"..\/include\/Game\/Derived\/Card\/Creature.h\"\n\n#include \n#include \n\nnamespace py = pybind11;\n\nint main()\n{\n auto* server = new Server(8888);\n server->Start();\n Factory factory;\n\n \/\/ Exit if the user enters quit\n std::string line;\n while (std::getline(std::cin, line) && line != \"quit\")\n {\n if (line == \"memes\")\n {\n py::object card = factory.createCard(\"Azar\");\n auto base = card.cast();\n auto creature = dynamic_cast(base);\n\n std::cout << \"Name: \" << creature->name << std::endl;\n std::cout << \"Tag: \" << creature->tag << std::endl;\n std::cout << \"Text: \" << creature->text << std::endl;\n std::cout << \"Attack: \" << creature->attackStat << std::endl;\n std::cout << \"Defense: \" << creature->defenseStat << std::endl;\n std::cout << \"Black: \" << creature->mana.black << std::endl;\n std::cout << \"Blue: \" << creature->mana.blue << std::endl;\n std::cout << \"Brown: \" << creature->mana.brown << std::endl;\n std::cout << \"Red: \" << creature->mana.red << std::endl;\n std::cout << \"Green: \" << creature->mana.green << std::endl;\n std::cout << \"White: \" << creature->mana.white << std::endl;\n }\n else if (line == \"list\")\n {\n for(const auto &client : server->clients)\n {\n if (!client->name.empty())\n {\n std::cout << client->name << std::endl;\n }\n }\n std::cout << server->clients.size() << \" client(s) connected\" << std::endl;\n }\n else\n {\n std::cout << \"Unknown command: '\" << line << \"'\" << std::endl;\n }\n }\n\n std::cout << \"Shutting down...\" << std::endl;\n server->Stop();\n std::cout << \"Bye!\" << std::endl;\n}\nAdded a flag to the exe \"-process\" which will run the server without any option for user input\/\/\n\/\/ Created by Sam on 9\/25\/2017.\n\/\/\n\n#include \"..\/include\/Game\/Core\/Game.h\"\n#include \"..\/include\/Game\/Core\/Player.h\"\n#include \"..\/include\/Network\/Server.h\"\n#include \"..\/include\/Game\/Python\/Factory.h\"\n#include \"..\/include\/Game\/Core\/Card.h\"\n#include \"..\/include\/Game\/Core\/Mana.h\"\n#include \"..\/include\/Game\/Derived\/Card\/Creature.h\"\n\n#include \n#include \n\nnamespace py = pybind11;\n\n\nvoid commandListen(Server* server, Factory& factory)\n{\n std::__cxx11::string line;\n while (getline(std::cin, line) && line != \"quit\")\n {\n if (line == \"memes\")\n {\n pybind11::object card = factory.createCard(\"Azar\");\n auto base = card.cast();\n auto creature = dynamic_cast(base);\n\n std::cout << \"Name: \" << creature->name << std::endl;\n std::cout << \"Tag: \" << creature->tag << std::endl;\n std::cout << \"Text: \" << creature->text << std::endl;\n std::cout << \"Attack: \" << creature->attackStat << std::endl;\n std::cout << \"Defense: \" << creature->defenseStat << std::endl;\n std::cout << \"Black: \" << creature->mana.black << std::endl;\n std::cout << \"Blue: \" << creature->mana.blue << std::endl;\n std::cout << \"Brown: \" << creature->mana.brown << std::endl;\n std::cout << \"Red: \" << creature->mana.red << std::endl;\n std::cout << \"Green: \" << creature->mana.green << std::endl;\n std::cout << \"White: \" << creature->mana.white << std::endl;\n }\n else if (line == \"list\")\n {\n for(const auto &client : server->clients)\n {\n if (!client->name.empty())\n {\n std::cout << client->name << std::endl;\n }\n }\n std::cout << server->clients.size() << \" client(s) connected\" << std::endl;\n }\n else\n {\n std::cout << \"Unknown command: '\" << line << \"'\" << std::endl;\n }\n }\n\n std::cout << \"Shutting down...\" << std::endl;\n server->Stop();\n std::cout << \"Bye!\" << std::endl;\n}\n\nint main(int argc, const char* argv[])\n{\n bool process = false;\n\n for(int i = 0; i < argc; ++i)\n {\n if(std::string(argv[i]) == \"-process\")\n {\n process = true;\n }\n }\n\n auto* server = new Server(8888);\n server->Start();\n Factory factory;\n\n if (process)\n {\n while(true){}\n }\n else\n {\n commandListen(server, factory);\n }\n}\n<|endoftext|>"} {"text":"\/\/ H264 receiver\n\/\/ Author: Max Schwarz \n\n#include \n\nextern \"C\"\n{\n#include \n#include \n}\n\n#include \n\n#include \n\nros::Publisher g_pub;\nAVCodecContext* g_codec = 0;\nSwsContext* g_sws = 0;\n\nvoid handleImage(const sensor_msgs::CompressedImageConstPtr& img)\n{\n\t\/\/ROS_INFO(\"got data: %lu\", img->data.size());\n\n\tAVPacket packet;\n\tav_init_packet(&packet);\n\tpacket.data = const_cast(img->data.data());\n\tpacket.size = img->data.size();\n\tpacket.pts = AV_NOPTS_VALUE;\n\tpacket.dts = AV_NOPTS_VALUE;\n\n\tAVFrame frame;\n\tmemset(&frame, 0, sizeof(frame));\n\n\tint gotPicture;\n\n\tif(avcodec_decode_video2(g_codec, &frame, &gotPicture, &packet) < 0)\n\t{\n\t\t\/\/ROS_ERROR(\"Could not decode frame\");\n\t\treturn;\n\t}\n\n\tif(gotPicture)\n\t{\n\t\tsensor_msgs::ImagePtr img(new sensor_msgs::Image);\n\n\t\timg->encoding = \"rgb8\";\n\t\timg->data.resize(frame.width * frame.height * 3);\n\t\timg->step = frame.width * 3;\n\t\timg->width = frame.width;\n\t\timg->height = frame.height;\n\t\timg->header.frame_id = \"cam\";\n\t\timg->header.stamp = ros::Time::now(); \/\/ FIXME\n\n\t\tuint8_t* destData[1] = {img->data.data()};\n\t\tint linesize[1] = {(int)img->step};\n\n\t\tsws_scale(g_sws, frame.data, frame.linesize, 0, frame.height,\n\t\t\tdestData, linesize);\n\n\t\t\/\/ROS_DEBUG(\"frame\");\n\t\tg_pub.publish(img);\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"cam_receiver\");\n\t\n\tros::NodeHandle nh(\"~\");\n\n\tavcodec_register_all();\n\n\tAVCodec* decoder = avcodec_find_decoder(AV_CODEC_ID_H264);\n\tif(!decoder)\n\t\tthrow std::runtime_error(\"H264 decoding not supported in this build of ffmpeg\");\n\n\tg_codec = avcodec_alloc_context3(decoder);\n\n\tg_codec->flags2 |= CODEC_FLAG2_SHOW_ALL;\n\n\tif(avcodec_open2(g_codec, decoder, 0) != 0)\n\t\tthrow std::runtime_error(\"Could not open decoder\");\n\n\tconst int WIDTH = 640;\n\tconst int HEIGHT = 480;\n\tg_sws = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_YUV420P, WIDTH, HEIGHT,\n\t AV_PIX_FMT_RGB24, 0, 0, 0, 0);\n\n\tg_pub = nh.advertise(\"image\", 1);\n\t\n\tros::Subscriber sub = nh.subscribe(\"encoded\", 5, &handleImage);\n\t\n\tros::spin();\n\t\n\treturn 0;\n}\nnimbro_cam_transport: receiver: low-delay settings\/\/ H264 receiver\n\/\/ Author: Max Schwarz \n\n#include \n\nextern \"C\"\n{\n#include \n#include \n}\n\n#include \n\n#include \n\nros::Publisher g_pub;\nAVCodecContext* g_codec = 0;\nSwsContext* g_sws = 0;\n\nvoid handleImage(const sensor_msgs::CompressedImageConstPtr& img)\n{\n\t\/\/ROS_INFO(\"got data: %lu\", img->data.size());\n\n\tAVPacket packet;\n\tav_init_packet(&packet);\n\tpacket.data = const_cast(img->data.data());\n\tpacket.size = img->data.size();\n\tpacket.pts = AV_NOPTS_VALUE;\n\tpacket.dts = AV_NOPTS_VALUE;\n\n\tAVFrame frame;\n\tmemset(&frame, 0, sizeof(frame));\n\n\tint gotPicture;\n\n\tif(avcodec_decode_video2(g_codec, &frame, &gotPicture, &packet) < 0)\n\t{\n\t\t\/\/ROS_ERROR(\"Could not decode frame\");\n\t\treturn;\n\t}\n\n\tif(gotPicture)\n\t{\n\t\tsensor_msgs::ImagePtr img(new sensor_msgs::Image);\n\n\t\timg->encoding = \"rgb8\";\n\t\timg->data.resize(frame.width * frame.height * 3);\n\t\timg->step = frame.width * 3;\n\t\timg->width = frame.width;\n\t\timg->height = frame.height;\n\t\timg->header.frame_id = \"cam\";\n\t\timg->header.stamp = ros::Time::now(); \/\/ FIXME\n\n\t\tuint8_t* destData[1] = {img->data.data()};\n\t\tint linesize[1] = {(int)img->step};\n\n\t\tsws_scale(g_sws, frame.data, frame.linesize, 0, frame.height,\n\t\t\tdestData, linesize);\n\n\t\t\/\/ROS_DEBUG(\"frame\");\n\t\tg_pub.publish(img);\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"cam_receiver\");\n\t\n\tros::NodeHandle nh(\"~\");\n\n\tavcodec_register_all();\n\n\tAVCodec* decoder = avcodec_find_decoder(AV_CODEC_ID_H264);\n\tif(!decoder)\n\t\tthrow std::runtime_error(\"H264 decoding not supported in this build of ffmpeg\");\n\n\tg_codec = avcodec_alloc_context3(decoder);\n\n\tg_codec->flags |= CODEC_FLAG_LOW_DELAY;\n\tg_codec->flags2 |= CODEC_FLAG2_SHOW_ALL;\n\n\tg_codec->thread_type = 0;\n\n\tif(avcodec_open2(g_codec, decoder, 0) != 0)\n\t\tthrow std::runtime_error(\"Could not open decoder\");\n\n\tconst int WIDTH = 640;\n\tconst int HEIGHT = 480;\n\tg_sws = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_YUV420P, WIDTH, HEIGHT,\n\t AV_PIX_FMT_RGB24, 0, 0, 0, 0);\n\n\tg_pub = nh.advertise(\"image\", 1);\n\t\n\tros::Subscriber sub = nh.subscribe(\"encoded\", 5, &handleImage);\n\t\n\tros::spin();\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \"looping_quintic_cr_spline.h\"\r\n\r\n\r\n#include \r\n#include \r\n\r\nLoopingQuinticCRSpline::LoopingQuinticCRSpline(const std::vector &points, double alpha)\r\n{\r\n assert(points.size() >= 6);\r\n\r\n this->points = points;\r\n\r\n std::unordered_map indexToT_Raw;\r\n std::unordered_map pointMap;\r\n\r\n int size = points.size();\r\n numSegments = size;\r\n\r\n\t\/\/we know points[0] will have a t value of 0\r\n\tindexToT_Raw[0] = 0;\r\n pointMap[0] = points[0];\r\n\r\n\t\/\/loop backwards from 0 to give the earlier points negative t values\r\n for(int i = -1; i >= -3; i--)\r\n\t{\r\n\t\t\/\/points[1] is a control point, so give it a nagative t value, so that the first actual point can have a t value of 0\r\n\t\tdouble distance = (points.at((i + size)%size) - points.at((i + 1 + size)%size)).length();\r\n\t\tindexToT_Raw[i] = indexToT_Raw[i + 1] - pow(distance, alpha);\r\n\t\tpointMap[i] = points.at((i + size)%size);\r\n\t}\r\n\r\n \/\/compute the t values of the other points\r\n for(int i = 1; i < size + 4; i++)\r\n {\r\n double distance = (points.at(i%size) - points.at((i - 1)%size)).length();\r\n indexToT_Raw[i] = indexToT_Raw[i - 1] + pow(distance, alpha);\r\n\r\n pointMap[i] = points.at((i + size)%size);\r\n }\r\n\r\n \/\/we want to know the t value of the last segment so that we can normalize them all\r\n float maxTRaw = indexToT_Raw.at(size);\r\n\r\n \/\/now that we have all ouf our t values and indexes figured out, normalize the t values by dividing tem by maxT\r\n for(auto it = indexToT_Raw.begin(); it != indexToT_Raw.end(); it++)\r\n {\r\n indexToT[it->first] = numSegments * it->second \/ maxTRaw;\r\n }\r\n maxT = indexToT.at(size);\r\n\r\n \/\/compute the tangents\r\n std::map tangentMap;\r\n for(int i = -1; i < size + 2; i++)\r\n {\r\n double tPrev = indexToT.at(i - 1);\r\n double tCurrent = indexToT.at(i);\r\n double tNext = indexToT.at(i + 1);\r\n\r\n Vector3D pPrev = pointMap.at(i - 1);\r\n Vector3D pCurrent = pointMap.at(i);\r\n Vector3D pNext = pointMap.at(i + 1);\r\n\r\n \/\/the tangent is the standard catmull-rom spline tangent calculation\r\n tangentMap[i] =\r\n pPrev * (tCurrent - tNext) \/ ((tNext - tPrev) * (tCurrent - tPrev))\r\n + pNext * (tCurrent - tPrev) \/ ((tNext - tPrev) * (tNext - tCurrent))\r\n\r\n \/\/plus a little something extra - this is derived from the pyramid contruction\r\n \/\/when the t values are evenly spaced (ie when alpha is 0), this whole line collapses to 0,\r\n \/\/yielding the standard catmull-rom formula\r\n - pCurrent * ((tCurrent - tPrev) - (tNext - tCurrent)) \/ ((tNext - tCurrent) * (tCurrent - tPrev));\r\n }\r\n\r\n \/\/compute the curvatures\r\n std::map curveMap;\r\n for(int i = 0; i < size + 1; i++)\r\n {\r\n double tPrev = indexToT.at(i - 1);\r\n double tCurrent = indexToT.at(i);\r\n double tNext = indexToT.at(i + 1);\r\n\r\n Vector3D pPrev = tangentMap.at(i - 1);\r\n Vector3D pCurrent = tangentMap.at(i);\r\n Vector3D pNext = tangentMap.at(i + 1);\r\n\r\n \/\/the tangent is the standard catmull-rom spline tangent calculation\r\n curveMap[i] =\r\n pPrev * (tCurrent - tNext) \/ ((tNext - tPrev) * (tCurrent - tPrev))\r\n + pNext * (tCurrent - tPrev) \/ ((tNext - tPrev) * (tNext - tCurrent))\r\n\r\n \/\/plus a little something extra - this is derived from the pyramid contruction\r\n \/\/when the t values are evenly spaced (ie when alpha is 0), this whole line collapses to 0,\r\n \/\/yielding the standard catmull-rom formula\r\n - pCurrent * ((tCurrent - tPrev) - (tNext - tCurrent)) \/ ((tNext - tCurrent) * (tCurrent - tPrev));\r\n\t}\r\n\r\n\r\n \/\/pre-arrange the data needed for interpolation\r\n for(int i = 0; i < numSegments; i++)\r\n {\r\n InterpolationData segment;\r\n\r\n segment.t0 = indexToT.at(i);\r\n segment.t1 = indexToT.at(i + 1);\r\n\r\n segment.p0 = pointMap.at(i);\r\n segment.p1 = pointMap.at(i + 1);\r\n\r\n double tDistance = segment.t1 - segment.t0;\r\n segment.tDistanceInverse = 1 \/ tDistance;\r\n\r\n \/\/we scale the tangents by this segment's t distance, because wikipedia says so\r\n segment.m0 = tangentMap.at(i) * tDistance;\r\n segment.m1 = tangentMap.at(i + 1) * tDistance;\r\n\r\n \/\/we scale the tangents by this segment's t distance, because wikipedia says so\r\n segment.c0 = curveMap.at(i) * tDistance * tDistance;\r\n segment.c1 = curveMap.at(i + 1) * tDistance * tDistance;\r\n\r\n segmentData.push_back(segment);\r\n }\r\n}\r\nchanged required number of points for looping quintic CR spline#include \"looping_quintic_cr_spline.h\"\r\n\r\n\r\n#include \r\n#include \r\n\r\nLoopingQuinticCRSpline::LoopingQuinticCRSpline(const std::vector &points, double alpha)\r\n{\r\n assert(points.size() >= 3);\r\n\r\n this->points = points;\r\n\r\n std::unordered_map indexToT_Raw;\r\n std::unordered_map pointMap;\r\n\r\n int size = points.size();\r\n numSegments = size;\r\n\r\n\t\/\/we know points[0] will have a t value of 0\r\n\tindexToT_Raw[0] = 0;\r\n pointMap[0] = points[0];\r\n\r\n\t\/\/loop backwards from 0 to give the earlier points negative t values\r\n for(int i = -1; i >= -3; i--)\r\n\t{\r\n\t\t\/\/points[1] is a control point, so give it a nagative t value, so that the first actual point can have a t value of 0\r\n\t\tdouble distance = (points.at((i + size)%size) - points.at((i + 1 + size)%size)).length();\r\n\t\tindexToT_Raw[i] = indexToT_Raw[i + 1] - pow(distance, alpha);\r\n\t\tpointMap[i] = points.at((i + size)%size);\r\n\t}\r\n\r\n \/\/compute the t values of the other points\r\n for(int i = 1; i < size + 4; i++)\r\n {\r\n double distance = (points.at(i%size) - points.at((i - 1)%size)).length();\r\n indexToT_Raw[i] = indexToT_Raw[i - 1] + pow(distance, alpha);\r\n\r\n pointMap[i] = points.at((i + size)%size);\r\n }\r\n\r\n \/\/we want to know the t value of the last segment so that we can normalize them all\r\n float maxTRaw = indexToT_Raw.at(size);\r\n\r\n \/\/now that we have all ouf our t values and indexes figured out, normalize the t values by dividing tem by maxT\r\n for(auto it = indexToT_Raw.begin(); it != indexToT_Raw.end(); it++)\r\n {\r\n indexToT[it->first] = numSegments * it->second \/ maxTRaw;\r\n }\r\n maxT = indexToT.at(size);\r\n\r\n \/\/compute the tangents\r\n std::map tangentMap;\r\n for(int i = -1; i < size + 2; i++)\r\n {\r\n double tPrev = indexToT.at(i - 1);\r\n double tCurrent = indexToT.at(i);\r\n double tNext = indexToT.at(i + 1);\r\n\r\n Vector3D pPrev = pointMap.at(i - 1);\r\n Vector3D pCurrent = pointMap.at(i);\r\n Vector3D pNext = pointMap.at(i + 1);\r\n\r\n \/\/the tangent is the standard catmull-rom spline tangent calculation\r\n tangentMap[i] =\r\n pPrev * (tCurrent - tNext) \/ ((tNext - tPrev) * (tCurrent - tPrev))\r\n + pNext * (tCurrent - tPrev) \/ ((tNext - tPrev) * (tNext - tCurrent))\r\n\r\n \/\/plus a little something extra - this is derived from the pyramid contruction\r\n \/\/when the t values are evenly spaced (ie when alpha is 0), this whole line collapses to 0,\r\n \/\/yielding the standard catmull-rom formula\r\n - pCurrent * ((tCurrent - tPrev) - (tNext - tCurrent)) \/ ((tNext - tCurrent) * (tCurrent - tPrev));\r\n }\r\n\r\n \/\/compute the curvatures\r\n std::map curveMap;\r\n for(int i = 0; i < size + 1; i++)\r\n {\r\n double tPrev = indexToT.at(i - 1);\r\n double tCurrent = indexToT.at(i);\r\n double tNext = indexToT.at(i + 1);\r\n\r\n Vector3D pPrev = tangentMap.at(i - 1);\r\n Vector3D pCurrent = tangentMap.at(i);\r\n Vector3D pNext = tangentMap.at(i + 1);\r\n\r\n \/\/the tangent is the standard catmull-rom spline tangent calculation\r\n curveMap[i] =\r\n pPrev * (tCurrent - tNext) \/ ((tNext - tPrev) * (tCurrent - tPrev))\r\n + pNext * (tCurrent - tPrev) \/ ((tNext - tPrev) * (tNext - tCurrent))\r\n\r\n \/\/plus a little something extra - this is derived from the pyramid contruction\r\n \/\/when the t values are evenly spaced (ie when alpha is 0), this whole line collapses to 0,\r\n \/\/yielding the standard catmull-rom formula\r\n - pCurrent * ((tCurrent - tPrev) - (tNext - tCurrent)) \/ ((tNext - tCurrent) * (tCurrent - tPrev));\r\n\t}\r\n\r\n\r\n \/\/pre-arrange the data needed for interpolation\r\n for(int i = 0; i < numSegments; i++)\r\n {\r\n InterpolationData segment;\r\n\r\n segment.t0 = indexToT.at(i);\r\n segment.t1 = indexToT.at(i + 1);\r\n\r\n segment.p0 = pointMap.at(i);\r\n segment.p1 = pointMap.at(i + 1);\r\n\r\n double tDistance = segment.t1 - segment.t0;\r\n segment.tDistanceInverse = 1 \/ tDistance;\r\n\r\n \/\/we scale the tangents by this segment's t distance, because wikipedia says so\r\n segment.m0 = tangentMap.at(i) * tDistance;\r\n segment.m1 = tangentMap.at(i + 1) * tDistance;\r\n\r\n \/\/we scale the tangents by this segment's t distance, because wikipedia says so\r\n segment.c0 = curveMap.at(i) * tDistance * tDistance;\r\n segment.c1 = curveMap.at(i + 1) * tDistance * tDistance;\r\n\r\n segmentData.push_back(segment);\r\n }\r\n}\r\n<|endoftext|>"} {"text":"#include \"actions.h\"\n#include \"..\/html\/html.h\"\n#include \"..\/account.h\"\n#include \"..\/session.h\"\n\nusing namespace Html;\n\nstd::string accountForm(const Account &_account, const std::string &error=std::string(),\n const std::string &message=std::string()){\n return Html::header(\"Your account\") + \"

Your account<\/h2>\" +\n (message.empty() ? \"\" : \"
\" + message + \"<\/div>\") +\n (error.empty() ? \"\" : \"
\" + error + \"<\/div>\") +\n \"
\"\n \"\"\n \"\"\n \"\"\n \"\"\n \"\"\n \"\"\n \"\"\n \"
<\/td>\"\n \"<\/tr>\"\n \"
<\/td>\"\n \"<\/tr>\"\n \"
<\/td>\"\n \"<\/tr>\"\n \"
<\/td>\"\n \"<\/tr>\"\n \"
<\/td>\"\n \"<\/tr>\"\n \"