blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c32bf0e16cdd4a860c1485be67ab7f25f68c4fcd | 5793be5223cb592233b8f967180c090b83795522 | /NbodyGravitation/PhysEngine.cpp | 7932818d0ed1178bc0f3cd43fb17154bf197c46f | [] | no_license | AlexandraTchalakian/NumericalPhysicsProject | d009e82fc66d884ad4e268013731339d0f7d7546 | 493cc3384dbcd98896a1903c88ebacd370c57876 | refs/heads/main | 2023-04-03T03:17:10.883677 | 2021-03-28T14:19:20 | 2021-03-28T14:19:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,509 | cpp | #include "PhysEngine.hpp"
#include "ConfigFile.hpp"
#include "ConfigFile.tpp"
#define Xt 0
#define Yt 1
#define Xa 2
#define Ya 3
#define Xl 4
#define Yl 5
#define Vxt 6
#define Vyt 7
#define Vxa 8
#define Vya 9
#define Vxl 10
#define Vyl 11
#define terre 1
#define asteroide 2
#define lune 3
#define asteroide_lune 4
using namespace std;
typedef valarray<double> Vecteur;
/** Constructor
*/
PhysEngine::PhysEngine(const ConfigFile configFile) : ra({configFile.get<double>("ra0x"),configFile.get<double>("ra0y")}), rt({configFile.get<double>("rt0x"),configFile.get<double>("rt0y")}),rl({configFile.get<double>("rl0x"),configFile.get<double>("rl0y")}),va({configFile.get<double>("va0x"),configFile.get<double>("va0y")}),vt({configFile.get<double>("vt0x"),configFile.get<double>("vt0y")}),vl({configFile.get<double>("vl0x"),configFile.get<double>("vl0y")}){
outputFile=NULL;
try{
dt=configFile.get<double>("dt");
tfin=configFile.get<double>("tfin");
G=configFile.get<double>("G");
Mt=configFile.get<double>("Mt");
Ma=configFile.get<double>("Ma");
Ml= configFile.get<double>("Ml");
Rt=configFile.get<double>("Rt");
Rl=configFile.get<double>("Rl");
t=0;
alpha=configFile.get<double>("alpha");
epsilon=configFile.get<double>("epsilon");
R=sqrt((ra[0]-rt[0])*(ra[0]-rt[0])+(ra[1]-rt[1])*(ra[1]-rt[1]));
V=sqrt(va[0]*va[0]-vt[0]+va[1]*va[1]);
Emec=0.5*Ma*V*V-G*Ma*Mt/R;
/*ra[0] = configFile.get<double>("ra0x");
ra[1] = configFile.get<double>("ra0y");
Vecteur rt(2);
rt[0] = configFile.get<double>("rt0x");
rt[1] = configFile.get<double>("rt0y");
Vecteur rl(2);
rl[0] = configFile.get<double>("rl0x");
rl[1] = configFile.get<double>("rl0y");
Vecteur va(2);
va[0] = configFile.get<double>("va0x");
va[1] = configFile.get<double>("va0y");
Vecteur vt(2);
vt[0] = configFile.get<double>("vt0x");
vt[1] = configFile.get<double>("vt0y");
Vecteur vl(2);
vl[0] = configFile.get<double>("vl0x");
vl[1] = configFile.get<double>("vl0y");*/
Jeanbob = configFile.get<bool>("adapt");
//manque l'inerge potentielle
std::string path=configFile.get<std::string>("outputPath");
outputFile = new std::ofstream();
outputFile->open( path.c_str());
if (!outputFile->is_open())
{
delete outputFile;
outputFile=NULL;
}
//cout << "dt="<< dt << "G=" << G << ", mt=" << Mt << ", ma=" << Ma ;
//cout << ", ml=" << Ml << ", rt1=" << rt[0] << ", rl1=" << rl[0] << endl;
//cout << "r0=" << r0 << ", v1=" << v1 ;
//cout << ", alpha=" << alpha << "Pas de temps adaptatif=" << Jeanbob endl;
}catch(std::string e){
cerr << "Exception: " << e.c_str() << endl;
if(outputFile!=NULL){outputFile->close();delete outputFile;}
}
}
/** Destructor
*/
PhysEngine::~PhysEngine(){
outputFile->close();
cout << "delete" <<endl;
delete outputFile;
cout << "fin destructeur" <<endl;
}
int PhysengineRungeKutta4::run(){
//Si il y a eu un probleme a la construction, on sort.
if(outputFile==NULL){
return -1;
}
cout << "Start the physics engine"<< " Ma=" << Ma <<"rt1=" << rt[1] << ", rl1=" << rl[1] << endl;
//cout << "Mt=" << Mt << endl;
//cout << "step : t=" << t << " dt=" << dt << "rt[O] " << rt[0] << "rt[1]" << rt[1] << endl;
//cout <<"ra[0]" << ra[0] << "ra[1]" << ra[1] ;
double n(0);
double h(get_distance(asteroide));
//adaptateur();
while(t <= tfin-0.5*dt){
++n;
// cout << "dans adaptateur avant : dt=" << dt << endl;
step();
adaptateur();
R=sqrt((ra[0]-rt[0])*(ra[0]-rt[0])+(ra[1]-rt[1])*(ra[1]-rt[1]));
V=sqrt(va[0]*va[0]-vt[0]+va[1]*va[1]);
Emec=0.5*Ma*V*V-G*Ma*Mt/R;
h= get_distance(asteroide);
printout(h);
//cout << "sortie" << endl;
//cout << "dans adaptateur apres : dt=" << dt << endl;
//cout << "t=" << t << endl;
}
cout << "Stop the physics engine" << endl;
//cout << "n=" << n << endl;
return 0;
}
/** Print the data in the output file
* */
void PhysEngine::printout(double h){
*outputFile << setprecision(14) << t << " " << rt[0] << " " << rt[1] ;
*outputFile << " " << ra[0] << " " << ra[1] << " "<< rl[0] << " " <<rl[1] << " " <<vt[0] << " " <<vt[1] << " " ;
*outputFile <<va[0] << " " <<va[1]<< " " <<vl[0]<< " " <<vl[1] << " " << dt << " " << h << " "<< Emec << " "<< get_distance(asteroide_lune) <<endl;
}
/** Return the angle acceleration
*/
void PhysEngine::acceleration(Vecteur& A, Vecteur r0a,Vecteur r0t,Vecteur r0l,Vecteur v0a, Vecteur v0t, Vecteur v0l){
double rta (sqrt((r0t[0] - r0a[0])*(r0t[0] - r0a[0])+(r0t[1] - r0a[1])*(r0t[1] - r0a[1])));
//cout << "rta = " << rta << endl;
//cout << "r0a[0] - r0t[0]=" << r0a[0] - r0t[0] << endl;
double rla (sqrt((r0l[0] - r0a[0])*(r0l[0] - r0a[0])+(r0l[1] - r0a[1])*(r0l[1] - r0a[1])));
double rtl (sqrt(pow((r0t[0] - r0l[0]),2)+pow((r0t[1] - r0l[1]),2)));
//cout << "rtl = " << rtl << endl;
A[Xt] = v0t[0];
A[Yt] = v0t[1];
A[Xa] = v0a[0];
A[Ya] = v0a[1];
A[Xl] = v0l[0];
A[Yl] = v0l[1];
A[Vxt] = -((Ma*G)/(rta*rta*rta))*(r0t[0] - r0a[0]) -((Ml*G)/(pow(rtl,3)))*(r0t[0] - r0l[0]);
A[Vyt] = -((Ma*G)/(rta*rta*rta))*(r0t[1] - r0a[1]) -((Ml*G)/(pow(rtl,3)))*(r0t[1] - r0l[1]);
A[Vxa] = -(r0a[0] - r0t[0])*((Mt*G)/(rta*rta*rta)) -((Ml*G)/(pow(rla,3)))*(r0a[0] - r0l[0]);
A[Vya] = -(r0a[1] - r0t[1])*((Mt*G)/(rta*rta*rta)) -((Ml*G)/(pow(rla,3)))*(r0a[1] - r0l[1]);
A[Vxl] = -((Mt*G)/(pow(rtl,3)))*(r0l[0] - r0t[0]) -((Ma*G)/(pow(rla,3)))*(r0l[0] - r0a[0]);
A[Vyl] = -((Mt*G)/(pow(rtl,3)))*(r0l[1] - r0t[1]) -((Ma*G)/(pow(rla,3)))*(r0l[1] - r0a[1]);
}
///////////////////////////////////////////////
//
// Implementation of the virtual step() method
//
//////////////////////////////////////////////
void PhysengineRungeKutta4::adaptateur(){
if(Jeanbob){
Vecteur ra_p (ra);
Vecteur rt_p (rt);
Vecteur rl_p (rl);
Vecteur va_p (va);
Vecteur vt_p (vt);
Vecteur vl_p (vl);
double t_p (t);
long double d1(0);
long double d2(0);
long double d(0);
do{
double dt_temp(dt);
step();
Vecteur ra_1 (ra);
Vecteur rt_1 (rt);
Vecteur rl_1 (rl);
Vecteur va_1 (va);
Vecteur vt_1 (vt);
Vecteur vl_1 (vl);
ra = ra_p;
rt = rt_p;
rl = rl_p;
va = va_p;
vt = vt_p;
vl = vl_p;
t = t_p;
dt = dt*0.5;
step();
step();
cout << "rl_1[0]=" << rl_1[0] << endl;
cout << "rl[0]=" << rl[0] << endl;
d1 = sqrt((ra_1[0] - ra[0])*(ra_1[0] - ra[0]) + (ra_1[1] - ra[1])*(ra_1[1] - ra[1]));
d2 = sqrt((rl_1[0] - rl[0])*(rl_1[0] - rl[0]) + (rl_1[1] - rl[1])*(rl_1[1] - rl[1]));
ra = ra_p;
rt = rt_p;
rl = rl_p;
va = va_p;
vt = vt_p;
vl = vl_p;
t = t_p;
dt = dt_temp;
//cout << "d1=" << d1 << endl;
//cout << "d2=" << d2 << endl;
cout << "epsilon=" << epsilon << endl;
d = d1+d2;
//d = d1;
if (abs(d) > epsilon){
dt = 0.95*dt*pow((epsilon/(abs(d))),0.2);
cout << "dt=" << dt << endl;
}else if (d <= epsilon){
dt = dt*pow((epsilon/(abs(d))),0.2);
}}while(d > epsilon);
}
t+= dt;
}
void PhysengineRungeKutta4::step(){
Vecteur A(12);
//cout << "Terre :"<< rt[0] << " " << rt[1] << "Asteroide : " << ra[0] << " " << ra[1] << endl;
acceleration (A,ra,rt,rl,va,vt,vl);
//cout << "A=" << A[Xt] << " " << A[Yt] << " " << A[Xa] << " " << A[Ya] << " " << A[Xl] << " " << A[Yl] << " " << A[Vxt] << " " << A[Vyt] << " " << A[Vxa] << " " << A[Vya] << endl;
Vecteur A1 (12);
A1 = A*dt;
Vecteur rt1({A1[Xt],A1[Yt]});
Vecteur ra1({A1[Xa],A1[Ya]});
Vecteur rl1({A1[Xl],A1[Yl]});
Vecteur vt1({A1[Vxt],A1[Vyt]});
Vecteur va1({A1[Vxa],A1[Vya]});
Vecteur vl1({A1[Vxl],A1[Vyl]});
//cout << "A1="<< A1[Xt] << " " << A1[Yt] << " " << A1[Xa] << " " << A1[Ya] << " " << A1[Xl] << " " << A1[Yl] << " " << A1[Vxt] << " " << A1[Vyt] << " " << A1[Vxa] << " " << A1[Vya] << endl;
Vecteur A2 (12);
acceleration(A2,ra + 0.5*ra1,rt + 0.5*rt1,rl + 0.5*rl1, va + 0.5*va1, vt + 0.5*vt1, vl + 0.5*vl1);
A2 = dt*A2;
// cout <<"A2=" << A2[Xt] << " " << A2[Yt] << " " << A2[Xa] << " " << A2[Ya] << " " << A2[Xl] << " " << A2[Yl] << " " << A2[Vxt] << " " << A2[Vyt] << " " << A2[Vxa] << " " << A2[Vya] << endl;
Vecteur rt2({A2[Xt],A2[Yt]});
Vecteur ra2({A2[Xa],A2[Ya]});
Vecteur rl2({A2[Xl],A2[Yl]});
Vecteur vt2({A2[Vxt],A2[Vyt]});
Vecteur va2({A2[Vxa],A2[Vya]});
Vecteur vl2({A2[Vxl],A2[Vyl]});
Vecteur A3(12);
acceleration(A3,ra + 0.5*ra2,rt + 0.5*rt2,rl + 0.5*rl2, va + 0.5*va2, vt + 0.5*vt2, vl + 0.5*vl2);
A3 = dt*A3;
//cout <<"A3=" << A3[Xt] << " " << A3[Yt] << " " << A3[Xa] << " " << A3[Ya] << " " << A3[Xl] << " " << A3[Yl] << " " << A3[Vxt] << " " << A3[Vyt] << " " << A3[Vxa] << " " << A3[Vya] << endl;
Vecteur A4(12);
Vecteur rt3({A3[Xt],A3[Yt]});
Vecteur ra3({A3[Xa],A3[Ya]});
Vecteur rl3({A3[Xl],A3[Yl]});
Vecteur vt3({A3[Vxt],A3[Vyt]});
Vecteur va3({A3[Vxa],A3[Vya]});
Vecteur vl3({A3[Vxl],A3[Vyl]});
acceleration(A4,ra + ra3,rt + rt3,rl + rl3, va + va3, vt + vt3, vl + vl3);
A4 = dt*A4;
// cout <<"A4=" << A4[Xt] << " " << A4[Yt] << " " << A4[Xa] << " " << A4[Ya] << " " << A4[Xl] << " " << A4[Yl] << " " << A4[Vxt] << " " << A4[Vyt] << " " << A4[Vxa] << " " << A4[Vya] << endl;
Vecteur rt4({A4[Xt],A4[Yt]});
Vecteur ra4({A4[Xa],A4[Ya]});
Vecteur rl4({A4[Xl],A4[Yl]});
Vecteur vt4({A4[Vxt],A4[Vyt]});
Vecteur va4({A4[Vxa],A4[Vya]});
Vecteur vl4({A4[Vxl],A4[Vyl]});
rt += (1.0/6)*(rt1 + 2.0*rt2 + 2.0*rt3 + rt4);
ra += (1.0/6)*(ra1 + 2.0*ra2 + 2.0*ra3 + ra4);
rl += (1.0/6)*(rl1 + 2.0*rl2 + 2.0*rl3 + rl4);
vt += (1.0/6)*(vt1 + 2.0*vt2 + 2.0*vt3 + vt4);
va += (1.0/6)*(va1 + 2.0*va2 + 2.0*va3 + va4);
vl += (1.0/6)*(vl1 + 2.0*vl2 + 2.0*vl3 + vl4);
}
// Getters, Setters
void PhysEngine::set_dt(const double& d){
dt = d;
}
double PhysEngine::get_distance(const unsigned int& astre) const{
if (astre == terre){
return sqrt(rt[0]*rt[0] + rt[1]*rt[1]);}
else if (astre == asteroide){
return sqrt(pow(ra[0] - rt[0],2) + pow(ra[1] - rt[1],2));}
else if (astre == lune){
return sqrt(pow(rl[0] - rt[0],2) + pow(rl[1] - rt[1],2));
cout << "lune" << endl;
}else if(astre == asteroide_lune){
return sqrt(pow(ra[0] - rl[0],2) + pow(ra[1] - rl[1],2));
}
cout << "erreur" << endl;
return 1;
}
double PhysEngine::get_dt() const{return dt;}
//constructeur copie
| [
"noreply@github.com"
] | noreply@github.com |
f970c3d78c78187fb98037d15e2763ed064ccdb0 | 0058191411b36ef4f5fbac7d4028e375d58e2dfa | /Common/mdbPeerInfo.cpp | f9eae16d54452a0251f995a059c4012e7609e6b8 | [] | no_license | radtek/QMDB81 | bad9c46a0268bc38ba5206975d956e62fa1f572e | 00794330516fa59a42f8e8d882332aff1f78da75 | refs/heads/master | 2021-06-06T16:54:10.801528 | 2016-10-25T07:32:59 | 2016-10-25T07:32:59 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 26,084 | cpp | #include "Common/mdbPeerInfo.h"
#include "Common/mdbPeerProactor.h"
#include "Common/mdbPeerEvent.h"
#include "Common/mdbPeerProtocol.h"
#include "Common/mdbSysThreads.h"
#include "Common/mdbSysTimerManager.h"
//namespace QuickMDB
//{
//using namespace BillingSDK;
struct TMdbNtcCheckPeerTimeout
{
TMdbEventDispatcher* pEventDispatcher;
TMdbPeerInfo* pPeerInfo;
MDB_UINT32 uiSeconds;
MDB_NTC_PEER_TIMEOUT_TYPE eTimeoutType;
};
TMdbTrafficCtrl::TMdbTrafficCtrl()
{
m_uiMaxRecvRate = m_uiMaxSendRate = m_uiMaxFlowRate = 0;
}
MDB_UINT32 TMdbTrafficCtrl::GetAllowRecvBytes(TMdbTrafficInfo* pTrafficInfo, MDB_UINT32 uiRecvBytes)
{
if(m_uiMaxRecvRate+m_uiMaxFlowRate == 0) return uiRecvBytes;
MDB_UINT32 uiRet = uiRecvBytes;
//MDB_NTC_DEBUG("m_tLastRecvTime[%d],m_uiSectionRecvBytes:[%u], m_uiSectionSendBytes[%u]", pTrafficInfo->GetLastRecvTime(), pTrafficInfo->GetCurSecRecvBytes(),
// pTrafficInfo->GetCurSecSendBytes());
MDB_UINT32 uiMaxRecvRate = m_uiMaxRecvRate;
if(uiMaxRecvRate > 0)
{
MDB_UINT32 uiTrafficRecvBytes = pTrafficInfo->GetCurSecRecvBytes();
if(uiTrafficRecvBytes >= uiMaxRecvRate)
{
return 0;
}
else if(uiRet+uiTrafficRecvBytes > uiMaxRecvRate)
{
uiRet = uiMaxRecvRate-uiTrafficRecvBytes;
}
}
MDB_UINT32 uiMaxFlowRate = m_uiMaxFlowRate;
if(uiMaxFlowRate > 0)
{
MDB_UINT32 uiTrafficTotalBytes = pTrafficInfo->GetCurSecTotalBytes();
if(uiTrafficTotalBytes >= uiMaxFlowRate)
{
return 0;
}
else if(uiRet+uiTrafficTotalBytes > uiMaxFlowRate)
{
uiRet = uiMaxFlowRate-uiTrafficTotalBytes;
}
}
return uiRet;
}
MDB_UINT32 TMdbTrafficCtrl::GetAllowSendBytes(TMdbTrafficInfo* pTrafficInfo, MDB_UINT32 uiSendBytes)
{
if(m_uiMaxSendRate+m_uiMaxFlowRate == 0) return uiSendBytes;
MDB_UINT32 uiRet = uiSendBytes;
MDB_UINT32 uiMaxSendRate = m_uiMaxSendRate;
if(uiMaxSendRate > 0)
{
MDB_UINT32 uiTrafficSendBytes = pTrafficInfo->GetCurSecSendBytes();
if(uiTrafficSendBytes >= uiMaxSendRate)
{
return 0;
}
else if(uiRet+uiTrafficSendBytes > uiMaxSendRate)
{
uiRet = uiMaxSendRate-uiTrafficSendBytes;
}
}
MDB_UINT32 uiMaxFlowRate = m_uiMaxFlowRate;
if(uiMaxFlowRate > 0)
{
MDB_UINT32 uiTrafficTotalBytes = pTrafficInfo->GetCurSecTotalBytes();
if(uiTrafficTotalBytes >= uiMaxFlowRate)
{
return 0;
}
else if(uiRet+uiTrafficTotalBytes > uiMaxFlowRate)
{
uiRet = uiMaxFlowRate-uiTrafficTotalBytes;
}
}
return uiRet;
}
struct TMdbPeerEventMonitor:public TMdbNtcBaseObject
{
TMdbSharedPtr<TMdbPeerInfo> pPeerInfo;
MDB_UINT16 events;
};
//TMdbNtcQueue TMdbTrafficCtrl::g_oSuspendMonitorPeerQueue(true, false);
TMdbNtcQueue TMdbTrafficCtrl::g_oSuspendMonitorPeerQueue;
void TMdbTrafficCtrl::ResumePeerTraffic()
{
if(!TMdbTrafficCtrl::g_oSuspendMonitorPeerQueue.IsEmpty())
{
static TMdbPeerProactor* ppPeerProactor[1024]={NULL};
TMdbPeerEventMonitor* pEventMonitor = NULL;
int iCount = 0;
do
{
pEventMonitor = static_cast<TMdbPeerEventMonitor*>(TMdbTrafficCtrl::g_oSuspendMonitorPeerQueue.Pop());
if(pEventMonitor == NULL) break;
pEventMonitor->pPeerInfo->AddEventMonitor(pEventMonitor->events);
TMdbPeerProactor* pPeerProactor = pEventMonitor->pPeerInfo->pPeerProactor;
if(pPeerProactor)
{
delete pEventMonitor;
pEventMonitor = NULL;
for(int i = 0; i < iCount; ++i)
{
if(pPeerProactor == ppPeerProactor[i])
{
pPeerProactor = NULL;
break;
}
}
if(pPeerProactor)
{
ppPeerProactor[iCount++] = pPeerProactor;
}
}
}while(1);
//将牵扯到的前摄器都唤醒
for (int i = 0; i < iCount; ++i)
{
ppPeerProactor[i]->Wakeup();
}
}
}
void TMdbTrafficCtrl::SuspendPeerTraffic(TMdbSharedPtr<TMdbPeerInfo>& pPeerInfo, MDB_UINT16 events)
{
TMdbPeerEventMonitor* pEventMonitor = new TMdbPeerEventMonitor;
pEventMonitor->pPeerInfo = pPeerInfo;
pEventMonitor->events = events;
g_oSuspendMonitorPeerQueue.Push(pEventMonitor);
}
TMdbNtcThreadLock TMdbPacketInfo::ms_oSpinLock;
MDB_ZF_IMPLEMENT_OBJECT(TMdbPacketInfo, TMdbNtcBaseObject);
TMdbPacketInfo::TMdbPacketInfo(MDB_UINT32 uiLength /* = 0 */)
{
uiOffset = 0;
m_pcData = NULL;
this->uiLength = uiLength;
if(uiLength > 0)
{
AllocBuffer(uiLength);
}
}
TMdbPacketInfo::TMdbPacketInfo(char* pcBuffer, MDB_UINT32 uiLength /* = -1 */)
{
m_pcData = NULL;
this->uiLength = 0;
uiOffset = 0;
if(uiLength == (MDB_UINT32)-1)
{
uiLength = (MDB_UINT32)strlen(pcBuffer);
}
if(uiLength > 0)
{
char* pcDataBuffer = AllocBuffer(uiLength);
if(pcBuffer)
{
memcpy(pcDataBuffer, pcBuffer, uiLength);
}
}
}
TMdbPacketInfo::TMdbPacketInfo(TMdbPacketInfo& oPacketInfo, MDB_UINT32 uiLength /* = -1 */)
{
uiOffset = 0;
m_pcData = NULL;
this->uiLength = uiLength;
Attach(oPacketInfo, uiLength);
}
void TMdbPacketInfo::Attach(TMdbPacketInfo& oPacketInfo, MDB_UINT32 uiLength /* = -1 */)
{
Detach();
m_pcData = oPacketInfo.AddRef();
uiOffset = oPacketInfo.uiOffset;
if(uiLength == (MDB_UINT32)-1)
{
this->uiLength = oPacketInfo.uiLength;
}
else
{
//iOffset = ((TPacketData*)oPacketInfo.pcData)->iLength-oPacketInfo.iLength-oPacketInfo.iOffset;
this->uiLength = uiLength;
}
}
char* TMdbPacketInfo::AllocBuffer(MDB_UINT32 uiLength)
{
if(m_pcData)
{
Detach();
}
m_pcData = new char[uiLength+sizeof(TPacketData)+1];
memset(m_pcData, 0x00, uiLength+sizeof(TPacketData));
m_pcData[uiLength+sizeof(TPacketData)] = '\0';
AddRef();
this->uiLength = uiLength;
uiOffset = 0;
return GetBuffer();
}
void TMdbPacketInfo::Detach()
{
if(m_pcData)
{
ms_oSpinLock.Lock();
MDB_UINT32 uiRefcnt = --reinterpret_cast<TPacketData*>(m_pcData)->uiRefcnt;
ms_oSpinLock.Unlock();
TADD_DETAIL("Detach[%p] ref_cnt:%d", m_pcData, uiRefcnt);
if(uiRefcnt != 0)
{
m_pcData = NULL;
}
else
{
delete []m_pcData;
m_pcData = NULL;
}
}
}
MDB_ZF_IMPLEMENT_OBJECT(TMdbMsgInfo, TMdbNtcBaseObject);
TMdbMsgInfo::TMdbMsgInfo(MDB_UINT32 uiLength /* = 0 */)
:oPacketInfo(uiLength)
{
m_uiRefcnt = 1;
m_uiHeadLength = 0;
}
TMdbRecvPackets::TMdbRecvPackets()
{
m_uiTotalLength = 0;
uiSplicedLength = 0;
pSplicingMsg = NULL;
SetAutoRelease(true);
}
TMdbRecvPackets::~TMdbRecvPackets()
{
Clear();
if(pSplicingMsg)
{
pSplicingMsg->Release();
pSplicingMsg = NULL;
}
}
bool TMdbRecvPackets::SplicePacket(MDB_UINT32 uiLength, TMdbPacketInfo& oPacketInfo)
{
if(m_uiTotalLength < uiLength)
{
return false;
}
char* pcBuffer = NULL;
MDB_UINT32 uiCurLength = 0;
if(oPacketInfo.uiLength <= uiLength)
{
pcBuffer = oPacketInfo.AllocBuffer(oPacketInfo.uiLength);
}
else
{
uiCurLength = oPacketInfo.uiLength-uiLength;
pcBuffer = oPacketInfo.GetBuffer();
}
TMdbPacketInfo* pPacketInfo = NULL;
while(m_pHeadNode)
{
pPacketInfo = static_cast<TMdbPacketInfo*>(m_pHeadNode->pData);
if(pPacketInfo == NULL) break;
if((MDB_UINT32)uiCurLength+pPacketInfo->uiLength >= oPacketInfo.uiLength)
{
MDB_UINT32 uiCopyLength = oPacketInfo.uiLength-uiCurLength;
if(uiCurLength == 0)//表示目标packet可以复用当前包
{
oPacketInfo.Attach(*pPacketInfo, uiLength);
}
else//进行部分拷贝到目标packet
{
memcpy(pcBuffer+uiCurLength, pPacketInfo->GetBuffer(), uiCopyLength);
}
pPacketInfo->uiLength -= uiCopyLength;
pPacketInfo->uiOffset += uiCopyLength;
m_uiTotalLength -= uiCopyLength;
if(pPacketInfo->uiLength == 0)
{
TMdbNtcBaseList::RemoveHead();
}
break;
}
else//当前包不足以拼接成目标packet
{
memcpy(pcBuffer+uiCurLength, pPacketInfo->GetBuffer(), pPacketInfo->uiLength);
uiCurLength += pPacketInfo->uiLength;
m_uiTotalLength -= pPacketInfo->uiLength;
//删除当前数据包
TMdbNtcBaseList::RemoveHead();
}
}
return true;
}
TMdbSendPackets::TMdbSendPackets()
{
iSendBytes = 0;
SetAutoRelease(true);
}
TMdbSendPackets::~TMdbSendPackets()
{
Clear();
}
MDB_ZF_IMPLEMENT_OBJECT(TMdbServerInfo, TMdbNtcServerSocket)
TMdbServerInfo::TMdbServerInfo(const char* pszServerHost /* = NULL */, int iServerPort /* = 0 */,
TMdbProtocol* pProtocol /* = NULL */, const TMdbRuntimeObject* pPeerRuntimeObject /* = NULL */)
{
if(pszServerHost)
{
m_sServerHost = pszServerHost;
}
m_iServerPort = iServerPort;
this->pProtocol = pProtocol;
this->pPeerProactor = NULL;
this->pProactorInfo = NULL;
this->pPeerRuntimeObject = pPeerRuntimeObject;
}
TMdbServerInfo::~TMdbServerInfo()
{
if(pProtocol)
{
delete pProtocol;
pProtocol = NULL;
}
if(pProactorInfo)
{
delete pProactorInfo;
pProactorInfo = NULL;
}
}
bool TMdbServerInfo::AddEventMonitor(MDB_UINT16 events)
{
//如果是前摄器线程,则无需唤醒前摄器以触发更新
if(pPeerProactor->GetThreadHandle() == mdb_ntc_zthread_handle())
{
return pPeerProactor->AddEventMonitor(m_uiSocketID, events);
}
else
{
return pPeerProactor->AsyncAddEventMonitor(m_uiSocketID, events);
}
}
bool TMdbServerInfo::RemoveEventMonitor(MDB_UINT16 events)
{
//如果是前摄器线程,则无需唤醒前摄器以触发更新
if(pPeerProactor->GetThreadHandle() == mdb_ntc_zthread_handle())
{
return pPeerProactor->RemoveEventMonitor(m_uiSocketID, events);
}
else
{
return pPeerProactor->AsyncRemoveEventMonitor(m_uiSocketID, events);
}
}
TMdbPeerHelper::TMdbPeerHelper(TMdbPeerInfo* pPeerInfo)
{
this->pPeerInfo = pPeerInfo;
}
TMdbPeerHelper::~TMdbPeerHelper()
{
}
MDB_ZF_IMPLEMENT_DYNCREATE_OBJECT(TMdbPeerInfo, TMdbNtcSocket);
TMdbPeerInfo::TMdbPeerInfo()
{
pno = 0;
pProactorInfo = NULL;
pPeerProactor = NULL;
pServerInfo = NULL;
pCurEventPump = NULL;
m_uiPeerFlag = 0;
m_tConnectime = time(NULL);
m_pTrafficCtrl = NULL;
m_pPeerHelper = NULL;
pProtocol = NULL;
memset(&m_uiTimerID, 0x00, sizeof(m_uiTimerID));//重置为0
memset(&m_uiMaxIdleTime, 0x00, sizeof(m_uiMaxIdleTime));//重置为0
SetPeerState(MDB_NTC_PEER_IDLE_STATE);
m_pRecvMsgQueue = NULL;
}
void TMdbPeerInfo::Init(QuickMDB_SOCKET uiSocketID , TMdbServerInfo* pServerInfo /* = NULL */)
{
this->m_uiSocketID = uiSocketID;
this->pServerInfo = pServerInfo;
pProtocol = pServerInfo?pServerInfo->pProtocol:NULL;
}
TMdbPeerInfo::~TMdbPeerInfo()
{
if(IsClient())//说明是connect方式,需要连同一起销毁
{
delete pServerInfo;
pServerInfo = NULL;
}
if(pProactorInfo)
{
delete pProactorInfo;
pProactorInfo = NULL;
}
for (int i = 0; i < MDB_NTC_MAX_IDLE_TIMEOUT_TYPE; ++i)
{
if(m_uiTimerID[i] > 0)
{
TMdbNtcCheckPeerTimeout* pCheckIdlePeer = NULL;
TMdbNtcTimerManager::DelTimerById(m_uiTimerID[i], (void**)&pCheckIdlePeer);
if(pCheckIdlePeer)
{
delete pCheckIdlePeer;
pCheckIdlePeer = NULL;
}
m_uiTimerID[i] = 0;
}
}
if(m_pPeerHelper)
{
delete m_pPeerHelper;
m_pPeerHelper = NULL;
}
if(m_pRecvMsgQueue)
{
ClearRecvMessage();
delete m_pRecvMsgQueue;
m_pRecvMsgQueue = NULL;
}
}
bool TMdbPeerInfo::SpliceMsg()
{
if(oRecvPackets.pSplicingMsg && (oRecvPackets.pSplicingMsg->GetLength() == oRecvPackets.uiSplicedLength
|| oRecvPackets.SplicePacket(oRecvPackets.pSplicingMsg->GetLength()-oRecvPackets.uiSplicedLength, oRecvPackets.pSplicingMsg->oPacketInfo)))
{
m_oTrafficInfo.AddRecvMsgNum();
TMdbMsgInfo* pSplicingMsg = oRecvPackets.pSplicingMsg;
oRecvPackets.pSplicingMsg = NULL;
oRecvPackets.uiSplicedLength = 0;
if(pProtocol == NULL || (!pProtocol->PreTranslateMessage(this, pSplicingMsg) && pSplicingMsg))
{
pPeerProactor->GetEventDispatcher()->Dispatch(new TMdbRecvMsgEvent(this, pSplicingMsg));
}
else if(pSplicingMsg)
{
pSplicingMsg->Release();
}
return true;
}
else
{
return false;
}
}
void TMdbPeerInfo::CheckRecvPackets()
{
/*if((oRecvPackets.pSplicingMsg == NULL || (SpliceMsg() && !IsShutdown())) && pProtocol)
{
}*/
if( NULL == pProtocol )
{
return ;
}
if( (oRecvPackets.pSplicingMsg == NULL)
|| ( SpliceMsg() && !IsShutdown())
)
{
pProtocol->CheckPackets(this);
}
}
void TMdbPeerInfo::SetMaxRecvRate(MDB_UINT32 uiMaxRecvRate)
{
m_oSpinLock.Lock();
if(m_pTrafficCtrl == NULL)
{
m_pTrafficCtrl = new TMdbTrafficCtrl;
}
m_pTrafficCtrl->SetMaxRecvRate(uiMaxRecvRate);
m_oSpinLock.Unlock();
}
void TMdbPeerInfo::SetMaxSendRate(MDB_UINT32 uiMaxSendRate)
{
m_oSpinLock.Lock();
if(m_pTrafficCtrl == NULL)
{
m_pTrafficCtrl = new TMdbTrafficCtrl;
}
m_pTrafficCtrl->SetMaxSendRate(uiMaxSendRate);
m_oSpinLock.Unlock();
}
void TMdbPeerInfo::SetMaxFlowRate(MDB_UINT32 uiMaxFlowRate)
{
m_oSpinLock.Lock();
if(m_pTrafficCtrl == NULL)
{
m_pTrafficCtrl = new TMdbTrafficCtrl;
}
m_pTrafficCtrl->SetMaxFlowRate(uiMaxFlowRate);
m_oSpinLock.Unlock();
}
void TMdbPeerInfo::SetPeerTimeout(MDB_NTC_PEER_TIMEOUT_TYPE eTimeoutType, MDB_UINT32 uiSeconds)
{
if(m_uiMaxIdleTime[eTimeoutType] == uiSeconds && m_uiTimerID[eTimeoutType] > 0) return;
//先杀掉之前的
if(m_uiTimerID[eTimeoutType] != 0)
{
TMdbNtcCheckPeerTimeout* pCheckIdlePeer = NULL;
TMdbNtcTimerManager::DelTimerById(m_uiTimerID[eTimeoutType], (void**)&pCheckIdlePeer);
if(pCheckIdlePeer)
{
delete pCheckIdlePeer;
pCheckIdlePeer = NULL;
}
m_uiTimerID[eTimeoutType] = 0;
}
m_uiMaxIdleTime[eTimeoutType] = uiSeconds;
if(uiSeconds > 0 && pPeerProactor)
{
TMdbNtcCheckPeerTimeout* pCheckIdlePeer = new TMdbNtcCheckPeerTimeout;
pCheckIdlePeer->pEventDispatcher = pPeerProactor->GetEventDispatcher();
pCheckIdlePeer->pPeerInfo = this;
pCheckIdlePeer->uiSeconds = uiSeconds;
pCheckIdlePeer->eTimeoutType = eTimeoutType;
m_uiTimerID[eTimeoutType] = MdbNtcAddTimer("", false, uiSeconds*10, CheckPeerTimeout, pCheckIdlePeer);
}
}
void TMdbPeerInfo::CheckPeerTimeout(void* pArg)
{
TMdbNtcCheckPeerTimeout* pCheckPeerTimeout = static_cast<TMdbNtcCheckPeerTimeout*>(pArg);
TMdbPeerInfo* pPeerInfo = pCheckPeerTimeout->pPeerInfo;
time_t tRecentTime = pPeerInfo->GetConnectTime();
if((pCheckPeerTimeout->eTimeoutType == MDB_NTC_DATA_IDLE_TIMEOUT || pCheckPeerTimeout->eTimeoutType == MDB_NTC_RECV_IDLE_TIMEOUT)
&& pPeerInfo->GetLastRecvTime() != -1 && pPeerInfo->GetLastRecvTime() > tRecentTime)
{
tRecentTime = pPeerInfo->GetLastRecvTime();
}
if((pCheckPeerTimeout->eTimeoutType == MDB_NTC_DATA_IDLE_TIMEOUT || pCheckPeerTimeout->eTimeoutType == MDB_NTC_SEND_IDLE_TIMEOUT)
&& pPeerInfo->GetLastSendTime() != -1 && pPeerInfo->GetLastSendTime() > tRecentTime)
{
tRecentTime = pPeerInfo->GetLastSendTime();
}
int iElapseSeconds = (int)(time(NULL)-tRecentTime), iNewTimerSeconds = (int)pCheckPeerTimeout->uiSeconds;
if(iElapseSeconds >= (int)pCheckPeerTimeout->uiSeconds)
{
pPeerInfo->SetTimeoutId(pCheckPeerTimeout->eTimeoutType, (MDB_UINT32)-1);
if(pPeerInfo->IsShutdown())
{
delete pCheckPeerTimeout;
pCheckPeerTimeout = NULL;
return;
}
else
{
//触发一个空闲超时的事件
TMdbTimeoutEvent* pTimeoutEvent = new TMdbTimeoutEvent(pPeerInfo, pCheckPeerTimeout->eTimeoutType);
pCheckPeerTimeout->pEventDispatcher->Dispatch(pTimeoutEvent);
}
}
else
{
iNewTimerSeconds = (int)(pCheckPeerTimeout->uiSeconds-(MDB_UINT32)iElapseSeconds);
}
//重新压入一个定时器
pPeerInfo->SetTimeoutId(pCheckPeerTimeout->eTimeoutType, (MDB_UINT32)MdbNtcAddTimer("", false, (MDB_UINT32)iNewTimerSeconds*10, CheckPeerTimeout, pCheckPeerTimeout));
}
bool TMdbPeerInfo::AddEventMonitor(MDB_UINT16 events, bool bLock /* = true */)
{
if(pPeerProactor == NULL) return false;
bool bRet = true;
if(bLock)
{
m_oSpinLock.Lock();
}
if(!IsShutdown() && (events == 0 || GetPeerFlag(events) != events))//只要任一个指定的事件不存在,则需要添加
{
TADD_DETAIL("add event:peer[%d],flag[%0x],event[%0x]", m_uiSocketID, m_uiPeerFlag, events);
SetPeerFlag(events);
//如果是前摄器线程,则无需唤醒前摄器以触发更新
if(pPeerProactor->GetThreadHandle() == mdb_ntc_zthread_handle())
{
bRet = pPeerProactor->AddEventMonitor(m_uiSocketID, events);
}
else
{
bRet = pPeerProactor->AsyncAddEventMonitor(m_uiSocketID, events);
}
}
else
{
TADD_DETAIL("no need to add event:peer[%d],flag[%0x],event[%0x]", m_uiSocketID, m_uiPeerFlag, events);
}
if(bLock)
{
m_oSpinLock.Unlock();
}
return bRet;
}
bool TMdbPeerInfo::RemoveEventMonitor(MDB_UINT16 events, bool bLock /* = true */)
{
if(pPeerProactor == NULL) return false;
bool bRet = true;
if(bLock)
{
m_oSpinLock.Lock();
}
if(events == 0 || GetPeerFlag(events))//只要任一个指定的事件存在,则需要移除
{
TADD_DETAIL("remove event:peer[%d],flag[%0x],event[%0x]", m_uiSocketID, m_uiPeerFlag, events);
if(events == 0)
{
ClearPeerFlag((MDB_UINT16)((MDB_NTC_PEER_EV_READ_FLAG|MDB_NTC_PEER_EV_WRITE_FLAG)&m_uiPeerFlag));
bRet = pPeerProactor->AsyncRemoveEventMonitor(m_uiSocketID, events);
}
else
{
ClearPeerFlag(events);
//如果是前摄器线程,则无需唤醒前摄器以触发更新
if(pPeerProactor->GetThreadHandle() == mdb_ntc_zthread_handle())
{
bRet = pPeerProactor->RemoveEventMonitor(m_uiSocketID, events);
}
else
{
bRet = pPeerProactor->AsyncRemoveEventMonitor(m_uiSocketID, events);
}
}
}
else
{
TADD_DETAIL("no need to remove event:peer[%d],flag[%0x],event[%0x]", m_uiSocketID, m_uiPeerFlag, events);
}
if(bLock)
{
m_oSpinLock.Unlock();
}
return bRet;
}
bool TMdbPeerInfo::Shutdown()
{
bool bRet = true;
m_oSpinLock.Lock();
if((m_uiPeerFlag&MDB_NTC_PEER_SHUTDOWN_FLAG) == 0)
{
m_uiPeerFlag |= MDB_NTC_PEER_SHUTDOWN_FLAG;
}
else
{
bRet = false;
}
m_oSpinLock.Unlock();
return bRet;
}
bool TMdbPeerInfo::Disconnect(TMdbNtcStringBuffer sReason /* = "" */, bool bPasvClose /* = false */)
{
bool bRet = Shutdown();
if(bRet)
{
TADD_DETAIL("fd[%u], disconnect %s", m_uiSocketID, sReason.c_str());
for (int i = 0; i < MDB_NTC_MAX_IDLE_TIMEOUT_TYPE; ++i)
{
if(m_uiTimerID[i] > 0)
{
TMdbNtcCheckPeerTimeout* pCheckIdlePeer = NULL;
TMdbNtcTimerManager::DelTimerById(m_uiTimerID[i], (void**)&pCheckIdlePeer);
if(pCheckIdlePeer)
{
delete pCheckIdlePeer;
pCheckIdlePeer = NULL;
}
m_uiTimerID[i] = 0;
}
}
sDisconnectReason = sReason;
if(bPasvClose)
{
this->SetPeerFlag(MDB_NTC_PEER_PASV_CLOSE_FLAG);
}
if(pPeerProactor)
{
RemoveEventMonitor(0);
}
}
return bRet;
}
void TMdbPeerInfo::DeleteTrafficCtrl()
{
m_oSpinLock.Lock();
if(m_pTrafficCtrl == NULL)
{
delete m_pTrafficCtrl;
m_pTrafficCtrl = NULL;
}
m_oSpinLock.Unlock();
}
void TMdbPeerInfo::SetMsgHandleMode(bool bDetached)
{
TMdbNtcAutoLock oAutoLock(&m_oSpinLock);
if(bDetached)
{
m_uiPeerFlag = (MDB_UINT16)(m_uiPeerFlag|MDB_NTC_PEER_MSG_DETACHED_FLAG);
if(m_pRecvMsgQueue == NULL) m_pRecvMsgQueue = new TMdbNtcQueue;
}
else
{
m_uiPeerFlag = (MDB_UINT16)(m_uiPeerFlag&(~MDB_NTC_PEER_MSG_DETACHED_FLAG));
if(m_pRecvMsgQueue == NULL) return;
do
{
TMdbMsgInfo* pMsgInfo = static_cast<TMdbMsgInfo*>(m_pRecvMsgQueue->Pop(0));
if(pMsgInfo == NULL) break;
this->GetEventDispatcher()->Dispatch(new TMdbRecvMsgEvent(this, pMsgInfo));
} while (1);
m_pRecvMsgQueue->Wakeup();
}
}
int TMdbPeerInfo::SendMessage(const void* pszMsg, MDB_UINT32 uiMsgLength /* = -1 */, int iMilliSeconds /* = -1 */)
{
int iSendBytes = 0;
/*
TMdbNtcSocketSendEvent* pSocketSendEvent = new TMdbNtcSocketSendEvent(this, pszMsg, iMsgLength);
do
{
if(IsShutdown())
{
iRet = -1;
break;
}
TMdbNtcSocketInfo* pSocketInfo = static_cast<TMdbNtcSocketInfo*>(this);
//根据send事件判断适合的事件泵
TMdbEventPump* pAdaptiveEventPump = PreDispatch(pSocketSendEvent);
if(pAdaptiveEventPump == NULL)
{
iRet = -1;
break;
}
pSocketSendEvent->AddRef();//当前保留计数,使得处理过程中不会delete
if(pAdaptiveEventPump->GetThreadHandle() == GetCurrentThreadHandle())
{
pSocketInfo->queueSendEvent.Push(pSocketSendEvent);//加入到socketinfo的队列中
//如果当前线程就是事件泵线程,则直接调用发送
iRet = DealSocketSendTask(pSocketInfo, iMilliSeconds, pSocketSendEvent);
}
else
{
//其他线程处理此事件,则当前线程等待
if(g_pSendThreadEvent == NULL)
{
g_pSendThreadEvent = new TMdbNtcThreadEvent;
}
pSocketSendEvent->pSendThreadEvent = g_pSendThreadEvent;
//将事件放到定时器线程中,iMilliSeconds,超时触发g_pThreadEvent
pSocketInfo->queueSendEvent.Push(pSocketSendEvent);//加入到socketinfo的队列中
//发起ev_write事件的监听
if(pSocketInfo->queueSendEvent.GetSize() == 1)
{
AddEventMonitor(pSocketSendEvent->pPeerInfo, MDB_NTC_PEER_EV_WRITE_FLAG);
}
//等待事件触发
g_pSendThreadEvent->Wait(iMilliSeconds);
}
iSendBytes = pSocketSendEvent->iSendBytes;
} while (0);
pSocketSendEvent->Release(iRet);
*/
return iSendBytes;
}
bool TMdbPeerInfo::PostMessage(const void* pMsg, MDB_UINT32 uiMsgLength /* = -1 */)
{
bool bRet = true;
if(uiMsgLength == (MDB_UINT32)-1) uiMsgLength = (MDB_UINT32)strlen((const char*)pMsg);
if(uiMsgLength == 0) return bRet;
TMdbPacketInfo* pPacketInfo = new TMdbPacketInfo(uiMsgLength);
memcpy(pPacketInfo->GetBuffer(), pMsg, uiMsgLength);
bRet = PostMessage(pPacketInfo);
if(bRet == false)
{
delete pPacketInfo;
pPacketInfo = NULL;
}
return bRet;
}
bool TMdbPeerInfo::PostMessage(TMdbPacketInfo* pPacketInfo)
{
if(IsShutdown())
{
mdb_ntc_errstr = "peer is already shutdown";
return false;
}
//pSocketEvent->AddRef();//将事件放到定时器线程中
oSendPackets.Push(pPacketInfo);//加入到socketinfo的队列中
//发起ev_write事件的监听
TADD_DETAIL("PostMessage:fd[%d],queueSendEvent[%u]", m_uiSocketID, oSendPackets.GetSize());
if(oSendPackets.GetSize() == 1)
{
this->AddEventMonitor(MDB_NTC_PEER_EV_WRITE_FLAG);
}
return true;
}
void TMdbPeerInfo::ClearRecvMessage()
{
if(m_pRecvMsgQueue)
{
do
{
TMdbMsgInfo* pMsgInfo = static_cast<TMdbMsgInfo*>(m_pRecvMsgQueue->Pop(0));
if(pMsgInfo == NULL) break;
else pMsgInfo->Release();
} while (1);
}
}
MDB_UINT32 MdbNtcAddTimer(const char *ATimerName,bool ALoopFlag,MDB_UINT32 ACount100ms,OnMdbEventFunc AEventFunc,void *pFuncParam)
{
TMdbNtcTimerManager::Initialize(false);
char szBuffer[11] = {'\0'};
for (int i = 0; i < 10; ++i)
{
szBuffer[i] = (char)('a'+rand()%26);
}
return TMdbNtcTimerManager::AddRelativeTimer(szBuffer, ALoopFlag, ACount100ms, AEventFunc, pFuncParam);
}
//_NTC_END
//}
| [
"974533812@qq.com"
] | 974533812@qq.com |
fa99a39530db8e06f92a683b6712b683a10065ee | 341caf2d6396c8820fcab3e81edbd3a020e3bf24 | /Src/IEUtility/IEFileLINUX.hpp | dd087d47ba5ef4b7512844bfd4658be4f76efe4e | [
"MIT"
] | permissive | yalcinerbora/indiengine | 057189a3d7be1aa17b3db224a040005af9a89aea | ff73025a2ac5aff8638fb1bd4f5508426af666bd | refs/heads/master | 2020-05-17T17:45:33.775739 | 2016-01-20T15:29:02 | 2016-01-20T15:29:02 | 22,794,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,382 | hpp | // LINUX Kernel API Implementation of IE File Class
// API Required Portions of the code is here
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <limits.h>
#define COPY_BUFFER_SIZE 8 * 1024
static IEFileErrorType LinuxErrorToIE(int r)
{
switch(r)
{
case ENOENT:
return IEFileErrorType::FILE_NOT_EXISTS;
break;
case EEXIST:
return IEFileErrorType::FILE_EXISTS;
break;
case EACCES:
case EAGAIN:
case EROFS:
return IEFileErrorType::PERMISSION_ERROR;
break;
// File Path Syntax Errors (You provide unrecognized charater etc..)
case ENAMETOOLONG:
return IEFileErrorType::PATH_SYNTAX_ERROR;
break;
default:
IE_ERROR("Platform Linux Error Code For Fatal Error : %d", r);
DEBUG("Error String %s \n", strerror(r));
return IEFileErrorType::FATAL_ERROR;
break;
}
}
static int IEActionTypeToLinux(IEFileActionType type)
{
static int values[] =
{
O_CREAT | O_EXCL,
O_TRUNC,
O_CREAT,
0,
O_CREAT
};
return values[static_cast<int>(type)];
}
static int IEAccessTypeToLinux(IEFileAccessType type)
{
static int values[] =
{
O_RDONLY,
O_WRONLY,
O_RDWR
};
return values[static_cast<int>(type)];
}
static int IEHintTypeToLinux(IEFileAccessHintType type)
{
static int values[] =
{
POSIX_FADV_NORMAL,
POSIX_FADV_SEQUENTIAL
};
return values[static_cast<int>(type)];
}
static int IEShareTypeToLinux(IEFileShareType type)
{
static int values[] =
{
LOCK_EX, // Exclusive Lock
LOCK_SH, // Shared Lock ()
LOCK_SH, // Shared Lock (Linux Does not have shared write only access)
0, // No Lock
};
return values[static_cast<int>(type)];
}
// Platform Specific
// File Access
template<unsigned int N>
template<unsigned int S>
IEFileErrorType IEFile<N>::Open(const IEFilePath<S>& path,
IEFileActionType action,
IEFileAccessType access,
IEFileShareType share,
IEFileAccessHintType hint)
{
if(fileOpened)
return IEFileErrorType::ALREADY_OPENED_A_FILE;
// Logical Errors That can be related
if(access == IEFileAccessType::READ &&
(action == IEFileActionType::OVERWRITE ||
action == IEFileActionType::CREATE_FORCE ||
action == IEFileActionType::CREATE))
{
return IEFileErrorType::CANT_READ_NEW_FILE;
}
// OPEN The FILE!
handle = open(path.Data(),
IEAccessTypeToLinux(access) |
IEActionTypeToLinux(action),
S_IRWXU);
if(handle < 0)
{
return LinuxErrorToIE(errno);
}
// POSIX Sequential Stuff
if(int error = posix_fadvise(handle, 0, 0, IEHintTypeToLinux(hint)))
{
close(handle); // Dont Check This Error, we're fucked already
return LinuxErrorToIE(error);
}
// Lock the File
int shareType = IEShareTypeToLinux(share);
if(shareType != 0 &&
flock(handle, shareType | LOCK_NB) < 0)
{
close(handle);
return LinuxErrorToIE(errno);
}
// Get File Size
struct stat fileStats;
if(fstat(handle, &fileStats) < 0)
{
return LinuxErrorToIE(errno);
}
// Populate Properties of the Class
fileOpened = true;
fileName = path.template GetLastS<N>();
fileSize = static_cast<IEUInt64>(fileStats.st_size);
eofReached = false;
// All Cool
return IEFileErrorType::OK;
}
template<unsigned int N>
IEFileErrorType IEFile<N>::Close()
{
if(fileOpened &&
close(handle) < 0)
{
return LinuxErrorToIE(errno);
}
fileOpened = false;
eofReached = true;
return IEFileErrorType::OK;
}
template<unsigned int N>
IEFileErrorType IEFile<N>::Read(IEByte buffer[], IEUInt32& actualAmount, IEUInt32 requestedAmount)
{
actualAmount = read(handle, buffer, requestedAmount);
if(actualAmount < 0)
{
return LinuxErrorToIE(errno);
}
if(actualAmount == 0)
{
eofReached = true;
}
return IEFileErrorType::OK;
}
template<unsigned int N>
IEFileErrorType IEFile<N>::ReadAll(IEByte buffer[])
{
ssize_t actualWritten = 0;
IEByte* bufferSegment = buffer;
IESize remainingFile = fileSize;
size_t readAmount;
do
{
if(remainingFile > SSIZE_MAX)
readAmount = SSIZE_MAX;
else
readAmount = static_cast<IEUInt32>(remainingFile);
// Do Read
actualWritten = read(handle,
bufferSegment,
readAmount);
if(actualWritten < 0)
{
return LinuxErrorToIE(errno);
}
remainingFile -= actualWritten;
bufferSegment += actualWritten;
}
while(remainingFile != 0);
eofReached = true;
return IEFileErrorType::OK;
}
template<unsigned int N>
IEFileErrorType IEFile<N>::Write(IEUInt32& actualAmount, const IEByte buffer[], IEUInt32 requestedAmount)
{
actualAmount = write(handle, buffer, requestedAmount);
if(actualAmount < 0)
{
return LinuxErrorToIE(errno);
}
return IEFileErrorType::OK;
}
// Static Functions
template<unsigned int N>
template<unsigned int S>
IEFileErrorType IEFile<N>::Delete(const IEFilePath<S>& path)
{
if(remove(path.Data()) < 0)
{
return LinuxErrorToIE(errno);
}
return IEFileErrorType::OK;
}
template<unsigned int N>
template<unsigned int S, unsigned int T>
IEFileErrorType IEFile<N>::Copy(const IEFilePath<S>& newFile, const IEFilePath<T>& existingFile)
{
IEFile<> f1, f2;
// Use IEFile Here Linux one is kinda long
IEFileErrorType err;
err = f1.Open(newFile,
IEFileActionType::CREATE,
IEFileAccessType::WRITE,
IEFileShareType::CONSERVATIVE);
if(err != IEFileErrorType::OK)
{
return err;
}
err = f2.Open(existingFile,
IEFileActionType::ACCESS,
IEFileAccessType::READ,
IEFileShareType::CONSERVATIVE);
if(err != IEFileErrorType::OK)
{
f1.Close();
IEFile<>::Delete(newFile);
return err;
}
// Pre allocate
if(int errorNo = posix_fallocate(f1.handle, 0, f2.fileSize))
{
f1.Close();
IEFile<>::Delete(newFile);
return LinuxErrorToIE(errorNo);
}
// Read to buffer write to buffer
IEByte* buffer[COPY_BUFFER_SIZE];
ssize_t actualWritten = 0;
size_t readAmount;
IESize remainingFile = f2.fileSize;
do
{
if(remainingFile > COPY_BUFFER_SIZE)
readAmount = COPY_BUFFER_SIZE;
else
readAmount = static_cast<IEUInt32>(remainingFile);
// Do Read
actualWritten = read(f2.handle,
buffer,
readAmount);
if(actualWritten < 0)
{
f1.Close();
IEFile<>::Delete(newFile);
return LinuxErrorToIE(errno);
}
remainingFile -= actualWritten;
// Now Write
if(write(f1.handle, buffer, actualWritten) < 0)
{
f1.Close();
IEFile<>::Delete(newFile);
return LinuxErrorToIE(errno);
}
}
while(remainingFile != 0);
return IEFileErrorType::OK;
}
template<unsigned int N>
template<unsigned int S, unsigned int T>
IEFileErrorType IEFile<N>::Move(const IEFilePath<S>& newFile, const IEFilePath<T>& existingFile)
{
// We Need to check existence of the newFile since linux rename overwrites
struct stat buffer;
if(stat(newFile.Data(), &buffer) == 0)
{
return IEFileErrorType::FILE_EXISTS;
}
// Continue
if(rename(existingFile.Data(), newFile.Data()) < 0)
{
return LinuxErrorToIE(errno);
}
return IEFileErrorType::OK;
}
template<unsigned int N>
template<unsigned int S>
IEFileErrorType IEFile<N>::FileExists(const IEFilePath<S>& path)
{
struct stat buffer;
if(stat(path.Data(), &buffer) < 0)
{
return LinuxErrorToIE(errno);
}
return IEFileErrorType::FILE_EXISTS;
} | [
"yalciner.bora@metu.edu.tr"
] | yalciner.bora@metu.edu.tr |
91d4529bf1a3ba9a03fbb85a7d9c5fe933cfc1a3 | 474ca3fbc2b3513d92ed9531a9a99a2248ec7f63 | /ThirdParty/behavior/inc/behaviac/base/core/system.h | d23bb6599eed91b7e0c6063c0f3dc7230265f56b | [] | no_license | LazyPlanet/MX-Architecture | 17b7b2e6c730409b22b7f38633e7b1f16359d250 | 732a867a5db3ba0c716752bffaeb675ebdc13a60 | refs/heads/master | 2020-12-30T15:41:18.664826 | 2018-03-02T00:59:12 | 2018-03-02T00:59:12 | 91,156,170 | 4 | 0 | null | 2018-02-04T03:29:46 | 2017-05-13T07:05:52 | C++ | UTF-8 | C++ | false | false | 3,996 | h | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Description: System related services
//
////////////////////////////////////////////////////////////////////////////////
#ifndef BEHAVIAC_BASE_CORE_SYSTEM_H
#define BEHAVIAC_BASE_CORE_SYSTEM_H
#include "behaviac/base/core/config.h"
#include "behaviac/base/core/assert_t.h"
#define BEHAVIAC_HW_MEM_ALIGN 16
#define BEHAVIAC_SHADOW_SIZE_SPIN_LOCK 24
#define BEHAVIAC_SHADOW_SIZE_ADAPTIVE_LOCK 40
#define BEHAVIAC_CFG_THREADNAME_MAXLENGTH 64
#define BEHAVIAC_CFG_FILENAME_MAXLENGTH 255
#define BEHAVIAC_CFG_CLASSNAME_MAXLENGTH 200
#define BEHAVIAC_CFG_SETEXENAME_BUF_SIZE 256
namespace behaviac
{
/// This is the Low Level System function set
/// Sleep for a number of milliseconds.
/// \param timeMS time in milliseconds
BEHAVIAC_API void Sleep(uint32_t timeMS);
/// Yield the current thread execution to another.
BEHAVIAC_API void YieldCPU();
/// Get the current module ID
BEHAVIAC_API Address GetModuleID();
/// Get the name of the executable.
/// \param exeNameBuffer pointer to a buffer in which to store the executable name
/// \param exeNameBufferSize size of the buffer in which the data will be stored
BEHAVIAC_API const Char* GetExeName(Char* exeNameBuffer, uint32_t exeNameBufferSize);
/// Set the name of the executable.
/// \param exeNameBuffer pointer to the user provided buffer containing the exe name.
BEHAVIAC_API void SetExeName(const Char* exeNameBuffer);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// behaviac Zero-initializer templates
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This template class initializes any type to 0 (ptrs, POD, classes, ...)
// In the case of classes, the Default Constructor is called after zeroing the class members, so
// the default initialization of the members is still performed.
// Usage: TYPE variable = ZeroType<TYPE>();
/// The ZeroType template initializes any type to 0 (ptrs, POD, classes, ...)
template <typename TYPE>
class ZeroType
{
public:
ZeroType()
{
memset(shadow, 0, sizeof(TYPE));
var = new(shadow)TYPE;
}
ZeroType(const ZeroType& source)
{
memcpy(shadow, source.shadow, sizeof(TYPE));
var = unaliased_cast<TYPE*>(shadow);
}
operator TYPE& ()
{
return *var;
}
TYPE& operator= (const TYPE& source)
{
*var = source;
return *var;
}
private:
uint8_t shadow[sizeof(TYPE)];
TYPE* var;
};
}
#endif // #ifndef BEHAVIAC_BASE_CORE_SYSTEM_H
| [
"1211618464@qq.com"
] | 1211618464@qq.com |
a2f9d650852511f5f8520753f346fa1454fa3623 | 7c7ca9efe5869a805a3c5238425be185758a71ce | /marsksim/boost/parameter/aux_/arg_list.hpp | b8ed824c51ad8093c769c00025aa2a9e2900d7f2 | [] | no_license | cansou/MyCustomMars | f332e6a1332eed9184838200d21cd36f5b57d3c9 | fb62f268a1913a70c39df329ef39df6034baac60 | refs/heads/master | 2022-10-20T18:53:22.220235 | 2020-06-12T08:46:25 | 2020-06-12T08:46:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,243 | hpp | // Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
// distribution is subject to the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef ARG_LIST_050329_HPP
#define ARG_LIST_050329_HPP
#include <boost/parameter/aux_/void.hpp>
#include <boost/parameter/aux_/result_of0.hpp>
#include <boost/parameter/aux_/default.hpp>
#include <boost/parameter/aux_/parameter_requirements.hpp>
#include <boost/parameter/aux_/yesno.hpp>
#include <boost/parameter/aux_/is_maybe.hpp>
#include <boost/parameter/config.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/begin.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/iterator_tags.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/facilities/intercept.hpp>
namespace mars_boost_ksim {} namespace boost_ksim = mars_boost_ksim; namespace mars_boost_ksim { namespace parameter {
// Forward declaration for aux::arg_list, below.
template<class T> struct keyword;
namespace aux {
// Tag type passed to MPL lambda.
struct lambda_tag;
//
// Structures used to build the tuple of actual arguments. The
// tuple is a nested cons-style list of arg_list specializations
// terminated by an empty_arg_list.
//
// Each specialization of arg_list is derived from its successor in
// the list type. This feature is used along with using
// declarations to build member function overload sets that can
// match against keywords.
//
// MPL sequence support
struct arg_list_tag;
// Terminates arg_list<> and represents an empty list. Since this
// is just the terminating case you might want to look at arg_list
// first, to get a feel for what's really happening here.
struct empty_arg_list
{
empty_arg_list() {}
// Constructor taking BOOST_PARAMETER_MAX_ARITY empty_arg_list
// arguments; this makes initialization
empty_arg_list(
BOOST_PP_ENUM_PARAMS(
BOOST_PARAMETER_MAX_ARITY, void_ BOOST_PP_INTERCEPT
))
{}
// A metafunction class that, given a keyword and a default
// type, returns the appropriate result type for a keyword
// lookup given that default
struct binding
{
template<class KW, class Default, class Reference>
struct apply
{
typedef Default type;
};
};
// Terminator for has_key, indicating that the keyword is unique
template <class KW>
static no_tag has_key(KW*);
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
// The overload set technique doesn't work with these older
// compilers, so they need some explicit handholding.
// A metafunction class that, given a keyword, returns the type
// of the base sublist whose get() function can produce the
// value for that key
struct key_owner
{
template<class KW>
struct apply
{
typedef empty_arg_list type;
};
};
template <class K, class T>
T& get(default_<K,T> x) const
{
return x.value;
}
template <class K, class F>
typename result_of0<F>::type
get(lazy_default<K,F> x) const
{
return x.compute_default();
}
#endif
// If this function is called, it means there is no argument
// in the list that matches the supplied keyword. Just return
// the default value.
template <class K, class Default>
Default& operator[](default_<K, Default> x) const
{
return x.value;
}
// If this function is called, it means there is no argument
// in the list that matches the supplied keyword. Just evaluate
// and return the default value.
template <class K, class F>
typename result_of0<F>::type
operator[](
BOOST_PARAMETER_lazy_default_fallback<K,F> x) const
{
return x.compute_default();
}
// No argument corresponding to ParameterRequirements::key_type
// was found if we match this overload, so unless that parameter
// has a default, we indicate that the actual arguments don't
// match the function's requirements.
template <class ParameterRequirements, class ArgPack>
static typename ParameterRequirements::has_default
satisfies(ParameterRequirements*, ArgPack*);
// MPL sequence support
typedef empty_arg_list type; // convenience
typedef arg_list_tag tag; // For dispatching to sequence intrinsics
};
// Forward declaration for arg_list::operator,
template <class KW, class T>
struct tagged_argument;
template <class T>
struct get_reference
{
typedef typename T::reference type;
};
// A tuple of tagged arguments, terminated with empty_arg_list.
// Every TaggedArg is an instance of tagged_argument<>.
template <class TaggedArg, class Next = empty_arg_list>
struct arg_list : Next
{
typedef arg_list<TaggedArg,Next> self;
typedef typename TaggedArg::key_type key_type;
typedef typename is_maybe<typename TaggedArg::value_type>::type holds_maybe;
typedef typename mpl::eval_if<
holds_maybe
, get_reference<typename TaggedArg::value_type>
, get_reference<TaggedArg>
>::type reference;
typedef typename mpl::if_<
holds_maybe
, reference
, typename TaggedArg::value_type
>::type value_type;
TaggedArg arg; // Stores the argument
// Store the arguments in successive nodes of this list
template< // class A0, class A1, ...
BOOST_PP_ENUM_PARAMS(BOOST_PARAMETER_MAX_ARITY, class A)
>
arg_list( // A0& a0, A1& a1, ...
BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PARAMETER_MAX_ARITY, A, & a)
)
: Next( // a1, a2, ...
BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PARAMETER_MAX_ARITY, a)
, void_reference()
)
, arg(a0)
{}
// Create a new list by prepending arg to a copy of tail. Used
// when incrementally building this structure with the comma
// operator.
arg_list(TaggedArg head, Next const& tail)
: Next(tail)
, arg(head)
{}
// A metafunction class that, given a keyword and a default
// type, returns the appropriate result type for a keyword
// lookup given that default
struct binding
{
template <class KW, class Default, class Reference>
struct apply
{
typedef typename mpl::eval_if<
mars_boost_ksim::is_same<KW, key_type>
, mpl::if_<Reference, reference, value_type>
, mpl::apply_wrap3<typename Next::binding, KW, Default, Reference>
>::type type;
};
};
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
// Overload for key_type, so the assert below will fire if the
// same keyword is used again
static yes_tag has_key(key_type*);
using Next::has_key;
BOOST_MPL_ASSERT_MSG(
sizeof(Next::has_key((key_type*)0)) == sizeof(no_tag)
, duplicate_keyword, (key_type)
);
#endif
//
// Begin implementation of indexing operators for looking up
// specific arguments by name
//
// Helpers that handle the case when TaggedArg is
// empty<T>.
template <class D>
reference get_default(D const&, mpl::false_) const
{
return arg.value;
}
template <class D>
reference get_default(D const& d, mpl::true_) const
{
return arg.value ? arg.value.get() : arg.value.construct(d.value);
}
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
// These older compilers don't support the overload set creation
// idiom well, so we need to do all the return type calculation
// for the compiler and dispatch through an outer function template
// A metafunction class that, given a keyword, returns the base
// sublist whose get() function can produce the value for that
// key.
struct key_owner
{
template<class KW>
struct apply
{
typedef typename mpl::eval_if<
mars_boost_ksim::is_same<KW, key_type>
, mpl::identity<arg_list<TaggedArg,Next> >
, mpl::apply_wrap1<typename Next::key_owner,KW>
>::type type;
};
};
// Outer indexing operators that dispatch to the right node's
// get() function.
template <class KW>
typename mpl::apply_wrap3<binding, KW, void_, mpl::true_>::type
operator[](keyword<KW> const& x) const
{
typename mpl::apply_wrap1<key_owner, KW>::type const& sublist = *this;
return sublist.get(x);
}
template <class KW, class Default>
typename mpl::apply_wrap3<binding, KW, Default&, mpl::true_>::type
operator[](default_<KW, Default> x) const
{
typename mpl::apply_wrap1<key_owner, KW>::type const& sublist = *this;
return sublist.get(x);
}
template <class KW, class F>
typename mpl::apply_wrap3<
binding,KW
, typename result_of0<F>::type
, mpl::true_
>::type
operator[](lazy_default<KW,F> x) const
{
typename mpl::apply_wrap1<key_owner, KW>::type const& sublist = *this;
return sublist.get(x);
}
// These just return the stored value; when empty_arg_list is
// reached, indicating no matching argument was passed, the
// default is returned, or if no default_ or lazy_default was
// passed, compilation fails.
reference get(keyword<key_type> const&) const
{
BOOST_MPL_ASSERT_NOT((holds_maybe));
return arg.value;
}
template <class Default>
reference get(default_<key_type,Default> const& d) const
{
return get_default(d, holds_maybe());
}
template <class Default>
reference get(lazy_default<key_type, Default>) const
{
return arg.value;
}
#else
reference operator[](keyword<key_type> const&) const
{
BOOST_MPL_ASSERT_NOT((holds_maybe));
return arg.value;
}
template <class Default>
reference operator[](default_<key_type, Default> const& d) const
{
return get_default(d, holds_maybe());
}
template <class Default>
reference operator[](lazy_default<key_type, Default>) const
{
return arg.value;
}
// Builds an overload set including operator[]s defined in base
// classes.
using Next::operator[];
//
// End of indexing support
//
//
// For parameter_requirements matching this node's key_type,
// return a bool constant wrapper indicating whether the
// requirements are satisfied by TaggedArg. Used only for
// compile-time computation and never really called, so a
// declaration is enough.
//
template <class HasDefault, class Predicate, class ArgPack>
static typename mpl::apply_wrap2<
typename mpl::lambda<Predicate, lambda_tag>::type
, value_type, ArgPack
>::type
satisfies(
parameter_requirements<key_type,Predicate,HasDefault>*
, ArgPack*
);
// Builds an overload set including satisfies functions defined
// in base classes.
using Next::satisfies;
#endif
// Comma operator to compose argument list without using parameters<>.
// Useful for argument lists with undetermined length.
template <class KW, class T2>
arg_list<tagged_argument<KW, T2>, self>
operator,(tagged_argument<KW,T2> x) const
{
return arg_list<tagged_argument<KW,T2>, self>(x, *this);
}
// MPL sequence support
typedef self type; // Convenience for users
typedef Next tail_type; // For the benefit of iterators
typedef arg_list_tag tag; // For dispatching to sequence intrinsics
};
// MPL sequence support
template <class ArgumentPack>
struct arg_list_iterator
{
typedef mpl::forward_iterator_tag category;
// The incremented iterator
typedef arg_list_iterator<typename ArgumentPack::tail_type> next;
// dereferencing yields the key type
typedef typename ArgumentPack::key_type type;
};
template <>
struct arg_list_iterator<empty_arg_list> {};
}} // namespace parameter::aux
// MPL sequence support
namespace mpl
{
template <>
struct begin_impl<parameter::aux::arg_list_tag>
{
template <class S>
struct apply
{
typedef parameter::aux::arg_list_iterator<S> type;
};
};
template <>
struct end_impl<parameter::aux::arg_list_tag>
{
template <class>
struct apply
{
typedef parameter::aux::arg_list_iterator<parameter::aux::empty_arg_list> type;
};
};
}
} // namespace mars_boost_ksim
#endif // ARG_LIST_050329_HPP
| [
""
] | |
2397b7b515373fcfcf30fab80e3a3f101f11e1f1 | 8dad76e7b386426f792a2f828421c9f7aafb6bca | /includes/utils/data/AData.hpp | 322b7ceb4e2634a3b0d517216055147bd8a90e7d | [] | no_license | Nadroj27/Arcade | c7d96936e257314fcad6a0e6fac8701ac42ab6a5 | 8f5f131d61820bea9cb29b094bdf998e63f24cd2 | refs/heads/master | 2021-01-21T19:40:01.405160 | 2017-10-10T11:14:18 | 2017-10-10T11:14:18 | 92,148,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | hpp | /*
** AData.hpp for cpp_arcade in /Users/Vacca_J/Epitech/Tek2/cpp_arcade/includes/utils/data
**
** Made by Vacca_J
** Login <Vacca_J@epitech.net>
**
** Started on Sun Apr 09 01:03:31 2017 Vacca_J
** Last update Sun Apr 09 01:03:57 2017 Vacca_J
*/
#ifndef ADATA_HPP_
#define ADATA_HPP_
#include "IData.hpp"
class AData : public IData {
public:
virtual ~AData () {};
DataType const &getShape() const;
virtual void setShape(DataType const &shape);
Position const &getPosition() const;
virtual void setPosition(Position const &position);
virtual void setPositionX(double const x);
virtual void setPositionY(double const y);
virtual void setPositionZ(double const z);
virtual void reset(void) = 0;
protected:
DataType _shape;
Position _position;
};
#else
class AData;
#endif /* !ADATA_HPP_ */
| [
"jordan.vacca@epitech.eu"
] | jordan.vacca@epitech.eu |
8b8d02244eb0fedb4b515f7dcc46d391f06ccda0 | 38d72671bcb647aac89383e0a818f3a4c4f26aae | /week01/build_the_sum.cpp | ab9b32727024c7210298470f229f89ff7f7f058d | [] | no_license | jkfrie/AlgoLab-HS19-ETHZ | 1e589db818be4058270310711cea7eca1497fb09 | 2262d84710861130325db5ca33e97bcc7ee2df24 | refs/heads/master | 2023-02-21T19:21:39.211680 | 2021-01-27T17:52:19 | 2021-01-27T17:52:19 | 213,035,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <limits>
#include <stdexcept>
using namespace std;
int main(int argc, char const *argv[]) {
ios_base::sync_with_stdio(false);
// TODO
}
| [
"jz.friedman@hotmail.com"
] | jz.friedman@hotmail.com |
042bf34e692e46243237ed6400f763a617769965 | 19e1c1c9328c47cbf4d17257e7b6a125e65c2175 | /ShaderTutors/13_StencilShadow/main.cpp | 6b4c553feebf4b95cd90ebb62129d9ec27f33967 | [] | no_license | kukaros/Asylum_Tutorials | 28a85308e30c58616b959e9f410210a9747b3e72 | ae2f6663dfa7a1682bda01e761bda0968bbc5e24 | refs/heads/master | 2021-01-23T11:04:16.539802 | 2015-03-13T11:51:51 | 2015-03-13T11:51:51 | 35,374,771 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,971 | cpp | //*************************************************************************************************************
#include <d3dx9.h>
#include <iostream>
#include <string>
#include <set>
#include <vector>
#include "../common/dxext.h"
#include "../common/orderedarray.hpp"
// TODO:
// - sphere texcoord is not correct
// - two-sided stencil
// - needs tonemap
#define NUM_OBJECTS 3
#define VOLUME_OFFSET 2e-2f // to avoid zfight
// not reliable
#define VOLUME_NUMVERTICES(x) max(128, x * 2)
#define VOLUME_NUMINDICES(x) max(256, x * 3) // x is numfaces
// helper macros
#define TITLE "Shader tutorial 13: Stencil shadow volume (CPU)"
#define MYERROR(x) { std::cout << "* Error: " << x << "!\n"; }
#define MYVALID(x) { if( FAILED(hr = x) ) { MYERROR(#x); return hr; } }
#define SAFE_RELEASE(x) { if( (x) ) { (x)->Release(); (x) = NULL; } }
// external variables
extern LPDIRECT3DDEVICE9 device;
extern HWND hwnd;
extern long screenwidth;
extern long screenheight;
extern short mousedx;
extern short mousedy;
extern short mousedown;
// tutorial structs
struct Edge
{
// orderedarray returns read-only reference
mutable D3DXVECTOR3 v1, v2; // vertex positions
mutable D3DXVECTOR3 n1, n2; // triangle normals
DWORD i1, i2; // vertex indices
mutable DWORD other; // other triangle
Edge()
{
i1 = i2 = 0;
other = 0xffffffff;
}
inline bool operator <(const Edge& other) const {
return ((i1 < other.i1) || (i1 == other.i1 && i2 < other.i2));
}
};
typedef mystl::orderedarray<Edge> edgeset;
typedef std::vector<Edge> edgelist;
struct ShadowCaster
{
D3DXMATRIX world;
edgeset edges;
edgelist silhouette;
LPD3DXMESH object; // for normal rendering
LPD3DXMESH caster; // for silhouette determination
LPDIRECT3DVERTEXBUFFER9 vertices; // volume vertices
LPDIRECT3DINDEXBUFFER9 indices; // volume indices
DWORD numvertices; // volume vertices
DWORD numfaces; // volume faces
ShadowCaster()
{
object = caster = 0;
vertices = 0;
indices = 0;
}
};
float textvertices[36] =
{
9.5f, 9.5f, 0, 1, 0, 0,
521.5f, 9.5f, 0, 1, 1, 0,
9.5f, 128.0f + 9.5f, 0, 1, 0, 1,
9.5f, 128.0f + 9.5f, 0, 1, 0, 1,
521.5f, 9.5f, 0, 1, 1, 0,
521.5f, 128.0f + 9.5f, 0, 1, 1, 1
};
// tutorial variables
LPD3DXEFFECT ambient = NULL;
LPD3DXEFFECT specular = NULL;
LPD3DXEFFECT extrude = NULL;
LPD3DXMESH shadowreceiver = NULL;
LPDIRECT3DTEXTURE9 texture1 = NULL;
LPDIRECT3DTEXTURE9 texture2 = NULL;
LPDIRECT3DTEXTURE9 text = NULL;
LPDIRECT3DVERTEXDECLARATION9 shadowdecl = NULL;
state<D3DXVECTOR2> cameraangle;
state<D3DXVECTOR2> lightangle;
ShadowCaster objects[NUM_OBJECTS]; // leak
bool drawsilhouette = false;
bool drawvolume = false;
// tutorial functions
void GenerateEdges(edgeset& out, LPD3DXMESH mesh);
void FindSilhouette(ShadowCaster& caster, const D3DXVECTOR3& lightpos);
void ExtrudeSilhouette(ShadowCaster& caster, const D3DXVECTOR3& lightpos);
void DrawScene(LPD3DXEFFECT effect, bool texture);
void DrawShadowVolume(const ShadowCaster& caster);
HRESULT InitScene()
{
HRESULT hr;
SetWindowText(hwnd, TITLE);
MYVALID(D3DXCreateTextureFromFileA(device, "../media/textures/marble.dds", &texture1));
MYVALID(D3DXCreateTextureFromFileA(device, "../media/textures/wood2.jpg", &texture2));
MYVALID(DXCreateEffect("../media/shaders/ambient.fx", device, &ambient));
MYVALID(DXCreateEffect("../media/shaders/blinnphong.fx", device, &specular));
MYVALID(DXCreateEffect("../media/shaders/extrude.fx", device, &extrude));
MYVALID(device->CreateTexture(512, 128, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &text, NULL));
MYVALID(DXCreateTexturedBox(device, D3DXMESH_MANAGED, &shadowreceiver));
// box
MYVALID(DXCreateTexturedBox(device, D3DXMESH_MANAGED, &objects[0].object));
MYVALID(DXCreateCollisionBox(device, D3DXMESH_SYSTEMMEM, &objects[0].caster));
D3DXMatrixTranslation(&objects[0].world, -1.5f, 0.55f, 1.2f);
MYVALID(device->CreateVertexBuffer(VOLUME_NUMVERTICES(objects[0].caster->GetNumVertices()) * sizeof(D3DXVECTOR4), D3DUSAGE_DYNAMIC, D3DFVF_XYZW, D3DPOOL_DEFAULT, &objects[0].vertices, NULL));
MYVALID(device->CreateIndexBuffer(VOLUME_NUMINDICES(objects[0].caster->GetNumFaces()) * sizeof(WORD), D3DUSAGE_DYNAMIC, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &objects[0].indices, NULL));
// sphere
MYVALID(DXCreateTexturedSphere(device, 0.5f, 30, 30, D3DXMESH_SYSTEMMEM, &objects[1].object));
MYVALID(DXCreateCollisionSphere(device, 0.5f, 30, 30, D3DXMESH_SYSTEMMEM, &objects[1].caster));
D3DXMatrixTranslation(&objects[1].world, 1.0f, 0.55f, 0.7f);
MYVALID(device->CreateVertexBuffer(VOLUME_NUMVERTICES(objects[1].caster->GetNumVertices()) * sizeof(D3DXVECTOR4), D3DUSAGE_DYNAMIC, D3DFVF_XYZW, D3DPOOL_DEFAULT, &objects[1].vertices, NULL));
MYVALID(device->CreateIndexBuffer(VOLUME_NUMINDICES(objects[1].caster->GetNumFaces()) * sizeof(WORD), D3DUSAGE_DYNAMIC, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &objects[1].indices, NULL));
// L shape
MYVALID(DXCreateTexturedLShape(device, D3DXMESH_MANAGED, &objects[2].object));
MYVALID(DXCreateCollisionLShape(device, D3DXMESH_SYSTEMMEM, &objects[2].caster));
D3DXMatrixTranslation(&objects[2].world, 0, 0.55f, -1);
MYVALID(device->CreateVertexBuffer(VOLUME_NUMVERTICES(objects[2].caster->GetNumVertices()) * sizeof(D3DXVECTOR4), D3DUSAGE_DYNAMIC, D3DFVF_XYZW, D3DPOOL_DEFAULT, &objects[2].vertices, NULL));
MYVALID(device->CreateIndexBuffer(VOLUME_NUMINDICES(objects[2].caster->GetNumFaces()) * sizeof(WORD), D3DUSAGE_DYNAMIC, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &objects[2].indices, NULL));
#if 0
D3DXMATERIAL defmat;
defmat.pTextureFilename = 0;
defmat.MatD3D.Ambient = D3DXCOLOR(1, 1, 1, 1);
defmat.MatD3D.Diffuse = D3DXCOLOR(1, 1, 1, 1);
defmat.MatD3D.Specular = D3DXCOLOR(1, 1, 1, 1);
defmat.MatD3D.Emissive = D3DXCOLOR(0, 0, 0, 0);
defmat.MatD3D.Power = 20;
DXSaveMeshToQM("../media/meshes10/box.qm", objects[0].object, &defmat, 1);
DXSaveMeshToQM("../media/meshes10/collisionbox.qm", objects[0].caster, &defmat, 1);
DXSaveMeshToQM("../media/meshes10/sphere.qm", objects[1].object, &defmat, 1);
DXSaveMeshToQM("../media/meshes10/collisionsphere.qm", objects[1].caster, &defmat, 1);
DXSaveMeshToQM("../media/meshes10/lshape.qm", objects[2].object, &defmat, 1);
DXSaveMeshToQM("../media/meshes10/collisionlshape.qm", objects[2].caster, &defmat, 1);
#endif
// generate edges
std::cout << "Generating edge info...\n";
for( int i = 0; i < NUM_OBJECTS; ++i )
GenerateEdges(objects[i].edges, objects[i].caster);
// shadow volume decl
D3DVERTEXELEMENT9 elem[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
D3DDECL_END()
};
MYVALID(device->CreateVertexDeclaration(elem, &shadowdecl));
// effect
specular->SetFloat("ambient", 0);
cameraangle = D3DXVECTOR2(0.78f, 0.78f);
lightangle = D3DXVECTOR2(2.8f, 0.78f);
DXRenderText("Use mouse to rotate camera and light\n\n1: draw silhouette\n2: draw shadow volume", text, 512, 128);
return S_OK;
}
//*************************************************************************************************************
void UninitScene()
{
for( int i = 0; i < NUM_OBJECTS; ++i )
{
SAFE_RELEASE(objects[i].object);
SAFE_RELEASE(objects[i].caster);
SAFE_RELEASE(objects[i].vertices);
SAFE_RELEASE(objects[i].indices);
objects[i].edges.clear();
objects[i].edges.swap(edgeset());
objects[i].silhouette.clear();
objects[i].silhouette.swap(edgelist());
}
SAFE_RELEASE(text);
SAFE_RELEASE(shadowdecl);
SAFE_RELEASE(shadowreceiver);
SAFE_RELEASE(specular);
SAFE_RELEASE(ambient);
SAFE_RELEASE(extrude);
SAFE_RELEASE(texture1);
SAFE_RELEASE(texture2);
}
//*************************************************************************************************************
void KeyPress(WPARAM wparam)
{
if( wparam == 0x31 )
drawsilhouette = !drawsilhouette;
else if( wparam == 0x32 )
drawvolume = !drawvolume;
}
//*************************************************************************************************************
void Update(float delta)
{
D3DXVECTOR2 velocity(mousedx, mousedy);
cameraangle.prev = cameraangle.curr;
lightangle.prev = lightangle.curr;
if( mousedown == 1 )
cameraangle.curr += velocity * 0.004f;
if( mousedown == 2 )
lightangle.curr += velocity * 0.004f;
// clamp to [-pi, pi]
if( cameraangle.curr.y >= 1.5f )
cameraangle.curr.y = 1.5f;
if( cameraangle.curr.y <= -1.5f )
cameraangle.curr.y = -1.5f;
// clamp to [0.1, pi]
if( lightangle.curr.y >= 1.5f )
lightangle.curr.y = 1.5f;
if( lightangle.curr.y <= 0.1f )
lightangle.curr.y = 0.1f;
}
//*************************************************************************************************************
void DrawScene(LPD3DXEFFECT effect)
{
D3DXMATRIX world;
D3DXMATRIX inv;
D3DXVECTOR4 uv(3, 3, 0, 0);
D3DXMatrixScaling(&world, 5, 0.1f, 5);
D3DXMatrixInverse(&inv, NULL, &world);
effect->SetMatrix("matWorld", &world);
effect->SetMatrix("matWorldInv", &inv);
effect->SetVector("uv", &uv);
effect->Begin(0, 0);
effect->BeginPass(0);
{
device->SetTexture(0, texture2);
shadowreceiver->DrawSubset(0);
if( !drawsilhouette )
{
device->SetTexture(0, texture1);
uv.x = uv.y = 1;
effect->SetVector("uv", &uv);
for( int i = 0; i < NUM_OBJECTS; ++i )
{
D3DXMatrixInverse(&inv, NULL, &objects[i].world);
effect->SetMatrix("matWorld", &objects[i].world);
effect->SetMatrix("matWorldInv", &inv);
effect->CommitChanges();
objects[i].object->DrawSubset(0);
}
}
}
effect->EndPass();
effect->End();
}
//*************************************************************************************************************
void Render(float alpha, float elapsedtime)
{
static float time = 0;
D3DXMATRIX view, proj, vp;
D3DXMATRIX world;
D3DXMATRIX inv;
D3DXVECTOR4 amblight(0.2f, 0.2f, 0.2f, 1);
D3DXVECTOR4 intensity(0.8f, 0.8f, 0.8f, 1);
D3DXVECTOR4 zero(0, 0, 0, 1);
D3DXVECTOR3 lightpos(0, 0, -10);
D3DXVECTOR3 eye(0, 0, -5.2f);
D3DXVECTOR3 look(0, 0.5f, 0);
D3DXVECTOR3 up(0, 1, 0);
D3DXVECTOR3 p1, p2;
D3DXVECTOR2 orient = cameraangle.smooth(alpha);
D3DXVECTOR2 light = lightangle.smooth(alpha);
time += elapsedtime;
// setup light
D3DXMatrixRotationYawPitchRoll(&view, light.x, light.y, 0);
D3DXVec3TransformCoord(&lightpos, &lightpos, &view);
// TODO: no need to calculate every frame
for( int i = 0; i < NUM_OBJECTS; ++i )
{
FindSilhouette(objects[i], (D3DXVECTOR3&)lightpos);
ExtrudeSilhouette(objects[i], (D3DXVECTOR3&)lightpos);
}
// setup camera
D3DXMatrixRotationYawPitchRoll(&view, orient.x, orient.y, 0);
D3DXVec3TransformCoord(&eye, &eye, &view);
D3DXMatrixLookAtLH(&view, &eye, &look, &up);
D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 4, (float)screenwidth / (float)screenheight, 0.1f, 20);
// put far plane to infinity
proj._33 = 1;
proj._43 = -0.1f;
D3DXMatrixMultiply(&vp, &view, &proj);
D3DXMatrixScaling(&world, 5, 0.1f, 5);
// specular effect uniforms
specular->SetMatrix("matViewProj", &vp);
specular->SetVector("eyePos", (D3DXVECTOR4*)&eye);
specular->SetVector("lightPos", (D3DXVECTOR4*)&lightpos);
specular->SetVector("ambient", &zero); // it's a fuck-up
specular->SetVector("intensity", &intensity); // lazy to tonemap
ambient->SetMatrix("matViewProj", &vp);
ambient->SetVector("ambient", &amblight);
if( SUCCEEDED(device->BeginScene()) )
{
device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL, 0xff6694ed, 1.0f, 0);
// STEP 1: z pass
ambient->SetTechnique("ambientlight");
ambient->SetMatrix("matViewProj", &vp);
DrawScene(ambient);
// STEP 2: draw shadow with depth fail method
device->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
device->SetRenderState(D3DRS_STENCILENABLE, TRUE);
device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
device->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
device->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP);
device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCR);
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
extrude->SetTechnique("extrude");
extrude->SetMatrix("matViewProj", &vp);
extrude->Begin(0, 0);
extrude->BeginPass(0);
{
for( int i = 0; i < NUM_OBJECTS; ++i )
DrawShadowVolume(objects[i]);
device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_DECR);
device->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
for( int i = 0; i < NUM_OBJECTS; ++i )
DrawShadowVolume(objects[i]);
}
extrude->EndPass();
extrude->End();
device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA);
// STEP 3: multipass lighting
device->SetRenderState(D3DRS_ZENABLE, TRUE);
device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_GREATER);
device->SetRenderState(D3DRS_STENCILREF, 1);
DrawScene(specular);
device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
if( drawsilhouette )
{
amblight = D3DXVECTOR4(1, 1, 0, 0.5f);
// reuse whatever we can...
extrude->SetVector("ambient", &amblight);
extrude->Begin(0, 0);
extrude->BeginPass(0);
device->SetVertexDeclaration(shadowdecl);
for( int i = 0; i < NUM_OBJECTS; ++i )
{
const ShadowCaster& caster = objects[i];
D3DXVECTOR4* verts = (D3DXVECTOR4*)malloc(caster.silhouette.size() * 2 * sizeof(D3DXVECTOR4));
for( size_t j = 0; j < caster.silhouette.size(); ++j )
{
const Edge& e = caster.silhouette[j];
verts[j * 2 + 0] = D3DXVECTOR4(e.v1, 1);
verts[j * 2 + 1] = D3DXVECTOR4(e.v2, 1);
}
extrude->SetMatrix("matWorld", &caster.world);
extrude->CommitChanges();
device->DrawPrimitiveUP(D3DPT_LINELIST, caster.silhouette.size(), verts, sizeof(D3DXVECTOR4));
free(verts);
}
extrude->EndPass();
extrude->End();
extrude->SetVector("ambient", &zero);
}
if( drawvolume )
{
device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
amblight = D3DXVECTOR4(1, 1, 0, 0.5f);
extrude->SetVector("ambient", &amblight);
extrude->Begin(0, 0);
extrude->BeginPass(0);
for( int i = 0; i < NUM_OBJECTS; ++i )
DrawShadowVolume(objects[i]);
extrude->EndPass();
extrude->End();
extrude->SetVector("ambient", &zero);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
}
// render text
device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1);
device->SetRenderState(D3DRS_ZENABLE, FALSE);
device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
device->SetTexture(0, text);
device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, textvertices, 6 * sizeof(float));
device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
device->SetRenderState(D3DRS_ZENABLE, TRUE);
device->SetTexture(0, 0);
device->EndScene();
}
device->Present(NULL, NULL, NULL, NULL);
}
//*************************************************************************************************************
void GenerateEdges(edgeset& out, LPD3DXMESH mesh)
{
D3DXVECTOR3 p1, p2, p3;
D3DXVECTOR3 a, b, n;
Edge e;
BYTE* vdata = 0;
WORD* idata = 0;
size_t ind;
DWORD numindices = mesh->GetNumFaces() * 3;
DWORD stride = mesh->GetNumBytesPerVertex();
WORD i1, i2, i3;
bool is32bit = (mesh->GetOptions() & D3DXMESH_32BIT);
out.clear();
if( is32bit )
{
MYERROR("GenerateEdges(): 4 byte indices not implemented yet");
return;
}
// generate edge info
mesh->LockIndexBuffer(D3DLOCK_READONLY, (LPVOID*)&idata);
mesh->LockVertexBuffer(D3DLOCK_READONLY, (LPVOID*)&vdata);
out.reserve(512);
for( DWORD i = 0; i < numindices; i += 3 )
{
if( out.capacity() <= out.size() )
out.reserve(out.size() + 1024);
i1 = idata[i + 0];
i2 = idata[i + 1];
i3 = idata[i + 2];
p1 = *((D3DXVECTOR3*)(vdata + i1 * stride));
p2 = *((D3DXVECTOR3*)(vdata + i2 * stride));
p3 = *((D3DXVECTOR3*)(vdata + i3 * stride));
a = p2 - p1;
b = p3 - p1;
D3DXVec3Cross(&n, &a, &b);
D3DXVec3Normalize(&n, &n);
if( i1 < i2 )
{
e.i1 = i1;
e.i2 = i2;
e.v1 = p1;
e.v2 = p2;
e.n1 = n;
if( !out.insert(e) )
std::cout << "Crack in mesh (first triangle)\n";
}
if( i2 < i3 )
{
e.i1 = i2;
e.i2 = i3;
e.v1 = p2;
e.v2 = p3;
e.n1 = n;
if( !out.insert(e) )
std::cout << "Crack in mesh (first triangle)\n";
}
if( i3 < i1 )
{
e.i1 = i3;
e.i2 = i1;
e.v1 = p3;
e.v2 = p1;
e.n1 = n;
if( !out.insert(e) )
std::cout << "Crack in mesh (first triangle)\n";
}
}
// find second triangle for each edge
for( DWORD i = 0; i < numindices; i += 3 )
{
i1 = idata[i + 0];
i2 = idata[i + 1];
i3 = idata[i + 2];
p1 = *((D3DXVECTOR3*)(vdata + i1 * stride));
p2 = *((D3DXVECTOR3*)(vdata + i2 * stride));
p3 = *((D3DXVECTOR3*)(vdata + i3 * stride));
a = p2 - p1;
b = p3 - p1;
D3DXVec3Cross(&n, &a, &b);
D3DXVec3Normalize(&n, &n);
if( i1 > i2 )
{
e.i1 = i2;
e.i2 = i1;
ind = out.find(e);
if( ind == edgeset::npos )
{
std::cout << "Lone triangle\n";
continue;
}
if( out[ind].other == 0xffffffff )
{
out[ind].other = i / 3;
out[ind].n2 = n;
}
else
std::cout << "Crack in mesh (second triangle)\n";
}
if( i2 > i3 )
{
e.i1 = i3;
e.i2 = i2;
ind = out.find(e);
if( ind == edgeset::npos )
{
std::cout << "Lone triangle\n";
continue;
}
if( out[ind].other == 0xffffffff )
{
out[ind].other = i / 3;
out[ind].n2 = n;
}
else
std::cout << "Crack in mesh (second triangle)\n";
}
if( i3 > i1 )
{
e.i1 = i1;
e.i2 = i3;
ind = out.find(e);
if( ind == edgeset::npos )
{
std::cout << "Lone triangle\n";
continue;
}
if( out[ind].other == 0xffffffff )
{
out[ind].other = i / 3;
out[ind].n2 = n;
}
else
std::cout << "Crack in mesh (second triangle)\n";
}
}
mesh->UnlockIndexBuffer();
mesh->UnlockVertexBuffer();
}
//*************************************************************************************************************
void FindSilhouette(ShadowCaster& caster, const D3DXVECTOR3& lightpos)
{
D3DXMATRIX inv;
D3DXVECTOR3 lp;
float a, b;
D3DXMatrixInverse(&inv, NULL, &caster.world);
D3DXVec3TransformCoord(&lp, &lightpos, &inv);
caster.silhouette.clear();
caster.silhouette.reserve(50);
for( size_t i = 0; i < caster.edges.size(); ++i )
{
const Edge& e = caster.edges[i];
if( e.other != 0xffffffff )
{
a = D3DXVec3Dot(&lp, &e.n1) - D3DXVec3Dot(&e.n1, &e.v1);
b = D3DXVec3Dot(&lp, &e.n2) - D3DXVec3Dot(&e.n2, &e.v1);
if( (a < 0) != (b < 0) )
{
if( caster.silhouette.capacity() <= caster.silhouette.size() )
caster.silhouette.reserve(caster.silhouette.size() + 50);
if( a < 0 )
{
std::swap(e.v1, e.v2);
std::swap(e.n1, e.n2);
}
caster.silhouette.push_back(e);
}
}
}
}
//*************************************************************************************************************
void ExtrudeSilhouette(ShadowCaster& caster, const D3DXVECTOR3& lightpos)
{
D3DXVECTOR4* vdata = 0;
WORD* idata = 0;
D3DXMATRIX inv;
D3DXVECTOR3 lp;
D3DXVECTOR3 center(0, 0, 0);
D3DXVECTOR3 ltocenter;
float weight = 0.5f / caster.silhouette.size();
caster.vertices->Lock(0, 0, (void**)&vdata, D3DLOCK_DISCARD);
caster.indices->Lock(0, 0, (void**)&idata, D3DLOCK_DISCARD);
D3DXMatrixInverse(&inv, NULL, &caster.world);
D3DXVec3TransformCoord(&lp, &lightpos, &inv);
for( size_t i = 0; i < caster.silhouette.size(); ++i )
{
const Edge& e = caster.silhouette[i];
center += e.v1 * weight;
center += e.v2 * weight;
}
ltocenter = center - lp;
D3DXVec3Normalize(<ocenter, <ocenter);
ltocenter *= VOLUME_OFFSET;
for( size_t i = 0; i < caster.silhouette.size(); ++i )
{
const Edge& e = caster.silhouette[i];
vdata[i * 4 + 0] = D3DXVECTOR4(e.v1 + ltocenter, 1);
vdata[i * 4 + 1] = D3DXVECTOR4(e.v1 - lp, 0);
vdata[i * 4 + 2] = D3DXVECTOR4(e.v2 + ltocenter, 1);
vdata[i * 4 + 3] = D3DXVECTOR4(e.v2 - lp, 0);
idata[i * 6 + 0] = i * 4 + 0;
idata[i * 6 + 1] = i * 4 + 1;
idata[i * 6 + 2] = i * 4 + 2;
idata[i * 6 + 3] = i * 4 + 2;
idata[i * 6 + 4] = i * 4 + 1;
idata[i * 6 + 5] = i * 4 + 3;
}
// back cap
vdata[caster.silhouette.size() * 4] = D3DXVECTOR4(center - lp, 0);
idata += caster.silhouette.size() * 6;
for( size_t i = 0; i < caster.silhouette.size(); ++i )
{
const Edge& e = caster.silhouette[i];
idata[i * 3 + 0] = i * 4 + 3;
idata[i * 3 + 1] = i * 4 + 1;
idata[i * 3 + 2] = caster.silhouette.size() * 4;
}
// front cap
WORD* idata2 = NULL;
D3DXVECTOR3* vdata2 = NULL;
WORD verticesadded = caster.silhouette.size() * 4 + 1;
DWORD indicesadded = caster.silhouette.size() * 9;
WORD i1, i2, i3;
D3DXVECTOR3 *v1, *v2, *v3;
D3DXVECTOR3 a, b, n;
float dist;
WORD* added = (WORD*)malloc(caster.caster->GetNumVertices() * sizeof(WORD));
memset(added, 0, caster.caster->GetNumVertices() * sizeof(WORD));
//vdata += caster.silhouette.size() * 4 + 1;
idata += caster.silhouette.size() * 3;
caster.caster->LockVertexBuffer(D3DLOCK_READONLY, (void**)&vdata2);
caster.caster->LockIndexBuffer(D3DLOCK_READONLY, (void**)&idata2);
for( DWORD i = 0; i < caster.caster->GetNumFaces() * 3; i += 3 )
{
i1 = idata2[i + 0];
i2 = idata2[i + 1];
i3 = idata2[i + 2];
v1 = (vdata2 + i1);
v2 = (vdata2 + i2);
v3 = (vdata2 + i3);
// OPTIM: store normals
a = v2->operator -(*v1);
b = v3->operator -(*v1);
D3DXVec3Cross(&n, &a, &b);
dist = D3DXVec3Dot(&n, &lp) - D3DXVec3Dot(&n, v1);
if( dist > 0 )
{
if( !added[i1] )
{
vdata[verticesadded] = D3DXVECTOR4(*v1 + ltocenter, 1);
added[i1] = verticesadded;
++verticesadded;
}
if( !added[i2] )
{
vdata[verticesadded] = D3DXVECTOR4(*v2 + ltocenter, 1);
added[i2] = verticesadded;
++verticesadded;
}
if( !added[i3] )
{
vdata[verticesadded] = D3DXVECTOR4(*v3 + ltocenter, 1);
added[i3] = verticesadded;
++verticesadded;
}
idata[0] = added[i1];
idata[1] = added[i2];
idata[2] = added[i3];
indicesadded += 3;
idata += 3;
}
}
free(added);
caster.caster->UnlockIndexBuffer();
caster.caster->UnlockVertexBuffer();
caster.indices->Unlock();
caster.vertices->Unlock();
caster.numvertices = verticesadded;
caster.numfaces = indicesadded / 3;
#ifdef _DEBUG
// as kissing frogs...
DWORD test1 = VOLUME_NUMVERTICES(caster.caster->GetNumVertices());
DWORD test2 = VOLUME_NUMINDICES(caster.caster->GetNumFaces());
if( (verticesadded > test1) ||
(indicesadded > test2) )
{
std::cout << "Buffer overflow!\n";
::_CrtDbgBreak();
}
#endif
}
//*************************************************************************************************************
void DrawShadowVolume(const ShadowCaster& caster)
{
extrude->SetMatrix("matWorld", &caster.world);
extrude->CommitChanges();
device->SetVertexDeclaration(shadowdecl);
device->SetStreamSource(0, caster.vertices, 0, sizeof(D3DXVECTOR4));
device->SetIndices(caster.indices);
device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, caster.numvertices, 0, caster.numfaces);
}
//*************************************************************************************************************
| [
"darthasylum@hotmail.com"
] | darthasylum@hotmail.com |
f4eb7831ef9057f7db3cf226bdd29874d5020b80 | 8b6fe368977190e1bc4c87dbb7bb4f0090ec0883 | /Lab_7_MorseTree/Lab_7_MorseTree/Lab_7_MorseTree/MorseTree_methods.cpp | 01c2ecc605a751eee1cb25b7e680b559e1517c3c | [] | no_license | AlspachS/CST211-Data-Structures | df040dffa009366f441c41818c0187137a3b9fae | 8c0c97a61ebdddb3ea898c9fb8a274e36290bc78 | refs/heads/master | 2020-04-05T02:32:04.975835 | 2018-11-07T02:43:44 | 2018-11-07T02:43:44 | 156,480,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,027 | cpp | #include "MorseTree.h"
/**********************************************************************
* MorseTree::MorseTree( )
*
* Purpose: Creates a tree with the data from the Morse.dat file.
*
* Entry: No tree exists.
*
* Exit: A MorseTree object has been created.
*
**********************************************************************/
MorseTree::MorseTree( ) :
mRoot( nullptr )
{
mRoot = new TreeNode< string >( "*" );
string morse( "" );
string letter( "" );
ifstream fin;
fin.open( "Morse.dat" );
while( !fin.eof( ) )
{
getline( fin, morse );
letter = morse[ 0 ];
Insert( letter, &morse[ 1 ] );
}
fin.close( );
}
/**********************************************************************
* MorseTree::MorseTree( const MorseTree & copy )
*
* Purpose: Copies one MorseTree into a MorseTree being created.
*
* Entry: One MorseTree exists, the other is being created.
*
* Exit: Two MorseTree now exist, one of which is a copy of the other.
*
**********************************************************************/
MorseTree::MorseTree( const MorseTree & copy ) :
mRoot( nullptr )
{
*this = copy;
}
/**********************************************************************
* MorseTree & MorseTree::operator=( const MorseTree & rhs )
*
* Purpose: Copies one existing MorseTree into another existing MorseTree.
*
* Entry: Two MorseTrees exist, one of which will become the same
* as the other.
*
* Exit: The two MorseTrees are now the same.
*
**********************************************************************/
MorseTree & MorseTree::operator=( const MorseTree & rhs )
{
if( this != &rhs )
{
Copy( mRoot, rhs.mRoot );
}
return * this;
}
/**********************************************************************
* MorseTree::~MorseTree( )
*
* Purpose: Destroys a MorseTree object as it goes out of scope.
*
* Entry: When an object leaves scope.
*
* Exit: After the object is destroyed.
*
**********************************************************************/
MorseTree::~MorseTree( )
{
Purge( );
}
/**********************************************************************
* void MorseTree::Insert( string data )
*
* Purpose: User-interface for the recursive insert function.
*
* Entry: The tree has read in some data, and that data is passed
* to the recursive insert function.
*
* Exit: The data has been inserted in the tree in the appropriate
* location.
*
**********************************************************************/
void MorseTree::Insert( string data, string morse )
{
Insert( data, morse, mRoot );
}
/**********************************************************************
* void MorseTree::Insert( string data, TreeNode< string > *& root )
*
* Purpose: Recursive function that receives the data from the user
* interface insert function. Searches for the correct
* location in the tree until an empty node has been found.
* Creates a node at this location with the data. This
* also leaves a trail of empty nodes in its wake.
*
* Entry: The data is the character the constructor has read in,
* and root is the current node the function is at.
*
* Exit: The data is in the correct location and the call stack
* has unwound. As the call stack unwinds, the parent
* pointer is set to the current node.
*
**********************************************************************/
void MorseTree::Insert( string data, string morse, TreeNode< string > *& root )
{
if( root == nullptr )
root = new TreeNode< string >( );
if( morse.size( ) != 0 )
{
if( morse[ 0 ] == '.' )
{
Insert( data, &morse[ 1 ], root->mLeftChild );
root->mLeftChild->mParent = root;
}
else
{
Insert( data, &morse[ 1 ], root->mRightChild );
root->mRightChild->mParent = root;
}
}
else
{
root->mData = data;
mAlphabet.push_back( root );
}
}
/**********************************************************************
* void MorseTree::Purge( )
*
* Purpose: User interface for the recursive purge function.
*
* Entry: The tree may or may not have data in it.
*
* Exit: The tree doesn't have any data in it.
*
**********************************************************************/
void MorseTree::Purge( )
{
Purge( mRoot );
}
/**********************************************************************
* void MorseTree::Purge( TreeNode< string > *& root )
*
* Purpose: Removes all data from the tree.
*
* Entry: The tree may or may not have data in it.
*
* Exit: All data is removed from the tree and the root node
* is set to nullptr.
*
**********************************************************************/
void MorseTree::Purge( TreeNode< string > *& root )
{
if( root != nullptr )
{
Purge( root->mLeftChild );
Purge( root->mRightChild );
delete root;
root = nullptr;
}
}
/**********************************************************************
* string MorseTree::Decode( string morse )
*
* Purpose: Decodes the morse string that is passed into the function
* and returns a character value that morse value represents.
*
* Entry: 'morse' is a string of dots and dashes that represent
* a morse code value.
*
* Exit: The character represented by the string 'morse' is
* found and returned.
*
**********************************************************************/
string MorseTree::Decode( string morse )
{
return Decode( morse, mRoot );
}
/**********************************************************************
* string MorseTree::Decode( string morse, TreeNode< string > *& root )
*
* Purpose: Does the heavy-lifting of the decode function.
* Recurses down the tree, using the morse string, to
* find the character the morse string represents.
*
* Entry: 'morse' is a string to indicate the direction to
* travel in the tree (dot to go left, dash to go right).
* Root is the root of the tree being traversed.
*
* Exit: The character value that 'morse' represents is found and
* returned.
* is set to nullptr.
*
**********************************************************************/
string MorseTree::Decode( string morse, TreeNode< string > *& root )
{
string toReturn( "" );
if( morse.size( ) != 0 )
{
if( morse[ 0 ] == '.' )
toReturn = Decode( &morse[ 1 ], root->mLeftChild );
else
toReturn = Decode( &morse[ 1 ], root->mRightChild );
}
else
toReturn = root->mData;
return toReturn;
}
/**********************************************************************
* string MorseTree::Encode( string text )
*
* Purpose: Receives the word to encode into morse code. Makes all
* characters in the word uppercase, finds their location
* in the 'mAlphabet' vector to get the starting TreeNode
* then calls the recursive Encode function. After the
* recursive insert exits, the received value is reversed
* and has a space appended to the end. After the entire
* word is encoded, a morse code space is appended to the
* end of the word. After all this, the morse string is
* returned.
*
* Entry: 'text' is a word to be encoded into morse code.
*
* Exit: The morse code value for the word is returned.
*
**********************************************************************/
string MorseTree::Encode( string text )
{
string toReturn( "" );
string morse( "" );
int index( 0 );
for( unsigned int i( 0 ); i < text.size( ); ++i )
{
text[ i ] = toupper( text[ i ] );
index = ( text[ i ] - 65 );
morse = Encode( mAlphabet[ index ] );
reverse( morse.begin( ), morse.end( ) );
toReturn += morse;
toReturn += " ";
}
toReturn += Encode( mAlphabet[ 26 ] );
toReturn += " ";
return toReturn;
}
/**********************************************************************
* void MorseTree::Encode( TreeNode< string > *& start )
*
* Purpose: Gathers the dots and dashes to encode a character into
* morse code. This happens by going to a node in the tree
* and following the 'mParent' pointers up the tree gathering
* dots and dashes until it gets to 'mRoot'. Once it gets
* to 'mRoot', the string of dots and dashes are backward,
* This is compensated for in the public Encode function.
*
* Entry: 'start' is the node of the character to encode.
*
* Exit: 'toReturn' has gathered the backward string of dots
* and dashes.
*
**********************************************************************/
string MorseTree::Encode( TreeNode< string > *& start )
{
string toReturn( "" );
if( start != mRoot )
{
if( start->mParent->mLeftChild == start )
{
toReturn += ".";
toReturn += Encode( start->mParent );
}
else
{
toReturn += "-";
toReturn += Encode( start->mParent );
}
}
return toReturn;
}
/**********************************************************************
* void MorseTree::Copy( TreeNode< string > *& copy, const TreeNode< string > * orig )
*
* Purpose: Creates a copy of a tree by recursively copying all the
* nodes in the tree.
*
* Entry: The copy node is the node to copy the original node
* into.
*
* Exit: The node is copied. When all instances of the function
* resolve, the tree should be copied.
*
**********************************************************************/
void MorseTree::Copy( TreeNode< string > *& copy, const TreeNode< string > * orig )
{
if( orig != nullptr )
{
copy = new TreeNode< string >( orig->mData );
Copy( copy->mLeftChild, orig->mLeftChild );
Copy( copy->mRightChild, orig->mRightChild );
mAlphabet.push_back( copy );
if( copy->mLeftChild != nullptr )
copy->mLeftChild->mParent = copy;
if( copy->mRightChild != nullptr )
copy->mRightChild->mParent = copy;
}
else
copy = nullptr;
}
| [
"steven.alspach@outlook.com"
] | steven.alspach@outlook.com |
bd29e69cbef26ea4511f0adaf75e91dc2691d431 | c239d63ebac20f08205fd18a5e93a3b11da10f03 | /Algorithm/CPP/binary_tree_preorder_traversal.cpp | db76024fb2592c5d3257aa21f2ec7302863b8d51 | [] | no_license | chaojunhou/LeetCode | ff0f8b9a548e49518ed5f11a65f1e2fadd519852 | 86c6c091f7fd4b361f873967e25e4afa20a21e99 | refs/heads/master | 2016-08-05T14:25:14.024655 | 2015-09-08T02:27:37 | 2015-09-08T02:27:37 | 34,740,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,230 | cpp | # include <stdio.h>
# include <iostream>
# include <vector>
# include <string>
# include <unordered_map>
# include <cctype>
# include <stack>
# include <algorithm>
# include <time.h>
# include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> Stack;
if (root)
{
Stack.push(root);
while (!Stack.empty())
{
auto p = Stack.top();
res.push_back(p->val);
Stack.pop();
if (p->right) Stack.push(p->right);
if (p->left) Stack.push(p->left);
}
}
return res;
}
void printTree(TreeNode* root)
{
if (root)
{
cout << root->val << " ";
printTree(root->left);
printTree(root->right);
}
}
};
int main()
{
Solution sol;
TreeNode *root1;
root1 = new TreeNode(4);
root1->left =new TreeNode(2);
root1->right = new TreeNode(5);
root1->left->left = new TreeNode(1);
root1->left->right = new TreeNode(3);
sol.printTree(root1);
cout << endl;
for (auto k:sol.preorderTraversal(root1)) cout<< k<< " ";
cout << endl;
cout<< endl;
system("pause");
return 0;
}
| [
"cjhou1984@gmail.com"
] | cjhou1984@gmail.com |
337a3a2898325ab039967e734a698a79831311d9 | 4bd600e65b6555f8a6afbb9775fd4739b7d9e4a2 | /Advanced/1026. Table Tennis (30).cpp | 5855e54015c844a14b9f485fd233d4ee9f62d237 | [] | no_license | BaldrLector/PAT | b9891fc3d1639e9b04b41a8e27df18e08c5feeb9 | a502e362fbc5fcc7ff6df4e950f88aaba82dfbe4 | refs/heads/master | 2021-01-21T01:20:52.746157 | 2017-09-13T12:27:37 | 2017-09-13T12:27:37 | 101,874,971 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,789 | cpp | /*
1026. Table Tennis (30)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
A table tennis club has N tables available to the public. The tables are numbered from 1 to N. For any pair of players, if there are some tables open when they arrive, they will be assigned to the available table with the smallest number. If all the tables are occupied, they will have to wait in a queue. It is assumed that every pair of players can play for at most 2 hours.
Your job is to count for everyone in queue their waiting time, and for each table the number of players it has served for the day.
One thing that makes this procedure a bit complicated is that the club reserves some tables for their VIP members. When a VIP table is open, the first VIP pair in the queue will have the priviledge to take it. However, if there is no VIP in the queue, the next pair of players can take it. On the other hand, if when it is the turn of a VIP pair, yet no VIP table is available, they can be assigned as any ordinary players.
Input Specification:
Each input file contains one test case. For each case, the first line contains an integer N (<=10000) - the total number of pairs of players. Then N lines follow, each contains 2 times and a VIP tag: HH:MM:SS - the arriving time, P - the playing time in minutes of a pair of players, and tag - which is 1 if they hold a VIP card, or 0 if not. It is guaranteed that the arriving time is between 08:00:00 and 21:00:00 while the club is open. It is assumed that no two customers arrives at the same time. Following the players' info, there are 2 positive integers: K (<=100) - the number of tables, and M (< K) - the number of VIP tables. The last line contains M table numbers.
Output Specification:
For each test case, first print the arriving time, serving time and the waiting time for each pair of players in the format shown by the sample. Then print in a line the number of players served by each table. Notice that the output must be listed in chronological order of the serving time. The waiting time must be rounded up to an integer minute(s). If one cannot get a table before the closing time, their information must NOT be printed.
Sample Input:
9
20:52:00 10 0
08:00:00 20 0
08:02:00 30 0
20:51:00 10 0
08:10:00 5 0
08:12:00 10 1
20:50:00 10 0
08:01:30 15 1
20:53:00 10 1
3 1
2
Sample Output:
08:00:00 08:00:00 0
08:01:30 08:01:30 0
08:02:00 08:02:00 0
08:12:00 08:16:30 5
08:10:00 08:20:00 10
20:50:00 20:50:00 0
20:51:00 20:51:00 0
20:52:00 20:52:00 0
3 3 2
*/
//未完成
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int K = 111;
const int INF = 100000000;
struct Player {
int arriveTime, startTime, trainTime;
bool isVip;
} newPlayer;
struct Table {
int enTime, numServe;
bool isVip;
} table[K];
vector<Player> player;
int covertTime(int h, int m, int s) {
return h * 3600 + m * 60 + s;
}
bool cmpArriveTime(Player a, Player b) {
return a.arriveTime < b.arriveTime;
}
bool cmpStartTime(Player a, Player b) {
return a.startTime < b.startTime;
}
int nextVipPlayer(int VIPi) {
VIPi++;
while (VIPi < player.size() && player[VIPi].isVip == 0) {
VIPi++;
}
return VIPi;
}
void allotTable(int pid, int tid) {
if (player[pid].arriveTime <= table[tid].enTime) {
player[pid].startTime = table[tid].enTime;
} else {
player[pid].startTime = player[pid].arriveTime;
}
table[tid].enTime=player[pid].startTime+player[pid].trainTime;
table[tid].numServe++;
}
int main() {
freopen("C:\\Users\\71000\\CLionProjects\\demo\\data.in", "r", stdin);
int k, m, n, VIPTable;
scanf("%d", &n);
int stTime = covertTime(8, 0, 0);
int endTime = covertTime(21, 0, 0);
for (int i = 0; i < n; i++) {
int h, m, s, trainTime, isVIP;
scanf("%d:%d:%d %d %d", &h, &m, &s, &trainTime, &isVIP);
newPlayer.arriveTime = covertTime(h, m, s);
newPlayer.startTime = endTime;
if (newPlayer.arriveTime >= endTime) continue;
newPlayer.trainTime=trainTime<=120?trainTime*60:7200;
newPlayer.isVip = isVIP;
player.push_back(newPlayer);
}
scanf("%d%d", &k, &m);
for (int i = 1; i <=k; ++i) {
table[i].enTime=stTime;
table[i].numServe=table[i].isVip=0;
}
for (int i = 0; i < m; ++i) {
scanf("%d", &VIPTable);
table[VIPTable].isVip=1;
}
sort(player.begin(),player.end(),cmpArriveTime);
int i=0,Vipi=-1;
Vipi=nextVipPlayer(Vipi);
while (i<player.size()){
int idx=-1,minEndtime=INF;
for (int j = 1; j <=k; ++j) {
if(table[j].enTime<minEndtime){
minEndtime=table[j].enTime;
idx=j;
}
}
if(table[idx].enTime>=endTime) break;
if(player[i].isVip==1&&i<Vipi){
i++;
continue;
}
if(table[idx].isVip==1){
if(player[i].isVip==1){
allotTable(i,idx);
if(Vipi==i) Vipi=nextVipPlayer(Vipi);
i++;
} else{
if(Vipi<player.size()&&player[Vipi].arriveTime<=table[idx].enTime){
allotTable(Vipi,idx);
Vipi=nextVipPlayer(Vipi);
} else{
allotTable(i,idx);
i++;
}
}
} else{
if(player[i].isVip==0){
allotTable(i,idx);
i++;
} else{
int VIPidx=-1,minVipEndTime=INF;
for (int j = 1; j <=k; ++j) {
if(table[j].isVip==1&&table[j].enTime<minVipEndTime){
minVipEndTime=table[j].enTime;
VIPidx=j;
}
}
if(VIPidx!=-1&&player[i].arriveTime>=table[VIPidx].enTime){
allotTable(i,VIPidx);
if(Vipi==i) Vipi=nextVipPlayer(Vipi);
i++;
} else{
allotTable(i,idx);
if(Vipi==1) Vipi=nextVipPlayer(Vipi);
i++;
}
}
}
}
sort(player.begin(),player.end(),cmpStartTime);
for (int i = 0; i < player.size()&&player[i].startTime<endTime; ++i) {
int t1=player[i].arriveTime;
int t2=player[i].startTime;
printf("%02d:%02d:%02d ", t1/3600, t1%3600/60, t1%60);
printf("%02d:%02d:%02d ", t2/3600, t2%3600/60, t2%60);
printf("%.0f\n", round((t2-t1))/60.0);
}
for (int i = 1; i <=k; ++i) {
printf("%d", table[i].numServe);
if(i<k) printf(" ");
}
return 0;
}
| [
"YGM_Baldr@163.com"
] | YGM_Baldr@163.com |
785943c821f983bc056b05a1b0d9a5c97074c81c | effdc2a761c5fda7e4c3fedb0d874e194e2e3c78 | /String/suffix-array.cc | 2b5c50d3403d62603c33a8fc895b9ea91a2fb6c5 | [] | no_license | duanqn/AC_lib | 286d955462e1a8b5447c27f6b41b1603004e9965 | 305fbabb9c7bcf3d8a4fbbc17bd9248492332cd9 | refs/heads/master | 2020-07-12T22:24:19.410464 | 2015-08-21T09:42:53 | 2015-08-21T09:42:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | cc | //@ Suffix Array (DA)
namespace SA
{
int r[N], sa[N], rank[N], height[N];
int wa[N], wb[N], ws[N], wv[N];
inline int cmp (int *r, int x, int y, int l) {
return r[x] == r[y] && r[x + l] == r[y + l];
}
void da (int *r, int n, int m)
{
int i, j, p, *x = wa, *y = wb;
for (i = 0; i < m; ++i) ws[i] = 0;
for (i = 0; i < n; ++i) ws[x[i] = r[i]]++;
for (i = 1; i < m; ++i) ws[i] += ws[i - 1];
//downto is for stability concern when elements duplicate
for (i = n - 1; i >= 0; --i) sa[--ws[x[i]]] = i;
for (j = 1, p = 1; p < n; j <<= 1, m = p)
{
//sort by (rank[i],rank[i+j])
//second
//second == 0, in arbitary order
for (i = n - j, p = 0; i < n; ++i) y[p++] = i;
// sa[i]-j : (*,i)
for (i = 0; i < n; ++i) if (sa[i] >= j) y[p++] = sa[i] - j;
//first
for (i = 0; i < n; ++i) wv[i] = x[y[i]];
for (i = 0; i < m; ++i) ws[i] = 0;
for (i = 0; i < n; ++i) ws[wv[i]]++;
for (i = 1; i < m; ++i) ws[i] += ws[i - 1];
//rvalue is not i : stability
for (i = n - 1; i >= 0; --i) sa[--ws[wv[i]]] = y[i];
//store the current rank in x
for (swap(x, y), p = i = 1, x[sa[0]] = 0; i < n; ++i)
x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++;
}
}
// LCP(i, SA[Rank[i] - 1]) >= LCP(i - 1, SA[Rank[i - 1] - 1]) - 1
void calheight (int *r, int n)
{
int i, j, k = 0;
for (i = 1; i <= n; ++i) rank[sa[i]] = i;
for (i = 0; i < n; height[rank[i++]] = k)
for (k ? --k : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; ++k) ;
}
struct SparseTable
{
static const int lgN = 22;
int GP[lgN][N], n, lg[N];
SparseTable ()
{
lg[1] = 0;
for (int i = 2, j = 0; i < N; ++i)
lg[i] = (j += ((1 << (j + 1)) == i));
}
void init (int S[], int n)
{
this->n = n;
for (int j = 0; j < n; ++j)
GP[0][j] = S[j];
for (int i = 1; i <= lg[n]; ++i)
for (int j = 0; j + (1 << i) <= n; ++j)
GP[i][j] = min(GP[i - 1][j], GP[i - 1][j + (1 << (i - 1))]);
}
inline int query (int l, int r)
{
assert(l >= 0 && l <= r && r < n);
int z = lg[r - l + 1];
int ret = min(GP[z][l], GP[z][r - (1 << z) + 1]);
return ret;
}
} st;
int n;
// S[0 .. n)
inline void init (int S[], int n)
{
SA::n = n;
S[n] = 0;
da(S, n + 1, 256);
calheight(S, n);
st.init(height, n + 1);
}
inline int LCP (int i, int j)
{
if (i == j) return n - i;
int l = rank[i], r = rank[j];
if (l > r) swap(l, r);
return st.query(l + 1, r);
}
}
| [
"wzy196@gmail.com"
] | wzy196@gmail.com |
d0c7293494a094fd19e814708b99d35a24bab120 | cb018f4cdc9b7b3fc37f53d9b23025cc87cf6437 | /include/CEEEventLoggingSession.hh | 88195a5220cfb7699a66505c67253495445896d5 | [] | no_license | enpg1qz/CEE-test | a782f70d5d3a801f5ce1816f012fc20f7111a113 | 53ae198fd2e57004332159b76242ca1b9a02f9c7 | refs/heads/master | 2021-04-15T15:23:50.980227 | 2018-06-01T11:23:46 | 2018-06-01T11:23:46 | 126,817,878 | 2 | 1 | null | 2018-06-01T05:26:32 | 2018-03-26T11:21:10 | C++ | UTF-8 | C++ | false | false | 552 | hh | #ifndef CEEEventLoggingSession_H
#define CEEEventLoggingSession_H
#include <G4UIsession.hh>
#include <iostream>
#include <fstream>
class CEEEventLoggingSession: public G4UIsession {
public:
CEEEventLoggingSession(G4String coutFile,G4String cerrFile);
~CEEEventLoggingSession();
G4UIsession* SessionStart();
virtual G4int ReceiveG4cout(const G4String&);
virtual G4int ReceiveG4cerr(const G4String&);
private:
std::ofstream coutStream;
std::ofstream cerrStream;
G4String coutFile;
G4String cerrFile;
};
#endif//CEEEventLoggingSession_H
| [
"qinq_net@buaa.edu.cn"
] | qinq_net@buaa.edu.cn |
0aa541d3f46a3abce64c08ee440e1139fde273f1 | 72f43460e5458f5c689e9225100e1728d2ce45a8 | /ui_dialog_reset.h | 587950940ddaf47087d62b00f9621f47023f9112 | [] | no_license | oxiaom/arm_sine | af47ad5be375cd1ee01a2c01b40fb883ff323d59 | 1f3f943c464633c3d075b63ef2312c6669aa84cf | refs/heads/master | 2020-03-14T16:34:12.418477 | 2018-05-28T05:26:28 | 2018-05-28T05:26:28 | 131,700,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,750 | h | /********************************************************************************
** Form generated from reading UI file 'dialog_reset.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DIALOG_RESET_H
#define UI_DIALOG_RESET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
QT_BEGIN_NAMESPACE
class Ui_Dialog_reset
{
public:
QPushButton *pushButton;
QPushButton *pushButton_2;
void setupUi(QDialog *Dialog_reset)
{
if (Dialog_reset->objectName().isEmpty())
Dialog_reset->setObjectName(QStringLiteral("Dialog_reset"));
Dialog_reset->resize(324, 121);
Dialog_reset->setStyleSheet(QStringLiteral("border-image: url(:/K1.png);"));
pushButton = new QPushButton(Dialog_reset);
pushButton->setObjectName(QStringLiteral("pushButton"));
pushButton->setGeometry(QRect(40, 30, 91, 51));
pushButton->setStyleSheet(QLatin1String(" \n"
"QPushButton{color: rgb(255, 255, 255);font: 90 16pt \"Aharoni\"; border-radius:10px;}\n"
"QPushButton{border-image: url(://K7.png); border-radius:10px;}\n"
"QPushButton:hover{border-image: url(:/K6.png); border-radius:10px;} \n"
"QPushButton:pressed{border-image: url(:/K6.png); border-radius:10px;}"));
pushButton_2 = new QPushButton(Dialog_reset);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
pushButton_2->setGeometry(QRect(160, 30, 111, 51));
pushButton_2->setStyleSheet(QLatin1String(" \n"
"QPushButton{color: rgb(255, 255, 255);font: 90 16pt \"Aharoni\"; border-radius:10px;}\n"
"QPushButton{border-image: url(://KR.png); border-radius:10px;}\n"
"QPushButton:hover{border-image: url(:/K6.png); border-radius:10px;} \n"
"QPushButton:pressed{border-image: url(:/K6.png); border-radius:10px;}"));
retranslateUi(Dialog_reset);
QMetaObject::connectSlotsByName(Dialog_reset);
} // setupUi
void retranslateUi(QDialog *Dialog_reset)
{
Dialog_reset->setWindowTitle(QApplication::translate("Dialog_reset", "Dialog", 0));
pushButton->setText(QApplication::translate("Dialog_reset", "\345\217\226\346\266\210", 0));
pushButton_2->setText(QApplication::translate("Dialog_reset", "\347\241\256\345\256\232", 0));
} // retranslateUi
};
namespace Ui {
class Dialog_reset: public Ui_Dialog_reset {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DIALOG_RESET_H
| [
"244255055@qq.com"
] | 244255055@qq.com |
79854e86062812f33610362e8fe38605137ad89d | 743e43898f0ffd8a5602dd8d908a6a20fdccf597 | /solvers/BFSSolver.cpp | eb25b85b1df3abc8177976009015bef9b5379cfe | [] | no_license | alexander-rivaldy/maze | dad112baa046afd8dd23d9be8a29f4b954272ea1 | d9b890ced1f59873dbb3782c7464ddffa739488c | refs/heads/master | 2021-06-24T21:42:04.720569 | 2017-09-08T09:13:34 | 2017-09-08T09:13:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | cpp | #include "BFSSolver.h"
#define START_POINT 0
#define CAN_SOLVE 1
#define CANT_SOLVE -1
using namespace std;
int BFSSolver::solve()
{
// Variables
//clock_t variables to record time required for the solver
auto tStart = chrono::high_resolution_clock::now();
visited = maze.cells; // Check Visited Cell
queue<Cell*> cells_queue; // Expansion area
vector<Cell *> pathway_queue ;
Cell * current_cell = nullptr; // Current Cell
Cell last_cell , *neighbour_cell;
// Initializes Cell
visited[START_POINT][START_POINT].visited = true;
current_cell = &visited[START_POINT][START_POINT];
last_cell.x = xFinish;
last_cell.y = yFinish;
current_cell->parent = nullptr;
current_cell->visited = true;
// Mark the current node as visited and enqueue it
cells_queue.push(current_cell);
pathway_queue.push_back(current_cell);
// While we have cells
while(!cells_queue.empty())
{
// Grab the First
current_cell = cells_queue.front();
cells_queue.pop();
// Reach the last cell = Problem Solved !
if(current_cell->x == last_cell.x && current_cell->y == last_cell.y)
{
// Print The PathSaver
vector<Cell*>real_path;
Cell* current;
for(unsigned int i = 0 ; i < pathway_queue.size() ; i++)
{
if(pathway_queue[i]->x == xFinish
&& pathway_queue[i]->y == yFinish)
{
current = pathway_queue[i];
}
}
while(current->parent!=nullptr)
{
Edge e;// Initialize to empty again
// Set A point
e.xCellA = current->x;
e.yCellA = current->y;
// Set B Point
e.xCellB = current->parent->x;
e.yCellB = current->parent->y;
path.push_back(e);
real_path.push_back(current->parent);
current = current->parent;
}
//calculating time taken to solve maze
auto tEnd = chrono::high_resolution_clock::now();
auto diff =chrono::duration_cast<chrono::microseconds>(tEnd-tStart);
cout<<"Time taken to solve : "<< diff.count() << " microseconds"<<endl;
//calculate time to draw path
tStart = chrono::high_resolution_clock::now();
//draws the path over the maze
drawPath(); // Path is vector<Edges>
tEnd = chrono::high_resolution_clock::now();
diff =chrono::duration_cast<chrono::microseconds>(tEnd-tStart);
cout<<"Time taken to write SVG : "<< diff.count() << " microseconds"<<endl;
return CAN_SOLVE;
}
else
{
// Find Unvisited Neighbour
for(auto i = current_cell->neighbours.begin();
i!=current_cell->neighbours.end(); i++)
{
neighbour_cell = *i;
// If it not visited -> mark it and add to queue
if(neighbour_cell->visited == false)
{
neighbour_cell->visited = true ; // Mark it as visited
neighbour_cell->parent = current_cell;
cells_queue.push(neighbour_cell);
pathway_queue.push_back(neighbour_cell);
}
}
}
}
return CANT_SOLVE;
}
| [
"root@DESKTOP-60SPF02.localdomain"
] | root@DESKTOP-60SPF02.localdomain |
80f4482cf2916aa28603facb805343e6df5386f8 | e0c2f2f1107dd67ba778d4d8e3b77de7ea29e68c | /src/numerics/rk2.cpp | 9e566e1f989b0e3d6473106d44611d9b590e94a4 | [
"Apache-2.0"
] | permissive | AnthonyVa/Cardcell | a4edb9e0470a7a9acecb99c9842d929ef6a9bf4b | ac1360d03d2ae9bf8d03a45c7e1823999f82addc | refs/heads/master | 2016-09-01T12:16:03.794281 | 2015-12-11T19:54:25 | 2015-12-11T19:54:25 | 47,361,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | /*
* rk2.cpp
*
* Created on: Nov 13, 2014
* Author: tony
*/
#include "rk2.h"
namespace solvers {
bool rk2::step( const double told, const double tnew, double* Yold, double* Ynew ){
const double dt = tnew - told;
const double dt2 = dt/2;
const double thalf = told + dt2;
// First function call k1 = dt f(tn, yn) / 2
cells->celldiffeq( told, Yold, k1);
// Finish computing k1 and pre-compute Yhalf for next step
for (int i=0; i< neqns; i++) {
k1[i] = k1[i] * dt2;
// Yhalf is (yn + k1)
Yhalf[i] = Yold[i] + k1[i];
}
// Second function call k2 = dt f(tn+1/2, yn + k1)
cells->celldiffeq( thalf, Yhalf, dYdt);
// Compute the new state
for (int i=0; i< neqns; i++)
Ynew[i] = Yold[i] + dYdt[i] * dt; //
return true; // successful step
}
} /* namespace solvers */
| [
"anthonyvar@gmail.com"
] | anthonyvar@gmail.com |
0fd8119343e8ec08f183e335700de22398dadc81 | 9d7b758dd5815cac3e92123941763439d5948141 | /ControllerApp/Classes/Native/Photon3Unity3D_ExitGames_Client_Photon_CmdLogItem2374365153.h | d8d4dd878a628b40772f603953329fab7ea36db8 | [] | no_license | kongriley/TronVR | 083758ec925bfca541376f9f6a250d70b6082208 | 4819148343616a1327f3e5eec7d14d2cfeca7abe | refs/heads/master | 2021-01-19T08:46:30.256678 | 2017-04-08T16:42:03 | 2017-04-08T16:42:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,659 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Object2689449295.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// ExitGames.Client.Photon.CmdLogItem
struct CmdLogItem_t2374365153 : public Il2CppObject
{
public:
// System.Int32 ExitGames.Client.Photon.CmdLogItem::TimeInt
int32_t ___TimeInt_0;
// System.Int32 ExitGames.Client.Photon.CmdLogItem::Channel
int32_t ___Channel_1;
// System.Int32 ExitGames.Client.Photon.CmdLogItem::SequenceNumber
int32_t ___SequenceNumber_2;
// System.Int32 ExitGames.Client.Photon.CmdLogItem::Rtt
int32_t ___Rtt_3;
// System.Int32 ExitGames.Client.Photon.CmdLogItem::Variance
int32_t ___Variance_4;
public:
inline static int32_t get_offset_of_TimeInt_0() { return static_cast<int32_t>(offsetof(CmdLogItem_t2374365153, ___TimeInt_0)); }
inline int32_t get_TimeInt_0() const { return ___TimeInt_0; }
inline int32_t* get_address_of_TimeInt_0() { return &___TimeInt_0; }
inline void set_TimeInt_0(int32_t value)
{
___TimeInt_0 = value;
}
inline static int32_t get_offset_of_Channel_1() { return static_cast<int32_t>(offsetof(CmdLogItem_t2374365153, ___Channel_1)); }
inline int32_t get_Channel_1() const { return ___Channel_1; }
inline int32_t* get_address_of_Channel_1() { return &___Channel_1; }
inline void set_Channel_1(int32_t value)
{
___Channel_1 = value;
}
inline static int32_t get_offset_of_SequenceNumber_2() { return static_cast<int32_t>(offsetof(CmdLogItem_t2374365153, ___SequenceNumber_2)); }
inline int32_t get_SequenceNumber_2() const { return ___SequenceNumber_2; }
inline int32_t* get_address_of_SequenceNumber_2() { return &___SequenceNumber_2; }
inline void set_SequenceNumber_2(int32_t value)
{
___SequenceNumber_2 = value;
}
inline static int32_t get_offset_of_Rtt_3() { return static_cast<int32_t>(offsetof(CmdLogItem_t2374365153, ___Rtt_3)); }
inline int32_t get_Rtt_3() const { return ___Rtt_3; }
inline int32_t* get_address_of_Rtt_3() { return &___Rtt_3; }
inline void set_Rtt_3(int32_t value)
{
___Rtt_3 = value;
}
inline static int32_t get_offset_of_Variance_4() { return static_cast<int32_t>(offsetof(CmdLogItem_t2374365153, ___Variance_4)); }
inline int32_t get_Variance_4() const { return ___Variance_4; }
inline int32_t* get_address_of_Variance_4() { return &___Variance_4; }
inline void set_Variance_4(int32_t value)
{
___Variance_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"wfrankw9@gmail.com"
] | wfrankw9@gmail.com |
b6cde087aa3044da4299ca9637f989f6da00d898 | e73b53540848c0411ccf4d68e84b6f4737c2f1ff | /runtime/cpp/src/external/yas/serializers/binary/qt/qt_qstack_serializers.hpp | 745fed9916cb369abd2d8abf118730b124160848 | [
"Apache-2.0"
] | permissive | DaMSL/K3 | 4d194ba4ca8229c56eb42b44b502542e182deaec | 51749157844e76ae79dba619116fc5ad9d685643 | refs/heads/master | 2020-04-06T07:05:04.883947 | 2016-07-11T22:00:07 | 2016-07-11T22:00:07 | 10,148,287 | 17 | 6 | null | 2015-05-05T21:12:36 | 2013-05-18T23:06:59 | HTML | UTF-8 | C++ | false | false | 2,772 | hpp |
// Copyright (c) 2010-2015 niXman (i dot nixman dog gmail dot com). All
// rights reserved.
//
// This file is part of YAS(https://github.com/niXman/yas) project.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef _yas__binary__qstack_serializer_hpp
#define _yas__binary__qstack_serializer_hpp
#include <yas/detail/config/config.hpp>
#if defined(YAS_SERIALIZE_QT_TYPES)
#include <QtCore/specialization_type>
namespace yas {
namespace detail {
/***************************************************************************/
template<>
struct serializer<
type_prop::not_a_pod,
ser_method::use_internal_serializer,
archive_type::binary,
direction::out,
specialization_type
> {
template<typename Archive>
static Archive& apply(Archive& ar, const specialization_type&) {
}
};
template<>
struct serializer<
type_prop::not_a_pod,
ser_method::use_internal_serializer,
archive_type::binary,
direction::in,
specialization_type
> {
template<typename Archive>
static Archive& apply(Archive& ar, specialization_type&) {
}
};
/***************************************************************************/
} // namespace detail
} // namespace yas
#endif // defined(YAS_SERIALIZE_QT_TYPES)
#endif // _yas__binary__qstack_serializer_hpp
| [
"joshdub223@gmail.com"
] | joshdub223@gmail.com |
8ecc63e992dfea81215200299f7c7eb556076279 | 30cd1a7af92fb1243c33f9b8dde445c29118bd1a | /third_party/allwpilib_2016/wpilibcIntegrationTests/src/PCMTest.cpp | 14f23ca8e7aba705a90ff67c0c3b375a577d14ea | [
"BSD-2-Clause"
] | permissive | FRC1296/CheezyDriver2016 | 3907a34fd5f8ccd2c90ab1042782106c0947c0cb | 4aa95b16bb63137250d2ad2529b03b2bd56c78c0 | refs/heads/master | 2016-08-12T23:22:00.077919 | 2016-03-19T05:56:18 | 2016-03-19T05:56:18 | 51,854,487 | 2 | 0 | null | 2016-02-29T10:10:27 | 2016-02-16T17:27:07 | C++ | UTF-8 | C++ | false | false | 5,692 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include <AnalogInput.h>
#include <Compressor.h>
#include <DigitalInput.h>
#include <DigitalOutput.h>
#include <DoubleSolenoid.h>
#include <Solenoid.h>
#include <Timer.h>
#include "gtest/gtest.h"
#include "TestBench.h"
/* The PCM switches the compressor up to a couple seconds after the pressure
switch changes. */
static const double kCompressorDelayTime = 3.0;
/* Solenoids should change much more quickly */
static const double kSolenoidDelayTime = 0.5;
/* The voltage divider on the test bench should bring the compressor output
to around these values. */
static const double kCompressorOnVoltage = 5.00;
static const double kCompressorOffVoltage = 1.68;
class PCMTest : public testing::Test {
protected:
Compressor *m_compressor;
DigitalOutput *m_fakePressureSwitch;
AnalogInput *m_fakeCompressor;
DoubleSolenoid *m_doubleSolenoid;
DigitalInput *m_fakeSolenoid1, *m_fakeSolenoid2;
virtual void SetUp() override {
m_compressor = new Compressor();
m_fakePressureSwitch =
new DigitalOutput(TestBench::kFakePressureSwitchChannel);
m_fakeCompressor = new AnalogInput(TestBench::kFakeCompressorChannel);
m_fakeSolenoid1 = new DigitalInput(TestBench::kFakeSolenoid1Channel);
m_fakeSolenoid2 = new DigitalInput(TestBench::kFakeSolenoid2Channel);
}
virtual void TearDown() override {
delete m_compressor;
delete m_fakePressureSwitch;
delete m_fakeCompressor;
delete m_fakeSolenoid1;
delete m_fakeSolenoid2;
}
void Reset() {
m_compressor->Stop();
m_fakePressureSwitch->Set(false);
}
};
/**
* Test if the compressor turns on and off when the pressure switch is toggled
*/
TEST_F(PCMTest, PressureSwitch) {
Reset();
m_compressor->SetClosedLoopControl(true);
// Turn on the compressor
m_fakePressureSwitch->Set(true);
Wait(kCompressorDelayTime);
EXPECT_NEAR(kCompressorOnVoltage, m_fakeCompressor->GetVoltage(), 0.1)
<< "Compressor did not turn on when the pressure switch turned on.";
// Turn off the compressor
m_fakePressureSwitch->Set(false);
Wait(kCompressorDelayTime);
EXPECT_NEAR(kCompressorOffVoltage, m_fakeCompressor->GetVoltage(), 0.1)
<< "Compressor did not turn off when the pressure switch turned off.";
}
/**
* Test if the correct solenoids turn on and off when they should
*/
TEST_F(PCMTest, Solenoid) {
Reset();
Solenoid solenoid1(TestBench::kSolenoidChannel1);
Solenoid solenoid2(TestBench::kSolenoidChannel2);
// Turn both solenoids off
solenoid1.Set(false);
solenoid2.Set(false);
Wait(kSolenoidDelayTime);
EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off";
EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off";
EXPECT_FALSE(solenoid1.Get()) << "Solenoid #1 did not read off";
EXPECT_FALSE(solenoid2.Get()) << "Solenoid #2 did not read off";
// Turn one solenoid on and one off
solenoid1.Set(true);
solenoid2.Set(false);
Wait(kSolenoidDelayTime);
EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on";
EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off";
EXPECT_TRUE(solenoid1.Get()) << "Solenoid #1 did not read on";
EXPECT_FALSE(solenoid2.Get()) << "Solenoid #2 did not read off";
// Turn one solenoid on and one off
solenoid1.Set(false);
solenoid2.Set(true);
Wait(kSolenoidDelayTime);
EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off";
EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on";
EXPECT_FALSE(solenoid1.Get()) << "Solenoid #1 did not read off";
EXPECT_TRUE(solenoid2.Get()) << "Solenoid #2 did not read on";
// Turn both on
solenoid1.Set(true);
solenoid2.Set(true);
Wait(kSolenoidDelayTime);
EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on";
EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on";
EXPECT_TRUE(solenoid1.Get()) << "Solenoid #1 did not read on";
EXPECT_TRUE(solenoid2.Get()) << "Solenoid #2 did not read on";
}
/**
* Test if the correct solenoids turn on and off when they should when used
* with the DoubleSolenoid class.
*/
TEST_F(PCMTest, DoubleSolenoid) {
DoubleSolenoid solenoid(TestBench::kSolenoidChannel1,
TestBench::kSolenoidChannel2);
solenoid.Set(DoubleSolenoid::kOff);
Wait(kSolenoidDelayTime);
EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off";
EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off";
EXPECT_TRUE(solenoid.Get() == DoubleSolenoid::kOff) << "Solenoid does not read off";
solenoid.Set(DoubleSolenoid::kForward);
Wait(kSolenoidDelayTime);
EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on";
EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off";
EXPECT_TRUE(solenoid.Get() == DoubleSolenoid::kForward) << "Solenoid does not read forward";
solenoid.Set(DoubleSolenoid::kReverse);
Wait(kSolenoidDelayTime);
EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off";
EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on";
EXPECT_TRUE(solenoid.Get() == DoubleSolenoid::kReverse) << "Solenoid does not read reverse";
}
| [
"tkb@cheezy.usfluidtech.com"
] | tkb@cheezy.usfluidtech.com |
a9bc571db099f81fed22d42c3558b8fe99a0f28e | 3963d4f07de199407b893600b6bd48b9887ee8f8 | /algorithmTest/36_40/빙고게임.cpp | 39e399460037c64098e0746b77b2ef881b3083bb | [] | no_license | james-sungjae-lee/2018_CPP | 6f9fc15d183293f1c04a67071d4f24f15c483331 | a277045f07be1350f2c914dbebfc5f24d6f2e6dd | refs/heads/master | 2022-09-22T23:41:45.030906 | 2018-06-10T01:22:20 | 2018-06-10T01:22:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,987 | cpp | #include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int checkRow(int check[25])
{
if(check[0] and check[1] and check[2] and check[3] and check[4])
return 1;
if(check[5] and check[6] and check[7] and check[8] and check[9])
return 1;
if(check[10] and check[11] and check[12] and check[13] and check[14])
return 1;
if(check[15] and check[16] and check[17] and check[18] and check[19])
return 1;
if(check[20] and check[21] and check[22] and check[23] and check[24])
return 1;
return 0;
}
int checkColumn(int check[25]){
if(check[0] and check[5] and check[10] and check[15] and check[20] )
return 1;
if(check[1] and check[6] and check[11] and check[16] and check[21])
return 1;
if(check[2] and check[7] and check[12] and check[17] and check[22])
return 1;
if(check[3] and check[8] and check[13] and check[18] and check[23])
return 1;
if(check[4] and check[9] and check[14] and check[19] and check[24])
return 1;
return 0;
}
int check1(int check[25]){
if(check[0] and check[6] and check[12] and check[18] and check[24])
return 1;
if(check[4] and check[8] and check[12] and check[16] and check[20])
return 1;
return 0;
}
int check2(int check[25]){
if(check[0] and check[4] and check[20] and check[24])
{
return 1;
}
return 0;
}
int main()
{
ifstream is;
is.open("input.txt");
int numTestCases;
is>>numTestCases;
for(int i=0; i<numTestCases; i++)
{
int result=0;
int inNum[25]={0};
int check[25]={0};
check[12]=1;
/*make bingo*/
for(int j=0; j<25; j++)
{
is>>inNum[j];
}
/*check bingo */
int num;
for(int j=1; j<76; j++)
{
is>>num;
for(int k=0; k<25; k++)
{
if(num==inNum[k])
{
check[k]=1;
}
}
if(result!=0);
else if(checkRow(check)==1)
{
result=j;
}
else if(checkColumn(check)==1)
{
result=j;
}
else if(check1(check)==1)
{
result=j;
}
else if(check2(check)==1)
{
result=j;
}
}
cout<<result<<endl;
}
}
| [
"odobenuseKR@gmail.com"
] | odobenuseKR@gmail.com |
f6210567e3f2b25b70d4c151d75f401febb65953 | 311525f7de84975434f55c00b545ccf7fe3dcce6 | /online/cf/polynomial_2022/same_count_one.cpp | 848a93e1802d423c4ed66e3a9249db0f71f4575b | [] | no_license | fishy15/competitive_programming | 60f485bc4022e41efb0b7d2e12d094213d074f07 | d9bca2e6bea704f2bfe5a30e08aa0788be6a8022 | refs/heads/master | 2023-08-16T02:05:08.270992 | 2023-08-06T01:00:21 | 2023-08-06T01:00:21 | 171,861,737 | 29 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,187 | cpp | #include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <array>
#include <algorithm>
#include <utility>
#include <map>
#include <queue>
#include <set>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <functional>
#include <numeric>
#define ll long long
#define ld long double
#define eps 1e-8
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
// change if necessary
#define MAXN 1000000
using namespace std;
void solve() {
int n, m;
cin >> n >> m;
vector grid(n, vector(m, 0));
vector zero_col(m, vector<int>());
vector one_col(m, vector<int>());
vector cur(n, 0);
int tot = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
if (grid[i][j] == 0) {
zero_col[j].push_back(i);
} else {
tot++;
cur[i]++;
one_col[j].push_back(i);
}
}
}
if (tot % n != 0) {
cout << "-1\n";
return;
}
int want = tot / n;
vector<array<int, 3>> ops;
for (int j = 0; j < m; j++) {
auto &zero = zero_col[j];
auto &one = one_col[j];
while (true) {
while (!zero.empty() && cur[zero.back()] >= want) zero.pop_back();
while (!one.empty() && cur[one.back()] <= want) one.pop_back();
if (!zero.empty() && !one.empty()) {
int low = zero.back();
int high = one.back();
zero.pop_back();
one.pop_back();
ops.push_back({low, high, j});
cur[low]++;
cur[high]--;
} else {
break;
}
}
}
for (int i = 0; i < n; i++) {
if (cur[i] != want) {
cout << "-1\n";
return;
}
}
cout << ops.size() << '\n';
for (auto [x, y, z] : ops) {
cout << x + 1 << ' ' << y + 1 << ' ' << z + 1 << '\n';
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| [
"aaryan.prakash3.14@gmail.com"
] | aaryan.prakash3.14@gmail.com |
397d828930fcd8f8c71a519fd01d98891d9655cd | 992da214facdfe75afd595e141685a5958c256dc | /ComponentUnicapImageClient/smartsoft/src/ComponentUnicapImageClientCore.hh | dc49170c47bf9d6df15c0ba4ec0d2fb037c61543 | [] | no_license | HannesBachter/ComponentRepository | e9d66bcc52108ebfa03e161122ad0e0d0042f3d6 | 71b7a90cf8b5cc91f70757b6fafbaf78d4c1b7a8 | refs/heads/master | 2023-02-16T13:17:17.161655 | 2020-08-03T14:43:54 | 2020-08-03T14:43:54 | 285,233,349 | 0 | 1 | null | 2020-08-05T08:51:59 | 2020-08-05T08:51:58 | null | UTF-8 | C++ | false | false | 2,493 | hh | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
// --------------------------------------------------------------------------
//
// Copyright (C) 2011 Matthias Lutz, Dennis Stampfer
//
// schlegel@hs-ulm.de
//
// Prof. Dr. Christian Schlegel
// University of Applied Sciences
// Prittwitzstr. 10
// D-89075 Ulm
// Germany
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//
// --------------------------------------------------------------------------
#ifndef _COMPONENTUNICAPIMAGECLIENTCORE_HH
#define _COMPONENTUNICAPIMAGECLIENTCORE_HH
#include "aceSmartSoft.hh"
#include <iostream>
#include <cv.h>
#include <opencv/highgui.h>
#include <DomainVision/CommVideoImage.hh>
#include "OpenCVHelpers/OpenCVHelpers.hh"
#include <mrpt/poses/CPose3D.h>
#include "VisualizationHelper.hh"
using namespace mrpt::poses;
class ComponentUnicapImageClientCore
{
private:
public:
ComponentUnicapImageClientCore();
IplImage* convertDataArrayToIplImage(DomainVision::CommVideoImage &query_image, CvSize size);
IplImage* currentImage;
CPose3D currentImagePose;
SmartACE::SmartMutex CurrentImageMutex;
VisualizationHelper vHelper;
};
#endif
| [
"lutz@hs-ulm.de"
] | lutz@hs-ulm.de |
6fe0752c926459bdcdf3d869ee1a7612bd7f65e0 | 24f2ea3b5bf980b5029b7219f431b0d2196f3b2e | /MobileStatementReader/AggregatedRecord.h | 5259548d063183ef621170fb2ef2b4d8b8342d3a | [] | no_license | fmi-lab/sdp-2017-kn-group3 | 0150a6414e467b4bffbc3bb3a2aa3afee578550e | 2f8f542a44c64a8f33b87850c6c240db81fc5ea0 | refs/heads/master | 2021-09-04T10:17:48.319967 | 2018-01-17T22:53:15 | 2018-01-17T22:53:15 | 106,745,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | #ifndef AGGREGATEDRECORD_H
#define AGGREGATEDRECORD_H
#include <ostream>
#include <string>
class AggregatedRecord
{
public:
AggregatedRecord(std::string="", int=0);
void addAmount(int);
std::string getDate() const;
friend std::ostream& operator<<(std::ostream&, const AggregatedRecord&);
protected:
private:
std::string date;
int amount;
};
#endif // AGGREGATEDRECORD_H
| [
"mvkraeva@gmail.com"
] | mvkraeva@gmail.com |
bb78225065ffc028a3f656c405e31b80fdbbae83 | ba63cfe1d4b142375ec65223dded3a74372da876 | /third_party/dawn/src/dawn_native/opengl/TextureGL.cpp | 0c4ea27bd787bda0f0e231063cbc83d5c776bc0b | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | iseeyo/src | 5843b9c612769628480e2e218ea6a0974ebdf5fd | 1517a4f7cdab5e0688339edecb9f9e77f9cb8bf2 | refs/heads/master | 2023-06-01T09:11:21.303692 | 2021-07-11T13:00:23 | 2021-07-11T13:00:23 | 300,853,336 | 0 | 0 | BSD-3-Clause | 2020-12-02T11:09:16 | 2020-10-03T10:25:55 | null | UTF-8 | C++ | false | false | 18,818 | cpp | // Copyright 2017 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dawn_native/opengl/TextureGL.h"
#include "common/Assert.h"
#include "common/Constants.h"
#include "common/Math.h"
#include "dawn_native/opengl/BufferGL.h"
#include "dawn_native/opengl/DeviceGL.h"
#include "dawn_native/opengl/UtilsGL.h"
namespace dawn_native { namespace opengl {
namespace {
GLenum TargetForTexture(const TextureDescriptor* descriptor) {
switch (descriptor->dimension) {
case wgpu::TextureDimension::e2D:
if (descriptor->size.depth > 1) {
ASSERT(descriptor->sampleCount == 1);
return GL_TEXTURE_2D_ARRAY;
} else {
if (descriptor->sampleCount > 1) {
return GL_TEXTURE_2D_MULTISAMPLE;
} else {
return GL_TEXTURE_2D;
}
}
default:
UNREACHABLE();
return GL_TEXTURE_2D;
}
}
GLenum TargetForTextureViewDimension(wgpu::TextureViewDimension dimension,
uint32_t arrayLayerCount,
uint32_t sampleCount) {
switch (dimension) {
case wgpu::TextureViewDimension::e2D:
return (sampleCount > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
case wgpu::TextureViewDimension::e2DArray:
if (arrayLayerCount == 1) {
return (sampleCount > 1) ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
}
ASSERT(sampleCount == 1);
return GL_TEXTURE_2D_ARRAY;
case wgpu::TextureViewDimension::Cube:
return GL_TEXTURE_CUBE_MAP;
case wgpu::TextureViewDimension::CubeArray:
return GL_TEXTURE_CUBE_MAP_ARRAY;
default:
UNREACHABLE();
return GL_TEXTURE_2D;
}
}
GLuint GenTexture(const OpenGLFunctions& gl) {
GLuint handle = 0;
gl.GenTextures(1, &handle);
return handle;
}
bool UsageNeedsTextureView(wgpu::TextureUsage usage) {
constexpr wgpu::TextureUsage kUsageNeedingTextureView =
wgpu::TextureUsage::Storage | wgpu::TextureUsage::Sampled;
return usage & kUsageNeedingTextureView;
}
bool RequiresCreatingNewTextureView(const TextureBase* texture,
const TextureViewDescriptor* textureViewDescriptor) {
if (texture->GetFormat().format != textureViewDescriptor->format) {
return true;
}
if (texture->GetArrayLayers() != textureViewDescriptor->arrayLayerCount) {
return true;
}
if (texture->GetNumMipLevels() != textureViewDescriptor->mipLevelCount) {
return true;
}
switch (textureViewDescriptor->dimension) {
case wgpu::TextureViewDimension::Cube:
case wgpu::TextureViewDimension::CubeArray:
return true;
default:
break;
}
return false;
}
} // namespace
// Texture
Texture::Texture(Device* device, const TextureDescriptor* descriptor)
: Texture(device, descriptor, GenTexture(device->gl), TextureState::OwnedInternal) {
const OpenGLFunctions& gl = ToBackend(GetDevice())->gl;
uint32_t width = GetWidth();
uint32_t height = GetHeight();
uint32_t levels = GetNumMipLevels();
uint32_t arrayLayers = GetArrayLayers();
uint32_t sampleCount = GetSampleCount();
const GLFormat& glFormat = GetGLFormat();
gl.BindTexture(mTarget, mHandle);
// glTextureView() requires the value of GL_TEXTURE_IMMUTABLE_FORMAT for origtexture to be
// GL_TRUE, so the storage of the texture must be allocated with glTexStorage*D.
// https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTextureView.xhtml
switch (GetDimension()) {
case wgpu::TextureDimension::e2D:
if (arrayLayers > 1) {
ASSERT(!IsMultisampledTexture());
gl.TexStorage3D(mTarget, levels, glFormat.internalFormat, width, height,
arrayLayers);
} else {
if (IsMultisampledTexture()) {
gl.TexStorage2DMultisample(mTarget, sampleCount, glFormat.internalFormat,
width, height, true);
} else {
gl.TexStorage2D(mTarget, levels, glFormat.internalFormat, width, height);
}
}
break;
default:
UNREACHABLE();
}
// The texture is not complete if it uses mipmapping and not all levels up to
// MAX_LEVEL have been defined.
gl.TexParameteri(mTarget, GL_TEXTURE_MAX_LEVEL, levels - 1);
if (GetDevice()->IsToggleEnabled(Toggle::NonzeroClearResourcesOnCreationForTesting)) {
GetDevice()->ConsumedError(
ClearTexture(GetAllSubresources(), TextureBase::ClearValue::NonZero));
}
}
Texture::Texture(Device* device,
const TextureDescriptor* descriptor,
GLuint handle,
TextureState state)
: TextureBase(device, descriptor, state), mHandle(handle) {
mTarget = TargetForTexture(descriptor);
}
Texture::~Texture() {
DestroyInternal();
}
void Texture::DestroyImpl() {
if (GetTextureState() == TextureState::OwnedInternal) {
ToBackend(GetDevice())->gl.DeleteTextures(1, &mHandle);
mHandle = 0;
}
}
GLuint Texture::GetHandle() const {
return mHandle;
}
GLenum Texture::GetGLTarget() const {
return mTarget;
}
const GLFormat& Texture::GetGLFormat() const {
return ToBackend(GetDevice())->GetGLFormat(GetFormat());
}
MaybeError Texture::ClearTexture(const SubresourceRange& range,
TextureBase::ClearValue clearValue) {
// TODO(jiawei.shao@intel.com): initialize the textures with compressed formats.
if (GetFormat().isCompressed) {
return {};
}
Device* device = ToBackend(GetDevice());
const OpenGLFunctions& gl = device->gl;
uint8_t clearColor = (clearValue == TextureBase::ClearValue::Zero) ? 0 : 1;
float fClearColor = (clearValue == TextureBase::ClearValue::Zero) ? 0.f : 1.f;
if (GetFormat().isRenderable) {
if (GetFormat().HasDepthOrStencil()) {
bool doDepthClear = GetFormat().HasDepth();
bool doStencilClear = GetFormat().HasStencil();
GLfloat depth = fClearColor;
GLint stencil = clearColor;
if (doDepthClear) {
gl.DepthMask(GL_TRUE);
}
if (doStencilClear) {
gl.StencilMask(GetStencilMaskFromStencilFormat(GetFormat().format));
}
auto DoClear = [&]() {
if (doDepthClear && doStencilClear) {
gl.ClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
} else if (doDepthClear) {
gl.ClearBufferfv(GL_DEPTH, 0, &depth);
} else if (doStencilClear) {
gl.ClearBufferiv(GL_STENCIL, 0, &stencil);
}
};
GLuint framebuffer = 0;
gl.GenFramebuffers(1, &framebuffer);
gl.BindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer);
for (uint32_t level = range.baseMipLevel;
level < range.baseMipLevel + range.levelCount; ++level) {
switch (GetDimension()) {
case wgpu::TextureDimension::e2D:
if (GetArrayLayers() == 1) {
if (clearValue == TextureBase::ClearValue::Zero &&
IsSubresourceContentInitialized(
SubresourceRange::SingleSubresource(level, 0))) {
// Skip lazy clears if already initialized.
continue;
}
gl.FramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
GL_DEPTH_STENCIL_ATTACHMENT, GetGLTarget(),
GetHandle(), static_cast<GLint>(level));
DoClear();
} else {
for (uint32_t layer = range.baseArrayLayer;
layer < range.baseArrayLayer + range.layerCount; ++layer) {
if (clearValue == TextureBase::ClearValue::Zero &&
IsSubresourceContentInitialized(
SubresourceRange::SingleSubresource(level, layer))) {
// Skip lazy clears if already initialized.
continue;
}
gl.FramebufferTextureLayer(
GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
GetHandle(), static_cast<GLint>(level),
static_cast<GLint>(layer));
DoClear();
}
}
break;
default:
UNREACHABLE();
}
}
gl.DeleteFramebuffers(1, &framebuffer);
} else {
static constexpr uint32_t MAX_TEXEL_SIZE = 16;
ASSERT(GetFormat().blockByteSize <= MAX_TEXEL_SIZE);
std::array<GLbyte, MAX_TEXEL_SIZE> clearColorData;
clearColor = (clearValue == TextureBase::ClearValue::Zero) ? 0 : 255;
clearColorData.fill(clearColor);
const GLFormat& glFormat = GetGLFormat();
for (uint32_t level = range.baseMipLevel;
level < range.baseMipLevel + range.levelCount; ++level) {
Extent3D mipSize = GetMipLevelPhysicalSize(level);
for (uint32_t layer = range.baseArrayLayer;
layer < range.baseArrayLayer + range.layerCount; ++layer) {
if (clearValue == TextureBase::ClearValue::Zero &&
IsSubresourceContentInitialized(
SubresourceRange::SingleSubresource(level, layer))) {
// Skip lazy clears if already initialized.
continue;
}
gl.ClearTexSubImage(mHandle, static_cast<GLint>(level), 0, 0,
static_cast<GLint>(layer), mipSize.width,
mipSize.height, 1, glFormat.format, glFormat.type,
clearColorData.data());
}
}
}
} else {
// TODO(natlee@microsoft.com): test compressed textures are cleared
// create temp buffer with clear color to copy to the texture image
ASSERT(kTextureBytesPerRowAlignment % GetFormat().blockByteSize == 0);
uint32_t bytesPerRow =
Align((GetWidth() / GetFormat().blockWidth) * GetFormat().blockByteSize,
kTextureBytesPerRowAlignment);
// Make sure that we are not rounding
ASSERT(bytesPerRow % GetFormat().blockByteSize == 0);
ASSERT(GetHeight() % GetFormat().blockHeight == 0);
dawn_native::BufferDescriptor descriptor = {};
descriptor.mappedAtCreation = true;
descriptor.usage = wgpu::BufferUsage::CopySrc;
descriptor.size = bytesPerRow * (GetHeight() / GetFormat().blockHeight);
if (descriptor.size > std::numeric_limits<uint32_t>::max()) {
return DAWN_OUT_OF_MEMORY_ERROR("Unable to allocate buffer.");
}
// TODO(natlee@microsoft.com): use Dynamic Uplaoder here for temp buffer
Ref<Buffer> srcBuffer = AcquireRef(ToBackend(device->CreateBuffer(&descriptor)));
// Fill the buffer with clear color
memset(srcBuffer->GetMappedRange(0, descriptor.size), clearColor, descriptor.size);
srcBuffer->Unmap();
// Bind buffer and texture, and make the buffer to texture copy
gl.PixelStorei(GL_UNPACK_ROW_LENGTH,
(bytesPerRow / GetFormat().blockByteSize) * GetFormat().blockWidth);
gl.PixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
for (uint32_t level = range.baseMipLevel; level < range.baseMipLevel + range.levelCount;
++level) {
gl.BindBuffer(GL_PIXEL_UNPACK_BUFFER, srcBuffer->GetHandle());
gl.ActiveTexture(GL_TEXTURE0);
gl.BindTexture(GetGLTarget(), GetHandle());
Extent3D size = GetMipLevelPhysicalSize(level);
switch (GetDimension()) {
case wgpu::TextureDimension::e2D:
if (GetArrayLayers() == 1) {
if (clearValue == TextureBase::ClearValue::Zero &&
IsSubresourceContentInitialized(
SubresourceRange::SingleSubresource(level, 0))) {
// Skip lazy clears if already initialized.
continue;
}
gl.TexSubImage2D(GetGLTarget(), static_cast<GLint>(level), 0, 0,
size.width, size.height, GetGLFormat().format,
GetGLFormat().type, 0);
} else {
for (uint32_t layer = range.baseArrayLayer;
layer < range.baseArrayLayer + range.layerCount; ++layer) {
if (clearValue == TextureBase::ClearValue::Zero &&
IsSubresourceContentInitialized(
SubresourceRange::SingleSubresource(level, layer))) {
// Skip lazy clears if already initialized.
continue;
}
gl.TexSubImage3D(GetGLTarget(), static_cast<GLint>(level), 0, 0,
static_cast<GLint>(layer), size.width, size.height,
1, GetGLFormat().format, GetGLFormat().type, 0);
}
}
break;
default:
UNREACHABLE();
}
}
gl.PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
gl.PixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
gl.BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}
if (clearValue == TextureBase::ClearValue::Zero) {
SetIsSubresourceContentInitialized(true, range);
device->IncrementLazyClearCountForTesting();
}
return {};
}
void Texture::EnsureSubresourceContentInitialized(const SubresourceRange& range) {
if (!GetDevice()->IsToggleEnabled(Toggle::LazyClearResourceOnFirstUse)) {
return;
}
if (!IsSubresourceContentInitialized(range)) {
GetDevice()->ConsumedError(ClearTexture(range, TextureBase::ClearValue::Zero));
}
}
// TextureView
TextureView::TextureView(TextureBase* texture, const TextureViewDescriptor* descriptor)
: TextureViewBase(texture, descriptor), mOwnsHandle(false) {
mTarget = TargetForTextureViewDimension(descriptor->dimension, descriptor->arrayLayerCount,
texture->GetSampleCount());
if (!UsageNeedsTextureView(texture->GetUsage())) {
mHandle = 0;
} else if (!RequiresCreatingNewTextureView(texture, descriptor)) {
mHandle = ToBackend(texture)->GetHandle();
} else {
// glTextureView() is supported on OpenGL version >= 4.3
// TODO(jiawei.shao@intel.com): support texture view on OpenGL version <= 4.2
const OpenGLFunctions& gl = ToBackend(GetDevice())->gl;
mHandle = GenTexture(gl);
const Texture* textureGL = ToBackend(texture);
const GLFormat& glFormat = ToBackend(GetDevice())->GetGLFormat(GetFormat());
gl.TextureView(mHandle, mTarget, textureGL->GetHandle(), glFormat.internalFormat,
descriptor->baseMipLevel, descriptor->mipLevelCount,
descriptor->baseArrayLayer, descriptor->arrayLayerCount);
mOwnsHandle = true;
}
}
TextureView::~TextureView() {
if (mOwnsHandle) {
ToBackend(GetDevice())->gl.DeleteTextures(1, &mHandle);
}
}
GLuint TextureView::GetHandle() const {
ASSERT(mHandle != 0);
return mHandle;
}
GLenum TextureView::GetGLTarget() const {
return mTarget;
}
}} // namespace dawn_native::opengl
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
6848b019fb01a7eca8d07c3e9da46e42d3e1ba11 | 7b332aca74f38c2f3c84a08b42def9eed4414cca | /sort_binary_linkedlist.cpp | 4299d2cc689f1cd3abaab0c1b16605c0d185e012 | [] | no_license | Adrenalinerush07/Linkedlist | f3657396b8b6f44ff99b78496062ad968c174792 | 5e529cb6ac31453509042a59a5603af5ff7d83ea | refs/heads/main | 2023-03-15T09:32:53.385599 | 2021-02-25T11:50:43 | 2021-02-25T11:50:43 | 328,711,826 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,970 | cpp | #include<bits/stdc++.h>
using namespace std;
#define int long long
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
// void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
const int N=2e5+4;
const int mod=1e9+7;
/*
https://www.geeksforgeeks.org/sort-a-linked-list-of-0s-1s-or-2s/
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* solve(ListNode* A) {
int count[3]={0, 0, 0};
ListNode* ptr=A;
while(ptr != NULL){
count[ptr->val]++;
ptr=ptr->next;
}
int i=0;
ptr=A;
while(ptr != NULL){
if(count[i]==0){
i++;
}
else{
ptr->val=i;
--count[i];
ptr=ptr->next;
}
}
return A;
}
void solve(){
}
int32_t main(){
// ios_base::sync_with_stdio(false);cin.tie(NULL);
int tt;
tt=1;
cin>>tt;
for(int t=1;t<=tt;t++){
solve();
}
} | [
"49005095+cyberghost002@users.noreply.github.com"
] | 49005095+cyberghost002@users.noreply.github.com |
4e2c1fe80abae32a087c09b4f6258d2cd642ee54 | b9592418649488b9ff3fe4f77e0baf2e5a9dc76e | /src/utils/Timer.cpp | 57f3977b5e2113b53dac4b49ff8a86cd0510f0c3 | [] | no_license | horu/simple-epoll-chat | 20bbd9b1e83df036fabf3694c7c6e90e5b2f5046 | 938f29bb44ea05c9a760961d932ccef562b7a2f9 | refs/heads/master | 2021-08-29T08:44:04.804239 | 2017-12-13T15:55:42 | 2017-12-13T16:01:56 | 114,140,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,404 | cpp | #include <sys/time.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <utils/Exception.h>
#include <utils/Poller.h>
#include <utils/Timer.h>
#include <utils/TimerListener.h>
using namespace utils;
Timer::Timer(Poller* poller, TimerListener* listener, Timeout timeout)
: timer_fd_(-1), poller_(poller), listener_(listener) {
timer_fd_ = timerfd_create(CLOCK_MONOTONIC, 0);
if (timer_fd_ == -1) {
throw Exception("timerfd_create", strerror(errno));
}
itimerspec timer_spec_new;
bzero(&timer_spec_new,sizeof(timer_spec_new));
timer_spec_new.it_value.tv_sec = timeout/1000;
timer_spec_new.it_value.tv_nsec = 1000*(timeout%1000);
int setting_result = timerfd_settime(timer_fd_, 0, &timer_spec_new, 0);
if (setting_result) {
throw Exception("timerfd_settime", strerror(errno));
}
poller_->Subscribe(this);
}
Timer::~Timer() {
poller_->Unsubscribe(this);
close(timer_fd_);
}
const FileDescriptor& Timer::GetFileDescriptor() const {
return timer_fd_;
}
void Timer::OnIn() {
// Read number of experations from fd to clean it
uint64_t experations_number;
while (read(timer_fd_, &experations_number, sizeof(experations_number)) >= 0);
listener_->OnTimeout(this);
}
void Timer::OnOut() {
}
void Timer::OnError() {
}
void Timer::OnClosed() {
}
| [
"you@example.com"
] | you@example.com |
d480d61dd311bdc6079c9b1dc00d809d2cefa444 | aaac23e7fa85785f43bf1d8037708ee77ef640ef | /src/trace_progress.cpp | ab5d8af291bccb70d2a3504298589da129cff4c6 | [
"OML",
"MIT",
"BSD-3-Clause",
"Zlib"
] | permissive | anto0ine/ciyam | ee2b057a9cd11008ae0d477dac111c0a8d2f60b3 | 7127d528c37584e7d562732274fa2ed6025daeaa | refs/heads/master | 2020-12-07T13:43:24.528962 | 2014-11-20T07:22:08 | 2014-11-20T07:22:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | cpp | // Copyright (c) 2013-2014 CIYAM Developers
//
// Distributed under the MIT/X11 software license, please refer to the file license.txt
// in the root project directory or http://www.opensource.org/licenses/mit-license.php.
// NOTE: This file is intended for #include usage in anonymous namespaces only.
struct trace_progress : progress
{
trace_progress( int flag ) : flag( flag ) { }
void output_progress( const string& message );
int flag;
};
void trace_progress::output_progress( const string& message )
{
if( get_trace_flags( ) & flag )
log_trace_message( flag, message );
}
| [
"ian@ciyam.com"
] | ian@ciyam.com |
e5e9004c430dde26c36b13eb9c8cf389d5bb91dd | d50b9c65742d6e2381963b47b5d51b148f343dfa | /varianta2-fisier.cpp | e666933e437d582689141928d32387a33f13f00b | [] | no_license | bogdanpreda/cpp | 0f0c0ae47f46bc6e292d49766a500dcfed47c90b | 0264a8f430818ef52b0e8cbc40830cb44513b7dc | refs/heads/master | 2021-01-01T18:12:04.284777 | 2015-03-15T19:32:43 | 2015-03-15T19:32:43 | 29,315,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include <iostream>
#include <fstream>
using namespace std;
int main () {
int nr,i,j,v[100],n=0,aux;
ifstream f("v2-nr.txt");
while(f>>nr) {
if(nr>0)
v[++n] = nr;
}
for(i=1;i<=n-1;i++)
for(j=i+1;j<=n;j++)
if(v[i]>=v[j]) {
aux=v[i];
v[i]=v[j];
v[j]=aux;
}
for(i=1;i<=n;i++) {
cout<<v[i]<<" ";
}
if(n==0) cout<<"nu exista";
}
| [
"yomzx5@gmail.com"
] | yomzx5@gmail.com |
9804c76b8aa8c6e1c52cb151984c6c6c93ac6a53 | 00109a038c9fcfad30e36149d85105e031369f3c | /RGB-D/main.cpp | 3ccebbd4e04238a3b62efa3b4c4e25f580fa2ee4 | [] | no_license | Visioan/RGBD_Reconstruction | 49716324c8eafb4d90463d8603c4f71967e7d82e | c9d0521c8d2f72faea6f10a8ad055265bf832e48 | refs/heads/master | 2020-03-10T00:53:50.948189 | 2018-04-11T14:14:29 | 2018-04-11T14:15:44 | 129,094,525 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,754 | cpp |
#include "helper.h"
#include <Eigen/Core>
#include <opencv2/core/eigen.hpp>
#include<iostream>
#include<algorithm>
#include<fstream>
#include<chrono>
#include<opencv2/core/core.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <boost\timer.hpp>
#include <pcl/console/parse.h>
#include <OpenNI.h>
//#include<System.h>
//#include "../../src/System.h"
#include "System.h"
#include <io.h> //判断文件夹是否存在
#include <direct.h> //创建文件夹
using namespace std;
void LoadImages(const string &strSequence, const string &strAssociationFilename, vector<string> &vstrImageFilenamesRGB, vector<string> &vstrImageFilenamesD, vector<double> &vTimestamps)
{
ifstream fAssociation;
fAssociation.open(strAssociationFilename.c_str());
while (!fAssociation.eof())
{
string s;
getline(fAssociation, s);
if (!s.empty())
{
stringstream ss;
ss << s;
double t;
string sRGB, sD;
ss >> t;
vTimestamps.push_back(t);
ss >> sRGB;
vstrImageFilenamesRGB.push_back(string(strSequence + "/" + sRGB));
ss >> t;
ss >> sD;
vstrImageFilenamesD.push_back(string(strSequence + "/" + sD));
}
}
}
bool Oni2Sequence(const string &stroni, const string &strSequence, const string &strAssociationFilename)
{
string path_oni = stroni;
string sequence_dir = strSequence;
string sequence_association = strAssociationFilename;
//string sequence_association = sequence_dir + "/association.txt";
string sequence_rgb = sequence_dir + "/rgb";
string sequence_depth = sequence_dir + "/depth";
//vector<cv::Mat> vrgbMat, vdepthMat;
//vector<double> vTimestamps;
pcl::console::print_highlight("开始从 oni 文件中读取数据……\n");
//ProcessingFromOni(path_oni, vrgbMat, vdepthMat, vTimestamps);
pcl::console::print_highlight(" 创建文件夹 %s\n", sequence_rgb.c_str());
if (_access(sequence_rgb.c_str(), 0) == -1)
_mkdir(sequence_rgb.c_str());
else
{
_rmdir(sequence_rgb.c_str());
_mkdir(sequence_rgb.c_str());
}
pcl::console::print_highlight(" 创建文件夹 %s\n", sequence_depth.c_str());
if (_access(sequence_depth.c_str(), 0) == -1)
_mkdir(sequence_depth.c_str());
else
{
_rmdir(sequence_depth.c_str());
_mkdir(sequence_depth.c_str());
}
pcl::console::print_highlight(" 创建文件 %s\n", sequence_association.c_str());
//
openni::OpenNI::initialize();
openni::Device fromOniFile;
fromOniFile.open(path_oni.c_str());
openni::PlaybackControl *pController = fromOniFile.getPlaybackControl();
openni::VideoStream streamColor, streamDepth;
openni::VideoFrameRef frameColor, frameDepth;
if (fromOniFile.hasSensor(openni::SENSOR_COLOR) && fromOniFile.hasSensor(openni::SENSOR_DEPTH))
{
if (streamColor.create(fromOniFile, openni::SENSOR_COLOR) == openni::STATUS_OK&&streamDepth.create(fromOniFile, openni::SENSOR_DEPTH) == openni::STATUS_OK)
{
pcl::console::print_highlight("Create Video Stream Success !\n");
}
else
{
pcl::console::print_highlight("Create Video Stream Error !\n");
std::cin.get();
return false;
}
}
else
{
pcl::console::print_error("Device do not have color sensor or depth sensor !\n");
std::cin.get();
return false;
}
int totalcolor = pController->getNumberOfFrames(streamColor);
int totaldepth = pController->getNumberOfFrames(streamDepth);
int total = totalcolor < totaldepth ? totalcolor : totaldepth;
pcl::console::print_highlight("Images in the sequence: %d\n\n ", total);
//
ofstream outf;
outf.open(sequence_association);
streamColor.start();
streamDepth.start();
for (int i = 0; i < total; i++)
{
streamColor.readFrame(&frameColor);
streamDepth.readFrame(&frameDepth);
cv::Mat rgbmat(frameColor.getHeight(), frameColor.getWidth(), CV_8UC3, (void*)frameColor.getData());
cv::cvtColor(rgbmat, rgbmat, CV_RGB2BGR);
cv::Mat depthMat(frameDepth.getHeight(), frameDepth.getWidth(), CV_16UC1, (void*)frameDepth.getData());
char imgname[1024];
sprintf_s(imgname, "%05d.png", i);
string rgbpath = sequence_rgb + "/" + imgname;
string depthpath = sequence_depth + "/" + imgname;
cv::imwrite(rgbpath, rgbmat.clone());
pcl::console::print_highlight(" write %s\t", rgbpath.c_str());
cv::imwrite(depthpath, depthMat.clone());
pcl::console::print_highlight(" %s\t", depthpath.c_str());
char associations[1024];
sprintf_s(associations, "%05d\trgb/%05d.png\t%05d\tdepth/%05d.png", i, i, i, i);
pcl::console::print_highlight(" %s\n", associations);
//std::cout << "write --->" << associations << std::endl;
outf << associations << std::endl;
}
outf.close();
pcl::console::print_highlight("Done !!!\n");
return true;
}
int print_help()
{
std::cout << "\nApplication parameters:" << endl;
std::cout << "\n配置 config.config文件" << endl;
std::cout << " --help, -h : print this message" << endl;
std::cout << "................................................................................." << endl;
std::cout << " --path_voc <path_to_vocabulary> : GPUSIFT 词袋路径 (必选) " << endl;
std::cout << " --path_setting <path_to_settings> : SLAM 参数设置路径(必选) " << endl;
std::cout << " --path_sequence <path_to_sequence> : 数据图片 文件夹(A,B 二选1,A) " << endl;
std::cout << " --path_association <resolution> : associations 文件路径(A,B 二选1,A) " << endl;
std::cout << " --path_oni <length> : oni 数据文件路径(A,B 二选1,B) " << endl;
std::cout << " " << endl;
std::cout << " (path_sequence,path_association)与(path_oni)两个种数据调用格式可以任选一个 " << endl;
std::cout << " " << endl;
std::cout << " --path_traj <path_to_traj> : 四元组 转移矩阵保存路径 (必选) " << endl;
std::cout << " --path_trajRT <path_to_trajRT> : 4*4 转移矩阵保存路径(必选) " << endl;
std::cout << " --path_KeyPointsRel <interval> : 帧间匹配点保存文件夹(必选) " << endl;
std::cout << " --path_pcdSave <param_file> : 点云文件保存路径(必选) " << endl;
return 0;
}
//#define TOOLARGE
int main(int argc, char **argv)
{
using namespace pcl::console;
if (find_switch(argc, argv, "--help") || find_switch(argc, argv, "-h")) {
return print_help();
}
Configuration config("tracking.config");
string path_voc = config.path_voc_;
string path_settings = config.path_settings_;
string path_sequence = config.path_sequence_;
string path_association = config.path_association_;
string path_oni = config.path_oni_;
string path_traj = config.path_traj_;
string path_trajRT = config.path_trajRT_;
string path_KeyPointsRel = config.path_KeyPointsRel_;
string path_pcdSave = config.path_pcdSave_;
string path_fusedata = config.path_fusedata_;
bool useBufData = config.usebufdata_;
int Segnum = config.segnum_;
string strdatabuf = config.strdatabuf_;
string strGrAndOptdatabuf = config.strdatabuf_;
if (path_voc.empty() || path_settings.empty() || path_traj.empty() || path_trajRT.empty() || path_KeyPointsRel.empty())
{
std::cout << "--path_voc" << path_voc << std::endl;
std::cout << "--path_setting" << path_settings << std::endl;
std::cout << "--path_traj" << path_traj << std::endl;
std::cout << "--path_trajRT" << path_trajRT << std::endl;
std::cout << "--path_KeyPointsRel" << path_KeyPointsRel << std::endl;
print_help();
std::cin.get();
return 0;
}
if ((path_sequence.empty() || path_association.empty()) && path_oni.empty())
{
std::cout << "--path_sequence" << path_sequence << std::endl;
std::cout << "--path_association" << path_association << std::endl;
std::cout << "--path_oni" << path_oni << std::endl;
print_help();
std::cin.get();
return 0;
}
if (path_sequence.empty() || path_association.empty() && path_oni.empty())
{
print_error("Error !!!\n");
print_help();
}
if (path_association.empty() && !path_oni.empty())
{
path_association = path_sequence + "/associations.txt";
if (!Oni2Sequence(path_oni, path_sequence, path_association))
{
print_error("Error !!!\n");
print_help();
return 0;
}
}
vector<string> vstrImageFilenamesRGB;
vector<string> vstrImageFilenamesD;
vector<double> vTimestamps;
LoadImages(path_sequence, path_association, vstrImageFilenamesRGB, vstrImageFilenamesD, vTimestamps);
std::vector<PointCloudT> vpointcloudRGB;
std::vector<RGBDTrajectory> vvframetransformation;
BufferData buffdata;
int volume_cols = 0, volume_rows = 0;
cv::Mat rgbMat = cv::imread(vstrImageFilenamesRGB[0], CV_LOAD_IMAGE_UNCHANGED);
cv::Mat depthMat = cv::imread(vstrImageFilenamesRGB[0], CV_LOAD_IMAGE_UNCHANGED);
volume_cols = depthMat.cols;
volume_rows = depthMat.rows;
// Create SLAM system. It initializes all system threads and gets ready to process frames.
SIFT_SLAM::System SLAM(path_voc, path_settings, SIFT_SLAM::System::RGBD, true);
// Vector for tracking time statistics
std::cout << endl << "-------" << endl;
std::cout << "Start processing sequence ..." << endl;
int nImages = vstrImageFilenamesRGB.size();
vector<double> vTimesTrack;
vTimesTrack.resize(nImages);
boost::timer timer;
for (int ni = 0; ni < nImages; ni++)
{
// Read image and depthmap from file
cv::Mat imRGB = cv::imread(vstrImageFilenamesRGB[ni], CV_LOAD_IMAGE_UNCHANGED);
cv::Mat imD = cv::imread(vstrImageFilenamesD[ni], CV_LOAD_IMAGE_UNCHANGED);
double tframe = vTimestamps[ni];
printf("%d\n", ni);
// Pass the image to the SLAM system
timer.restart();
if (SLAM.TrackRGBD(imRGB, imD, tframe, ni, nImages))
{
RGBDTrajectory tv = SLAM.HandleRestAndGetFrameTransformation();
vvframetransformation.push_back(tv);
SLAM.SetSatartFrameId(ni);//设置ID号
ni--;//跟踪失败的那一阵作为新片段的第一帧重新跟踪
}
cv::waitKey(30);
}
//将最后的一个fragment保存
RGBDTrajectory tv = SLAM.GetLastFrameTransformation();
vvframetransformation.push_back(tv);
// Stop all threads
SLAM.Shutdown();
std::cout << "-------" << endl << endl;
std::cout << "Tracking Done ! " << endl;
SLAM.SaveKeyFrameTrajectoryTUM(path_traj);
SLAM.SaveTrajectoryTUMRT(path_trajRT);
SLAM.SaveKeyPointsRelative(config.path_KeyPointsRel_);
SLAM.SaveMat("E:\\Experiment\\code\\Sift_SLAM_v4\\dataCache\\mat");
SLAM.SaveTestMat("E:\\Experiment\\code\\Sift_SLAM_v4\\dataCache\\mat");
//SLAM.SaveKeyPointsRelative(path_KeyPointsRel);
std::cout << "Saving Done ! " << endl;
for (size_t i = 0; i < vvframetransformation.size(); i++)
{
char bufTraj[1024];
sprintf(bufTraj, "%s/traj/%d_TrajSeg.txt", strdatabuf.c_str(), i);
vvframetransformation[i].SaveToFile(std::string(bufTraj));
}
std::cin.get();
return 0;
}
| [
"wlj_vision@163.com"
] | wlj_vision@163.com |
67549ac39a2075b61e37793d55289a71af0d7631 | 6827288646a2ee893d1ba8d8ab5b791c6a13ecc4 | /SDLProject/Entity.cpp | eb232e62b373c6e83577bb5f33515e1e7e424742 | [] | no_license | schen12131/Project-4 | e89814ec99c10d018ea042a59da929dc5cacfc2c | a79d23ddac47876cf7c7076644439f09415433b5 | refs/heads/master | 2021-05-16T19:36:58.967352 | 2020-03-27T22:45:41 | 2020-03-27T22:45:41 | 250,441,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,213 | cpp | #include "Entity.h"
Entity::Entity()
{
position = glm::vec3(0);
movement = glm::vec3(0);
acceleration = glm::vec3(0);
velocity = glm::vec3(0);
speed = 0;
modelMatrix = glm::mat4(1.0f);
}
bool Entity:: checkCollision(Entity *other){
if (isActive == false|| other->isActive == false) return false;
float xdist = fabs(position.x - other->position.x)-((width + other->width)/2.0f);
float ydist = fabs(position.y - other->position.y)-((height + other->height)/2.0f);
if (xdist < 0 && ydist < 0) return true;
return false;
}
void Entity::CheckCollisionsY(Entity *objects, int objectCount)
{
for (int i = 0; i < objectCount; i++)
{
Entity *object = &objects[i];
if (checkCollision(object))
{
float ydist = fabs(position.y - object->position.y);
float penetrationY = fabs(ydist - (height / 2.0f) - (object->height / 2.0f));
if (velocity.y > 0) {
position.y -= penetrationY;
velocity.y = 0;
collidedTop = true;
if (this->entityType == PLAYER && object->entityType == ENEMY){
this->isActive = false;
}
}
else if (velocity.y < 0) {
position.y += penetrationY;
velocity.y = 0;
collidedBottom = true;
if (this->entityType == PLAYER && object->entityType == ENEMY){
object->isActive = false;
}
}
}
}
}
void Entity::CheckCollisionsX(Entity *objects, int objectCount)
{
for (int i = 0; i < objectCount; i++)
{
Entity *object = &objects[i];
if (checkCollision(object))
{
float xdist = fabs(position.x - object->position.x);
float penetrationX = fabs(xdist - (width / 2.0f) - (object->width / 2.0f));
if (velocity.x > 0) {
position.x -= penetrationX;
velocity.x = 0;
collidedRight = true;
if (this->entityType == PLAYER && object->entityType == ENEMY){
this->isActive = false;
}
}
else if (velocity.x < 0) {
position.x += penetrationX;
velocity.x = 0;
collidedLeft = true;
if (this->entityType == PLAYER && object->entityType == ENEMY){
this->isActive = false;
}
}
}
}
}
void Entity:: jumping(int y){
if (position.y == 1.5) jump = true;
}
void Entity:: AIWalker(int x){
if (x < 0 && position.x <= -5.0){
movement = glm::vec3(1, 0, 0);
}
else if (x > 0 && position.x >= 5.0){
movement = glm::vec3(-1, 0, 0);
}
else{
movement = glm::vec3(x, 0, 0);
}
}
void Entity::AIWaitAndGo(Entity *player){
switch (aiState) {
case IDLE:
if (glm::distance(position, player->position)<3.0f){
aiState = WALKING;
}
break;
case WALKING:
if (player->position.x < position.x){
movement = glm::vec3(-1, 0, 0);
} else{
movement = glm::vec3(1, 0, 0);
}
break;
case ATTACKING:
break;
}
}
void Entity::AI(int x, int y, Entity *player){
switch (aiType) {
case WALKER:
AIWalker(movement.x);
break;
case WAITANDGO:
AIWaitAndGo(player);
break;
case JUMPER:
jumping(movement.y);
break;
}
}
void Entity::Update(float deltaTime, Entity *player, Entity *platforms, int platformCount)
{
if (isActive == false) return;
collidedTop = false;
collidedBottom = false;
collidedLeft = false;
collidedRight = false;
if (entityType == ENEMY){
AI(movement.x, movement.y, player);
}
if (animIndices != NULL) {
if (glm::length(movement) != 0) {
animTime += deltaTime;
if (animTime >= 0.25f)
{
animTime = 0.0f;
animIndex++;
if (animIndex >= animFrames)
{
animIndex = 0;
}
}
} else {
animIndex = 0;
}
}
if (jump){
jump = false;
velocity.y += jumpPower;
}
velocity.x = movement.x * speed;
velocity += acceleration * deltaTime;
position.y += velocity.y * deltaTime; // Move on Y
CheckCollisionsY(platforms, platformCount);// Fix if needed
position.x += velocity.x * deltaTime; // Move on X
CheckCollisionsX(platforms, platformCount);// Fix if needed
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
}
void Entity::DrawSpriteFromTextureAtlas(ShaderProgram *program, GLuint textureID, int index)
{
float u = (float)(index % animCols) / (float)animCols;
float v = (float)(index / animCols) / (float)animRows;
float width = 1.0f / (float)animCols;
float height = 1.0f / (float)animRows;
float texCoords[] = { u, v + height, u + width, v + height, u + width, v,
u, v + height, u + width, v, u, v};
float vertices[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5 };
glBindTexture(GL_TEXTURE_2D, textureID);
glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices);
glEnableVertexAttribArray(program->positionAttribute);
glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
glEnableVertexAttribArray(program->texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(program->positionAttribute);
glDisableVertexAttribArray(program->texCoordAttribute);
}
void Entity::Render(ShaderProgram *program) {
if (isActive == false) return;
program->SetModelMatrix(modelMatrix);
if (animIndices != NULL) {
DrawSpriteFromTextureAtlas(program, textureID, animIndices[animIndex]);
return;
}
if (success != NULL) {
DrawSpriteFromTextureAtlas(program, textureID, success[index]);
}
if (fail != NULL) {
DrawSpriteFromTextureAtlas(program, textureID, fail[index]);
}
float vertices[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5 };
float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
glBindTexture(GL_TEXTURE_2D, textureID);
glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices);
glEnableVertexAttribArray(program->positionAttribute);
glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
glEnableVertexAttribArray(program->texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(program->positionAttribute);
glDisableVertexAttribArray(program->texCoordAttribute);
}
| [
"40004737+schen12131@users.noreply.github.com"
] | 40004737+schen12131@users.noreply.github.com |
fc9dd1b2cd08ccf4ede382cf10c18fdf61f02cf0 | 5a34d0d4964e4122e21cb9d3d117af07efbb697d | /ArraysHW.cpp | 99260676e9bd5c0dd987895322d698901dd99ccd | [] | no_license | mbkhan721/C-Plus-Plus | 49795565bcd0ad6d2c436f7cbc254fddef1bf8b8 | c29c6ebbb899a3f66c6f0661bf1e8e8c53a69a83 | refs/heads/master | 2023-07-31T05:43:36.945380 | 2021-09-27T04:50:37 | 2021-09-27T04:50:37 | 372,982,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,034 | cpp | #include<iostream>
#include<time.h>
using namespace std;
/*
void swap(char &e1, char &e2) {
char temp = e1;
e1 = e2;
e2 = temp;
}
int main() {
// -------------------------------------- 1.
cout << "\n1. " << "\n";
int a[5]; // declare an array of 5 integers
for (int i = 0; i < 5; i++) {
cout << "[" << i << "] = ";
cin >> a[i]; // input values from the console into the array
}
cout << "\nArray: ";
for (int i = 0; i < 5; i++) {
cout << a[i] << " "; // loop to output the array
}
int min = a[0];
for (int i = 1; i < 5; i++) { // iterate from the second to last value of the array
if (min > a[i]) { // if the current min is larger then the current value
min = a[i]; // replace min with the current value
}
}
cout << "\nMin: " << min << endl; // determine the smallest element in the array.
int max = a[0];
for (int i = 1; i < 5; i++) { // iterate from the second to last value of the array
if (max < a[i]) { // if the current max is smaller then the current value
max = a[i]; // replace max with the current value
}
}
cout << "\Max: " << max << endl; // determine the largest element in the array.
// -------------------------------------- 2.
cout << "\n2. " << "\n";
const int SIZE = 26;
char alphabet[SIZE];
for (int i = 0; i < SIZE; i++) { // Populating the array with alphabets
alphabet[i] = i + 'A';
}
cout << "Original: ";
for (int i = 0; i < SIZE; i++) { // Printing the original array
cout << alphabet[i] << " ";
}
cout << endl; // Swapping the array content
for (int i = 0, j = SIZE - 1; i < SIZE / 2; i++, j--) { // i starts form left to the middle, j starts from length - 1
swap(alphabet[i], alphabet[j]); // i increments and j decrements
cout << "i = " << i << " j = " << j << endl;
}
cout << "\nReversed: "; // Printing the reversed array
for (int i = 0; i < SIZE; i++) {
cout << alphabet[i] << " ";
}
// -------------------------------------- 3.
cout << "\n3. " << "\n";
const int D1 = 7;
const int D2 = 20;
string flag[D1][D2];
for (int r = 0; r < D1; r++) {
for (int c = 0; c < D2; c++) {
if (r <= 3 && c < 7) {
flag[r][c] = "* ";
}
else if (r % 2 == 0) { // If rows are even, print "="
flag[r][c] = "= ";
}
else {
flag[r][c] = "- ";
}
}
}
for (int r = 0; r < D1; r++) {
for (int c = 0; c < D2; c++) {
cout << flag[r][c] << " ";
}
cout << "\n";
}
// -------------------------------------- 4.
cout << "\n4. " << "\n";
const int R = 4;
const int C = 4;
int integers[R][C];
srand(time(NULL));
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
integers[i][j] = rand() % 16 + 10;
}
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cout << integers[i][j] << " ";
}
cout << endl;
}
cout << "\nRow 2: ";
for (int col = 0; col < C; col++) {
cout << integers[1][col] << " ";
}
cout << "\nCol 3: ";
for (int row = 0; row < R; row++) {
cout << integers[row][2] << " ";
}
cout << "\nDiagonal 1: ";
for (int i = 0, c = 0; i < R; i++, c++) {
if (i == c) {
cout << integers[i][c] << " ";
}
}
cout << "\nAnother way to print Diagonal 1: ";
for (int i = 0; i < C; i++) {
cout << integers[i][i] << " ";
}
cout << "\nDiagonal 2: ";
for (int i = 0; i < R; i++) {
cout << integers[i][R-i-1] << " "; // One dimention counts up, other counts down
} // 0,3
// 1,2
// 2,1
// 3,0
// Loops goes as follows
// i = 0; R < 4; i++
// R i 1
// 4-0-1 = 3
// 4-1-1 = 2
// 4-2-1 = 1
// 4-3-1 = 0
// Hint: Recall that loops can have multiple initializations, conditions and
// increment changes such as :
// for(int i=5, j=2; i>=0 && j<10; i--, j++) { loop code; }
cout << endl;
return 0;
}
*/ | [
"muhammad.khan33@student.qcc.cuny.edu"
] | muhammad.khan33@student.qcc.cuny.edu |
e15afce42c2239cef608a6ecabf2b69a11327dfd | 97c60972ff8cbb79f976bbf0a0d5328d0826aa56 | /游戏/高仿战火重燃游戏/战火重燃游戏/ZHCRMC/AppRecommandSDK/lib/appcenter/mychallenge.h | 2ca1bd7a1c54f997643d5f5581753336ca7ffc7c | [] | no_license | zhangmingjie01/highCopyProject | cdd4cfb39b24cdc7dc86205540304b3c8a64cef0 | 1dd2e00e4d4344612c8d2688d4b45d5f573466e6 | refs/heads/master | 2020-03-11T13:23:10.231617 | 2017-05-11T08:13:40 | 2017-05-11T08:13:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | h | #ifndef __MYSECURITY_INC_MYCHALLENGE_H__
#define __MYSECURITY_INC_MYCHALLENGE_H__
#include "blowfish.h"
#include "dsa.h"
#include "sha.h"
#include "myrandom.h"
#define SPY_DATA_LEN 256
#define SPY_SIGN_LEN 256
typedef struct
{
unsigned int data_len;
unsigned int sig_len;
unsigned char data[SPY_DATA_LEN];
unsigned char sig[SPY_SIGN_LEN];
}tCryptolalia;
class MyChallenge
{
public:
MyChallenge(const unsigned char *remote_public_key,
unsigned int remote_public_key_len,
const unsigned char *private_key,
unsigned int private_key_len,
const unsigned char *challenge_key,
unsigned int challenge_key_len);
~MyChallenge();
public:
bool create();
void encrypt() const;
void decrypt() const;
bool sign();
bool verify();
bool transform();
bool equal(const MyChallenge &rc) const;
tCryptolalia* cryptoData();
void setCryptoData(tCryptolalia *rd);
private:
const unsigned char* _remote_public_key;
unsigned int _remote_public_key_len;
const unsigned char* _private_key;
unsigned int _private_key_len;
unsigned char _iv[8];
BF_KEY * _bf_key;
tCryptolalia * _cpo_data;
};
#endif /* __MYSECURITY_INC_MYCHALLENGE_H__ */
| [
"3290235031@qq.com"
] | 3290235031@qq.com |
c696aadbedeeee05a3aef9ac8cb97940f854b59c | 21ca39ac8c31f968ba906ad50c69fa37087f1bac | /include/misc/Parser.hpp | bc0f7da4859e5bcfc8a4eaea44a5e43b399c4e0f | [
"Apache-2.0"
] | permissive | juliusHuelsmann/Logger | 1ac068bd6f0b9367d9febb421e3bd5040cbd21e3 | 8fd61f0318229dfdbb334a0d41e71fd48cd74979 | refs/heads/master | 2020-04-01T02:38:09.706304 | 2020-03-05T11:50:25 | 2020-03-05T11:50:25 | 152,787,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,645 | hpp | // Author: Julius Hülsmann
// Email: juliusHuelsmann@gmail.com, julius.huelsmann@data-spree.com
// Creation Date: 12/24/19
// YYY: take extensions from my dbn framework.
#ifndef MISC_PARSER_HPP
#define MISC_PARSER_HPP
#include <zmq.hpp>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <set>
#include <type_traits>
namespace parser {
using BasicType = char;
template <typename T, typename K, typename SizeType,
typename std::enable_if_t<std::is_integral<SizeType>::value> * = nullptr>
inline void copy(T *anchor, K const *src, SizeType size, SizeType &offset) noexcept {
std::memcpy(&(reinterpret_cast<BasicType *>(anchor)[std::exchange(offset, offset + size)]),
reinterpret_cast<BasicType const *>(src), size);
}
template <typename T, typename K, typename SizeType,
typename std::enable_if_t<std::is_integral<SizeType>::value> * = nullptr>
inline void copySwap(T *anchor, K const *src, SizeType size, SizeType &offset) noexcept {
std::memcpy(reinterpret_cast<BasicType *>(anchor),
&(reinterpret_cast<BasicType const *>(src)[std::exchange(offset, offset + size)]), size);
}
/// Return copy of the memory chunk
/// memory[#offset: #offset + sizeof(T)] interpreted as #ReturnType.
template <typename ReturnType, typename A, typename SizeType,
typename std::enable_if_t<std::is_integral<SizeType>::value> * = nullptr>
inline ReturnType get(A const *memory, SizeType &offset) noexcept {
return *reinterpret_cast<ReturnType const *>(
&reinterpret_cast<BasicType const *>(memory)[std::exchange(offset, offset + sizeof(ReturnType))]);
}
template <typename ParameterType, typename A, typename SizeType,
typename std::enable_if_t<std::is_integral<SizeType>::value> * = nullptr>
inline void get(A const *memory, ParameterType &val, SizeType &offset) noexcept {
val = *reinterpret_cast<ParameterType const *>(
&reinterpret_cast<BasicType const *>(memory)[std::exchange(offset, offset + sizeof(ParameterType))]);
}
template <typename ParameterType, typename A, typename SizeType,
typename std::enable_if_t<std::is_integral<SizeType>::value> * = nullptr>
inline void set(A *memory, ParameterType val, SizeType &offset) noexcept {
*reinterpret_cast<ParameterType *>(
&(reinterpret_cast<BasicType *>(memory)[std::exchange(offset, offset + sizeof(ParameterType))])) = val;
}
/// Utility to the set function that can be used with arbitrary numeric (const) types of #val.
#define SET(pntr, val, idx) set<std::remove_const_t<decltype(val)>>(pntr, val, idx)
} // namespace parser
#endif // MISC_PARSER_HPP
| [
"juliusHuelsmann@gmail.com"
] | juliusHuelsmann@gmail.com |
ea93250caa0c02574381a979c7e9ba1a2b0cb584 | 90efdfa1f56e2082283e510c7aa9a77ceab8ce18 | /template/src/TemplateGame.cpp | f2e2c676509bad562c6b4f5aa824987ece891997 | [] | no_license | aurodev/GPlay3D | 451e2863d6ac3222762672d358eecd494d9cc272 | ad6b88dd22688e2b6e6e2fa02779daa0b5545592 | refs/heads/master | 2020-07-13T04:28:30.234238 | 2018-06-26T06:48:20 | 2018-06-26T06:48:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,838 | cpp | #include "TemplateGame.h"
// Declare our game instance
TemplateGame game;
TemplateGame::TemplateGame()
: _scene(NULL)
{
}
void TemplateGame::initialize()
{
// Load game scene from file
_scene = Scene::load("res/data/scenes/demo.scene");
// Get the box model and initialize its material parameter values and bindings
Node* boxNode = _scene->findNode("box");
Model* boxModel = dynamic_cast<Model*>(boxNode->getDrawable());
Material* boxMaterial = boxModel->getMaterial();
// Set the aspect ratio for the scene's camera to match the current resolution
_scene->getActiveCamera()->setAspectRatio(getAspectRatio());
}
void TemplateGame::finalize()
{
SAFE_RELEASE(_scene);
}
void TemplateGame::update(float elapsedTime)
{
// Rotate model
_scene->findNode("box")->rotateY(MATH_DEG_TO_RAD((float)elapsedTime / 1000.0f * 180.0f));
}
void TemplateGame::render(float elapsedTime)
{
// Clear the color and depth buffers
clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0);
// Visit all the nodes in the scene for drawing
_scene->visit(this, &TemplateGame::drawScene);
}
bool TemplateGame::drawScene(Node* node)
{
// If the node visited contains a drawable object, draw it
Drawable* drawable = node->getDrawable();
if (drawable)
drawable->draw();
return true;
}
void TemplateGame::keyEvent(Keyboard::KeyEvent evt, int key)
{
if (evt == Keyboard::KEY_PRESS)
{
switch (key)
{
case Keyboard::KEY_ESCAPE:
exit();
break;
}
}
}
void TemplateGame::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
switch (evt)
{
case Touch::TOUCH_PRESS:
break;
case Touch::TOUCH_RELEASE:
break;
case Touch::TOUCH_MOVE:
break;
};
}
| [
"fredakilla@gmail.com"
] | fredakilla@gmail.com |
2a96560e3e62ee569e6f96b9bdf016c2c8e935fb | d633604663c4e8328afe4af36645eef5bbff8883 | /moea.cpp | 81310aa1dc471332d9e7e99ee0a9132c7b7dae07 | [] | no_license | axhiao/NSGA-II | 40247a04fd4ed2b53895afae0e3349fbc4da9f59 | e0defe501820e46b6b4f612e3262b9cd3901129f | refs/heads/master | 2016-09-06T10:26:36.493557 | 2014-10-11T13:57:26 | 2014-10-11T13:57:26 | 25,080,295 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,302 | cpp | /*==========================================================================
// C++ Implementation of NSGAII for Contest Multiobjective Problems
//
// Author: Xiaoliang Ma
//
// See the details of NSGAII and test problems in the following papers
//
// 1) K. Deb, S. Agrawal, A. Pratap, and T. Meyarivan, ¡°A fast and elitist multiobjective genetic algorithm:
NSGA-II,¡± IEEE Trans. Evol.Comput., vol. 6, no. 2, pp. 182¨C197, Apr. 2002.
//
// If you have any questions about the codes, please contact
//
// Xiaoliang Ma at maxiaoliang@yeah.net
//
// Date: 21/DEC/2009
//
// ===========================================================================*/
#include "algorithm.h"
void main()
{
std::ifstream readf("TestInstance.txt");// TestInstance.txt store the
// parameter setting of test instance
strcpy(crossoverType, "SBX"); // the type of crossover operater
strcpy(mutationType, "ploynomial"); // theoperater
//--- set needed test case index from begin to end --- type of mutation
int fun_start_num = 23; // the start index of needed test case
int fun_end_num =23; // the end index of needed test case
int num_run = 30; // the number of run for each test case
//--- skip the front test instance ---
int seq;
for (int i =1;i<fun_start_num;i++)
{ //--- the parameter setting of test instance ---
readf>>seq;
readf>>strTestInstance; // the name of test case
readf>>nvar; // the number of variable for the test case
readf>>nobj; // the number of objetive for the test case
}
//--- running from the fun_start_num case to the fun_end_num case ---
for(inst=fun_start_num; inst<=fun_end_num; inst++)
{ //--- the parameter setting of test instance ---
readf>>seq;
readf>>strTestInstance; // the name of test case
readf>>nvar; // the number of variable for the test case
readf>>nobj; // the number of objetive for the test case
getVarBoundy(); // get the domain of x_var
if (inst >= 11 && inst <= 23||inst >= 34 && inst <= 40)
{
if (nobj == 2)
{
pop=100;
num_max_evulation = 50000;
strcpy(crossoverType,"SBX");
//pops = 100;
}
else if (nobj == 3)
{
pop=300;
num_max_evulation = 75000;// DTLZ6:23
strcpy(crossoverType,"SBX");
//pops = 100;
}
}
else if (inst >= 1 && inst <= 10 || inst >= 24 && inst <= 33|| inst >= 41 && inst <= 133)
{
if (nobj == 2)
{
pop = 300;
num_neighbour = int(pop * 0.1);
num_max_evulation = 60000;
strcpy(crossoverType,"DE");
//pops = 600;
}
else if (nobj == 3)
{
pop = 600;
num_neighbour = int(pop * 0.1);
num_max_evulation = 300000;
strcpy(crossoverType,"DE");
//pops = 1000;
}
}
else if (inst >= 134 && inst <= 144)
{
if (nobj == 2)
{
pop=50;
num_max_evulation = 30000;
strcpy(crossoverType,"SBX");
//pops = 100;
}
else if (nobj == 3)
{
pop=100;
num_max_evulation = 30000;
strcpy(crossoverType,"SBX");
}
else if (nobj == 4)
{
pop=120;
num_max_evulation = 30000;
strcpy(crossoverType,"SBX");
//pops = 100;
}
else if (nobj == 6)
{
pop=126;
num_max_evulation = 30000;
strcpy(crossoverType,"SBX");
}
}
else if (inst >= 145 && inst <= 145)
{//ZDT_4
pop=220;
num_max_evulation = 200000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 146 && inst <= 150)
{//DTLZ_5
pop=252;
num_max_evulation = 200000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 151 && inst <= 160)
{//ZDT_3
num_max_evulation = 50000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 161 && inst <= 166)
{
pop = 100;
num_max_evulation = 30000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 167 && inst <= 170)
{
pop = 252;
num_max_evulation = 200000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 171 && inst <= 174)
{
pop = 220;
num_max_evulation = 130000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 175 && inst <= 178)
{
pop = 495;
num_max_evulation = 180000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 179 && inst <= 182)
{
pop = 792;
num_max_evulation = 250000;
strcpy(crossoverType,"SBX");
}
else if (inst >= 183 && inst <= 184)
{
pop = 252;
num_max_evulation = 350000;
strcpy(crossoverType,"SBX");
}
else if (inst == 185)
{
pop = 220;
num_max_evulation = 350000;
strcpy(crossoverType,"SBX");
}
else if (inst == 186)
{
pop = 100;
num_max_evulation = 50000;
strcpy(crossoverType,"SBX");
}
else if (inst == 187)
{
pop = 300;
num_max_evulation = 100000;
strcpy(crossoverType,"SBX");
}
else if (inst == 188)
{
pop = 100;
num_max_evulation = 50000;
strcpy(crossoverType,"SBX");
}
else if (inst == 189)
{
pop = 300;
num_max_evulation = 100000;
strcpy(crossoverType,"SBX");
}
CMOEA MOEA(pop); //
printf("\n -- Instance: %s, %d variables %d objectives \n\n", strTestInstance, nvar, nobj);
for(int run=1; run<=num_run; run++)
{
printf("\n -- %d-th run -- \n", run);
MOEA.exec_emo(run); //
}
//lowBound.clear();
//uppBound.clear();
}
//--- release the store resource in heap ---
lowBound.clear();
uppBound.clear();
}
| [
"axhiao@gmail.com"
] | axhiao@gmail.com |
e5b3f32d23b54fa7d8c77b3c198148f2426c8187 | ceba7336e4ddbdab6a0d5a19e0558171ca0e9487 | /max_points.cpp | 2c44f42c2d7b5b052b558ed36e5f3dc73fb90b19 | [] | no_license | ivysoftware/leetcode | c2099da7993deb46d86620d1150f7b82e1bf1385 | d6aeef0f6353b0850bce8b167de578ead0fdf43d | refs/heads/master | 2021-01-23T09:29:36.752983 | 2015-03-25T14:21:59 | 2015-03-25T14:21:59 | 11,875,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,573 | cpp | #include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <sys/time.h>
#include <algorithm>
using namespace std;
//复杂度:O(n^2),空间复杂度O(n^2)
//更简化的做法:不保存截距,中间结果对于只计算最大值的情况,尽量用中间变量代替,抛弃无用的中间结果
// 统计通过某点的直线中,最多有多少个点
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
class Solution {
public:
struct Line{
float k;
float b;
int count;
};
bool PointSort(const Point& a, const Point &b)
{
if(a.x > b.x)
return true;
else if(a.x == b.x && a.y > b.y)
return true;
return false;
}
bool IsSame(Point& a, Point &b)
{
if(a.x == b.x && a.y == b.y)
return true;
else
return false;
}
int maxPoints(vector<Point> &points) {
//sort(points.begin(), points.end(), PointSort);
//1. normal line non-y asix
map<float, map<float, set<int> > > k2b2p;
float k = 0, b = 0;
int maxcount = 0;
map<float, map<float, set<int> > >::iterator k_it;
map<float, set<int> >::iterator b_it ;
set<int>::iterator set_it;
//2. y-axis
map<int, int> y2c;
set<float> ks;
set<float>::iterator k_set_it;
for(unsigned i = 0; i < points.size(); i ++)
{
ks.clear();
y2c[points[i].y] ++;
for(unsigned j = i + 1; j < points.size(); j ++)
{
if(points[i].x == points[j].x && points[i].y == points[j].y)
ks.insert(j);
}
for(unsigned j = i + 1; j < points.size(); j ++)
{
if(points[i].y == points[j].y)
continue;
k = (float)(points[i].x - points[j].x)/(float)(points[i].y - points[j].y);
b = points[i].y - points[i].x * k;
k2b2p[k][b].insert(i);
k2b2p[k][b].insert(j);
k_set_it = ks.begin();
for(; k_set_it != ks.end(); k_set_it ++)
k2b2p[k][b].insert(*(k_set_it));
}
}
k_it = k2b2p.begin();
for(; k_it!=k2b2p.end(); k_it++)
{
b_it = k_it->second.begin();
for(; b_it != k_it->second.end(); b_it++){
if(maxcount < (int)b_it->second.size()){
maxcount = b_it->second.size();
cout << "k=" << k_it->first << " ,b=" << b_it->second.size() << ", size=" << b_it->second.size() << endl;
set_it = b_it->second.begin();
for( ;set_it != b_it->second.end(); set_it++)
cout << "point:" << *(set_it) << endl;
}
}
}
map<int,int>::iterator it_y = y2c.begin();
for(; it_y!=y2c.end(); it_y ++)
{
if(maxcount < it_y->second){
maxcount = it_y->second;
cout << "y2c:" << it_y->first << " " << it_y->second << endl;
}
}
return maxcount;
}
};
int main()
{
/* max points */
Point arr[] = {Point(0,-12),
Point(0,-5), Point(0,-8), Point(0,-9),
Point(-2,-1),Point(0,-11), Point(0,-9),Point(0,-12)};
vector<Point> points(arr, arr+8);
Solution s;
cout << s.maxPoints(points)
}
| [
"ivysoftwarenankai@gmail.com"
] | ivysoftwarenankai@gmail.com |
20e6f26721b36c5cdd60365b63ac640da43efd21 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/squid/hunk_7382.cpp | 3c920a6d1512f97d4b1736fc4dec130ee7a56ef7 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | cpp | return 0;
}
file_close(swaplog_fd);
- swaplog_fd = file_open(swaplog_file, NULL, O_WRONLY | O_CREAT);
+ swaplog_fd = file_open(swaplog_file, NULL, O_WRONLY | O_CREAT, NULL, NULL);
if (swaplog_fd < 0) {
sprintf(tmp_error_buf, "Cannot open swap logfile: %s", swaplog_file);
fatal(tmp_error_buf);
| [
"993273596@qq.com"
] | 993273596@qq.com |
0997ce32a1ffdef541e9a2e24d4fd4d27faa027d | 01656baedc31af913c7363c488d82e55ca462be7 | /src/shared_ptr_ll.hpp | 3ef27a4a8438553ff3587b27ac82e9fb86c9b779 | [] | no_license | nagalun/naga-utils | ffe5d923b558ea78cb17ada07c15f6aaefe1188d | 60f1c00ff4aa613f2d73547b18d178c08a543e2a | refs/heads/master | 2023-07-05T22:44:50.608434 | 2023-06-27T17:44:32 | 2023-06-27T17:44:32 | 163,791,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | hpp | #pragma once
#include <memory>
namespace ll {
// Lock-less shared pointer, even when linking pthread
template<typename T>
using shared_ptr = std::__shared_ptr<T, __gnu_cxx::_S_single>;
template<typename T>
using weak_ptr = std::__weak_ptr<T, __gnu_cxx::_S_single>;
template<typename T, typename... Args>
inline ll::shared_ptr<T> make_shared(Args&&... args) {
return std::__make_shared<T, __gnu_cxx::_S_single, Args...>(
std::forward<Args>(args)...);
}
}
| [
"nagalun@users.noreply.github.com"
] | nagalun@users.noreply.github.com |
161473e0a99c46c5d41922fe2239178f42e0b754 | 44d05587f8578ee645ee572dff25a2496b865aac | /stm32cubeide/stm32f446re_AuCAR/Inc/ROS/pr2_msgs/PowerBoardState.h | 5ae6fdb76f553b7752ac85b1cb13fe5c498b1d26 | [
"Apache-2.0"
] | permissive | YeongJunKim/AuCAR | 3b1eb4c06b3c5533a45272f69f323019ea920f34 | c2abb1ecbab2a25b1dd896ddbea50ac76fa4478d | refs/heads/master | 2021-07-16T11:09:50.274652 | 2020-08-13T04:32:35 | 2020-08-13T04:32:35 | 188,990,518 | 2 | 1 | Apache-2.0 | 2020-06-17T18:24:59 | 2019-05-28T08:48:04 | C | UTF-8 | C++ | false | false | 5,784 | h | #ifndef _ROS_pr2_msgs_PowerBoardState_h
#define _ROS_pr2_msgs_PowerBoardState_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "std_msgs/Header.h"
namespace pr2_msgs
{
class PowerBoardState : public ros::Msg
{
public:
typedef std_msgs::Header _header_type;
_header_type header;
typedef const char* _name_type;
_name_type name;
typedef uint32_t _serial_num_type;
_serial_num_type serial_num;
typedef float _input_voltage_type;
_input_voltage_type input_voltage;
typedef int8_t _master_state_type;
_master_state_type master_state;
int8_t circuit_state[3];
float circuit_voltage[3];
typedef bool _run_stop_type;
_run_stop_type run_stop;
typedef bool _wireless_stop_type;
_wireless_stop_type wireless_stop;
enum { STATE_NOPOWER = 0 };
enum { STATE_STANDBY = 1 };
enum { STATE_PUMPING = 2 };
enum { STATE_ON = 3 };
enum { STATE_ENABLED = 3 };
enum { STATE_DISABLED = 4 };
enum { MASTER_NOPOWER = 0 };
enum { MASTER_STANDBY = 1 };
enum { MASTER_ON = 2 };
enum { MASTER_OFF = 3 };
enum { MASTER_SHUTDOWN = 4 };
PowerBoardState():
header(),
name(""),
serial_num(0),
input_voltage(0),
master_state(0),
circuit_state(),
circuit_voltage(),
run_stop(0),
wireless_stop(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->header.serialize(outbuffer + offset);
uint32_t length_name = strlen(this->name);
varToArr(outbuffer + offset, length_name);
offset += 4;
memcpy(outbuffer + offset, this->name, length_name);
offset += length_name;
*(outbuffer + offset + 0) = (this->serial_num >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (this->serial_num >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (this->serial_num >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (this->serial_num >> (8 * 3)) & 0xFF;
offset += sizeof(this->serial_num);
offset += serializeAvrFloat64(outbuffer + offset, this->input_voltage);
union {
int8_t real;
uint8_t base;
} u_master_state;
u_master_state.real = this->master_state;
*(outbuffer + offset + 0) = (u_master_state.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->master_state);
for( uint32_t i = 0; i < 3; i++){
union {
int8_t real;
uint8_t base;
} u_circuit_statei;
u_circuit_statei.real = this->circuit_state[i];
*(outbuffer + offset + 0) = (u_circuit_statei.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->circuit_state[i]);
}
for( uint32_t i = 0; i < 3; i++){
offset += serializeAvrFloat64(outbuffer + offset, this->circuit_voltage[i]);
}
union {
bool real;
uint8_t base;
} u_run_stop;
u_run_stop.real = this->run_stop;
*(outbuffer + offset + 0) = (u_run_stop.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->run_stop);
union {
bool real;
uint8_t base;
} u_wireless_stop;
u_wireless_stop.real = this->wireless_stop;
*(outbuffer + offset + 0) = (u_wireless_stop.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->wireless_stop);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->header.deserialize(inbuffer + offset);
uint32_t length_name;
arrToVar(length_name, (inbuffer + offset));
offset += 4;
for(unsigned int k= offset; k< offset+length_name; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_name-1]=0;
this->name = (char *)(inbuffer + offset-1);
offset += length_name;
this->serial_num = ((uint32_t) (*(inbuffer + offset)));
this->serial_num |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
this->serial_num |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
this->serial_num |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
offset += sizeof(this->serial_num);
offset += deserializeAvrFloat64(inbuffer + offset, &(this->input_voltage));
union {
int8_t real;
uint8_t base;
} u_master_state;
u_master_state.base = 0;
u_master_state.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->master_state = u_master_state.real;
offset += sizeof(this->master_state);
for( uint32_t i = 0; i < 3; i++){
union {
int8_t real;
uint8_t base;
} u_circuit_statei;
u_circuit_statei.base = 0;
u_circuit_statei.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->circuit_state[i] = u_circuit_statei.real;
offset += sizeof(this->circuit_state[i]);
}
for( uint32_t i = 0; i < 3; i++){
offset += deserializeAvrFloat64(inbuffer + offset, &(this->circuit_voltage[i]));
}
union {
bool real;
uint8_t base;
} u_run_stop;
u_run_stop.base = 0;
u_run_stop.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->run_stop = u_run_stop.real;
offset += sizeof(this->run_stop);
union {
bool real;
uint8_t base;
} u_wireless_stop;
u_wireless_stop.base = 0;
u_wireless_stop.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->wireless_stop = u_wireless_stop.real;
offset += sizeof(this->wireless_stop);
return offset;
}
const char * getType(){ return "pr2_msgs/PowerBoardState"; };
const char * getMD5(){ return "08899b671e6a1a449e7ce0000da8ae7b"; };
};
}
#endif
| [
"dud3722000@naver.com"
] | dud3722000@naver.com |
fd9b701526b09680b3840259f11a4f015ce0e4ff | 674cad3c5f99f608f920b70c7ea865d72cfe940c | /Uri/Geral/uri1063.cpp | 1f240bc8f92cc36e60f28db9c7df309e86a61c13 | [] | no_license | wellvolks/Problemas | c876b6120f1622d614767ecc99dba802c395e772 | 6513ea2b126977f45cb2388f753188e95328af2e | refs/heads/master | 2020-06-30T18:38:15.453372 | 2017-11-20T00:42:36 | 2017-11-20T00:42:36 | 67,306,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,049 | cpp | #include <map>
#include <set>
#include <list>
#include <stack>
#include <cmath>
#include <queue>
#include <ctime>
#include <cfloat>
#include <vector>
#include <string>
#include <cstdio>
#include <bitset>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3FFFFFFFFFLL
#define FILL(X, V) memset( X, V, sizeof(X) )
#define TI(X) __typeof((X).begin())
#define ALL(V) V.begin(), V.end()
#define SIZE(V) int((V).size())
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define RFOR(i, b, a) for(int i = b; i >= a; --i)
#define REP(i, N) for(int i = 0; i < N; ++i)
#define RREP(i, N) for(int i = N-1; i >= 0; --i)
#define FORIT(i, a) for( TI(a) i = a.begin(); i != a.end(); i++ )
#define PB push_back
#define MP make_pair
typedef long long int64;
typedef unsigned long long uint64;
using namespace std;
struct tri{
int id, qt;
tri(int id = 0, int qt = 0) : id(id), qt(qt) { }
};
inline void read( int &n ) {
n = 0;
bool neg = false;
char c = getchar_unlocked();
if( c == EOF){ n = -400; return; }
while (!('0' <= c && c <= '9')) {
if( c == '-' ) neg = true;
c = getchar_unlocked();
}
while ('0' <= c && c <= '9') {
n = n * 10 + c - '0';
c = getchar_unlocked();
}
n = (neg ? (-n) : (n));
}
inline void readChar( char &n ) {
char c = getchar_unlocked();
if( c == EOF) exit(1);
while (!('a' <= c && c <= 'z')) {
c = getchar_unlocked();
}
n = c;
}
int main(){
int n, qt, num;
while(true){
read(n);
if(!n) break;
char a[30];
char b[10000];
char c[30];
int posA = n-1, posB = 1;
REP(i,n) readChar( a[posA--] ); //cin >> a[posA--];
a[posA] = '\0';
posA = n;
REP(i,n) readChar( c[i] ); //cin >> c[i];
bool flag = true;
REP(i,n){
if(!flag)break;
if(posB != 0 && c[i] == b[posB-1]){ posB--; printf("R"); }
else{
while(true){
if(posA != 0){
if(c[i] == a[posA-1]){
putchar('I');
putchar('R');
posA--;
flag = true;
break;
}
else{
b[posB++] = a[posA-1];
putchar('I');
posA--;
flag = false;
}
}
else{
flag = false;
break;
}
}
}
}
if(!flag) puts(" Impossible");
else puts("");
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
18ddfa06957629543185a1b97be7192763d52977 | db9df9237d3d368f25c7d9329d4b05ad5a7bb30e | /src/a_rank_levele_up/snake_mapmove_step4/main.cpp | d4313443df7ca57c8582a669e6780393f7c94c5d | [] | no_license | KEY60228/paiza_learning | 006cbec131e9370d71d81f6935175fa0d278313d | 84ad7a6cbffc8c46e686c10099e210dffe41c7e2 | refs/heads/master | 2023-08-12T16:34:06.114154 | 2021-10-01T04:04:38 | 2021-10-01T04:04:38 | 380,766,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,922 | cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int h, w, y, x, n;
cin >> h >> w >> y >> x >> n;
vector<string> v;
for (int i = 0; i < h; i++) {
string s;
cin >> s;
v.push_back(s);
}
int D = 100;
for (int i = 0; i < n; i++) {
char c;
int k;
cin >> c >> k;
try {
switch (D % 4) {
case 0:
if (c == 'R') {
for (int j = 1; j <= k; j++) {
x++;
if (v[y].at(x) == '#') {
throw exception();
}
if (j == k) {
D++;
}
}
} else {
for (int j = 1; j <= k; j++) {
x--;
if (v[y].at(x) == '#') {
throw exception();
}
if (j == k) {
D--;
}
}
}
break;
case 1:
if (c == 'R') {
for (int j = 1; j <= k; j++) {
y++;
if (v.at(y)[x] == '#') {
throw exception();
}
if (j == k) {
D++;
}
}
} else {
for (int j = 1; j <= k; j++) {
y--;
if (v.at(y)[x] == '#') {
throw exception();
}
if (j == k) {
D--;
}
}
}
break;
case 2:
if (c == 'R') {
for (int j = 1; j <= k; j++) {
x--;
if (v[y].at(x) == '#') {
throw exception();
}
if (j == k) {
D++;
}
}
} else {
for (int j = 1; j <= k; j++) {
x++;
if (v[y].at(x) == '#') {
throw exception();
}
if (j == k) {
D--;
}
}
}
break;
case 3:
if (c == 'R') {
for (int j = 1; j <= k; j++) {
y--;
if (v.at(y)[x] == '#') {
throw exception();
}
if (j == k) {
D++;
}
}
} else {
for (int j = 1; j <= k; j++) {
y++;
if (v.at(y)[x] == '#') {
throw exception();
}
if (j == k) {
D--;
}
}
}
break;
}
} catch (exception const & e) {
if (c == 'R') {
switch (D % 4) {
case 0:
x--;
break;
case 1:
y--;
break;
case 2:
x++;
break;
case 3:
y++;
break;
}
} else {
switch (D % 4) {
case 0:
x++;
break;
case 1:
y++;
break;
case 2:
x--;
break;
case 3:
y--;
break;
}
}
cout << y << " " << x << endl;
cout << "Stop" << endl;
break;
}
cout << y << " " << x << endl;
}
return 0;
} | [
"Mt.mouth60228@gmail.com"
] | Mt.mouth60228@gmail.com |
b452b5041b0f8324f701194b9dff45020ec7116f | 9a488a219a4f73086dc704c163d0c4b23aabfc1f | /tags/Release-1_0rc/src/SystemTray.hh | 8be1cd8bb1715dec08792e87cfd4b7c73c76a0ea | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | BackupTheBerlios/fluxbox-svn | 47b8844b562f56d02b211fd4323c2a761b473d5b | 3ac62418ccf8ffaddbf3c181f28d2f652543f83f | refs/heads/master | 2016-09-05T14:55:27.249504 | 2007-12-14T23:27:57 | 2007-12-14T23:27:57 | 40,667,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,911 | hh | // SystemTray.hh
// Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id$
#ifndef SYSTEMTRAY_HH
#define SYSTEMTRAY_HH
#include "FbTk/FbWindow.hh"
#include "FbTk/EventHandler.hh"
#include "FbTk/Observer.hh"
#include "ToolbarItem.hh"
#include "ButtonTheme.hh"
#include "Screen.hh"
#include <X11/Xlib.h>
#include <list>
class AtomHandler;
class SystemTray: public ToolbarItem, public FbTk::EventHandler, public FbTk::Observer {
public:
explicit SystemTray(const FbTk::FbWindow &parent, ButtonTheme &theme, BScreen& screen);
virtual ~SystemTray();
void move(int x, int y);
void resize(unsigned int width, unsigned int height);
void moveResize(int x, int y,
unsigned int width, unsigned int height);
void show();
void hide();
bool active() { return !m_clients.empty(); }
bool clientMessage(const XClientMessageEvent &event);
void exposeEvent(XExposeEvent &event);
void handleEvent(XEvent &event);
void addClient(Window win);
void removeClient(Window win);
unsigned int width() const;
unsigned int height() const;
unsigned int borderWidth() const;
int numClients() const { return m_clients.size(); }
const FbTk::FbWindow &window() const { return m_window; }
inline void renderTheme(unsigned char alpha) {}
inline void updateSizing() {}
void parentMoved() { m_window.parentMoved(); }
private:
void update(FbTk::Subject *subj);
typedef std::list<FbTk::FbWindow *> ClientList;
ClientList::iterator findClient(Window win);
void rearrangeClients();
void removeAllClients();
FbTk::FbWindow m_window;
ButtonTheme& m_theme;
BScreen& m_screen;
Pixmap m_pixmap;
std::auto_ptr<AtomHandler> m_handler;
ClientList m_clients;
};
#endif // SYSTEMTRAY_HH
| [
"fluxgen@54ec5f11-9ae8-0310-9a2b-99d706b22625"
] | fluxgen@54ec5f11-9ae8-0310-9a2b-99d706b22625 |
665502a1bc54c1815e4bc5569a7b36c421a3bc92 | bc4af9166e9c4074338a58f5a9bced45a2c08720 | /d01/ex06/HumanB.cpp | 3b676911fe85d7a146918059a67dc94e9ba52ecf | [] | no_license | abassibe/CPP | 75eeb5f82fefd2fe37d79cabe8a00ffbac9a6790 | a5fe1431052ee089f95a57c30857a837f879736f | refs/heads/master | 2020-05-04T20:50:27.611626 | 2019-04-08T13:34:20 | 2019-04-08T13:34:20 | 179,453,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* HumanB.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abassibe <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/26 18:18:13 by abassibe #+# #+# */
/* Updated: 2019/03/26 18:25:11 by abassibe ### ########.fr */
/* */
/* ************************************************************************** */
#include "HumanB.hpp"
#include <iostream>
HumanB::HumanB(std::string name) : _name(name)
{
}
HumanB::~HumanB()
{
}
void HumanB::setWeapon(Weapon &weapon)
{
_weapon = &weapon;
}
void HumanB::attack() const
{
std::cout << _name << " attacks with his " << _weapon->getType() << std::endl;
}
| [
"abassibe@e1r3p6.42.fr"
] | abassibe@e1r3p6.42.fr |
6fc8084541d026edd948f53fbd90f787b2acef1b | 7b878196951a912866dced8fb0dda0724635dc37 | /src/ofApp.cpp | 9ab0248cd477096de92226f1330819b5537166ca | [] | no_license | CaterTsai/kinectBlobSimulation | 2a862bf528a86f001cd91b4d9f187288767266cc | 25a104f648d71b75a36b06eafd5636047be061cc | refs/heads/master | 2020-03-28T15:47:33.560733 | 2018-09-13T17:19:09 | 2018-09-13T17:19:09 | 148,626,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,807 | cpp | #include "ofApp.h"
#pragma region KinectUnit
//--------------------------------------------------------------
void kinectUnit::setup(int id, ofRectangle rect, int port)
{
_kinectId = id;
_range = rect;
_package._kid = id;
_udpSender.Create();
_udpSender.Connect("127.0.0.1", port);
_udpSender.SetNonBlocking(true);
}
//--------------------------------------------------------------
void kinectUnit::update(array<testBlobData, cTestBlobSize>& blobList)
{
int index = 0;
for (int i = 0; i < cKMaxBlobNumEach; i++)
{
_package._blobData[i].x = 0;
_package._blobData[i].y = 0;
_package._blobData[i].width = 0;
_package._blobData[i].height = 0;
}
for (auto& iter : blobList)
{
ofRectangle rect(iter.pos, iter.width, iter.height);
if (_range.intersects(rect))
{
auto intersectRect = getIntersectRect(rect);
_package._blobData[index].x = intersectRect.x - _range.x;
_package._blobData[index].y = intersectRect.y - _range.y;
_package._blobData[index].width = intersectRect.width;
_package._blobData[index].height = intersectRect.height;
index++;
}
if (index >= cKMaxBlobNumEach)
{
break;
}
}
send();
}
//--------------------------------------------------------------
void kinectUnit::draw()
{
ofPushStyle();
ofPushMatrix();
ofTranslate(_range.getTopLeft());
ofDrawRectangle(0, 0, _range.width, _range.height);
for (int i = 0; i < cKMaxBlobNumEach; i++)
{
ofDrawRectangle(
_package._blobData[i].x,
_package._blobData[i].y,
_package._blobData[i].width,
_package._blobData[i].height
);
}
ofPopMatrix();
ofPopStyle();
}
//--------------------------------------------------------------
ofRectangle kinectUnit::getIntersectRect(ofRectangle& rect)
{
ofVec2f posLT, posRB;
posLT.x = MAX(rect.getLeft(), _range.getLeft());
posLT.y = MAX(rect.getTop(), _range.getTop());
posRB.x = MIN(rect.getRight(), _range.getRight());
posRB.y = MIN(rect.getBottom(), _range.getBottom());
return ofRectangle(posLT, posRB);
}
//--------------------------------------------------------------
void kinectUnit::send()
{
char msg[cUDPSendMsgLength] = { 0 };
memcpy(msg, &_package, sizeof(kinectPackage));
_udpSender.Send(msg, cUDPSendMsgLength);
}
#pragma endregion
//--------------------------------------------------------------
void ofApp::setup() {
_kinectsList[0].setup(1, ofRectangle(10, 10, 640, 480), 2233);
_kinectsList[1].setup(2, ofRectangle(630, 10, 640, 480), 2244);
_kinectsList[2].setup(3, ofRectangle(10, 470, 640, 480), 2255);
_kinectsList[3].setup(4, ofRectangle(630, 470, 640, 480), 2266);
_sendTimer = cSendTime;
ofBackground(0);
ofSetFrameRate(60);
_timer = ofGetElapsedTimef();
}
//--------------------------------------------------------------
void ofApp::update() {
float delta = ofGetElapsedTimef() - _timer;
_timer += delta;
_sendTimer -= delta;
if (_sendTimer <= 0.0f)
{
_sendTimer = cSendTime;
for (int i = 0; i < 4; i++)
{
_kinectsList[i].update(_blobDataList);
}
}
updateBlob(delta);
}
//--------------------------------------------------------------
void ofApp::draw() {
ofPushStyle();
{
ofNoFill();
ofSetColor(255, 0, 0);
_kinectsList[0].draw();
ofSetColor(255, 255, 0);
_kinectsList[1].draw();
ofSetColor(255, 0, 255);
_kinectsList[2].draw();
ofSetColor(0, 255, 0);
_kinectsList[3].draw();
}
ofPopStyle();
drawBlob();
}
//--------------------------------------------------------------
void ofApp::updateBlob(float delta)
{
for (auto& iter : _blobDataList)
{
iter.update(delta);
}
}
//--------------------------------------------------------------
void ofApp::drawBlob()
{
ofPushStyle();
ofNoFill();
ofSetColor(255);
for (auto& iter : _blobDataList)
{
ofDrawRectangle(iter.pos, iter.width, iter.height);
}
ofPopStyle();
}
| [
"caterokusai@gmail.com"
] | caterokusai@gmail.com |
e6693b1579a7acddf5f2927bdf1dc235eaf43483 | 2277375bd4a554d23da334dddd091a36138f5cae | /ThirdParty/CUDA/include/thrust/system/cuda/detail/copy_if.h | 4cbf6adf504cd5908c36b8057d6be116b4427655 | [] | no_license | kevinmore/Project-Nebula | 9a0553ccf8bdc1b4bb5e2588fc94516d9e3532bc | f6d284d4879ae1ea1bd30c5775ef8733cfafa71d | refs/heads/master | 2022-10-22T03:55:42.596618 | 2020-06-19T09:07:07 | 2020-06-19T09:07:07 | 25,372,691 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,418 | h | /*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <thrust/detail/config.h>
#include <thrust/system/cuda/detail/execution_policy.h>
namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
template<typename DerivedPolicy,
typename InputIterator1,
typename InputIterator2,
typename OutputIterator,
typename Predicate>
OutputIterator copy_if(execution_policy<DerivedPolicy> &exec,
InputIterator1 first,
InputIterator1 last,
InputIterator2 stencil,
OutputIterator result,
Predicate pred);
} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust
#include <thrust/system/cuda/detail/copy_if.inl>
| [
"dingfengyu@gmail.com"
] | dingfengyu@gmail.com |
77f720e98ce8e0bab40dae3d6a9a9ab0597ec8aa | 1e23d293a86830184ff9d59039e4d8f2d2a8f318 | /code_convert.h | af07f7e12f25955ad92e1b65f74a0eb582537eed | [] | no_license | beru/bitmap-font-encoder | c95a3e9641119f79cf0c93fd797a41db84685473 | 1ca6f91c440dc05db4c4ec2ac99a14ffe908209a | refs/heads/master | 2016-09-06T17:27:29.748951 | 2011-08-23T13:21:33 | 2011-08-23T13:21:33 | 33,050,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | h | #pragma once
namespace CodeConvert {
bool Init();
uint16_t unicode_to_jis(uint16_t unicode);
// uint16_t jis_to_unicode(uint16_t unicode);
} // namespace CodeConvert
| [
"berupon@gmail.com"
] | berupon@gmail.com |
2cddc137c3a95389a423d761180b70a519ca22d2 | b0dd7779c225971e71ae12c1093dc75ed9889921 | /boost/icl/concept/interval_associator_base.hpp | 3f362354738c2db6b61659557dafe5c1363153e0 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 6,476 | hpp | /*-----------------------------------------------------------------------------+
Copyright (c) 2011-2011: Joachim Faulhaber
+------------------------------------------------------------------------------+
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENCE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
+-----------------------------------------------------------------------------*/
#ifndef BOOST_ICL_CONCEPT_INTERVAL_ASSOCIATOR_BASE_HPP_JOFA_110301
#define BOOST_ICL_CONCEPT_INTERVAL_ASSOCIATOR_BASE_HPP_JOFA_110301
#include <boost/icl/type_traits/domain_type_of.hpp>
#include <boost/icl/type_traits/interval_type_of.hpp>
#include <boost/icl/type_traits/is_combinable.hpp>
#include <boost/icl/concept/set_value.hpp>
#include <boost/icl/concept/map_value.hpp>
#include <boost/icl/concept/interval.hpp>
namespace boost{ namespace icl
{
//==============================================================================
//= Selection<IntervalSet|IntervalMap>
//==============================================================================
template<class Type> inline
typename enable_if<mpl::and_< is_interval_container<Type>
, is_discrete<typename domain_type_of<Type>::type>
>
, typename Type::const_iterator>::type
find(const Type& object, const typename domain_type_of<Type>::type& key_val)
{
typedef typename Type::const_iterator const_iterator;
typedef typename Type::interval_type interval_type;
return object.find(icl::detail::unit_trail<interval_type>(key_val));
}
template<class Type> inline
typename enable_if<mpl::and_< is_interval_container<Type>
, is_continuous<typename domain_type_of<Type>::type>
, has_dynamic_bounds<typename interval_type_of<Type>::type>
>
, typename Type::const_iterator>::type
find(const Type& object, const typename domain_type_of<Type>::type& key_val)
{
typedef typename Type::const_iterator const_iterator;
typedef typename Type::interval_type interval_type;
return object.find(icl::singleton<interval_type>(key_val));
}
template<class Type> inline
typename enable_if<mpl::and_< is_interval_container<Type>
, is_continuous<typename domain_type_of<Type>::type>
, is_static_right_open<typename interval_type_of<Type>::type>
, boost::detail::is_incrementable<typename domain_type_of<Type>::type>
>
, typename Type::const_iterator>::type
find(const Type& object, const typename domain_type_of<Type>::type& key_val)
{
typedef typename Type::const_iterator const_iterator;
typedef typename Type::interval_type interval_type;
const_iterator first_collision = object.lower_bound(icl::detail::unit_trail<interval_type>(key_val));
// A part of the unit_trail(key_value)-interval may be found in the container, that
// does not contain key_value. Therefore we have to check for its existence:
return ( first_collision == object.end()
|| icl::contains(key_value<Type>(first_collision), key_val) )
? first_collision
: object.end();
}
template<class Type> inline
typename enable_if<mpl::and_< is_interval_container<Type>
, is_continuous<typename domain_type_of<Type>::type>
, is_static_left_open<typename interval_type_of<Type>::type>
, boost::detail::is_incrementable<typename domain_type_of<Type>::type>
>
, typename Type::const_iterator>::type
find(const Type& object, const typename domain_type_of<Type>::type& key_val)
{
typedef typename Type::const_iterator const_iterator;
typedef typename Type::interval_type interval_type;
const_iterator last_collision = object.upper_bound(icl::detail::unit_trail<interval_type>(key_val));
if(last_collision != object.begin())
--last_collision;
// A part of the unit_trail(key_value)-interval may be found in the container, that
// does not contain key_value. Therefore we have to check for its existence:
return ( last_collision == object.end()
|| icl::contains(key_value<Type>(last_collision), key_val) )
? last_collision
: object.end();
}
// NOTE: find(object, key) won't compile if key is of continuous type that does
// not implement in(de)crementation (e.g. std::string).
template<class Type> inline
typename enable_if< is_interval_container<Type>
, typename Type::const_iterator>::type
find(const Type& object, const typename interval_type_of<Type>::type& inter_val)
{
return object.find(inter_val);
}
//==============================================================================
//= Morphisms
//==============================================================================
template<class Type>
typename enable_if<is_interval_container<Type>, Type>::type&
join(Type& object)
{
typedef typename Type::interval_type interval_type;
typedef typename Type::iterator iterator;
iterator it_ = object.begin();
if(it_ == object.end())
return object;
iterator next_ = it_; next_++;
while(next_ != object.end())
{
if( segmental::is_joinable<Type>(it_, next_) )
{
iterator fst_mem = it_; // hold the first member
// Go on while touching members are found
it_++; next_++;
while( next_ != object.end()
&& segmental::is_joinable<Type>(it_, next_) )
{ it_++; next_++; }
// finally we arrive at the end of a sequence of joinable intervals
// and it points to the last member of that sequence
const_cast<interval_type&>(key_value<Type>(it_))
= hull(key_value<Type>(it_), key_value<Type>(fst_mem));
object.erase(fst_mem, it_);
it_++; next_=it_;
if(next_!=object.end())
next_++;
}
else { it_++; next_++; }
}
return object;
}
}} // namespace boost icl
#endif
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
ee1bdca1af10208cf81a13697c71d4435cc56049 | ba1bb56395640b66122052c1ccd340ca8cac3e68 | /SistemaExperto/src/lista_nodos.cpp | 282ac14b38dd77f6f7c7ca2c33c13342e2379575 | [] | no_license | victornoriega/data-structures | d4b0646bf9cd2911fecc21a2366374125d61833a | 7d15a641cf103faa542d35bd594d2c4801f828c7 | refs/heads/master | 2021-07-25T06:03:18.567376 | 2017-11-06T13:50:18 | 2017-11-06T13:50:18 | 109,658,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,096 | cpp | #include "lista_nodos.h"
#include <lista_arcos.h>
#include <utilerias.h>
#include <cstdlib>
lista_nodos::lista_nodos()
{
nuevo();
}
lista_nodos::~lista_nodos()
{
borrar();
}
void lista_nodos::nuevo(){
principio=NULL;
anterior=NULL;
lugar_encontrado=NULL;
}
void lista_nodos::borrar(){
caja2 *p;
while(principio){
p=principio;
principio=p->siguiente;
free(p);
}
anterior=NULL;
donde=VACIO;
encontrado=NO;
}
int lista_nodos::agregar(int a){
caja2 *p;
buscar(a);
if(encontrado==SI) return 0;
p=(caja2*)malloc(sizeof(caja2));
p->num_nodo=a;
p->bandera=0;
p->ruta_corta=0.0;
p->anterior=NULL;
p->direccion=NULL;
(p->salientes).nuevo();
(p->entrantes).nuevo();
if(donde==VACIO){
p->siguiente=NULL;
principio=p;
}else if(donde==PRINCIPIO){
p->siguiente=principio;
principio=p;
}else if(donde==ENMEDIO){
p->siguiente=anterior->siguiente;
anterior->siguiente=p;
}else{
p->siguiente=NULL;
anterior->siguiente=p;
}
return 1;
}
void lista_nodos::buscar(int a){
caja2 *p;
p=principio;
if(!principio){
encontrado=NO;
donde=VACIO;
return;
}else{
while(p){
if(p->num_nodo==a){
encontrado=SI;
if(principio==p){
donde=PRINCIPIO;
}else if(p->siguiente==NULL){
donde=FINAL;
}
else{
donde=ENMEDIO;
}
return;
}else if(p->num_nodo>a){
encontrado=NO;
if(principio==p){
donde=PRINCIPIO;
}else{
donde=ENMEDIO;
}
return;
}else{
anterior=p;
p=p->siguiente;
}
}
encontrado=NO;
donde=FINAL;
}
}
caja2* lista_nodos::lugarEncontrado(){
return lugar_encontrado;
}
| [
"victornoriega"
] | victornoriega |
4262c0612808b88835b877cc46b14318362573ed | f69d6d8c7643c4e34356e0a5c290433bd2d09e07 | /app/cursorRight.hpp | 2a14a7678291a551721ec1b23952ea09c1733e48 | [] | no_license | enochychang/CLI-Text-Editor | d5d17c1c18a8a4f268cdcaf5cab877dddbe5529b | 9e2f7c4f1accfbad00c1b0b4ad2070c75ae0e4d6 | refs/heads/master | 2021-04-12T17:18:45.278710 | 2020-03-22T02:07:24 | 2020-03-22T02:07:24 | 249,095,917 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | hpp | #ifndef CURSORRIGHT_HPP
#define CURSORRIGHT_HPP
#include "Command.hpp"
class cursorRight : public Command {
void execute(EditorModel& model) override;
void undo(EditorModel& model) override;
};
#endif | [
"enochychang@gmail.com"
] | enochychang@gmail.com |
669d9ee98d739452e678b5317f9249522b54b08b | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8/squeespoon/3264486_5654742835396608_squeespoon.cpp | d724e5f625d56a65e328f2f97ed25b5c739c1597 | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 514 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
freopen("C-small-1-attempt2.in","r",stdin);
freopen("C-small-1-attempt2.out","w",stdout);
int t;
cin>>t;
int cas = 0;
while(t--){
cas++;
ll n,k;
cin>>n>>k;
while(k > 1){
// cout<<n<<" "<<k<<endl;
if(n&1){
n>>=1;
k>>=1;
}else{
n>>=1;
if(k&1){
n--;
}
k>>=1;
}
}
printf("Case #%d: ",cas);
cout<<n/2<<" "<<(n-1)/2<<endl;
}
return 0;
}
| [
"e.quiring@tu-bs.de"
] | e.quiring@tu-bs.de |
83bb98574a2a032f246f22b51d65cf1870d628d1 | 260e5dec446d12a7dd3f32e331c1fde8157e5cea | /Indi/SDK/Indi_Drink_Rizzo_SpectrumVodkaGreen_classes.hpp | a2714e67a1f5545b6a9eb6f05159906d197baf1a | [] | no_license | jfmherokiller/TheOuterWorldsSdkDump | 6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0 | 18a8c6b1f5d87bb1ad4334be4a9f22c52897f640 | refs/heads/main | 2023-08-30T09:27:17.723265 | 2021-09-17T00:24:52 | 2021-09-17T00:24:52 | 407,437,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | hpp | #pragma once
// TheOuterWorlds SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "Indi_Drink_Rizzo_SpectrumVodkaGreen_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Drink_Rizzo_SpectrumVodkaGreen.Drink_Rizzo_SpectrumVodkaGreen_C
// 0x0000 (0x0230 - 0x0230)
class UDrink_Rizzo_SpectrumVodkaGreen_C : public UConsumableItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Drink_Rizzo_SpectrumVodkaGreen.Drink_Rizzo_SpectrumVodkaGreen_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"peterpan0413@live.com"
] | peterpan0413@live.com |
0f5df323011324fef3ab96d08f4bc84e19192c52 | fc79fe29914d224d9f3a1e494aff6b8937be723f | /Libraries/Rim Entities/include/rim/entities/rimEntityEvent.h | ba9ea2c8f75b72a987b36eb0d08f88ccf23759c4 | [] | no_license | niti1987/Quadcopter | e078d23dd1e736fda19b516a5cd5e4aca5aa3c50 | 6ca26b1224395c51369442f202d1b4c4b7188351 | refs/heads/master | 2021-01-01T18:55:55.210906 | 2014-12-09T23:37:09 | 2014-12-09T23:37:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,738 | h | /*
* rimEntityEvent.h
* Rim Entities
*
* Created by Carl Schissler on 5/13/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#ifndef INCLUDE_RIM_ENTITY_EVENT_H
#define INCLUDE_RIM_ENTITY_EVENT_H
#include "rimEntitiesConfig.h"
//##########################################################################################
//************************** Start Rim Entities Namespace ********************************
RIM_ENTITIES_NAMESPACE_START
//******************************************************************************************
//##########################################################################################
class Entity;
class EntitySystem;
/// The type to use for event types.
typedef String EventType;
//********************************************************************************
//********************************************************************************
//********************************************************************************
/// A class that encapsulates an entity event.
/**
* An event consists of a string-based event type, a time when the event
* occurred, a time-out period for the event, and a value of arbitrary type
* that the user an use to pass any kind of data with an event.
*/
class Event
{
public:
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Constructors
/// Create an event with the specified type and timeout period.
/**
* If not specified, the timeout period has a default value of 60 seconds.
*/
Event( const EventType& newType, const Entity* entitySender = NULL, const EntitySystem* systemSender = NULL,
const Time newTimeoutPeriod = 60.0 );
/// Create an event with the specified type, value, and timeout period.
/**
* If not specified, the timeout period has a default value of 60 seconds.
*/
template < typename ValueType >
Event( const EventType& newType, ValueType newValue, const Entity* entitySender = NULL,
const EntitySystem* systemSender = NULL, Time newTimeoutPeriod = 60.0 );
/// Create a copy of the specified event.
Event( const Event& other );
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Destructor
/// Destroy this event and all of its state.
virtual ~Event();
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Assignment Operator
/// Assign the state of another event to this event.
Event& operator = ( const Event& other );
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Event Type Accessor Methods
/// Return a reference to a string representing the type of this event.
RIM_INLINE const EventType& getType() const
{
return type;
}
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Event Time Accessor Methods
/// Return a reference to a Time object which represents the moment that this event was created.
RIM_INLINE const Time& getTime() const
{
return time;
}
/// Return a reference to a Time object which represents the time that this event is valid.
RIM_INLINE const Time& getTimeoutPeriod() const
{
return timeoutPeriod;
}
/// Return whether or not this event has timed out yet.
/**
* If the current time is later than the event's creation time plus
* its timeout period, the event is no longer considered valid.
*/
RIM_INLINE Bool isValid() const
{
return Time::getCurrent() >= time + timeoutPeriod;
}
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Event Value Accessor Methods
/// Return whether or not this event has a value associated with it.
RIM_INLINE Bool hasValue() const
{
return value != NULL;
}
/// Return a pointer to this event's value.
/**
* If the event does not have a value or if the requested templated
* type is incompatible with the event's value, NULL is returned.
*/
template < typename ValueType >
RIM_INLINE const ValueType* getValue() const;
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Event Sender Accessor Methods
/// Return a pointer to entity that produced this event, or NULL if there is no entity sender.
RIM_INLINE const Entity* getEntity() const
{
return entitySender;
}
/// Return a pointer to entity system that produced this event, or NULL if there is no system sender.
RIM_INLINE const EntitySystem* getSystem() const
{
return systemSender;
}
private:
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Private Class Declarations
/// The base class for classes that hold event values of arbitrary type.
class EventValueBase;
/// A class which holds an event value of the specified value type.
template < typename ValueType >
class EventValue;
//********************************************************************************
//********************************************************************************
//********************************************************************************
//****** Private Data Members
/// A string representing the type of this event.
EventType type;
/// The time at which this event was created.
Time time;
/// The amount of time that can pass before this event becomes invalid.
Time timeoutPeriod;
/// The value for this event. This value is used to carry arbitrary information about the event.
EventValueBase* value;
/// A pointer to the entity which produced this event.
const Entity* entitySender;
/// A pointer to the entity system which produced this event.
const EntitySystem* systemSender;
};
//##########################################################################################
//##########################################################################################
//############
//############ Base Event Value Class Defintion
//############
//##########################################################################################
//##########################################################################################
class Event:: EventValueBase
{
public:
virtual ~EventValueBase()
{
}
/// Return a pointer to the value stored in this event value.
/**
* If there is no value or the type is incompatible, the method
* returns NULL.
*/
template < typename ValueType >
RIM_INLINE ValueType* getValue();
/// Return a const pointer to the value stored in this event value.
/**
* If there is no value or the type is incompatible, the method
* returns NULL.
*/
template < typename ValueType >
RIM_INLINE const ValueType* getValue() const;
/// Construct and return a copy of this event value.
virtual EventValueBase* copy() const = 0;
};
//##########################################################################################
//##########################################################################################
//############
//############ Event Value Class Defintion
//############
//##########################################################################################
//##########################################################################################
template < typename ValueType >
class Event:: EventValue : public EventValueBase
{
public:
/// Create a new event value object which stores a copy of the specified value.
RIM_INLINE EventValue( const ValueType& newValue )
: value( newValue )
{
}
/// Return a pointer to the value stored in this event value.
/**
* If there is no value or the type is incompatible, the method
* returns NULL.
*/
RIM_INLINE ValueType* getValue()
{
return &value;
}
/// Return a const pointer to the value stored in this event value.
/**
* If there is no value or the type is incompatible, the method
* returns NULL.
*/
RIM_INLINE const ValueType* getValue() const
{
return &value;
}
/// Construct and return a copy of this event value.
virtual EventValueBase* copy() const
{
return util::construct<EventValue<ValueType> >( *this );
}
private:
/// The user-defined value object associated with this event value.
ValueType value;
};
//##########################################################################################
//##########################################################################################
//############
//############ Event Constructors
//############
//##########################################################################################
//##########################################################################################
template < typename ValueType >
Event:: Event( const EventType& newType, ValueType newValue, const Entity* newEntitySender,
const EntitySystem* newSystemSender, Time newTimeoutPeriod )
: type( newType ),
time( Time::getCurrent() ),
timeoutPeriod( newTimeoutPeriod )
{
value = util::construct<EventValue<ValueType> >( newValue );
}
//##########################################################################################
//##########################################################################################
//############
//############ Event Value Accessor Methods
//############
//##########################################################################################
//##########################################################################################
template < typename ValueType >
ValueType* Event::EventValueBase:: getValue()
{
EventValue<ValueType>* array = dynamic_cast<EventValue<ValueType>*>( this );
if ( array != NULL )
return array->getComponents();
else
return NULL;
}
template < typename ValueType >
const ValueType* Event::EventValueBase:: getValue() const
{
const EventValue<ValueType>* value = dynamic_cast<const EventValue<ValueType>*>( this );
if ( value != NULL )
return value->getValue();
else
return NULL;
}
template < typename ValueType >
const ValueType* Event:: getValue() const
{
if ( value != NULL )
return value->getValue<ValueType>();
else
return NULL;
}
//##########################################################################################
//************************** End Rim Entities Namespace **********************************
RIM_ENTITIES_NAMESPACE_END
//******************************************************************************************
//##########################################################################################
#endif // INCLUDE_RIM_ENTITY_EVENT_H
| [
"niti1987@gmail.com"
] | niti1987@gmail.com |
146214533ef151919ea086490362359bdf16c115 | 0a3a0da7358c55ebbfc3e1904e53409c6397ec1a | /DataBase/tablefield.h | e47515607fbb5f92532a0bc7366559eee291d61c | [] | no_license | Sokolov-Dmitriy/RPM | ab7aeb65153b9216b70b7828143a2f843ae301ca | 7bb72026c5840b672608e62957d2707c441b7065 | refs/heads/master | 2022-11-15T05:17:26.327354 | 2020-07-07T09:32:30 | 2020-07-07T09:32:30 | 275,368,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,003 | h | #ifndef TABLEFIELD_H
#define TABLEFIELD_H
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlTableModel>
#include <QString>
#include <QGridLayout>
#include <QModelIndex>
#include <QCloseEvent>
#include <QModelIndex>
#include <QVector>
#include <QTextEdit>
class TableField : public QWidget
{
Q_OBJECT
protected:
/**
* @brief closeEvent - функция перехвата события закрытия окна
* @param event - указатель на событие
*/
void closeEvent(QCloseEvent *event);
public:
/**
* @brief TableField - конструктор окна добавления/редактирования данных в поле
* @param tableModel - указатеь на модель таблицы
* @param index - индекс записи
* @param parent - указатель на QWidjet
*/
explicit TableField(QSqlTableModel* tableModel,QModelIndex index,QWidget *parent = nullptr);
/**
* @brief TableField - конструктор окна добавления/редактирования данных в поле
* @param tableModel - указатеь на модель таблицы
* @param parent - указатель на QWidjet
*/
explicit TableField(QSqlTableModel* tableModel,QWidget *parent = nullptr);
/**
* @brief columnNames - вектор с названями полей
*/
QVector<QLabel*> columnNames;
/**
* @brief columnText - указатель на QLineEdit
*/
QVector<QLineEdit*> columnText;
/**
* @brief setInformation - функция записи в QLineEdit информации из таблицы
*/
void setInformation();
/**
* @brief setWidjet - установки родительского Widjet
*/
void setWidjet();
private:
/**
* @brief errorText - указатель на поле QTExtEdit
*/
QTextEdit* errorText = new QTextEdit();
/**
* @brief row - номер сктроки
*/
int row;
/**
* @brief tableModel - указатель на модель таблицы
*/
QSqlTableModel* tableModel;
/**
* @brief index - индекс в поля в таблице
*/
QModelIndex index;
/**
* @brief gridLayoyt - указатель на QGridLayout
*/
QGridLayout* gridLayoyt = new QGridLayout(this);
/**
* @brief createQuery - функция запроса к таблице
* @return - результат запроса
*/
QSqlQuery createQuery();
signals:
public slots:
/**
* @brief saveEditField - слот для сохранения отредактированных данные
*/
void saveEditField();
/**
* @brief saveNewField - слот для сохранения новых данных
*/
void saveNewField();
};
#endif // TABLEFIELD_H
| [
"63058945+Sokolov-Dmitriy@users.noreply.github.com"
] | 63058945+Sokolov-Dmitriy@users.noreply.github.com |
706cf601a838616f8c286ad6749056a4fc71b86c | ed892c8a5ea7e9deaa917af45783326a843e9e1f | /apps/rosetta/riflib/scaffold/MorphingScaffoldProvider.cc | 528ce1a7958e97ef88a5736695d37e846e2d5c0a | [
"Apache-2.0"
] | permissive | chnorn/rifdock | d3945e4dc9cec0a6653dec3f6777131c5995a0e8 | 5a1e50e53ce4af1f58edce2ca75d30cfb8d27838 | refs/heads/master | 2020-09-09T20:39:14.987004 | 2019-12-05T19:49:41 | 2019-12-05T19:49:41 | 221,562,834 | 0 | 0 | NOASSERTION | 2019-11-13T22:22:28 | 2019-11-13T22:22:27 | null | UTF-8 | C++ | false | false | 14,957 | cc | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://wsic_dockosettacommons.org. Questions about this casic_dock
// (c) addressed to University of Waprotocolsgton UW TechTransfer, email: license@u.washington.eprotocols
#include <riflib/types.hh>
#include <riflib/scaffold/MorphingScaffoldProvider.hh>
#include <riflib/scaffold/util.hh>
#include <riflib/util_complex.hh>
#include <ObjexxFCL/format.hh>
#include <riflib/HSearchConstraints.hh>
#include <core/import_pose/import_pose.hh>
#include <string>
#include <vector>
#include <boost/any.hpp>
#include <boost/format.hpp>
using ::scheme::scaffold::BAD_SCAFFOLD_INDEX;
using ::scheme::scaffold::TreeIndex;
using ::scheme::scaffold::TreeLimits;
namespace devel {
namespace scheme {
MorphingScaffoldProvider::MorphingScaffoldProvider(
uint64_t iscaff,
shared_ptr< RotamerIndex > rot_index_p_in,
RifDockOpt const & opt_in,
MakeTwobodyOpts const & make2bopts_in,
::devel::scheme::RotamerRFTablesManager & rotrf_table_manager_in ) :
rot_index_p( rot_index_p_in),
opt(opt_in),
make2bopts(make2bopts_in),
rotrf_table_manager(rotrf_table_manager_in) {
std::string scafftag;
core::pose::Pose scaffold;
utility::vector1<core::Size> scaffold_res;
EigenXform scaffold_perturb;
MorphRules morph_rules;
ExtraScaffoldData extra_data;
get_info_for_iscaff( iscaff, opt, scafftag, scaffold, scaffold_res, scaffold_perturb, morph_rules, extra_data, rot_index_p);
ScaffoldDataCacheOP temp_data_cache_ = make_shared<ScaffoldDataCache>(
scaffold,
scaffold_res,
scafftag,
scaffold_perturb,
rot_index_p,
opt,
extra_data);
ParametricSceneConformationCOP conformation = make_conformation_from_data_cache(temp_data_cache_, false);
MorphMember mmember;
mmember.conformation = conformation;
mmember.tree_relation.depth = 0;
mmember.tree_relation.parent_member = BAD_SCAFFOLD_INDEX;
mmember.tree_relation.first_child = BAD_SCAFFOLD_INDEX;
mmember.tree_relation.last_child = BAD_SCAFFOLD_INDEX;
add_morph_member( mmember );
}
void
MorphingScaffoldProvider::test_make_children(TreeIndex ti) {
using ObjexxFCL::format::I;
std::string scafftag;
core::pose::Pose _scaffold;
utility::vector1<core::Size> scaffold_res;
EigenXform scaffold_perturb;
MorphRules morph_rules;
ExtraScaffoldData extra_data;
get_info_for_iscaff( 0, opt, scafftag, _scaffold, scaffold_res, scaffold_perturb, morph_rules, extra_data, rot_index_p);
if ( opt.morph_rules_fnames.size() > 0 || opt.morph_silent_file == "" ) {
#ifdef USEHDF5
ApplyDSLMScratch dslm_scratch;
// This mess is to get around 2 bugs in the dsl mover
// 1. The database handle is dropped when you the mover is destroyed
// 2. The mover stops working if you use it too many times in a row
protocols::indexed_structure_store::movers::DirectSegmentLookupMoverOP dont_drop_that_database;
for ( uint64_t rulei = 0; rulei < morph_rules.size(); rulei++ ) {
MorphRule const & rule = morph_rules[rulei];
std::cout << "Looking for fragment insertions using these rules: " << std::endl;
std::cout << " low_cut_site: " << rule.low_cut_site << std::endl;
std::cout << " high_cut_site: " << rule.high_cut_site << std::endl;
std::cout << " max_deletion: " << rule.max_deletion << std::endl;
std::cout << " max_insertion: " << rule.max_insertion << std::endl;
std::cout << " max_fragments: " << rule.max_fragments << std::endl;
std::cout << "fragment_cluster_tolerance: " << rule.fragment_cluster_tolerance << std::endl;
std::cout << " fragment_max_rmsd: " << rule.fragment_max_rmsd << std::endl;
protocols::indexed_structure_store::movers::DirectSegmentLookupMoverOP dsl_mover_op(
new protocols::indexed_structure_store::movers::DirectSegmentLookupMover());
protocols::indexed_structure_store::movers::DirectSegmentLookupMover & dsl_mover = *dsl_mover_op;
if (!dont_drop_that_database) {
dont_drop_that_database = dsl_mover_op;
}
uint64_t removed_length = rule.high_cut_site - rule.low_cut_site - 1;
protocols::indexed_structure_store::DirectSegmentLookupConfig config;
config.rmsd_tolerance = 0.3;
config.segment_cluster_tolerance = rule.fragment_cluster_tolerance;
config.max_insertion_length = removed_length + rule.max_insertion;
dsl_mover.lookup_config( config );
dsl_mover.from_chain( 1 );
dsl_mover.to_chain( 2 );
ScaffoldDataCacheOP data_cache = get_data_cache_slow( ti );
core::pose::PoseCOP scaffold = data_cache->scaffold_unmodified_p;
std::vector<core::pose::PoseOP> poses = apply_direct_segment_lookup_mover(
dsl_mover,
*scaffold,
rule.low_cut_site,
rule.high_cut_site,
removed_length - rule.max_deletion,
rule.max_fragments,
rule.fragment_max_rmsd,
dslm_scratch );
int count = 0;
for ( core::pose::PoseOP pose : poses ) {
count++;
extra_data.force_scaffold_center = data_cache->scaffold_center;
ScaffoldDataCacheOP temp_data_cache_ = make_shared<ScaffoldDataCache>(
*pose,
scaffold_res,
scafftag + boost::str(boost::format("%03ir%03i") % rulei % count),
scaffold_perturb,
rot_index_p,
opt,
extra_data
);
if ( opt.use_parent_body_energies ) {
std::cout << "use_parent_body_energies: Preparing parent body energies" << std::endl;
if ( ! data_cache->local_onebody_p ) {
data_cache->setup_onebody_tables( rot_index_p, opt );
}
if ( ! data_cache->local_twobody_p ) {
data_cache->setup_twobody_tables( rot_index_p, opt, make2bopts, rotrf_table_manager);
}
// one-body
temp_data_cache_->scaffold_onebody_glob0_p = data_cache->scaffold_onebody_glob0_p;
temp_data_cache_->local_onebody_p = data_cache->local_onebody_p;
// two-body
temp_data_cache_->scaffold_twobody_p = data_cache->scaffold_twobody_p;
temp_data_cache_->local_twobody_p = data_cache->local_twobody_p;
}
ParametricSceneConformationCOP conformation = make_conformation_from_data_cache(temp_data_cache_, false);
MorphMember mmember;
mmember.conformation = conformation;
mmember.tree_relation.depth = 1;
mmember.tree_relation.parent_member = 0;
mmember.tree_relation.first_child = BAD_SCAFFOLD_INDEX;
mmember.tree_relation.last_child = BAD_SCAFFOLD_INDEX;
mmember.morph_history.push_back(rule);
pose->dump_pdb(temp_data_cache_->scafftag + ".pdb");
add_morph_member( mmember );
}
}
#else
utility_exit_with_message("You must run cmake with the -DUSEHDF5=1 flag to use fragment insertions!!!");
#endif
}
// horrible code duplication
// fix this eventually
if ( opt.morph_silent_file != "" ) {
std::vector<core::pose::PoseOP> poses = extract_poses_from_silent_file( opt.morph_silent_file );
if ( poses.size() > opt.morph_silent_max_structures ) {
// std::cout << "Clustering silent file into " << opt.morph_silent_max_structures << " cluster centers" << std::endl;
if ( opt.morph_silent_random_selection ) {
std::cout << "Randomly selecting " << opt.morph_silent_max_structures << " from silent file" << std::endl;
poses = random_selection_poses_leaving_n( poses, opt.morph_silent_max_structures );
} else {
std::cout << "Clustering silent file into " << opt.morph_silent_max_structures << " cluster centers" << std::endl;
if ( opt.morph_silent_cluster_use_frac >= 1) {
poses = cluster_poses_leaving_n( poses, opt.morph_silent_max_structures );
} else {
poses = cluster_poses_leaving_n_representing_frac( poses, opt.morph_silent_max_structures, opt.morph_silent_cluster_use_frac, 0.05);
}
}
}
ScaffoldDataCacheOP data_cache = get_data_cache_slow( ti );
EigenXform archetype_to_input = EigenXform::Identity();
if ( opt.morph_silent_archetype != "" ) {
core::pose::Pose archetype = *core::import_pose::pose_from_file( opt.morph_silent_archetype );
archetype_to_input = find_xform_from_identical_pose_to_pose( archetype, *data_cache->scaffold_unmodified_p, 1 );
}
for ( core::pose::PoseOP const & pose : poses ) {
apply_xform_to_pose( *pose, archetype_to_input );
extra_data.force_scaffold_center = data_cache->scaffold_center;
ScaffoldDataCacheOP temp_data_cache_ = make_shared<ScaffoldDataCache>(
*pose,
scaffold_res,
pose->pdb_info()->name(),
scaffold_perturb,
rot_index_p,
opt,
extra_data
);
if ( opt.use_parent_body_energies ) {
std::cout << "use_parent_body_energies: Preparing parent body energies" << std::endl;
if ( ! data_cache->local_onebody_p ) {
data_cache->setup_onebody_tables( rot_index_p, opt );
}
if ( ! data_cache->local_twobody_p ) {
data_cache->setup_twobody_tables( rot_index_p, opt, make2bopts, rotrf_table_manager);
}
// one-body
temp_data_cache_->scaffold_onebody_glob0_p = data_cache->scaffold_onebody_glob0_p;
temp_data_cache_->local_onebody_p = data_cache->local_onebody_p;
// two-body
temp_data_cache_->scaffold_twobody_p = data_cache->scaffold_twobody_p;
temp_data_cache_->local_twobody_p = data_cache->local_twobody_p;
}
ParametricSceneConformationCOP conformation = make_conformation_from_data_cache(temp_data_cache_, false);
MorphMember mmember;
mmember.conformation = conformation;
mmember.tree_relation.depth = 1;
mmember.tree_relation.parent_member = 0;
mmember.tree_relation.first_child = BAD_SCAFFOLD_INDEX;
mmember.tree_relation.last_child = BAD_SCAFFOLD_INDEX;
// pose->dump_pdb(temp_data_cache_->scafftag + ".pdb");
add_morph_member( mmember );
}
}
if ( opt.include_parent ) {
MorphMember const & parent_mm = get_morph_member( ti );
MorphMember mmember;
mmember.conformation = parent_mm.conformation;
mmember.tree_relation.depth = 1;
mmember.tree_relation.parent_member = 0;
mmember.tree_relation.first_child = BAD_SCAFFOLD_INDEX;
mmember.tree_relation.last_child = BAD_SCAFFOLD_INDEX;
add_morph_member( mmember );
}
}
TreeIndex
MorphingScaffoldProvider::add_morph_member( MorphMember mmember ) {
uint64_t depth = mmember.tree_relation.depth;
assert( depth <= map_.size() );
if ( depth == map_.size() ) {
map_.resize( map_.size() + 1 );
}
map_[depth].push_back( mmember );
// Tree indexes are 16 bit so be careful
runtime_assert(depth < BAD_SCAFFOLD_INDEX);
runtime_assert(map_[depth].size() < BAD_SCAFFOLD_INDEX);
return TreeIndex(depth, map_[depth].size());
}
ScaffoldDataCacheOP
MorphingScaffoldProvider::get_data_cache_slow(TreeIndex i) {
return get_scaffold( i )->cache_data_;
}
ParametricSceneConformationCOP
MorphingScaffoldProvider::get_scaffold(TreeIndex i) {
MorphMember & mmember = get_morph_member( i );
return mmember.conformation;
}
MorphMember &
MorphingScaffoldProvider::get_morph_member(TreeIndex i) {
runtime_assert( is_valid_index( i ) );
return map_[ i.depth ][ i.member ];
}
TreeLimits
MorphingScaffoldProvider::get_scaffold_index_limits() const {
TreeLimits limits(map_.size());
for ( uint64_t i = 0; i < map_.size(); i++ ) {
limits[i] = map_[i].size();
}
return limits;
}
void
MorphingScaffoldProvider::set_fa_mode( bool fa ) {
for ( uint64_t depth = 0; depth < map_.size(); depth++ ) {
for ( uint64_t i = 0; i < map_[depth].size(); i++) {
MorphMember & mmember = get_morph_member( TreeIndex(depth, i) );
ScaffoldDataCacheOP cache = mmember.conformation->cache_data_;
if ( cache->conformation_is_fa != fa ) {
mmember.conformation = make_conformation_from_data_cache(cache, fa);
}
}
}
}
void
MorphingScaffoldProvider::setup_twobody_tables( ::scheme::scaffold::TreeIndex i ) {
get_data_cache_slow( i )->setup_twobody_tables( rot_index_p, opt, make2bopts, rotrf_table_manager);
}
void
MorphingScaffoldProvider::setup_twobody_tables_per_thread( ::scheme::scaffold::TreeIndex i ) {
get_data_cache_slow( i )->setup_twobody_tables_per_thread( );
}
void
MorphingScaffoldProvider::modify_pose_for_output( ::scheme::scaffold::TreeIndex i, core::pose::Pose & pose ) {
MorphMember & mm = get_morph_member( i );
core::pose::PDBInfoOP pdb_info = pose.pdb_info();
for ( uint64_t i = 0; i < mm.morph_history.size(); i++) {
MorphRule const & rule = mm.morph_history[i];
core::Size low_add = rule.low_cut_site - 1;
core::Size high_add = rule.high_cut_site + 1;
for ( core::Size seq_pos = low_add; seq_pos <= high_add; seq_pos++ ) {
if ( ! pdb_info->res_haslabel(seq_pos, "FRAGMENT")) {
pdb_info->add_reslabel(seq_pos, "FRAGMENT");
}
pdb_info->add_reslabel(seq_pos, boost::str(boost::format("FRAGMENT%03ir")%i));
}
}
}
}}
| [
"bcov@uw.edu"
] | bcov@uw.edu |
c08592d08543c2f9c6731685f7b715f92c5062eb | affb96a0c74fdb70c99d48eff557c6c1951e8607 | /lib/flecs-components-physics/include/flecs_components_physics.h | 3feb7bef2ad72094be9811114cf5cb5873ccf96c | [
"MIT"
] | permissive | Cwc-game/tower_defense | 62db7fc6f1f70f290a8575e2a583a4e7e1bf6f79 | 0ff4f663401623f0650ec7567f0a26906f77c038 | refs/heads/master | 2023-01-03T08:15:48.462194 | 2020-10-29T14:00:03 | 2020-10-29T14:00:03 | 299,392,268 | 0 | 1 | null | 2020-09-28T18:06:58 | 2020-09-28T18:06:57 | null | UTF-8 | C++ | false | false | 2,544 | h | #ifndef FLECS_COMPONENTS_PHYSICS_H
#define FLECS_COMPONENTS_PHYSICS_H
#include <flecs-components-physics/bake_config.h>
#ifdef __cplusplus
//extern "C" {
#endif
ECS_STRUCT(EcsVelocity2, {
float x;
float y;
});
ECS_STRUCT(EcsVelocity3, {
float x;
float y;
float z;
});
ECS_STRUCT(EcsAngularSpeed, {
float value;
});
ECS_STRUCT(EcsAngularVelocity, {
float x;
float y;
float z;
});
ECS_STRUCT(EcsBounciness, {
float value;
});
ECS_STRUCT(EcsFriction, {
float value;
});
typedef struct FlecsComponentsPhysics {
ECS_DECLARE_ENTITY(EcsCollider);
ECS_DECLARE_ENTITY(EcsRigidBody);
ECS_DECLARE_COMPONENT(EcsVelocity2);
ECS_DECLARE_COMPONENT(EcsVelocity3);
ECS_DECLARE_COMPONENT(EcsAngularSpeed);
ECS_DECLARE_COMPONENT(EcsAngularVelocity);
ECS_DECLARE_COMPONENT(EcsBounciness);
ECS_DECLARE_COMPONENT(EcsFriction);
} FlecsComponentsPhysics;
#ifdef __cplusplus
extern "C" {
#endif
void FlecsComponentsPhysicsImport(
ecs_world_t *world);
#ifdef __cplusplus
}
#endif
#define FlecsComponentsPhysicsImportHandles(handles)\
ECS_IMPORT_ENTITY(handles, EcsCollider);\
ECS_IMPORT_ENTITY(handles, EcsRigidBody);\
ECS_IMPORT_COMPONENT(handles, EcsVelocity2);\
ECS_IMPORT_COMPONENT(handles, EcsVelocity3);\
ECS_IMPORT_COMPONENT(handles, EcsAngularSpeed);\
ECS_IMPORT_COMPONENT(handles, EcsAngularVelocity);\
ECS_IMPORT_COMPONENT(handles, EcsBounciness);\
ECS_IMPORT_COMPONENT(handles, EcsFriction);
#ifdef __cplusplus
//}
#endif
#ifdef __cplusplus
namespace flecs {
namespace components {
class physics : FlecsComponentsPhysics {
public:
using Velocity2 = EcsVelocity2;
using Velocity3 = EcsVelocity3;
using AngularSpeed = EcsAngularSpeed;
using AngularVelocity = EcsAngularVelocity;
using Bounciness = EcsBounciness;
using Friction = EcsFriction;
physics(flecs::world& ecs) {
FlecsComponentsPhysicsImport(ecs.c_ptr());
ecs.module<flecs::components::physics>();
ecs.pod_component<Velocity2>("flecs::components::physics::Velocity2");
ecs.pod_component<Velocity3>("flecs::components::physics::Velocity3");
ecs.pod_component<AngularSpeed>("flecs::components::physics::AngularSpeed");
ecs.pod_component<AngularVelocity>("flecs::components::physics::AngularVelocity");
ecs.pod_component<Bounciness>("flecs::components::physics::Bounciness");
ecs.pod_component<Friction>("flecs::components::physics::Friction");
}
};
}
}
#endif
#endif
| [
"maeiky@gmail.com"
] | maeiky@gmail.com |
3b786b6bfd010638ea9cc213cd223b8547d9d86a | 23933ebe3136c6c340a9b0840124ec87545f0148 | /a5-Widerstand/SourceCode/Widerstände.cpp | 47b12b47a89df95bea0ae0d0be89266ace34af0f | [] | no_license | sammy-f-s/bwinf-37-piedpiper | 07c33ce500076481a62a84253f8d512bc9023a79 | 965517217cd2c71ad50f587288a9c0376cb76a79 | refs/heads/master | 2020-04-08T23:52:23.307391 | 2018-11-30T15:52:32 | 2018-11-30T15:52:32 | 159,843,808 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,982 | cpp | // Widerstände.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include "stdafx.h"
#include "Resistor.h"
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <tuple>
//Rendern
#include "SFML\System.hpp"
#include "SFML\Graphics.hpp"
#include "SFML\Window.hpp"
using namespace std;
//Funktionsprototypen
void drawCircuit(vector <Resistor> &used, sf::Font &font);
tuple <float, Resistor> closestSerialAdd(vector <float> &resistors, float desired, float current);
tuple <float, Resistor> closestParallelAdd(vector <float> &resistors, float desired, float current);
float parAdd(float a, float b);
float currentResistorValue(vector <Resistor> &used);
void drawRect(int x, int y, int w, int h, sf::RenderWindow &window);
void drawText(string text, int x, int y, sf::RenderWindow &window, sf::Font &font);
void drawLine(int x1, int y1, int x2, int y2, sf::RenderWindow &window);
int main()
{
//Liste verfügbarer Widerstände
vector <float> availResistors;
//Liste der benutzten Widerstände
vector <Resistor> usedResistors;
//Laden einer Schriftart
sf::Font font;
font.loadFromFile("OpenSans.ttf");
//Auslesen der Widerstände
ifstream stream("widerstaende.txt");
string line;
if (stream.is_open())
{
while (std::getline(stream, line))
{
availResistors.push_back(stof(line));
}
}
//k?
int k;
cout << "Gewuenschtes k?";
cin >> k;
//gewünschter Widerstand?
float desiredRes;
cout << "\nGewuenschter Widerstand?";
cin >> desiredRes;
/* Beispiel aus der Aufgabe
usedResistors.emplace_back(1200, Serial);
usedResistors.emplace_back(3300, Parallel);
usedResistors.emplace_back(120, Serial);
usedResistors.emplace_back(1000, Parallel);
*/
for (int i = 0; i < k; i++)
{
float cRV = currentResistorValue(usedResistors);
float diff = abs(desiredRes - cRV);
//Übergabe Variablen
float val;
Resistor resistor_Serial;
Resistor resistor_Parallel;
//Serielle Annäherung
tie(val, resistor_Serial) = closestSerialAdd(availResistors, desiredRes, cRV);
float serialDiff = abs(val - desiredRes);
if (val == cRV) { serialDiff == 100000; } //wenn kein kleinerer wert gefunden wird, ist val = 0, wodurch das übernächste "if" nicht anschlägt (bedingt durch closestSerialAdd())
//Parallele Annäherung
tie(val, resistor_Parallel) = closestParallelAdd(availResistors, desiredRes, cRV);
float parallelDiff = abs(val - desiredRes);
if (val == cRV) { parallelDiff == 100000; }
if (diff < serialDiff && diff < parallelDiff)
{
//näher geht es nicht
break;
}
else
{
if (serialDiff <= parallelDiff)
{
usedResistors.push_back(resistor_Serial);
//Entfernen des benutzten Widerstands aus der Liste der verfügbaren
availResistors.erase(std::remove(availResistors.begin(), availResistors.end(), resistor_Serial.ohm), availResistors.end());
}
else
{
usedResistors.push_back(resistor_Parallel);
//Entfernen des benutzten Widerstands aus der Liste der verfügbaren
availResistors.erase(std::remove(availResistors.begin(), availResistors.end(), resistor_Parallel.ohm), availResistors.end());
}
}
}
drawCircuit(usedResistors, font);
return 0;
}
tuple<float, Resistor> closestSerialAdd(vector <float> &resistors, float desired, float current)
{
float recordDiff = abs(desired - current);
float recordResistorValue = 0.0;
//Ermitteln des Widerstands, welcher als Parallel-Addition mit der vorhandenen Schaltung, am nächsten am gewünschten Wert liegt
for (float f : resistors)
{
float newDiff = abs(desired - (current + f));
if (newDiff < recordDiff)
{
recordDiff = newDiff;
recordResistorValue = f;
}
}
//Zurückgeben des erreichten Wertes (welcher am nächsten am gesuchten liegt), sowie dem dazugehörigen Widerstand als Tupel
return tuple<float, Resistor>(current + recordResistorValue, Resistor(recordResistorValue, Serial));
}
tuple<float, Resistor> closestParallelAdd(vector <float> &resistors, float desired, float current)
{
float recordDiff = abs(desired - current);
float recordResistorValue = 0.0;
//Ermitteln des Widerstands, welcher als Parallel-Addition mit der vorhandenen Schaltung, am nächsten am gewünschten Wert liegt
for (float f : resistors)
{
float newDiff = abs(desired - parAdd(current, f));
if (newDiff < recordDiff)
{
recordDiff = newDiff;
recordResistorValue = f;
}
}
//Zurückgeben des erreichten Wertes (welcher am nächsten am gesuchten liegt), sowie dem dazugehörigen Widerstand als Tupel
return tuple<float, Resistor>(parAdd(current, recordResistorValue), Resistor(recordResistorValue, Parallel));
}
float parAdd(float a, float b)
{
return (1 / ((1 / a) + (1 / b)));
}
float currentResistorValue(vector <Resistor> &used)
{
float sum = 0;
for (int i = 0; i < used.size(); i++)
{
if (used[i].wtype == Serial)
{
sum += used[i].ohm;
}
else if (used[i].wtype == Parallel)
{
sum = parAdd(sum, used[i].ohm);
}
}
return sum;
}
void drawCircuit(vector <Resistor> &used, sf::Font &font)
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Aufgabe 5");
//Hilfsvariablen zum Rendern
int parallelen = 1;
int len = 10;
int ylen = 100;
sf::Vector2i start = sf::Vector2i(50, 100);
sf::Vector2i end = sf::Vector2i(50, 100);
while (window.isOpen())
{
sf::Event event;
if (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
}
window.clear();
drawLine(0, 100, 50, 100, window);
for (Resistor r : used)
{
if (r.wtype == Serial && r.ohm != 0)
{
drawLine(end.x, end.y, end.x + len, end.y, window);
drawRect(end.x + len, end.y - 20, 100, 40, window);
drawText(to_string((int)r.ohm), end.x + len + 2.5, end.y, window, font);
drawLine(end.x + 100 + len, end.y, end.x + 100 + len + len + 10 * parallelen, end.y, window);
end.x += 100 + len + len;
}
else if (r.wtype == Parallel && r.ohm != 0)
{
drawLine(start.x - 10 * parallelen, start.y, start.x - 10 * parallelen, start.y + ylen * parallelen, window);
drawLine(start.x - 10 * parallelen, start.y + ylen * parallelen, start.x + len - 10 * parallelen, start.y + ylen * parallelen, window);
drawRect(start.x + len - 10 * parallelen, start.y + ylen * parallelen - 20, 100, 40, window);
drawText(to_string((int)r.ohm), start.x + len + 2.5 - 10 * parallelen, start.y + ylen * parallelen, window, font);
drawLine(start.x + len + 100 - 10 * parallelen, start.y + ylen * parallelen, end.x + 10 * parallelen, end.y + ylen * parallelen, window);
drawLine(end.x + 10 * parallelen, end.y + ylen * parallelen, end.x + 10 * parallelen, end.y, window);
end.x += 10;
parallelen++;
}
}
drawLine(end.x, end.y, end.x + 50, end.y, window);
drawText("Gesamtwiderstand = " + to_string(currentResistorValue(used)), 0, 0, window, font);
//Rendervariablen zurücksetzen für nächsten Frame
parallelen = 1;
start = sf::Vector2i(50, 100);
end = sf::Vector2i(50, 100);
window.display();
}
}
void drawRect(int x, int y, int w, int h, sf::RenderWindow &window)
{
sf::RectangleShape r;
r.setOutlineColor(sf::Color::White);
r.setOutlineThickness(1);
r.setFillColor(sf::Color::Transparent);
r.setPosition(x, y);
r.setSize(sf::Vector2f(w, h));
window.draw(r);
}
void drawText(string text, int x, int y, sf::RenderWindow &window, sf::Font &font)
{
sf::Text t;
t.setPosition(x, y);
t.setFont(font);
t.setString(text);
t.setCharacterSize(15);
window.draw(t);
}
void drawLine(int x1, int y1, int x2, int y2, sf::RenderWindow &window)
{
sf::VertexArray line(sf::Lines, 2);
line[0] = sf::Vector2f(x1, y1);
line[1] = sf::Vector2f(x2, y2);
window.draw(line);
} | [
"jerritglaesker@gmail.com"
] | jerritglaesker@gmail.com |
93e2ae30a6326e5472cd7dfc8b0fd98dc93585c6 | f13454466609ac7e7061f7891b735c6c0b2c1c5a | /week_3/assignment_4/linked_list.cpp | a3221ae68a9c38adfd77acf47147b52fa2ac47f8 | [] | no_license | bf-eds/cpp_red | 178c17638950b21ff911ede4d25c2e0272c17cb3 | 00b655f72ab62416d755a2a528a3bc47a7d6e35c | refs/heads/master | 2020-04-07T13:02:31.732414 | 2019-07-18T18:13:11 | 2019-07-18T18:13:11 | 158,390,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,412 | cpp | //
// Created by human on 06.01.2019.
//
#include "test_runner.h"
#include <vector>
using namespace std;
template<typename T>
class LinkedList
{
public:
struct Node
{
T value;
Node *next = nullptr;
};
~LinkedList()
{
while (head)
{
PopFront();
}
}
void PushFront(const T &value)
{
auto node = new Node{value};
node->next = head;
head = node;
}
void InsertAfter(Node *node, const T &value)
{
if (node == nullptr)
{
PushFront(value);
}
else
{
auto new_node = new Node{value};
new_node->next = node->next;
node->next = new_node;
}
}
void RemoveAfter(Node *node)
{
if (node == nullptr)
{
PopFront();
}
else if (node->next != nullptr)
{
auto remove_node = node->next;
node->next = node->next->next;
delete remove_node;
}
}
void PopFront()
{
if (head != nullptr)
{
auto remove_node = head;
head = head->next;
delete remove_node;
}
}
Node *GetHead()
{
return head;
}
const Node *GetHead() const
{
return head;
}
private:
Node *head = nullptr;
};
template<typename T>
vector<T> ToVector(const LinkedList<T> &list)
{
vector<T> result;
for (auto node = list.GetHead(); node; node = node->next)
{
result.push_back(node->value);
}
return result;
}
void TestPushFront()
{
LinkedList<int> list;
list.PushFront(1);
ASSERT_EQUAL(list.GetHead()->value, 1);
list.PushFront(2);
ASSERT_EQUAL(list.GetHead()->value, 2);
list.PushFront(3);
ASSERT_EQUAL(list.GetHead()->value, 3);
const vector<int> expected = {3, 2, 1};
ASSERT_EQUAL(ToVector(list), expected);
}
void TestInsertAfter()
{
LinkedList<string> list;
list.PushFront("a");
auto head = list.GetHead();
ASSERT(head);
ASSERT_EQUAL(head->value, "a");
list.InsertAfter(head, "b");
const vector<string> expected1 = {"a", "b"};
ASSERT_EQUAL(ToVector(list), expected1);
list.InsertAfter(head, "c");
const vector<string> expected2 = {"a", "c", "b"};
ASSERT_EQUAL(ToVector(list), expected2);
}
void TestRemoveAfter()
{
LinkedList<int> list;
for (int i = 1; i <= 5; ++i)
{
list.PushFront(i);
}
const vector<int> expected = {5, 4, 3, 2, 1};
ASSERT_EQUAL(ToVector(list), expected);
auto next_to_head = list.GetHead()->next;
list.RemoveAfter(next_to_head); // удаляем 3
list.RemoveAfter(next_to_head); // удаляем 2
const vector<int> expected1 = {5, 4, 1};
ASSERT_EQUAL(ToVector(list), expected1);
while (list.GetHead()->next)
{
list.RemoveAfter(list.GetHead());
}
ASSERT_EQUAL(list.GetHead()->value, 5);
}
void TestPopFront()
{
LinkedList<int> list;
for (int i = 1; i <= 5; ++i)
{
list.PushFront(i);
}
for (int i = 1; i <= 5; ++i)
{
list.PopFront();
}
ASSERT(list.GetHead() == nullptr);
}
int main()
{
TestRunner tr;
RUN_TEST(tr, TestPushFront);
RUN_TEST(tr, TestInsertAfter);
RUN_TEST(tr, TestRemoveAfter);
RUN_TEST(tr, TestPopFront);
return 0;
} | [
"d.eroshenkov@dreamkas.ru"
] | d.eroshenkov@dreamkas.ru |
ec9fdd59e40ea079514ff84e14ed31888a727e30 | d2249116413e870d8bf6cd133ae135bc52021208 | /TY3DCtrl/test/mapdemoDlg.h | 0f546a652419607d42ed17393f031b52900e55c0 | [] | no_license | Unknow-man/mfc-4 | ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5 | b58abf9eb4c6d90ef01b9f1203b174471293dfba | refs/heads/master | 2023-02-17T18:22:09.276673 | 2021-01-20T07:46:14 | 2021-01-20T07:46:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | h |
#pragma once
#include "afxwin.h"
#include "mxcom.h"
class CMapDemoDlg : public CDialog
{
// Construction
public:
CMapDemoDlg(CWnd* pParent = NULL); // standard constructor
~CMapDemoDlg();
// Dialog Data
enum { IDD = IDD_MAPDEMO_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
public:
// Implementation
protected:
HICON m_hIcon;
BOOL PreTranslateMessage(MSG* pMsg);
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClose();
DECLARE_MESSAGE_MAP()
protected:
CMxScene mScene;
CMxTree mProjTree;
void OnDestroy();
ISceneCtrlPtr mScenePtr;
IProjectTreeCtrlPtr mTreePtr;
DECLARE_EVENTSINK_MAP()
};
| [
"chenchao0632@163.com"
] | chenchao0632@163.com |
d9d23fedae4412a31fe91a6062acdacbbc11690b | af9c370c8d0f5f0ba8e5c13eb099bf5a56dc87ab | /student/06/vertical/main.cpp | a945848e86e5445a3367d230390610f0fc15e0fb | [] | no_license | shamsch/programming2coursework | 1d379f093cbc78df5a381d5e12b7364d5b340e83 | 24cdd5f1ac41454b8eff575ad9b6082cc201501d | refs/heads/master | 2023-05-28T09:57:27.816975 | 2021-05-06T19:15:04 | 2021-05-06T19:15:04 | 376,154,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cpp | #include <iostream>
#ifndef RECURSIVE_FUNC
#define RECURSIVE_FUNC
#endif
using namespace std;
void print_vertical(unsigned int num)
{
RECURSIVE_FUNC
// Do not remove RECURSIVE_FUNC declaration, it's necessary for automatic testing to work
// ------------
// Add your implementation here
if (num > 10){
print_vertical(num / 10);
}
cout << num % 10 << endl;
}
// Do not modify rest of the code, or the automated testing won't work.
#ifndef UNIT_TESTING
int main()
{
unsigned int number = 0;
cout << "Enter a number: ";
cin >> number;
cout << "The given number (" << number << ") written vertically:" << endl;
print_vertical(number);
return 0;
}
#endif
| [
"shamsurraza.chowdhury@tuni.fi"
] | shamsurraza.chowdhury@tuni.fi |
93ee728aea9463dabecf43e128c5aef29d1bedad | b314f6bc92f753241786b58deb28068f24816164 | /TiAALS/ExternalObjects/IRVideoAnnotater2/VideoAnnotater/VideoAnnotaterView/VideoAnnotaterWindowController/VideoAnnotaterWindowController.cpp | 1bd1b26c5ae8d504c47d5946d3494b843e0df215 | [] | no_license | KeitaroTakahashi/TIAALS_KeitaroVer | 5de5be3959b93855cd3fca5e83ece623d3d014e8 | 1ff7920ab7f1cabe25155716a4990aea3d9dfd21 | refs/heads/main | 2023-04-12T18:24:35.997946 | 2021-04-13T10:46:21 | 2021-04-13T10:46:21 | 357,516,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,614 | cpp | //
// VideoAnnotaterWindowController.cpp
// TIAALS_LIGHT - App
//
// Created by Keitaro on 24/03/2021.
//
#include "VideoAnnotaterWindowController.hpp"
VideoAnnotaterWindowController::VideoAnnotaterWindowController(IRStr* str) : IRObjectController("Video Annotater",str)
{
this->videoAnnotaterController.reset( new VideoAnnotaterWindowControllerUI(str) );
addAndMakeVisible(this->videoAnnotaterController.get());
this->videoAnnotaterController->addChangeListener(this);
// create arrange controller
//createAndAddArrangeController();
}
VideoAnnotaterWindowController::~VideoAnnotaterWindowController()
{
this->videoAnnotaterController.reset();
}
void VideoAnnotaterWindowController::ControllerResized()
{
//std::cout << "ControllerResized\n";
int y = 10;
int yIncrement = 30;
int yBigIncrement = 40;
y += yBigIncrement;
y += yIncrement;
this->videoAnnotaterController->setBounds(0, y, getWidth(), getHeight() - y);
}
void VideoAnnotaterWindowController::paint(Graphics& g)
{
g.fillAll(getStr()->SYSTEMCOLOUR.contents);
g.setColour(Colours::black);
g.drawLine(0,42.5,getWidth(),42.5);
//g.drawLine(0,250, getWidth(), 250);
//g.drawLine(0,400,getWidth(),400);
}
void VideoAnnotaterWindowController::controllerChangeListenerCallback (ChangeBroadcaster* source)
{
if(source == this->videoAnnotaterController.get())
{
using s = VideoAnnotaterWindowControllerUI::VideoAnnotaterWindowControllerUIStatus;
switch(this->videoAnnotaterController->getStatus())
{
case s::openVideoFile:
callVideoFileCallback();
break;
case s::videoSizePercent:
callVideoSizePercentCallback();
default:
break;
}
}
}
void VideoAnnotaterWindowController::mainControllerSelected()
{
this->videoAnnotaterController->setVisible(true);
setArrangeControllerVisible(false);
}
void VideoAnnotaterWindowController::arrangeControllerSelected()
{
//this->videoAnnotaterController->setVisible(false);
//setArrangeControllerVisible(true);
}
void VideoAnnotaterWindowController::callVideoFileCallback()
{
if(this->openVideoFileCallback != nullptr)
{
this->openVideoFileCallback();
}
}
void VideoAnnotaterWindowController::callVideoSizePercentCallback()
{
std::cout << "callVideoSizePercentCallback\n";
if(this->videoSizePercentCallback != nullptr)
this->videoSizePercentCallback(this->videoAnnotaterController->getVideoSizePercent());
}
| [
"neoterize@mac.com"
] | neoterize@mac.com |
476ce0e845511aa9c998c5a1a536cb52e9a10151 | 3391892861a1e1e71af6e414bcdb9fc0df66c62e | /src/jk/cog/vm/timer_record.hpp | 6e672c7799c5f76e86d9a25b0df58094f2524688 | [
"Apache-2.0"
] | permissive | jdmclark/gorc | a21208b1d03a85fc5a99fdd51fdad27446cc4767 | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | refs/heads/develop | 2021-01-21T05:01:26.609783 | 2020-12-21T00:26:22 | 2020-12-21T02:34:31 | 10,290,074 | 103 | 10 | Apache-2.0 | 2020-12-21T02:34:33 | 2013-05-25T21:27:37 | C++ | UTF-8 | C++ | false | false | 644 | hpp | #pragma once
#include "io/binary_input_stream.hpp"
#include "io/binary_output_stream.hpp"
#include "jk/cog/script/value.hpp"
namespace gorc {
namespace cog {
class timer_record {
public:
time_delta duration;
time_delta remaining;
value param0;
value param1;
timer_record(time_delta const &duration,
value param0,
value param1);
timer_record(deserialization_constructor_tag, binary_input_stream &bis);
void binary_serialize_object(binary_output_stream &bos) const;
};
}
}
| [
"jon@nullptr.ca"
] | jon@nullptr.ca |
53f2d3aff509da7c78db1abbf779d8f0cacf2bd7 | 30c0974df70d24e485dfed1afab9f8db135ff019 | /projects/libhttp/src/demohttprequesthandler.cpp | ede74773514cdae12ff2d83351b245d8a1f9b748 | [
"Apache-2.0"
] | permissive | leckel2014/CoreLooper | 48cc7ae970fe9c46400b1eb9747dfc0d90c62219 | 5afd067488bd81105297eb84016949d539b67ea9 | refs/heads/master | 2020-05-25T19:04:26.976075 | 2019-03-05T12:25:29 | 2019-03-05T12:25:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,759 | cpp | #include "stdafx.h"
#include "demohttprequesthandler.h"
#include "net/channel.h"
#include "looper/loop.h"
#include "httptool.h"
using namespace Bear::Core::Net;
namespace Bear {
namespace Core {
namespace Net {
namespace Http {
DemoHttpRequestHandler::DemoHttpRequestHandler()
{
SetObjectName("DemoHttpRequestHandler");
DW("%s,this=0x%08x", __func__, this);
mDumpFile.Open(ShellTool::GetAppPath() + "/http.recv.bin");
}
DemoHttpRequestHandler::~DemoHttpRequestHandler()
{
DW("%s,this=0x%08x", __func__, this);
}
LRESULT DemoHttpRequestHandler::OnMessage(UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case BM_DESTROY:
{
if (mChannel)
{
mChannel->Destroy();
mChannel = nullptr;
}
break;
}
}
auto ret = __super::OnMessage(msg, wp, lp);
return ret;
}
void DemoHttpRequestHandler::OnClose(Channel*)
{
DW("%s", __func__);
if (mChannel)
{
mChannel->Destroy();
mChannel = nullptr;
}
Destroy();
}
void DemoHttpRequestHandler::OnSend(Channel*)
{
int x = 0;
}
void DemoHttpRequestHandler::OnConnect(Channel *endPoint, long error, ByteBuffer *pBox, Bundle* extraInfo)
{
if (error)
{
DW("%s,connect fail", __func__);
Destroy();
if (mChannel)
{
mChannel->Destroy();
mChannel = nullptr;
}
}
else
{
DV("%s,connect ok", __func__);
mInbox.PrepareBuf(4 * 1024);
mOutbox.PrepareBuf(4 * 1024);
srand(1);
SetTimer(mTimerCheckSend,1);
SendRequest();
}
}
void DemoHttpRequestHandler::OnReceive(Channel*)
{
/*
{
static int idx = -1;
++idx;
DV("%s,idx=%04d", __func__, idx);
}
//*/
while (mChannel)
{
mInbox.MoveToHead();
int bytes = mInbox.GetTailFreeSize();
if (bytes <= 1)
{
break;
}
int ret = mChannel->Receive(mInbox.GetNewDataPointer(), bytes - 1);
if (ret <= 0)
{
break;
}
mInbox.WriteDirect(ret);
mInbox.MakeSureEndWithNull();
ParseInbox();
}
}
//解析出inbox中所有的http ack,可能含多个ack
void DemoHttpRequestHandler::ParseInbox()
{
ASSERT(mInbox.IsEndWithNull());
while (!mInbox.IsEmpty())
{
switch (mHttpAckInfo.mHttpAckStatus)
{
case eHttpAckStatus_WaitHeader:
{
const char *ps = (const char*)mInbox.GetDataPointer();
const char *key = "\r\n\r\n";
const char *pEnd = strstr(ps, key);
if (!pEnd)
{
return;
}
string header(ps, pEnd - ps);
{
static int idx = -1;
DV("S=>C [%04d] %s", ++idx, header.c_str());
}
mHttpAckInfo.mContentLength = HttpTool::GetInt(header, "Content-Length");
if (mHttpAckInfo.mContentLength > 0)
{
SwitchStatus(eHttpAckStatus_ReceivingBody);
}
else
{
SwitchStatus(eHttpAckStatus_Done);
}
int eat = (int)(pEnd + strlen(key) - ps);
mInbox.Eat(eat);
break;
}
case eHttpAckStatus_ReceivingBody:
{
ASSERT(mHttpAckInfo.mContentRecvBytes <= mHttpAckInfo.mContentLength);
int maxEatBytes = mHttpAckInfo.mContentLength - mHttpAckInfo.mContentRecvBytes;
int bytes = mInbox.GetActualDataLength();
int len = MIN(maxEatBytes, bytes);
mHttpAckInfo.mContentRecvBytes += len;
OnRecvHttpAckBody(mInbox.GetDataPointer(), len);
mInbox.Eat(len);
mInbox.MoveToHead();
if (mHttpAckInfo.mContentRecvBytes == mHttpAckInfo.mContentLength)
{
mHttpAckInfo.Reset();
}
break;
}
case eHttpAckStatus_Done:
{
break;
}
default:
{
ASSERT(FALSE);
break;
}
}
}
}
void DemoHttpRequestHandler::OnRecvHttpAckBody(LPVOID data, int dataLen)
{
mDumpFile.Write(data, dataLen);
}
void DemoHttpRequestHandler::SwitchStatus(DemoHttpRequestHandler::eHttpAckStatus status)
{
mHttpAckInfo.mHttpAckStatus = status;
switch (status)
{
case eHttpAckStatus_Done:
{
mHttpAckInfo.Reset();
break;
}
}
}
void DemoHttpRequestHandler::SendRequest()
{
if (!mChannel)
{
return;
}
ASSERT(mOutbox.IsEmpty());
for (int i = 0; i < 10; i++)
{
string req = StringTool::Format(
"GET /UploadSensorData?id=00002XYZ&reqIndex=%d&temperature=30&humidity=57&windSpeed=0&windDirection=10&audioDB=35.0&ioInput=0&ioOutput=0&ioOutput=1&configVersion=2 HTTP/1.1\r\n"
"\r\n"
, mReqIndex++
);
{
static int idx = -1;
++idx;
DV("C=>S [%04d] %s", idx, req.c_str());
int len = (int)req.length();
mOutbox.Write((LPVOID)req.c_str(), len);
}
}
}
void DemoHttpRequestHandler::OnTimer(long timerId)
{
if(timerId == mTimerCheckSend)
{
if (!mChannel)
{
return;
}
if (mOutbox.IsEmpty())
{
SendRequest();
}
else
{
LPBYTE data = mOutbox.GetDataPointer();
int bytes = MIN(1, mOutbox.GetActualDataLength());
int ret = mChannel->Send(data, bytes);
if (ret > 0)
{
mOutbox.Eat(ret);
}
//DV("%s", __func__);
//int ms = rand() % 100;
//ShellTool::Sleep(ms);
}
return;
}
__super::OnTimer(timerId);
}
}
}
}
} | [
"xwpcom@163.com"
] | xwpcom@163.com |
0a53241f98ee72e245e4d51a665d2b5affdecb9c | 67fdcec788781899da48ca88b5e7b7e5ef9af2b3 | /SD/hw22/StarTrekDVD.cpp | bd4a5aa43871f8fd95d79414148cf2a211c1a7d4 | [] | no_license | lucasheilman/college | 3e920b8aacc4c7f89230e1bd1a8a01cf76de70e1 | eaa699a0d6a3dff682c1f59d53ffa19377f1fc1b | refs/heads/master | 2020-03-21T14:30:20.073255 | 2018-06-25T23:38:14 | 2018-06-25T23:38:14 | 138,660,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | cpp | #include <iostream>
using namespace std;
#include "StarTrekDVD.h"
#include "DVD.h"
StarTrekDVD::StarTrekDVD(int i, const char *t, const char *dir,int n,const char *cap): DVD::DVD(i,t,dir){
episode = n;
captain = makecopy(cap);
}
StarTrekDVD::StarTrekDVD(): DVD::DVD(){
episode = -1;
captain = makecopy("");
}
StarTrekDVD::StarTrekDVD(const StarTrekDVD &d): DVD::DVD(d){
episode = d.episode;
captain = makecopy(d.captain);
}
StarTrekDVD::~StarTrekDVD(){
delete [] captain;
}
int StarTrekDVD::getEpisode(){
return episode;
}
char * StarTrekDVD::getCaptain(){
return captain;
}
void StarTrekDVD::setEpisode(int i){
episode = i;
}
void StarTrekDVD::setCaptain(const char *t){
captain = makecopy(t);
}
void StarTrekDVD::display(){
cout << '[' << id << ". ST" << episode << ": " << title << '/' << director << '/' << captain << ']';
}
char *StarTrekDVD::makecopy(const char *str){
int len;
char * newstr;
for(len = 0; str[len] != '\0'; len++){}
newstr = new char[len+1];
for(int a = 0; a < len+1; a++){
newstr[a] = str[a];
}
return newstr;
}
StarTrekDVD& StarTrekDVD::operator= (const StarTrekDVD &dvd){
DVD::operator=(dvd);
episode = dvd.episode;
captain = makecopy(dvd.captain);
return *this;
}
| [
"heilma1@stolaf.edu"
] | heilma1@stolaf.edu |
206428b6905dd5682d2ad47294594299ae4c2b36 | a0dccd84ac643dc87a09256c79766492d9d072da | /GalaxySpaceShooter/Classes/models/enemy/EnemyManagement.h | e702592aeaad846768c4691f4a34c0b135888e3a | [] | no_license | a3845021/Galaxy-Space-Shooter-Cocos2d-x | 0adc2b76669190611276d93cd33b51ade0591d39 | 71e21bf6d7c71ef5f6e45223e2f26fe1303c785b | refs/heads/master | 2020-04-26T15:59:45.750260 | 2019-02-22T08:59:37 | 2019-02-22T08:59:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 653 | h | #pragma once
#include <vector>
#include "Enemy.h"
#include "cocos2d.h"
class EnemyManagement
{
private:
// Keep track of the scene level index for releasing enemies
int mSceneLevelIndex;
// The enemies controller
std::vector<Enemy*> mVectorOfEnemies;
// Keep track of the frame count for shooting
int mReleasingFrameCount;
void ReleaseAnEnemy(const cocos2d::Vec2& aircraftCurrentPosition) const;
public:
EnemyManagement(cocos2d::Scene* scene, const int& sceneLevelIndex);
void Update(const cocos2d::Vec2& aircraftPosition);
std::vector<Enemy*> GetAVectorOfEnemies() const;
std::vector<Enemy*> GetAVectorOfActiveEnemies() const;
};
| [
"tweakkit200497@gmail.com"
] | tweakkit200497@gmail.com |
ba546dd6404a4bbe343219151ee260d467bb0dbe | b9264aa2552272b19ca393ba818f9dcb8d91da10 | /hashmap/lib/seqan3/submodules/sdsl-lite/include/sdsl/wt_pc.hpp | 63b24b8814b57768861e9a4ef52bc98e7425e4b9 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"CC-BY-4.0",
"MIT"
] | permissive | eaasna/low-memory-prefilter | c29b3aeb76f70afc4f26da3d9f063b0bc2e251e0 | efa20dc8a95ce688d2a9d08773d120dff4cccbb6 | refs/heads/master | 2023-07-04T16:45:05.817237 | 2021-08-12T12:01:11 | 2021-08-12T12:01:11 | 383,427,746 | 0 | 0 | BSD-3-Clause | 2021-07-06T13:24:31 | 2021-07-06T10:22:54 | C++ | UTF-8 | C++ | false | false | 28,511 | hpp | // Copyright (c) 2016, the SDSL Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
/*! \file wt_pc.hpp
\brief wt_pc.hpp contains a class for the wavelet tree of byte sequences.
The wavelet tree shape is parametrized by a prefix code.
\author Simon Gog, Timo Beller
*/
#ifndef INCLUDED_SDSL_WT_PC
#define INCLUDED_SDSL_WT_PC
#include "bit_vectors.hpp"
#include "rank_support.hpp"
#include "select_support.hpp"
#include "wt_helper.hpp"
#include <vector>
#include <utility>
#include <tuple>
//! Namespace for the succinct data structure library.
namespace sdsl {
//! A prefix code-shaped wavelet.
/*!
* \tparam t_shape Shape of the tree ().
* \tparam t_bitvector Underlying bitvector structure.
* \tparam t_rank Rank support for pattern `1` on the bitvector.
* \tparam t_select Select support for pattern `1` on the bitvector.
* \tparam t_select_zero Select support for pattern `0` on the bitvector.
* \tparam t_tree_strat Tree strategy determines alphabet and the tree
* class used to navigate the WT.
*
* @ingroup wt
*/
template <class t_shape,
class t_bitvector = bit_vector,
class t_rank = typename t_bitvector::rank_1_type,
class t_select = typename t_bitvector::select_1_type,
class t_select_zero = typename t_bitvector::select_0_type,
class t_tree_strat = byte_tree<>>
class wt_pc {
public:
typedef typename t_tree_strat::template type<wt_pc> tree_strat_type;
typedef int_vector<>::size_type size_type;
typedef typename tree_strat_type::value_type value_type;
typedef typename t_bitvector::difference_type difference_type;
typedef random_access_const_iterator<wt_pc> const_iterator;
typedef const_iterator iterator;
typedef t_bitvector bit_vector_type;
typedef t_rank rank_1_type;
typedef t_select select_1_type;
typedef t_select_zero select_0_type;
typedef wt_tag index_category;
typedef typename tree_strat_type::alphabet_category alphabet_category;
typedef typename t_shape::template type<wt_pc> shape_type;
enum { lex_ordered = shape_type::lex_ordered };
using node_type = typename tree_strat_type::node_type;
private:
#ifdef WT_PC_CACHE
mutable value_type m_last_access_answer;
mutable size_type m_last_access_i;
mutable size_type m_last_access_rl;
#endif
size_type m_size = 0; // original text size
size_type m_sigma = 0; // alphabet size
bit_vector_type m_bv; // bit vector to store the wavelet tree
rank_1_type m_bv_rank; // rank support for the wavelet tree bit vector
select_1_type m_bv_select1; // select support for the wavelet tree bit vector
select_0_type m_bv_select0;
tree_strat_type m_tree;
// insert a character into the wavelet tree, see construct method
void insert_char(value_type old_chr,
std::vector<uint64_t>& bv_node_pos,
size_type times,
bit_vector& bv)
{
uint64_t p = m_tree.bit_path(old_chr);
uint32_t path_len = p >> 56;
node_type v = m_tree.root();
for (uint32_t l = 0; l < path_len; ++l, p >>= 1) {
if (p & 1) {
bv.set_int(bv_node_pos[v], 0xFFFFFFFFFFFFFFFFULL, times);
}
bv_node_pos[v] += times;
v = m_tree.child(v, p & 1);
}
}
// calculates the tree shape returns the size of the WT bit vector
size_type construct_tree_shape(const std::vector<size_type>& C)
{
// vector for node of the tree
std::vector<pc_node> temp_nodes; //(2*m_sigma-1);
shape_type::construct_tree(C, temp_nodes);
// Convert code tree into BFS order in memory and
// calculate bv_pos values
size_type bv_size = 0;
m_tree = tree_strat_type(temp_nodes, bv_size, this);
return bv_size;
}
void construct_init_rank_select()
{
util::init_support(m_bv_rank, &m_bv);
util::init_support(m_bv_select0, &m_bv);
util::init_support(m_bv_select1, &m_bv);
}
// recursive internal version of the method interval_symbols
void _interval_symbols(size_type i,
size_type j,
size_type& k,
std::vector<value_type>& cs,
std::vector<size_type>& rank_c_i,
std::vector<size_type>& rank_c_j,
node_type v) const
{
// invariant: j>i
size_type i_new = (m_bv_rank(m_tree.bv_pos(v) + i) - m_tree.bv_pos_rank(v));
size_type j_new = (m_bv_rank(m_tree.bv_pos(v) + j) - m_tree.bv_pos_rank(v));
// goto left child
i -= i_new;
j -= j_new;
if (i != j) {
node_type v_new = m_tree.child(v, 0);
if (!m_tree.is_leaf(v_new)) {
_interval_symbols(i, j, k, cs, rank_c_i, rank_c_j, v_new);
} else {
rank_c_i[k] = i;
rank_c_j[k] = j;
cs[k++] = m_tree.bv_pos_rank(v_new);
}
}
// goto right child
if (i_new != j_new) {
node_type v_new = m_tree.child(v, 1);
if (!m_tree.is_leaf(v_new)) {
_interval_symbols(i_new, j_new, k, cs, rank_c_i, rank_c_j, v_new);
} else {
rank_c_i[k] = i_new;
rank_c_j[k] = j_new;
cs[k++] = m_tree.bv_pos_rank(v_new);
}
}
}
public:
const size_type& sigma = m_sigma;
const bit_vector_type& bv = m_bv;
// Default constructor
wt_pc(){};
//! Construct the wavelet tree from a sequence defined by two interators
/*!
* \param begin Iterator to the start of the input.
* \param end Iterator one past the end of the input.
* \par Time complexity
* \f$ \Order{n\log|\Sigma|}\f$, where \f$n=size\f$
*/
template <typename t_it>
wt_pc(t_it begin, t_it end) : m_size(std::distance(begin, end))
{
if (0 == m_size) return;
// O(n + |\Sigma|\log|\Sigma|) algorithm for calculating node sizes
// TODO: C should also depend on the tree_strategy. C is just a mapping
// from a symbol to its frequency. So a map<uint64_t,uint64_t> could be
// used for integer alphabets...
std::vector<size_type> C;
// 1. Count occurrences of characters
calculate_character_occurences(begin, end, C);
// 2. Calculate effective alphabet size
calculate_effective_alphabet_size(C, m_sigma);
// 3. Generate tree shape
size_type tree_size = construct_tree_shape(C);
// 4. Generate wavelet tree bit sequence m_bv
bit_vector temp_bv(tree_size, 0);
// Initializing starting position of wavelet tree nodes
std::vector<uint64_t> bv_node_pos(m_tree.size(), 0);
for (size_type v = 0; v < m_tree.size(); ++v) {
bv_node_pos[v] = m_tree.bv_pos(v);
}
value_type old_chr = *begin;
uint32_t times = 0;
for (auto it = begin; it != end; ++it) {
value_type chr = *it;
if (chr != old_chr) {
insert_char(old_chr, bv_node_pos, times, temp_bv);
times = 1;
old_chr = chr;
} else { // chr == old_chr
++times;
if (times == 64) {
insert_char(old_chr, bv_node_pos, times, temp_bv);
times = 0;
}
}
}
if (times > 0) {
insert_char(old_chr, bv_node_pos, times, temp_bv);
}
m_bv = bit_vector_type(std::move(temp_bv));
// 5. Initialize rank and select data structures for m_bv
construct_init_rank_select();
// 6. Finish inner nodes by precalculating the bv_pos_rank values
m_tree.init_node_ranks(m_bv_rank);
}
template <typename t_it>
wt_pc(t_it begin, t_it end, std::string) : wt_pc(begin, end)
{
}
//! Copy constructor
wt_pc(const wt_pc& wt)
: m_size(wt.m_size)
, m_sigma(wt.m_sigma)
, m_bv(wt.m_bv)
, m_bv_rank(wt.m_bv_rank)
, m_bv_select1(wt.m_bv_select1)
, m_bv_select0(wt.m_bv_select0)
, m_tree(wt.m_tree)
{
m_bv_rank.set_vector(&m_bv);
m_bv_select1.set_vector(&m_bv);
m_bv_select0.set_vector(&m_bv);
}
wt_pc(wt_pc&& wt)
: m_size(wt.m_size)
, m_sigma(wt.m_sigma)
, m_bv(std::move(wt.m_bv))
, m_bv_rank(std::move(wt.m_bv_rank))
, m_bv_select1(std::move(wt.m_bv_select1))
, m_bv_select0(std::move(wt.m_bv_select0))
, m_tree(std::move(wt.m_tree))
{
m_bv_rank.set_vector(&m_bv);
m_bv_select1.set_vector(&m_bv);
m_bv_select0.set_vector(&m_bv);
}
//! Assignment operator
wt_pc& operator=(const wt_pc& wt)
{
if (this != &wt) {
wt_pc tmp(wt); // re-use copy-constructor
*this = std::move(tmp); // re-use move-assignment
}
return *this;
}
//! Move assignment operator
wt_pc& operator=(wt_pc&& wt)
{
if (this != &wt) {
m_size = wt.m_size;
m_sigma = wt.m_sigma;
m_bv = std::move(wt.m_bv);
m_bv_rank = std::move(wt.m_bv_rank);
m_bv_rank.set_vector(&m_bv);
m_bv_select1 = std::move(wt.m_bv_select1);
m_bv_select1.set_vector(&m_bv);
m_bv_select0 = std::move(wt.m_bv_select0);
m_bv_select0.set_vector(&m_bv);
m_tree = std::move(wt.m_tree);
}
return *this;
}
//! Returns the size of the original vector.
size_type size() const { return m_size; }
//! Returns whether the wavelet tree contains no data.
bool empty() const { return m_size == 0; }
//! Recovers the i-th symbol of the original vector.
/*!
* \param i Index in the original vector.
* \return The i-th symbol of the original vector.
* \par Time complexity
* \f$ \Order{H_0} \f$ on average, where \f$ H_0 \f$ is the
* zero order entropy of the sequence
*
* \par Precondition
* \f$ i < size() \f$
*/
value_type operator[](size_type i) const
{
assert(i < size());
// which stores how many of the next symbols are equal
// with the current char
node_type v = m_tree.root(); // start at root node
while (!m_tree.is_leaf(v)) { // while not a leaf
if (m_bv[m_tree.bv_pos(v) + i]) { // goto right child
i = m_bv_rank(m_tree.bv_pos(v) + i) - m_tree.bv_pos_rank(v);
v = m_tree.child(v, 1);
} else { // goto the left child
i -= (m_bv_rank(m_tree.bv_pos(v) + i) - m_tree.bv_pos_rank(v));
v = m_tree.child(v, 0);
}
}
// if v is a leaf bv_pos_rank returns symbol itself
return m_tree.bv_pos_rank(v);
};
//! Calculates how many symbols c are in the prefix [0..i-1].
/*!
* \param i Exclusive right bound of the range.
* \param c Symbol c.
* \return Number of occurrences of symbol c in the prefix [0..i-1].
* \par Time complexity
* \f$ \Order{H_0} \f$ on average, where \f$ H_0 \f$ is the
* zero order entropy of the sequence
*
* \par Precondition
* \f$ i \leq size() \f$
*/
size_type rank(size_type i, value_type c) const
{
assert(i <= size());
if (!m_tree.is_valid(m_tree.c_to_leaf(c))) {
return 0; // if `c` was not in the text
}
if (m_sigma == 1) {
return i; // if m_sigma == 1 answer is trivial
}
uint64_t p = m_tree.bit_path(c);
uint32_t path_len = (p >> 56);
size_type result = i;
node_type v = m_tree.root();
for (uint32_t l = 0; l < path_len and result; ++l, p >>= 1) {
if (p & 1) {
result = (m_bv_rank(m_tree.bv_pos(v) + result) - m_tree.bv_pos_rank(v));
} else {
result -= (m_bv_rank(m_tree.bv_pos(v) + result) - m_tree.bv_pos_rank(v));
}
v = m_tree.child(v, p & 1); // goto child
}
return result;
};
//! Calculates how many times symbol wt[i] occurs in the prefix [0..i-1].
/*!
* \param i The index of the symbol.
* \return Pair (rank(wt[i],i),wt[i])
* \par Time complexity
* \f$ \Order{H_0} \f$
*
* \par Precondition
* \f$ i < size() \f$
*/
std::pair<size_type, value_type> inverse_select(size_type i) const
{
assert(i < size());
node_type v = m_tree.root();
while (!m_tree.is_leaf(v)) { // while not a leaf
if (m_bv[m_tree.bv_pos(v) + i]) { // goto right child
i = (m_bv_rank(m_tree.bv_pos(v) + i) - m_tree.bv_pos_rank(v));
v = m_tree.child(v, 1);
} else { // goto left child
i -= (m_bv_rank(m_tree.bv_pos(v) + i) - m_tree.bv_pos_rank(v));
v = m_tree.child(v, 0);
}
}
// if v is a leaf bv_pos_rank returns symbol itself
return std::make_pair(i, (value_type)m_tree.bv_pos_rank(v));
}
//! Calculates the ith occurrence of the symbol c in the supported vector.
/*!
* \param i The ith occurrence.
* \param c The symbol c.
* \par Time complexity
* \f$ \Order{H_0} \f$ on average, where \f$ H_0 \f$ is the zero order
* entropy of the sequence
*
* \par Precondition
* \f$ 1 \leq i \leq rank(size(), c) \f$
*/
size_type select(size_type i, value_type c) const
{
assert(1 <= i and i <= rank(size(), c));
node_type v = m_tree.c_to_leaf(c);
if (!m_tree.is_valid(v)) { // if c was not in the text
return m_size; // -> return a position right to the end
}
if (m_sigma == 1) {
return std::min(i - 1, m_size);
}
size_type result = i - 1; // otherwise
uint64_t p = m_tree.bit_path(c);
uint32_t path_len = (p >> 56);
// path_len > 0, since we have handled m_sigma = 1.
p <<= (64 - path_len);
for (uint32_t l = 0; l < path_len; ++l, p <<= 1) {
if ((p & 0x8000000000000000ULL) == 0) { // node was a left child
v = m_tree.parent(v);
result = m_bv_select0(m_tree.bv_pos(v) - m_tree.bv_pos_rank(v) + result + 1) -
m_tree.bv_pos(v);
} else { // node was a right child
v = m_tree.parent(v);
result = m_bv_select1(m_tree.bv_pos_rank(v) + result + 1) - m_tree.bv_pos(v);
}
}
return result;
};
//! For each symbol c in wt[i..j-1] get rank(i,c) and rank(j,c).
/*!
* \param i The start index (inclusive) of the interval.
* \param j The end index (exclusive) of the interval.
* \param k Reference for number of different symbols in [i..j-1].
* \param cs Reference to a vector that will contain in
* cs[0..k-1] all symbols that occur in [i..j-1] in
* arbitrary order (if lex_ordered = false) and ascending
* order (if lex_ordered = true).
* \param rank_c_i Reference to a vector which equals
* rank_c_i[p] = rank(i,cs[p]), for \f$ 0 \leq p < k \f$.
* \param rank_c_j Reference to a vector which equals
* rank_c_j[p] = rank(j,cs[p]), for \f$ 0 \leq p < k \f$.
* \par Time complexity
* \f$ \Order{\min{\sigma, k \log \sigma}} \f$
*
* \par Precondition
* \f$ i \leq j \leq size() \f$
* \f$ cs.size() \geq \sigma \f$
* \f$ rank_{c_i}.size() \geq \sigma \f$
* \f$ rank_{c_j}.size() \geq \sigma \f$
*/
void interval_symbols(size_type i,
size_type j,
size_type& k,
std::vector<value_type>& cs,
std::vector<size_type>& rank_c_i,
std::vector<size_type>& rank_c_j) const
{
assert(i <= j and j <= size());
if (i == j) {
k = 0;
} else if (1 == m_sigma) {
k = 1;
cs[0] = m_tree.bv_pos_rank(m_tree.root());
rank_c_i[0] = std::min(i, m_size);
rank_c_j[0] = std::min(j, m_size);
} else if ((j - i) == 1) {
k = 1;
auto rc = inverse_select(i);
rank_c_i[0] = rc.first;
cs[0] = rc.second;
rank_c_j[0] = rank_c_i[0] + 1;
} else if ((j - i) == 2) {
auto rc = inverse_select(i);
rank_c_i[0] = rc.first;
cs[0] = rc.second;
rc = inverse_select(i + 1);
rank_c_i[1] = rc.first;
cs[1] = rc.second;
if (cs[0] == cs[1]) {
k = 1;
rank_c_j[0] = rank_c_i[0] + 2;
} else {
k = 2;
if (lex_ordered and cs[0] > cs[1]) {
std::swap(cs[0], cs[1]);
std::swap(rank_c_i[0], rank_c_i[1]);
}
rank_c_j[0] = rank_c_i[0] + 1;
rank_c_j[1] = rank_c_i[1] + 1;
}
} else {
k = 0;
_interval_symbols(i, j, k, cs, rank_c_i, rank_c_j, 0);
}
}
//! How many symbols are lexicographic smaller/greater than c in [i..j-1].
/*!
* \param i Start index (inclusive) of the interval.
* \param j End index (exclusive) of the interval.
* \param c Symbol c.
* \return A triple containing:
* * rank(i,c)
* * #symbols smaller than c in [i..j-1]
* * #symbols greater than c in [i..j-1]
*
* \par Precondition
* \f$ i \leq j \leq size() \f$
* \note
* This method is only available if lex_ordered = true
*/
template <class t_ret_type = std::tuple<size_type, size_type, size_type>>
typename std::enable_if<shape_type::lex_ordered, t_ret_type>::type
lex_count(size_type i, size_type j, value_type c) const
{
assert(i <= j and j <= size());
if (1 == m_sigma) {
value_type _c = m_tree.bv_pos_rank(m_tree.root());
if (c == _c) { // c is the only symbol in the wt
return t_ret_type{i, 0, 0};
} else if (c < _c) {
return t_ret_type{0, 0, j - i};
} else {
return t_ret_type{0, j - i, 0};
}
}
if (i == j) {
return t_ret_type{rank(i, c), 0, 0};
}
uint64_t p = m_tree.bit_path(c);
uint32_t path_len = p >> 56;
if (path_len == 0) { // path_len=0: => c is not present
value_type _c = (value_type)p;
if (c == _c) { // c is smaller than any symbol in wt
return t_ret_type{0, 0, j - i};
}
auto res = lex_count(i, j, _c);
return t_ret_type{0, j - i - std::get<2>(res), std::get<2>(res)};
}
size_type smaller = 0, greater = 0;
node_type v = m_tree.root();
for (uint32_t l = 0; l < path_len; ++l, p >>= 1) {
size_type r1_1 = (m_bv_rank(m_tree.bv_pos(v) + i) - m_tree.bv_pos_rank(v));
size_type r1_2 = (m_bv_rank(m_tree.bv_pos(v) + j) - m_tree.bv_pos_rank(v));
if (p & 1) {
smaller += j - r1_2 - i + r1_1;
i = r1_1;
j = r1_2;
} else {
greater += r1_2 - r1_1;
i -= r1_1;
j -= r1_2;
}
v = m_tree.child(v, p & 1);
}
return t_ret_type{i, smaller, greater};
}
//! How many symbols are lexicographic smaller than c in [0..i-1].
/*!
* \param i Exclusive right bound of the range.
* \param c Symbol c.
* \return A tuple containing:
* * rank(i,c)
* * #symbols smaller than c in [0..i-1]
* \par Precondition
* \f$ i \leq size() \f$
* \note
* This method is only available if lex_ordered = true
*/
template <class t_ret_type = std::tuple<size_type, size_type>>
typename std::enable_if<shape_type::lex_ordered, t_ret_type>::type
lex_smaller_count(size_type i, value_type c) const
{
assert(i <= size());
if (1 == m_sigma) {
value_type _c = m_tree.bv_pos_rank(m_tree.root());
if (c == _c) { // c is the only symbol in the wt
return t_ret_type{i, 0};
} else if (c < _c) {
return t_ret_type{0, 0};
} else {
return t_ret_type{0, i};
}
}
uint64_t p = m_tree.bit_path(c);
uint32_t path_len = p >> 56;
if (path_len == 0) { // path_len=0: => c is not present
value_type _c = (value_type)p;
if (c == _c) { // c is smaller than any symbol in wt
return t_ret_type{0, 0};
}
auto res = lex_smaller_count(i, _c);
return t_ret_type{0, std::get<0>(res) + std::get<1>(res)};
}
size_type result = 0;
size_type all = i; // possible occurrences of c
node_type v = m_tree.root();
for (uint32_t l = 0; l < path_len and all; ++l, p >>= 1) {
size_type ones = (m_bv_rank(m_tree.bv_pos(v) + all) - m_tree.bv_pos_rank(v));
if (p & 1) {
result += all - ones;
all = ones;
} else {
all -= ones;
}
v = m_tree.child(v, p & 1);
}
return t_ret_type{all, result};
}
//! Returns a const_iterator to the first element.
const_iterator begin() const { return const_iterator(this, 0); }
//! Returns a const_iterator to the element after the last element.
const_iterator end() const { return const_iterator(this, size()); }
//! Serializes the data structure into the given ostream
size_type
serialize(std::ostream& out, structure_tree_node* v = nullptr, std::string name = "") const
{
structure_tree_node* child = structure_tree::add_child(v, name, util::class_name(*this));
size_type written_bytes = 0;
written_bytes += write_member(m_size, out, child, "size");
written_bytes += write_member(m_sigma, out, child, "sigma");
written_bytes += m_bv.serialize(out, child, "bv");
written_bytes += m_bv_rank.serialize(out, child, "bv_rank");
written_bytes += m_bv_select1.serialize(out, child, "bv_select_1");
written_bytes += m_bv_select0.serialize(out, child, "bv_select_0");
written_bytes += m_tree.serialize(out, child, "tree");
structure_tree::add_size(child, written_bytes);
return written_bytes;
}
//! Loads the data structure from the given istream.
void load(std::istream& in)
{
read_member(m_size, in);
read_member(m_sigma, in);
m_bv.load(in);
m_bv_rank.load(in, &m_bv);
m_bv_select1.load(in, &m_bv);
m_bv_select0.load(in, &m_bv);
m_tree.load(in);
}
//! Equality operator.
bool operator==(wt_pc const & other) const noexcept
{
return (m_size == other.m_size) && (m_sigma == other.m_sigma) &&
(m_bv == other.m_bv) && (m_bv_rank == other.m_bv_rank) &&
(m_bv_select1 == other.m_bv_select1) && (m_bv_select0 == other.m_bv_select0) &&
(m_tree == other.m_tree);
}
//! Inequality operator.
bool operator!=(wt_pc const & other) const noexcept
{
return !(*this == other);
}
template <typename archive_t>
void CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const
{
ar(CEREAL_NVP(m_size));
ar(CEREAL_NVP(m_sigma));
ar(CEREAL_NVP(m_bv));
ar(CEREAL_NVP(m_bv_rank));
ar(CEREAL_NVP(m_bv_select1));
ar(CEREAL_NVP(m_bv_select0));
ar(CEREAL_NVP(m_tree));
}
template <typename archive_t>
void CEREAL_LOAD_FUNCTION_NAME(archive_t & ar)
{
ar(CEREAL_NVP(m_size));
ar(CEREAL_NVP(m_sigma));
ar(CEREAL_NVP(m_bv));
ar(CEREAL_NVP(m_bv_rank));
m_bv_rank.set_vector(&m_bv);
ar(CEREAL_NVP(m_bv_select1));
m_bv_select1.set_vector(&m_bv);
ar(CEREAL_NVP(m_bv_select0));
m_bv_select0.set_vector(&m_bv);
ar(CEREAL_NVP(m_tree));
}
//! Random access container to bitvector of node v
auto bit_vec(const node_type& v) const -> node_bv_container<t_bitvector>
{
return node_bv_container<t_bitvector>(begin(v), end(v));
}
//! Random access container to sequence of node v
auto seq(const node_type& v) const
-> random_access_container<std::function<value_type(size_type)>>
{
return random_access_container<std::function<value_type(size_type)>>(
[&v, this](size_type i) {
node_type vv = v;
while (!is_leaf(vv)) {
auto vs = expand(vv);
auto rs = expand(vv, range_type{{0, i}});
bool bit = *(begin(vv) + i);
i = std::get<1>(rs[bit]);
vv = vs[bit];
}
return sym(vv);
},
size(v));
}
//! Checks if the node is a leaf node
bool is_leaf(const node_type& v) const { return m_tree.is_leaf(v); }
//! Symbol for a leaf
value_type sym(const node_type& v) const { return m_tree.bv_pos_rank(v); }
//! Indicates if node v is empty
bool empty(const node_type& v) const { return size(v) == 0; }
//! Return the size of node v
auto size(const node_type& v) const -> decltype(m_tree.size(v))
{
if (is_leaf(v)) {
if (v == root())
return size();
else {
auto parent = m_tree.parent(v);
auto rs = expand(parent, range_type{{0, size(parent) - 1}});
if (m_tree.child(parent, 0) == v)
return std::get<1>(std::get<0>(rs)) - std::get<0>((std::get<0>(rs))) + 1;
else
return std::get<1>(std::get<1>(rs)) - std::get<0>((std::get<1>(rs))) + 1;
}
} else {
return m_tree.size(v);
}
}
//! Returns the root node
node_type root() const { return m_tree.root(); }
//! Returns the two child nodes of an inner node
/*! \param v An inner node of a wavelet tree.
* \return Return a pair of nodes (left child, right child).
* \pre !is_leaf(v)
*/
std::array<node_type, 2> expand(const node_type& v) const
{
return {{m_tree.child(v, 0), m_tree.child(v, 1)}};
}
//! Returns for each range its left and right child ranges
/*! \param v An inner node of an wavelet tree.
* \param ranges A vector of ranges. Each range [s,e]
* has to be contained in v=[v_s,v_e].
* \return A vector a range pairs. The first element of each
* range pair correspond to the original range
* mapped to the left child of v; the second element to the
* range mapped to the right child of v.
* \pre !is_leaf(v) and s>=v_s and e<=v_e
*/
std::array<range_vec_type, 2> expand(const node_type& v, const range_vec_type& ranges) const
{
auto ranges_copy = ranges;
return expand(v, std::move(ranges_copy));
}
//! Returns for each range its left and right child ranges
/*! \param v An inner node of an wavelet tree.
* \param ranges A vector of ranges. Each range [s,e]
* has to be contained in v=[v_s,v_e].
* \return A vector a range pairs. The first element of each
* range pair correspond to the original range
* mapped to the left child of v; the second element to the
* range mapped to the right child of v.
* \pre !is_leaf(v) and s>=v_s and e<=v_e
*/
std::array<range_vec_type, 2> expand(const node_type& v, range_vec_type&& ranges) const
{
auto v_sp_rank = m_tree.bv_pos_rank(v);
range_vec_type res(ranges.size());
size_t i = 0;
for (auto& r : ranges) {
auto sp_rank = m_bv_rank(m_tree.bv_pos(v) + r[0]);
auto right_size = m_bv_rank(m_tree.bv_pos(v) + r[1] + 1) - sp_rank;
auto left_size = (r[1] - r[0] + 1) - right_size;
auto right_sp = sp_rank - v_sp_rank;
auto left_sp = r[0] - right_sp;
r = {{left_sp, left_sp + left_size - 1}};
res[i++] = {{right_sp, right_sp + right_size - 1}};
}
return {{ranges, std::move(res)}};
}
//! Returns for a range its left and right child ranges
/*! \param v An inner node of an wavelet tree.
* \param r A ranges [s,e], such that [s,e] is
* contained in v=[v_s,v_e].
* \return A range pair. The first element of the
* range pair correspond to the original range
* mapped to the left child of v; the second element to the
* range mapped to the right child of v.
* \pre !is_leaf(v) and s>=v_s and e<=v_e
*/
std::array<range_type, 2> expand(const node_type& v, const range_type& r) const
{
auto v_sp_rank = m_tree.bv_pos_rank(v);
auto sp_rank = m_bv_rank(m_tree.bv_pos(v) + r[0]);
auto right_size = m_bv_rank(m_tree.bv_pos(v) + r[1] + 1) - sp_rank;
auto left_size = (r[1] - r[0] + 1) - right_size;
auto right_sp = sp_rank - v_sp_rank;
auto left_sp = r[0] - right_sp;
return {{{{left_sp, left_sp + left_size - 1}}, {{right_sp, right_sp + right_size - 1}}}};
}
//! return the path to the leaf for a given symbol
std::pair<uint64_t, uint64_t> path(value_type c) const
{
uint64_t path = m_tree.bit_path(c);
uint64_t path_len = path >> 56;
// reverse the path till we fix the ordering
path = bits::rev(path);
path = path >> (64 - path_len); // remove the length
return {path_len, path};
}
//! Returns for a symbol c the next larger or equal symbol in the WT.
/*! \param c the symbol
* \return A pair. The first element of the pair consititues if
* a valid answer was found (true) or no valid answer (false)
* could be found. The second element contains the found symbol.
*/
std::pair<bool, value_type> symbol_gte(value_type c) const { return m_tree.symbol_gte(c); }
//! Returns for a symbol c the previous smaller or equal symbol in the WT.
/*! \param c the symbol
* \return A pair. The first element of the pair consititues if
* a valid answer was found (true) or no valid answer (false)
* could be found. The second element contains the found symbol.
*/
std::pair<bool, value_type> symbol_lte(value_type c) const { return m_tree.symbol_lte(c); }
private:
//! Iterator to the begin of the bitvector of inner node v
auto begin(const node_type& v) const -> decltype(m_bv.begin() + m_tree.bv_pos(v))
{
return m_bv.begin() + m_tree.bv_pos(v);
}
//! Iterator to the begin of the bitvector of inner node v
auto end(const node_type& v) const -> decltype(m_bv.begin() + m_tree.bv_pos(v) + m_tree.size(v))
{
return m_bv.begin() + m_tree.bv_pos(v) + m_tree.size(v);
}
};
}
#endif
| [
"evelin.aasna@fu-berlin.de"
] | evelin.aasna@fu-berlin.de |
f9609ab0a66031fc3f04d20ae91b7476eaa74ac6 | b1f7a2309825dbe6d5953f6582d7f442d1d40422 | /lc-cn/找到字符串中所有字母异位词.cpp | b57de7d35832fd455de649a2ad7e24259a5567db | [] | no_license | helloMickey/Algorithm | cbb8aea2a4279b2d76002592a658c54475977ff0 | d0923a9e14e288def11b0a8191097b5fd7a85f46 | refs/heads/master | 2023-07-03T00:58:05.754471 | 2021-08-09T14:42:49 | 2021-08-09T14:42:49 | 201,753,017 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp | // https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
// 核心思路:滑动窗口
// 借助哈希表,判断两个串是否是 异位词
/*
作者:bestblade
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/solution/hua-dong-chuang-kou-shu-zu-ha-xi-biao-by-r2k2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
//判断两个单词是否相同
bool check(int s[], int p[]) {
for (int i = 0; i < 26; i++) {
if (s[i] != p[i]) {
return false;
}
}
return true;
}
vector<int> findAnagrams(string s, string p) {
vector<int> res;
if (p.size() > s.size()) {
return res;
}
//采用数组代替哈希表,速度更快,但是要自己写判断函数
int s_cnt[26] = { 0 };
int p_cnt[26] = { 0 };
for (int i = 0; i < p.size(); ++i) {
s_cnt[s[i] - 'a']++;
p_cnt[p[i] - 'a']++;
}
if (check(s_cnt,p_cnt)) {
res.emplace_back(0);
}
int l = 0;
int r = p.size() - 1;
while (r < s.size() - 1) {
s_cnt[s[l++] - 'a']--;
s_cnt[s[++r] - 'a']++;
if (check(s_cnt, p_cnt)) {
res.emplace_back(l);
}
}
return res;
} | [
"chenke876234714@gmail.com"
] | chenke876234714@gmail.com |
4c3369743ca596301e18760056613a9acaf4a84b | e7178a4395b86f34a97054636a8e63a4ece74e78 | /Caligula/CollisionHandler.h | 3478836964679202afb0d9544c90c1df799b7360 | [] | no_license | Jarskih/Bomberman2 | d164cbe3af09fa0b5b5af040bdf1547f5645fe63 | 0f9625625561d9de9cbb34f8a0f644ee23047dee | refs/heads/master | 2020-04-26T04:55:15.568385 | 2019-03-08T15:16:41 | 2019-03-08T15:16:41 | 173,317,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | #pragma once
/*
* CollisionHandler.h
* Simple axis aligned bounding box collision detection
*/
class Collider;
class RectangleCollider;
class CollisionHandler
{
bool IsColliding(RectangleCollider* p_lhs, RectangleCollider* p_rhs);
public:
bool IsColliding(Collider* p_lhs, Collider* p_rhs); // Axis Aligned Bounding Box (AABB)
};
| [
"madcook86@gmail.com"
] | madcook86@gmail.com |
4effb0a194e4c8324c38cf48b346a49a010fb44d | 10545d7ecf88f97a406c0dd5830d05fd47c4c978 | /2015_1C_1.cpp | 7ec5f3bcb7c4ab3471a43553c45e9d402689caa7 | [] | no_license | AbhishekTiwari0812/CodeJamCodes | 080c761f5fd124fa1604c49ec29ad496772fda98 | ef3238ab9bb353c53f721c5a803b3b104df05603 | refs/heads/master | 2021-06-07T05:37:54.379465 | 2016-10-23T06:11:04 | 2016-10-23T06:11:04 | 48,569,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,729 | cpp | #include <iostream>
#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <set>
#include <cmath>
using namespace std;
typedef long long int lli;
long int visit;
typedef struct node{
int x;
int y;
int visited;
int value;
struct node *neighbours;
}node;
node ***G;
int R,C;
vector<node *> getNeighbours(node *current){
vector<node *>output;
if(current->x>0)
if(G[current->x-1][current->y]->value==1)
output.push_back(G[current->x-1][current->y]);
if(current->y >0)
if(G[current->x][current->y-1]->value==1)
output.push_back(G[current->x][current->y-1]);
if(current->x<R-1)
if(G[current->x+1][current->y]->value==1)
output.push_back(G[current->x+1][current->y]);
if(current->y<C-1)
if(G[current->x][current->y+1]->value==1)
output.push_back(G[current->x][current->y+1]);
return output;
}
void dfs_visit(node *root){
////cout<<"Point::"<<root->x<<" "<<root->y<<endl;
vector<node *> v=getNeighbours(root);
for(int i=0;i<v.size();i++){
if(G[v[i]->x][v[i]->y]->visited!=visit){
G[v[i]->x][v[i]->y]->visited=visit;
dfs_visit(G[v[i]->x][v[i]->y]);
}
}
}
int components;
void DFS(){
for(int i=0;i<R;i++)
for(int j=0;j<C;j++){
if(G[i][j]->value==1 && G[i][j]->visited != visit){
components+=1;
// //cout<<"DFS Point::"<<G[i][j]->x<<" "<<G[i][j]->y<<endl;
G[i][j]->visited=visit;
dfs_visit(G[i][j]);
}
}
}
int main(){
ifstream in;
ofstream out;
in.open("A-large.in");
out.open("output.out");
int test;
int x,y;
char type;
in>>test;
char some_char;
int queries;
int z;
for(int some=0;some<test;some++){
visit=1;
out<<"Case #"<<(some+1)<<":"<<endl;
in>>R>>C;
G=new node**[R];
for(int i=0;i<R;i++){
G[i]=new node*[C];
for(int j=0;j<C;j++){
G[i][j]=new node;
G[i][j]->visited=-1;
in>>some_char;
some_char=some_char-'0';
G[i][j]->x=i;
G[i][j]->y=j;
G[i][j]->value=(int)some_char;
}
}
components=0;
vector<node *> helper;
in>>queries;
DFS();
for(int i=0;i<queries;i++){
in>>type;
if(type=='Q'){
out<<components<<endl;
}
else if(type=='M'){
in>>x>>y>>z;
if(G[x][y]->value==z)
continue;
helper= getNeighbours(G[x][y]);
if(helper.size()==0){
if(z==1 && G[x][y]->value!=1){
components+=1;
G[x][y]->value=1;
}
else if(z==0 && G[x][y]->value!=0){
components-=1;
G[x][y]->value=0;
}
}
else if(helper.size()==1){
G[x][y]->value=z;
}
else if(helper.size()>1){
if(G[x][y]->value!=z){
G[x][y]->value=z;
visit+=1;
components=0;
DFS();
}
else continue;
}
}
}
}
in.close();
out.close();
return 0;
} | [
"abhishektiwari08121994007@gmail.com"
] | abhishektiwari08121994007@gmail.com |
df06de6ebabb8a8ea51ef8a0c964d4038a2129ca | acd48b7d59221e51f956b20ae6303d0bae47bfd5 | /1217.cpp | a6fc459d10523753300295a551be82e6800e8980 | [] | no_license | lisongming/practice | 2a47a60a69b6e10722e3d63f548aacaadecbb117 | 5e7bbdc87ea535c42f21008c553356583d555acd | refs/heads/master | 2020-04-24T21:50:00.871230 | 2019-05-13T15:53:00 | 2019-05-13T15:53:00 | 172,291,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 195 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int s,x=0;
while(scanf("%d",&s),s!=0){
for(int i=1;i<=32;i++){
if(s==i*i*i){
x++;
}
}
}
printf("%d",x);
return 0;
}
| [
"939200869@qq.com"
] | 939200869@qq.com |
6fb370651e997a451d606c9ae3184e10d1c5022f | 73608516e0161b51c2d73ac879d948048fc2bee6 | /66_Valid_Number.cpp | 723f8c0d3953bad141e822b9a3df634d0f1906bd | [] | no_license | huangweiwu/leetcode | 9fa7c10a4d45b5018992f998277e38205ea41646 | 0fa3eec7a07a184379b6bacf78c9f591abc32065 | refs/heads/master | 2016-08-08T07:34:30.926666 | 2015-07-30T03:26:44 | 2015-07-30T03:26:44 | 34,848,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | cpp | //判断一个字符串是否有效数字
//思路:
//考虑很多的情况
//1) 首先去掉字符串开头的空格
//2) 直到遇到e之前必须是一个有效的数字
//3) 遇到e之后,必须是一个有效的整数
class Solution {
public:
bool isNumber(const char *s) {
if(s == NULL)
return false;
while(isspace(*s))
s++;
if(*s=='+' || *s=='-')
s++;
bool hasE = false;
bool hasDot = false;
bool hasSpace = false;
bool firstpart = false;
bool secondpart = false;
while(*s != '\0') {
if(*s == '.') {
if(hasDot || hasE || hasSpace)
return false;
else
hasDot = true;
}
else if(*s == 'e' || *s == 'E') {
if(!firstpart || hasE || hasSpace)
return false;
else
hasE = true;
}
else if(isdigit(*s)) {
if(hasSpace)
return false;
if(!hasE)
firstpart = true;
else
secondpart = true;
}
else if(*s=='+' || *s=='-') {
if(hasSpace || !hasE || (*(s-1)!='e' && *(s-1)!='E'))
return false;
}
else if(isspace(*s))
hasSpace = true;
else
return false;
s++;
}
if(!firstpart)
return false;
else if(hasE && !secondpart)
return false;
else
return true;
}
}; | [
"huangweiwu@iie.ac.cn"
] | huangweiwu@iie.ac.cn |
09c432d56c0abfd43dbb67d84b2714d06d9160c2 | d986f73097b67b339963ab532f4fc8602c32a461 | /hw17/Coordinates.cc | 4728494c9bd5ee2bb75aca51e6b5bd48ef0424ce | [] | no_license | jaaamessszzz/Rosetta-Boot-Camp-2017-Homeworks | 166c963eb3a87cf3285228e6824cdfcd655b1f8b | 927744a5cb947447ec26898ce263c8a60f2a55d1 | refs/heads/master | 2021-01-11T17:44:28.860149 | 2017-01-23T17:54:07 | 2017-01-23T17:54:07 | 79,831,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,848 | cc | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
/// This Coordinates class contains three double numbers, x_, y_, z_,
/// which are used to describe the coordinates of a point in 3-D dimension.
/// Users can set and modify x_ and y_, and calculate z_, according certain Function.
/// In this exercise, we are only dealing with three functions
#include <iostream>
#include <cstdlib>
#include <stdexcept>
#include "Landscape.cc"
#include "Coordinates.hh"
///// Implementation of Coordinates functions starts here /////
///// TODO: Implementat the constructors and member functions for class Coordinates
///// that are declared in Coordinates.hh
// We have already implemented this function for you. You should invoke
// this function in the constructor.
void
Coordinates::set_landscape_function(std::string new_function) {
landscape_function_name_ = new_function;
if ( landscape_function_name_ == "sum_squares" ) {
landscape_ = std::shared_ptr<Landscape> ( new SumSquares() );
} else if ( landscape_function_name_ == "rastrigin" ) {
landscape_ = std::shared_ptr<Landscape> ( new Rastrigin() );
} else if ( landscape_function_name_ == "ackley" ) {
landscape_ = std::shared_ptr<Landscape> ( new Ackley() );
} else {
throw std::invalid_argument( "The function '" + new_function + "' hasn't been defined! Valid options are 'sum_squares', 'rastrigin', and 'ackley'" );
}
}
Coordinates::Coordinates(){}
Coordinates::~Coordinates(){}
Coordinates::Coordinates(std::string fxn){
set_landscape_function(fxn);
x_ = 0;
y_ = 0;
z_ = 0;
temp_x_ = 0;
temp_y_ = 0;
}
Coordinates::Coordinates(Coordinates & src){
x_ = src.get_x();
y_ = src.get_y();
z_ = src.get_z();
temp_x_ = src.temp_x_;
temp_y_ = src.temp_y_;
landscape_ = src.landscape_;
landscape_function_name_ = src.landscape_function_name_;
}
// X Getters and setters
double
Coordinates::get_x(){
return x_;
}
void
Coordinates::set_x(double x){
x_ = x;
update_z();
}
void
Coordinates::modify_x(double delta){
temp_x_ = x_;
x_ = x_ + delta;
update_z();
}
// Y Getters and setters
double
Coordinates::get_y(){
return y_;
}
void
Coordinates::set_y(double y){
y_ = y;
update_z();
}
void
Coordinates::modify_y(double delta){
temp_y_ = y_;
y_ = y_ + delta;
update_z();
}
// Z Getter and setter
double
Coordinates::get_z() const {
return z_;
}
std::string
Coordinates::get_landscape_function(){
return landscape_function_name_;
}
void
Coordinates::update_z() {
z_ = landscape_->calculate_z(x_, y_);
}
void
Coordinates::reset_temp_xy(){
x_ = temp_x_;
y_ = temp_y_;
update_z();
}
double
Coordinates::calculate_z(double x, double y){
return (landscape_->calculate_z(x, y));
}
double
Coordinates::get_temp_x(){
return temp_x_;
}
double
Coordinates::get_temp_y(){
return temp_y_;
} | [
"james.lucas@berkeley.edu"
] | james.lucas@berkeley.edu |
4934eec3f8a26ea662aa2efefce52c8e84a24639 | 714c8b09a967cd675e6000e0ce3e09f74821e343 | /src/svg/mark_svg.h | 8f9c5704f09e6171d57fcb82644fdab5cfe98af0 | [
"MIT"
] | permissive | colinw7/CQPixmapEd | 5590afde3eb2e620a47efcdfe30f819acc8f2572 | 498939cad4b9789524bd7f13079c18bcba793ba3 | refs/heads/master | 2023-01-28T10:08:39.800555 | 2023-01-16T14:44:03 | 2023-01-16T14:44:03 | 10,395,629 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 32,476 | h | #ifndef MARK_pixmap_H
#define MARK_pixmap_H
#include <CQPixmapCache.h>
class MARK_pixmap {
private:
uchar data_[6062] = {
0x3c,0x3f,0x78,0x6d,0x6c,0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x3d,0x22,0x31,
0x2e,0x30,0x22,0x20,0x65,0x6e,0x63,0x6f,0x64,0x69,0x6e,0x67,0x3d,0x22,0x55,0x54,
0x46,0x2d,0x38,0x22,0x20,0x73,0x74,0x61,0x6e,0x64,0x61,0x6c,0x6f,0x6e,0x65,0x3d,
0x22,0x6e,0x6f,0x22,0x3f,0x3e,0x0a,0x3c,0x21,0x2d,0x2d,0x20,0x43,0x72,0x65,0x61,
0x74,0x65,0x64,0x20,0x77,0x69,0x74,0x68,0x20,0x49,0x6e,0x6b,0x73,0x63,0x61,0x70,
0x65,0x20,0x28,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x69,0x6e,
0x6b,0x73,0x63,0x61,0x70,0x65,0x2e,0x6f,0x72,0x67,0x2f,0x29,0x20,0x2d,0x2d,0x3e,
0x0a,0x0a,0x3c,0x73,0x76,0x67,0x0a,0x20,0x20,0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,
0x64,0x63,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x70,0x75,0x72,0x6c,0x2e,
0x6f,0x72,0x67,0x2f,0x64,0x63,0x2f,0x65,0x6c,0x65,0x6d,0x65,0x6e,0x74,0x73,0x2f,
0x31,0x2e,0x31,0x2f,0x22,0x0a,0x20,0x20,0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x63,
0x63,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x63,0x72,0x65,0x61,0x74,0x69,
0x76,0x65,0x63,0x6f,0x6d,0x6d,0x6f,0x6e,0x73,0x2e,0x6f,0x72,0x67,0x2f,0x6e,0x73,
0x23,0x22,0x0a,0x20,0x20,0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x72,0x64,0x66,0x3d,
0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,
0x72,0x67,0x2f,0x31,0x39,0x39,0x39,0x2f,0x30,0x32,0x2f,0x32,0x32,0x2d,0x72,0x64,
0x66,0x2d,0x73,0x79,0x6e,0x74,0x61,0x78,0x2d,0x6e,0x73,0x23,0x22,0x0a,0x20,0x20,
0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x73,0x76,0x67,0x3d,0x22,0x68,0x74,0x74,0x70,
0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72,0x67,0x2f,0x32,0x30,
0x30,0x30,0x2f,0x73,0x76,0x67,0x22,0x0a,0x20,0x20,0x20,0x78,0x6d,0x6c,0x6e,0x73,
0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,
0x6f,0x72,0x67,0x2f,0x32,0x30,0x30,0x30,0x2f,0x73,0x76,0x67,0x22,0x0a,0x20,0x20,
0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,0x3d,
0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,
0x2e,0x73,0x6f,0x75,0x72,0x63,0x65,0x66,0x6f,0x72,0x67,0x65,0x2e,0x6e,0x65,0x74,
0x2f,0x44,0x54,0x44,0x2f,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,0x2d,0x30,0x2e,
0x64,0x74,0x64,0x22,0x0a,0x20,0x20,0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x69,0x6e,
0x6b,0x73,0x63,0x61,0x70,0x65,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,
0x77,0x77,0x2e,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x2e,0x6f,0x72,0x67,0x2f,
0x6e,0x61,0x6d,0x65,0x73,0x70,0x61,0x63,0x65,0x73,0x2f,0x69,0x6e,0x6b,0x73,0x63,
0x61,0x70,0x65,0x22,0x0a,0x20,0x20,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22,0x34,
0x35,0x30,0x2e,0x35,0x32,0x38,0x30,0x35,0x22,0x0a,0x20,0x20,0x20,0x68,0x65,0x69,
0x67,0x68,0x74,0x3d,0x22,0x34,0x34,0x36,0x2e,0x34,0x38,0x37,0x34,0x33,0x22,0x0a,
0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x73,0x76,0x67,0x32,0x22,0x0a,0x20,0x20,0x20,
0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x3d,0x22,0x31,0x2e,0x31,0x22,0x0a,0x20,0x20,
0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x76,0x65,0x72,0x73,0x69,0x6f,
0x6e,0x3d,0x22,0x30,0x2e,0x39,0x31,0x20,0x72,0x22,0x0a,0x20,0x20,0x20,0x73,0x6f,
0x64,0x69,0x70,0x6f,0x64,0x69,0x3a,0x64,0x6f,0x63,0x6e,0x61,0x6d,0x65,0x3d,0x22,
0x6d,0x61,0x72,0x6b,0x2e,0x73,0x76,0x67,0x22,0x3e,0x0a,0x20,0x20,0x3c,0x64,0x65,
0x66,0x73,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x64,0x65,0x66,0x73,
0x34,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x3c,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,
0x69,0x3a,0x6e,0x61,0x6d,0x65,0x64,0x76,0x69,0x65,0x77,0x0a,0x20,0x20,0x20,0x20,
0x20,0x69,0x64,0x3d,0x22,0x62,0x61,0x73,0x65,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,
0x70,0x61,0x67,0x65,0x63,0x6f,0x6c,0x6f,0x72,0x3d,0x22,0x23,0x66,0x66,0x66,0x66,
0x66,0x66,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x62,0x6f,0x72,0x64,0x65,0x72,0x63,
0x6f,0x6c,0x6f,0x72,0x3d,0x22,0x23,0x36,0x36,0x36,0x36,0x36,0x36,0x22,0x0a,0x20,
0x20,0x20,0x20,0x20,0x62,0x6f,0x72,0x64,0x65,0x72,0x6f,0x70,0x61,0x63,0x69,0x74,
0x79,0x3d,0x22,0x31,0x2e,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,
0x73,0x63,0x61,0x70,0x65,0x3a,0x70,0x61,0x67,0x65,0x6f,0x70,0x61,0x63,0x69,0x74,
0x79,0x3d,0x22,0x30,0x2e,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,
0x73,0x63,0x61,0x70,0x65,0x3a,0x70,0x61,0x67,0x65,0x73,0x68,0x61,0x64,0x6f,0x77,
0x3d,0x22,0x32,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,
0x70,0x65,0x3a,0x7a,0x6f,0x6f,0x6d,0x3d,0x22,0x32,0x2e,0x31,0x31,0x38,0x33,0x34,
0x30,0x32,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,
0x65,0x3a,0x63,0x78,0x3d,0x22,0x31,0x33,0x32,0x2e,0x36,0x39,0x30,0x38,0x31,0x22,
0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,
0x79,0x3d,0x22,0x32,0x32,0x32,0x2e,0x32,0x33,0x33,0x35,0x36,0x22,0x0a,0x20,0x20,
0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x64,0x6f,0x63,0x75,
0x6d,0x65,0x6e,0x74,0x2d,0x75,0x6e,0x69,0x74,0x73,0x3d,0x22,0x70,0x78,0x22,0x0a,
0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x75,
0x72,0x72,0x65,0x6e,0x74,0x2d,0x6c,0x61,0x79,0x65,0x72,0x3d,0x22,0x6c,0x61,0x79,
0x65,0x72,0x31,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x73,0x68,0x6f,0x77,0x67,0x72,
0x69,0x64,0x3d,0x22,0x66,0x61,0x6c,0x73,0x65,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,
0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x77,0x69,0x6e,0x64,0x6f,0x77,0x2d,
0x77,0x69,0x64,0x74,0x68,0x3d,0x22,0x32,0x30,0x30,0x37,0x22,0x0a,0x20,0x20,0x20,
0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x77,0x69,0x6e,0x64,0x6f,
0x77,0x2d,0x68,0x65,0x69,0x67,0x68,0x74,0x3d,0x22,0x31,0x33,0x35,0x36,0x22,0x0a,
0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x77,0x69,
0x6e,0x64,0x6f,0x77,0x2d,0x78,0x3d,0x22,0x32,0x33,0x34,0x22,0x0a,0x20,0x20,0x20,
0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x77,0x69,0x6e,0x64,0x6f,
0x77,0x2d,0x79,0x3d,0x22,0x34,0x32,0x34,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,
0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x77,0x69,0x6e,0x64,0x6f,0x77,0x2d,0x6d,
0x61,0x78,0x69,0x6d,0x69,0x7a,0x65,0x64,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,
0x20,0x20,0x66,0x69,0x74,0x2d,0x6d,0x61,0x72,0x67,0x69,0x6e,0x2d,0x74,0x6f,0x70,
0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x66,0x69,0x74,0x2d,0x6d,0x61,
0x72,0x67,0x69,0x6e,0x2d,0x6c,0x65,0x66,0x74,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,
0x20,0x20,0x20,0x66,0x69,0x74,0x2d,0x6d,0x61,0x72,0x67,0x69,0x6e,0x2d,0x72,0x69,
0x67,0x68,0x74,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x66,0x69,0x74,
0x2d,0x6d,0x61,0x72,0x67,0x69,0x6e,0x2d,0x62,0x6f,0x74,0x74,0x6f,0x6d,0x3d,0x22,
0x30,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x3c,0x6d,0x65,0x74,0x61,0x64,0x61,0x74,
0x61,0x0a,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x6d,0x65,0x74,0x61,0x64,
0x61,0x74,0x61,0x37,0x22,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x72,0x64,0x66,0x3a,
0x52,0x44,0x46,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x63,0x63,0x3a,0x57,
0x6f,0x72,0x6b,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x72,0x64,0x66,
0x3a,0x61,0x62,0x6f,0x75,0x74,0x3d,0x22,0x22,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x3c,0x64,0x63,0x3a,0x66,0x6f,0x72,0x6d,0x61,0x74,0x3e,0x69,0x6d,
0x61,0x67,0x65,0x2f,0x73,0x76,0x67,0x2b,0x78,0x6d,0x6c,0x3c,0x2f,0x64,0x63,0x3a,
0x66,0x6f,0x72,0x6d,0x61,0x74,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x3c,0x64,0x63,0x3a,0x74,0x79,0x70,0x65,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x72,0x64,0x66,0x3a,0x72,0x65,0x73,0x6f,0x75,0x72,0x63,0x65,
0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x70,0x75,0x72,0x6c,0x2e,0x6f,0x72,
0x67,0x2f,0x64,0x63,0x2f,0x64,0x63,0x6d,0x69,0x74,0x79,0x70,0x65,0x2f,0x53,0x74,
0x69,0x6c,0x6c,0x49,0x6d,0x61,0x67,0x65,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x3c,0x64,0x63,0x3a,0x74,0x69,0x74,0x6c,0x65,0x3e,0x3c,
0x2f,0x64,0x63,0x3a,0x74,0x69,0x74,0x6c,0x65,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x3c,0x2f,0x63,0x63,0x3a,0x57,0x6f,0x72,0x6b,0x3e,0x0a,0x20,0x20,0x20,0x20,
0x3c,0x2f,0x72,0x64,0x66,0x3a,0x52,0x44,0x46,0x3e,0x0a,0x20,0x20,0x3c,0x2f,0x6d,
0x65,0x74,0x61,0x64,0x61,0x74,0x61,0x3e,0x0a,0x20,0x20,0x3c,0x67,0x0a,0x20,0x20,
0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x6c,0x61,0x62,0x65,
0x6c,0x3d,0x22,0x4c,0x61,0x79,0x65,0x72,0x20,0x31,0x22,0x0a,0x20,0x20,0x20,0x20,
0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x67,0x72,0x6f,0x75,0x70,0x6d,
0x6f,0x64,0x65,0x3d,0x22,0x6c,0x61,0x79,0x65,0x72,0x22,0x0a,0x20,0x20,0x20,0x20,
0x20,0x69,0x64,0x3d,0x22,0x6c,0x61,0x79,0x65,0x72,0x31,0x22,0x0a,0x20,0x20,0x20,
0x20,0x20,0x74,0x72,0x61,0x6e,0x73,0x66,0x6f,0x72,0x6d,0x3d,0x22,0x74,0x72,0x61,
0x6e,0x73,0x6c,0x61,0x74,0x65,0x28,0x34,0x2e,0x37,0x38,0x36,0x36,0x38,0x39,0x36,
0x2c,0x37,0x2e,0x35,0x33,0x33,0x36,0x33,0x32,0x33,0x29,0x22,0x3e,0x0a,0x20,0x20,
0x20,0x20,0x3c,0x72,0x65,0x63,0x74,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,
0x74,0x79,0x6c,0x65,0x3d,0x22,0x63,0x6f,0x6c,0x6f,0x72,0x3a,0x23,0x30,0x30,0x30,
0x30,0x30,0x30,0x3b,0x63,0x6c,0x69,0x70,0x2d,0x72,0x75,0x6c,0x65,0x3a,0x6e,0x6f,
0x6e,0x7a,0x65,0x72,0x6f,0x3b,0x64,0x69,0x73,0x70,0x6c,0x61,0x79,0x3a,0x69,0x6e,
0x6c,0x69,0x6e,0x65,0x3b,0x6f,0x76,0x65,0x72,0x66,0x6c,0x6f,0x77,0x3a,0x76,0x69,
0x73,0x69,0x62,0x6c,0x65,0x3b,0x76,0x69,0x73,0x69,0x62,0x69,0x6c,0x69,0x74,0x79,
0x3a,0x76,0x69,0x73,0x69,0x62,0x6c,0x65,0x3b,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,
0x3a,0x31,0x3b,0x69,0x73,0x6f,0x6c,0x61,0x74,0x69,0x6f,0x6e,0x3a,0x61,0x75,0x74,
0x6f,0x3b,0x6d,0x69,0x78,0x2d,0x62,0x6c,0x65,0x6e,0x64,0x2d,0x6d,0x6f,0x64,0x65,
0x3a,0x6e,0x6f,0x72,0x6d,0x61,0x6c,0x3b,0x63,0x6f,0x6c,0x6f,0x72,0x2d,0x69,0x6e,
0x74,0x65,0x72,0x70,0x6f,0x6c,0x61,0x74,0x69,0x6f,0x6e,0x3a,0x73,0x52,0x47,0x42,
0x3b,0x63,0x6f,0x6c,0x6f,0x72,0x2d,0x69,0x6e,0x74,0x65,0x72,0x70,0x6f,0x6c,0x61,
0x74,0x69,0x6f,0x6e,0x2d,0x66,0x69,0x6c,0x74,0x65,0x72,0x73,0x3a,0x6c,0x69,0x6e,
0x65,0x61,0x72,0x52,0x47,0x42,0x3b,0x73,0x6f,0x6c,0x69,0x64,0x2d,0x63,0x6f,0x6c,
0x6f,0x72,0x3a,0x23,0x30,0x30,0x30,0x30,0x30,0x30,0x3b,0x73,0x6f,0x6c,0x69,0x64,
0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x3b,0x66,0x69,0x6c,0x6c,0x3a,
0x23,0x66,0x66,0x66,0x66,0x66,0x66,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x6f,0x70,0x61,
0x63,0x69,0x74,0x79,0x3a,0x30,0x2e,0x35,0x30,0x31,0x39,0x36,0x30,0x37,0x38,0x3b,
0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,
0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x30,0x30,0x30,0x30,
0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,
0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,0x6c,0x69,0x6d,
0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,0x68,
0x61,0x72,0x72,0x61,0x79,0x3a,0x34,0x38,0x2c,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x30,0x2e,0x35,0x30,0x31,
0x39,0x36,0x30,0x37,0x38,0x3b,0x63,0x6f,0x6c,0x6f,0x72,0x2d,0x72,0x65,0x6e,0x64,
0x65,0x72,0x69,0x6e,0x67,0x3a,0x61,0x75,0x74,0x6f,0x3b,0x69,0x6d,0x61,0x67,0x65,
0x2d,0x72,0x65,0x6e,0x64,0x65,0x72,0x69,0x6e,0x67,0x3a,0x61,0x75,0x74,0x6f,0x3b,
0x73,0x68,0x61,0x70,0x65,0x2d,0x72,0x65,0x6e,0x64,0x65,0x72,0x69,0x6e,0x67,0x3a,
0x61,0x75,0x74,0x6f,0x3b,0x74,0x65,0x78,0x74,0x2d,0x72,0x65,0x6e,0x64,0x65,0x72,
0x69,0x6e,0x67,0x3a,0x61,0x75,0x74,0x6f,0x3b,0x65,0x6e,0x61,0x62,0x6c,0x65,0x2d,
0x62,0x61,0x63,0x6b,0x67,0x72,0x6f,0x75,0x6e,0x64,0x3a,0x61,0x63,0x63,0x75,0x6d,
0x75,0x6c,0x61,0x74,0x65,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,
0x68,0x6f,0x66,0x66,0x73,0x65,0x74,0x3a,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x69,0x64,0x3d,0x22,0x72,0x65,0x63,0x74,0x34,0x31,0x34,0x30,0x22,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22,0x33,0x37,
0x31,0x2e,0x32,0x31,0x38,0x35,0x31,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x68,0x65,0x69,0x67,0x68,0x74,0x3d,0x22,0x33,0x36,0x30,0x2e,0x30,0x30,0x37,0x32,
0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x78,0x3d,0x22,0x33,0x33,0x2e,0x36,
0x33,0x34,0x39,0x38,0x33,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x79,0x3d,
0x22,0x33,0x33,0x2e,0x36,0x33,0x31,0x38,0x32,0x34,0x22,0x20,0x2f,0x3e,0x0a,0x20,
0x20,0x20,0x20,0x3c,0x67,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,
0x22,0x67,0x34,0x31,0x38,0x38,0x22,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,
0x70,0x61,0x74,0x68,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,
0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x6f,0x72,
0x2d,0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,0x65,0x3d,0x22,0x30,0x22,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x70,0x61,0x74,0x68,
0x34,0x31,0x38,0x34,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x64,
0x3d,0x22,0x6d,0x20,0x35,0x2e,0x35,0x39,0x38,0x38,0x30,0x30,0x34,0x2c,0x33,0x32,
0x2e,0x35,0x30,0x33,0x34,0x39,0x39,0x20,0x35,0x34,0x2e,0x32,0x38,0x37,0x37,0x38,
0x35,0x36,0x2c,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,
0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,
0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,
0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x30,0x30,0x30,0x30,
0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,
0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,
0x62,0x75,0x74,0x74,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,
0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,0x74,0x65,0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,0x3b,
0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,0x68,0x61,0x72,0x72,0x61,0x79,
0x3a,0x6e,0x6f,0x6e,0x65,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,
0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,0x3a,0x6e,0x6f,0x64,0x65,0x74,0x79,0x70,0x65,
0x73,0x3d,0x22,0x63,0x63,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,
0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,0x65,0x3d,0x22,0x30,0x22,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x70,0x61,
0x74,0x68,0x34,0x31,0x38,0x36,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x64,0x3d,0x22,0x4d,0x20,0x33,0x32,0x2e,0x35,0x30,0x36,0x36,0x35,0x38,0x2c,
0x35,0x2e,0x31,0x32,0x33,0x35,0x37,0x32,0x36,0x20,0x33,0x32,0x2e,0x39,0x37,0x38,
0x37,0x32,0x36,0x2c,0x35,0x38,0x2e,0x34,0x36,0x37,0x32,0x32,0x33,0x22,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,
0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,
0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x3a,0x23,0x30,0x30,0x30,0x30,0x30,0x30,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,
0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,
0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,0x74,
0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,
0x74,0x65,0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,
0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,
0x61,0x73,0x68,0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x73,0x74,
0x72,0x6f,0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x22,0x20,
0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x2f,0x67,0x3e,0x0a,0x20,0x20,0x20,0x20,
0x3c,0x67,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x67,0x34,
0x31,0x39,0x32,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,
0x65,0x3d,0x22,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,
0x34,0x22,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,
0x66,0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,
0x75,0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,
0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,
0x69,0x74,0x65,0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,
0x69,0x74,0x79,0x3a,0x31,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,
0x65,0x72,0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,
0x2d,0x64,0x61,0x73,0x68,0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x22,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x6d,0x20,0x35,
0x2e,0x35,0x39,0x38,0x38,0x30,0x30,0x34,0x2c,0x33,0x32,0x2e,0x35,0x30,0x33,0x34,
0x39,0x39,0x20,0x35,0x34,0x2e,0x32,0x38,0x37,0x37,0x38,0x35,0x36,0x2c,0x30,0x22,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x70,0x61,
0x74,0x68,0x34,0x31,0x39,0x34,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,0x63,
0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,0x65,0x3d,0x22,0x30,
0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,
0x22,0x66,0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,
0x72,0x75,0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,
0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,
0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,
0x6d,0x69,0x74,0x65,0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,
0x65,0x72,0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,
0x2d,0x64,0x61,0x73,0x68,0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,
0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,
0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x4d,0x20,
0x33,0x32,0x2e,0x35,0x30,0x36,0x36,0x35,0x38,0x2c,0x35,0x2e,0x31,0x32,0x33,0x35,
0x37,0x32,0x36,0x20,0x33,0x32,0x2e,0x39,0x37,0x38,0x37,0x32,0x36,0x2c,0x35,0x38,
0x2e,0x34,0x36,0x37,0x32,0x32,0x33,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x69,0x64,0x3d,0x22,0x70,0x61,0x74,0x68,0x34,0x31,0x39,0x36,0x22,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,
0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,
0x61,0x74,0x75,0x72,0x65,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,0x3a,0x6e,0x6f,0x64,0x65,
0x74,0x79,0x70,0x65,0x73,0x3d,0x22,0x63,0x63,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,
0x20,0x20,0x3c,0x2f,0x67,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x67,0x0a,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x22,0x0a,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x67,0x34,0x31,0x39,0x38,0x22,0x0a,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x74,0x72,0x61,0x6e,0x73,0x66,0x6f,0x72,0x6d,0x3d,0x22,
0x74,0x72,0x61,0x6e,0x73,0x6c,0x61,0x74,0x65,0x28,0x33,0x37,0x31,0x2e,0x35,0x31,
0x37,0x32,0x39,0x2c,0x30,0x2e,0x34,0x37,0x32,0x30,0x36,0x37,0x37,0x31,0x29,0x22,
0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,
0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,0x61,0x74,
0x75,0x72,0x65,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x69,0x64,0x3d,0x22,0x70,0x61,0x74,0x68,0x34,0x32,0x30,0x30,0x22,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x6d,0x20,0x35,0x2e,0x35,
0x39,0x38,0x38,0x30,0x30,0x34,0x2c,0x33,0x32,0x2e,0x35,0x30,0x33,0x34,0x39,0x39,
0x20,0x35,0x34,0x2e,0x32,0x38,0x37,0x37,0x38,0x35,0x36,0x2c,0x30,0x22,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,
0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,
0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,
0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,
0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,0x74,
0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,
0x74,0x65,0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,
0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,
0x61,0x73,0x68,0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x73,0x74,
0x72,0x6f,0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x22,0x20,
0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,
0x3a,0x6e,0x6f,0x64,0x65,0x74,0x79,0x70,0x65,0x73,0x3d,0x22,0x63,0x63,0x22,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,
0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,
0x61,0x74,0x75,0x72,0x65,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x70,0x61,0x74,0x68,0x34,0x32,0x30,0x32,0x22,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x4d,0x20,0x33,
0x32,0x2e,0x35,0x30,0x36,0x36,0x35,0x38,0x2c,0x35,0x2e,0x31,0x32,0x33,0x35,0x37,
0x32,0x36,0x20,0x33,0x32,0x2e,0x39,0x37,0x38,0x37,0x32,0x36,0x2c,0x35,0x38,0x2e,
0x34,0x36,0x37,0x32,0x32,0x33,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,
0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,
0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,
0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,
0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,
0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,
0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,0x74,0x65,0x72,0x3b,0x73,0x74,0x72,
0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,
0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,0x68,0x61,0x72,0x72,0x61,
0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6f,0x70,
0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,
0x3c,0x2f,0x67,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x67,0x0a,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x74,0x72,0x61,0x6e,0x73,0x66,0x6f,0x72,0x6d,0x3d,0x22,0x74,0x72,
0x61,0x6e,0x73,0x6c,0x61,0x74,0x65,0x28,0x30,0x2e,0x39,0x34,0x34,0x31,0x34,0x30,
0x33,0x32,0x2c,0x33,0x35,0x39,0x2e,0x32,0x34,0x33,0x35,0x32,0x29,0x22,0x0a,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x67,0x34,0x32,0x30,0x34,0x22,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x73,
0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x22,0x3e,0x0a,
0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,0x69,0x6c,0x6c,
0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,0x6c,0x65,0x3a,
0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,
0x30,0x30,0x35,0x35,0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x77,0x69,
0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,
0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,0x74,0x65,0x72,
0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,0x6c,0x69,0x6d,
0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,0x68,
0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x73,0x74,0x72,0x6f,0x6b,
0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x22,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x6d,0x20,0x35,0x2e,0x35,0x39,0x38,
0x38,0x30,0x30,0x34,0x2c,0x33,0x32,0x2e,0x35,0x30,0x33,0x34,0x39,0x39,0x20,0x35,
0x34,0x2e,0x32,0x38,0x37,0x37,0x38,0x35,0x36,0x2c,0x30,0x22,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,0x70,0x61,0x74,0x68,0x34,0x32,
0x30,0x36,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,
0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,0x63,0x74,0x6f,0x72,0x2d,
0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,0x65,0x3d,0x22,0x30,0x22,0x20,0x2f,0x3e,
0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,0x69,0x6c,
0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,0x6c,0x65,
0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,
0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x77,
0x69,0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,
0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,0x74,0x65,
0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,0x6c,0x69,
0x6d,0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,
0x68,0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x22,0x0a,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x4d,0x20,0x33,0x32,0x2e,0x35,
0x30,0x36,0x36,0x35,0x38,0x2c,0x35,0x2e,0x31,0x32,0x33,0x35,0x37,0x32,0x36,0x20,
0x33,0x32,0x2e,0x39,0x37,0x38,0x37,0x32,0x36,0x2c,0x35,0x38,0x2e,0x34,0x36,0x37,
0x32,0x32,0x33,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,
0x3d,0x22,0x70,0x61,0x74,0x68,0x34,0x32,0x30,0x38,0x22,0x0a,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,
0x6e,0x6e,0x65,0x63,0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,
0x65,0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,
0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,0x3a,0x6e,0x6f,0x64,0x65,0x74,0x79,0x70,0x65,
0x73,0x3d,0x22,0x63,0x63,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x2f,
0x67,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x67,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,
0x30,0x30,0x35,0x35,0x64,0x34,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,
0x64,0x3d,0x22,0x67,0x34,0x32,0x31,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x74,0x72,0x61,0x6e,0x73,0x66,0x6f,0x72,0x6d,0x3d,0x22,0x74,0x72,0x61,0x6e,
0x73,0x6c,0x61,0x74,0x65,0x28,0x33,0x37,0x31,0x2e,0x39,0x38,0x39,0x33,0x36,0x2c,
0x33,0x36,0x30,0x2e,0x36,0x35,0x39,0x37,0x32,0x29,0x22,0x3e,0x0a,0x20,0x20,0x20,
0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,0x6e,0x6e,0x65,
0x63,0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,0x65,0x3d,0x22,
0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3d,0x22,
0x70,0x61,0x74,0x68,0x34,0x32,0x31,0x32,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x64,0x3d,0x22,0x6d,0x20,0x35,0x2e,0x35,0x39,0x38,0x38,0x30,0x30,
0x34,0x2c,0x33,0x32,0x2e,0x35,0x30,0x33,0x34,0x39,0x39,0x20,0x35,0x34,0x2e,0x32,
0x38,0x37,0x37,0x38,0x35,0x36,0x2c,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x73,0x74,0x79,0x6c,0x65,0x3d,0x22,0x66,0x69,0x6c,0x6c,0x3a,0x6e,
0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,0x6c,0x2d,0x72,0x75,0x6c,0x65,0x3a,0x65,0x76,
0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,
0x35,0x35,0x64,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x77,0x69,0x64,0x74,
0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,
0x63,0x61,0x70,0x3a,0x62,0x75,0x74,0x74,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,
0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,0x6e,0x3a,0x6d,0x69,0x74,0x65,0x72,0x3b,0x73,
0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,0x69,0x74,0x65,0x72,0x6c,0x69,0x6d,0x69,0x74,
0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x64,0x61,0x73,0x68,0x61,0x72,
0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,
0x6f,0x70,0x61,0x63,0x69,0x74,0x79,0x3a,0x31,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,
0x20,0x20,0x20,0x20,0x3c,0x70,0x61,0x74,0x68,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x73,0x6f,0x64,0x69,0x70,0x6f,0x64,0x69,0x3a,0x6e,0x6f,0x64,0x65,
0x74,0x79,0x70,0x65,0x73,0x3d,0x22,0x63,0x63,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x69,0x6e,0x6b,0x73,0x63,0x61,0x70,0x65,0x3a,0x63,0x6f,0x6e,
0x6e,0x65,0x63,0x74,0x6f,0x72,0x2d,0x63,0x75,0x72,0x76,0x61,0x74,0x75,0x72,0x65,
0x3d,0x22,0x30,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,
0x3d,0x22,0x70,0x61,0x74,0x68,0x34,0x32,0x31,0x34,0x22,0x0a,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x64,0x3d,0x22,0x4d,0x20,0x33,0x32,0x2e,0x35,0x30,0x36,
0x36,0x35,0x38,0x2c,0x35,0x2e,0x31,0x32,0x33,0x35,0x37,0x32,0x36,0x20,0x33,0x32,
0x2e,0x39,0x37,0x38,0x37,0x32,0x36,0x2c,0x35,0x38,0x2e,0x34,0x36,0x37,0x32,0x32,
0x33,0x22,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73,0x74,0x79,0x6c,
0x65,0x3d,0x22,0x66,0x69,0x6c,0x6c,0x3a,0x6e,0x6f,0x6e,0x65,0x3b,0x66,0x69,0x6c,
0x6c,0x2d,0x72,0x75,0x6c,0x65,0x3a,0x65,0x76,0x65,0x6e,0x6f,0x64,0x64,0x3b,0x73,
0x74,0x72,0x6f,0x6b,0x65,0x3a,0x23,0x30,0x30,0x35,0x35,0x64,0x34,0x3b,0x73,0x74,
0x72,0x6f,0x6b,0x65,0x2d,0x77,0x69,0x64,0x74,0x68,0x3a,0x31,0x36,0x3b,0x73,0x74,
0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x63,0x61,0x70,0x3a,0x62,0x75,0x74,
0x74,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6c,0x69,0x6e,0x65,0x6a,0x6f,0x69,
0x6e,0x3a,0x6d,0x69,0x74,0x65,0x72,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6d,
0x69,0x74,0x65,0x72,0x6c,0x69,0x6d,0x69,0x74,0x3a,0x34,0x3b,0x73,0x74,0x72,0x6f,
0x6b,0x65,0x2d,0x64,0x61,0x73,0x68,0x61,0x72,0x72,0x61,0x79,0x3a,0x6e,0x6f,0x6e,
0x65,0x3b,0x73,0x74,0x72,0x6f,0x6b,0x65,0x2d,0x6f,0x70,0x61,0x63,0x69,0x74,0x79,
0x3a,0x31,0x22,0x20,0x2f,0x3e,0x0a,0x20,0x20,0x20,0x20,0x3c,0x2f,0x67,0x3e,0x0a,
0x20,0x20,0x3c,0x2f,0x67,0x3e,0x0a,0x3c,0x2f,0x73,0x76,0x67,0x3e,0x0a,
};
public:
MARK_pixmap() {
CQPixmapCache::instance()->addData("MARK", data_, 6062);
}
};
static MARK_pixmap s_MARK_pixmap;
#endif
| [
"colinw@nc.rr.com"
] | colinw@nc.rr.com |
8b96d1f69f3098bfaf19776fd6f6a85ffa516bc2 | abd3a3385b33cd4d9f3e75fe013a7cd5bc4eada4 | /src/wallet/coinselection.h | d1d65ec608f35cce058abe9bd91eceae07bb6c38 | [
"MIT"
] | permissive | peercoin/peercoin | 1200f3d3bd0c0646829ccaad787e49a28e61806c | d15189ebd6084ccca2d20b594a224dff12409fd8 | refs/heads/master | 2023-08-18T06:32:01.286131 | 2023-05-26T07:37:13 | 2023-05-26T07:37:13 | 5,211,620 | 358 | 483 | MIT | 2023-09-13T23:00:42 | 2012-07-28T03:07:36 | C++ | UTF-8 | C++ | false | false | 10,364 | h | // Copyright (c) 2017-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_COINSELECTION_H
#define BITCOIN_WALLET_COINSELECTION_H
#include <consensus/amount.h>
#include <primitives/transaction.h>
#include <random.h>
#include <optional>
namespace wallet {
//! final minimum change amount after paying for fees
static const CAmount MIN_FINAL_CHANGE = MIN_TXOUT_AMOUNT;
/** A UTXO under consideration for use in funding a new transaction. */
class CInputCoin {
public:
CInputCoin(const CTransactionRef& tx, unsigned int i)
{
if (!tx)
throw std::invalid_argument("tx should not be null");
if (i >= tx->vout.size())
throw std::out_of_range("The output index is out of range");
outpoint = COutPoint(tx->GetHash(), i);
txout = tx->vout[i];
effective_value = txout.nValue;
}
CInputCoin(const CTransactionRef& tx, unsigned int i, int input_bytes) : CInputCoin(tx, i)
{
m_input_bytes = input_bytes;
}
CInputCoin(const COutPoint& outpoint_in, const CTxOut& txout_in)
{
outpoint = outpoint_in;
txout = txout_in;
effective_value = txout.nValue;
}
CInputCoin(const COutPoint& outpoint_in, const CTxOut& txout_in, int input_bytes) : CInputCoin(outpoint_in, txout_in)
{
m_input_bytes = input_bytes;
}
COutPoint outpoint;
CTxOut txout;
CAmount effective_value;
CAmount m_fee{0};
CAmount m_long_term_fee{0};
/** Pre-computed estimated size of this output as a fully-signed input in a transaction. Can be -1 if it could not be calculated */
int m_input_bytes{-1};
bool operator<(const CInputCoin& rhs) const {
return outpoint < rhs.outpoint;
}
bool operator!=(const CInputCoin& rhs) const {
return outpoint != rhs.outpoint;
}
bool operator==(const CInputCoin& rhs) const {
return outpoint == rhs.outpoint;
}
};
/** Parameters for one iteration of Coin Selection. */
struct CoinSelectionParams
{
/** Size of a change output in bytes, determined by the output type. */
size_t change_output_size = 0;
/** Size of the input to spend a change output in virtual bytes. */
size_t change_spend_size = 0;
/** Cost of creating the change output. */
CAmount m_change_fee{0};
/** Cost of creating the change output + cost of spending the change output in the future. */
CAmount m_cost_of_change{0};
/** Size of the transaction before coin selection, consisting of the header and recipient
* output(s), excluding the inputs and change output(s). */
size_t tx_noinputs_size = 0;
/** Indicate that we are subtracting the fee from outputs */
bool m_subtract_fee_outputs = false;
/** When true, always spend all (up to OUTPUT_GROUP_MAX_ENTRIES) or none of the outputs
* associated with the same address. This helps reduce privacy leaks resulting from address
* reuse. Dust outputs are not eligible to be added to output groups and thus not considered. */
bool m_avoid_partial_spends = false;
CoinSelectionParams(size_t change_output_size, size_t change_spend_size,
size_t tx_noinputs_size, bool avoid_partial) :
change_output_size(change_output_size),
change_spend_size(change_spend_size),
tx_noinputs_size(tx_noinputs_size),
m_avoid_partial_spends(avoid_partial)
{}
CoinSelectionParams() {}
};
/** Parameters for filtering which OutputGroups we may use in coin selection.
* We start by being very selective and requiring multiple confirmations and
* then get more permissive if we cannot fund the transaction. */
struct CoinEligibilityFilter
{
/** Minimum number of confirmations for outputs that we sent to ourselves.
* We may use unconfirmed UTXOs sent from ourselves, e.g. change outputs. */
const int conf_mine;
/** Minimum number of confirmations for outputs received from a different wallet. */
const int conf_theirs;
/** Maximum number of unconfirmed ancestors aggregated across all UTXOs in an OutputGroup. */
const uint64_t max_ancestors;
/** Maximum number of descendants that a single UTXO in the OutputGroup may have. */
const uint64_t max_descendants;
/** When avoid_reuse=true and there are full groups (OUTPUT_GROUP_MAX_ENTRIES), whether or not to use any partial groups.*/
const bool m_include_partial_groups{false};
CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_ancestors) {}
CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_descendants) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_descendants) {}
CoinEligibilityFilter(int conf_mine, int conf_theirs, uint64_t max_ancestors, uint64_t max_descendants, bool include_partial) : conf_mine(conf_mine), conf_theirs(conf_theirs), max_ancestors(max_ancestors), max_descendants(max_descendants), m_include_partial_groups(include_partial) {}
};
/** A group of UTXOs paid to the same output script. */
struct OutputGroup
{
/** The list of UTXOs contained in this output group. */
std::vector<CInputCoin> m_outputs;
/** Whether the UTXOs were sent by the wallet to itself. This is relevant because we may want at
* least a certain number of confirmations on UTXOs received from outside wallets while trusting
* our own UTXOs more. */
bool m_from_me{true};
/** The total value of the UTXOs in sum. */
CAmount m_value{0};
/** The minimum number of confirmations the UTXOs in the group have. Unconfirmed is 0. */
int m_depth{999};
/** The aggregated count of unconfirmed ancestors of all UTXOs in this
* group. Not deduplicated and may overestimate when ancestors are shared. */
size_t m_ancestors{0};
/** The maximum count of descendants of a single UTXO in this output group. */
size_t m_descendants{0};
/** The value of the UTXOs after deducting the cost of spending them at the effective feerate. */
CAmount effective_value{0};
/** The fee to spend these UTXOs at the effective feerate. */
CAmount fee{0};
/** Indicate that we are subtracting the fee from outputs.
* When true, the value that is used for coin selection is the UTXO's real value rather than effective value */
bool m_subtract_fee_outputs{false};
OutputGroup() {}
OutputGroup(const CoinSelectionParams& params) :
m_subtract_fee_outputs(params.m_subtract_fee_outputs)
{}
void Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants, bool positive_only);
bool EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const;
CAmount GetSelectionAmount() const;
};
/** Compute the waste for this result given the cost of change
* and the opportunity cost of spending these inputs now vs in the future.
* If change exists, waste = change_cost + inputs * (effective_feerate - long_term_feerate)
* If no change, waste = excess + inputs * (effective_feerate - long_term_feerate)
* where excess = selected_effective_value - target
* change_cost = effective_feerate * change_output_size + long_term_feerate * change_spend_size
*
* Note this function is separate from SelectionResult for the tests.
*
* @param[in] inputs The selected inputs
* @param[in] change_cost The cost of creating change and spending it in the future.
* Only used if there is change, in which case it must be positive.
* Must be 0 if there is no change.
* @param[in] target The amount targeted by the coin selection algorithm.
* @param[in] use_effective_value Whether to use the input's effective value (when true) or the real value (when false).
* @return The waste
*/
[[nodiscard]] CAmount GetSelectionWaste(const std::set<CInputCoin>& inputs, CAmount change_cost, CAmount target, bool use_effective_value = true);
struct SelectionResult
{
private:
/** Set of inputs selected by the algorithm to use in the transaction */
std::set<CInputCoin> m_selected_inputs;
/** The target the algorithm selected for. Note that this may not be equal to the recipient amount as it can include non-input fees */
const CAmount m_target;
/** Whether the input values for calculations should be the effective value (true) or normal value (false) */
bool m_use_effective{false};
/** The computed waste */
std::optional<CAmount> m_waste;
public:
explicit SelectionResult(const CAmount target)
: m_target(target) {}
SelectionResult() = delete;
/** Get the sum of the input values */
[[nodiscard]] CAmount GetSelectedValue() const;
void Clear();
void AddInput(const OutputGroup& group);
/** Calculates and stores the waste for this selection via GetSelectionWaste */
void ComputeAndSetWaste(CAmount change_cost);
[[nodiscard]] CAmount GetWaste() const;
/** Get m_selected_inputs */
const std::set<CInputCoin>& GetInputSet() const;
/** Get the vector of CInputCoins that will be used to fill in a CTransaction's vin */
std::vector<CInputCoin> GetShuffledInputVector() const;
bool operator<(SelectionResult other) const;
};
std::optional<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change);
/** Select coins by Single Random Draw. OutputGroups are selected randomly from the eligible
* outputs until the target is satisfied
*
* @param[in] utxo_pool The positive effective value OutputGroups eligible for selection
* @param[in] target_value The target value to select for
* @returns If successful, a SelectionResult, otherwise, std::nullopt
*/
std::optional<SelectionResult> SelectCoinsSRD(const std::vector<OutputGroup>& utxo_pool, CAmount target_value);
// Original coin selection algorithm as a fallback
std::optional<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue);
} // namespace wallet
#endif // BITCOIN_WALLET_COINSELECTION_H
| [
"backpacker69@protonmail.com"
] | backpacker69@protonmail.com |
0be2ddf3f5d4b733f8ab309a68ce88acdf74c7d2 | f9e3111ded6df3611bc3a8c0ff7602de01abbb95 | /zsl-golang/zsl/snark/libsnark/src/algebra/curves/mnt/mnt4/mnt4_g2.cpp | d1da1fc2cdebfc856ea43a8c107527a3972aab31 | [
"Apache-2.0",
"MIT"
] | permissive | kobigurk/zsl-q | fa74107c45c5e813f070dcac366b789ce2686c47 | 918385ee41a5c3a7e44a1fc97881e0801381b1f4 | refs/heads/master | 2020-04-03T05:51:33.901118 | 2018-10-28T10:19:14 | 2018-10-28T10:19:14 | 155,057,810 | 0 | 0 | Apache-2.0 | 2018-10-28T10:15:06 | 2018-10-28T10:15:05 | null | UTF-8 | C++ | false | false | 14,674 | cpp | /** @file
*****************************************************************************
Implementation of interfaces for the MNT4 G2 group.
See mnt4_g2.hpp .
*****************************************************************************
* @author This file is part of libsnark, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#include "algebra/curves/mnt/mnt4/mnt4_g2.hpp"
namespace libsnark {
#ifdef PROFILE_OP_COUNTS
long long mnt4_G2::add_cnt = 0;
long long mnt4_G2::dbl_cnt = 0;
#endif
std::vector<size_t> mnt4_G2::wnaf_window_table;
std::vector<size_t> mnt4_G2::fixed_base_exp_window_table;
mnt4_Fq2 mnt4_G2::twist;
mnt4_Fq2 mnt4_G2::coeff_a;
mnt4_Fq2 mnt4_G2::coeff_b;
mnt4_G2 mnt4_G2::G2_zero;
mnt4_G2 mnt4_G2::G2_one;
mnt4_Fq2 mnt4_G2::mul_by_a(const mnt4_Fq2 &elt)
{
return mnt4_Fq2(mnt4_twist_mul_by_a_c0 * elt.c0, mnt4_twist_mul_by_a_c1 * elt.c1);
}
mnt4_Fq2 mnt4_G2::mul_by_b(const mnt4_Fq2 &elt)
{
return mnt4_Fq2(mnt4_twist_mul_by_b_c0 * elt.c1, mnt4_twist_mul_by_b_c1 * elt.c0);
}
mnt4_G2::mnt4_G2()
{
this->X_ = G2_zero.X_;
this->Y_ = G2_zero.Y_;
this->Z_ = G2_zero.Z_;
}
void mnt4_G2::print() const
{
if (this->is_zero())
{
printf("O\n");
}
else
{
mnt4_G2 copy(*this);
copy.to_affine_coordinates();
gmp_printf("(%Nd*z + %Nd , %Nd*z + %Nd)\n",
copy.X_.c1.as_bigint().data, mnt4_Fq::num_limbs,
copy.X_.c0.as_bigint().data, mnt4_Fq::num_limbs,
copy.Y_.c1.as_bigint().data, mnt4_Fq::num_limbs,
copy.Y_.c0.as_bigint().data, mnt4_Fq::num_limbs);
}
}
void mnt4_G2::print_coordinates() const
{
if (this->is_zero())
{
printf("O\n");
}
else
{
gmp_printf("(%Nd*z + %Nd : %Nd*z + %Nd : %Nd*z + %Nd)\n",
this->X_.c1.as_bigint().data, mnt4_Fq::num_limbs,
this->X_.c0.as_bigint().data, mnt4_Fq::num_limbs,
this->Y_.c1.as_bigint().data, mnt4_Fq::num_limbs,
this->Y_.c0.as_bigint().data, mnt4_Fq::num_limbs,
this->Z_.c1.as_bigint().data, mnt4_Fq::num_limbs,
this->Z_.c0.as_bigint().data, mnt4_Fq::num_limbs);
}
}
void mnt4_G2::to_affine_coordinates()
{
if (this->is_zero())
{
this->X_ = mnt4_Fq2::zero();
this->Y_ = mnt4_Fq2::one();
this->Z_ = mnt4_Fq2::zero();
}
else
{
const mnt4_Fq2 Z_inv = Z_.inverse();
X_ = X_ * Z_inv;
Y_ = Y_ * Z_inv;
Z_ = mnt4_Fq2::one();
}
}
void mnt4_G2::to_special()
{
this->to_affine_coordinates();
}
bool mnt4_G2::is_special() const
{
return (this->is_zero() || this->Z_ == mnt4_Fq2::one());
}
bool mnt4_G2::is_zero() const
{
return (this->X_.is_zero() && this->Z_.is_zero());
}
bool mnt4_G2::operator==(const mnt4_G2 &other) const
{
if (this->is_zero())
{
return other.is_zero();
}
if (other.is_zero())
{
return false;
}
/* now neither is O */
// X1/Z1 = X2/Z2 <=> X1*Z2 = X2*Z1
if ((this->X_ * other.Z_) != (other.X_ * this->Z_))
{
return false;
}
// Y1/Z1 = Y2/Z2 <=> Y1*Z2 = Y2*Z1
if ((this->Y_ * other.Z_) != (other.Y_ * this->Z_))
{
return false;
}
return true;
}
bool mnt4_G2::operator!=(const mnt4_G2& other) const
{
return !(operator==(other));
}
mnt4_G2 mnt4_G2::operator+(const mnt4_G2 &other) const
{
// handle special cases having to do with O
if (this->is_zero())
{
return other;
}
if (other.is_zero())
{
return *this;
}
// no need to handle points of order 2,4
// (they cannot exist in a prime-order subgroup)
// handle double case, and then all the rest
/*
The code below is equivalent to (but faster than) the snippet below:
if (this->operator==(other))
{
return this->dbl();
}
else
{
return this->add(other);
}
*/
const mnt4_Fq2 X1Z2 = (this->X_) * (other.Z_); // X1Z2 = X1*Z2
const mnt4_Fq2 X2Z1 = (this->Z_) * (other.X_); // X2Z1 = X2*Z1
// (used both in add and double checks)
const mnt4_Fq2 Y1Z2 = (this->Y_) * (other.Z_); // Y1Z2 = Y1*Z2
const mnt4_Fq2 Y2Z1 = (this->Z_) * (other.Y_); // Y2Z1 = Y2*Z1
if (X1Z2 == X2Z1 && Y1Z2 == Y2Z1)
{
// perform dbl case
const mnt4_Fq2 XX = (this->X_).squared(); // XX = X1^2
const mnt4_Fq2 ZZ = (this->Z_).squared(); // ZZ = Z1^2
const mnt4_Fq2 w = mnt4_G2::mul_by_a(ZZ) + (XX + XX + XX); // w = a*ZZ + 3*XX
const mnt4_Fq2 Y1Z1 = (this->Y_) * (this->Z_);
const mnt4_Fq2 s = Y1Z1 + Y1Z1; // s = 2*Y1*Z1
const mnt4_Fq2 ss = s.squared(); // ss = s^2
const mnt4_Fq2 sss = s * ss; // sss = s*ss
const mnt4_Fq2 R = (this->Y_) * s; // R = Y1*s
const mnt4_Fq2 RR = R.squared(); // RR = R^2
const mnt4_Fq2 B = ((this->X_)+R).squared()-XX-RR; // B = (X1+R)^2 - XX - RR
const mnt4_Fq2 h = w.squared() - (B+B); // h = w^2 - 2*B
const mnt4_Fq2 X3 = h * s; // X3 = h*s
const mnt4_Fq2 Y3 = w * (B-h)-(RR+RR); // Y3 = w*(B-h) - 2*RR
const mnt4_Fq2 Z3 = sss; // Z3 = sss
return mnt4_G2(X3, Y3, Z3);
}
// if we have arrived here we are in the add case
const mnt4_Fq2 Z1Z2 = (this->Z_) * (other.Z_); // Z1Z2 = Z1*Z2
const mnt4_Fq2 u = Y2Z1 - Y1Z2; // u = Y2*Z1-Y1Z2
const mnt4_Fq2 uu = u.squared(); // uu = u^2
const mnt4_Fq2 v = X2Z1 - X1Z2; // v = X2*Z1-X1Z2
const mnt4_Fq2 vv = v.squared(); // vv = v^2
const mnt4_Fq2 vvv = v * vv; // vvv = v*vv
const mnt4_Fq2 R = vv * X1Z2; // R = vv*X1Z2
const mnt4_Fq2 A = uu * Z1Z2 - (vvv + R + R); // A = uu*Z1Z2 - vvv - 2*R
const mnt4_Fq2 X3 = v * A; // X3 = v*A
const mnt4_Fq2 Y3 = u * (R-A) - vvv * Y1Z2; // Y3 = u*(R-A) - vvv*Y1Z2
const mnt4_Fq2 Z3 = vvv * Z1Z2; // Z3 = vvv*Z1Z2
return mnt4_G2(X3, Y3, Z3);
}
mnt4_G2 mnt4_G2::operator-() const
{
return mnt4_G2(this->X_, -(this->Y_), this->Z_);
}
mnt4_G2 mnt4_G2::operator-(const mnt4_G2 &other) const
{
return (*this) + (-other);
}
mnt4_G2 mnt4_G2::add(const mnt4_G2 &other) const
{
// handle special cases having to do with O
if (this->is_zero())
{
return other;
}
if (other.is_zero())
{
return (*this);
}
// no need to handle points of order 2,4
// (they cannot exist in a prime-order subgroup)
// handle double case
if (this->operator==(other))
{
return this->dbl();
}
#ifdef PROFILE_OP_COUNTS
this->add_cnt++;
#endif
// NOTE: does not handle O and pts of order 2,4
// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#addition-add-1998-cmo-2
const mnt4_Fq2 Y1Z2 = (this->Y_) * (other.Z_); // Y1Z2 = Y1*Z2
const mnt4_Fq2 X1Z2 = (this->X_) * (other.Z_); // X1Z2 = X1*Z2
const mnt4_Fq2 Z1Z2 = (this->Z_) * (other.Z_); // Z1Z2 = Z1*Z2
const mnt4_Fq2 u = (other.Y_) * (this->Z_) - Y1Z2; // u = Y2*Z1-Y1Z2
const mnt4_Fq2 uu = u.squared(); // uu = u^2
const mnt4_Fq2 v = (other.X_) * (this->Z_) - X1Z2; // v = X2*Z1-X1Z2
const mnt4_Fq2 vv = v.squared(); // vv = v^2
const mnt4_Fq2 vvv = v * vv; // vvv = v*vv
const mnt4_Fq2 R = vv * X1Z2; // R = vv*X1Z2
const mnt4_Fq2 A = uu * Z1Z2 - (vvv + R + R); // A = uu*Z1Z2 - vvv - 2*R
const mnt4_Fq2 X3 = v * A; // X3 = v*A
const mnt4_Fq2 Y3 = u * (R-A) - vvv * Y1Z2; // Y3 = u*(R-A) - vvv*Y1Z2
const mnt4_Fq2 Z3 = vvv * Z1Z2; // Z3 = vvv*Z1Z2
return mnt4_G2(X3, Y3, Z3);
}
mnt4_G2 mnt4_G2::mixed_add(const mnt4_G2 &other) const
{
#ifdef PROFILE_OP_COUNTS
this->add_cnt++;
#endif
// NOTE: does not handle O and pts of order 2,4
// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#addition-add-1998-cmo-2
//assert(other.Z == mnt4_Fq2::one());
if (this->is_zero())
{
return other;
}
if (other.is_zero())
{
return (*this);
}
#ifdef DEBUG
assert(other.is_special());
#endif
const mnt4_Fq2 &X1Z2 = (this->X_); // X1Z2 = X1*Z2 (but other is special and not zero)
const mnt4_Fq2 X2Z1 = (this->Z_) * (other.X_); // X2Z1 = X2*Z1
// (used both in add and double checks)
const mnt4_Fq2 &Y1Z2 = (this->Y_); // Y1Z2 = Y1*Z2 (but other is special and not zero)
const mnt4_Fq2 Y2Z1 = (this->Z_) * (other.Y_); // Y2Z1 = Y2*Z1
if (X1Z2 == X2Z1 && Y1Z2 == Y2Z1)
{
return this->dbl();
}
const mnt4_Fq2 u = Y2Z1 - this->Y_; // u = Y2*Z1-Y1
const mnt4_Fq2 uu = u.squared(); // uu = u2
const mnt4_Fq2 v = X2Z1 - this->X_; // v = X2*Z1-X1
const mnt4_Fq2 vv = v.squared(); // vv = v2
const mnt4_Fq2 vvv = v*vv; // vvv = v*vv
const mnt4_Fq2 R = vv * this->X_; // R = vv*X1
const mnt4_Fq2 A = uu * this->Z_ - vvv - R - R; // A = uu*Z1-vvv-2*R
const mnt4_Fq2 X3 = v * A; // X3 = v*A
const mnt4_Fq2 Y3 = u*(R-A) - vvv * this->Y_; // Y3 = u*(R-A)-vvv*Y1
const mnt4_Fq2 Z3 = vvv * this->Z_; // Z3 = vvv*Z1
return mnt4_G2(X3, Y3, Z3);
}
mnt4_G2 mnt4_G2::dbl() const
{
#ifdef PROFILE_OP_COUNTS
this->dbl_cnt++;
#endif
if (this->is_zero())
{
return (*this);
}
else
{
// NOTE: does not handle O and pts of order 2,4
// http://www.hyperelliptic.org/EFD/g1p/auto-shortw-projective.html#doubling-dbl-2007-bl
const mnt4_Fq2 XX = (this->X_).squared(); // XX = X1^2
const mnt4_Fq2 ZZ = (this->Z_).squared(); // ZZ = Z1^2
const mnt4_Fq2 w = mnt4_G2::mul_by_a(ZZ) + (XX + XX + XX); // w = a*ZZ + 3*XX
const mnt4_Fq2 Y1Z1 = (this->Y_) * (this->Z_);
const mnt4_Fq2 s = Y1Z1 + Y1Z1; // s = 2*Y1*Z1
const mnt4_Fq2 ss = s.squared(); // ss = s^2
const mnt4_Fq2 sss = s * ss; // sss = s*ss
const mnt4_Fq2 R = (this->Y_) * s; // R = Y1*s
const mnt4_Fq2 RR = R.squared(); // RR = R^2
const mnt4_Fq2 B = ((this->X_)+R).squared()-XX-RR; // B = (X1+R)^2 - XX - RR
const mnt4_Fq2 h = w.squared() - (B+B); // h = w^2-2*B
const mnt4_Fq2 X3 = h * s; // X3 = h*s
const mnt4_Fq2 Y3 = w * (B-h)-(RR+RR); // Y3 = w*(B-h) - 2*RR
const mnt4_Fq2 Z3 = sss; // Z3 = sss
return mnt4_G2(X3, Y3, Z3);
}
}
mnt4_G2 mnt4_G2::mul_by_q() const
{
return mnt4_G2(mnt4_twist_mul_by_q_X * (this->X_).Frobenius_map(1),
mnt4_twist_mul_by_q_Y * (this->Y_).Frobenius_map(1),
(this->Z_).Frobenius_map(1));
}
bool mnt4_G2::is_well_formed() const
{
if (this->is_zero())
{
return true;
}
else
{
/*
y^2 = x^3 + ax + b
We are using projective, so equation we need to check is actually
(y/z)^2 = (x/z)^3 + a (x/z) + b
z y^2 = x^3 + a z^2 x + b z^3
z (y^2 - b z^2) = x ( x^2 + a z^2)
*/
const mnt4_Fq2 X2 = this->X_.squared();
const mnt4_Fq2 Y2 = this->Y_.squared();
const mnt4_Fq2 Z2 = this->Z_.squared();
const mnt4_Fq2 aZ2 = mnt4_twist_coeff_a * Z2;
return (this->Z_ * (Y2 - mnt4_twist_coeff_b * Z2) == this->X_ * (X2 + aZ2));
}
}
mnt4_G2 mnt4_G2::zero()
{
return G2_zero;
}
mnt4_G2 mnt4_G2::one()
{
return G2_one;
}
mnt4_G2 mnt4_G2::random_element()
{
return (mnt4_Fr::random_element().as_bigint()) * G2_one;
}
std::ostream& operator<<(std::ostream &out, const mnt4_G2 &g)
{
mnt4_G2 copy(g);
copy.to_affine_coordinates();
out << (copy.is_zero() ? 1 : 0) << OUTPUT_SEPARATOR;
#ifdef NO_PT_COMPRESSION
out << copy.X_ << OUTPUT_SEPARATOR << copy.Y_;
#else
/* storing LSB of Y */
out << copy.X_ << OUTPUT_SEPARATOR << (copy.Y_.c0.as_bigint().data[0] & 1);
#endif
return out;
}
std::istream& operator>>(std::istream &in, mnt4_G2 &g)
{
char is_zero;
mnt4_Fq2 tX, tY;
#ifdef NO_PT_COMPRESSION
in >> is_zero >> tX >> tY;
is_zero -= '0';
#else
in.read((char*)&is_zero, 1); // this reads is_zero;
is_zero -= '0';
consume_OUTPUT_SEPARATOR(in);
unsigned char Y_lsb;
in >> tX;
consume_OUTPUT_SEPARATOR(in);
in.read((char*)&Y_lsb, 1);
Y_lsb -= '0';
// y = +/- sqrt(x^3 + a*x + b)
if (!is_zero)
{
mnt4_Fq2 tX2 = tX.squared();
mnt4_Fq2 tY2 = (tX2 + mnt4_twist_coeff_a ) * tX + mnt4_twist_coeff_b;
tY = tY2.sqrt();
if ((tY.c0.as_bigint().data[0] & 1) != Y_lsb)
{
tY = -tY;
}
}
#endif
// using projective coordinates
if (!is_zero)
{
g.X_ = tX;
g.Y_ = tY;
g.Z_ = mnt4_Fq2::one();
}
else
{
g = mnt4_G2::zero();
}
return in;
}
template<>
void batch_to_special_all_non_zeros<mnt4_G2>(std::vector<mnt4_G2> &vec)
{
std::vector<mnt4_Fq2> Z_vec;
Z_vec.reserve(vec.size());
for (auto &el: vec)
{
Z_vec.emplace_back(el.Z());
}
batch_invert<mnt4_Fq2>(Z_vec);
const mnt4_Fq2 one = mnt4_Fq2::one();
for (size_t i = 0; i < vec.size(); ++i)
{
vec[i] = mnt4_G2(vec[i].X() * Z_vec[i], vec[i].Y() * Z_vec[i], one);
}
}
} // libsnark
| [
"simon@bitcartel.com"
] | simon@bitcartel.com |
dc769301cbd82003e56836e75393abee9247b805 | 31ba4644568aed5f1865474f666ae7d87664312f | /new_fitter/backup/junoSpectrum_old.cc | 263c70a1e2455d8592d47e5549ac45090e083968 | [] | no_license | YMTheory/energyModel_Fit | 11bf4a3350fb770f075585b16bc4adc9ec64802c | db6b236827d934ddf713e54d7f744d23fba102c5 | refs/heads/master | 2022-08-13T08:07:30.594576 | 2022-07-21T10:08:16 | 2022-07-21T10:08:16 | 253,709,247 | 0 | 0 | null | 2021-03-16T01:29:52 | 2020-04-07T06:42:00 | C++ | UTF-8 | C++ | false | false | 11,840 | cc | #include "junoSpectrum.hh"
#include "electronQuench.hh"
#include "electronCerenkov.hh"
#include "junoParameters.hh"
#include <TFile.h>
#include <TTree.h>
#include <TH1.h>
#include <iostream>
using namespace std;
double junoSpectrum::m_pdf_eTru[2000];
double junoSpectrum::m_pdf_prob[2000];
double junoSpectrum::m_max_eTru;
double junoSpectrum::m_gammaScale = 0;
junoSpectrum::junoSpectrum( int nMaxBins,
int nMaxBinsData,
int nMaxBr,
int nMaxGam,
double eMin,
double eMax,
double fitMin,
double fitMax,
string name)
{
std::cout << " nMaxBins = " << nMaxBins << std::endl;
std::cout << " nMaxBinsData = " << nMaxBinsData << std::endl;
std::cout << " nMaxBr = " << nMaxBr << std::endl;
std::cout << " nMaxGam = " << nMaxGam << std::endl;
m_nBins = nMaxBins;
m_nBinsData = nMaxBinsData;
m_nBr = nMaxBr;
m_nGam = nMaxGam;
m_eMin = eMin;
m_eMax = eMax;
m_fitMin = fitMin;
m_fitMax = fitMax;
m_name = name;
m_title = name;
m_binCenter = new double[nMaxBins];
m_eVis = new double[nMaxBins];
m_eVisBck = new double[nMaxBins];
m_eRec = new double[nMaxBins];
m_eRecBck = new double[nMaxBins];
m_eTheo = new double[nMaxBinsData];
m_eData = new double[nMaxBinsData];
m_eDataErr = new double[nMaxBinsData];
m_eTru = new double*[nMaxBr];
m_eTruBck = new double*[nMaxBr];
m_eTruAlp = new double [nMaxBr];
for (int branchIdx = 0; branchIdx < nMaxBr; branchIdx++)
{
m_eTru [branchIdx] = new double[nMaxBins];
m_eTruBck[branchIdx] = new double[nMaxBins];
}
m_eTruGam = new double*[nMaxBr];
m_eTruGamStr= new int*[nMaxBr];
for (int branchIdx = 0; branchIdx < nMaxBr; branchIdx++)
{
m_eTruGam[branchIdx] = new double[nMaxGam];
m_eTruGamStr[branchIdx] = new int[nMaxGam];
}
}
junoSpectrum::~junoSpectrum()
{
std::cout << " Destroying " << m_name << " <------" << std::endl;
//std::cout << " **** m_nBr = " << m_nBr << std::endl;
for (int branchIdx = 0; branchIdx < m_nBr; branchIdx++)
{
delete [] m_eTru [branchIdx];
delete [] m_eTruBck[branchIdx];
}
for (int branchIdx = 0; branchIdx < m_nBr; branchIdx++)
{
delete [] m_eTruGam[branchIdx];
}
delete [] m_binCenter;
delete [] m_eVis ;
delete [] m_eVisBck ;
delete [] m_eRec ;
delete [] m_eRecBck ;
delete [] m_eTheo ;
delete [] m_eData ;
delete [] m_eDataErr ;
delete [] m_eTru ;
delete [] m_eTruBck ;
delete [] m_eTruGam ;
delete [] m_eTruAlp ;
}
void junoSpectrum::LoadData(string fileName)
{
m_opt = true;
m_dataIsLoaded = false;
m_binWidth = (m_eMax-m_eMin)/double(m_nBins);
m_fitMinBin = int((m_fitMin-m_eMin)/m_binWidth);
m_fitMaxBin = int((m_fitMax-m_eMin)/m_binWidth);
for(int branchIdx=0; branchIdx<m_nBr; branchIdx++)
{
for(int i=0; i<m_nBins; i++)
{
m_binCenter[i] = m_eMin + m_binWidth*(i+0.5); //cout << "binCenter: " << m_binCenter[i] << endl;
m_eTru [branchIdx][i] = 0;
m_eTruBck[branchIdx][i] = 0;
}
for(int gamIdx=0; gamIdx<m_nGam; gamIdx++)
{
m_eTruGam[branchIdx][gamIdx] = 0;
}
m_eTruAlp[branchIdx] = 0;
}
InitTheo();
//if (fileName.find(".root") != std::string::npos)
InitData(fileName);
//else
// InitToyMC(fileName);
m_dataIsLoaded = true;
cout << " finished preparation of " << m_name << " data <------ " << endl;
}
void junoSpectrum::TheoHistTree(string filename, int isotope)
{
double energyScale = 1.0;
TFile *file = new TFile(filename.c_str());
TTree *tree = (TTree*)file->Get("T");
double eGamma[10];
int eGammaStr[10];
int nGamma,branchNumber;
double branchRatio;
double weight,weight1;
tree->SetBranchAddress("num" ,&branchNumber);
tree->SetBranchAddress("BR" ,&branchRatio);
tree->SetBranchAddress("numPhoton",&nGamma);
tree->SetBranchAddress("photonE" ,eGamma);
tree->SetBranchAddress("photonName", eGammaStr);
//if(m_name=="B12")
std::cout << " R*******eading theory hist " << std::endl;
std::cout << "total branch number : " << tree->GetEntries() << endl;
for (int branchIdx=0;branchIdx!=tree->GetEntries();branchIdx++){
tree->GetEntry(branchIdx);
//if(m_name=="B12")
std::cout << " ------> " << branchIdx << " with " << nGamma << " gamma and branch ratio: "<< branchRatio << std::endl;
/// gammas
for (int gamIdx=0;gamIdx!=nGamma;gamIdx++)
{
m_eTruGam[branchIdx][gamIdx] = eGamma[gamIdx]/energyScale;
m_eTruGamStr[branchIdx][gamIdx] = eGammaStr[gamIdx];
std::cout << eGamma[gamIdx] << " " << eGammaStr[gamIdx] << std::endl;
//if(m_name=="B12")
}
/// electrons
TH1F* electronHist = (TH1F*)file->Get(Form("hh%d",branchNumber));
for (int binIdx=0;binIdx!=m_nBins;binIdx++)
{
weight = electronHist->Interpolate(m_binCenter[binIdx]*energyScale);
if(isotope==0)
m_eTru[branchIdx][binIdx] = branchRatio * weight;
if(isotope==1)
m_eTruBck[branchIdx][binIdx] = branchRatio * weight;
}
delete electronHist;
}
delete tree;
file->Close();
delete file;
}
void junoSpectrum::InitData(string fileName)
{
std::cout << " >>> Loading spectrum data from " << fileName << endl;
DataHist(fileName);
}
void junoSpectrum::DataHist(string fileName)
{
TFile* file = new TFile(fileName.c_str());
TH1F* sigH = (TH1F*)file->Get("Michel");
for (int i=0; i!=m_nBinsData;i++)
{
double content = sigH->GetBinContent(i+1);
double error = sigH->GetBinError (i+1);
m_eData [i] = content;
m_eDataErr[i] = error;
}
delete sigH;
file->Close();
delete file;
}
void junoSpectrum::Normalize()
{
int rebin = m_nBins/m_nBinsData;
double binWidthData = m_binWidth * rebin;
double nTheo = 0;
double nData = 0;
for (int i = 0; i < m_nBinsData; i++)
{
m_eTheo[i] = 0;
for (int j = 0; j < rebin; j++){
m_eTheo[i] += m_eVis[i*rebin+j];
}
if(i*binWidthData>m_fitMin && i*binWidthData<m_fitMax)
{
nTheo += m_eTheo[i];
nData += m_eData[i];
}
}
double scale = 1;
if( nTheo!=0 ) { scale = nData/nTheo; }
for (int i = 0; i < m_nBinsData; i++)
{
m_eTheo[i] *= scale;
}
for (int i = 0; i < m_nBins; i++)
{
m_eVis [i] *= scale;
m_eVisBck[i] *= scale;
}
}
void junoSpectrum::ApplyScintillatorNL()
{
for(int i=0; i<m_nBins; i++) {
m_eVis [i] = 0;
m_eVisBck[i] = 0;
}
int newBin, newBinBck;
int newBinLow,newBinLowBck;
int newBinHig,newBinHigBck;
double bias,biasBck;
double eTru;
double eVis,eVisBck;
double eVisElec;
vector<double> eVisGam;
double eVisAnn = 2.* 0.511;
for(int branchIdx=0; branchIdx<m_nBr; branchIdx++)
{
//eVisGam[branchIdx] = 0;
eVisGam.push_back(0);
for (int gamIdx = 0; gamIdx < m_nGam; gamIdx++)
{
//if(m_eTruGam[branchIdx][gamIdx]>100)
//eVisGam[branchIdx] = 0.9;
//else
if(m_eTruGam[branchIdx][gamIdx]==0) break;
//if(m_eTruGam[branchIdx][gamIdx]<1000)
//if(m_eTruGam[branchIdx][gamIdx]>0)
//eVisGam[branchIdx] += m_eTruGam[branchIdx][gamIdx];
eVisGam[branchIdx] += EvisGamma(to_string(m_eTruGamStr[branchIdx][gamIdx]))*m_eTruGam[branchIdx][gamIdx] * (1+m_gammaScale);
//eVisGam[branchIdx] += GetEVisGamma(m_eTruGam[branchIdx][gamIdx]);
//eVisGam[branchIdx] = 0.9;
}
//if(m_eTruAlp[branchIdx]>0) {
////std::cout << " ALPEVIS = " << m_eTruAlp[branchIdx]*dybEnergyModel::AlphaNL(m_eTruAlp[branchIdx]) << std::endl;
//eVisGam[branchIdx] += m_eTruAlp[branchIdx]*dybEnergyModel::AlphaNL(m_eTruAlp[branchIdx]/3.);
//}
}
//if(m_name == "B12") eVisGam[1] = 4.47167;
/// apply scintillator NL
for(int i=0; i<m_nBins; i++)
{
eTru = m_binCenter[i];
eVisElec = eTru;
eVisElec = eTru * (electronQuench::ScintillatorNL(eTru)+electronCerenkov::getCerenkovPE(eTru));
if(is_positron) eVisElec += 2*EvisGamma("511")*0.511 * (1+m_gammaScale) ;
//if(is_positron) eVisElec += 2*0.467167;
//cout << eTru << " " << electronQuench::getBirk1() << " " << electronQuench::ScintillatorNL(eTru)<< " " << electronCerenkov::getkC() << " " << eVisElec << endl;
for(int branchIdx=0; branchIdx<m_nBr; branchIdx++)
{
eVis = eVisElec + eVisGam[branchIdx];
if(m_name=="B12" and branchIdx==2) eVis += 0.5; // 3-alpha branch
eVisBck = eVis + eVisAnn;
//newBinSig = int(eVisSig/m_binWidth);
//newBinBck = int(eVisBck/m_binWidth);
newBinLow = int((eVis -m_eMin)/m_binWidth);
newBinLowBck = int((eVisBck-m_eMin)/m_binWidth);
newBinHig = int((eVis -m_eMin)/m_binWidth)+1;
newBinHigBck = int((eVisBck-m_eMin)/m_binWidth)+1;
bias = (eVis -m_eMin - newBinLow *m_binWidth)/m_binWidth;
biasBck = (eVisBck -m_eMin - newBinLowBck*m_binWidth)/m_binWidth;
//cout << newBinLow << " " << newBinHig << " " << bias << endl;
//if(newBinSig<0) newBinSig=0;
//if(newBinBck<0) newBinBck=0;
//if(newBinSig>=m_nBins) newBinSig=m_nBins-1;
//if(newBinBck>=m_nBins) newBinBck=m_nBins-1;
//std::cout << " newBinSig = " << newBinSig << std::endl;
//if(i>6500&&i<7000)
//std::cout << branchIdx << "/" << i << ": newBinHigBck = " << newBinHigBck << std::endl;
if(newBinLow<m_nBins) m_eVis [newBinLow ] += (1-bias )*m_eTru [branchIdx][i];
if(newBinLowBck<m_nBins) m_eVisBck[newBinLowBck] += (1-biasBck)*m_eTruBck[branchIdx][i];
if(newBinHig<m_nBins) m_eVis [newBinHig ] += bias *m_eTru [branchIdx][i];
if(newBinHigBck<m_nBins) m_eVisBck[newBinHigBck] += biasBck *m_eTruBck[branchIdx][i];
}
}
//for(int j=0; j<m_nBins; j++) {
// cout << m_eVis[j] << endl;
//}
}
double junoSpectrum::GetChi2(int nDoF)
{
ApplyScintillatorNL ();
Normalize ();
double chi2 = 0;
int rebin = m_nBins / m_nBinsData;
double binWidthData = m_binWidth * rebin;
m_nData = 0;
for(int i=0; i < m_nBinsData; i++) {
if(i*binWidthData<m_fitMin or binWidthData*i>m_fitMax-0.1) continue;
if( m_eDataErr[i]!=0 ) {
chi2 += pow( (m_eData[i] - m_eTheo[i])/m_eDataErr[i], 2);
m_nData++;
}
}
cout << m_name << " chi2: " << chi2 << " with nData : " << m_nData << endl;
if(nDoF>0) chi2 /= double(m_nData - nDoF);
return chi2;
}
double junoSpectrum::EvisGamma(string eTru)
{
TFile file(junoParameters::gammaPdf_File.c_str(), "read");
string pdfName = "gamma"+eTru+"keV";
TH1D* gGammaPdf = (TH1D*)file.Get(pdfName.c_str());
if(!gGammaPdf) cout << "No Such Pdf : " << pdfName << endl;
//cout << "Read " << pdfName << " P.d.f ..." << endl;
for(int i=0; i<gGammaPdf->GetNbinsX(); i++) {
m_pdf_eTru[i] = gGammaPdf->GetBinCenter(i+1);
m_pdf_prob[i] = gGammaPdf->GetBinContent(i+1);
if (m_pdf_prob[i] > 0) m_max_eTru = i; // max energy cut ...
}
file.Close();
double numerator = 0.; double denominator = 0.;
for(int iBin=1; iBin<m_max_eTru; iBin++) {
double E1 = m_pdf_eTru[iBin-1];
double E2 = m_pdf_eTru[iBin];
double prob1 = m_pdf_prob[iBin-1];
double prob2 = m_pdf_prob[iBin];
double fNL1 = electronQuench::ScintillatorNL(E1) + electronCerenkov::getCerenkovPE(E1);
double fNL2 = electronQuench::ScintillatorNL(E2) + electronCerenkov::getCerenkovPE(E2);
numerator += ( prob1*E1*fNL1 + prob2*E2*fNL2 ) * (E2-E1) /2.;
denominator += (prob1*E1 + prob2*E2) * (E2-E1)/ 2.;
}
if(denominator ==0) { cout << " >> Error Happens While CalculateGammaNL <<<" << endl; return 0;}
return numerator/denominator;
}
| [
"932899789@qq.com"
] | 932899789@qq.com |
0dc1fc9d6683c231b4dc913d855259f5f4cc0da3 | 3c2625d622bf17b9b72b31a1bd4053fedb1bc2c0 | /JJlib/calculator/JJCalc.h | c63a4d84c9ee307c107409cd0aa99862ed037e91 | [] | no_license | harion01/JJUtil | 578cd344b1a5420e8bfe37b0078651c5bf5186ca | 36ff9a05d24892b631eef2b50c7a0f690eeb235b | refs/heads/master | 2021-01-12T05:25:18.266422 | 2017-06-01T05:39:20 | 2017-06-01T05:39:20 | 77,925,894 | 1 | 0 | null | 2017-02-05T04:56:05 | 2017-01-03T14:49:02 | C++ | UTF-8 | C++ | false | false | 286 | h | #ifndef JJCALC_H
#define JJCALC_H
#include "JJparser.h"
#include <iostream>
#include <stack>
class JJcalc : private JJparser{
private:
int GetPriority(string Operator);
string InToPost(string InfixExpression);
public:
double Calculate(string InfixExpression);
};
#endif
| [
"harion01@gmail.com"
] | harion01@gmail.com |
bb5615bec71fe1ea15bc343cb16555f416881e7e | 381d605da20ca3342687e26c5bd00936fe7a46e7 | /Hackerrank/CountingValleys.cpp | e04e20d179ed6a35b705ec50af505fe042095ea0 | [] | no_license | z0CoolCS/CompetitiveProgramming | 4a4c278533001a0a4e8440ecfba9c7a4bb8132db | 0894645c918f316c2ce6ddc5fd5fb20af6c8b071 | refs/heads/master | 2023-04-28T08:15:29.245592 | 2021-04-20T01:02:28 | 2021-04-20T01:02:28 | 228,505,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 909 | cpp | #include <bits/stdc++.h>
using namespace std;
// Complete the countingValleys function below.
int countingValleys(int n, string s) {
int cont=0,ind=-1;
bool faro=false;
for(int i=0;i<n;i++){
if(s[i]=='U'){
if(ind!=-1){
faro=false;
if(i-1-ind>0)
cont++;
ind=-1;
}
}
else{
if(!faro){
ind=i;
faro=true;
}
else if(i==n-1){
if(i-1-ind>0)
cont++;
}
}
}
return cont;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin, s);
int result = countingValleys(n, s);
fout << result << "\n";
fout.close();
return 0;
}
| [
"giordano.alvitez@utec.edu.pe"
] | giordano.alvitez@utec.edu.pe |
8ba4433b4d80ea2d9d3d5d9e6d44144f5247d0ff | f1fa28cd2c931133b156b61e8d2795da50bed504 | /cppAlgos/146lruCache.cpp | 3656835cdc8e0352d713379889aaedb2361c4765 | [] | no_license | hashsequence/CPP_Prac | 041da65c75f39737200a0362dafa26d5dccb009c | 7cbdc9dfa2fdc238168a48780580db8247ca7a14 | refs/heads/master | 2023-04-07T18:01:27.112498 | 2023-03-30T07:36:47 | 2023-03-30T07:36:47 | 173,832,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,437 | cpp | /*
146. LRU Cache
Medium
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 ); // 2 is capacity
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
solution:
I can use an unorderd_map to have O(1) access to the element for retrieval
and also O(1) insert
however how do I keep track of which items are used the most,
I can implement a doubly linked list
and put the least recently used is the head
*/
class LRUCache {
public:
struct Node {
int key;
int value;
Node* next;
Node* prev;
Node(int key, int value) : key(key), value(value) {
next = nullptr;
prev = nullptr;
}
};
class LinkedList {
public:
Node* head;
Node* tail;
int size;
int capacity;
LinkedList() {}
LinkedList(int capacity ) : capacity(capacity) {
size = 0;
head = nullptr;
tail = nullptr;
}
Node* popFront() {
if (size == 0) {
return nullptr;
}
if (size == 1) {
Node* delNode = head;
head = nullptr;
tail = nullptr;
size--;
return delNode;
}
if (size > 1) {
Node* delNode = head;
head = head->next;
head->prev = nullptr;
size--;
return delNode;
}
return nullptr;
}
Node* popEnd() {
if (size == 0) {
return nullptr;
}
if (size == 1) {
Node* delNode = head;
head = nullptr;
tail = nullptr;
size--;
return delNode;
}
if (size > 1) {
Node* delNode = tail;
tail = tail->prev;
tail->next = nullptr;
size--;
return delNode;
}
return nullptr;
}
void insert(Node* node) {
if (size == 0) {
head = node;
head->prev = nullptr;
head->next = nullptr;
tail = head;
size++;
return;
}
if (size > 0) {
tail->next = node;
node->prev = tail;
tail = node;
tail->next = nullptr;
size++;
return;
}
}
Node* remove(Node* node) {
if (node == nullptr || size == 0) {
return node;
}
if (size >= 1) {
if (node == head) {
return popFront();
}
if (node == tail) {
return popEnd();
}
node->prev->next = node->next;
node->next->prev = node->prev;
size--;
return node;
}
return nullptr;
}
~LinkedList() {
while (size > 0) {
popFront();
}
}
};
unordered_map<int,Node*> mp;
LinkedList ls;
int cap;
int size;
LRUCache(int capacity) {
cap = capacity;
size = 0;
ls = LinkedList(capacity);
}
int get(int key) {
if (mp.find(key) != mp.end()){
if (size == 1) {
return mp[key]->value;
} else if (size > 1) {
ls.remove(mp[key]);
ls.insert(mp[key]);
}
return mp[key]->value;
}
return -1;
}
void put(int key, int value) {
if (mp.find(key) == mp.end()) {
Node* nNode = new Node(key, value);
if (size == cap) {
Node* delNode = ls.popFront();
mp.erase(delNode->key);
delete delNode;
size--;
}
mp[key] = nNode;
ls.insert(nNode);
size++;
} else {
Node* delNode = mp.find(key)->second;
ls.remove(delNode);
mp.erase(key);
delete delNode;
Node* nNode = new Node(key, value);
mp[key] = nNode;
ls.insert(nNode);
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
| [
"noreply@github.com"
] | noreply@github.com |
e03c2a7e9c7a5a77cc67450398972c4d9d422054 | 3c43234dced51ced077952ee43c2f91d7a11a2ec | /src/qt/sendcoinsdialog.cpp | 24f57053f7b038b270425dc6fe3e03bc827f0561 | [
"MIT"
] | permissive | franksalinas2/xfs | 80e354f89891662966b670bdfdddbb2ed1740e5c | bd9757101f91d9bb4f69fb33ccf433adcbb20bc2 | refs/heads/master | 2021-01-13T07:12:50.973631 | 2016-10-20T17:55:33 | 2016-10-20T17:55:33 | 71,486,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,914 | cpp | #include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "init.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "addressbookpage.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "coincontrol.h"
#include "coincontroldialog.h"
#include <QMessageBox>
#include <QLocale>
#include <QTextDocument>
#include <QScrollBar>
#include <QClipboard>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a FrankSalinasCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)"));
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont());
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &)));
// Coin Control: clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// Coin Control
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels()));
ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus;
if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
sendstatus = model->sendCoins(recipients);
else
sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
CoinControlDialog::coinControl->UnSelectAll();
coinControlUpdateLabels();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
QCoreApplication::instance()->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(stake);
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
QApplication::clipboard()->setText(ui->labelCoinControlBytes->text());
}
// Coin Control: copy label "Priority" to clipboard
void SendCoinsDialog::coinControlClipboardPriority()
{
QApplication::clipboard()->setText(ui->labelCoinControlPriority->text());
}
// Coin Control: copy label "Low output" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
CoinControlDialog::coinControl->SetNull();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg;
dlg.setModel(model);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (model)
{
if (state == Qt::Checked)
CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get();
else
CoinControlDialog::coinControl->destChange = CNoDestination();
}
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString & text)
{
if (model)
{
CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get();
// label for the change address
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
if (text.isEmpty())
ui->labelCoinControlChangeLabel->setText("");
else if (!CBitcoinAddress(text.toStdString()).IsValid())
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid FrankSalinasCoin address"));
}
else
{
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
{
CPubKey pubkey;
CKeyID keyid;
CBitcoinAddress(text.toStdString()).GetKeyID(keyid);
if (model->getPubKey(keyid, pubkey))
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
else
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address"));
}
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
return;
// set pay amounts
CoinControlDialog::payAmounts.clear();
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
CoinControlDialog::payAmounts.append(entry->getValue().amount);
}
if (CoinControlDialog::coinControl->HasSelected())
{
// actual coin control calculation
CoinControlDialog::updateLabels(model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
}
else
{
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
| [
"empowrcoin@gmail.com"
] | empowrcoin@gmail.com |
eaa7d4a1f5b90ed116160fb7dd6d6c82a805893e | 76f0efb245ff0013e0428ee7636e72dc288832ab | /out/Default/gen/device/bluetooth/public/interfaces/bluetooth_uuid.mojom-blink.h | b796bdd4e90d891d1a813b5c957f000f1237ffa2 | [] | no_license | dckristiono/chromium | e8845d2a8754f39e0ca1d3d3d44d01231957367c | 8ad7c1bd5778bfda3347cf6b30ef60d3e4d7c0b9 | refs/heads/master | 2020-04-22T02:34:41.775069 | 2016-08-24T14:05:09 | 2016-08-24T14:05:09 | 66,465,243 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,583 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_BLUETOOTH_PUBLIC_INTERFACES_BLUETOOTH_UUID_MOJOM_BLINK_H_
#define DEVICE_BLUETOOTH_PUBLIC_INTERFACES_BLUETOOTH_UUID_MOJOM_BLINK_H_
#include <stdint.h>
#include <type_traits>
#include <utility>
#include "base/callback.h"
#include "base/optional.h"
#include "mojo/public/cpp/bindings/array_data_view.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr_info.h"
#include "mojo/public/cpp/bindings/associated_interface_request.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/lib/control_message_handler.h"
#include "mojo/public/cpp/bindings/lib/control_message_proxy.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/lib/union_accessor.h"
#include "mojo/public/cpp/bindings/map.h"
#include "mojo/public/cpp/bindings/map_data_view.h"
#include "mojo/public/cpp/bindings/message_filter.h"
#include "mojo/public/cpp/bindings/native_struct.h"
#include "mojo/public/cpp/bindings/native_struct_data_view.h"
#include "mojo/public/cpp/bindings/no_interface.h"
#include "mojo/public/cpp/bindings/string_data_view.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
#include "mojo/public/cpp/bindings/union_traits.h"
#include "device/bluetooth/public/interfaces/bluetooth_uuid.mojom-shared.h"
#include "mojo/public/cpp/bindings/wtf_array.h"
#include "mojo/public/cpp/bindings/wtf_map.h"
#include "third_party/WebKit/Source/wtf/Optional.h"
#include "third_party/WebKit/Source/wtf/text/WTFString.h"
namespace device {
namespace mojom {
namespace blink {
class BluetoothUUID;
class BluetoothUUIDDataView;
using BluetoothUUIDPtr = mojo::InlinedStructPtr<BluetoothUUID>;
class BluetoothUUID {
public:
using DataView = BluetoothUUIDDataView;
using Data_ = internal::BluetoothUUID_Data;
static BluetoothUUIDPtr New();
template <typename U>
static BluetoothUUIDPtr From(const U& u) {
return mojo::TypeConverter<BluetoothUUIDPtr, U>::Convert(u);
}
template <typename U>
U To() const {
return mojo::TypeConverter<U, BluetoothUUID>::Convert(*this);
}
BluetoothUUID();
~BluetoothUUID();
// Clone() is a template so it is only instantiated if it is used. Thus, the
// bindings generator does not need to know whether Clone() or copy
// constructor/assignment are available for members.
template <typename StructPtrType = BluetoothUUIDPtr>
BluetoothUUIDPtr Clone() const;
// Equals() is a template so it is only instantiated if it is used. Thus, the
// bindings generator does not need to know whether Equals() or == operator
// are available for members.
template <typename T,
typename std::enable_if<std::is_same<
T, BluetoothUUID>::value>::type* = nullptr>
bool Equals(const T& other) const;
template <typename UserType>
static mojo::WTFArray<uint8_t> Serialize(UserType* input) {
return mojo::internal::StructSerializeImpl<
BluetoothUUIDPtr, mojo::WTFArray<uint8_t>>(input);
}
template <typename UserType>
static bool Deserialize(const mojo::WTFArray<uint8_t>& input,
UserType* output) {
return mojo::internal::StructDeserializeImpl<
BluetoothUUIDPtr, mojo::WTFArray<uint8_t>>(
input, output);
}
WTF::String uuid;
};
class BluetoothUUIDDataView {
public:
BluetoothUUIDDataView() {}
BluetoothUUIDDataView(
internal::BluetoothUUID_Data* data,
mojo::internal::SerializationContext* context)
: data_(data), context_(context) {}
bool is_null() const { return !data_; }
inline void GetUuidDataView(
mojo::StringDataView* output);
template <typename UserType>
bool ReadUuid(UserType* output) {
auto pointer = data_->uuid.Get();
return mojo::internal::Deserialize<mojo::String>(
pointer, output, context_);
}
private:
internal::BluetoothUUID_Data* data_ = nullptr;
mojo::internal::SerializationContext* context_ = nullptr;
};
} // namespace blink
} // namespace mojom
} // namespace device
namespace mojo {
namespace internal {
template <>
struct DataViewTraits<::device::mojom::blink::BluetoothUUIDDataView> {
using MojomType = ::device::mojom::blink::BluetoothUUIDPtr;
};
} // namespace internal
} // namespace mojo
namespace device {
namespace mojom {
namespace blink {
template <typename StructPtrType>
BluetoothUUIDPtr BluetoothUUID::Clone() const {
// Use StructPtrType to prevent the compiler from trying to compile this
// without being asked.
StructPtrType rv(New());
rv->uuid = mojo::internal::Clone(uuid);
return rv;
}
template <typename T,
typename std::enable_if<std::is_same<
T, BluetoothUUID>::value>::type*>
bool BluetoothUUID::Equals(const T& other) const {
if (!mojo::internal::Equals(this->uuid, other.uuid))
return false;
return true;
}
inline void BluetoothUUIDDataView::GetUuidDataView(
mojo::StringDataView* output) {
auto pointer = data_->uuid.Get();
*output = mojo::StringDataView(pointer, context_);
}
} // namespace blink
} // namespace mojom
} // namespace device
namespace mojo {
template <>
struct StructTraits<::device::mojom::blink::BluetoothUUID, ::device::mojom::blink::BluetoothUUIDPtr> {
static bool IsNull(const ::device::mojom::blink::BluetoothUUIDPtr& input) { return !input; }
static void SetToNull(::device::mojom::blink::BluetoothUUIDPtr* output) { output->reset(); }
static decltype(::device::mojom::blink::BluetoothUUID::uuid)& uuid(
::device::mojom::blink::BluetoothUUIDPtr& input) {
return input->uuid;
}
static bool Read(::device::mojom::blink::BluetoothUUIDDataView input, ::device::mojom::blink::BluetoothUUIDPtr* output);
};
namespace internal {
template <typename MaybeConstUserType>
struct Serializer<::device::mojom::blink::BluetoothUUIDPtr, MaybeConstUserType> {
using UserType = typename std::remove_const<MaybeConstUserType>::type;
using Traits = StructTraits<::device::mojom::blink::BluetoothUUID, UserType>;
static size_t PrepareToSerialize(MaybeConstUserType& input,
SerializationContext* context) {
if (CallIsNullIfExists<Traits>(input))
return 0;
void* custom_context = CustomContextHelper<Traits>::SetUp(input, context);
ALLOW_UNUSED_LOCAL(custom_context);
size_t size = sizeof(::device::mojom::internal::BluetoothUUID_Data);
decltype(CallWithContext(Traits::uuid, input, custom_context)) in_uuid = CallWithContext(Traits::uuid, input, custom_context);
size += mojo::internal::PrepareToSerialize<mojo::String>(
in_uuid, context);
return size;
}
static void Serialize(MaybeConstUserType& input,
Buffer* buffer,
::device::mojom::internal::BluetoothUUID_Data** output,
SerializationContext* context) {
if (CallIsNullIfExists<Traits>(input)) {
*output = nullptr;
return;
}
void* custom_context = CustomContextHelper<Traits>::GetNext(context);
auto result =
::device::mojom::internal::BluetoothUUID_Data::New(buffer);
ALLOW_UNUSED_LOCAL(result);
decltype(CallWithContext(Traits::uuid, input, custom_context)) in_uuid = CallWithContext(Traits::uuid, input, custom_context);
typename decltype(result->uuid)::BaseType* uuid_ptr;
mojo::internal::Serialize<mojo::String>(
in_uuid, buffer, &uuid_ptr, context);
result->uuid.Set(uuid_ptr);
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(
result->uuid.is_null(),
mojo::internal::VALIDATION_ERROR_UNEXPECTED_NULL_POINTER,
"null uuid in BluetoothUUID struct");
*output = result;
CustomContextHelper<Traits>::TearDown(input, custom_context);
}
static bool Deserialize(::device::mojom::internal::BluetoothUUID_Data* input,
UserType* output,
SerializationContext* context) {
if (!input)
return CallSetToNullIfExists<Traits>(output);
::device::mojom::blink::BluetoothUUIDDataView data_view(input, context);
return Traits::Read(data_view, output);
}
};
} // namespace internal
} // namespace mojo
#endif // DEVICE_BLUETOOTH_PUBLIC_INTERFACES_BLUETOOTH_UUID_MOJOM_BLINK_H_ | [
"dckristiono@gmail.com"
] | dckristiono@gmail.com |
5b4263b5508a0233bb5c944d66f06d4021cd8c69 | f9e4d19c81778c9fc7ce9354d1db40571d24db65 | /Navibrate/rf24_ble_master_attiny/rf24_ble_master_attiny.ino | bf1d5c22aba2f05260e2a5fd08ba17c794adfaee | [] | no_license | lunanigra/playground | 487dcebd0611066080297a080cef980520c5bb6f | a233379812a8002884d979302a3667c28882fcbf | refs/heads/master | 2020-04-26T11:00:22.825535 | 2015-05-26T22:10:35 | 2015-05-26T22:10:35 | 6,400,384 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,649 | ino | #include "tinySPI.h"
#include "nRF24L01.h"
#include "RF24.h"
#include <SoftwareSerial.h>
unsigned long blinkRightNowStart = 0;
unsigned long blinkRightNextStart = 0;
unsigned long blinkLeftNowStart = 0;
unsigned long blinkLeftNextStart = 0;
unsigned long blinkTurnStart = 0;
unsigned long blinkXStart = 0;
unsigned long vibrateRightNowStart = 0;
unsigned long vibrateRightNextStart = 0;
unsigned long vibrateLeftNowStart = 0;
unsigned long vibrateLeftNextStart = 0;
unsigned long vibrateTurnStart = 0;
unsigned long vibrateXStart = 0;
const unsigned int blinkNowPattern[] = {500, 200, 500, 200, 500, 200, 500, 200, 500};
const unsigned int blinkNextPattern[] = {150, 250, 150, 250, 150, 250, 150, 250, 150};
const unsigned int vibrateNowPattern[] = {2500};
const unsigned int vibrateNextPattern[] = {400, 1000, 400};
// Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins A0 & A1
RF24 radio(PIN_A0, PIN_A1);
// Radio pipe addresses for the 3 nodes to communicate.
const uint64_t pipes[3] = {0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL};
// Hardware configuraton: Set up Bluetooth RX, TX
SoftwareSerial Bluetooth(PIN_A2, PIN_A3);
char blueToothVal; //value sent over via bluetooth
char lastValue; //stores last state of device (on/off)
char commandVal;
void setup() {
pinMode(PIN_B0, OUTPUT);
pinMode(PIN_B1, OUTPUT);
pinMode(PIN_B2, OUTPUT);
pinMode(PIN_A7, OUTPUT);
delay(100);
radio.begin();
// optionally, increase the delay between retries & # of retries
radio.setRetries(15, 15);
// optionally, reduce the payload size. seems to
// improve reliability
radio.setPayloadSize(sizeof(char));
// Open pipes to other nodes for communication
// This simple sketch opens two pipes for these two nodes to communicate
// back and forth.
// Open 'our' pipe for writing
// Open the 'other' pipes for reading, in position #1 (we can have up to 5 pipes open for reading)
radio.openWritingPipe(pipes[0]);
radio.openReadingPipe(1, pipes[1]);
radio.openReadingPipe(2, pipes[2]);
// Start listening
radio.setAutoAck(true);
radio.powerUp();
radio.startListening();
// Dump the configuration of the rf unit for debugging
radio.printDetails();
Bluetooth.begin(9600);
sendATCommand("AT");
sendATCommand("AT+NAMENAVIBRATE");
sendATCommand("AT+PASS000000");
// sendATCommand("AT+ADVI1");
}
bool done = true;
void loop() {
if (commandVal != ' ') {
// First, stop listening so we can talk.
radio.stopListening();
// Take the time, and send it. This will block until complete
// bool ok = radio.write(&commandVal, sizeof(char), true);
bool ok = radio.write(&commandVal, sizeof(char));
if (ok) {
commandVal = ' ';
} else {
delay(20);
}
// Now, continue listening
radio.startListening();
}
// Handle Bluetooth communication
if (Bluetooth.available()) {
// if there is data being recieved
blueToothVal = Bluetooth.read(); //read it
if (blueToothVal == 'r') {
Bluetooth.println("OK: r");
blinkRightNextStart = vibrateRightNextStart = millis();
commandVal = blueToothVal;
} else if (blueToothVal == 'R') {
Bluetooth.println("OK: R");
blinkRightNowStart = vibrateRightNowStart = millis();
commandVal = blueToothVal;
} else if (blueToothVal == 'l') {
Bluetooth.println("OK: l");
blinkLeftNextStart = vibrateLeftNextStart = millis();
commandVal = blueToothVal;
} else if (blueToothVal == 'L') {
Bluetooth.println("OK: L");
blinkLeftNowStart = vibrateLeftNowStart = millis();
commandVal = blueToothVal;
} else if (blueToothVal == 't' || blueToothVal == 'T') {
Bluetooth.println("OK: T");
blinkTurnStart = vibrateTurnStart = millis();
commandVal = blueToothVal;
} else if (blueToothVal == 'x' || blueToothVal == 'X') {
Bluetooth.println("OK: X");
blinkXStart = vibrateXStart = millis();
commandVal = blueToothVal;
} else {
Bluetooth.println("Error");
}
}
writePinStatus(blinkRightNowStart, blinkNowPattern, sizeof(blinkNowPattern) / sizeof(unsigned int), PIN_B0, PIN_B0);
writePinStatus(blinkRightNextStart, blinkNextPattern, sizeof(blinkNextPattern) / sizeof(unsigned int), PIN_B0, PIN_B0);
writePinStatus(blinkLeftNowStart, blinkNowPattern, sizeof(blinkNowPattern) / sizeof(unsigned int), PIN_B1, PIN_B1);
writePinStatus(blinkLeftNextStart, blinkNextPattern, sizeof(blinkNextPattern) / sizeof(unsigned int), PIN_B1, PIN_B1);
writePinStatus(blinkXStart, blinkNowPattern, sizeof(blinkNowPattern) / sizeof(unsigned int), PIN_B0, PIN_B1);
writePinStatus(blinkTurnStart, blinkNextPattern, sizeof(blinkNextPattern) / sizeof(unsigned int), PIN_B0, PIN_B1);
writePinStatus(vibrateRightNowStart, vibrateNowPattern, sizeof(vibrateNowPattern) / sizeof(unsigned int), PIN_B2, PIN_B2);
writePinStatus(vibrateRightNextStart, vibrateNextPattern, sizeof(vibrateNextPattern) / sizeof(unsigned int), PIN_B2, PIN_B2);
writePinStatus(vibrateLeftNowStart, vibrateNowPattern, sizeof(vibrateNowPattern) / sizeof(unsigned int), PIN_A7, PIN_A7);
writePinStatus(vibrateLeftNextStart, vibrateNextPattern, sizeof(vibrateNextPattern) / sizeof(unsigned int), PIN_A7, PIN_A7);
writePinStatus(vibrateXStart, vibrateNowPattern, sizeof(vibrateNowPattern) / sizeof(unsigned int), PIN_B2, PIN_A7);
writePinStatus(vibrateTurnStart, vibrateNextPattern, sizeof(vibrateNextPattern) / sizeof(unsigned int), PIN_B2, PIN_A7);
// delay(20);
}
void sendATCommand(const String& command) {
Bluetooth.print(command);
boolean done = false;
unsigned long time = millis();
while (!done && (millis() - time < 5000)) {
if (Bluetooth.available()) {
blueToothVal = Bluetooth.read();
if (blueToothVal == 'O') {
done = true;
time = millis();
while (millis() - time < 1000) {
if (Bluetooth.available()) {
blueToothVal = Bluetooth.read();
}
}
}
}
}
}
void writePinStatus(unsigned long &startedTime, const unsigned int* pattern, size_t size, uint8_t pin1, uint8_t pin2) {
unsigned long currentTime = millis();
if (startedTime > 0) {
int idx = 0;
unsigned long time = startedTime; // pattern[0];
for (int i = 0; i < size; i++) {
if (currentTime > time) idx = i;
time += pattern[i];
}
if (currentTime > time) {
startedTime = 0;
digitalWrite(pin1, LOW);
digitalWrite(pin2, LOW);
} else {
digitalWrite(pin1, (idx % 2 == 0) ? HIGH : LOW);
digitalWrite(pin2, (idx % 2 == 0) ? HIGH : LOW);
}
}
}
| [
"haddorp@lunanigra.de"
] | haddorp@lunanigra.de |
433f5ec4ed41a079aa65b2cf9357171190372810 | d668209e9951d249020765c011a836f193004c01 | /tools/pnnx/src/pass_level4/canonicalize.h | e65f19e1c3b919549844fdd40f058c07ee7a7183 | [
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause"
] | permissive | Tencent/ncnn | d8371746c00439304c279041647362a723330a79 | 14b000d2b739bd0f169a9ccfeb042da06fa0a84a | refs/heads/master | 2023-08-31T14:04:36.635201 | 2023-08-31T04:19:23 | 2023-08-31T04:19:23 | 95,879,426 | 18,818 | 4,491 | NOASSERTION | 2023-09-14T15:44:56 | 2017-06-30T10:55:37 | C++ | UTF-8 | C++ | false | false | 782 | h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include "ir.h"
namespace pnnx {
void canonicalize(Graph& graph);
}
| [
"noreply@github.com"
] | noreply@github.com |
d215c6f075ce2a9f50c9aab50b7fde0069c917e7 | 5da7acab91c9d64406338a149538ab2d34820e10 | /tensorflow/compiler/mlir/lite/transforms/optimize.cc | 8cde45a88959c8ce8c8ac3c4931cdb615ffa5653 | [
"Apache-2.0"
] | permissive | H4NG-MAN/tensorflow | 32b818b9b1172abd03acb27b154c6c48d94feb93 | 432b55a161e70db42103d38d3e18c165dd0c7fde | refs/heads/master | 2023-06-28T23:03:12.286796 | 2019-12-07T16:18:25 | 2019-12-07T16:18:25 | 212,573,936 | 2 | 0 | Apache-2.0 | 2023-06-26T17:18:26 | 2019-10-03T12:25:23 | C++ | UTF-8 | C++ | false | false | 9,299 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This transformation pass takes operations in TensorFlowLite dialect and
// optimizes them to resulting operations in TensorFlowLite dialect.
#include <climits>
#include <cstdint>
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Casting.h"
#include "mlir/Dialect/StandardOps/Ops.h" // TF:local_config_mlir
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/Matchers.h" // TF:local_config_mlir
#include "mlir/IR/PatternMatch.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Support/Functional.h" // TF:local_config_mlir
#include "mlir/Support/LLVM.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/lite/utils/validators.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace TFL {
//===----------------------------------------------------------------------===//
// The actual Optimize Pass.
namespace {
using ::llvm::cast;
// Optimize TFLite operations in functions.
struct Optimize : public FunctionPass<Optimize> {
void runOnFunction() override;
};
// Returns whether the given type `a` is broadcast-compatible with `b`.
bool IsBroadcastableElementsAttrAndType(Type a, Type b) {
return OpTrait::util::getBroadcastedType(a, b) != Type();
}
// Returns whether the given `a` and `b` ElementsAttr have broadcast-compatible
// types.
bool IsBroadcastableElementsAttrs(Attribute a, Attribute b) {
return IsBroadcastableElementsAttrAndType(a.getType(), b.getType());
}
#include "tensorflow/compiler/mlir/lite/transforms/generated_optimize.inc"
// Fuse Add with proceeding FullyConnected.
// TODO(b/136285429): Move to tablegen when variadic is supported
struct FuseFullyConnectedAndAdd : public OpRewritePattern<TFL::AddOp> {
using OpRewritePattern<TFL::AddOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(TFL::AddOp add_op,
PatternRewriter &rewriter) const override {
// Add.
DenseElementsAttr added_value;
Value *constant_val = add_op.rhs();
if (!matchPattern(constant_val, m_Constant(&added_value)))
return matchFailure();
// Fully Connected.
auto fc_op =
dyn_cast_or_null<TFL::FullyConnectedOp>(add_op.lhs()->getDefiningOp());
if (!fc_op) return matchFailure();
Value *filter = fc_op.filter();
Value *bias = fc_op.bias();
ElementsAttr bias_value;
const bool is_none_bias = bias->getType().isa<NoneType>();
if (!is_none_bias && !matchPattern(bias, m_Constant(&bias_value)))
return matchFailure();
if (fc_op.fused_activation_function() != "NONE") return matchFailure();
// Rewrite
Location loc = fc_op.getLoc();
// If bias isn't None, it needs to be added as well.
if (is_none_bias) {
bias = constant_val;
} else {
auto none_af = rewriter.getStringAttr("NONE");
bias = rewriter.create<AddOp>(loc, bias, constant_val, none_af).output();
}
rewriter.replaceOpWithNewOp<TFL::FullyConnectedOp>(
add_op, add_op.getType(),
/*input=*/fc_op.input(),
/*filter=*/filter,
/*bias=*/bias,
/*fused_activation_function=*/
rewriter.getStringAttr(add_op.fused_activation_function()),
/*weights_format=*/rewriter.getStringAttr(fc_op.weights_format()),
/*keep_num_dims=*/rewriter.getBoolAttr(fc_op.keep_num_dims()));
return matchSuccess();
}
};
// TODO(b/136285429): Move to tablegen when variadic is supported.
struct FuseFullyConnectedAndRelu : public OpRewritePattern<TFL::ReluOp> {
using OpRewritePattern<TFL::ReluOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(TFL::ReluOp relu_op,
PatternRewriter &rewriter) const override {
Operation *input = relu_op.getOperand()->getDefiningOp();
if (!isa_and_nonnull<FullyConnectedOp>(input)) return matchFailure();
auto fully_connected_op = cast<FullyConnectedOp>(input);
if (fully_connected_op.fused_activation_function() != "NONE")
return matchFailure();
auto new_activation_func = rewriter.getStringAttr("RELU");
auto new_weights_format =
rewriter.getStringAttr(fully_connected_op.weights_format());
auto new_keep_num_dims =
rewriter.getBoolAttr(fully_connected_op.keep_num_dims());
rewriter.replaceOpWithNewOp<FullyConnectedOp>(
relu_op, relu_op.getType(), fully_connected_op.input(),
fully_connected_op.filter(), fully_connected_op.bias(),
new_activation_func, new_weights_format, new_keep_num_dims);
return matchSuccess();
}
};
// Fuse Mul with proceeding FullyConnected.
// TODO(b/136285429): Move to tablegen when variadic is supported
struct FuseFullyConnectedAndMul : public OpRewritePattern<TFL::MulOp> {
using OpRewritePattern<TFL::MulOp>::OpRewritePattern;
PatternMatchResult matchAndRewrite(TFL::MulOp mul_op,
PatternRewriter &rewriter) const override {
// Mul.
DenseElementsAttr cst;
Value *constant_val = mul_op.rhs();
if (!matchPattern(constant_val, m_Constant(&cst))) return matchFailure();
// Fully Connected.
auto fc_op =
dyn_cast_or_null<TFL::FullyConnectedOp>(mul_op.lhs()->getDefiningOp());
if (!fc_op) return matchFailure();
Value *filter = fc_op.filter();
Value *bias = fc_op.bias();
ElementsAttr cst_tmp;
if (!matchPattern(filter, m_Constant(&cst_tmp))) return matchFailure();
if (!bias->getType().isa<NoneType>() &&
!matchPattern(bias, m_Constant(&cst_tmp)))
return matchFailure();
if (fc_op.fused_activation_function().equals("None")) return matchFailure();
// Broadcast the constant operand of Mul if it isn't compatible to the
// filter input. We only support broadcasting the operand along the depth
// dimension, when the operand's depth is 1.
Value *new_const_val = constant_val;
if (!IsBroadcastableElementsAttrAndType(cst.getType(), filter->getType())) {
auto original_shape = cst.getType().getShape();
llvm::SmallVector<int64_t, 4> normalized_shape(original_shape.begin(),
original_shape.end());
normalized_shape.push_back(1);
auto new_cst = cst.reshape(rewriter.getTensorType(
normalized_shape, cst.getType().getElementType()));
Type new_type = new_cst.getType();
if (!IsBroadcastableElementsAttrAndType(new_type, filter->getType())) {
return matchFailure();
}
auto new_op =
rewriter.create<ConstantOp>(mul_op.getLoc(), new_type, new_cst);
new_const_val = new_op.getResult();
}
// Rewrite. Since the folder of TFL::MulOp couldn't broadcast the operands,
// TF::MulOp is used to fold the constant.
// TODO(b/139192933): switch to the TFL constant folding
Location loc = fc_op.getLoc();
auto new_filter =
rewriter.create<TF::MulOp>(loc, filter, new_const_val).z();
// If bias isn't None, it needs to be multiplied as well.
if (!bias->getType().isa<NoneType>()) {
bias = rewriter.create<TF::MulOp>(loc, bias, constant_val).z();
}
rewriter.replaceOpWithNewOp<TFL::FullyConnectedOp>(
mul_op, mul_op.getType(),
/*input=*/fc_op.input(),
/*filter=*/new_filter,
/*bias=*/bias,
/*fused_activation_function=*/
rewriter.getStringAttr(mul_op.fused_activation_function()),
/*weights_format=*/rewriter.getStringAttr(fc_op.weights_format()),
/*keep_num_dims=*/rewriter.getBoolAttr(fc_op.keep_num_dims()));
return matchSuccess();
}
};
void Optimize::runOnFunction() {
OwningRewritePatternList patterns;
auto *ctx = &getContext();
auto func = getFunction();
// Add the generated patterns to the list.
TFL::populateWithGenerated(ctx, &patterns);
patterns.insert<FuseFullyConnectedAndAdd, FuseFullyConnectedAndRelu,
FuseFullyConnectedAndMul>(ctx);
applyPatternsGreedily(func, patterns);
}
} // namespace
// Creates an instance of the TensorFlow Lite dialect Optimize pass.
std::unique_ptr<OpPassBase<FuncOp>> CreateOptimizePass() {
return std::make_unique<Optimize>();
}
static PassRegistration<Optimize> pass(
"tfl-optimize", "Optimize within the TensorFlow Lite dialect");
} // namespace TFL
} // namespace mlir
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
08d2ea45e202a4b505cde4de731797f0aac3fafa | b444a8cdbeb56faf0572a4c160bc1131a68c528f | /src/objects/string.cc | bd4de838675d8d2c19b745ad8d09630aa15946b5 | [
"BSD-3-Clause",
"Apache-2.0",
"SunPro"
] | permissive | gunesacar/v8 | a12b5b5f12214faaea2907b146d7eb856fcb5d58 | 9edcb19658d2508db6652606be60cd4e6c27969d | refs/heads/master | 2022-12-04T09:03:10.795407 | 2020-10-05T18:50:02 | 2020-10-05T18:50:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,160 | cc | // Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/objects/string.h"
#include "src/common/assert-scope.h"
#include "src/common/globals.h"
#include "src/handles/handles-inl.h"
#include "src/heap/heap-inl.h"
#include "src/heap/memory-chunk.h"
#include "src/heap/read-only-heap.h"
#include "src/numbers/conversions.h"
#include "src/objects/map.h"
#include "src/objects/oddball.h"
#include "src/objects/string-comparator.h"
#include "src/objects/string-inl.h"
#include "src/strings/char-predicates.h"
#include "src/strings/string-builder-inl.h"
#include "src/strings/string-hasher.h"
#include "src/strings/string-search.h"
#include "src/strings/string-stream.h"
#include "src/strings/unicode-inl.h"
#include "src/utils/ostreams.h"
namespace v8 {
namespace internal {
Handle<String> String::SlowFlatten(Isolate* isolate, Handle<ConsString> cons,
AllocationType allocation) {
DCHECK_NE(cons->second().length(), 0);
// TurboFan can create cons strings with empty first parts.
while (cons->first().length() == 0) {
// We do not want to call this function recursively. Therefore we call
// String::Flatten only in those cases where String::SlowFlatten is not
// called again.
if (cons->second().IsConsString() && !cons->second().IsFlat()) {
cons = handle(ConsString::cast(cons->second()), isolate);
} else {
return String::Flatten(isolate, handle(cons->second(), isolate));
}
}
DCHECK(AllowHeapAllocation::IsAllowed());
DCHECK(AllowGarbageCollection::IsAllowed());
int length = cons->length();
allocation =
ObjectInYoungGeneration(*cons) ? allocation : AllocationType::kOld;
Handle<SeqString> result;
if (cons->IsOneByteRepresentation()) {
Handle<SeqOneByteString> flat =
isolate->factory()
->NewRawOneByteString(length, allocation)
.ToHandleChecked();
DisallowHeapAllocation no_gc;
WriteToFlat(*cons, flat->GetChars(no_gc), 0, length);
result = flat;
} else {
Handle<SeqTwoByteString> flat =
isolate->factory()
->NewRawTwoByteString(length, allocation)
.ToHandleChecked();
DisallowHeapAllocation no_gc;
WriteToFlat(*cons, flat->GetChars(no_gc), 0, length);
result = flat;
}
cons->set_first(*result);
cons->set_second(ReadOnlyRoots(isolate).empty_string());
DCHECK(result->IsFlat());
return result;
}
namespace {
template <class StringClass>
void MigrateExternalStringResource(Isolate* isolate, ExternalString from,
StringClass to) {
Address to_resource_address = to.resource_as_address();
if (to_resource_address == kNullAddress) {
StringClass cast_from = StringClass::cast(from);
// |to| is a just-created internalized copy of |from|. Migrate the resource.
to.SetResource(isolate, cast_from.resource());
// Zap |from|'s resource pointer to reflect the fact that |from| has
// relinquished ownership of its resource.
isolate->heap()->UpdateExternalString(
from, ExternalString::cast(from).ExternalPayloadSize(), 0);
cast_from.SetResource(isolate, nullptr);
} else if (to_resource_address != from.resource_as_address()) {
// |to| already existed and has its own resource. Finalize |from|.
isolate->heap()->FinalizeExternalString(from);
}
}
} // namespace
void String::MakeThin(Isolate* isolate, String internalized) {
DisallowHeapAllocation no_gc;
DCHECK_NE(*this, internalized);
DCHECK(internalized.IsInternalizedString());
if (this->IsExternalString()) {
if (internalized.IsExternalOneByteString()) {
MigrateExternalStringResource(isolate, ExternalString::cast(*this),
ExternalOneByteString::cast(internalized));
} else if (internalized.IsExternalTwoByteString()) {
MigrateExternalStringResource(isolate, ExternalString::cast(*this),
ExternalTwoByteString::cast(internalized));
} else {
// If the external string is duped into an existing non-external
// internalized string, free its resource (it's about to be rewritten
// into a ThinString below).
isolate->heap()->FinalizeExternalString(*this);
}
}
bool has_pointers = StringShape(*this).IsIndirect();
int old_size = this->Size();
// Slot invalidation is not necessary here: ThinString only stores tagged
// value, so it can't store an untagged value in a recorded slot.
isolate->heap()->NotifyObjectLayoutChange(*this, no_gc,
InvalidateRecordedSlots::kNo);
bool one_byte = internalized.IsOneByteRepresentation();
Handle<Map> map = one_byte ? isolate->factory()->thin_one_byte_string_map()
: isolate->factory()->thin_string_map();
DCHECK_GE(old_size, ThinString::kSize);
this->synchronized_set_map(*map);
ThinString thin = ThinString::cast(*this);
thin.set_actual(internalized);
Address thin_end = thin.address() + ThinString::kSize;
int size_delta = old_size - ThinString::kSize;
if (size_delta != 0) {
Heap* heap = isolate->heap();
heap->CreateFillerObjectAt(
thin_end, size_delta,
has_pointers ? ClearRecordedSlots::kYes : ClearRecordedSlots::kNo);
}
}
bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
DisallowHeapAllocation no_allocation;
// Externalizing twice leaks the external resource, so it's
// prohibited by the API.
DCHECK(this->SupportsExternalization());
DCHECK(resource->IsCacheable());
#ifdef ENABLE_SLOW_DCHECKS
if (FLAG_enable_slow_asserts) {
// Assert that the resource and the string are equivalent.
DCHECK(static_cast<size_t>(this->length()) == resource->length());
ScopedVector<uc16> smart_chars(this->length());
String::WriteToFlat(*this, smart_chars.begin(), 0, this->length());
DCHECK_EQ(0, memcmp(smart_chars.begin(), resource->data(),
resource->length() * sizeof(smart_chars[0])));
}
#endif // DEBUG
int size = this->Size(); // Byte size of the original string.
// Abort if size does not allow in-place conversion.
if (size < ExternalString::kUncachedSize) return false;
// Read-only strings cannot be made external, since that would mutate the
// string.
if (IsReadOnlyHeapObject(*this)) return false;
Isolate* isolate = GetIsolateFromWritableObject(*this);
bool is_internalized = this->IsInternalizedString();
bool has_pointers = StringShape(*this).IsIndirect();
if (has_pointers) {
isolate->heap()->NotifyObjectLayoutChange(*this, no_allocation,
InvalidateRecordedSlots::kYes);
}
// Morph the string to an external string by replacing the map and
// reinitializing the fields. This won't work if the space the existing
// string occupies is too small for a regular external string. Instead, we
// resort to an uncached external string instead, omitting the field caching
// the address of the backing store. When we encounter uncached external
// strings in generated code, we need to bailout to runtime.
Map new_map;
ReadOnlyRoots roots(isolate);
if (size < ExternalString::kSizeOfAllExternalStrings) {
if (is_internalized) {
new_map = roots.uncached_external_internalized_string_map();
} else {
new_map = roots.uncached_external_string_map();
}
} else {
new_map = is_internalized ? roots.external_internalized_string_map()
: roots.external_string_map();
}
// Byte size of the external String object.
int new_size = this->SizeFromMap(new_map);
isolate->heap()->CreateFillerObjectAt(
this->address() + new_size, size - new_size,
has_pointers ? ClearRecordedSlots::kYes : ClearRecordedSlots::kNo);
// We are storing the new map using release store after creating a filler for
// the left-over space to avoid races with the sweeper thread.
this->synchronized_set_map(new_map);
ExternalTwoByteString self = ExternalTwoByteString::cast(*this);
self.AllocateExternalPointerEntries(isolate);
self.SetResource(isolate, resource);
isolate->heap()->RegisterExternalString(*this);
if (is_internalized) self.Hash(); // Force regeneration of the hash value.
return true;
}
bool String::MakeExternal(v8::String::ExternalOneByteStringResource* resource) {
DisallowHeapAllocation no_allocation;
// Externalizing twice leaks the external resource, so it's
// prohibited by the API.
DCHECK(this->SupportsExternalization());
DCHECK(resource->IsCacheable());
#ifdef ENABLE_SLOW_DCHECKS
if (FLAG_enable_slow_asserts) {
// Assert that the resource and the string are equivalent.
DCHECK(static_cast<size_t>(this->length()) == resource->length());
if (this->IsTwoByteRepresentation()) {
ScopedVector<uint16_t> smart_chars(this->length());
String::WriteToFlat(*this, smart_chars.begin(), 0, this->length());
DCHECK(String::IsOneByte(smart_chars.begin(), this->length()));
}
ScopedVector<char> smart_chars(this->length());
String::WriteToFlat(*this, smart_chars.begin(), 0, this->length());
DCHECK_EQ(0, memcmp(smart_chars.begin(), resource->data(),
resource->length() * sizeof(smart_chars[0])));
}
#endif // DEBUG
int size = this->Size(); // Byte size of the original string.
// Abort if size does not allow in-place conversion.
if (size < ExternalString::kUncachedSize) return false;
// Read-only strings cannot be made external, since that would mutate the
// string.
if (IsReadOnlyHeapObject(*this)) return false;
Isolate* isolate = GetIsolateFromWritableObject(*this);
bool is_internalized = this->IsInternalizedString();
bool has_pointers = StringShape(*this).IsIndirect();
if (has_pointers) {
isolate->heap()->NotifyObjectLayoutChange(*this, no_allocation,
InvalidateRecordedSlots::kYes);
}
// Morph the string to an external string by replacing the map and
// reinitializing the fields. This won't work if the space the existing
// string occupies is too small for a regular external string. Instead, we
// resort to an uncached external string instead, omitting the field caching
// the address of the backing store. When we encounter uncached external
// strings in generated code, we need to bailout to runtime.
Map new_map;
ReadOnlyRoots roots(isolate);
if (size < ExternalString::kSizeOfAllExternalStrings) {
new_map = is_internalized
? roots.uncached_external_one_byte_internalized_string_map()
: roots.uncached_external_one_byte_string_map();
} else {
new_map = is_internalized
? roots.external_one_byte_internalized_string_map()
: roots.external_one_byte_string_map();
}
// Byte size of the external String object.
int new_size = this->SizeFromMap(new_map);
isolate->heap()->CreateFillerObjectAt(
this->address() + new_size, size - new_size,
has_pointers ? ClearRecordedSlots::kYes : ClearRecordedSlots::kNo);
// We are storing the new map using release store after creating a filler for
// the left-over space to avoid races with the sweeper thread.
this->synchronized_set_map(new_map);
ExternalOneByteString self = ExternalOneByteString::cast(*this);
self.AllocateExternalPointerEntries(isolate);
self.SetResource(isolate, resource);
isolate->heap()->RegisterExternalString(*this);
if (is_internalized) self.Hash(); // Force regeneration of the hash value.
return true;
}
bool String::SupportsExternalization() {
if (this->IsThinString()) {
return i::ThinString::cast(*this).actual().SupportsExternalization();
}
// RO_SPACE strings cannot be externalized.
if (IsReadOnlyHeapObject(*this)) {
return false;
}
// Already an external string.
if (StringShape(*this).IsExternal()) {
return false;
}
#ifdef V8_COMPRESS_POINTERS
// Small strings may not be in-place externalizable.
if (this->Size() < ExternalString::kUncachedSize) return false;
#else
DCHECK_LE(ExternalString::kUncachedSize, this->Size());
#endif
Isolate* isolate = GetIsolateFromWritableObject(*this);
return !isolate->heap()->IsInGCPostProcessing();
}
const char* String::PrefixForDebugPrint() const {
StringShape shape(*this);
if (IsTwoByteRepresentation()) {
StringShape shape(*this);
if (shape.IsInternalized()) {
return "u#";
} else if (shape.IsCons()) {
return "uc\"";
} else if (shape.IsThin()) {
return "u>\"";
} else if (shape.IsExternal()) {
return "ue\"";
} else {
return "u\"";
}
} else {
StringShape shape(*this);
if (shape.IsInternalized()) {
return "#";
} else if (shape.IsCons()) {
return "c\"";
} else if (shape.IsThin()) {
return ">\"";
} else if (shape.IsExternal()) {
return "e\"";
} else {
return "\"";
}
}
UNREACHABLE();
}
const char* String::SuffixForDebugPrint() const {
StringShape shape(*this);
if (shape.IsInternalized()) return "";
return "\"";
}
void String::StringShortPrint(StringStream* accumulator) {
if (!LooksValid()) {
accumulator->Add("<Invalid String>");
return;
}
const int len = length();
accumulator->Add("<String[%u]: ", len);
accumulator->Add(PrefixForDebugPrint());
if (len > kMaxShortPrintLength) {
accumulator->Add("...<truncated>>");
accumulator->Add(SuffixForDebugPrint());
accumulator->Put('>');
return;
}
PrintUC16(accumulator, 0, len);
accumulator->Add(SuffixForDebugPrint());
accumulator->Put('>');
}
void String::PrintUC16(std::ostream& os, int start, int end) { // NOLINT
if (end < 0) end = length();
StringCharacterStream stream(*this, start);
for (int i = start; i < end && stream.HasMore(); i++) {
os << AsUC16(stream.GetNext());
}
}
void String::PrintUC16(StringStream* accumulator, int start, int end) {
if (end < 0) end = length();
StringCharacterStream stream(*this, start);
for (int i = start; i < end && stream.HasMore(); i++) {
uint16_t c = stream.GetNext();
if (c == '\n') {
accumulator->Add("\\n");
} else if (c == '\r') {
accumulator->Add("\\r");
} else if (c == '\\') {
accumulator->Add("\\\\");
} else if (!std::isprint(c)) {
accumulator->Add("\\x%02x", c);
} else {
accumulator->Put(static_cast<char>(c));
}
}
}
// static
Handle<String> String::Trim(Isolate* isolate, Handle<String> string,
TrimMode mode) {
string = String::Flatten(isolate, string);
int const length = string->length();
// Perform left trimming if requested.
int left = 0;
if (mode == kTrim || mode == kTrimStart) {
while (left < length && IsWhiteSpaceOrLineTerminator(string->Get(left))) {
left++;
}
}
// Perform right trimming if requested.
int right = length;
if (mode == kTrim || mode == kTrimEnd) {
while (right > left &&
IsWhiteSpaceOrLineTerminator(string->Get(right - 1))) {
right--;
}
}
return isolate->factory()->NewSubString(string, left, right);
}
int32_t String::ToArrayIndex(Address addr) {
DisallowHeapAllocation no_gc;
String key(addr);
uint32_t index;
if (!key.AsArrayIndex(&index)) return -1;
if (index <= INT_MAX) return index;
return -1;
}
bool String::LooksValid() {
// TODO(leszeks): Maybe remove this check entirely, Heap::Contains uses
// basically the same logic as the way we access the heap in the first place.
// RO_SPACE objects should always be valid.
if (ReadOnlyHeap::Contains(*this)) return true;
BasicMemoryChunk* chunk = BasicMemoryChunk::FromHeapObject(*this);
if (chunk->heap() == nullptr) return false;
return chunk->heap()->Contains(*this);
}
namespace {
bool AreDigits(const uint8_t* s, int from, int to) {
for (int i = from; i < to; i++) {
if (s[i] < '0' || s[i] > '9') return false;
}
return true;
}
int ParseDecimalInteger(const uint8_t* s, int from, int to) {
DCHECK_LT(to - from, 10); // Overflow is not possible.
DCHECK(from < to);
int d = s[from] - '0';
for (int i = from + 1; i < to; i++) {
d = 10 * d + (s[i] - '0');
}
return d;
}
} // namespace
// static
Handle<Object> String::ToNumber(Isolate* isolate, Handle<String> subject) {
// Flatten {subject} string first.
subject = String::Flatten(isolate, subject);
// Fast array index case.
uint32_t index;
if (subject->AsArrayIndex(&index)) {
return isolate->factory()->NewNumberFromUint(index);
}
// Fast case: short integer or some sorts of junk values.
if (subject->IsSeqOneByteString()) {
int len = subject->length();
if (len == 0) return handle(Smi::zero(), isolate);
DisallowHeapAllocation no_gc;
uint8_t const* data =
Handle<SeqOneByteString>::cast(subject)->GetChars(no_gc);
bool minus = (data[0] == '-');
int start_pos = (minus ? 1 : 0);
if (start_pos == len) {
return isolate->factory()->nan_value();
} else if (data[start_pos] > '9') {
// Fast check for a junk value. A valid string may start from a
// whitespace, a sign ('+' or '-'), the decimal point, a decimal digit
// or the 'I' character ('Infinity'). All of that have codes not greater
// than '9' except 'I' and .
if (data[start_pos] != 'I' && data[start_pos] != 0xA0) {
return isolate->factory()->nan_value();
}
} else if (len - start_pos < 10 && AreDigits(data, start_pos, len)) {
// The maximal/minimal smi has 10 digits. If the string has less digits
// we know it will fit into the smi-data type.
int d = ParseDecimalInteger(data, start_pos, len);
if (minus) {
if (d == 0) return isolate->factory()->minus_zero_value();
d = -d;
} else if (!subject->HasHashCode() && len <= String::kMaxArrayIndexSize &&
(len == 1 || data[0] != '0')) {
// String hash is not calculated yet but all the data are present.
// Update the hash field to speed up sequential convertions.
uint32_t hash = StringHasher::MakeArrayIndexHash(d, len);
#ifdef DEBUG
subject->Hash(); // Force hash calculation.
DCHECK_EQ(static_cast<int>(subject->hash_field()),
static_cast<int>(hash));
#endif
subject->set_hash_field(hash);
}
return handle(Smi::FromInt(d), isolate);
}
}
// Slower case.
int flags = ALLOW_HEX | ALLOW_OCTAL | ALLOW_BINARY;
return isolate->factory()->NewNumber(StringToDouble(isolate, subject, flags));
}
String::FlatContent String::GetFlatContent(
const DisallowHeapAllocation& no_gc) {
USE(no_gc);
int length = this->length();
StringShape shape(*this);
String string = *this;
int offset = 0;
if (shape.representation_tag() == kConsStringTag) {
ConsString cons = ConsString::cast(string);
if (cons.second().length() != 0) {
return FlatContent();
}
string = cons.first();
shape = StringShape(string);
} else if (shape.representation_tag() == kSlicedStringTag) {
SlicedString slice = SlicedString::cast(string);
offset = slice.offset();
string = slice.parent();
shape = StringShape(string);
DCHECK(shape.representation_tag() != kConsStringTag &&
shape.representation_tag() != kSlicedStringTag);
}
if (shape.representation_tag() == kThinStringTag) {
ThinString thin = ThinString::cast(string);
string = thin.actual();
shape = StringShape(string);
DCHECK(!shape.IsCons());
DCHECK(!shape.IsSliced());
}
if (shape.encoding_tag() == kOneByteStringTag) {
const uint8_t* start;
if (shape.representation_tag() == kSeqStringTag) {
start = SeqOneByteString::cast(string).GetChars(no_gc);
} else {
start = ExternalOneByteString::cast(string).GetChars();
}
return FlatContent(start + offset, length);
} else {
DCHECK_EQ(shape.encoding_tag(), kTwoByteStringTag);
const uc16* start;
if (shape.representation_tag() == kSeqStringTag) {
start = SeqTwoByteString::cast(string).GetChars(no_gc);
} else {
start = ExternalTwoByteString::cast(string).GetChars();
}
return FlatContent(start + offset, length);
}
}
std::unique_ptr<char[]> String::ToCString(AllowNullsFlag allow_nulls,
RobustnessFlag robust_flag,
int offset, int length,
int* length_return) {
if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
return std::unique_ptr<char[]>();
}
// Negative length means the to the end of the string.
if (length < 0) length = kMaxInt - offset;
// Compute the size of the UTF-8 string. Start at the specified offset.
StringCharacterStream stream(*this, offset);
int character_position = offset;
int utf8_bytes = 0;
int last = unibrow::Utf16::kNoPreviousCharacter;
while (stream.HasMore() && character_position++ < offset + length) {
uint16_t character = stream.GetNext();
utf8_bytes += unibrow::Utf8::Length(character, last);
last = character;
}
if (length_return) {
*length_return = utf8_bytes;
}
char* result = NewArray<char>(utf8_bytes + 1);
// Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
stream.Reset(*this, offset);
character_position = offset;
int utf8_byte_position = 0;
last = unibrow::Utf16::kNoPreviousCharacter;
while (stream.HasMore() && character_position++ < offset + length) {
uint16_t character = stream.GetNext();
if (allow_nulls == DISALLOW_NULLS && character == 0) {
character = ' ';
}
utf8_byte_position +=
unibrow::Utf8::Encode(result + utf8_byte_position, character, last);
last = character;
}
result[utf8_byte_position] = 0;
return std::unique_ptr<char[]>(result);
}
std::unique_ptr<char[]> String::ToCString(AllowNullsFlag allow_nulls,
RobustnessFlag robust_flag,
int* length_return) {
return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
}
template <typename sinkchar>
void String::WriteToFlat(String src, sinkchar* sink, int f, int t) {
DisallowHeapAllocation no_gc;
String source = src;
int from = f;
int to = t;
while (from < to) {
DCHECK_LE(0, from);
DCHECK_LE(to, source.length());
switch (StringShape(source).full_representation_tag()) {
case kOneByteStringTag | kExternalStringTag: {
CopyChars(sink, ExternalOneByteString::cast(source).GetChars() + from,
to - from);
return;
}
case kTwoByteStringTag | kExternalStringTag: {
const uc16* data = ExternalTwoByteString::cast(source).GetChars();
CopyChars(sink, data + from, to - from);
return;
}
case kOneByteStringTag | kSeqStringTag: {
CopyChars(sink, SeqOneByteString::cast(source).GetChars(no_gc) + from,
to - from);
return;
}
case kTwoByteStringTag | kSeqStringTag: {
CopyChars(sink, SeqTwoByteString::cast(source).GetChars(no_gc) + from,
to - from);
return;
}
case kOneByteStringTag | kConsStringTag:
case kTwoByteStringTag | kConsStringTag: {
ConsString cons_string = ConsString::cast(source);
String first = cons_string.first();
int boundary = first.length();
if (to - boundary >= boundary - from) {
// Right hand side is longer. Recurse over left.
if (from < boundary) {
WriteToFlat(first, sink, from, boundary);
if (from == 0 && cons_string.second() == first) {
CopyChars(sink + boundary, sink, boundary);
return;
}
sink += boundary - from;
from = 0;
} else {
from -= boundary;
}
to -= boundary;
source = cons_string.second();
} else {
// Left hand side is longer. Recurse over right.
if (to > boundary) {
String second = cons_string.second();
// When repeatedly appending to a string, we get a cons string that
// is unbalanced to the left, a list, essentially. We inline the
// common case of sequential one-byte right child.
if (to - boundary == 1) {
sink[boundary - from] = static_cast<sinkchar>(second.Get(0));
} else if (second.IsSeqOneByteString()) {
CopyChars(sink + boundary - from,
SeqOneByteString::cast(second).GetChars(no_gc),
to - boundary);
} else {
WriteToFlat(second, sink + boundary - from, 0, to - boundary);
}
to = boundary;
}
source = first;
}
break;
}
case kOneByteStringTag | kSlicedStringTag:
case kTwoByteStringTag | kSlicedStringTag: {
SlicedString slice = SlicedString::cast(source);
unsigned offset = slice.offset();
WriteToFlat(slice.parent(), sink, from + offset, to + offset);
return;
}
case kOneByteStringTag | kThinStringTag:
case kTwoByteStringTag | kThinStringTag:
source = ThinString::cast(source).actual();
break;
}
}
DCHECK_EQ(from, to);
}
template <typename SourceChar>
static void CalculateLineEndsImpl(std::vector<int>* line_ends,
Vector<const SourceChar> src,
bool include_ending_line) {
const int src_len = src.length();
for (int i = 0; i < src_len - 1; i++) {
SourceChar current = src[i];
SourceChar next = src[i + 1];
if (IsLineTerminatorSequence(current, next)) line_ends->push_back(i);
}
if (src_len > 0 && IsLineTerminatorSequence(src[src_len - 1], 0)) {
line_ends->push_back(src_len - 1);
}
if (include_ending_line) {
// Include one character beyond the end of script. The rewriter uses that
// position for the implicit return statement.
line_ends->push_back(src_len);
}
}
template <typename LocalIsolate>
Handle<FixedArray> String::CalculateLineEnds(LocalIsolate* isolate,
Handle<String> src,
bool include_ending_line) {
src = Flatten(isolate, src);
// Rough estimate of line count based on a roughly estimated average
// length of (unpacked) code.
int line_count_estimate = src->length() >> 4;
std::vector<int> line_ends;
line_ends.reserve(line_count_estimate);
{
DisallowHeapAllocation no_allocation; // ensure vectors stay valid.
// Dispatch on type of strings.
String::FlatContent content = src->GetFlatContent(no_allocation);
DCHECK(content.IsFlat());
if (content.IsOneByte()) {
CalculateLineEndsImpl(&line_ends, content.ToOneByteVector(),
include_ending_line);
} else {
CalculateLineEndsImpl(&line_ends, content.ToUC16Vector(),
include_ending_line);
}
}
int line_count = static_cast<int>(line_ends.size());
Handle<FixedArray> array =
isolate->factory()->NewFixedArray(line_count, AllocationType::kOld);
for (int i = 0; i < line_count; i++) {
array->set(i, Smi::FromInt(line_ends[i]));
}
return array;
}
template Handle<FixedArray> String::CalculateLineEnds(Isolate* isolate,
Handle<String> src,
bool include_ending_line);
template Handle<FixedArray> String::CalculateLineEnds(LocalIsolate* isolate,
Handle<String> src,
bool include_ending_line);
bool String::SlowEquals(String other) {
DisallowHeapAllocation no_gc;
// Fast check: negative check with lengths.
int len = length();
if (len != other.length()) return false;
if (len == 0) return true;
// Fast check: if at least one ThinString is involved, dereference it/them
// and restart.
if (this->IsThinString() || other.IsThinString()) {
if (other.IsThinString()) other = ThinString::cast(other).actual();
if (this->IsThinString()) {
return ThinString::cast(*this).actual().Equals(other);
} else {
return this->Equals(other);
}
}
// Fast check: if hash code is computed for both strings
// a fast negative check can be performed.
if (HasHashCode() && other.HasHashCode()) {
#ifdef ENABLE_SLOW_DCHECKS
if (FLAG_enable_slow_asserts) {
if (Hash() != other.Hash()) {
bool found_difference = false;
for (int i = 0; i < len; i++) {
if (Get(i) != other.Get(i)) {
found_difference = true;
break;
}
}
DCHECK(found_difference);
}
}
#endif
if (Hash() != other.Hash()) return false;
}
// We know the strings are both non-empty. Compare the first chars
// before we try to flatten the strings.
if (this->Get(0) != other.Get(0)) return false;
if (IsSeqOneByteString() && other.IsSeqOneByteString()) {
const uint8_t* str1 = SeqOneByteString::cast(*this).GetChars(no_gc);
const uint8_t* str2 = SeqOneByteString::cast(other).GetChars(no_gc);
return CompareRawStringContents(str1, str2, len);
}
StringComparator comparator;
return comparator.Equals(*this, other);
}
bool String::SlowEquals(Isolate* isolate, Handle<String> one,
Handle<String> two) {
// Fast check: negative check with lengths.
int one_length = one->length();
if (one_length != two->length()) return false;
if (one_length == 0) return true;
// Fast check: if at least one ThinString is involved, dereference it/them
// and restart.
if (one->IsThinString() || two->IsThinString()) {
if (one->IsThinString())
one = handle(ThinString::cast(*one).actual(), isolate);
if (two->IsThinString())
two = handle(ThinString::cast(*two).actual(), isolate);
return String::Equals(isolate, one, two);
}
// Fast check: if hash code is computed for both strings
// a fast negative check can be performed.
if (one->HasHashCode() && two->HasHashCode()) {
#ifdef ENABLE_SLOW_DCHECKS
if (FLAG_enable_slow_asserts) {
if (one->Hash() != two->Hash()) {
bool found_difference = false;
for (int i = 0; i < one_length; i++) {
if (one->Get(i) != two->Get(i)) {
found_difference = true;
break;
}
}
DCHECK(found_difference);
}
}
#endif
if (one->Hash() != two->Hash()) return false;
}
// We know the strings are both non-empty. Compare the first chars
// before we try to flatten the strings.
if (one->Get(0) != two->Get(0)) return false;
one = String::Flatten(isolate, one);
two = String::Flatten(isolate, two);
DisallowHeapAllocation no_gc;
String::FlatContent flat1 = one->GetFlatContent(no_gc);
String::FlatContent flat2 = two->GetFlatContent(no_gc);
if (flat1.IsOneByte() && flat2.IsOneByte()) {
return CompareRawStringContents(flat1.ToOneByteVector().begin(),
flat2.ToOneByteVector().begin(),
one_length);
} else {
for (int i = 0; i < one_length; i++) {
if (flat1.Get(i) != flat2.Get(i)) return false;
}
return true;
}
}
// static
ComparisonResult String::Compare(Isolate* isolate, Handle<String> x,
Handle<String> y) {
// A few fast case tests before we flatten.
if (x.is_identical_to(y)) {
return ComparisonResult::kEqual;
} else if (y->length() == 0) {
return x->length() == 0 ? ComparisonResult::kEqual
: ComparisonResult::kGreaterThan;
} else if (x->length() == 0) {
return ComparisonResult::kLessThan;
}
int const d = x->Get(0) - y->Get(0);
if (d < 0) {
return ComparisonResult::kLessThan;
} else if (d > 0) {
return ComparisonResult::kGreaterThan;
}
// Slow case.
x = String::Flatten(isolate, x);
y = String::Flatten(isolate, y);
DisallowHeapAllocation no_gc;
ComparisonResult result = ComparisonResult::kEqual;
int prefix_length = x->length();
if (y->length() < prefix_length) {
prefix_length = y->length();
result = ComparisonResult::kGreaterThan;
} else if (y->length() > prefix_length) {
result = ComparisonResult::kLessThan;
}
int r;
String::FlatContent x_content = x->GetFlatContent(no_gc);
String::FlatContent y_content = y->GetFlatContent(no_gc);
if (x_content.IsOneByte()) {
Vector<const uint8_t> x_chars = x_content.ToOneByteVector();
if (y_content.IsOneByte()) {
Vector<const uint8_t> y_chars = y_content.ToOneByteVector();
r = CompareChars(x_chars.begin(), y_chars.begin(), prefix_length);
} else {
Vector<const uc16> y_chars = y_content.ToUC16Vector();
r = CompareChars(x_chars.begin(), y_chars.begin(), prefix_length);
}
} else {
Vector<const uc16> x_chars = x_content.ToUC16Vector();
if (y_content.IsOneByte()) {
Vector<const uint8_t> y_chars = y_content.ToOneByteVector();
r = CompareChars(x_chars.begin(), y_chars.begin(), prefix_length);
} else {
Vector<const uc16> y_chars = y_content.ToUC16Vector();
r = CompareChars(x_chars.begin(), y_chars.begin(), prefix_length);
}
}
if (r < 0) {
result = ComparisonResult::kLessThan;
} else if (r > 0) {
result = ComparisonResult::kGreaterThan;
}
return result;
}
Object String::IndexOf(Isolate* isolate, Handle<Object> receiver,
Handle<Object> search, Handle<Object> position) {
if (receiver->IsNullOrUndefined(isolate)) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kCalledOnNullOrUndefined,
isolate->factory()->NewStringFromAsciiChecked(
"String.prototype.indexOf")));
}
Handle<String> receiver_string;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver_string,
Object::ToString(isolate, receiver));
Handle<String> search_string;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, search_string,
Object::ToString(isolate, search));
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position,
Object::ToInteger(isolate, position));
uint32_t index = receiver_string->ToValidIndex(*position);
return Smi::FromInt(
String::IndexOf(isolate, receiver_string, search_string, index));
}
namespace {
template <typename T>
int SearchString(Isolate* isolate, String::FlatContent receiver_content,
Vector<T> pat_vector, int start_index) {
if (receiver_content.IsOneByte()) {
return SearchString(isolate, receiver_content.ToOneByteVector(), pat_vector,
start_index);
}
return SearchString(isolate, receiver_content.ToUC16Vector(), pat_vector,
start_index);
}
} // namespace
int String::IndexOf(Isolate* isolate, Handle<String> receiver,
Handle<String> search, int start_index) {
DCHECK_LE(0, start_index);
DCHECK(start_index <= receiver->length());
uint32_t search_length = search->length();
if (search_length == 0) return start_index;
uint32_t receiver_length = receiver->length();
if (start_index + search_length > receiver_length) return -1;
receiver = String::Flatten(isolate, receiver);
search = String::Flatten(isolate, search);
DisallowHeapAllocation no_gc; // ensure vectors stay valid
// Extract flattened substrings of cons strings before getting encoding.
String::FlatContent receiver_content = receiver->GetFlatContent(no_gc);
String::FlatContent search_content = search->GetFlatContent(no_gc);
// dispatch on type of strings
if (search_content.IsOneByte()) {
Vector<const uint8_t> pat_vector = search_content.ToOneByteVector();
return SearchString<const uint8_t>(isolate, receiver_content, pat_vector,
start_index);
}
Vector<const uc16> pat_vector = search_content.ToUC16Vector();
return SearchString<const uc16>(isolate, receiver_content, pat_vector,
start_index);
}
MaybeHandle<String> String::GetSubstitution(Isolate* isolate, Match* match,
Handle<String> replacement,
int start_index) {
DCHECK_GE(start_index, 0);
Factory* factory = isolate->factory();
const int replacement_length = replacement->length();
const int captures_length = match->CaptureCount();
replacement = String::Flatten(isolate, replacement);
Handle<String> dollar_string =
factory->LookupSingleCharacterStringFromCode('$');
int next_dollar_ix =
String::IndexOf(isolate, replacement, dollar_string, start_index);
if (next_dollar_ix < 0) {
return replacement;
}
IncrementalStringBuilder builder(isolate);
if (next_dollar_ix > 0) {
builder.AppendString(factory->NewSubString(replacement, 0, next_dollar_ix));
}
while (true) {
const int peek_ix = next_dollar_ix + 1;
if (peek_ix >= replacement_length) {
builder.AppendCharacter('$');
return builder.Finish();
}
int continue_from_ix = -1;
const uint16_t peek = replacement->Get(peek_ix);
switch (peek) {
case '$': // $$
builder.AppendCharacter('$');
continue_from_ix = peek_ix + 1;
break;
case '&': // $& - match
builder.AppendString(match->GetMatch());
continue_from_ix = peek_ix + 1;
break;
case '`': // $` - prefix
builder.AppendString(match->GetPrefix());
continue_from_ix = peek_ix + 1;
break;
case '\'': // $' - suffix
builder.AppendString(match->GetSuffix());
continue_from_ix = peek_ix + 1;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
// Valid indices are $1 .. $9, $01 .. $09 and $10 .. $99
int scaled_index = (peek - '0');
int advance = 1;
if (peek_ix + 1 < replacement_length) {
const uint16_t next_peek = replacement->Get(peek_ix + 1);
if (next_peek >= '0' && next_peek <= '9') {
const int new_scaled_index = scaled_index * 10 + (next_peek - '0');
if (new_scaled_index < captures_length) {
scaled_index = new_scaled_index;
advance = 2;
}
}
}
if (scaled_index == 0 || scaled_index >= captures_length) {
builder.AppendCharacter('$');
continue_from_ix = peek_ix;
break;
}
bool capture_exists;
Handle<String> capture;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, capture, match->GetCapture(scaled_index, &capture_exists),
String);
if (capture_exists) builder.AppendString(capture);
continue_from_ix = peek_ix + advance;
break;
}
case '<': { // $<name> - named capture
using CaptureState = String::Match::CaptureState;
if (!match->HasNamedCaptures()) {
builder.AppendCharacter('$');
continue_from_ix = peek_ix;
break;
}
Handle<String> bracket_string =
factory->LookupSingleCharacterStringFromCode('>');
const int closing_bracket_ix =
String::IndexOf(isolate, replacement, bracket_string, peek_ix + 1);
if (closing_bracket_ix == -1) {
// No closing bracket was found, treat '$<' as a string literal.
builder.AppendCharacter('$');
continue_from_ix = peek_ix;
break;
}
Handle<String> capture_name =
factory->NewSubString(replacement, peek_ix + 1, closing_bracket_ix);
Handle<String> capture;
CaptureState capture_state;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, capture,
match->GetNamedCapture(capture_name, &capture_state), String);
if (capture_state == CaptureState::MATCHED) {
builder.AppendString(capture);
}
continue_from_ix = closing_bracket_ix + 1;
break;
}
default:
builder.AppendCharacter('$');
continue_from_ix = peek_ix;
break;
}
// Go the the next $ in the replacement.
// TODO(jgruber): Single-char lookups could be much more efficient.
DCHECK_NE(continue_from_ix, -1);
next_dollar_ix =
String::IndexOf(isolate, replacement, dollar_string, continue_from_ix);
// Return if there are no more $ characters in the replacement. If we
// haven't reached the end, we need to append the suffix.
if (next_dollar_ix < 0) {
if (continue_from_ix < replacement_length) {
builder.AppendString(factory->NewSubString(
replacement, continue_from_ix, replacement_length));
}
return builder.Finish();
}
// Append substring between the previous and the next $ character.
if (next_dollar_ix > continue_from_ix) {
builder.AppendString(
factory->NewSubString(replacement, continue_from_ix, next_dollar_ix));
}
}
UNREACHABLE();
}
namespace { // for String.Prototype.lastIndexOf
template <typename schar, typename pchar>
int StringMatchBackwards(Vector<const schar> subject,
Vector<const pchar> pattern, int idx) {
int pattern_length = pattern.length();
DCHECK_GE(pattern_length, 1);
DCHECK(idx + pattern_length <= subject.length());
if (sizeof(schar) == 1 && sizeof(pchar) > 1) {
for (int i = 0; i < pattern_length; i++) {
uc16 c = pattern[i];
if (c > String::kMaxOneByteCharCode) {
return -1;
}
}
}
pchar pattern_first_char = pattern[0];
for (int i = idx; i >= 0; i--) {
if (subject[i] != pattern_first_char) continue;
int j = 1;
while (j < pattern_length) {
if (pattern[j] != subject[i + j]) {
break;
}
j++;
}
if (j == pattern_length) {
return i;
}
}
return -1;
}
} // namespace
Object String::LastIndexOf(Isolate* isolate, Handle<Object> receiver,
Handle<Object> search, Handle<Object> position) {
if (receiver->IsNullOrUndefined(isolate)) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kCalledOnNullOrUndefined,
isolate->factory()->NewStringFromAsciiChecked(
"String.prototype.lastIndexOf")));
}
Handle<String> receiver_string;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver_string,
Object::ToString(isolate, receiver));
Handle<String> search_string;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, search_string,
Object::ToString(isolate, search));
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position,
Object::ToNumber(isolate, position));
uint32_t start_index;
if (position->IsNaN()) {
start_index = receiver_string->length();
} else {
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, position,
Object::ToInteger(isolate, position));
start_index = receiver_string->ToValidIndex(*position);
}
uint32_t pattern_length = search_string->length();
uint32_t receiver_length = receiver_string->length();
if (start_index + pattern_length > receiver_length) {
start_index = receiver_length - pattern_length;
}
if (pattern_length == 0) {
return Smi::FromInt(start_index);
}
receiver_string = String::Flatten(isolate, receiver_string);
search_string = String::Flatten(isolate, search_string);
int last_index = -1;
DisallowHeapAllocation no_gc; // ensure vectors stay valid
String::FlatContent receiver_content = receiver_string->GetFlatContent(no_gc);
String::FlatContent search_content = search_string->GetFlatContent(no_gc);
if (search_content.IsOneByte()) {
Vector<const uint8_t> pat_vector = search_content.ToOneByteVector();
if (receiver_content.IsOneByte()) {
last_index = StringMatchBackwards(receiver_content.ToOneByteVector(),
pat_vector, start_index);
} else {
last_index = StringMatchBackwards(receiver_content.ToUC16Vector(),
pat_vector, start_index);
}
} else {
Vector<const uc16> pat_vector = search_content.ToUC16Vector();
if (receiver_content.IsOneByte()) {
last_index = StringMatchBackwards(receiver_content.ToOneByteVector(),
pat_vector, start_index);
} else {
last_index = StringMatchBackwards(receiver_content.ToUC16Vector(),
pat_vector, start_index);
}
}
return Smi::FromInt(last_index);
}
template <>
bool String::IsEqualTo(Vector<const uint8_t> str) {
return IsOneByteEqualTo(str);
}
template <>
bool String::IsEqualTo(Vector<const uc16> str) {
return IsTwoByteEqualTo(str);
}
bool String::HasOneBytePrefix(Vector<const char> str) {
int slen = str.length();
if (slen > length()) return false;
DisallowHeapAllocation no_gc;
FlatContent content = GetFlatContent(no_gc);
if (content.IsOneByte()) {
return CompareChars(content.ToOneByteVector().begin(), str.begin(), slen) ==
0;
}
return CompareChars(content.ToUC16Vector().begin(), str.begin(), slen) == 0;
}
bool String::IsOneByteEqualTo(Vector<const uint8_t> str) {
int slen = length();
if (str.length() != slen) return false;
DisallowHeapAllocation no_gc;
FlatContent content = GetFlatContent(no_gc);
if (content.IsOneByte()) {
return CompareChars(content.ToOneByteVector().begin(), str.begin(), slen) ==
0;
}
return CompareChars(content.ToUC16Vector().begin(), str.begin(), slen) == 0;
}
bool String::IsTwoByteEqualTo(Vector<const uc16> str) {
int slen = length();
if (str.length() != slen) return false;
DisallowHeapAllocation no_gc;
FlatContent content = GetFlatContent(no_gc);
if (content.IsOneByte()) {
return CompareChars(content.ToOneByteVector().begin(), str.begin(), slen) ==
0;
}
return CompareChars(content.ToUC16Vector().begin(), str.begin(), slen) == 0;
}
namespace {
template <typename Char>
uint32_t HashString(String string, size_t start, int length, uint64_t seed) {
DisallowHeapAllocation no_gc;
if (length > String::kMaxHashCalcLength) {
return StringHasher::GetTrivialHash(length);
}
std::unique_ptr<Char[]> buffer;
const Char* chars;
if (string.IsConsString()) {
DCHECK_EQ(0, start);
DCHECK(!string.IsFlat());
buffer.reset(new Char[length]);
String::WriteToFlat(string, buffer.get(), 0, length);
chars = buffer.get();
} else {
chars = string.GetChars<Char>(no_gc) + start;
}
return StringHasher::HashSequentialString<Char>(chars, length, seed);
}
} // namespace
uint32_t String::ComputeAndSetHash() {
DisallowHeapAllocation no_gc;
// Should only be called if hash code has not yet been computed.
DCHECK(!HasHashCode());
// Store the hash code in the object.
uint64_t seed = HashSeed(GetReadOnlyRoots());
size_t start = 0;
String string = *this;
if (string.IsSlicedString()) {
SlicedString sliced = SlicedString::cast(string);
start = sliced.offset();
string = sliced.parent();
}
if (string.IsConsString() && string.IsFlat()) {
string = ConsString::cast(string).first();
}
if (string.IsThinString()) {
string = ThinString::cast(string).actual();
if (length() == string.length()) {
set_hash_field(string.hash_field());
return hash_field() >> kHashShift;
}
}
uint32_t field = string.IsOneByteRepresentation()
? HashString<uint8_t>(string, start, length(), seed)
: HashString<uint16_t>(string, start, length(), seed);
set_hash_field(field);
// Check the hash code is there.
DCHECK(HasHashCode());
uint32_t result = field >> kHashShift;
DCHECK_NE(result, 0); // Ensure that the hash value of 0 is never computed.
return result;
}
bool String::SlowAsArrayIndex(uint32_t* index) {
DisallowHeapAllocation no_gc;
int length = this->length();
if (length <= kMaxCachedArrayIndexLength) {
Hash(); // Force computation of hash code.
uint32_t field = hash_field();
if ((field & kIsNotIntegerIndexMask) != 0) return false;
*index = ArrayIndexValueBits::decode(field);
return true;
}
if (length == 0 || length > kMaxArrayIndexSize) return false;
StringCharacterStream stream(*this);
return StringToIndex(&stream, index);
}
bool String::SlowAsIntegerIndex(size_t* index) {
DisallowHeapAllocation no_gc;
int length = this->length();
if (length <= kMaxCachedArrayIndexLength) {
Hash(); // Force computation of hash code.
uint32_t field = hash_field();
if ((field & kIsNotIntegerIndexMask) != 0) return false;
*index = ArrayIndexValueBits::decode(field);
return true;
}
if (length == 0 || length > kMaxIntegerIndexSize) return false;
StringCharacterStream stream(*this);
return StringToIndex<StringCharacterStream, size_t, kToIntegerIndex>(&stream,
index);
}
void String::PrintOn(FILE* file) {
int length = this->length();
for (int i = 0; i < length; i++) {
PrintF(file, "%c", Get(i));
}
}
Handle<String> SeqString::Truncate(Handle<SeqString> string, int new_length) {
if (new_length == 0) return string->GetReadOnlyRoots().empty_string_handle();
int new_size, old_size;
int old_length = string->length();
if (old_length <= new_length) return string;
if (string->IsSeqOneByteString()) {
old_size = SeqOneByteString::SizeFor(old_length);
new_size = SeqOneByteString::SizeFor(new_length);
} else {
DCHECK(string->IsSeqTwoByteString());
old_size = SeqTwoByteString::SizeFor(old_length);
new_size = SeqTwoByteString::SizeFor(new_length);
}
int delta = old_size - new_size;
Address start_of_string = string->address();
DCHECK(IsAligned(start_of_string, kObjectAlignment));
DCHECK(IsAligned(start_of_string + new_size, kObjectAlignment));
Heap* heap = Heap::FromWritableHeapObject(*string);
// Sizes are pointer size aligned, so that we can use filler objects
// that are a multiple of pointer size.
heap->CreateFillerObjectAt(start_of_string + new_size, delta,
ClearRecordedSlots::kNo);
// We are storing the new length using release store after creating a filler
// for the left-over space to avoid races with the sweeper thread.
string->synchronized_set_length(new_length);
return string;
}
void SeqOneByteString::clear_padding() {
int data_size = SeqString::kHeaderSize + length() * kOneByteSize;
memset(reinterpret_cast<void*>(address() + data_size), 0,
SizeFor(length()) - data_size);
}
void SeqTwoByteString::clear_padding() {
int data_size = SeqString::kHeaderSize + length() * kUC16Size;
memset(reinterpret_cast<void*>(address() + data_size), 0,
SizeFor(length()) - data_size);
}
uint16_t ConsString::Get(int index) {
DCHECK(index >= 0 && index < this->length());
// Check for a flattened cons string
if (second().length() == 0) {
String left = first();
return left.Get(index);
}
String string = String::cast(*this);
while (true) {
if (StringShape(string).IsCons()) {
ConsString cons_string = ConsString::cast(string);
String left = cons_string.first();
if (left.length() > index) {
string = left;
} else {
index -= left.length();
string = cons_string.second();
}
} else {
return string.Get(index);
}
}
UNREACHABLE();
}
uint16_t ThinString::Get(int index) { return actual().Get(index); }
uint16_t SlicedString::Get(int index) { return parent().Get(offset() + index); }
int ExternalString::ExternalPayloadSize() const {
int length_multiplier = IsTwoByteRepresentation() ? i::kShortSize : kCharSize;
return length() * length_multiplier;
}
FlatStringReader::FlatStringReader(Isolate* isolate, Handle<String> str)
: Relocatable(isolate), str_(str.location()), length_(str->length()) {
PostGarbageCollection();
}
FlatStringReader::FlatStringReader(Isolate* isolate, Vector<const char> input)
: Relocatable(isolate),
str_(nullptr),
is_one_byte_(true),
length_(input.length()),
start_(input.begin()) {}
void FlatStringReader::PostGarbageCollection() {
if (str_ == nullptr) return;
Handle<String> str(str_);
DCHECK(str->IsFlat());
DisallowHeapAllocation no_gc;
// This does not actually prevent the vector from being relocated later.
String::FlatContent content = str->GetFlatContent(no_gc);
DCHECK(content.IsFlat());
is_one_byte_ = content.IsOneByte();
if (is_one_byte_) {
start_ = content.ToOneByteVector().begin();
} else {
start_ = content.ToUC16Vector().begin();
}
}
void ConsStringIterator::Initialize(ConsString cons_string, int offset) {
DCHECK(!cons_string.is_null());
root_ = cons_string;
consumed_ = offset;
// Force stack blown condition to trigger restart.
depth_ = 1;
maximum_depth_ = kStackSize + depth_;
DCHECK(StackBlown());
}
String ConsStringIterator::Continue(int* offset_out) {
DCHECK_NE(depth_, 0);
DCHECK_EQ(0, *offset_out);
bool blew_stack = StackBlown();
String string;
// Get the next leaf if there is one.
if (!blew_stack) string = NextLeaf(&blew_stack);
// Restart search from root.
if (blew_stack) {
DCHECK(string.is_null());
string = Search(offset_out);
}
// Ensure future calls return null immediately.
if (string.is_null()) Reset(ConsString());
return string;
}
String ConsStringIterator::Search(int* offset_out) {
ConsString cons_string = root_;
// Reset the stack, pushing the root string.
depth_ = 1;
maximum_depth_ = 1;
frames_[0] = cons_string;
const int consumed = consumed_;
int offset = 0;
while (true) {
// Loop until the string is found which contains the target offset.
String string = cons_string.first();
int length = string.length();
int32_t type;
if (consumed < offset + length) {
// Target offset is in the left branch.
// Keep going if we're still in a ConString.
type = string.map().instance_type();
if ((type & kStringRepresentationMask) == kConsStringTag) {
cons_string = ConsString::cast(string);
PushLeft(cons_string);
continue;
}
// Tell the stack we're done descending.
AdjustMaximumDepth();
} else {
// Descend right.
// Update progress through the string.
offset += length;
// Keep going if we're still in a ConString.
string = cons_string.second();
type = string.map().instance_type();
if ((type & kStringRepresentationMask) == kConsStringTag) {
cons_string = ConsString::cast(string);
PushRight(cons_string);
continue;
}
// Need this to be updated for the current string.
length = string.length();
// Account for the possibility of an empty right leaf.
// This happens only if we have asked for an offset outside the string.
if (length == 0) {
// Reset so future operations will return null immediately.
Reset(ConsString());
return String();
}
// Tell the stack we're done descending.
AdjustMaximumDepth();
// Pop stack so next iteration is in correct place.
Pop();
}
DCHECK_NE(length, 0);
// Adjust return values and exit.
consumed_ = offset + length;
*offset_out = consumed - offset;
return string;
}
UNREACHABLE();
}
String ConsStringIterator::NextLeaf(bool* blew_stack) {
while (true) {
// Tree traversal complete.
if (depth_ == 0) {
*blew_stack = false;
return String();
}
// We've lost track of higher nodes.
if (StackBlown()) {
*blew_stack = true;
return String();
}
// Go right.
ConsString cons_string = frames_[OffsetForDepth(depth_ - 1)];
String string = cons_string.second();
int32_t type = string.map().instance_type();
if ((type & kStringRepresentationMask) != kConsStringTag) {
// Pop stack so next iteration is in correct place.
Pop();
int length = string.length();
// Could be a flattened ConsString.
if (length == 0) continue;
consumed_ += length;
return string;
}
cons_string = ConsString::cast(string);
PushRight(cons_string);
// Need to traverse all the way left.
while (true) {
// Continue left.
string = cons_string.first();
type = string.map().instance_type();
if ((type & kStringRepresentationMask) != kConsStringTag) {
AdjustMaximumDepth();
int length = string.length();
if (length == 0) break; // Skip empty left-hand sides of ConsStrings.
consumed_ += length;
return string;
}
cons_string = ConsString::cast(string);
PushLeft(cons_string);
}
}
UNREACHABLE();
}
const byte* String::AddressOfCharacterAt(int start_index,
const DisallowHeapAllocation& no_gc) {
DCHECK(IsFlat());
String subject = *this;
if (subject.IsConsString()) {
subject = ConsString::cast(subject).first();
} else if (subject.IsSlicedString()) {
start_index += SlicedString::cast(subject).offset();
subject = SlicedString::cast(subject).parent();
}
if (subject.IsThinString()) {
subject = ThinString::cast(subject).actual();
}
CHECK_LE(0, start_index);
CHECK_LE(start_index, subject.length());
if (subject.IsSeqOneByteString()) {
return reinterpret_cast<const byte*>(
SeqOneByteString::cast(subject).GetChars(no_gc) + start_index);
} else if (subject.IsSeqTwoByteString()) {
return reinterpret_cast<const byte*>(
SeqTwoByteString::cast(subject).GetChars(no_gc) + start_index);
} else if (subject.IsExternalOneByteString()) {
return reinterpret_cast<const byte*>(
ExternalOneByteString::cast(subject).GetChars() + start_index);
} else {
DCHECK(subject.IsExternalTwoByteString());
return reinterpret_cast<const byte*>(
ExternalTwoByteString::cast(subject).GetChars() + start_index);
}
}
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void String::WriteToFlat(
String source, uint16_t* sink, int from, int to);
} // namespace internal
} // namespace v8
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4dc3a3528f77e3ce561e410b48be718e3427d376 | 7ccdcc27e50526d568dfe2918aabfb172ef41b62 | /mysrc/maximumSubarray/maximunSubarray.cpp | 456288c3b1157c04bb33d6e257ef4a957770d6dc | [] | no_license | albin3/leetcode | 71c30df4a7a778b2ce10619a244b7bc2a5122f33 | c458f80ec4a493f3b104883f6fa54321386f58a9 | refs/heads/master | 2021-01-22T15:22:32.827552 | 2015-08-12T10:08:59 | 2015-08-12T10:08:59 | 26,163,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,209 | cpp | // Source : https://leetcode.com/problems/maximum-subarray/
// Author: Albin Zeng.
// Date: 2015-06-23
/**********************************************************************************************************
*
* Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
*
* For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
* the contiguous subarray [4,−1,2,1] has the largest sum = 6.
*
* click to show more practice.
*
* More practice:
* If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
*
*********************************************************************************************************/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() < 1) return 0;
int max = -(int)(((unsigned int)-1)/2)-1;
int currentsum = 0;
for (int i=0; i<nums.size(); i++) {
currentsum += nums[i];
max = max > currentsum ? max : currentsum;
currentsum = currentsum > 0 ? currentsum : 0;
}
return max;
}
};
| [
"binwei.zeng3@gmail.com"
] | binwei.zeng3@gmail.com |
d0a5e46aede2b2a29914b0da204133c410ea0866 | df119a8da7d9a721acdfac57ddd08a3492a3e6f0 | /DoublyLinkedList.h | 916b5b0a62c85b04711779a10d328579d657c978 | [] | no_license | Rajat-Chapman/Assignment4 | 50f49f5e3c65191dbfd3fbbf4f8d70354cb15de2 | f6bc864335ed1a67084e14daa6b3172013608eb1 | refs/heads/master | 2022-04-22T15:29:10.677090 | 2020-04-23T05:16:20 | 2020-04-23T05:16:20 | 258,100,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,860 | h | #include <iostream>
#include "ListNode.h"
using namespace std;
template <class T>
class DoublyLinkedList {
public:
ListNode<T> *front;
ListNode<T> *back;
unsigned int size;
DoublyLinkedList() {
size = 0;
front = NULL;
back = NULL;
}
~DoublyLinkedList() {
};
void insertBack(T d) {
ListNode<T> *node = new ListNode<T>(d);
// IF LIST IS EMPTY
if (size == 0) {
front = node;
} else {
back->next = node;
node->prev = back;
}
back = node;
size++;
}
T removeFront() {
if (!isEmpty()) {
ListNode<T> *oldFront = front;
T oldData = oldFront->data;
// IF THERE IS ONLY ONE ELEMENT
if (front->next == NULL) {
front = NULL;
back = NULL;
} else {
// MORE THAN ONE ELEMENT
front->next->prev = NULL;
front = front->next;
}
delete oldFront;
size--;
return oldData;
} else {
return T();
}
}
void removeAt(int pos) {
int index = 0;
ListNode<T> *current = front;
ListNode<T> *previous = front;
while (index != pos) {
previous = current;
current = current->next;
++index;
}
// WE FOUND WHAT NEEDS TO BE DELETED
previous->next = current->next;
current->next->previous = previous;
current->next = NULL;
current->previous = NULL;
current->data = NULL;
size--;
delete current;
}
T getFront() {
return front->data;
}
void printList() {
ListNode<T> *current = front;
while (true)
{
if (current->next == NULL)
{
break;
}
cout << current->data << ", ";
current = current->next;
}
}
int getSize() {
return size;
}
bool isEmpty() {
return (size == 0);
}
};
| [
"noreply@github.com"
] | noreply@github.com |
43d0a7ee67cb82ecdfb237c42787241662a5bade | 413f1cf03d1679397745373432aacfd2dc2c90c4 | /src/include/ulib/win32/ResourceData.hpp | 000e9f0500ec80a18972baa9f488e69d02159bdb | [
"BSD-2-Clause"
] | permissive | vividos/UlibCpp | 2a0c52c2083099483292dd7da967356983763508 | 919e8442c3581de9928369619809a92095625078 | refs/heads/main | 2023-06-01T08:14:54.161523 | 2023-05-14T12:44:12 | 2023-05-14T12:44:12 | 99,147,108 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | hpp | //
// ulib - a collection of useful classes
// Copyright (C) 2004,2005,2006,2007,2008,2011,2017 Michael Fink
//
/// \file ResourceData.hpp resource data class
//
#pragma once
#include <vector>
namespace Win32
{
/// \brief Resource data helper
/// This class extracts resource data (that may be stored as RT_RCDATA type)
/// and extracts it as string or file on disk.
class ResourceData
{
public:
/// ctor
ResourceData(LPCTSTR resourceName, LPCTSTR resourceType = _T("\"RT_RCDATA\""), HINSTANCE instanceHandle = nullptr);
/// returns true if the resource is available
bool IsAvailable() const;
/// returns resource data as byte array
bool AsRawData(std::vector<BYTE>& rawData);
/// returns resource data as string
CString AsString(bool storedAsUnicode = false);
/// saves resource data as file
bool AsFile(LPCTSTR filename);
private:
/// retrieves resource as void pointer and returns size
LPVOID GetResource(DWORD& size);
/// closes resource handle
void CloseResource();
private:
/// resource name
LPCTSTR m_resourceName;
/// resource type
LPCTSTR m_resourceType;
/// locked global memory pointer to resource
HGLOBAL m_global;
/// size of resource
DWORD m_size;
/// instance handle to search for resource
HINSTANCE m_instanceHandle;
};
} // namespace Win32
| [
"michael.fink@asamnet.de"
] | michael.fink@asamnet.de |
7f90efebf835fadc388c34f0f4a697986e453e68 | 90b2bbba2d3187136ef0441208ad999a74f416e6 | /architectures.h | dd9644b93e581b4cf3522a247e7939471b9fa42b | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | mewbak/binexport | 3d70631576583384a045ae621b2c299bfc716a03 | dfc35494579abeed5ed2a99ee801365bba64dc4e | refs/heads/master | 2020-05-20T23:12:16.591197 | 2019-12-04T16:41:55 | 2019-12-04T16:41:55 | 53,541,746 | 0 | 0 | null | 2016-03-10T00:18:55 | 2016-03-10T00:18:54 | null | UTF-8 | C++ | false | false | 859 | h | // Copyright 2011-2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ARCHITECTURES_H_
#define ARCHITECTURES_H_
namespace security::binexport {
enum class Architecture {
kArm,
kAArch64,
kDex,
kMsil,
kX86Arch32,
kX86Arch64,
};
} // namespace security::binexport
#endif // ARCHITECTURES_H_
| [
"cblichmann@google.com"
] | cblichmann@google.com |
6f2694fc276822004b7ee883f59034f541e6a241 | c7979f4f6435fe8d0d07fff7a430da55e3592aed | /half_marathon/A.cpp | aaecc2749000dbd13fa4749eb8f4180347563b8d | [] | no_license | banboooo044/AtCoder | cee87d40bb98abafde19017f4f4e2f984544b9f8 | 7541d521cf0da848ecb5eb10ffea7d75a44cbbb6 | refs/heads/master | 2020-04-14T11:35:24.977457 | 2019-09-17T03:20:27 | 2019-09-17T03:20:27 | 163,818,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,181 | cpp | #include <bits/stdc++.h>
#define REP(i,n) for (long i=0;i<(n);i++)
#define FOR(i,a,b) for (long i=(a);i<(b);i++)
#define RREP(i,n) for(long i=n;i>=0;i--)
#define RFOR(i,a,b) for(long i=(a);i>(b);i--)
#define dump1d_arr(array) REP(i,array.size()) cerr << #array << "[" << (i) << "] ==> " << (array[i]) << endl;
#define dump2d_arr(array) REP(i,array.size()) REP(j,array[i].size()) cerr << #array << "[" << (i) << "]" << "[" << (j) << "] ==> " << (array[i][j]) << endl;
#define dump(x) cerr << #x << " => " << (x) << endl;
#define CLR(vec) { REP(i,vec.size()) vec[i] = 0; }
#define llINF (long long) 9223372036854775807
#define loINF (long) 2147483647
#define shINF (short) 32767
#define SORT(c) sort((c).begin(),(c).end())
using namespace std;
typedef vector<short> VI;
typedef vector<VI> VVI;
typedef map<short,VI> mp;
int main(void){
short N,K,H,W,T;
char input;
cin >> N >> K >> H >> W >> T;
mp flg;
flg[1] = flg[2] = flg[3] = flg[4] = VI(0);
REP(k,N) {
REP(i,25){
REP(j,25){
cin >> input;
if (input == '@') flg[1].push_back(k);
}
REP(j,25){
cin >> input;
if (input == '@') flg[2].push_back(k);
}
}
REP(i,25){
REP(j,25){
cin >> input;
if (input == '@') flg[3].push_back(k);
}
REP(j,25){
cin >> input;
if (input == '@') flg[4].push_back(k);
}
}
}
long flg_max = 1;
long val = flg[1].size();
//dump1d_arr(flg[1]);
FOR(i,2,5){
//dump1d_arr(flg[i]);
if (val < flg[i].size()){
flg_max = i;
val = flg[i].size();
}
}
long l = flg[flg_max].size() - 1;
REP(i,K) {
cout << flg[flg_max][l-i] << " ";
}
cout << "\n";
string ans = "";
if (flg_max == 2){
REP(k,25){
REP(i,12) ans += "LDRD";
ans += "LL";
REP(i,12) ans += "ULUR";
ans += "LL";
}
}
if (flg_max == 1){
REP(k,25){
REP(i,12) ans += "RDLD";
ans += "RR";
REP(i,12) ans += "URUL";
ans += "RR";
}
}
if (flg_max == 4){
REP(k,25){
REP(i,12) ans += "LURU";
ans += "LL";
REP(i,12) ans += "DLDR";
ans += "LL";
}
}
if (flg_max == 3){
REP(k,25){
REP(i,12) ans += "RULU";
ans += "RR";
REP(i,12) ans += "DRDL";
ans += "RR";
}
}
cout << ans << endl;
return 0;
} | [
"touhoucrisis7@gmail.com"
] | touhoucrisis7@gmail.com |
6b82c65e0b0a8cedae3bc511c82faf7fea9408f9 | 4183598a94774bc20922f6196d8e785b87cec075 | /lab9/netflix.h | 6441541a3389cf6126824e3730313c48cd1f18c7 | [] | no_license | 29iA/csc2100-2101 | 2e4c23068a8fbf3c94d5733cb26fdfbdad7bfb52 | 878dfa89210d24f6f5c5ef39aca0d2b8dd248d90 | refs/heads/master | 2016-09-01T16:08:39.400951 | 2016-04-23T01:16:50 | 2016-04-23T01:16:50 | 54,795,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | h | /*
TITLE: jellybean.cpp
AUTHOR: Cong Tuan Nguyen
DATE: 3/29/16
PURPOSE: Introduction to multiple file (header and function) and using pointer notation
*/
#ifndef _JELLYBEAN_H // Defining header file
#define _JELLYBEAN_H
#include <iostream>
#include <iomanip>
using namespace std;
// Here Lies Regular Preprocessor Directives
int* makeArray(int);
int getStudentData(int*, int);
double getAverage(int*, int);
void selectionSort(int*, int);
void printArray(int*, int);
double getMedian(int*, int);
#endif // End if statement | [
"29congtuanP@gmail.com"
] | 29congtuanP@gmail.com |
d2cf87aef580ea4f502f7aaf5d308dd49ccc3b8a | 2c0ee6c0c183082967b7e1ed928fe36a6c02ce41 | /source/libexiftool/ExifTool.h | 971644ca4c3ee8d261e14af28e4ff6dec9209a4b | [] | no_license | larc90/sockets_connect | 8792e81008402efe4aec7eba36c09a41fd6f9137 | f7becca62602e92c19fd5bf6bf5895b988c09092 | refs/heads/master | 2020-03-24T01:44:30.906244 | 2018-08-15T19:17:10 | 2018-08-15T19:17:10 | 142,349,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,066 | h | //------------------------------------------------------------------------------
// File: ExifTool.h
//
// Description: C++ library interface to Perl exiftool application script
//
// License: Copyright 2013-2018, Phil Harvey (phil at owl.phy.queensu.ca)
//
// This is software, in whole or part, is free for use in
// non-commercial applications, provided that this copyright notice
// is retained. A licensing fee may be required for use in a
// commercial application.
//
// Created: 2013-11-23 - Phil Harvey
//------------------------------------------------------------------------------
#ifndef __EXIFTOOL_H__
#define __EXIFTOOL_H__
#include "ExifToolPipe.h"
#include "TagInfo.h"
#define NOW 0
#define NEVER 1e9
#define SUMMARY_DIRECTORIES_SCANNED "directories scanned"
#define SUMMARY_DIRECTORIES_CREATED "directories created"
#define SUMMARY_FILES_FAILED_CONDITION "files failed condition"
#define SUMMARY_IMAGE_FILES_CREATED "image files created"
#define SUMMARY_IMAGE_FILES_UPDATED "image files updated"
#define SUMMARY_IMAGE_FILES_UNCHANGED "image files unchanged"
#define SUMMARY_IMAGE_FILES_MOVED "image files moved"
#define SUMMARY_IMAGE_FILES_COPIED "image files copied"
#define SUMMARY_FILE_UPDATE_ERRORS "files weren't updated due to errors"
#define SUMMARY_FILE_CREATE_ERRORS "files weren't created due to errors"
#define SUMMARY_IMAGE_FILES_READ "image files read"
#define SUMMARY_IMAGE_FILE_ERRORS "files could not be read"
#define SUMMARY_OUTPUT_FILES_CREATED "output files created"
#define SUMMARY_OUTPUT_FILES_APPENDED "output files appended"
#define SUMMARY_HARD_LINKS_CREATED "hard links created"
#define SUMMARY_HARD_LINK_ERRORS "hard links could not be created"
class ExifTool
{
public:
ExifTool(const char *exec=NULL, const char *arg1=NULL);
virtual ~ExifTool();
TagInfo *ImageInfo(const char *file, const char *opts=NULL, double timeout=NEVER);
int ExtractInfo(const char *file, const char *opts=NULL);
TagInfo *GetInfo(int cmdNum=0, double timeout=NEVER);
int SetNewValue(const char *tag=NULL, const char *value=NULL, int len=-1);
int WriteInfo(const char *file, const char *opts=NULL, TagInfo *info=NULL);
int Command(const char *cmd=NULL);
int Complete(double timeout=NEVER);
int IsRunning();
int LastComplete() { return mLastComplete; }
int LastCommand() { return mCmdNum; } // (undocumented)
void SetLastComplete(int lastComplete) { mLastComplete = lastComplete; }
char * GetOutput() { return mLastComplete > 0 ? mStdout.GetString() : NULL; }
int GetOutputLen() { return mLastComplete > 0 ? mStdout.GetStringLen() : 0; }
char * GetError() { return mLastComplete > 0 ? mStderr.GetString() : NULL; }
int GetErrorLen() { return mLastComplete > 0 ? mStderr.GetStringLen() : 0; } // (undocumented)
int GetSummary(const char *msg);
// flags to allow some ExifTool features to be disabled
// (must be set before creating ExifTool object)
static int sNoSigPipe; // set to disable SIGPIPE handler
static int sNoWatchdog; // set to disable watchdog process
private:
ExifToolPipe mStdout; // buffer for exiftool stdout read pipe
ExifToolPipe mStderr; // buffer for exiftool stderr read pipe
int mTo; // write pipe for exiftool stdin
int mPid; // exiftool application process ID
int mWatchdog; // watchdog process ID
TagInfo * mWriteInfo; // tag information to write
char * mCmdQueue; // queued command arguments (NULL if nothing queued)
int mCmdQueueLen; // length of data in command queue
int mCmdQueueSize;// size of command queue
int mLastComplete;// result of last Complete() call
int mCmdNum; // last command number
};
#endif // __EXIFTOOL_H__
| [
"noreply@github.com"
] | noreply@github.com |
16a1079e0b3f44020028751a5ef0d7465ca71e80 | 70e46e0c28ed288cf4a76938afef822576be6757 | /chapter02/demo11.cpp | de8b711f16bcc085899662d4f15bce84d7832dd6 | [] | no_license | weekend27/Cpp-Primer-Answer | 93b7fdf6ca6ff4ce1d58fe7c6734d513b5ac14a7 | f8bdbd02ed1c15586d0389a21eb8dc8e46f96e3e | refs/heads/master | 2021-01-01T06:45:07.994010 | 2015-08-07T06:32:39 | 2015-08-07T06:32:39 | 40,344,767 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | /*
reference
*/
#include <iostream>
using namespace std;
int main(){
int ival = 141024;
int &refVal = ival;
//int &refVal2; //error: a reference must be initialized
cout << refVal << endl; //141024
refVal = 0;
cout << ival << endl; //0
int &refVal3 = refVal;
cout << refVal3 << endl; //0
int i = refVal3;
cout << i << endl; //0
// int &refVal4 = 10; //error: initializer must be an object
// cout << refVal4 << endl;
// double &refVal5 = ival; //error: initializer must be an int object
// cout << refVal5 << endl;
int j = 3.01; //truncated
cout << j << endl;
return 0;
} | [
"weekend27@163.com"
] | weekend27@163.com |
b1c5f9b073c59cad03e72e52dd31b038b34aaa9f | 38c10c01007624cd2056884f25e0d6ab85442194 | /content/shell/browser/layout_test/layout_test_content_browser_client.cc | 9039997d14930d7caf01b4d2b8ac00a6d5bb5731 | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 2,836 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/shell/browser/layout_test/layout_test_content_browser_client.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigator_connect_context.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/shell/browser/layout_test/layout_test_browser_context.h"
#include "content/shell/browser/layout_test/layout_test_message_filter.h"
#include "content/shell/browser/layout_test/layout_test_navigator_connect_service_factory.h"
#include "content/shell/browser/layout_test/layout_test_notification_manager.h"
#include "content/shell/browser/shell_browser_context.h"
#include "content/shell/common/shell_messages.h"
#include "content/shell/renderer/layout_test/blink_test_helpers.h"
namespace content {
namespace {
LayoutTestContentBrowserClient* g_layout_test_browser_client;
} // namespace
LayoutTestContentBrowserClient::LayoutTestContentBrowserClient() {
DCHECK(!g_layout_test_browser_client);
layout_test_notification_manager_.reset(new LayoutTestNotificationManager());
g_layout_test_browser_client = this;
}
LayoutTestContentBrowserClient::~LayoutTestContentBrowserClient() {
g_layout_test_browser_client = nullptr;
}
LayoutTestContentBrowserClient* LayoutTestContentBrowserClient::Get() {
return g_layout_test_browser_client;
}
LayoutTestBrowserContext*
LayoutTestContentBrowserClient::GetLayoutTestBrowserContext() {
return static_cast<LayoutTestBrowserContext*>(browser_context());
}
LayoutTestNotificationManager*
LayoutTestContentBrowserClient::GetLayoutTestNotificationManager() {
return layout_test_notification_manager_.get();
}
void LayoutTestContentBrowserClient::RenderProcessWillLaunch(
RenderProcessHost* host) {
ShellContentBrowserClient::RenderProcessWillLaunch(host);
StoragePartition* partition =
BrowserContext::GetDefaultStoragePartition(browser_context());
host->AddFilter(new LayoutTestMessageFilter(
host->GetID(),
partition->GetDatabaseTracker(),
partition->GetQuotaManager(),
partition->GetURLRequestContext()));
host->Send(new ShellViewMsg_SetWebKitSourceDir(GetWebKitRootDirFilePath()));
}
PlatformNotificationService*
LayoutTestContentBrowserClient::GetPlatformNotificationService() {
return layout_test_notification_manager_.get();
}
void LayoutTestContentBrowserClient::GetAdditionalNavigatorConnectServices(
const scoped_refptr<NavigatorConnectContext>& context) {
context->AddFactory(
make_scoped_ptr(new LayoutTestNavigatorConnectServiceFactory));
}
} // namespace content
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
f72a66821b166429785b8bc5931b206f62b92f45 | 4f30eb741ecc4f9e21c0bc527bff1260ba468974 | /src/yb/master/backfill_index.cc | ec31356139e1285c82b5ba05f7a49c7d73e04d97 | [
"OpenSSL",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hectorgcr/yugabyte-db | b677be3dedc0ae2445b76adbdc3314bc54e86631 | b87e6428c47b7408f665adaddf7e4e3333546046 | refs/heads/master | 2022-04-16T17:37:00.809784 | 2020-04-10T23:08:58 | 2020-04-10T23:08:58 | 106,061,322 | 1 | 0 | null | 2017-10-07T00:37:03 | 2017-10-07T00:37:03 | null | UTF-8 | C++ | false | false | 38,710 | cc | // Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/master/backfill_index.h"
#include <stdlib.h>
#include <algorithm>
#include <bitset>
#include <functional>
#include <mutex>
#include <set>
#include <unordered_map>
#include <vector>
#include <glog/logging.h>
#include <boost/optional.hpp>
#include <boost/thread/shared_mutex.hpp>
#include "yb/common/common_flags.h"
#include "yb/common/partial_row.h"
#include "yb/common/partition.h"
#include "yb/common/roles_permissions.h"
#include "yb/common/wire_protocol.h"
#include "yb/consensus/consensus.h"
#include "yb/consensus/consensus.proxy.h"
#include "yb/consensus/consensus_peers.h"
#include "yb/consensus/quorum_util.h"
#include "yb/gutil/atomicops.h"
#include "yb/gutil/map-util.h"
#include "yb/gutil/mathlimits.h"
#include "yb/gutil/stl_util.h"
#include "yb/gutil/strings/escaping.h"
#include "yb/gutil/strings/join.h"
#include "yb/gutil/strings/substitute.h"
#include "yb/gutil/sysinfo.h"
#include "yb/gutil/walltime.h"
#include "yb/master/async_rpc_tasks.h"
#include "yb/master/catalog_loaders.h"
#include "yb/master/catalog_manager_bg_tasks.h"
#include "yb/master/catalog_manager_util.h"
#include "yb/master/cluster_balance.h"
#include "yb/master/master.h"
#include "yb/master/master.pb.h"
#include "yb/master/master.proxy.h"
#include "yb/master/master_util.h"
#include "yb/master/sys_catalog.h"
#include "yb/master/system_tablet.h"
#include "yb/master/tasks_tracker.h"
#include "yb/master/ts_descriptor.h"
#include "yb/master/ts_manager.h"
#include "yb/master/yql_aggregates_vtable.h"
#include "yb/master/yql_auth_resource_role_permissions_index.h"
#include "yb/master/yql_auth_role_permissions_vtable.h"
#include "yb/master/yql_auth_roles_vtable.h"
#include "yb/master/yql_columns_vtable.h"
#include "yb/master/yql_empty_vtable.h"
#include "yb/master/yql_functions_vtable.h"
#include "yb/master/yql_indexes_vtable.h"
#include "yb/master/yql_keyspaces_vtable.h"
#include "yb/master/yql_local_vtable.h"
#include "yb/master/yql_partitions_vtable.h"
#include "yb/master/yql_peers_vtable.h"
#include "yb/master/yql_size_estimates_vtable.h"
#include "yb/master/yql_tables_vtable.h"
#include "yb/master/yql_triggers_vtable.h"
#include "yb/master/yql_types_vtable.h"
#include "yb/master/yql_views_vtable.h"
#include "yb/rpc/messenger.h"
#include "yb/tserver/ts_tablet_manager.h"
#include "yb/tablet/operations/change_metadata_operation.h"
#include "yb/tablet/tablet.h"
#include "yb/tablet/tablet_metadata.h"
#include "yb/tserver/tserver_admin.proxy.h"
#include "yb/yql/redis/redisserver/redis_constants.h"
#include "yb/util/crypt.h"
#include "yb/util/debug-util.h"
#include "yb/util/debug/trace_event.h"
#include "yb/util/flag_tags.h"
#include "yb/util/logging.h"
#include "yb/util/math_util.h"
#include "yb/util/monotime.h"
#include "yb/util/random_util.h"
#include "yb/util/rw_mutex.h"
#include "yb/util/stopwatch.h"
#include "yb/util/thread.h"
#include "yb/util/thread_restrictions.h"
#include "yb/util/threadpool.h"
#include "yb/util/trace.h"
#include "yb/util/tsan_util.h"
#include "yb/util/uuid.h"
#include "yb/client/client.h"
#include "yb/client/meta_cache.h"
#include "yb/client/table_creator.h"
#include "yb/client/table_handle.h"
#include "yb/client/yb_table_name.h"
#include "yb/tserver/remote_bootstrap_client.h"
DEFINE_int32(index_backfill_rpc_timeout_ms, 1 * 60 * 1000, // 1 min.
"Timeout used by the master when attempting to backfilll a tablet "
"during index creation.");
TAG_FLAG(index_backfill_rpc_timeout_ms, advanced);
TAG_FLAG(index_backfill_rpc_timeout_ms, runtime);
DEFINE_int32(index_backfill_rpc_max_retries, 150,
"Number of times to retry backfilling a tablet chunk "
"during index creation.");
TAG_FLAG(index_backfill_rpc_max_retries, advanced);
TAG_FLAG(index_backfill_rpc_max_retries, runtime);
DEFINE_int32(index_backfill_rpc_max_delay_ms, 10 * 60 * 1000, // 10 min.
"Maximum delay before retrying a backfill tablet chunk request "
"during index creation.");
TAG_FLAG(index_backfill_rpc_max_delay_ms, advanced);
TAG_FLAG(index_backfill_rpc_max_delay_ms, runtime);
DEFINE_int32(index_backfill_wait_for_alter_table_completion_ms, 100,
"Delay before retrying to see if an in-progress alter table has "
"completed, during index backfill.");
TAG_FLAG(index_backfill_wait_for_alter_table_completion_ms, advanced);
TAG_FLAG(index_backfill_wait_for_alter_table_completion_ms, runtime);
DEFINE_test_flag(int32, TEST_slowdown_backfill_alter_table_rpcs_ms, 0,
"Slows down the send alter table rpc's so that the master may be stopped between "
"different phases.");
namespace yb {
namespace master {
using namespace std::literals;
using strings::Substitute;
using tserver::TabletServerErrorPB;
Status MultiStageAlterTable::UpdateIndexPermission(
CatalogManager *catalog_manager,
const scoped_refptr<TableInfo>& indexed_table,
const TableId& index_table_id,
IndexPermissions new_perm) {
DVLOG(3) << __PRETTY_FUNCTION__ << yb::ToString(*indexed_table);
if (FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms > 0) {
TRACE("Sleeping for $0 ms", FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms);
DVLOG(3) << __PRETTY_FUNCTION__ << yb::ToString(*indexed_table) << " sleeping for "
<< FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms
<< "ms BEFORE updating the index permission to " << IndexPermissions_Name(new_perm);
SleepFor(MonoDelta::FromMilliseconds(FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms));
DVLOG(3) << __PRETTY_FUNCTION__ << "Done Sleeping";
TRACE("Done Sleeping");
}
{
TRACE("Locking indexed table");
auto l = indexed_table->LockForWrite();
auto &indexed_table_data = *l->mutable_data();
indexed_table_data.pb.mutable_fully_applied_schema()->CopyFrom(
indexed_table_data.pb.schema());
VLOG(1) << "Setting fully_applied_schema_version to "
<< indexed_table_data.pb.version();
indexed_table_data.pb.set_fully_applied_schema_version(
indexed_table_data.pb.version());
indexed_table_data.pb.mutable_fully_applied_indexes()->CopyFrom(
indexed_table_data.pb.indexes());
if (indexed_table_data.pb.has_index_info()) {
indexed_table_data.pb.mutable_fully_applied_index_info()->CopyFrom(
indexed_table_data.pb.index_info());
}
bool updated = false;
auto old_schema_version = indexed_table_data.pb.version();
for (int i = 0; i < indexed_table_data.pb.indexes_size(); i++) {
IndexInfoPB *idx_pb = indexed_table_data.pb.mutable_indexes(i);
if (idx_pb->table_id() == index_table_id) {
IndexPermissions old_perm = idx_pb->index_permissions();
if (old_perm == new_perm) {
LOG(INFO) << "The index permission"
<< " for index table id : " << yb::ToString(index_table_id)
<< " seems to have already been updated to "
<< IndexPermissions_Name(new_perm)
<< " by somebody else. This is OK.";
return STATUS_SUBSTITUTE(
AlreadyPresent, "IndexPermissions for $0 is already $1",
index_table_id, IndexPermissions_Name(new_perm));
}
idx_pb->set_index_permissions(new_perm);
VLOG(1) << "Updating index permissions "
<< " from " << IndexPermissions_Name(old_perm) << " to "
<< IndexPermissions_Name(new_perm) << " schema_version from " << old_schema_version
<< " to " << old_schema_version + 1 << ". New index info would be "
<< yb::ToString(idx_pb);
updated = true;
break;
}
}
if (!updated) {
LOG(WARNING) << "Could not find the desired index "
<< yb::ToString(index_table_id)
<< " to update in the indexed_table "
<< yb::ToString(indexed_table_data.pb)
<< "\nThis may be OK, if the index was deleted.";
return STATUS_SUBSTITUTE(
InvalidArgument, "Could not find the desired index $0", index_table_id);
}
VLOG(1) << "Before updating indexed_table_data.pb.version() is "
<< indexed_table_data.pb.version();
indexed_table_data.pb.set_version(indexed_table_data.pb.version() + 1);
VLOG(1) << "After updating indexed_table_data.pb.version() is "
<< indexed_table_data.pb.version();
indexed_table_data.set_state(SysTablesEntryPB::ALTERING,
Substitute("Alter table version=$0 ts=$1",
indexed_table_data.pb.version(),
LocalTimeAsString()));
// Update sys-catalog with the new indexed table info.
TRACE("Updating indexed table metadata on disk");
RETURN_NOT_OK(catalog_manager->sys_catalog_->UpdateItem(
indexed_table.get(), catalog_manager->leader_ready_term_));
// Update the in-memory state.
TRACE("Committing in-memory state");
l->Commit();
}
if (PREDICT_FALSE(FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms > 0)) {
TRACE("Sleeping for $0 ms",
FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms);
DVLOG(3) << __PRETTY_FUNCTION__ << yb::ToString(*indexed_table) << " sleeping for "
<< FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms
<< "ms AFTER updating the index permission to " << IndexPermissions_Name(new_perm);
SleepFor(MonoDelta::FromMilliseconds(FLAGS_TEST_slowdown_backfill_alter_table_rpcs_ms));
DVLOG(3) << __PRETTY_FUNCTION__ << "Done Sleeping";
TRACE("Done Sleeping");
}
return Status::OK();
}
Status MultiStageAlterTable::StartBackfillingData(
CatalogManager *catalog_manager,
const scoped_refptr<TableInfo> &indexed_table, const IndexInfoPB index_pb) {
if (indexed_table->IsBackfilling()) {
LOG(WARNING) << __func__ << " Not starting backfill for "
<< indexed_table->ToString() << " one is already in progress ";
return STATUS(AlreadyPresent, "Backfill already in progress");
}
VLOG(1) << __func__ << " starting backfill on " << indexed_table->ToString()
<< " for " << index_pb.table_id();
{
TRACE("Locking indexed table");
auto l = indexed_table->LockForWrite();
auto &indexed_table_data = *l->mutable_data();
indexed_table_data.pb.mutable_fully_applied_schema()->CopyFrom(
indexed_table_data.pb.schema());
VLOG(1) << "Setting fully_applied_schema_version to "
<< indexed_table_data.pb.version();
indexed_table_data.pb.set_fully_applied_schema_version(
indexed_table_data.pb.version());
indexed_table_data.pb.mutable_fully_applied_indexes()->CopyFrom(
indexed_table_data.pb.indexes());
if (indexed_table_data.pb.has_index_info()) {
indexed_table_data.pb.mutable_fully_applied_index_info()->CopyFrom(
indexed_table_data.pb.index_info());
}
// Update sys-catalog with the new indexed table info.
TRACE("Updating indexed table metadata on disk");
RETURN_NOT_OK_PREPEND(
catalog_manager->sys_catalog_->UpdateItem(
indexed_table.get(), catalog_manager->leader_ready_term_),
"Updating indexed table metadata on disk. Abandoning.");
// Update the in-memory state.
TRACE("Committing in-memory state");
l->Commit();
}
indexed_table->SetIsBackfilling(true);
auto backfill_table = std::make_shared<BackfillTable>(
catalog_manager->master_, catalog_manager->worker_pool_.get(),
indexed_table, std::vector<IndexInfoPB>{index_pb});
backfill_table->Launch();
return Status::OK();
}
bool MultiStageAlterTable::LaunchNextTableInfoVersionIfNecessary(
CatalogManager* catalog_manager, const scoped_refptr<TableInfo>& indexed_table) {
DVLOG(3) << __PRETTY_FUNCTION__ << yb::ToString(*indexed_table);
// Add index info to indexed table and increment schema version.
bool updated = false;
IndexInfoPB index_info_to_update;
{
TRACE("Locking indexed table");
VLOG(1) << ("Locking indexed table");
auto l = indexed_table->LockForRead();
for (int i = 0; i < l->data().pb.indexes_size(); i++) {
const IndexInfoPB& idx_pb = l->data().pb.indexes(i);
if (idx_pb.has_index_permissions() &&
idx_pb.index_permissions() < INDEX_PERM_READ_WRITE_AND_DELETE) {
index_info_to_update = idx_pb;
// Until we get to #2784, we'll have only one index being built at a time.
LOG_IF(DFATAL, updated) << "For now, we cannot have multiple indexes build in parallel.";
updated = true;
}
}
}
if (!updated) {
TRACE("Not necessary to launch next version");
VLOG(1) << "Not necessary to launch next version : " << yb::ToString(index_info_to_update);
return false;
}
const IndexPermissions old_perm = index_info_to_update.index_permissions();
if (old_perm == INDEX_PERM_DELETE_ONLY || old_perm == INDEX_PERM_WRITE_AND_DELETE) {
const IndexPermissions new_perm =
(old_perm == INDEX_PERM_DELETE_ONLY ? INDEX_PERM_WRITE_AND_DELETE : INDEX_PERM_DO_BACKFILL);
Status s = UpdateIndexPermission(catalog_manager, indexed_table,
index_info_to_update.table_id(), new_perm);
if (!s.ok()) {
LOG(WARNING) << "Could not update permission to "
<< IndexPermissions_Name(new_perm)
<< " Possible that the master-leader has changed, or a race "
"with another thread trying to launch next version. "
<< s;
} else {
catalog_manager->SendAlterTableRequest(indexed_table);
}
} else {
LOG_IF(DFATAL, old_perm != INDEX_PERM_DO_BACKFILL)
<< "Expect the old permission to be "
<< "INDEX_PERM_DO_BACKFILL found " << IndexPermissions_Name(old_perm)
<< " instead.";
TRACE("Starting backfill process");
VLOG(1) << ("Starting backfill process");
WARN_NOT_OK(StartBackfillingData(catalog_manager, indexed_table.get(), index_info_to_update),
"Could not launch Backfill");
}
return true;
}
// -----------------------------------------------------------------------------------------------
// BackfillTableJob
// -----------------------------------------------------------------------------------------------
std::string BackfillTableJob::description() const {
const std::shared_ptr<BackfillTable> retain_bt = backfill_table_;
auto curr_state = state();
if (!IsStateTerminal(curr_state) && retain_bt) {
return retain_bt->description();
} else if (curr_state == MonitoredTaskState::kFailed) {
return Format("Backfilling $0 Failed", index_ids_);
} else if (curr_state == MonitoredTaskState::kAborted) {
return Format("Backfilling $0 Aborted", index_ids_);
} else {
DCHECK(curr_state == MonitoredTaskState::kComplete);
return Format("Backfilling $0 Done", index_ids_);
}
}
MonitoredTaskState BackfillTableJob::AbortAndReturnPrevState() {
auto old_state = state();
while (!IsStateTerminal(old_state)) {
if (state_.compare_exchange_strong(old_state,
MonitoredTaskState::kAborted)) {
return old_state;
}
old_state = state();
}
return old_state;
}
void BackfillTableJob::SetState(MonitoredTaskState new_state) {
auto old_state = state();
if (!IsStateTerminal(old_state)) {
if (state_.compare_exchange_strong(old_state, new_state) && IsStateTerminal(new_state)) {
MarkDone();
}
}
}
// -----------------------------------------------------------------------------------------------
// BackfillTable
// -----------------------------------------------------------------------------------------------
BackfillTable::BackfillTable(Master *master, ThreadPool *callback_pool,
const scoped_refptr<TableInfo> &indexed_table,
std::vector<IndexInfoPB> indexes)
: master_(master), callback_pool_(callback_pool),
indexed_table_(indexed_table), indexes_to_build_(indexes) {
LOG_IF(DFATAL, indexes_to_build_.size() != 1)
<< "As of Dec 2019, we only support "
<< "building one index at a time. indexes_to_build_.size() = "
<< indexes_to_build_.size();
std::ostringstream out;
out << "{ ";
bool first = true;
for (const auto &index_info : indexes_to_build_) {
if (!first) {
out << ", ";
}
out << master_->catalog_manager()->GetTableInfo(index_info.table_id())->name();
first = false;
}
out << " }";
index_ids_ = out.str();
auto l = indexed_table_->LockForRead();
schema_version_ = indexed_table_->metadata().state().pb.version();
leader_term_ = master_->catalog_manager()->leader_ready_term();
const auto &properties =
indexed_table_->metadata().state().pb.schema().table_properties();
if (properties.has_backfilling_timestamp() &&
read_time_for_backfill_.FromUint64(properties.backfilling_timestamp()).ok()) {
timestamp_chosen_.store(true, std::memory_order_release);
VLOG_WITH_PREFIX(1) << "Will be using " << read_time_for_backfill_
<< " for backfill";
} else {
read_time_for_backfill_ = HybridTime::kInvalid;
timestamp_chosen_.store(false, std::memory_order_release);
}
done_.store(false, std::memory_order_release);
}
void BackfillTable::Launch() {
backfill_job_ = std::make_shared<BackfillTableJob>(shared_from_this());
backfill_job_->SetState(MonitoredTaskState::kRunning);
master_->catalog_manager()->jobs_tracker_->AddTask(backfill_job_);
if (!timestamp_chosen_.load(std::memory_order_acquire)) {
LaunchComputeSafeTimeForRead();
} else {
LaunchBackfill();
}
}
void BackfillTable::LaunchComputeSafeTimeForRead() {
vector<scoped_refptr<TabletInfo>> tablets;
indexed_table_->GetAllTablets(&tablets);
num_tablets_.store(tablets.size(), std::memory_order_release);
tablets_pending_.store(tablets.size(), std::memory_order_release);
auto min_cutoff = master()->clock()->Now();
for (const scoped_refptr<TabletInfo>& tablet : tablets) {
auto get_safetime = std::make_shared<GetSafeTimeForTablet>(
shared_from_this(), tablet, min_cutoff);
get_safetime->Launch();
}
}
std::string BackfillTable::LogPrefix() const {
return Format("Backfill Index Table(s) $0 ", index_ids_);
}
std::string BackfillTable::description() const {
auto num_pending = tablets_pending_.load(std::memory_order_acquire);
auto num_tablets = num_tablets_.load(std::memory_order_acquire);
return Format(
"Backfill Index Table(s) $0 : $1", index_ids_,
(timestamp_chosen()
? (done() ? Format("Backfill $0/$1 tablets done", num_pending, num_tablets)
: Format("Backfilling $0/$1 tablets", num_pending, num_tablets))
: Format("Waiting to GetSafeTime from $0/$1 tablets", num_pending, num_tablets)));
}
Status BackfillTable::UpdateSafeTime(const Status& s, HybridTime ht) {
if (!s.ok()) {
// Move on to ABORTED permission.
LOG_WITH_PREFIX(ERROR)
<< "Failed backfill. Could not compute safe time for "
<< yb::ToString(indexed_table_) << s;
if (!timestamp_chosen_.exchange(true)) {
RETURN_NOT_OK_PREPEND(AlterTableStateToAbort(),
"Failed to mark backfill as failed. Abandoning.");
}
return Status::OK();
}
// Need to guard this.
HybridTime read_timestamp;
{
std::lock_guard<simple_spinlock> l(mutex_);
VLOG(2) << " Updating read_time_for_backfill_ to max{ "
<< read_time_for_backfill_.ToString() << ", " << ht.ToString()
<< " }.";
read_time_for_backfill_.MakeAtLeast(ht);
read_timestamp = read_time_for_backfill_;
}
// If OK then move on to READ permissions.
if (!timestamp_chosen() && --tablets_pending_ == 0) {
LOG_WITH_PREFIX(INFO) << "Completed fetching SafeTime for the table "
<< yb::ToString(indexed_table_) << " will be using "
<< read_timestamp.ToString();
{
auto l = indexed_table_->LockForWrite();
l->mutable_data()
->pb.mutable_schema()
->mutable_table_properties()
->set_backfilling_timestamp(read_timestamp.ToUint64());
RETURN_NOT_OK_PREPEND(
master_->catalog_manager()->sys_catalog_->UpdateItem(
indexed_table_.get(), leader_term()),
"Failed to persist backfilling timestamp. Abandoning.");
l->Commit();
}
VLOG_WITH_PREFIX(2) << "Saved " << read_timestamp
<< " as backfilling_timestamp";
timestamp_chosen_.store(true, std::memory_order_release);
LaunchBackfill();
}
return Status::OK();
}
void BackfillTable::LaunchBackfill() {
VLOG_WITH_PREFIX(1) << "launching backfill with timestamp: "
<< read_time_for_backfill_;
vector<scoped_refptr<TabletInfo>> tablets;
indexed_table_->GetAllTablets(&tablets);
num_tablets_.store(tablets.size(), std::memory_order_release);
tablets_pending_.store(tablets.size(), std::memory_order_release);
for (const scoped_refptr<TabletInfo>& tablet : tablets) {
auto backfill_tablet = std::make_shared<BackfillTablet>(shared_from_this(), tablet);
backfill_tablet->Launch();
}
}
void BackfillTable::Done(const Status& s) {
if (!s.ok()) {
// Move on to ABORTED permission.
LOG_WITH_PREFIX(ERROR) << "Failed to backfill the index " << s;
if (!done_.exchange(true)) {
WARN_NOT_OK(AlterTableStateToAbort(),
"Failed to mark backfill as failed.");
} else {
LOG_WITH_PREFIX(INFO)
<< "Some body else already aborted the index backfill.";
}
return;
}
// If OK then move on to READ permissions.
if (!done() && --tablets_pending_ == 0) {
LOG_WITH_PREFIX(INFO) << "Completed backfilling the index table.";
done_.store(true, std::memory_order_release);
WARN_NOT_OK(AlterTableStateToSuccess(), "Failed to complete backfill.");
}
}
Status BackfillTable::AlterTableStateToSuccess() {
const TableId& index_table_id = indexes()[0].table_id();
RETURN_NOT_OK_PREPEND(MultiStageAlterTable::UpdateIndexPermission(
master_->catalog_manager(), indexed_table_,
index_table_id, INDEX_PERM_READ_WRITE_AND_DELETE),
"Could not update permission to "
"INDEX_PERM_READ_WRITE_AND_DELETE. Possible that the "
"master-leader has changed.");
VLOG(1) << "Sending alter table requests to the Indexed table";
master_->catalog_manager()->SendAlterTableRequest(indexed_table_);
VLOG(1) << "DONE Sending alter table requests to the Indexed table";
RETURN_NOT_OK(AllowCompactionsToGCDeleteMarkers(index_table_id));
VLOG(1) << __func__ << " done backfill on " << indexed_table_->ToString()
<< " for " << index_table_id;
indexed_table_->SetIsBackfilling(false);
backfill_job_->SetState(MonitoredTaskState::kComplete);
return ClearCheckpointStateInTablets();
}
Status BackfillTable::AlterTableStateToAbort() {
const TableId& index_table_id = indexes()[0].table_id();
RETURN_NOT_OK_PREPEND(MultiStageAlterTable::UpdateIndexPermission(
master_->catalog_manager(), indexed_table_,
index_table_id, INDEX_PERM_BACKFILL_FAILED),
"Could not update permission to "
"INDEX_PERM_BACKFILL_FAILED. Possible that the "
"master-leader has changed.");
master_->catalog_manager()->SendAlterTableRequest(indexed_table_);
indexed_table_->SetIsBackfilling(false);
backfill_job_->SetState(MonitoredTaskState::kFailed);
return ClearCheckpointStateInTablets();
}
Status BackfillTable::ClearCheckpointStateInTablets() {
vector<scoped_refptr<TabletInfo>> tablets;
indexed_table_->GetAllTablets(&tablets);
std::vector<TabletInfo*> tablet_ptrs;
for (scoped_refptr<TabletInfo>& tablet : tablets) {
tablet_ptrs.push_back(tablet.get());
tablet->mutable_metadata()->StartMutation();
tablet->mutable_metadata()->mutable_dirty()->pb.clear_backfilled_until();
}
RETURN_NOT_OK_PREPEND(
master()->catalog_manager()->sys_catalog()->UpdateItems(tablet_ptrs,
leader_term()),
"Could not persist that the table is done backfilling.");
for (scoped_refptr<TabletInfo>& tablet : tablets) {
VLOG(2) << "Done backfilling the table. " << yb::ToString(tablet)
<< " clearing backfilled_until";
tablet->mutable_metadata()->CommitMutation();
}
{
auto l = indexed_table_->LockForWrite();
l->mutable_data()
->pb.mutable_schema()
->mutable_table_properties()
->clear_backfilling_timestamp();
RETURN_NOT_OK_PREPEND(master_->catalog_manager()->sys_catalog_->UpdateItem(
indexed_table_.get(), leader_term()),
"Could not clear backfilling timestamp.");
l->Commit();
}
VLOG_WITH_PREFIX(2) << "Cleared backfilling timestamp.";
return Status::OK();
}
Status BackfillTable::AllowCompactionsToGCDeleteMarkers(
const TableId &index_table_id) {
DVLOG(3) << __PRETTY_FUNCTION__;
scoped_refptr<TableInfo> index_table_info;
TableIdentifierPB index_table_id_pb;
index_table_id_pb.set_table_id(index_table_id);
RETURN_NOT_OK_PREPEND(
master_->catalog_manager()->FindTable(index_table_id_pb,
&index_table_info),
yb::Format("Could not find table info for the index table $0 to enable "
"compactions. "
"This is ok in case somebody issued a delete index.",
yb::ToString(index_table_id)));
// Add a sleep here to wait until the Table is fully created.
bool is_ready = false;
bool first_run = true;
do {
if (!first_run) {
YB_LOG_EVERY_N_SECS(INFO, 1) << "Waiting for the previous alter table to "
"complete on the index table "
<< yb::ToString(index_table_id);
SleepFor(
MonoDelta::FromMilliseconds(FLAGS_index_backfill_wait_for_alter_table_completion_ms));
}
first_run = false;
{
VLOG(2) << __func__ << ": Trying to lock index table for Read";
auto l = index_table_info->LockForRead();
is_ready = (l->data().pb.state() == SysTablesEntryPB::RUNNING);
}
VLOG(2) << __func__ << ": Unlocked index table for Read";
} while (!is_ready);
{
TRACE("Locking index table");
VLOG(2) << __func__ << ": Trying to lock index table for Write";
auto l = index_table_info->LockForWrite();
VLOG(2) << __func__ << ": locked index table for Write";
l->mutable_data()->pb.mutable_schema()->mutable_table_properties()->set_is_backfilling(false);
// Update sys-catalog with the new indexed table info.
TRACE("Updating index table metadata on disk");
RETURN_NOT_OK_PREPEND(
master_->catalog_manager()->sys_catalog_->UpdateItem(
index_table_info.get(), leader_term()),
yb::Format(
"Could not update index_table_info for $0 to enable compactions.",
index_table_id));
// Update the in-memory state.
TRACE("Committing in-memory state");
l->Commit();
}
VLOG(2) << __func__ << ": Unlocked index table for Read";
VLOG(1) << "Sending backfill done requests to the Index table";
RETURN_NOT_OK(SendRpcToAllowCompactionsToGCDeleteMarkers(index_table_info));
VLOG(1) << "DONE Sending backfill done requests to the Index table";
return Status::OK();
}
Status BackfillTable::SendRpcToAllowCompactionsToGCDeleteMarkers(
const scoped_refptr<TableInfo> &table) {
vector<scoped_refptr<TabletInfo>> tablets;
table->GetAllTablets(&tablets);
for (const scoped_refptr<TabletInfo>& tablet : tablets) {
RETURN_NOT_OK(SendRpcToAllowCompactionsToGCDeleteMarkers(tablet));
}
return Status::OK();
}
Status BackfillTable::SendRpcToAllowCompactionsToGCDeleteMarkers(
const scoped_refptr<TabletInfo> &tablet) {
auto call = std::make_shared<AsyncBackfillDone>(master_, callback_pool_, tablet);
tablet->table()->AddTask(call);
RETURN_NOT_OK_PREPEND(call->Run(), "Failed to send backfill done request");
return Status::OK();
}
// -----------------------------------------------------------------------------------------------
// BackfillTablet
// -----------------------------------------------------------------------------------------------
BackfillTablet::BackfillTablet(
std::shared_ptr<BackfillTable> backfill_table, const scoped_refptr<TabletInfo>& tablet)
: backfill_table_(backfill_table), tablet_(tablet) {
{
auto l = tablet_->LockForRead();
Partition::FromPB(tablet_->metadata().state().pb.partition(), &partition_);
if (tablet_->metadata().state().pb.has_backfilled_until()) {
next_row_to_backfill_ = tablet_->metadata().state().pb.backfilled_until();
done_.store(next_row_to_backfill_.empty(), std::memory_order_release);
}
}
if (!next_row_to_backfill_.empty()) {
VLOG(1) << tablet_->ToString() << " resuming backfill from "
<< yb::ToString(next_row_to_backfill_);
} else if (done()) {
VLOG(1) << tablet_->ToString() << " backfill already done";
} else {
VLOG(1) << tablet_->ToString() << " begining backfill from "
<< "<start-of-the-tablet>";
}
}
void BackfillTablet::LaunchNextChunkOrDone() {
if (done()) {
backfill_table_->Done(Status::OK());
} else {
auto chunk = std::make_shared<BackfillChunk>(shared_from_this(),
next_row_to_backfill_);
chunk->Launch();
}
}
void BackfillTablet::Done(const Status& status, const string& next_row_key) {
if (!status.ok()) {
LOG(INFO) << "Failed to backfill the tablet " << yb::ToString(tablet_) << status;
backfill_table_->Done(status);
return;
}
next_row_to_backfill_ = next_row_key;
VLOG(2) << "Done backfilling the tablet " << yb::ToString(tablet_)
<< " until " << yb::ToString(next_row_to_backfill_);
{
tablet_->mutable_metadata()->StartMutation();
tablet_->mutable_metadata()->mutable_dirty()->pb.set_backfilled_until(
next_row_to_backfill_);
WARN_NOT_OK(
backfill_table_->master()->catalog_manager()->sys_catalog()->UpdateItem(
tablet_.get(), backfill_table_->leader_term()),
"Could not persist that the tablet is done backfilling.");
tablet_->mutable_metadata()->CommitMutation();
}
// This is the last chunk.
if (next_row_to_backfill_.empty()) {
LOG(INFO) << "Done backfilling the tablet " << yb::ToString(tablet_);
done_.store(true, std::memory_order_release);
}
LaunchNextChunkOrDone();
}
// -----------------------------------------------------------------------------------------------
// GetSafeTimeForTablet
// -----------------------------------------------------------------------------------------------
void GetSafeTimeForTablet::Launch() {
tablet_->table()->AddTask(shared_from_this());
Status status = Run();
// Need to print this after Run() because that's where it picks the TS which description()
// needs.
if (status.ok()) {
VLOG(3) << "Started GetSafeTimeForTablet : " << this->description();
} else {
LOG(WARNING) << Substitute("Failed to send GetSafeTime request for $0. ",
tablet_->ToString())
<< status;
}
}
bool GetSafeTimeForTablet::SendRequest(int attempt) {
VLOG(1) << __PRETTY_FUNCTION__;
tserver::GetSafeTimeRequestPB req;
req.set_dest_uuid(permanent_uuid());
req.set_tablet_id(tablet_->tablet_id());
auto now = backfill_table_->master()->clock()->Now().ToUint64();
req.set_min_hybrid_time_for_backfill(min_cutoff_.ToUint64());
req.set_propagated_hybrid_time(now);
ts_admin_proxy_->GetSafeTimeAsync(req, &resp_, &rpc_, BindRpcCallback());
VLOG(1) << "Send " << description() << " to " << permanent_uuid()
<< " (attempt " << attempt << "):\n"
<< req.DebugString();
return true;
}
void GetSafeTimeForTablet::HandleResponse(int attempt) {
VLOG(1) << __PRETTY_FUNCTION__;
Status status = Status::OK();
if (resp_.has_error()) {
status = StatusFromPB(resp_.error().status());
// Do not retry on a fatal error
switch (resp_.error().code()) {
case TabletServerErrorPB::TABLET_NOT_FOUND:
case TabletServerErrorPB::MISMATCHED_SCHEMA:
case TabletServerErrorPB::TABLET_HAS_A_NEWER_SCHEMA:
case TabletServerErrorPB::OPERATION_NOT_SUPPORTED:
LOG(WARNING) << "TS " << permanent_uuid() << ": GetSafeTime failed for tablet "
<< tablet_->ToString() << " no further retry: " << status.ToString();
TransitionToTerminalState(MonitoredTaskState::kRunning, MonitoredTaskState::kFailed);
break;
default:
LOG(WARNING) << "TS " << permanent_uuid() << ": GetSafeTime failed for tablet "
<< tablet_->ToString() << ": " << status.ToString() << " code "
<< resp_.error().code();
break;
}
} else {
TransitionToTerminalState(MonitoredTaskState::kRunning, MonitoredTaskState::kComplete);
VLOG(1) << "TS " << permanent_uuid() << ": GetSafeTime complete on tablet "
<< tablet_->ToString();
}
server::UpdateClock(resp_, master_->clock());
}
void GetSafeTimeForTablet::UnregisterAsyncTaskCallback() {
Status status;
HybridTime safe_time;
if (resp_.has_error()) {
status = StatusFromPB(resp_.error().status());
VLOG(3) << "GetSafeTime for " << tablet_->ToString() << " got an error. Returning "
<< safe_time;
} else if (state() != MonitoredTaskState::kComplete) {
status = STATUS_SUBSTITUTE(InternalError, "$0 in state $1", description(),
ToString(state()));
} else {
safe_time = HybridTime(resp_.safe_time());
if (safe_time.is_special()) {
LOG(ERROR) << "GetSafeTime for " << tablet_->ToString() << " got " << safe_time;
} else {
VLOG(3) << "GetSafeTime for " << tablet_->ToString() << " got " << safe_time;
}
}
WARN_NOT_OK(backfill_table_->UpdateSafeTime(status, safe_time),
"Could not UpdateSafeTime");
}
// -----------------------------------------------------------------------------------------------
// BackfillChunk
// -----------------------------------------------------------------------------------------------
void BackfillChunk::Launch() {
backfill_tablet_->tablet()->table()->AddTask(shared_from_this());
Status status = Run();
WARN_NOT_OK(
status, Substitute(
"Failed to send backfill Chunk request for $0",
backfill_tablet_->tablet().get()->ToString()));
// Need to print this after Run() because that's where it picks the TS which description()
// needs.
if (status.ok()) {
LOG(INFO) << "Started BackfillChunk : " << this->description();
}
}
MonoTime BackfillChunk::ComputeDeadline() {
MonoTime timeout = MonoTime::Now();
timeout.AddDelta(MonoDelta::FromMilliseconds(FLAGS_index_backfill_rpc_timeout_ms));
return MonoTime::Earliest(timeout, deadline_);
}
int BackfillChunk::num_max_retries() {
return FLAGS_index_backfill_rpc_max_retries;
}
int BackfillChunk::max_delay_ms() {
return FLAGS_index_backfill_rpc_max_delay_ms;
}
bool BackfillChunk::SendRequest(int attempt) {
VLOG(1) << __PRETTY_FUNCTION__;
tserver::BackfillIndexRequestPB req;
req.set_dest_uuid(permanent_uuid());
req.set_tablet_id(backfill_tablet_->tablet()->tablet_id());
req.set_read_at_hybrid_time(backfill_tablet_->read_time_for_backfill().ToUint64());
req.set_schema_version(backfill_tablet_->schema_version());
req.set_start_key(start_key_);
for (const IndexInfoPB& idx_info : backfill_tablet_->indexes()) {
req.add_indexes()->CopyFrom(idx_info);
}
req.set_propagated_hybrid_time(backfill_tablet_->master()->clock()->Now().ToUint64());
ts_admin_proxy_->BackfillIndexAsync(req, &resp_, &rpc_, BindRpcCallback());
VLOG(1) << "Send " << description() << " to " << permanent_uuid()
<< " (attempt " << attempt << "):\n"
<< req.DebugString();
return true;
}
void BackfillChunk::HandleResponse(int attempt) {
VLOG(1) << __PRETTY_FUNCTION__;
Status status;
if (resp_.has_error()) {
status = StatusFromPB(resp_.error().status());
// Do not retry on a fatal error
switch (resp_.error().code()) {
case TabletServerErrorPB::TABLET_NOT_FOUND:
case TabletServerErrorPB::MISMATCHED_SCHEMA:
case TabletServerErrorPB::TABLET_HAS_A_NEWER_SCHEMA:
case TabletServerErrorPB::OPERATION_NOT_SUPPORTED:
LOG(WARNING) << "TS " << permanent_uuid() << ": backfill failed for tablet "
<< backfill_tablet_->tablet()->ToString()
<< " no further retry: " << status.ToString();
TransitionToTerminalState(MonitoredTaskState::kRunning, MonitoredTaskState::kFailed);
break;
default:
LOG(WARNING) << "TS " << permanent_uuid() << ": backfill failed for tablet "
<< backfill_tablet_->tablet()->ToString() << ": " << status.ToString()
<< " code " << resp_.error().code();
break;
}
} else {
TransitionToTerminalState(MonitoredTaskState::kRunning, MonitoredTaskState::kComplete);
VLOG(1) << "TS " << permanent_uuid() << ": backfill complete on tablet "
<< backfill_tablet_->tablet()->ToString();
}
server::UpdateClock(resp_, master_->clock());
}
void BackfillChunk::UnregisterAsyncTaskCallback() {
Status status;
if (resp_.has_error()) {
status = StatusFromPB(resp_.error().status());
} else if (state() != MonitoredTaskState::kComplete) {
status = STATUS_SUBSTITUTE(InternalError, "$0 in state $1", description(),
ToString(state()));
}
backfill_tablet_->Done(status, resp_.backfilled_until());
}
} // namespace master
} // namespace yb
| [
"amitanandaiyer@users.noreply.github.com"
] | amitanandaiyer@users.noreply.github.com |
129b0194a6e5a268947c8d6854cd91161bbe87c9 | f6f783368bbfe3e2f059c40aae2fc945a07f137d | /src/main.cpp | 522e3cf1de61c05f56e21446e63921b845758dd3 | [] | no_license | jbernhard/iss-oscar | 2c07062898d60963eac0b7cfead39458027cd72c | 14f7aa4f7e73ecf6b44fbe060142ecd3cb9b2d3b | refs/heads/master | 2016-09-06T18:55:58.572981 | 2013-07-08T20:15:41 | 2013-07-08T20:15:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,853 | cpp | //===============================================================================
// iSpectraSampler
//===============================================================================
//
// Zhi Qiu & Chun Shen
// qiu.24@asc.ohio-state.edu
// shen.201@asc.ohio-state.edu
//
// Date: 03/2012
// Version info written in the main function.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <ctime>
#include <string>
#include <sstream>
#include <math.h>
#include <vector>
#include <sys/time.h>
#include <stdlib.h>
#include "main.h"
#include "ParameterReader.h"
#include "Table.h"
#include "readindata.h"
#include "emissionfunction.h"
#include "arsenal.h"
using namespace std;
int main(int argc, char** argv)
{
cout << "iSS-OSCAR hypersurface sampler" << endl
<< "written by Zhi Qiu & Chun Shen" << endl
<< "modified by Jonah Bernhard" << endl << endl;
// Chun's input reading process
string path="surface";
//load freeze out information
int FO_length = 0;
ostringstream decdatfile;
cout << " -- Loading the decoupling data....";
decdatfile << path << "/OSCAR2008H.dat";
FO_length=get_filelength(decdatfile.str());
cout <<" cells number: " << FO_length << endl;
//read the data arrays for the decoupling information
FO_surf* FOsurf_ptr = new FO_surf[FO_length];
for(int i=0; i<FO_length; i++)
for(int j=0; j<Maxparticle; j++)
FOsurf_ptr[i].particle_mu[j] = 0.0e0;
try {
read_decdat(path, FO_length, FOsurf_ptr);
} catch (const char* msg) {
cerr << msg << endl;
return 1;
}
//return 0;
//read the positions of the freeze out surface
read_surfdat(path, FO_length, FOsurf_ptr);
//read the chemical potential on the freeze out surface
int N_stableparticle;
ifstream particletable("EOS/EOS_particletable.dat");
particletable >> N_stableparticle;
double** particle_mu = new double* [N_stableparticle];
for(int i=0; i<N_stableparticle; i++)
particle_mu[i] = new double [FO_length];
if(N_stableparticle >0)
{
read_decdat_mu(path, FO_length, N_stableparticle, particle_mu);
}
//read particle resonance decay table
particle_info *particle = new particle_info [Maxparticle];
for (int i=0; i<Maxparticle; i++) particle[i].decays=0; // to avoid infinite loop
int Nparticle=read_resonance(particle);
cout <<"particle number: " << Nparticle << endl;
if(N_stableparticle >0)
{
cout << " -- EOS is partically chemical equilibrium " << endl;
calculate_particle_mu(Nparticle, FOsurf_ptr, FO_length, particle, particle_mu);
}
else
{
cout << " -- EOS is chemical equilibrium. " << endl;
for(int i=0; i<Nparticle; i++)
for(int j=0; j<FO_length; j++)
FOsurf_ptr[i].particle_mu[j] = 0.0e0;
}
cout << endl << " -- Read in data finished!" << endl << endl;
// Next, Zhi's turn...
// First other parameters; Zhi's style
ParameterReader paraRdr;
paraRdr.readFromFile("parameters.dat");
paraRdr.readFromArguments(argc, argv);
//paraRdr.echo();
// init random seed from system time
timeval a;
gettimeofday(&a, 0);
long randomSeed=paraRdr.getVal("randomSeed");
if (randomSeed<0) randomSeed=a.tv_usec; // randomSeed<0 means to use CPU clock
srand48(randomSeed);
Table chosen_particles("EOS/chosen_particles.dat"); // skip others except for these particle
Table pT_tab("tables/pT_gauss_table.dat"); // pt position and weight table
Table phi_tab("tables/phi_gauss_table.dat"); // phi position and weight table
Table eta_tab("tables/eta_gauss_table_20_full.dat"); // eta uniform dist table
EmissionFunctionArray efa(&chosen_particles, &pT_tab, &phi_tab, &eta_tab, particle, Nparticle, FOsurf_ptr, FO_length, ¶Rdr);
efa.shell();
//efa.combine_samples_to_OSCAR();
}
| [
"jeb65@grads-ad"
] | jeb65@grads-ad |
c11ec4a4c9a2af006edbe8f5fdc17bb8085be980 | 8590b7928fdcff351a6e347c4b04a085f29b7895 | /common/recorder/recorder_datarec.h | 8688c78324998bcf3b4a738fda4a42dcd2caed7c | [] | no_license | liao007/VIC-CropSyst-Package | 07fd0f29634cf28b96a299dc07156e4f98a63878 | 63a626250ccbf9020717b7e69b6c70e40a264bc2 | refs/heads/master | 2023-05-23T07:15:29.023973 | 2021-05-29T02:17:32 | 2021-05-29T02:17:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,282 | h | #ifndef recorder_datarecH
#define recorder_datarecH
#define MAX_VARIABLES_TO_RECORD 1000
#define MAX_RECORDING_OBJECTS 10
#ifndef uedH
# include "UED/library/UED.h"
#endif
#ifndef datarecH
# include "corn/data_source/datarec.h"
#endif
namespace CORN {
class Recording_object; // forward decl.
class Recorder_float32; // forward decl.
class Recorder_float64; // forward decl.
//______________________________________________________________________________
class Desired_variables_list
{
protected:
uint16 count; // When 0 allow recorders to record all variables, otherwise just the desired variables
UED::Variable_code desired_vars[MAX_VARIABLES_TO_RECORD];
public:
inline Desired_variables_list()
: count(0)
{}
void desire(UED::Variable_code new_var);
void desire(UED::Variable_code new_vars[]);
bool is_desired(UED::Variable_code variable_code);
// Searches the list of desired variables for variable_code and returns true if it is listed.
inline bool desire_all_variables() { return count == 0;}
};
//_Desired_variables_list______________________________________________________/
class Recorder_data_record
: public Data_record
, public Desired_variables_list
{
// Recording objects are no longer needed, we simply add or delete the respective sections we are interested in
// Recording_object *recording_objs[MAX_RECORDING_OBJECTS];
public:
Date_time_clad_64 date_time;
// of the current record entry.
public:
Recorder_data_record();
// Wo expect_structure() setup structure as recorders are added.
void remember(Recording_object *obj_to_remember);
void forget (Recording_object *obj_to_forget) disassociation_;
void expect_recorder(Recorder_float32 *recorder);
void expect_recorder(Recorder_float64 *recorder);
// Appends the recorder to the current section;
inline datetime64 set_date_time(datetime64 date_time64_)
{ date_time.set_datetime64(date_time64_); return date_time64_; }
};
//_Recorder_data_record________________________________________________________/
}//_namespace CORN_____________________________________________________________/
#endif
| [
"mingliang.liu@wsu.edu"
] | mingliang.liu@wsu.edu |
9e25b66b0ec14185ae33329a44cce5ad92f116d5 | 2d23a0a86c9d249315968f23645f880fa2ad606b | /scenes/dinosaurs.h | 6cf6e4fadd46bf9666c26ae69ec58662dc41daaa | [] | no_license | LyricZhao/BoArtist | ba6a92feba0b951f8db145aeae87fd765118b006 | 8fdb4c34fa952111b51eccb4c92d59e344dc85fb | refs/heads/master | 2020-04-29T11:43:53.017104 | 2019-06-15T15:08:28 | 2019-06-15T15:08:28 | 176,109,957 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,549 | h | # ifndef __DINOSAURS_H__
# define __DINOSAURS_H__
# include "../objects/api.h"
namespace dinosaurs {
int width = 2560, height = 1440, samples = 6000000;
Vector3D light_point(400, 200, 100), u(1, 0, 0), v(0, 1, 0), w(0, 0, 1);
Ray camera(Vector3D(-200, 0, 0), Vector3D(1.1, 1, 0).norm());
int iteration_time = 1000;
double dof = 3.9, r_alpha = 0.7, sppm_radius = 10, energy = 90, camera_scale = 0.5, focal_distance = 217.;
Ray ray_generator(unsigned short *seed) {
double x = erand48(seed) * 2 - 1, y = erand48(seed) * 2 - 1, z = erand48(seed) * 2 - 1;
return Ray(light_point, Vector3D(x, y, z).norm());
}
# define GRAY_SCALE 0.6
Object* objects[] = {
new Plane(Vector3D(0, 1 / 1470.0, 0), DIFF, 1.5, Texture("sources/dinosaur_texture.jpg", Color_F(0.75, 0.75, 0.75)), Color_F(), Vector3D(0, 0, -30), Vector3D(10, 0, 0), Vector3D(0, 0, 10)),
new Plane(Vector3D(0, 0, 1. / (-45)), DIFF, 1.5, Texture("sources/dinosaur_texture.jpg", Color_F(0.75, 0.75, 0.75)), Color_F(), Vector3D(0, 0, -30), Vector3D(10, 0, 0), Vector3D(0, 10, 0)),
new Mesh(Vector3D(0, 200, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(50, 350, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(100, 500, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(150, 650, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(200, 800, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(250, 950, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(300, 1000, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(350, 1150, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(400, 1300, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
new Mesh(Vector3D(450, 1450, 0), "sources/dinosaur.2k.obj", DIFF, 1.5, 1, Texture("", Color_F(rand01(), rand01(), rand01()) * GRAY_SCALE)),
};
const char output[] = "outputs/dinosaurs_dof";
};
# endif
| [
"lyricz@yeah.net"
] | lyricz@yeah.net |
a34dc4b13df55593a9fdec98a440651db8b1ebc5 | 299adc750db8d36bacdaa0ba49eedd507301459a | /ESPAlarmController/test/system_mocks/FileImpl.h | ea8a7764042c6f39d17142cb3be365b2f247ba27 | [] | no_license | jludwig75/ESPAlarmSystem | c5db08a14fd93e8d114c56730bb9c91ad9f01601 | 7b51fb5371b60713af393618e6d43b448130ac52 | refs/heads/master | 2023-03-22T11:02:29.101574 | 2021-03-20T16:54:40 | 2021-03-20T16:54:40 | 338,482,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | h | #pragma once
#include "FileData.h"
#include "FS.h"
namespace fs
{
class FSImpl;
class FileImpl
{
public:
FileImpl(FSImpl* fs, FileDataPtr data, size_t startPosition, bool readOnly);
size_t write(uint8_t c);
size_t write(const uint8_t *buf, size_t size);
int available();
int read();
int peek();
void flush();
size_t read(uint8_t* buf, size_t size);
bool seek(uint32_t pos, SeekMode mode);
size_t position() const;
size_t size() const;
void close();
time_t getLastWrite();
const char* name() const;
boolean isDirectory(void);
File openNextFile(const char* mode);
void rewindDirectory(void);
private:
FSImpl* _fs;
FileDataPtr _data;
size_t _currentOffset;
bool _readOnly;
};
} | [
"jr.ludwig@gmail.com"
] | jr.ludwig@gmail.com |
e0b643a7dfe3bc8309d4ba869d5608a2d533e0bd | 733de464662408d2ed3fa637b0c7ecdc7c281c0a | /flow/node/connector/connector.h | 7d73050747ae9928bf514e697b22175227d22413 | [
"MIT"
] | permissive | aconstlink/snakeoil | f15740eb93d3e36b656621bb57a0f7eb2592f252 | 3c6e02655e1134f8422f01073090efdde80fc109 | refs/heads/master | 2021-01-01T17:39:53.820180 | 2020-02-23T20:56:36 | 2020-02-23T20:56:36 | 98,117,868 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | h | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_FLOW_NODE_CONNECTOR_CONNECTOR_H_
#define _SNAKEOIL_FLOW_NODE_CONNECTOR_CONNECTOR_H_
#include "../../typedefs.h"
#include "../../protos.h"
#include "../../api.h"
namespace so_flow
{
namespace so_node
{
struct input_connector ;
so_typedef( input_connector ) ;
struct output_connector ;
so_typedef( output_connector ) ;
struct SNAKEOIL_FLOW_API input_connector
{
so_flow::key_t key ;
so_flow::inode_ptr_t nptr ;
};
struct SNAKEOIL_FLOW_API output_connector
{
so_flow::key_t key ;
so_flow::inode_ptr_t nptr ;
so_flow::inode_ptr_t connect( input_connector_cref_t ) ;
};
}
}
#endif
| [
"aconstlink@gmail.com"
] | aconstlink@gmail.com |
83d630b35ffac1b9d9864996e9bccf7a3a5fdee2 | c6ecad18dd41ea69c22baf78dfeb95cf9ba547d0 | /src/boost_1_42_0/libs/asio/test/is_write_buffered.cpp | b8dfd7b3911f3d3ded35c4bf894eeaca4ce4d90f | [
"BSL-1.0"
] | permissive | neuschaefer/qnap-gpl | b1418d504ebe17d7a31a504d315edac309430fcf | 7bb76f6cfe7abef08777451a75924f667cca335b | refs/heads/master | 2022-08-16T17:47:37.015870 | 2020-05-24T18:56:05 | 2020-05-24T18:56:05 | 266,605,194 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,354 | cpp | //
// is_write_buffered.cpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/is_write_buffered.hpp>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/asio/buffered_read_stream.hpp>
#include <boost/asio/buffered_write_stream.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include "unit_test.hpp"
using namespace std; // For memcmp, memcpy and memset.
class test_stream
: private boost::noncopyable
{
public:
typedef boost::asio::io_service io_service_type;
typedef test_stream lowest_layer_type;
test_stream(boost::asio::io_service& io_service)
: io_service_(io_service)
{
}
io_service_type& io_service()
{
return io_service_;
}
lowest_layer_type& lowest_layer()
{
return *this;
}
template <typename Const_Buffers>
size_t write(const Const_Buffers&)
{
return 0;
}
template <typename Const_Buffers>
size_t write(const Const_Buffers&, boost::system::error_code& ec)
{
ec = boost::system::error_code();
return 0;
}
template <typename Const_Buffers, typename Handler>
void async_write(const Const_Buffers&, Handler handler)
{
boost::system::error_code error;
io_service_.post(boost::asio::detail::bind_handler(handler, error, 0));
}
template <typename Mutable_Buffers>
size_t read(const Mutable_Buffers&)
{
return 0;
}
template <typename Mutable_Buffers>
size_t read(const Mutable_Buffers&, boost::system::error_code& ec)
{
ec = boost::system::error_code();
return 0;
}
template <typename Mutable_Buffers, typename Handler>
void async_read(const Mutable_Buffers&, Handler handler)
{
boost::system::error_code error;
io_service_.post(boost::asio::detail::bind_handler(handler, error, 0));
}
private:
io_service_type& io_service_;
};
void is_write_buffered_test()
{
BOOST_CHECK(!boost::asio::is_write_buffered<
boost::asio::ip::tcp::socket>::value);
BOOST_CHECK(!boost::asio::is_write_buffered<
boost::asio::buffered_read_stream<
boost::asio::ip::tcp::socket> >::value);
BOOST_CHECK(!!boost::asio::is_write_buffered<
boost::asio::buffered_write_stream<
boost::asio::ip::tcp::socket> >::value);
BOOST_CHECK(!!boost::asio::is_write_buffered<
boost::asio::buffered_stream<boost::asio::ip::tcp::socket> >::value);
BOOST_CHECK(!boost::asio::is_write_buffered<test_stream>::value);
BOOST_CHECK(!boost::asio::is_write_buffered<
boost::asio::buffered_read_stream<test_stream> >::value);
BOOST_CHECK(!!boost::asio::is_write_buffered<
boost::asio::buffered_write_stream<test_stream> >::value);
BOOST_CHECK(!!boost::asio::is_write_buffered<
boost::asio::buffered_stream<test_stream> >::value);
}
test_suite* init_unit_test_suite(int, char*[])
{
test_suite* test = BOOST_TEST_SUITE("is_write_buffered");
test->add(BOOST_TEST_CASE(&is_write_buffered_test));
return test;
}
| [
"j.neuschaefer@gmx.net"
] | j.neuschaefer@gmx.net |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.