blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author
stringlengths
0
119
f96db63378c31faa8ccaada106249350f2e76ec9
631847fafbcfa07bf33eee078d9b59b464ce4b50
/optimization/first_sdEta_mjj_optimization/sdEta_mistake_analyses/sdEta_mmjj_gridsearch/analysis_deltaeta4.6_mmjj_2000/Build/SampleAnalyzer/User/Analyzer/user.cpp
7490b92a99bfeb9b39040f52bb388b1ef76f0a41
[ "MIT" ]
permissive
sheride/axion_pheno
7b46aeb7cc562800d78edd9048504fdbc0f5fa42
7d3fc08f5ae5b17a3500eba19a2e43f87f076ce5
refs/heads/master
2021-07-01T08:47:59.981416
2021-02-03T23:03:50
2021-02-03T23:03:50
219,261,636
0
0
null
null
null
null
UTF-8
C++
false
false
14,628
cpp
#include "SampleAnalyzer/User/Analyzer/user.h" using namespace MA5; bool user::Initialize(const MA5::Configuration& cfg, const std::map<std::string,std::string>& parameters) { // Initializing PhysicsService for MC PHYSICS->mcConfig().Reset(); // definition of the multiparticle "hadronic" PHYSICS->mcConfig().AddHadronicId(-5); PHYSICS->mcConfig().AddHadronicId(-4); PHYSICS->mcConfig().AddHadronicId(-3); PHYSICS->mcConfig().AddHadronicId(-2); PHYSICS->mcConfig().AddHadronicId(-1); PHYSICS->mcConfig().AddHadronicId(1); PHYSICS->mcConfig().AddHadronicId(2); PHYSICS->mcConfig().AddHadronicId(3); PHYSICS->mcConfig().AddHadronicId(4); PHYSICS->mcConfig().AddHadronicId(5); PHYSICS->mcConfig().AddHadronicId(21); // definition of the multiparticle "invisible" PHYSICS->mcConfig().AddInvisibleId(-16); PHYSICS->mcConfig().AddInvisibleId(-14); PHYSICS->mcConfig().AddInvisibleId(-12); PHYSICS->mcConfig().AddInvisibleId(12); PHYSICS->mcConfig().AddInvisibleId(14); PHYSICS->mcConfig().AddInvisibleId(16); PHYSICS->mcConfig().AddInvisibleId(1000022); // ===== Signal region ===== // Manager()->AddRegionSelection("myregion"); // ===== Selections ===== // Manager()->AddCut("1_M ( jets[1] jets[2] ) > 120.0"); Manager()->AddCut("2_sdETA ( jets[1] jets[2] ) > 4.6 and M ( jets[1] jets[2] ) > 2000.0"); // ===== Histograms ===== // Manager()->AddHisto("1_PT", 200,0.0,1000.0); Manager()->AddHisto("2_ETA", 160,-8.0,8.0); Manager()->AddHisto("3_PHI", 64,-3.2,3.2); Manager()->AddHisto("4_PT", 100,0.0,500.0); Manager()->AddHisto("5_ETA", 160,-8.0,8.0); Manager()->AddHisto("6_PHI", 64,-3.2,3.2); Manager()->AddHisto("7_DELTAR", 75,0.0,15.0); Manager()->AddHisto("8_M", 160,0.0,8000.0); Manager()->AddHisto("9_MET", 100,0.0,1000.0); Manager()->AddHisto("10_sdETA", 100,-8.0,8.0); Manager()->AddHisto("11_M", 400,0.0,1000.0); Manager()->AddHisto("12_PT", 80,0.0,1000.0); Manager()->AddHisto("13_PT", 400,0.0,1000.0); Manager()->AddHisto("14_THT", 80,0.0,1000.0); Manager()->AddHisto("15_MET", 200,0.0,1000.0); Manager()->AddHisto("16_TET", 80,0.0,1000.0); // No problem during initialization return true; } bool user::Execute(SampleFormat& sample, const EventFormat& event) { MAfloat32 __event_weight__ = 1.0; if (weighted_events_ && event.mc()!=0) __event_weight__ = event.mc()->weight(); if (sample.mc()!=0) sample.mc()->addWeightedEvents(__event_weight__); Manager()->InitializeForNewEvent(__event_weight__); // Clearing particle containers { _P_a_I1I_PTorderingfinalstate_REG_.clear(); _P_a_I2I_PTorderingfinalstate_REG_.clear(); _P_jets_I1I_PTorderingfinalstate_REG_.clear(); _P_jets_I2I_PTorderingfinalstate_REG_.clear(); _P_aPTorderingfinalstate_REG_.clear(); _P_jetsPTorderingfinalstate_REG_.clear(); } // Filling particle containers { for (MAuint32 i=0;i<event.mc()->particles().size();i++) { if (isP__aPTorderingfinalstate((&(event.mc()->particles()[i])))) _P_aPTorderingfinalstate_REG_.push_back(&(event.mc()->particles()[i])); if (isP__jetsPTorderingfinalstate((&(event.mc()->particles()[i])))) _P_jetsPTorderingfinalstate_REG_.push_back(&(event.mc()->particles()[i])); } } // Sorting particles // Sorting particle collection according to PTordering // for getting 1th particle _P_a_I1I_PTorderingfinalstate_REG_=SORTER->rankFilter(_P_aPTorderingfinalstate_REG_,1,PTordering); // Sorting particle collection according to PTordering // for getting 2th particle _P_a_I2I_PTorderingfinalstate_REG_=SORTER->rankFilter(_P_aPTorderingfinalstate_REG_,2,PTordering); // Sorting particle collection according to PTordering // for getting 1th particle _P_jets_I1I_PTorderingfinalstate_REG_=SORTER->rankFilter(_P_jetsPTorderingfinalstate_REG_,1,PTordering); // Sorting particle collection according to PTordering // for getting 2th particle _P_jets_I2I_PTorderingfinalstate_REG_=SORTER->rankFilter(_P_jetsPTorderingfinalstate_REG_,2,PTordering); // Event selection number 1 // * Cut: select M ( jets[1] jets[2] ) > 120.0, regions = [] { std::vector<MAbool> filter(1,false); { { MAuint32 ind[2]; std::vector<std::set<const MCParticleFormat*> > combis; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { for (ind[1]=0;ind[1]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[1]++) { if (_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]==_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]) continue; // Checking if consistent combination std::set<const MCParticleFormat*> mycombi; for (MAuint32 i=0;i<2;i++) { mycombi.insert(_P_jets_I1I_PTorderingfinalstate_REG_[ind[i]]); mycombi.insert(_P_jets_I2I_PTorderingfinalstate_REG_[ind[i]]); } MAbool matched=false; for (MAuint32 i=0;i<combis.size();i++) if (combis[i]==mycombi) {matched=true; break;} if (matched) continue; else combis.push_back(mycombi); ParticleBaseFormat q; q+=_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->momentum(); q+=_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]->momentum(); if (q.m()>120.0) {filter[0]=true; break;} } } } } MAbool filter_global = (filter[0]); if(!Manager()->ApplyCut(filter_global, "1_M ( jets[1] jets[2] ) > 120.0")) return true; } // Histogram number 1 // * Plot: PT ( jets[1] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("1_PT", _P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->pt()); } } } // Histogram number 2 // * Plot: ETA ( jets[1] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("2_ETA", _P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->eta()); } } } // Histogram number 3 // * Plot: PHI ( jets[1] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("3_PHI", _P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->phi()); } } } // Histogram number 4 // * Plot: PT ( jets[2] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("4_PT", _P_jets_I2I_PTorderingfinalstate_REG_[ind[0]]->pt()); } } } // Histogram number 5 // * Plot: ETA ( jets[2] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("5_ETA", _P_jets_I2I_PTorderingfinalstate_REG_[ind[0]]->eta()); } } } // Histogram number 6 // * Plot: PHI ( jets[2] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("6_PHI", _P_jets_I2I_PTorderingfinalstate_REG_[ind[0]]->phi()); } } } // Histogram number 7 // * Plot: DELTAR ( jets[1] , jets[2] ) { { MAuint32 a[1]; for (a[0]=0;a[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();a[0]++) { MAuint32 b[1]; for (b[0]=0;b[0]<_P_jets_I2I_PTorderingfinalstate_REG_.size();b[0]++) { if ( _P_jets_I1I_PTorderingfinalstate_REG_[a[0]] == _P_jets_I2I_PTorderingfinalstate_REG_[b[0]] ) continue; Manager()->FillHisto("7_DELTAR", _P_jets_I1I_PTorderingfinalstate_REG_[a[0]]->dr(_P_jets_I2I_PTorderingfinalstate_REG_[b[0]])); } } } } // Histogram number 8 // * Plot: M ( jets[1] jets[2] ) { { MAuint32 ind[2]; std::vector<std::set<const MCParticleFormat*> > combis; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { for (ind[1]=0;ind[1]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[1]++) { if (_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]==_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]) continue; // Checking if consistent combination std::set<const MCParticleFormat*> mycombi; for (MAuint32 i=0;i<2;i++) { mycombi.insert(_P_jets_I1I_PTorderingfinalstate_REG_[ind[i]]); mycombi.insert(_P_jets_I2I_PTorderingfinalstate_REG_[ind[i]]); } MAbool matched=false; for (MAuint32 i=0;i<combis.size();i++) if (combis[i]==mycombi) {matched=true; break;} if (matched) continue; else combis.push_back(mycombi); ParticleBaseFormat q; q+=_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->momentum(); q+=_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]->momentum(); Manager()->FillHisto("8_M", q.m()); } } } } // Histogram number 9 // * Plot: MET { Manager()->FillHisto("9_MET", PHYSICS->Transverse->EventMET(event.mc())); } // Histogram number 10 // * Plot: sdETA ( jets[1] jets[2] ) { { MAuint32 ind[2]; std::vector<std::set<const MCParticleFormat*> > combis; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { for (ind[1]=0;ind[1]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[1]++) { if (_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]==_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]) continue; // Checking if consistent combination std::set<const MCParticleFormat*> mycombi; for (MAuint32 i=0;i<2;i++) { mycombi.insert(_P_jets_I1I_PTorderingfinalstate_REG_[ind[i]]); mycombi.insert(_P_jets_I2I_PTorderingfinalstate_REG_[ind[i]]); } MAbool matched=false; for (MAuint32 i=0;i<combis.size();i++) if (combis[i]==mycombi) {matched=true; break;} if (matched) continue; else combis.push_back(mycombi); MAdouble64 value=0; value+=_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->eta(); value-=_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]->eta(); Manager()->FillHisto("10_sdETA", value); } } } } // Histogram number 11 // * Plot: M ( a[1] a[2] ) { { MAuint32 ind[2]; std::vector<std::set<const MCParticleFormat*> > combis; for (ind[0]=0;ind[0]<_P_a_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { for (ind[1]=0;ind[1]<_P_a_I2I_PTorderingfinalstate_REG_.size();ind[1]++) { if (_P_a_I2I_PTorderingfinalstate_REG_[ind[1]]==_P_a_I1I_PTorderingfinalstate_REG_[ind[0]]) continue; // Checking if consistent combination std::set<const MCParticleFormat*> mycombi; for (MAuint32 i=0;i<2;i++) { mycombi.insert(_P_a_I1I_PTorderingfinalstate_REG_[ind[i]]); mycombi.insert(_P_a_I2I_PTorderingfinalstate_REG_[ind[i]]); } MAbool matched=false; for (MAuint32 i=0;i<combis.size();i++) if (combis[i]==mycombi) {matched=true; break;} if (matched) continue; else combis.push_back(mycombi); ParticleBaseFormat q; q+=_P_a_I1I_PTorderingfinalstate_REG_[ind[0]]->momentum(); q+=_P_a_I2I_PTorderingfinalstate_REG_[ind[1]]->momentum(); Manager()->FillHisto("11_M", q.m()); } } } } // Histogram number 12 // * Plot: PT ( a[1] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_a_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("12_PT", _P_a_I1I_PTorderingfinalstate_REG_[ind[0]]->pt()); } } } // Histogram number 13 // * Plot: PT ( a[2] ) { { MAuint32 ind[1]; for (ind[0]=0;ind[0]<_P_a_I2I_PTorderingfinalstate_REG_.size();ind[0]++) { Manager()->FillHisto("13_PT", _P_a_I2I_PTorderingfinalstate_REG_[ind[0]]->pt()); } } } // Histogram number 14 // * Plot: THT { Manager()->FillHisto("14_THT", PHYSICS->Transverse->EventTHT(event.mc())); } // Histogram number 15 // * Plot: MET { Manager()->FillHisto("15_MET", PHYSICS->Transverse->EventMET(event.mc())); } // Histogram number 16 // * Plot: TET { Manager()->FillHisto("16_TET", PHYSICS->Transverse->EventTET(event.mc())); } // Event selection number 2 // * Cut: select sdETA ( jets[1] jets[2] ) > 4.6 and M ( jets[1] jets[2] ) > 2000.0, regions = [] { std::vector<MAbool> filter(2,false); { { MAuint32 ind[2]; std::vector<std::set<const MCParticleFormat*> > combis; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { for (ind[1]=0;ind[1]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[1]++) { if (_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]==_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]) continue; // Checking if consistent combination std::set<const MCParticleFormat*> mycombi; for (MAuint32 i=0;i<2;i++) { mycombi.insert(_P_jets_I1I_PTorderingfinalstate_REG_[ind[i]]); mycombi.insert(_P_jets_I2I_PTorderingfinalstate_REG_[ind[i]]); } MAbool matched=false; for (MAuint32 i=0;i<combis.size();i++) if (combis[i]==mycombi) {matched=true; break;} if (matched) continue; else combis.push_back(mycombi); if ((_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->eta()-_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]->eta())>4.6) {filter[0]=true; break;} } } } } { { MAuint32 ind[2]; std::vector<std::set<const MCParticleFormat*> > combis; for (ind[0]=0;ind[0]<_P_jets_I1I_PTorderingfinalstate_REG_.size();ind[0]++) { for (ind[1]=0;ind[1]<_P_jets_I2I_PTorderingfinalstate_REG_.size();ind[1]++) { if (_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]==_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]) continue; // Checking if consistent combination std::set<const MCParticleFormat*> mycombi; for (MAuint32 i=0;i<2;i++) { mycombi.insert(_P_jets_I1I_PTorderingfinalstate_REG_[ind[i]]); mycombi.insert(_P_jets_I2I_PTorderingfinalstate_REG_[ind[i]]); } MAbool matched=false; for (MAuint32 i=0;i<combis.size();i++) if (combis[i]==mycombi) {matched=true; break;} if (matched) continue; else combis.push_back(mycombi); ParticleBaseFormat q; q+=_P_jets_I1I_PTorderingfinalstate_REG_[ind[0]]->momentum(); q+=_P_jets_I2I_PTorderingfinalstate_REG_[ind[1]]->momentum(); if (q.m()>2000.0) {filter[1]=true; break;} } } } } MAbool filter_global = (filter[0] && filter[1]); if(!Manager()->ApplyCut(filter_global, "2_sdETA ( jets[1] jets[2] ) > 4.6 and M ( jets[1] jets[2] ) > 2000.0")) return true; } return true; } void user::Finalize(const SampleFormat& summary, const std::vector<SampleFormat>& files) { }
df835822936c9d436c4507bd81ffc766aea588f6
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/base/cluster/mgmt/cluscfg/basecluster/cclusdiskjoin.cpp
b67ea7ca19fb35aaf00205441d4481af9f631f58
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,579
cpp
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 1999-2000 Microsoft Corporation // // Module Name: // CClusDiskJoin.cpp // // Description: // Contains the definition of the CClusDiskJoin class. // // Maintained By: // Vij Vasu (Vvasu) 08-MAR-2000 // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Include Files ////////////////////////////////////////////////////////////////////////////// // The precompiled header. #include "pch.h" // The header for this file #include "CClusDiskJoin.h" // For the CBaseClusterJoin class. #include "CBaseClusterJoin.h" // For the CImpersonateUser class. #include "CImpersonateUser.h" // For the ResUtil functions #include "ResAPI.h" ////////////////////////////////////////////////////////////////////////////// // Macro definitions ////////////////////////////////////////////////////////////////////////////// // Name of the private property of a physical disk resouce that has its signature. #define PHYSICAL_DISK_SIGNATURE_PRIVPROP_NAME L"Signature" ////////////////////////////////////////////////////////////////////////////// //++ // // CClusDiskJoin::CClusDiskJoin() // // Description: // Constructor of the CClusDiskJoin class // // Arguments: // pbcjParentActionIn // Pointer to the base cluster action of which this action is a part. // // Return Value: // None. // // Exceptions Thrown: // Any exceptions thrown by underlying functions // //-- ////////////////////////////////////////////////////////////////////////////// CClusDiskJoin::CClusDiskJoin( CBaseClusterJoin * pbcjParentActionIn ) : BaseClass( pbcjParentActionIn ) , m_nSignatureArraySize( 0 ) , m_nSignatureCount( 0 ) { BCATraceScope( "" ); SetRollbackPossible( true ); } //*** CClusDiskJoin::CClusDiskJoin() ////////////////////////////////////////////////////////////////////////////// //++ // // CClusDiskJoin::~CClusDiskJoin() // // Description: // Destructor of the CClusDiskJoin class. // // Arguments: // None. // // Return Value: // None. // // Exceptions Thrown: // Any exceptions thrown by underlying functions // //-- ////////////////////////////////////////////////////////////////////////////// CClusDiskJoin::~CClusDiskJoin( void ) { BCATraceScope( "" ); } //*** CClusDiskJoin::~CClusDiskJoin() ////////////////////////////////////////////////////////////////////////////// //++ // // void // CClusDiskJoin::Commit() // // Description: // Configure and start the service. // // Arguments: // None. // // Return Value: // None. // // Exceptions Thrown: // Any that are thrown by the contained actions. // //-- ////////////////////////////////////////////////////////////////////////////// void CClusDiskJoin::Commit( void ) { BCATraceScope( "" ); // Call the base class commit method. BaseClass::Commit(); try { // Create and start the service. ConfigureService(); // Try and attach to all the disks that the sponsor knows about. AttachToClusteredDisks(); } // try: catch( ... ) { // If we are here, then something went wrong with the create. BCATraceMsg( "Caught exception during commit." ); // // Cleanup anything that the failed create might have done. // Catch any exceptions thrown during Cleanup to make sure that there // is no collided unwind. // try { CleanupService(); } catch( ... ) { // // The rollback of the committed action has failed. // There is nothing that we can do. // We certainly cannot rethrow this exception, since // the exception that caused the rollback is more important. // THR( E_UNEXPECTED ); BCATraceMsg( "Caught exception during cleanup." ); LogMsg( "THIS COMPUTER MAY BE IN AN INVALID STATE. An error has occurred during cleanup." ); } // catch: all // Rethrow the exception thrown by commit. throw; } // catch: all // If we are here, then everything went well. SetCommitCompleted( true ); } //*** CClusDiskJoin::Commit() ////////////////////////////////////////////////////////////////////////////// //++ // // void // CClusDiskJoin::Rollback() // // Description: // Cleanup the service. // // Arguments: // None. // // Return Value: // None. // // Exceptions Thrown: // Any that are thrown by the underlying functions. // //-- ////////////////////////////////////////////////////////////////////////////// void CClusDiskJoin::Rollback( void ) { BCATraceScope( "" ); // Call the base class rollback method. BaseClass::Rollback(); // Cleanup the service. CleanupService(); SetCommitCompleted( false ); } //*** CClusDiskJoin::Rollback() ////////////////////////////////////////////////////////////////////////////// //++ // // void // CClusDiskJoin::AttachToClusteredDisks() // // Description: // Get the signatures of all disks that have been clustered from the sponsor. // Attach to all these disks. // // Arguments: // None. // // Return Value: // None. // // Exceptions Thrown: // CRuntimeError // If any of the APIs fail. // // Any that are thrown by the underlying functions. // //-- ////////////////////////////////////////////////////////////////////////////// void CClusDiskJoin::AttachToClusteredDisks( void ) { BCATraceScope( "" ); DWORD dwError = ERROR_SUCCESS; // Get the parent action pointer. CBaseClusterJoin * pcjClusterJoin = dynamic_cast< CBaseClusterJoin *>( PbcaGetParent() ); // If the parent action of this action is not CBaseClusterJoin if ( pcjClusterJoin == NULL ) { THROW_ASSERT( E_POINTER, "The parent action of this action is not CBaseClusterJoin." ); } // an invalid pointer was passed in. // // Connect to the sponsor cluster and get the signatures of all clustered disks. // do { // Smart handle to sponsor cluster SmartClusterHandle schSponsorCluster; BCATraceMsg( "Attempting to impersonate the cluster service account." ); // Impersonate the cluster service account, so that we can contact the sponsor cluster. // The impersonation is automatically ended when this object is destroyed. CImpersonateUser ciuImpersonateClusterServiceAccount( pcjClusterJoin->HGetClusterServiceAccountToken() ); { BCATraceMsg( "Trying to open a handle to the sponsor cluster." ); // Open a handle to the sponsor cluster. HCLUSTER hSponsorCluster = OpenCluster( pcjClusterJoin->RStrGetClusterBindingString().PszData() ); // Assign it to a smart handle for safe release. schSponsorCluster.Assign( hSponsorCluster ); } // Did we succeed in opening a handle to the sponsor cluster? if ( schSponsorCluster.FIsInvalid() ) { dwError = TW32( GetLastError() ); BCATraceMsg( "An error occurred trying to open a handle to the sponsor cluster." ); LogMsg( "An error occurred trying to open a handle to the sponsor cluster." ); break; } // if: OpenCluster() failed BCATraceMsg1( "Enumerating all '%s' resources in the cluster.", CLUS_RESTYPE_NAME_PHYS_DISK ); // Enumerate all the physical disk resouces in the cluster and get their signatures. dwError = TW32( ResUtilEnumResourcesEx( schSponsorCluster.HHandle() , NULL , CLUS_RESTYPE_NAME_PHYS_DISK , S_DwResourceEnumCallback , this ) ); if ( dwError != ERROR_SUCCESS ) { // Free the signature array. m_rgdwSignatureArray.PRelease(); m_nSignatureArraySize = 0; m_nSignatureCount = 0; BCATraceMsg( "An error occurred trying enumerate resources in the sponsor cluster." ); LogMsg( "An error occurred trying enumerate resources in the sponsor cluster." ); break; } // if: ResUtilEnumResourcesEx() failed } while( false ); // dummy do-while loop to avoid gotos. if ( dwError != ERROR_SUCCESS ) { LogMsg( "Error %#08x occurred trying to attach to the disks in the sponsor cluster.", dwError ); BCATraceMsg1( "Error %#08x occurred trying to attach to the disks in the sponsor cluster. Throwing exception.", dwError ); THROW_RUNTIME_ERROR( HRESULT_FROM_WIN32( dwError ), IDS_ERROR_CLUSDISK_CONFIGURE ); } // if: something has gone wrong else { BCATraceMsg1( "Attaching to the %d disks in the sponsor cluster.", m_nSignatureCount ); AttachToDisks( m_rgdwSignatureArray.PMem() , m_nSignatureCount ); } // else: everything has gone well so far } //*** CClusDiskJoin::AttachToClusteredDisks() ////////////////////////////////////////////////////////////////////////////// //++ // // DWORD // CClusDiskJoin::DwAddSignature() // // Description: // Add a signature to the array of signatures of disks that ClusDisk should // attach to. If the array is already full, grow the array. // // Arguments: // dwSignatureIn // Signature to be added to the array. // // Return Value: // ERROR_SUCCESS // If everything was ok. // // Other Win32 error codes on failure. // // Exceptions Thrown: // None. This function is called from a callback routine and therefore // cannot throw any exceptions. // //-- ////////////////////////////////////////////////////////////////////////////// DWORD CClusDiskJoin::DwAddSignature( DWORD dwSignatureIn ) throw() { BCATraceScope( "" ); DWORD dwError = ERROR_SUCCESS; do { // Is the capacity of the array reached? if ( m_nSignatureCount == m_nSignatureArraySize ) { // Increase the array size by a random amount. const int nGrowSize = 256; BCATraceMsg2( "Signature count has reached array size ( %d ). Growing array by %d.", m_nSignatureArraySize, nGrowSize ); m_nSignatureArraySize += nGrowSize; // Grow the array. DWORD * pdwNewArray = new DWORD[ m_nSignatureArraySize ]; if ( pdwNewArray == NULL ) { BCATraceMsg1( "Memory allocation failed trying to allocate %d DWORDs.", m_nSignatureArraySize ); dwError = TW32( ERROR_OUTOFMEMORY ); break; } // if: memory allocation failed // Copy the old array into the new one. CopyMemory( pdwNewArray, m_rgdwSignatureArray.PMem(), m_nSignatureCount * sizeof( SmartDwordArray::DataType ) ); // Free the old array and store the new one. m_rgdwSignatureArray.Assign( pdwNewArray ); } // if: the array capacity has been reached // Store the new signature in next array location ( m_rgdwSignatureArray.PMem() )[ m_nSignatureCount ] = dwSignatureIn; ++m_nSignatureCount; BCATraceMsg2( "Signature %#08X added to array. There are now %d signature in the array.", dwSignatureIn, m_nSignatureCount ); } while( false ); // dummy do-while loop to avoid gotos. BCATraceMsg1( "Return value is %d.", dwError ); return dwError; } //*** CClusDiskJoin::DwAddSignature() ////////////////////////////////////////////////////////////////////////////// //++ // // static DWORD // CClusDiskJoin::S_DwResourceEnumCallback() // // Description: // This function is called back for every physical disk resouce by // ResUtilEnumResourcesEx() as a part of enumerating resources. // This function gets the signature of the current physical disk // resource and stores it in the object that initiated the enumeration // ( the pointer to the object is in parameter 4 ). // // Arguments: // HCLUSTER hClusterIn // Handle to the cluster whose resources are being enumerated. // // HRESOURCE hSelfIn // hSelfIn passed to ResUtilEnumResourcesEx(), if any. // // HRESOURCE hCurrentResourceIn // Handle to the current resource. // // PVOID pvParamIn // Pointer to the object of this class that initiated this enumeration. // // Return Value: // ERROR_SUCCESS // If everything was ok. // // Other Win32 error codes on failure. // Returning an error code will terminate the enumeration. // // Exceptions Thrown: // None. This function is called from a callback routine and therefore // cannot throw any exceptions. // //-- ////////////////////////////////////////////////////////////////////////////// DWORD CClusDiskJoin::S_DwResourceEnumCallback( HCLUSTER hClusterIn , HRESOURCE hSelfIn , HRESOURCE hCurrentResourceIn , PVOID pvParamIn ) { BCATraceScope( "" ); DWORD dwError = ERROR_SUCCESS; CClusDiskJoin * pcdjThisObject = reinterpret_cast< CClusDiskJoin * >( pvParamIn ); // Get the 'Signature' private property of this physical disk. do { SmartByteArray sbaPropertyBuffer; DWORD dwBytesReturned = 0; DWORD dwBufferSize; DWORD dwSignature = 0; BCATraceMsg1( "Trying to get the signature of the disk resource whose handle is %p.", hCurrentResourceIn ); // Get the size of the buffer required to hold all the private properties of this resource. dwError = ClusterResourceControl( hCurrentResourceIn , NULL , CLUSCTL_RESOURCE_GET_PRIVATE_PROPERTIES , NULL , 0 , NULL , 0 , &dwBytesReturned ); if ( ( dwError != ERROR_MORE_DATA ) && ( dwError != ERROR_SUCCESS ) ) { // Something went wrong. TW32( dwError ); BCATraceMsg( "ClusterResourceControl() failed while trying to get the size of the property buffer." ); break; } // if: the return value of ClusterResourceControl() was not ERROR_MORE_DATA dwBufferSize = dwBytesReturned; // Allocate the memory required for the property buffer. sbaPropertyBuffer.Assign( new BYTE[ dwBufferSize ] ); if ( sbaPropertyBuffer.FIsEmpty() ) { BCATraceMsg1( "Memory allocation failed trying to allocate %d bytes.", dwBufferSize ); dwError = TW32( ERROR_OUTOFMEMORY ); break; } // if: memory allocation failed // Get the all the private properties of this resource. dwError = TW32( ClusterResourceControl( hCurrentResourceIn , NULL , CLUSCTL_RESOURCE_GET_PRIVATE_PROPERTIES , NULL , 0 , sbaPropertyBuffer.PMem() , dwBufferSize , &dwBytesReturned ) ); if ( dwError != ERROR_SUCCESS ) { BCATraceMsg( "ClusterResourceControl() failed while trying to get the properties of the current resource." ); break; } // if: an error occurring trying to get the private properties. // Get the signature of this disk resource. dwError = TW32( ResUtilFindDwordProperty( sbaPropertyBuffer.PMem() , dwBufferSize , PHYSICAL_DISK_SIGNATURE_PRIVPROP_NAME , &dwSignature ) ); if ( dwError != ERROR_SUCCESS ) { BCATraceMsg( "An error has occurred trying to get the signature from the property buffer." ); break; } // if: we could not get the signature dwError = TW32( pcdjThisObject->DwAddSignature( dwSignature ) ); if ( dwError != ERROR_SUCCESS ) { BCATraceMsg( "An error has occurred trying to add the signature to the signature array." ); break; } // if: we could not store the signature } while( false ); // dummy do-while loop to avoid gotos. BCATraceMsg1( "Return value is %d.", dwError ); return dwError; } //*** CClusDiskJoin::S_DwResourceEnumCallback()
eb90868a613de1010b07f5f6ea6265d608ab1a03
0654228578d742c8aadc52f1755268c2ef4cabe0
/IPSSIM_December/dataSet_2A.h
48900e323c4d8eb3939c27886012c07c73c959fe
[]
no_license
ir0nheart/IPSSIM_December
4c7c4060a6f1de213921838de31e952b701227ec
81f1e6b8b6c19f4755d21e45df6b1a5391837532
refs/heads/master
2020-04-13T18:35:32.857545
2019-01-07T20:06:14
2019-01-07T20:06:14
163,379,083
0
0
null
null
null
null
UTF-8
C++
false
false
857
h
#pragma once #include "DataSet.h" class dataSet_2A:DataSet { /* Simulation Type (One Line Input) * Four Words. The first word must be "SUTRA" - We actually gonna ignore this * The second and third words indicate the version. - We will implement only "Version 2.2" * The Fourth indicates the type of transport, and must be either "ENERGY" or "SOLUTE" * Additional words like "TRANSPORT" will be ignored */ public: dataSet_2A(std::string data_); ~dataSet_2A(); std::string sim_name() const { return simName; } std::string version_str() const { return versionStr; } std::string sim_type_str() const { return simTypeStr; } std::string transport_str() const { return transportStr; } void parse_data() override; private: std::string simName; std::string versionStr; std::string simTypeStr; std::string transportStr; };
b83bc00d545b2b975eee4daa3f3ae35ab21fefd5
06cd635b4405c890cdf2d71f2138f632737ca4f9
/tp2/src/globals.cpp
edc6f281e49aa0ca6253d3be25ee896ac69635f9
[]
no_license
MatiasJAco/sg6671-tp1-g2
7a84311b9d2ab6f7678cfeeacdc97ea71e55c701
59ed875a6d1e36c7e33e6a00fdbb7c9a6be26cbb
refs/heads/master
2020-04-01T23:12:06.859230
2011-06-17T11:10:44
2011-06-17T11:10:44
32,540,156
0
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
#include "globals.h" //Spline vector<float> ctlVectorSpline; //Interfaz deque<GLuint> solidsList; GLuint dl_curvaSpline; GLuint dl_curvaBezier; //Texturas GLuint texName; GLubyte checkImage[checkImageHeight][checkImageWidth][4]; //Animacion int rotation = 0; bool animation = true; int target = 0;
[ "[email protected]@8c9cdbba-f223-9568-bec3-c68b3cb6d8cf" ]
[email protected]@8c9cdbba-f223-9568-bec3-c68b3cb6d8cf
4c6760d9971b93e736cc25ff03ad6228352aa4af
2b60adb7ae670123c727111c3198c531e441f6fd
/doc/proto/message/mail.pb.h
dba9f9a8638899df61f1577efac6cecb15741ec0
[]
no_license
kingstop/830
586b1c20bc5bb26b84afbbd0eb970fcbc22b2d02
a5fabeb71111241947634383843a3280a8d0bd53
refs/heads/master
2021-01-01T16:56:34.635261
2015-06-30T15:46:25
2015-06-30T15:46:25
38,308,920
1
1
null
null
null
null
UTF-8
C++
false
true
41,138
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: mail.proto #ifndef PROTOBUF_mail_2eproto__INCLUDED #define PROTOBUF_mail_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/generated_enum_reflection.h> #include <google/protobuf/unknown_field_set.h> #include "common.pb.h" // @@protoc_insertion_point(includes) namespace clientmsg { // Internal implementation detail -- do not call these. void protobuf_AddDesc_mail_2eproto(); void protobuf_AssignDesc_mail_2eproto(); void protobuf_ShutdownFile_mail_2eproto(); class UserOneMailContent; class UserOpenMail; class SendMailContent; class DelMail; class ReadMail; class UserSendMailByid; class UserSendMailByName; enum enumMailType { enumMailType_Sys = 1, enumMailType_RequestAddFriend = 2 }; bool enumMailType_IsValid(int value); const enumMailType enumMailType_MIN = enumMailType_Sys; const enumMailType enumMailType_MAX = enumMailType_RequestAddFriend; const int enumMailType_ARRAYSIZE = enumMailType_MAX + 1; const ::google::protobuf::EnumDescriptor* enumMailType_descriptor(); inline const ::std::string& enumMailType_Name(enumMailType value) { return ::google::protobuf::internal::NameOfEnum( enumMailType_descriptor(), value); } inline bool enumMailType_Parse( const ::std::string& name, enumMailType* value) { return ::google::protobuf::internal::ParseNamedEnum<enumMailType>( enumMailType_descriptor(), name, value); } // =================================================================== class UserOneMailContent : public ::google::protobuf::Message { public: UserOneMailContent(); virtual ~UserOneMailContent(); UserOneMailContent(const UserOneMailContent& from); inline UserOneMailContent& operator=(const UserOneMailContent& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const UserOneMailContent& default_instance(); void Swap(UserOneMailContent* other); // implements Message ---------------------------------------------- UserOneMailContent* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const UserOneMailContent& from); void MergeFrom(const UserOneMailContent& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional uint32 mailid = 1; inline bool has_mailid() const; inline void clear_mailid(); static const int kMailidFieldNumber = 1; inline ::google::protobuf::uint32 mailid() const; inline void set_mailid(::google::protobuf::uint32 value); // optional string content = 2; inline bool has_content() const; inline void clear_content(); static const int kContentFieldNumber = 2; inline const ::std::string& content() const; inline void set_content(const ::std::string& value); inline void set_content(const char* value); inline void set_content(const char* value, size_t size); inline ::std::string* mutable_content(); inline ::std::string* release_content(); inline void set_allocated_content(::std::string* content); // optional .clientmsg.enumMailType type = 3; inline bool has_type() const; inline void clear_type(); static const int kTypeFieldNumber = 3; inline ::clientmsg::enumMailType type() const; inline void set_type(::clientmsg::enumMailType value); // optional uint32 isdelete = 4; inline bool has_isdelete() const; inline void clear_isdelete(); static const int kIsdeleteFieldNumber = 4; inline ::google::protobuf::uint32 isdelete() const; inline void set_isdelete(::google::protobuf::uint32 value); // optional uint32 isread = 5; inline bool has_isread() const; inline void clear_isread(); static const int kIsreadFieldNumber = 5; inline ::google::protobuf::uint32 isread() const; inline void set_isread(::google::protobuf::uint32 value); // @@protoc_insertion_point(class_scope:clientmsg.UserOneMailContent) private: inline void set_has_mailid(); inline void clear_has_mailid(); inline void set_has_content(); inline void clear_has_content(); inline void set_has_type(); inline void clear_has_type(); inline void set_has_isdelete(); inline void clear_has_isdelete(); inline void set_has_isread(); inline void clear_has_isread(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::std::string* content_; ::google::protobuf::uint32 mailid_; int type_; ::google::protobuf::uint32 isdelete_; ::google::protobuf::uint32 isread_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(5 + 31) / 32]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static UserOneMailContent* default_instance_; }; // ------------------------------------------------------------------- class UserOpenMail : public ::google::protobuf::Message { public: UserOpenMail(); virtual ~UserOpenMail(); UserOpenMail(const UserOpenMail& from); inline UserOpenMail& operator=(const UserOpenMail& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const UserOpenMail& default_instance(); void Swap(UserOpenMail* other); // implements Message ---------------------------------------------- UserOpenMail* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const UserOpenMail& from); void MergeFrom(const UserOpenMail& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // @@protoc_insertion_point(class_scope:clientmsg.UserOpenMail) private: ::google::protobuf::UnknownFieldSet _unknown_fields_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[1]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static UserOpenMail* default_instance_; }; // ------------------------------------------------------------------- class SendMailContent : public ::google::protobuf::Message { public: SendMailContent(); virtual ~SendMailContent(); SendMailContent(const SendMailContent& from); inline SendMailContent& operator=(const SendMailContent& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const SendMailContent& default_instance(); void Swap(SendMailContent* other); // implements Message ---------------------------------------------- SendMailContent* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const SendMailContent& from); void MergeFrom(const SendMailContent& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .clientmsg.UserOneMailContent mail_contents = 1; inline int mail_contents_size() const; inline void clear_mail_contents(); static const int kMailContentsFieldNumber = 1; inline const ::clientmsg::UserOneMailContent& mail_contents(int index) const; inline ::clientmsg::UserOneMailContent* mutable_mail_contents(int index); inline ::clientmsg::UserOneMailContent* add_mail_contents(); inline const ::google::protobuf::RepeatedPtrField< ::clientmsg::UserOneMailContent >& mail_contents() const; inline ::google::protobuf::RepeatedPtrField< ::clientmsg::UserOneMailContent >* mutable_mail_contents(); // @@protoc_insertion_point(class_scope:clientmsg.SendMailContent) private: ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::RepeatedPtrField< ::clientmsg::UserOneMailContent > mail_contents_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static SendMailContent* default_instance_; }; // ------------------------------------------------------------------- class DelMail : public ::google::protobuf::Message { public: DelMail(); virtual ~DelMail(); DelMail(const DelMail& from); inline DelMail& operator=(const DelMail& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const DelMail& default_instance(); void Swap(DelMail* other); // implements Message ---------------------------------------------- DelMail* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const DelMail& from); void MergeFrom(const DelMail& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated uint32 mail_ids = 2; inline int mail_ids_size() const; inline void clear_mail_ids(); static const int kMailIdsFieldNumber = 2; inline ::google::protobuf::uint32 mail_ids(int index) const; inline void set_mail_ids(int index, ::google::protobuf::uint32 value); inline void add_mail_ids(::google::protobuf::uint32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >& mail_ids() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >* mutable_mail_ids(); // @@protoc_insertion_point(class_scope:clientmsg.DelMail) private: ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::RepeatedField< ::google::protobuf::uint32 > mail_ids_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static DelMail* default_instance_; }; // ------------------------------------------------------------------- class ReadMail : public ::google::protobuf::Message { public: ReadMail(); virtual ~ReadMail(); ReadMail(const ReadMail& from); inline ReadMail& operator=(const ReadMail& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const ReadMail& default_instance(); void Swap(ReadMail* other); // implements Message ---------------------------------------------- ReadMail* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const ReadMail& from); void MergeFrom(const ReadMail& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated uint32 mail_ids = 1; inline int mail_ids_size() const; inline void clear_mail_ids(); static const int kMailIdsFieldNumber = 1; inline ::google::protobuf::uint32 mail_ids(int index) const; inline void set_mail_ids(int index, ::google::protobuf::uint32 value); inline void add_mail_ids(::google::protobuf::uint32 value); inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >& mail_ids() const; inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >* mutable_mail_ids(); // @@protoc_insertion_point(class_scope:clientmsg.ReadMail) private: ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::RepeatedField< ::google::protobuf::uint32 > mail_ids_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static ReadMail* default_instance_; }; // ------------------------------------------------------------------- class UserSendMailByid : public ::google::protobuf::Message { public: UserSendMailByid(); virtual ~UserSendMailByid(); UserSendMailByid(const UserSendMailByid& from); inline UserSendMailByid& operator=(const UserSendMailByid& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const UserSendMailByid& default_instance(); void Swap(UserSendMailByid* other); // implements Message ---------------------------------------------- UserSendMailByid* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const UserSendMailByid& from); void MergeFrom(const UserSendMailByid& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional uint64 remoteid = 1; inline bool has_remoteid() const; inline void clear_remoteid(); static const int kRemoteidFieldNumber = 1; inline ::google::protobuf::uint64 remoteid() const; inline void set_remoteid(::google::protobuf::uint64 value); // optional string content = 2; inline bool has_content() const; inline void clear_content(); static const int kContentFieldNumber = 2; inline const ::std::string& content() const; inline void set_content(const ::std::string& value); inline void set_content(const char* value); inline void set_content(const char* value, size_t size); inline ::std::string* mutable_content(); inline ::std::string* release_content(); inline void set_allocated_content(::std::string* content); // optional .clientmsg.enumMailType type = 3; inline bool has_type() const; inline void clear_type(); static const int kTypeFieldNumber = 3; inline ::clientmsg::enumMailType type() const; inline void set_type(::clientmsg::enumMailType value); // @@protoc_insertion_point(class_scope:clientmsg.UserSendMailByid) private: inline void set_has_remoteid(); inline void clear_has_remoteid(); inline void set_has_content(); inline void clear_has_content(); inline void set_has_type(); inline void clear_has_type(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint64 remoteid_; ::std::string* content_; int type_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static UserSendMailByid* default_instance_; }; // ------------------------------------------------------------------- class UserSendMailByName : public ::google::protobuf::Message { public: UserSendMailByName(); virtual ~UserSendMailByName(); UserSendMailByName(const UserSendMailByName& from); inline UserSendMailByName& operator=(const UserSendMailByName& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const UserSendMailByName& default_instance(); void Swap(UserSendMailByName* other); // implements Message ---------------------------------------------- UserSendMailByName* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const UserSendMailByName& from); void MergeFrom(const UserSendMailByName& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string remotename = 1; inline bool has_remotename() const; inline void clear_remotename(); static const int kRemotenameFieldNumber = 1; inline const ::std::string& remotename() const; inline void set_remotename(const ::std::string& value); inline void set_remotename(const char* value); inline void set_remotename(const char* value, size_t size); inline ::std::string* mutable_remotename(); inline ::std::string* release_remotename(); inline void set_allocated_remotename(::std::string* remotename); // optional string content = 2; inline bool has_content() const; inline void clear_content(); static const int kContentFieldNumber = 2; inline const ::std::string& content() const; inline void set_content(const ::std::string& value); inline void set_content(const char* value); inline void set_content(const char* value, size_t size); inline ::std::string* mutable_content(); inline ::std::string* release_content(); inline void set_allocated_content(::std::string* content); // optional .clientmsg.enumMailType type = 3; inline bool has_type() const; inline void clear_type(); static const int kTypeFieldNumber = 3; inline ::clientmsg::enumMailType type() const; inline void set_type(::clientmsg::enumMailType value); // @@protoc_insertion_point(class_scope:clientmsg.UserSendMailByName) private: inline void set_has_remotename(); inline void clear_has_remotename(); inline void set_has_content(); inline void clear_has_content(); inline void set_has_type(); inline void clear_has_type(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::std::string* remotename_; ::std::string* content_; int type_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; friend void protobuf_AddDesc_mail_2eproto(); friend void protobuf_AssignDesc_mail_2eproto(); friend void protobuf_ShutdownFile_mail_2eproto(); void InitAsDefaultInstance(); static UserSendMailByName* default_instance_; }; // =================================================================== // =================================================================== // UserOneMailContent // optional uint32 mailid = 1; inline bool UserOneMailContent::has_mailid() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void UserOneMailContent::set_has_mailid() { _has_bits_[0] |= 0x00000001u; } inline void UserOneMailContent::clear_has_mailid() { _has_bits_[0] &= ~0x00000001u; } inline void UserOneMailContent::clear_mailid() { mailid_ = 0u; clear_has_mailid(); } inline ::google::protobuf::uint32 UserOneMailContent::mailid() const { return mailid_; } inline void UserOneMailContent::set_mailid(::google::protobuf::uint32 value) { set_has_mailid(); mailid_ = value; } // optional string content = 2; inline bool UserOneMailContent::has_content() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void UserOneMailContent::set_has_content() { _has_bits_[0] |= 0x00000002u; } inline void UserOneMailContent::clear_has_content() { _has_bits_[0] &= ~0x00000002u; } inline void UserOneMailContent::clear_content() { if (content_ != &::google::protobuf::internal::kEmptyString) { content_->clear(); } clear_has_content(); } inline const ::std::string& UserOneMailContent::content() const { return *content_; } inline void UserOneMailContent::set_content(const ::std::string& value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void UserOneMailContent::set_content(const char* value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void UserOneMailContent::set_content(const char* value, size_t size) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* UserOneMailContent::mutable_content() { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } return content_; } inline ::std::string* UserOneMailContent::release_content() { clear_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { return NULL; } else { ::std::string* temp = content_; content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); return temp; } } inline void UserOneMailContent::set_allocated_content(::std::string* content) { if (content_ != &::google::protobuf::internal::kEmptyString) { delete content_; } if (content) { set_has_content(); content_ = content; } else { clear_has_content(); content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); } } // optional .clientmsg.enumMailType type = 3; inline bool UserOneMailContent::has_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void UserOneMailContent::set_has_type() { _has_bits_[0] |= 0x00000004u; } inline void UserOneMailContent::clear_has_type() { _has_bits_[0] &= ~0x00000004u; } inline void UserOneMailContent::clear_type() { type_ = 1; clear_has_type(); } inline ::clientmsg::enumMailType UserOneMailContent::type() const { return static_cast< ::clientmsg::enumMailType >(type_); } inline void UserOneMailContent::set_type(::clientmsg::enumMailType value) { assert(::clientmsg::enumMailType_IsValid(value)); set_has_type(); type_ = value; } // optional uint32 isdelete = 4; inline bool UserOneMailContent::has_isdelete() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void UserOneMailContent::set_has_isdelete() { _has_bits_[0] |= 0x00000008u; } inline void UserOneMailContent::clear_has_isdelete() { _has_bits_[0] &= ~0x00000008u; } inline void UserOneMailContent::clear_isdelete() { isdelete_ = 0u; clear_has_isdelete(); } inline ::google::protobuf::uint32 UserOneMailContent::isdelete() const { return isdelete_; } inline void UserOneMailContent::set_isdelete(::google::protobuf::uint32 value) { set_has_isdelete(); isdelete_ = value; } // optional uint32 isread = 5; inline bool UserOneMailContent::has_isread() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void UserOneMailContent::set_has_isread() { _has_bits_[0] |= 0x00000010u; } inline void UserOneMailContent::clear_has_isread() { _has_bits_[0] &= ~0x00000010u; } inline void UserOneMailContent::clear_isread() { isread_ = 0u; clear_has_isread(); } inline ::google::protobuf::uint32 UserOneMailContent::isread() const { return isread_; } inline void UserOneMailContent::set_isread(::google::protobuf::uint32 value) { set_has_isread(); isread_ = value; } // ------------------------------------------------------------------- // UserOpenMail // ------------------------------------------------------------------- // SendMailContent // repeated .clientmsg.UserOneMailContent mail_contents = 1; inline int SendMailContent::mail_contents_size() const { return mail_contents_.size(); } inline void SendMailContent::clear_mail_contents() { mail_contents_.Clear(); } inline const ::clientmsg::UserOneMailContent& SendMailContent::mail_contents(int index) const { return mail_contents_.Get(index); } inline ::clientmsg::UserOneMailContent* SendMailContent::mutable_mail_contents(int index) { return mail_contents_.Mutable(index); } inline ::clientmsg::UserOneMailContent* SendMailContent::add_mail_contents() { return mail_contents_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::clientmsg::UserOneMailContent >& SendMailContent::mail_contents() const { return mail_contents_; } inline ::google::protobuf::RepeatedPtrField< ::clientmsg::UserOneMailContent >* SendMailContent::mutable_mail_contents() { return &mail_contents_; } // ------------------------------------------------------------------- // DelMail // repeated uint32 mail_ids = 2; inline int DelMail::mail_ids_size() const { return mail_ids_.size(); } inline void DelMail::clear_mail_ids() { mail_ids_.Clear(); } inline ::google::protobuf::uint32 DelMail::mail_ids(int index) const { return mail_ids_.Get(index); } inline void DelMail::set_mail_ids(int index, ::google::protobuf::uint32 value) { mail_ids_.Set(index, value); } inline void DelMail::add_mail_ids(::google::protobuf::uint32 value) { mail_ids_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >& DelMail::mail_ids() const { return mail_ids_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >* DelMail::mutable_mail_ids() { return &mail_ids_; } // ------------------------------------------------------------------- // ReadMail // repeated uint32 mail_ids = 1; inline int ReadMail::mail_ids_size() const { return mail_ids_.size(); } inline void ReadMail::clear_mail_ids() { mail_ids_.Clear(); } inline ::google::protobuf::uint32 ReadMail::mail_ids(int index) const { return mail_ids_.Get(index); } inline void ReadMail::set_mail_ids(int index, ::google::protobuf::uint32 value) { mail_ids_.Set(index, value); } inline void ReadMail::add_mail_ids(::google::protobuf::uint32 value) { mail_ids_.Add(value); } inline const ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >& ReadMail::mail_ids() const { return mail_ids_; } inline ::google::protobuf::RepeatedField< ::google::protobuf::uint32 >* ReadMail::mutable_mail_ids() { return &mail_ids_; } // ------------------------------------------------------------------- // UserSendMailByid // optional uint64 remoteid = 1; inline bool UserSendMailByid::has_remoteid() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void UserSendMailByid::set_has_remoteid() { _has_bits_[0] |= 0x00000001u; } inline void UserSendMailByid::clear_has_remoteid() { _has_bits_[0] &= ~0x00000001u; } inline void UserSendMailByid::clear_remoteid() { remoteid_ = GOOGLE_ULONGLONG(0); clear_has_remoteid(); } inline ::google::protobuf::uint64 UserSendMailByid::remoteid() const { return remoteid_; } inline void UserSendMailByid::set_remoteid(::google::protobuf::uint64 value) { set_has_remoteid(); remoteid_ = value; } // optional string content = 2; inline bool UserSendMailByid::has_content() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void UserSendMailByid::set_has_content() { _has_bits_[0] |= 0x00000002u; } inline void UserSendMailByid::clear_has_content() { _has_bits_[0] &= ~0x00000002u; } inline void UserSendMailByid::clear_content() { if (content_ != &::google::protobuf::internal::kEmptyString) { content_->clear(); } clear_has_content(); } inline const ::std::string& UserSendMailByid::content() const { return *content_; } inline void UserSendMailByid::set_content(const ::std::string& value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void UserSendMailByid::set_content(const char* value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void UserSendMailByid::set_content(const char* value, size_t size) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* UserSendMailByid::mutable_content() { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } return content_; } inline ::std::string* UserSendMailByid::release_content() { clear_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { return NULL; } else { ::std::string* temp = content_; content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); return temp; } } inline void UserSendMailByid::set_allocated_content(::std::string* content) { if (content_ != &::google::protobuf::internal::kEmptyString) { delete content_; } if (content) { set_has_content(); content_ = content; } else { clear_has_content(); content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); } } // optional .clientmsg.enumMailType type = 3; inline bool UserSendMailByid::has_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void UserSendMailByid::set_has_type() { _has_bits_[0] |= 0x00000004u; } inline void UserSendMailByid::clear_has_type() { _has_bits_[0] &= ~0x00000004u; } inline void UserSendMailByid::clear_type() { type_ = 1; clear_has_type(); } inline ::clientmsg::enumMailType UserSendMailByid::type() const { return static_cast< ::clientmsg::enumMailType >(type_); } inline void UserSendMailByid::set_type(::clientmsg::enumMailType value) { assert(::clientmsg::enumMailType_IsValid(value)); set_has_type(); type_ = value; } // ------------------------------------------------------------------- // UserSendMailByName // optional string remotename = 1; inline bool UserSendMailByName::has_remotename() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void UserSendMailByName::set_has_remotename() { _has_bits_[0] |= 0x00000001u; } inline void UserSendMailByName::clear_has_remotename() { _has_bits_[0] &= ~0x00000001u; } inline void UserSendMailByName::clear_remotename() { if (remotename_ != &::google::protobuf::internal::kEmptyString) { remotename_->clear(); } clear_has_remotename(); } inline const ::std::string& UserSendMailByName::remotename() const { return *remotename_; } inline void UserSendMailByName::set_remotename(const ::std::string& value) { set_has_remotename(); if (remotename_ == &::google::protobuf::internal::kEmptyString) { remotename_ = new ::std::string; } remotename_->assign(value); } inline void UserSendMailByName::set_remotename(const char* value) { set_has_remotename(); if (remotename_ == &::google::protobuf::internal::kEmptyString) { remotename_ = new ::std::string; } remotename_->assign(value); } inline void UserSendMailByName::set_remotename(const char* value, size_t size) { set_has_remotename(); if (remotename_ == &::google::protobuf::internal::kEmptyString) { remotename_ = new ::std::string; } remotename_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* UserSendMailByName::mutable_remotename() { set_has_remotename(); if (remotename_ == &::google::protobuf::internal::kEmptyString) { remotename_ = new ::std::string; } return remotename_; } inline ::std::string* UserSendMailByName::release_remotename() { clear_has_remotename(); if (remotename_ == &::google::protobuf::internal::kEmptyString) { return NULL; } else { ::std::string* temp = remotename_; remotename_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); return temp; } } inline void UserSendMailByName::set_allocated_remotename(::std::string* remotename) { if (remotename_ != &::google::protobuf::internal::kEmptyString) { delete remotename_; } if (remotename) { set_has_remotename(); remotename_ = remotename; } else { clear_has_remotename(); remotename_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); } } // optional string content = 2; inline bool UserSendMailByName::has_content() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void UserSendMailByName::set_has_content() { _has_bits_[0] |= 0x00000002u; } inline void UserSendMailByName::clear_has_content() { _has_bits_[0] &= ~0x00000002u; } inline void UserSendMailByName::clear_content() { if (content_ != &::google::protobuf::internal::kEmptyString) { content_->clear(); } clear_has_content(); } inline const ::std::string& UserSendMailByName::content() const { return *content_; } inline void UserSendMailByName::set_content(const ::std::string& value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void UserSendMailByName::set_content(const char* value) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(value); } inline void UserSendMailByName::set_content(const char* value, size_t size) { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } content_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* UserSendMailByName::mutable_content() { set_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { content_ = new ::std::string; } return content_; } inline ::std::string* UserSendMailByName::release_content() { clear_has_content(); if (content_ == &::google::protobuf::internal::kEmptyString) { return NULL; } else { ::std::string* temp = content_; content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); return temp; } } inline void UserSendMailByName::set_allocated_content(::std::string* content) { if (content_ != &::google::protobuf::internal::kEmptyString) { delete content_; } if (content) { set_has_content(); content_ = content; } else { clear_has_content(); content_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); } } // optional .clientmsg.enumMailType type = 3; inline bool UserSendMailByName::has_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void UserSendMailByName::set_has_type() { _has_bits_[0] |= 0x00000004u; } inline void UserSendMailByName::clear_has_type() { _has_bits_[0] &= ~0x00000004u; } inline void UserSendMailByName::clear_type() { type_ = 1; clear_has_type(); } inline ::clientmsg::enumMailType UserSendMailByName::type() const { return static_cast< ::clientmsg::enumMailType >(type_); } inline void UserSendMailByName::set_type(::clientmsg::enumMailType value) { assert(::clientmsg::enumMailType_IsValid(value)); set_has_type(); type_ = value; } // @@protoc_insertion_point(namespace_scope) } // namespace clientmsg #ifndef SWIG namespace google { namespace protobuf { template <> inline const EnumDescriptor* GetEnumDescriptor< ::clientmsg::enumMailType>() { return ::clientmsg::enumMailType_descriptor(); } } // namespace google } // namespace protobuf #endif // SWIG // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_mail_2eproto__INCLUDED
756175407bcb04d9c30b027344812ca9b9f08732
8c0f3902d02056e9904f04041c953467689d296b
/main.cpp
9fc59fb1090b647a0a3cc42e6ff0e9c30e766d32
[]
no_license
michael52695/bubble_sort_data10k
41e619a5201f7ca2f877d1d46f19a2b98e784e59
e9e8a194e05f579dfec3b57f3612bdd657ac95df
refs/heads/master
2021-01-23T03:48:23.989471
2013-02-05T08:00:53
2013-02-05T08:00:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
cpp
#include <iostream> #include <conio.h> #include<cstdlib> #include<string> #include<sstream> #include <fstream> using namespace std; int main() { int a[10000],count=0,n=0; int x,i=0,j=0; // clrscr(); ifstream myfile; string line; myfile.open ("data10k.txt"); while(!myfile.eof()){ getline(myfile,line); stringstream(line)>>x; a[i]=x; // cout<< x<<endl; i++; } for(int i = 0; i < 10000; i++) { for(int j = 0; j < 10000; j++) { if(a[i] < a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } std::cout << "\n\nThe numbers in ascending orders are given below:\n\n"; for(int i = 0; i < 10000; i++) { // std::cout << "Sorted [" << i + 1 << "] element: "; std::cout << a[i]; std::cout << "\n"; } delete [] a; myfile.close(); return 0; }
01ed8ce63924dad99d36dbdce0cdc059ad6da22a
ac1b74c5e8b9f09c15c0f7c33cc6dbc9a11cb89e
/2020/Day 1/report.cpp
8e47dc38ee5a60c795b4830bdce8b36567fb4d4b
[]
no_license
mrtonbrian/Advent-Of-Code
2ea5e5cc7d4b8ebbedf2eac12122dbcd60c54526
4b6e532d04db6212650e2345171042751f0fd9a5
refs/heads/master
2023-01-21T13:13:05.683855
2020-12-04T10:09:08
2020-12-04T10:09:08
318,156,987
1
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
#include <bits/stdc++.h> using namespace std; vector<int> nums; pair<int, int> twosum(int target, int start, int end) { unordered_set<int> complements; for (int i = 0; i < end; i++) { int x = nums[i]; if (complements.count(x)) { return make_pair(x, target-x); } complements.insert(target - x); } return make_pair(-1,-1); } int main() { int target = 2020; ifstream input("report.in"); while (true) { int i; input >> i; if (input.eof()) {break;} nums.push_back(i); } // Part 1 pair<int, int> part1 = twosum(target, 0, nums.size()); printf("Part 1 Answer: %d * %d = %d\n", part1.first, part1.second, part1.first * part1.second); // Part 2 for (int i = 0; i < nums.size(); i++) { int x = nums[i]; pair<int, int> remain = twosum(target - x, i, nums.size()); if (remain.first != -1 && remain.second != -1) { printf("Part 2 Answer: %d * %d * %d = %d\n", x, remain.first, remain.second, x * remain.first * remain.second); break; } } }
6db9d0687a3f2e8396e3504e7998d72e28c80a50
84f44ae897128baa9c6e3947052b9cb948153cc3
/lcd/lcd.ino
1bedd0aac006d4c2b40af9f76abc02ef50ac5c9c
[ "MIT" ]
permissive
mallvielfrass/ArduinoProject
6095dbc536f2e1549e6b668af9f00c10dacdbc24
a221b575a528a7a6f7d6ee5dd19ba63ff93b99c7
refs/heads/master
2020-12-07T08:01:23.954899
2020-01-08T23:35:55
2020-01-08T23:35:55
232,679,387
0
0
null
null
null
null
UTF-8
C++
false
false
2,803
ino
#include <LiquidCrystal.h> LiquidCrystal lcd(8, 9, 4, 5, 6, 7); #define BTN_UP 1 #define BTN_DOWN 2 #define BTN_LEFT 3 #define BTN_RIGHT 4 #define BTN_SELECT 5 #define BTN_NONE 10 #include <NewPing.h> #define PIN_TRIG 12 #define PIN_ECHO 11 #define MAX_DISTANCE 4000 NewPing sonar(PIN_TRIG, PIN_ECHO, MAX_DISTANCE); int detectButton() { int keyAnalog = analogRead(A0); if (keyAnalog < 100) { // Значение меньше 100 – нажата кнопка right return BTN_RIGHT; } else if (keyAnalog < 200) { // Значение больше 100 (иначе мы бы вошли в предыдущий блок результата сравнения, но меньше 200 – нажата кнопка UP return BTN_UP; } else if (keyAnalog < 400) { // Значение больше 200, но меньше 400 – нажата кнопка DOWN return BTN_DOWN; } else if (keyAnalog < 600) { // Значение больше 400, но меньше 600 – нажата кнопка LEFT return BTN_LEFT; } else if (keyAnalog < 800) { // Значение больше 600, но меньше 800 – нажата кнопка SELECT return BTN_SELECT; } else { // Все остальные значения (до 1023) будут означать, что нажатий не было return BTN_NONE; } } void clearLine(int line){ lcd.setCursor(0, 1); lcd.print(" "); } void printDisplay(String message){ Serial.println(message); lcd.setCursor(0, 1); lcd.print(message); delay(1000); clearLine(1); } void setup() { Serial.begin(9600); lcd.begin(16, 2); lcd.print("Arduino Master"); delay(3000); lcd.setCursor(0, 0); lcd.print("Arduino Master"); } void loop() { delay(200); unsigned int distance = sonar.ping_cm(); // Печатаем расстояние в мониторе порта Serial.print(distance); Serial.println("см"); lcd.setCursor(0, 1); lcd.print(" "); lcd.setCursor(0, 1); lcd.print(distance); int button = detectButton(); switch (button) { case BTN_UP: printDisplay("UP"); break; case BTN_DOWN: printDisplay("DOWN"); break; case BTN_LEFT: printDisplay("LEFT"); break; case BTN_RIGHT: printDisplay("RIGHT"); break; case BTN_SELECT: printDisplay("SELECT"); break; default: //printDisplay("Press any key"); break; } }
3fed7314ebe91b2287392f2d906bfd279ccd33d6
420f1a298ad4c94e44e7ff60fe309d79b080723a
/org.alljoyn.ControlPanel.Humidifier/HumidifierServiceEventArgs.h
347241574b070b70fad7e62ebad137c1c695eca5
[ "MIT" ]
permissive
jpoon/HeavenFresh-AllJoyn-Example
fe5820915b2e715fd6cd725babfdb16fa297dec8
10ed91014f072031eb13df613cc1165e19fd7726
refs/heads/master
2021-01-17T12:19:24.140864
2016-07-20T06:41:19
2016-07-20T06:41:19
42,607,513
0
1
null
2015-09-17T17:22:58
2015-09-16T19:04:13
C++
UTF-8
C++
false
false
27,544
h
//----------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // // Tool: AllJoynCodeGenerator.exe // // This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn // Visual Studio Extension in the Visual Studio Gallery. // // The generated code should be packaged in a Windows 10 C++/CX Runtime // Component which can be consumed in any UWP-supported language using // APIs that are available in Windows.Devices.AllJoyn. // // Using AllJoynCodeGenerator - Invoke the following command with a valid // Introspection XML file and a writable output directory: // AllJoynCodeGenerator -i <INPUT XML FILE> -o <OUTPUT DIRECTORY> // </auto-generated> //----------------------------------------------------------------------------- #pragma once namespace org { namespace alljoyn { namespace ControlPanel { namespace Humidifier { // Methods public ref class HumidifierPowerONCalledEventArgs sealed { public: HumidifierPowerONCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierPowerONResult^ Result { HumidifierPowerONResult^ get() { return m_result; } void set(_In_ HumidifierPowerONResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierPowerONResult^>^ GetResultAsync(HumidifierPowerONCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierPowerONResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierPowerONResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierPowerONResult^ m_result; }; public ref class HumidifierPowerOFFCalledEventArgs sealed { public: HumidifierPowerOFFCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierPowerOFFResult^ Result { HumidifierPowerOFFResult^ get() { return m_result; } void set(_In_ HumidifierPowerOFFResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierPowerOFFResult^>^ GetResultAsync(HumidifierPowerOFFCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierPowerOFFResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierPowerOFFResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierPowerOFFResult^ m_result; }; public ref class HumidifierSendSoftwareUpgradeFileCalledEventArgs sealed { public: HumidifierSendSoftwareUpgradeFileCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ uint32 interfaceMemberCurrentIndex, _In_ Windows::Foundation::Collections::IVectorView<byte>^ interfaceMemberFileData); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierSendSoftwareUpgradeFileResult^ Result { HumidifierSendSoftwareUpgradeFileResult^ get() { return m_result; } void set(_In_ HumidifierSendSoftwareUpgradeFileResult^ value) { m_result = value; } } property uint32 CurrentIndex { uint32 get() { return m_interfaceMemberCurrentIndex; } } property Windows::Foundation::Collections::IVectorView<byte>^ FileData { Windows::Foundation::Collections::IVectorView<byte>^ get() { return m_interfaceMemberFileData; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierSendSoftwareUpgradeFileResult^>^ GetResultAsync(HumidifierSendSoftwareUpgradeFileCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSendSoftwareUpgradeFileResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSendSoftwareUpgradeFileResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierSendSoftwareUpgradeFileResult^ m_result; uint32 m_interfaceMemberCurrentIndex; Windows::Foundation::Collections::IVectorView<byte>^ m_interfaceMemberFileData; }; // Readable Properties public ref class HumidifierGetPowerStatusRequestedEventArgs sealed { public: HumidifierGetPowerStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetPowerStatusResult^ Result { HumidifierGetPowerStatusResult^ get() { return m_result; } void set(_In_ HumidifierGetPowerStatusResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetPowerStatusResult^>^ GetResultAsync(HumidifierGetPowerStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetPowerStatusResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetPowerStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetPowerStatusResult^ m_result; }; public ref class HumidifierGetHumidityValueRequestedEventArgs sealed { public: HumidifierGetHumidityValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetHumidityValueResult^ Result { HumidifierGetHumidityValueResult^ get() { return m_result; } void set(_In_ HumidifierGetHumidityValueResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetHumidityValueResult^>^ GetResultAsync(HumidifierGetHumidityValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetHumidityValueResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetHumidityValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetHumidityValueResult^ m_result; }; public ref class HumidifierGetIonStatusRequestedEventArgs sealed { public: HumidifierGetIonStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetIonStatusResult^ Result { HumidifierGetIonStatusResult^ get() { return m_result; } void set(_In_ HumidifierGetIonStatusResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetIonStatusResult^>^ GetResultAsync(HumidifierGetIonStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetIonStatusResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetIonStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetIonStatusResult^ m_result; }; public ref class HumidifierGetWarmMistStatusRequestedEventArgs sealed { public: HumidifierGetWarmMistStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetWarmMistStatusResult^ Result { HumidifierGetWarmMistStatusResult^ get() { return m_result; } void set(_In_ HumidifierGetWarmMistStatusResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetWarmMistStatusResult^>^ GetResultAsync(HumidifierGetWarmMistStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetWarmMistStatusResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetWarmMistStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetWarmMistStatusResult^ m_result; }; public ref class HumidifierGetMistVolumeValueRequestedEventArgs sealed { public: HumidifierGetMistVolumeValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetMistVolumeValueResult^ Result { HumidifierGetMistVolumeValueResult^ get() { return m_result; } void set(_In_ HumidifierGetMistVolumeValueResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetMistVolumeValueResult^>^ GetResultAsync(HumidifierGetMistVolumeValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetMistVolumeValueResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetMistVolumeValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetMistVolumeValueResult^ m_result; }; public ref class HumidifierGetTimerValueRequestedEventArgs sealed { public: HumidifierGetTimerValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetTimerValueResult^ Result { HumidifierGetTimerValueResult^ get() { return m_result; } void set(_In_ HumidifierGetTimerValueResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetTimerValueResult^>^ GetResultAsync(HumidifierGetTimerValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetTimerValueResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetTimerValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetTimerValueResult^ m_result; }; public ref class HumidifierGetCurrentRoomTempValueRequestedEventArgs sealed { public: HumidifierGetCurrentRoomTempValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetCurrentRoomTempValueResult^ Result { HumidifierGetCurrentRoomTempValueResult^ get() { return m_result; } void set(_In_ HumidifierGetCurrentRoomTempValueResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetCurrentRoomTempValueResult^>^ GetResultAsync(HumidifierGetCurrentRoomTempValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetCurrentRoomTempValueResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetCurrentRoomTempValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetCurrentRoomTempValueResult^ m_result; }; public ref class HumidifierGetCurrentRoomHumidityValueRequestedEventArgs sealed { public: HumidifierGetCurrentRoomHumidityValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetCurrentRoomHumidityValueResult^ Result { HumidifierGetCurrentRoomHumidityValueResult^ get() { return m_result; } void set(_In_ HumidifierGetCurrentRoomHumidityValueResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetCurrentRoomHumidityValueResult^>^ GetResultAsync(HumidifierGetCurrentRoomHumidityValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetCurrentRoomHumidityValueResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetCurrentRoomHumidityValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetCurrentRoomHumidityValueResult^ m_result; }; public ref class HumidifierGetWaterTankStatusRequestedEventArgs sealed { public: HumidifierGetWaterTankStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property HumidifierGetWaterTankStatusResult^ Result { HumidifierGetWaterTankStatusResult^ get() { return m_result; } void set(_In_ HumidifierGetWaterTankStatusResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<HumidifierGetWaterTankStatusResult^>^ GetResultAsync(HumidifierGetWaterTankStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierGetWaterTankStatusResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierGetWaterTankStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; HumidifierGetWaterTankStatusResult^ m_result; }; // Writable Properties public ref class HumidifierSetPowerStatusRequestedEventArgs sealed { public: HumidifierSetPowerStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ int32 value); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property int32 Value { int32 get() { return m_value; } } property HumidifierSetPowerStatusResult^ Result { HumidifierSetPowerStatusResult^ get() { return m_result; } void set(_In_ HumidifierSetPowerStatusResult^ value) { m_result = value; } } static Windows::Foundation::IAsyncOperation<HumidifierSetPowerStatusResult^>^ GetResultAsync(HumidifierSetPowerStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSetPowerStatusResult^> { return t; }); } Windows::Foundation::Deferral^ GetDeferral(); private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSetPowerStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; int32 m_value; HumidifierSetPowerStatusResult^ m_result; }; public ref class HumidifierSetHumidityValueRequestedEventArgs sealed { public: HumidifierSetHumidityValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ int32 value); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property int32 Value { int32 get() { return m_value; } } property HumidifierSetHumidityValueResult^ Result { HumidifierSetHumidityValueResult^ get() { return m_result; } void set(_In_ HumidifierSetHumidityValueResult^ value) { m_result = value; } } static Windows::Foundation::IAsyncOperation<HumidifierSetHumidityValueResult^>^ GetResultAsync(HumidifierSetHumidityValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSetHumidityValueResult^> { return t; }); } Windows::Foundation::Deferral^ GetDeferral(); private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSetHumidityValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; int32 m_value; HumidifierSetHumidityValueResult^ m_result; }; public ref class HumidifierSetIonStatusRequestedEventArgs sealed { public: HumidifierSetIonStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ int32 value); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property int32 Value { int32 get() { return m_value; } } property HumidifierSetIonStatusResult^ Result { HumidifierSetIonStatusResult^ get() { return m_result; } void set(_In_ HumidifierSetIonStatusResult^ value) { m_result = value; } } static Windows::Foundation::IAsyncOperation<HumidifierSetIonStatusResult^>^ GetResultAsync(HumidifierSetIonStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSetIonStatusResult^> { return t; }); } Windows::Foundation::Deferral^ GetDeferral(); private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSetIonStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; int32 m_value; HumidifierSetIonStatusResult^ m_result; }; public ref class HumidifierSetWarmMistStatusRequestedEventArgs sealed { public: HumidifierSetWarmMistStatusRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ int32 value); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property int32 Value { int32 get() { return m_value; } } property HumidifierSetWarmMistStatusResult^ Result { HumidifierSetWarmMistStatusResult^ get() { return m_result; } void set(_In_ HumidifierSetWarmMistStatusResult^ value) { m_result = value; } } static Windows::Foundation::IAsyncOperation<HumidifierSetWarmMistStatusResult^>^ GetResultAsync(HumidifierSetWarmMistStatusRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSetWarmMistStatusResult^> { return t; }); } Windows::Foundation::Deferral^ GetDeferral(); private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSetWarmMistStatusResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; int32 m_value; HumidifierSetWarmMistStatusResult^ m_result; }; public ref class HumidifierSetMistVolumeValueRequestedEventArgs sealed { public: HumidifierSetMistVolumeValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ int32 value); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property int32 Value { int32 get() { return m_value; } } property HumidifierSetMistVolumeValueResult^ Result { HumidifierSetMistVolumeValueResult^ get() { return m_result; } void set(_In_ HumidifierSetMistVolumeValueResult^ value) { m_result = value; } } static Windows::Foundation::IAsyncOperation<HumidifierSetMistVolumeValueResult^>^ GetResultAsync(HumidifierSetMistVolumeValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSetMistVolumeValueResult^> { return t; }); } Windows::Foundation::Deferral^ GetDeferral(); private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSetMistVolumeValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; int32 m_value; HumidifierSetMistVolumeValueResult^ m_result; }; public ref class HumidifierSetTimerValueRequestedEventArgs sealed { public: HumidifierSetTimerValueRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ int32 value); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property int32 Value { int32 get() { return m_value; } } property HumidifierSetTimerValueResult^ Result { HumidifierSetTimerValueResult^ get() { return m_result; } void set(_In_ HumidifierSetTimerValueResult^ value) { m_result = value; } } static Windows::Foundation::IAsyncOperation<HumidifierSetTimerValueResult^>^ GetResultAsync(HumidifierSetTimerValueRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<HumidifierSetTimerValueResult^> { return t; }); } Windows::Foundation::Deferral^ GetDeferral(); private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<HumidifierSetTimerValueResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; int32 m_value; HumidifierSetTimerValueResult^ m_result; }; } } } }
c4804a913d9cc502f0961a555af6da5c62361bf9
9355bd6f4e0a2468d0160e5194d95d7877309e37
/Ejercicio 2/MyForm.cpp
6d5fc971d0c878f8cf9d607ccfe951a093a7a66d
[]
no_license
ErwinLima/Laboratorio-5
7e34defa73ac834dd066eba1bc13d482ec25cadd
cf5ce229c3be417b8bb6e9c41f71a7545bca5f17
refs/heads/master
2023-08-11T17:57:51.123968
2021-10-10T05:11:55
2021-10-10T05:11:55
411,373,420
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include "MyForm.h" using namespace System; using namespace System::Windows::Forms; [STAThreadAttribute] int main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); Ejercicio2::MyForm form; Application::Run(%form); return 0; }
20821468ad01121ab09c9ada139369a474b5a40f
79d33ac942942703fc433a767fc295f39f12f3a8
/PC_Software/Lasaw/Include/GridCtrl_src/GridCtrl.h
e7424fbb0a899ac1598cbd0594e222cc55dd4a15
[]
no_license
yisea123/glassCut
a6a00bbead9535515c0b47f2c84c36f20a3db26b
239d122f3079662950179f3b0662e23f5fb470bd
refs/heads/master
2020-09-05T13:55:46.604987
2019-06-18T09:35:25
2019-06-18T09:35:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,864
h
///////////////////////////////////////////////////////////////////////////// // GridCtrl.h : header file // // MFC Grid Control - main header // // Written by Chris Maunder <[email protected]> // Copyright (c) 1998-2005. All Rights Reserved. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name and all copyright // notices remains intact. // // An email letting me know how you are using it would be nice as well. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability for any damage/loss of business that // this product may cause. // // For use with CGridCtrl v2.20+ // ////////////////////////////////////////////////////////////////////// // FEATURES BY Mukit, Ataul (2007-11-17): // 1. Merge Cell // 2. Ability to do XL Style Freeze Pane // 3. The Horizontal Gray Area Removed // FINDINGS: // 1. A cell cannot be edited if a tooltip is shown.. // 2. The InplaceEditCtrl is not multiline even if a cell can contain Multiline Text.. // 3. If a cell is too small, the InplaceEditCtrl is almost invisible.. // Add By Sejin, Jeong (2015-03-31) // 1. Add filter function // 2. Modify merge cell // 3. remove "Ability to do XL Style Freeze Pane" // 4. remove "The Horizontal Gray Area Removed" #if !defined(AFX_GRIDCTRL_H__519FA702_722C_11D1_ABBA_00A0243D1382__INCLUDED_) #define AFX_GRIDCTRL_H__519FA702_722C_11D1_ABBA_00A0243D1382__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "CellRange.h" #include "GridCell.h" #include <afxtempl.h> #include <vector> /////////////////////////////////////////////////////////////////////////////////// // Defines - these determine the features (and the final size) of the final code /////////////////////////////////////////////////////////////////////////////////// //#define GRIDCONTROL_NO_TITLETIPS // Do not use titletips for cells with large data //#define GRIDCONTROL_NO_DRAGDROP // Do not use OLE drag and drop //#define GRIDCONTROL_NO_CLIPBOARD // Do not use clipboard routines #ifdef _WIN32_WCE # define GRIDCONTROL_NO_TITLETIPS // Do not use titletips for cells with large data # define GRIDCONTROL_NO_DRAGDROP // Do not use OLE drag and drop # define GRIDCONTROL_NO_CLIPBOARD // Do not use clipboard routines # define GRIDCONTROL_NO_PRINTING // Do not use printing routines # ifdef WCE_NO_PRINTING // Older versions of CE had different #def's # define _WIN32_WCE_NO_PRINTING # endif # ifdef WCE_NO_CURSOR # define _WIN32_WCE_NO_CURSOR # endif #endif // _WIN32_WCE // Use this as the classname when inserting this control as a custom control // in the MSVC++ dialog editor #define GRIDCTRL_CLASSNAME _T("MFCGridCtrl") // Window class name #define IDC_INPLACE_CONTROL 8 // ID of inplace edit controls /////////////////////////////////////////////////////////////////////////////////// // Conditional includes /////////////////////////////////////////////////////////////////////////////////// #ifndef GRIDCONTROL_NO_TITLETIPS # include "TitleTip.h" #endif #ifndef GRIDCONTROL_NO_DRAGDROP # include "GridDropTarget.h" # undef GRIDCONTROL_NO_CLIPBOARD // Force clipboard functions on #endif #ifndef GRIDCONTROL_NO_CLIPBOARD # include <afxole.h> #endif /////////////////////////////////////////////////////////////////////////////////// // Helper functions /////////////////////////////////////////////////////////////////////////////////// // Handy functions #define IsSHIFTpressed() ( (GetKeyState(VK_SHIFT) & (1 << (sizeof(SHORT)*8-1))) != 0 ) #define IsCTRLpressed() ( (GetKeyState(VK_CONTROL) & (1 << (sizeof(SHORT)*8-1))) != 0 ) // Backwards compatibility for pre 2.20 grid versions #define DDX_GridControl(pDX, nIDC, rControl) DDX_Control(pDX, nIDC, rControl) /////////////////////////////////////////////////////////////////////////////////// // Structures /////////////////////////////////////////////////////////////////////////////////// // This structure sent to Grid's parent in a WM_NOTIFY message typedef struct tagNM_GRIDVIEW { NMHDR hdr; int iRow; int iColumn; } NM_GRIDVIEW; // This is sent to the Grid from child in-place edit controls typedef struct tagGV_DISPINFO { NMHDR hdr; GV_ITEM item; } GV_DISPINFO; // This is sent to the Grid from child in-place edit controls typedef struct tagGV_CACHEHINT { NMHDR hdr; CCellRange range; } GV_CACHEHINT; // storage typedef for each row in the grid typedef CTypedPtrArray<CObArray, CGridCellBase*> GRID_ROW; // For virtual mode callback typedef BOOL (CALLBACK* GRIDCALLBACK)(GV_DISPINFO *, LPARAM); /////////////////////////////////////////////////////////////////////////////////// // Defines /////////////////////////////////////////////////////////////////////////////////// // Grid line/scrollbar selection #define GVL_NONE 0L // Neither #define GVL_HORZ 1L // Horizontal line or scrollbar #define GVL_VERT 2L // Vertical line or scrollbar #define GVL_BOTH 3L // Both // Autosizing option #define GVS_DEFAULT 0 #define GVS_HEADER 1 // Size using column fixed cells data only #define GVS_DATA 2 // Size using column non-fixed cells data only #define GVS_BOTH 3 // Size using column fixed and non-fixed // Cell Searching options #define GVNI_FOCUSED 0x0001 #define GVNI_SELECTED 0x0002 #define GVNI_DROPHILITED 0x0004 #define GVNI_READONLY 0x0008 #define GVNI_FIXED 0x0010 #define GVNI_MODIFIED 0x0020 #define MODIFY_SET 0x0000 #define MODIFY_ADD 0x0001 #define MODIFY_SUB 0x0002 // LUC #define GVNI_FREEZED 0x0040 #define GVNI_ABOVE LVNI_ABOVE #define GVNI_BELOW LVNI_BELOW #define GVNI_TOLEFT LVNI_TOLEFT #define GVNI_TORIGHT LVNI_TORIGHT #define GVNI_ALL (LVNI_BELOW|LVNI_TORIGHT|LVNI_TOLEFT) #define GVNI_AREA (LVNI_BELOW|LVNI_TORIGHT) // Hit test values (not yet implemented) #define GVHT_DATA 0x0000 #define GVHT_TOPLEFT 0x0001 #define GVHT_COLHDR 0x0002 #define GVHT_ROWHDR 0x0004 #define GVHT_COLSIZER 0x0008 #define GVHT_ROWSIZER 0x0010 #define GVHT_LEFT 0x0020 #define GVHT_RIGHT 0x0040 #define GVHT_ABOVE 0x0080 #define GVHT_BELOW 0x0100 // Messages sent to the grid's parent (More will be added in future) #define GVN_BEGINDRAG LVN_BEGINDRAG // LVN_FIRST-9 #define GVN_BEGINLABELEDIT LVN_BEGINLABELEDIT // LVN_FIRST-5 #define GVN_BEGINRDRAG LVN_BEGINRDRAG #define GVN_COLUMNCLICK LVN_COLUMNCLICK #define GVN_DELETEITEM LVN_DELETEITEM #define GVN_ENDLABELEDIT LVN_ENDLABELEDIT // LVN_FIRST-6 #define GVN_SELCHANGING LVN_ITEMCHANGING #define GVN_SELCHANGED LVN_ITEMCHANGED #define GVN_GETDISPINFO LVN_GETDISPINFO #define GVN_ODCACHEHINT LVN_ODCACHEHINT class CGridCtrl; ///////////////////////////////////////////////////////////////////////////// // CGridCtrl window typedef bool (*PVIRTUALCOMPARE)(int, int); class CGridCtrl : public CWnd { DECLARE_DYNCREATE(CGridCtrl) friend class CGridCell; friend class CGridCellBase; // Construction public: CGridCtrl(int nRows = 0, int nCols = 0, int nFixedRows = 0, int nFixedCols = 0); BOOL Create(const RECT& rect, CWnd* parent, UINT nID, DWORD dwStyle = WS_CHILD | WS_BORDER | WS_TABSTOP | WS_VISIBLE | WS_EX_TRANSPARENT); /////////////////////////////////////////////////////////////////////////////////// // Attributes /////////////////////////////////////////////////////////////////////////////////// public: ///// LUC /////////////////////////////////////////////////////////////////////// //// LUC : MergeCell//////// INT_PTR MergeCells(CCellRange& mergedCellRange); void SplitCells(INT_PTR nMergeID); BOOL IsMergedCell(int row, int col, CCellRange& mergedCellRange); BOOL GetMergedCellRect(int row, int col, CRect& rect); BOOL GetMergedCellRect(CCellRange& mergedCell, CRect& rect); BOOL GetTopLeftMergedCell(int& row, int& col, CRect& mergeRect); BOOL GetBottomRightMergedCell(int& row, int& col, CRect& mergeRect); virtual BOOL IsFocused(CGridCellBase& cell, int nRow, int nCol); virtual BOOL IsSelected(CGridCellBase& cell, int nRow, int nCol); BOOL m_bDrawingMergedCell; INT_PTR m_nCurrentMergeID; static CRect rectNull; static CCellID cellNull; // Jeong : show, hide row int m_nSaveRowHeight; // Jeong : Splitting a string CStringArray* Split(CString strSource, CString strToken); /////////////////////////////////////////////////////////////////////////////////////// int GetRowCount() const { return m_nRows; } int GetColumnCount() const { return m_nCols; } int GetFixedRowCount() const { return m_nFixedRows; } int GetFixedColumnCount() const { return m_nFixedCols; } int GetNonFixedRowsCount()const { return m_nRows - m_nFixedRows; } int GetNonFixedColumnCount()const { return m_nCols - m_nFixedCols; } BOOL SetRowCount(int nRows = 10); BOOL SetColumnCount(int nCols = 10); BOOL SetFixedRowCount(int nFixedRows = 1); BOOL SetFixedColumnCount(int nFixedCols = 1); public: int GetRowHeight(int nRow) const; BOOL SetRowHeight(int row, int height); int GetColumnWidth(int nCol) const; BOOL SetColumnWidth(int col, int width); BOOL GetCellOrigin(int nRow, int nCol, LPPOINT p); BOOL GetCellOrigin(const CCellID& cell, LPPOINT p); BOOL GetCellRect(int nRow, int nCol, LPRECT pRect); BOOL GetCellRect(const CCellID& cell, LPRECT pRect); BOOL GetTextRect(const CCellID& cell, LPRECT pRect); BOOL GetTextRect(int nRow, int nCol, LPRECT pRect); // LUC // Change for MergeCell CCellID GetCellFromPt(CPoint point, BOOL bAllowFixedCellCheck = TRUE, CCellID& cellOriginal = cellNull); // LUC int GetFixedRowHeight() const; int GetFixedColumnWidth() const; long GetVirtualWidth() const; long GetVirtualHeight() const; CSize GetTextExtent(int nRow, int nCol, LPCTSTR str); // EFW - Get extent of current text in cell inline CSize GetCellTextExtent(int nRow, int nCol) { return GetTextExtent(nRow, nCol, GetItemText(nRow,nCol)); } void SetGridBkColor(COLORREF clr) { m_crGridBkColour = clr; } COLORREF GetGridBkColor() const { return m_crGridBkColour; } void SetGridLineColor(COLORREF clr) { m_crGridLineColour = clr; } COLORREF GetGridLineColor() const { return m_crGridLineColour; } void SetTitleTipBackClr(COLORREF clr = CLR_DEFAULT) { m_crTTipBackClr = clr; } COLORREF GetTitleTipBackClr() { return m_crTTipBackClr; } void SetTitleTipTextClr(COLORREF clr = CLR_DEFAULT) { m_crTTipTextClr = clr; } COLORREF GetTitleTipTextClr() { return m_crTTipTextClr; } // ***************************************************************************** // // These have been deprecated. Use GetDefaultCell and then set the colors void SetTextColor(COLORREF clr) { m_cellDefault.SetTextClr(clr); } COLORREF GetTextColor() { return m_cellDefault.GetTextClr(); } void SetTextBkColor(COLORREF clr) { m_cellDefault.SetBackClr(clr); } COLORREF GetTextBkColor() { return m_cellDefault.GetBackClr(); } void SetFixedTextColor(COLORREF clr) { m_cellFixedRowDef.SetTextClr(clr); m_cellFixedColDef.SetTextClr(clr); m_cellFixedRowColDef.SetTextClr(clr); } COLORREF GetFixedTextColor() const { return m_cellFixedRowDef.GetTextClr(); } void SetFixedBkColor(COLORREF clr) { m_cellFixedRowDef.SetBackClr(clr); m_cellFixedColDef.SetBackClr(clr); m_cellFixedRowColDef.SetBackClr(clr); } COLORREF GetFixedBkColor() const { return m_cellFixedRowDef.GetBackClr(); } void SetGridColor(COLORREF clr) { SetGridLineColor(clr); } COLORREF GetGridColor() { return GetGridLineColor(); } void SetBkColor(COLORREF clr) { SetGridBkColor(clr); } COLORREF GetBkColor() { return GetGridBkColor(); } void SetDefCellMargin( int nMargin) { m_cellDefault.SetMargin(nMargin); m_cellFixedRowDef.SetMargin(nMargin); m_cellFixedColDef.SetMargin(nMargin); m_cellFixedRowColDef.SetMargin(nMargin); } int GetDefCellMargin() const { return m_cellDefault.GetMargin(); } int GetDefCellHeight() const { return m_cellDefault.GetHeight(); } void SetDefCellHeight(int nHeight) { m_cellDefault.SetHeight(nHeight); m_cellFixedRowDef.SetHeight(nHeight); m_cellFixedColDef.SetHeight(nHeight); m_cellFixedRowColDef.SetHeight(nHeight); } int GetDefCellWidth() const { return m_cellDefault.GetWidth(); } void SetDefCellWidth(int nWidth) { m_cellDefault.SetWidth(nWidth); m_cellFixedRowDef.SetWidth(nWidth); m_cellFixedColDef.SetWidth(nWidth); m_cellFixedRowColDef.SetWidth(nWidth); } // ***************************************************************************** // int GetSelectedCount() const { return (int)m_SelectedCellMap.GetCount(); } CCellID SetFocusCell(CCellID cell); CCellID SetFocusCell(int nRow, int nCol); CCellID GetFocusCell() const { return m_idCurrentCell; } void SetVirtualMode(BOOL bVirtual); BOOL GetVirtualMode() const { return m_bVirtualMode; } void SetCallbackFunc(GRIDCALLBACK pCallback, LPARAM lParam) { m_pfnCallback = pCallback; m_lParam = lParam; } GRIDCALLBACK GetCallbackFunc() { return m_pfnCallback; } void SetImageList(CImageList* pList) { m_pImageList = pList; } CImageList* GetImageList() const { return m_pImageList; } void SetGridLines(int nWhichLines = GVL_BOTH); int GetGridLines() const { return m_nGridLines; } void SetEditable(BOOL bEditable = TRUE) { m_bEditable = bEditable; } BOOL IsEditable() const { return m_bEditable; } void SetListMode(BOOL bEnableListMode = TRUE); BOOL GetListMode() const { return m_bListMode; } void SetSingleRowSelection(BOOL bSing = TRUE) { m_bSingleRowSelection = bSing; } BOOL GetSingleRowSelection() { return m_bSingleRowSelection & m_bListMode; } void SetSingleColSelection(BOOL bSing = TRUE) { m_bSingleColSelection = bSing; } BOOL GetSingleColSelection() { return m_bSingleColSelection; } void EnableSelection(BOOL bEnable = TRUE) { ResetSelectedRange(); m_bEnableSelection = bEnable; ResetSelectedRange(); } BOOL IsSelectable() const { return m_bEnableSelection; } void SetFixedColumnSelection(BOOL bSelect) { m_bFixedColumnSelection = bSelect;} BOOL GetFixedColumnSelection() { return m_bFixedColumnSelection; } void SetFixedRowSelection(BOOL bSelect) { m_bFixedRowSelection = bSelect; } BOOL GetFixedRowSelection() { return m_bFixedRowSelection; } void EnableDragAndDrop(BOOL bAllow = TRUE) { m_bAllowDragAndDrop = bAllow; } BOOL GetDragAndDrop() const { return m_bAllowDragAndDrop; } void SetRowResize(BOOL bResize = TRUE) { m_bAllowRowResize = bResize; } BOOL GetRowResize() const { return m_bAllowRowResize; } void SetColumnResize(BOOL bResize = TRUE) { m_bAllowColumnResize = bResize; } BOOL GetColumnResize() const { return m_bAllowColumnResize; } void SetHeaderSort(BOOL bSortOnClick = TRUE) { m_bSortOnClick = bSortOnClick; } BOOL GetHeaderSort() const { return m_bSortOnClick; } void SetHandleTabKey(BOOL bHandleTab = TRUE) { m_bHandleTabKey = bHandleTab; } BOOL GetHandleTabKey() const { return m_bHandleTabKey; } void SetDoubleBuffering(BOOL bBuffer = TRUE) { m_bDoubleBuffer = bBuffer; } BOOL GetDoubleBuffering() const { return m_bDoubleBuffer; } void EnableTitleTips(BOOL bEnable = TRUE) { m_bTitleTips = bEnable; } BOOL GetTitleTips() { return m_bTitleTips; } void SetSortColumn(int nCol); int GetSortColumn() const { return m_nSortColumn; } void SetSortAscending(BOOL bAscending) { m_bAscending = bAscending; } BOOL GetSortAscending() const { return m_bAscending; } void SetTrackFocusCell(BOOL bTrack) { m_bTrackFocusCell = bTrack; } BOOL GetTrackFocusCell() { return m_bTrackFocusCell; } void SetFrameFocusCell(BOOL bFrame) { m_bFrameFocus = bFrame; } BOOL GetFrameFocusCell() { return m_bFrameFocus; } void SetAutoSizeStyle(int nStyle = GVS_BOTH) { m_nAutoSizeColumnStyle = nStyle; } int GetAutoSizeStyle() { return m_nAutoSizeColumnStyle; } void EnableHiddenColUnhide(BOOL bEnable = TRUE){ m_bHiddenColUnhide = bEnable; } BOOL GetHiddenColUnhide() { return m_bHiddenColUnhide; } void EnableHiddenRowUnhide(BOOL bEnable = TRUE){ m_bHiddenRowUnhide = bEnable; } BOOL GetHiddenRowUnhide() { return m_bHiddenRowUnhide; } void EnableColumnHide(BOOL bEnable = TRUE) { m_bAllowColHide = bEnable; } BOOL GetColumnHide() { return m_bAllowColHide; } void EnableRowHide(BOOL bEnable = TRUE) { m_bAllowRowHide = bEnable; } BOOL GetRowHide() { return m_bAllowRowHide; } /////////////////////////////////////////////////////////////////////////////////// // default Grid cells. Use these for setting default values such as colors and fonts /////////////////////////////////////////////////////////////////////////////////// public: CGridCellBase* GetDefaultCell(BOOL bFixedRow, BOOL bFixedCol) const; /////////////////////////////////////////////////////////////////////////////////// // Grid cell Attributes /////////////////////////////////////////////////////////////////////////////////// public: CGridCellBase* GetCell(int nRow, int nCol) const; // Get the actual cell! void SetModified(BOOL bModified = TRUE, int nRow = -1, int nCol = -1); BOOL GetModified(int nRow = -1, int nCol = -1); BOOL IsCellFixed(int nRow, int nCol); BOOL SetItem(const GV_ITEM* pItem); BOOL GetItem(GV_ITEM* pItem); BOOL SetItemText(int nRow, int nCol, LPCTSTR str); // The following was virtual. If you want to override, use // CGridCellBase-derived class's GetText() to accomplish same thing CString GetItemText(int nRow, int nCol) const; // EFW - 06/13/99 - Added to support printf-style formatting codes. // Also supports use with a string resource ID #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 210) BOOL SetItemTextFmt(int nRow, int nCol, LPCTSTR szFmt, ...); BOOL SetItemTextFmtID(int nRow, int nCol, UINT nID, ...); #endif BOOL SetItemData(int nRow, int nCol, LPARAM lParam); LPARAM GetItemData(int nRow, int nCol) const; BOOL SetItemImage(int nRow, int nCol, int iImage); int GetItemImage(int nRow, int nCol) const; BOOL AddItemState(CCellRange Selection, UINT state); BOOL AddItemState(int nRow, int nCol, UINT state); BOOL SetItemState(CCellRange Selection, UINT state,BYTE modify=0); BOOL SetItemState(int nRow, int nCol, UINT state, BYTE modify = 0); UINT GetItemState(int nRow, int nCol) const; BOOL SetItemFormat(int nRow, int nCol, UINT nFormat); UINT GetItemFormat(int nRow, int nCol) const; BOOL SetItemBkColour(int nRow, int nCol, COLORREF cr = CLR_DEFAULT); COLORREF GetItemBkColour(int nRow, int nCol) const; BOOL SetItemFgColour(int nRow, int nCol, COLORREF cr = CLR_DEFAULT); COLORREF GetItemFgColour(int nRow, int nCol) const; BOOL SetItemFont(int nRow, int nCol, const LOGFONT* lf); const LOGFONT* GetItemFont(int nRow, int nCol); BOOL IsItemEditing(int nRow, int nCol); BOOL SetCellType(int nRow, int nCol, CRuntimeClass* pRuntimeClass); BOOL SetCellType(CCellRange Selection, CRuntimeClass* pRuntimeClass); BOOL SetDefaultCellType(CRuntimeClass* pRuntimeClass); /////////////////////////////////////////////////////////////////////////////////// // Operations /////////////////////////////////////////////////////////////////////////////////// public: int InsertColumn(LPCTSTR strHeading, UINT nFormat = DT_CENTER|DT_VCENTER|DT_SINGLELINE, int nColumn = -1); int InsertRow(LPCTSTR strHeading, int nRow = -1); BOOL DeleteColumn(int nColumn); BOOL DeleteRow(int nRow); BOOL DeleteNonFixedRows(); BOOL DeleteAllItems(); void ClearCells(CCellRange Selection); BOOL AutoSizeRow(int nRow, BOOL bResetScroll = TRUE); BOOL AutoSizeColumn(int nCol, UINT nAutoSizeStyle = GVS_DEFAULT, BOOL bResetScroll = TRUE); void AutoSizeRows(); void AutoSizeColumns(UINT nAutoSizeStyle = GVS_DEFAULT); void AutoSize(UINT nAutoSizeStyle = GVS_DEFAULT); void ExpandColumnsToFit(BOOL bExpandFixed = TRUE); void ExpandLastColumn(); void ExpandRowsToFit(BOOL bExpandFixed = TRUE); void ExpandToFit(BOOL bExpandFixed = TRUE); void Refresh(); void AutoFill(); // Fill grid with blank cells void EnsureVisible(CCellID &cell) { EnsureVisible(cell.row, cell.col); } void EnsureVisible(int nRow, int nCol); BOOL IsCellVisible(int nRow, int nCol); BOOL IsCellVisible(CCellID cell); BOOL IsCellEditable(int nRow, int nCol) const; BOOL IsCellEditable(CCellID &cell) const; BOOL IsCellSelected(int nRow, int nCol) const; BOOL IsCellSelected(CCellID &cell) const; // SetRedraw stops/starts redraws on things like changing the # rows/columns // and autosizing, but not for user-intervention such as resizes void SetRedraw(BOOL bAllowDraw, BOOL bResetScrollBars = FALSE); BOOL RedrawCell(int nRow, int nCol, CDC* pDC = NULL); BOOL RedrawCell(const CCellID& cell, CDC* pDC = NULL); BOOL RedrawRow(int row); BOOL RedrawColumn(int col); #ifndef _WIN32_WCE BOOL Save(LPCTSTR filename, TCHAR chSeparator = _T(',')); BOOL Load(LPCTSTR filename, TCHAR chSeparator = _T(',')); #endif /////////////////////////////////////////////////////////////////////////////////// // Cell Ranges /////////////////////////////////////////////////////////////////////////////////// public: CCellRange GetCellRange() const; CCellRange GetSelectedCellRange() const; void SetSelectedRange(const CCellRange& Range, BOOL bForceRepaint = FALSE, BOOL bSelectCells = TRUE); void SetSelectedRange(int nMinRow, int nMinCol, int nMaxRow, int nMaxCol, BOOL bForceRepaint = FALSE, BOOL bSelectCells = TRUE); BOOL IsValid(int nRow, int nCol) const; BOOL IsValid(const CCellID& cell) const; BOOL IsValid(const CCellRange& range) const; /////////////////////////////////////////////////////////////////////////////////// // Clipboard, drag and drop, and cut n' paste operations /////////////////////////////////////////////////////////////////////////////////// #ifndef GRIDCONTROL_NO_CLIPBOARD virtual void CutSelectedText(); virtual COleDataSource* CopyTextFromGrid(); virtual BOOL PasteTextToGrid(CCellID cell, COleDataObject* pDataObject, BOOL bSelectPastedCells=TRUE); #endif #ifndef GRIDCONTROL_NO_DRAGDROP public: virtual void OnBeginDrag(); virtual DROPEFFECT OnDragEnter(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point); virtual DROPEFFECT OnDragOver(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point); virtual void OnDragLeave(); virtual BOOL OnDrop(COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point); #endif #ifndef GRIDCONTROL_NO_CLIPBOARD virtual void OnEditCut(); virtual void OnEditCopy(); virtual void OnEditPaste(); #endif virtual void OnEditSelectAll(); /////////////////////////////////////////////////////////////////////////////////// // Misc. /////////////////////////////////////////////////////////////////////////////////// public: CCellID GetNextItem(CCellID& cell, int nFlags) const; BOOL SortItems(int nCol, BOOL bAscending, LPARAM data = 0); BOOL SortTextItems(int nCol, BOOL bAscending, LPARAM data = 0); BOOL SortItems(PFNLVCOMPARE pfnCompare, int nCol, BOOL bAscending, LPARAM data = 0); void SetCompareFunction(PFNLVCOMPARE pfnCompare); // in-built sort functions static int CALLBACK pfnCellTextCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); static int CALLBACK pfnCellNumericCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); /////////////////////////////////////////////////////////////////////////////////// // Printing /////////////////////////////////////////////////////////////////////////////////// #if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING) public: void Print(CPrintDialog* pPrntDialog = NULL); // EFW - New printing support functions void EnableWysiwygPrinting(BOOL bEnable = TRUE) { m_bWysiwygPrinting = bEnable; } BOOL GetWysiwygPrinting() { return m_bWysiwygPrinting; } void SetShadedPrintOut(BOOL bEnable = TRUE) { m_bShadedPrintOut = bEnable; } BOOL GetShadedPrintOut(void) { return m_bShadedPrintOut; } // Use -1 to have it keep the existing value void SetPrintMarginInfo(int nHeaderHeight, int nFooterHeight, int nLeftMargin, int nRightMargin, int nTopMargin, int nBottomMargin, int nGap); void GetPrintMarginInfo(int &nHeaderHeight, int &nFooterHeight, int &nLeftMargin, int &nRightMargin, int &nTopMargin, int &nBottomMargin, int &nGap); /////////////////////////////////////////////////////////////////////////////////// // Printing overrides for derived classes /////////////////////////////////////////////////////////////////////////////////// public: virtual void OnBeginPrinting(CDC *pDC, CPrintInfo *pInfo); virtual void OnPrint(CDC *pDC, CPrintInfo *pInfo); virtual void OnEndPrinting(CDC *pDC, CPrintInfo *pInfo); #endif // #if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING) // Implementation public: virtual ~CGridCtrl(); protected: BOOL RegisterWindowClass(); BOOL Initialise(); void SetupDefaultCells(); LRESULT SendMessageToParent(int nRow, int nCol, int nMessage) const; LRESULT SendDisplayRequestToParent(GV_DISPINFO* pDisplayInfo) const; LRESULT SendCacheHintToParent(const CCellRange& range) const; BOOL InvalidateCellRect(const int row, const int col); BOOL InvalidateCellRect(const CCellID& cell); BOOL InvalidateCellRect(const CCellRange& cellRange); void EraseBkgnd(CDC* pDC); BOOL GetCellRangeRect(const CCellRange& cellRange, LPRECT lpRect); BOOL SetCell(int nRow, int nCol, CGridCellBase* pCell); int SetMouseMode(int nMode) { int nOldMode = m_MouseMode; m_MouseMode = nMode; return nOldMode; } int GetMouseMode() const { return m_MouseMode; } BOOL MouseOverRowResizeArea(CPoint& point); BOOL MouseOverColumnResizeArea(CPoint& point); CCellID GetTopleftNonFixedCell(BOOL bForceRecalculation = FALSE); CCellRange GetUnobstructedNonFixedCellRange(BOOL bForceRecalculation = FALSE); // LUC CCellRange GetVisibleNonFixedCellRange(LPRECT pRect = NULL, BOOL bForceRecalculation = FALSE); CCellRange GetVisibleFixedCellRange(LPRECT pRect = NULL, BOOL bForceRecalculation = FALSE); BOOL IsVisibleVScroll() { return ( (m_nBarState & GVL_VERT) > 0); } BOOL IsVisibleHScroll() { return ( (m_nBarState & GVL_HORZ) > 0); } void ResetSelectedRange(); void ResetScrollBars(); void EnableScrollBars(int nBar, BOOL bEnable = TRUE); int GetScrollPos32(int nBar, BOOL bGetTrackPos = FALSE); BOOL SetScrollPos32(int nBar, int nPos, BOOL bRedraw = TRUE); BOOL SortTextItems(int nCol, BOOL bAscending, int low, int high); BOOL SortItems(PFNLVCOMPARE pfnCompare, int nCol, BOOL bAscending, LPARAM data, int low, int high); CPoint GetPointClicked(int nRow, int nCol, const CPoint& point); void ValidateAndModifyCellContents(int nRow, int nCol, LPCTSTR strText); // Overrrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CGridCtrl) protected: virtual void PreSubclassWindow(); //}}AFX_VIRTUAL protected: #if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING) // Printing virtual void PrintFixedRowCells(int nStartColumn, int nStopColumn, int& row, CRect& rect, CDC *pDC, BOOL& bFirst); virtual void PrintColumnHeadings(CDC *pDC, CPrintInfo *pInfo); virtual void PrintHeader(CDC *pDC, CPrintInfo *pInfo); virtual void PrintFooter(CDC *pDC, CPrintInfo *pInfo); virtual void PrintRowButtons(CDC *pDC, CPrintInfo* /*pInfo*/); #endif #ifndef GRIDCONTROL_NO_DRAGDROP // Drag n' drop virtual CImageList* CreateDragImage(CPoint *pHotSpot); // no longer necessary #endif // Mouse Clicks virtual void OnFixedColumnClick(CCellID& cell); virtual void OnFixedRowClick(CCellID& cell); // Editing virtual void OnEditCell(int nRow, int nCol, CPoint point, UINT nChar); virtual void OnEndEditCell(int nRow, int nCol, CString str); virtual BOOL ValidateEdit(int nRow, int nCol, LPCTSTR str); virtual void EndEditing(); // Drawing virtual void OnDraw(CDC* pDC); // CGridCellBase Creation and Cleanup virtual CGridCellBase* CreateCell(int nRow, int nCol); virtual void DestroyCell(int nRow, int nCol); // Attributes protected: // General attributes COLORREF m_crFixedTextColour, m_crFixedBkColour; COLORREF m_crGridBkColour, m_crGridLineColour; COLORREF m_crWindowText, m_crWindowColour, m_cr3DFace, // System colours m_crShadow; COLORREF m_crTTipBackClr, m_crTTipTextClr; // Titletip colours - FNA BOOL m_bVirtualMode; LPARAM m_lParam; // lParam for callback GRIDCALLBACK m_pfnCallback; // The callback function int m_nGridLines; BOOL m_bEditable; BOOL m_bModified; BOOL m_bAllowDragAndDrop; BOOL m_bListMode; BOOL m_bSingleRowSelection; BOOL m_bSingleColSelection; BOOL m_bAllowDraw; BOOL m_bEnableSelection; BOOL m_bFixedRowSelection, m_bFixedColumnSelection; BOOL m_bSortOnClick; BOOL m_bHandleTabKey; BOOL m_bDoubleBuffer; BOOL m_bTitleTips; int m_nBarState; BOOL m_bWysiwygPrinting; BOOL m_bHiddenColUnhide, m_bHiddenRowUnhide; BOOL m_bAllowColHide, m_bAllowRowHide; BOOL m_bAutoSizeSkipColHdr; BOOL m_bTrackFocusCell; BOOL m_bFrameFocus; UINT m_nAutoSizeColumnStyle; // Cell size details int m_nRows, m_nFixedRows, m_nCols, m_nFixedCols; // LUC CArray<CCellRange, CCellRange&> m_arMergedCells; CUIntArray m_arRowHeights, m_arColWidths; int m_nVScrollMax, m_nHScrollMax; // Fonts and images CRuntimeClass* m_pRtcDefault; // determines kind of Grid Cell created by default CGridDefaultCell m_cellDefault; // "default" cell. Contains default colours, font etc. CGridDefaultCell m_cellFixedColDef, m_cellFixedRowDef, m_cellFixedRowColDef; CFont m_PrinterFont; // for the printer CImageList* m_pImageList; // Cell data CTypedPtrArray<CObArray, GRID_ROW*> m_RowData; // Mouse operations such as cell selection int m_MouseMode; BOOL m_bLMouseButtonDown, m_bRMouseButtonDown; CPoint m_LeftClickDownPoint, m_LastMousePoint; CCellID m_LeftClickDownCell, m_SelectionStartCell; CCellID m_idCurrentCell, m_idTopLeftCell; INT_PTR m_nTimerID; int m_nTimerInterval; int m_nResizeCaptureRange; BOOL m_bAllowRowResize, m_bAllowColumnResize; int m_nRowsPerWheelNotch; CMap<DWORD,DWORD, CCellID, CCellID&> m_SelectedCellMap, m_PrevSelectedCellMap; #ifndef GRIDCONTROL_NO_TITLETIPS CTitleTip m_TitleTip; // Title tips for cells #endif // Drag and drop CCellID m_LastDragOverCell; #ifndef GRIDCONTROL_NO_DRAGDROP CGridDropTarget m_DropTarget; // OLE Drop target for the grid #endif // Printing information CSize m_CharSize; int m_nPageHeight; CSize m_LogicalPageSize, // Page size in gridctrl units. m_PaperSize; // Page size in device units. // additional properties to support Wysiwyg printing int m_nPageWidth; int m_nPrintColumn; int m_nCurrPrintRow; int m_nNumPages; int m_nPageMultiplier; // sorting int m_bAscending; int m_nSortColumn; PFNLVCOMPARE m_pfnCompare; // EFW - Added to support shaded/unshaded printout. If true, colored // cells will print as-is. If false, all text prints as black on white. BOOL m_bShadedPrintOut; // EFW - Added support for user-definable margins. Top and bottom are in // lines. Left, right, and gap are in characters (avg width is used). int m_nHeaderHeight, m_nFooterHeight, m_nLeftMargin, m_nRightMargin, m_nTopMargin, m_nBottomMargin, m_nGap; protected: void SelectAllCells(); void SelectColumns(CCellID currentCell, BOOL bForceRedraw=FALSE, BOOL bSelectCells=TRUE); void SelectRows(CCellID currentCell, BOOL bForceRedraw=FALSE, BOOL bSelectCells=TRUE); void SelectCells(CCellID currentCell, BOOL bForceRedraw=FALSE, BOOL bSelectCells=TRUE); void OnSelecting(const CCellID& currentCell); // Generated message map functions //{{AFX_MSG(CGridCtrl) afx_msg void OnPaint(); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg UINT OnGetDlgCode(); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnRButtonDblClk(UINT nFlags, CPoint point); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnUpdateEditSelectAll(CCmdUI* pCmdUI); //}}AFX_MSG #ifndef _WIN32_WCE_NO_CURSOR afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); #endif #ifndef _WIN32_WCE afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); // EFW - Added afx_msg void OnSysColorChange(); #endif #ifndef _WIN32_WCE_NO_CURSOR afx_msg void OnCaptureChanged(CWnd *pWnd); #endif #ifndef GRIDCONTROL_NO_CLIPBOARD afx_msg void OnUpdateEditCopy(CCmdUI* pCmdUI); afx_msg void OnUpdateEditCut(CCmdUI* pCmdUI); afx_msg void OnUpdateEditPaste(CCmdUI* pCmdUI); #endif #if (_MFC_VER >= 0x0421) || (_WIN32_WCE >= 210) afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); #endif #if !defined(_WIN32_WCE) && (_MFC_VER >= 0x0421) afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); #endif afx_msg LRESULT OnSetFont(WPARAM hFont, LPARAM lParam); afx_msg LRESULT OnGetFont(WPARAM hFont, LPARAM lParam); afx_msg LRESULT OnImeChar(WPARAM wCharCode, LPARAM lParam); afx_msg void OnEndInPlaceEdit(NMHDR* pNMHDR, LRESULT* pResult); DECLARE_MESSAGE_MAP() enum eMouseModes { MOUSE_NOTHING, MOUSE_SELECT_ALL, MOUSE_SELECT_COL, MOUSE_SELECT_ROW, MOUSE_SELECT_CELLS, MOUSE_SCROLLING_CELLS, MOUSE_OVER_ROW_DIVIDE, MOUSE_SIZING_ROW, MOUSE_OVER_COL_DIVIDE, MOUSE_SIZING_COL, MOUSE_PREPARE_EDIT, #ifndef GRIDCONTROL_NO_DRAGDROP MOUSE_PREPARE_DRAG, MOUSE_DRAGGING #endif }; // for sort in virtual mode, and column order, save and load layer public: typedef std::vector<int> intlist; void Reorder(int From, int To); void SetVirtualCompare(PVIRTUALCOMPARE VirtualCompare) { m_pfnVirtualCompare = VirtualCompare;} int m_CurCol; void AllowReorderColumn(bool b=true) { m_AllowReorderColumn = b;} void EnableDragRowMode(bool b=true) { m_bDragRowMode = b; if(b) EnableDragAndDrop(); } // to change row order int GetLayer(int** pLayer); // gives back the number of ints of the area (do not forget to delete *pLayer) void SetLayer(int* pLayer); // coming from a previous GetLayer (ignored if not same number of column, or the same revision number) void ForceQuitFocusOnTab(bool b=true) { m_QuitFocusOnTab = b;} // use only if GetParent() is a CDialog void AllowSelectRowInFixedCol(bool b=true) { m_AllowSelectRowInFixedCol = b;} // // allow acces? intlist m_arRowOrder, m_arColOrder; static CGridCtrl* m_This; protected: virtual void AddSubVirtualRow(int Num, int Nb); bool m_bDragRowMode; int m_CurRow; private: void ResetVirtualOrder(); PVIRTUALCOMPARE m_pfnVirtualCompare; static bool NotVirtualCompare(int c1, int c2); bool m_InDestructor; bool m_AllowReorderColumn; bool m_QuitFocusOnTab; bool m_AllowSelectRowInFixedCol; }; // Returns the default cell implementation for the given grid region inline CGridCellBase* CGridCtrl::GetDefaultCell(BOOL bFixedRow, BOOL bFixedCol) const { if (bFixedRow && bFixedCol) return (CGridCellBase*) &m_cellFixedRowColDef; if (bFixedRow) return (CGridCellBase*) &m_cellFixedRowDef; if (bFixedCol) return (CGridCellBase*) &m_cellFixedColDef; return (CGridCellBase*) &m_cellDefault; } inline CGridCellBase* CGridCtrl::GetCell(int nRow, int nCol) const { if (nRow < 0 || nRow >= m_nRows || nCol < 0 || nCol >= m_nCols) return NULL; if (GetVirtualMode()) { CGridCellBase* pCell = GetDefaultCell(nRow < m_nFixedRows, nCol < m_nFixedCols); static GV_DISPINFO gvdi; gvdi.item.row = nRow; gvdi.item.col = nCol; gvdi.item.mask = 0xFFFFFFFF; gvdi.item.nState = 0; gvdi.item.nFormat = pCell->GetFormat(); gvdi.item.iImage = pCell->GetImage(); gvdi.item.crBkClr = pCell->GetBackClr(); gvdi.item.crFgClr = pCell->GetTextClr(); gvdi.item.lParam = pCell->GetData(); memcpy(&gvdi.item.lfFont, pCell->GetFont(), sizeof(LOGFONT)); gvdi.item.nMargin = pCell->GetMargin(); gvdi.item.strText.Empty(); // Fix the state bits if (IsCellSelected(nRow, nCol)) gvdi.item.nState |= GVIS_SELECTED; if (nRow < GetFixedRowCount()) gvdi.item.nState |= (GVIS_FIXED | GVIS_FIXEDROW); if (nCol < GetFixedColumnCount()) gvdi.item.nState |= (GVIS_FIXED | GVIS_FIXEDCOL); if (GetFocusCell() == CCellID(nRow, nCol)) gvdi.item.nState |= GVIS_FOCUSED; if(!m_InDestructor) { gvdi.item.row = m_arRowOrder[nRow]; gvdi.item.col = m_arColOrder[nCol]; if (m_pfnCallback) m_pfnCallback(&gvdi, m_lParam); else SendDisplayRequestToParent(&gvdi); gvdi.item.row = nRow; gvdi.item.col = nCol; } static CGridCell cell; cell.SetState(gvdi.item.nState); cell.SetFormat(gvdi.item.nFormat); cell.SetImage(gvdi.item.iImage); cell.SetBackClr(gvdi.item.crBkClr); cell.SetTextClr(gvdi.item.crFgClr); cell.SetData(gvdi.item.lParam); cell.SetFont(&(gvdi.item.lfFont)); cell.SetMargin(gvdi.item.nMargin); cell.SetText(gvdi.item.strText); cell.SetGrid((CGridCtrl*)this); return (CGridCellBase*) &cell; } GRID_ROW* pRow = m_RowData[nRow]; if (!pRow) return NULL; return pRow->GetAt(m_arColOrder[nCol]); } inline BOOL CGridCtrl::SetCell(int nRow, int nCol, CGridCellBase* pCell) { if (GetVirtualMode()) return FALSE; if (nRow < 0 || nRow >= m_nRows || nCol < 0 || nCol >= m_nCols) return FALSE; GRID_ROW* pRow = m_RowData[nRow]; if (!pRow) return FALSE; pCell->SetCoords( nRow, nCol); pRow->SetAt(nCol, pCell); return TRUE; } ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_GRIDCTRL_H__519FA702_722C_11D1_ABBA_00A0243D1382__INCLUDED_)
cbe0c46480f8e033ed1b84c63cef9daed3805ab5
cc25bf4e9813ca7cb99b8474bb02bb7802e43e65
/aufgabe3.cpp
cf03151de89ad1a650e9db5506553b447d04b329
[]
no_license
buecktobias/PAD2
71cd583838cf6091feb696db7f8720f6960a4b96
5def756a969c6ad820cd5b450dd04e8fd876d0a9
refs/heads/main
2023-04-12T08:45:16.413592
2021-05-05T19:20:14
2021-05-05T19:20:14
363,633,910
0
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
// // Created by tobias on 05.05.21. // #include <iostream> #include <cmath> #include "aufgabe3.h" void start3(){ int n; std::cout << "Wie viele Nummern willst du eingeben?: "; std::cin >> n; std::cout << std::endl; std::cout << "Gebe die Nummern ein! "; std::vector<double> numbers; for(int i = 0; i < n; i++){ double newNumber; std::cin >> newNumber; numbers.push_back(newNumber); } std::cout << "Der Median ist: " << median(numbers) << std::endl; } double median(std::vector<double> numbers){ std::sort(numbers.begin(), numbers.end()); if(numbers.size() % 2 == 0){ int lowerIndex = std::round((numbers.size() / 2) - 1); int upperIndex = lowerIndex + 1 ; return (numbers[lowerIndex] + numbers[upperIndex]) / 2.0; }else{ int middleElement = std::ceil(numbers.size() / 2); return numbers[middleElement]; } }
a522d2fc45e6e405c775604c639147b7ae1e52b7
a83ea575ef83bcb7a5db6adfc55b64a68a32d5d6
/Svn/Server/db/ClientManagerEventFlag.cpp
ebcfe24d4f2f3714b3b767e6774535b37dd6d2fd
[]
no_license
divinner/Astra2-Files
1290abbd04082a35a4ca52a442d481328a5c1a7b
7e4b50af4601ae7358039d700b45ccde25220219
refs/heads/master
2022-11-11T23:51:57.666395
2020-07-06T13:44:25
2020-07-06T13:44:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,302
cpp
#include "stdafx.h" #include "ClientManager.h" #include "Main.h" #include "Config.h" #include "DBManager.h" #include "QID.h" void CClientManager::LoadEventFlag() { char szQuery[1024]; snprintf(szQuery, sizeof(szQuery), "SELECT szName, lValue FROM quest%s WHERE dwPID = 0", GetTablePostfix()); std::unique_ptr<SQLMsg> pMsg(CDBManager::instance().DirectQuery(szQuery)); SQLResult* pRes = pMsg->Get(); if (pRes && pRes->uiNumRows) // @correction023 { MYSQL_ROW row; while ((row = mysql_fetch_row(pRes->pSQLResult))) { TPacketSetEventFlag p; strlcpy(p.szFlagName, row[0], sizeof(p.szFlagName)); str_to_number(p.lValue, row[1]); sys_log(0, "EventFlag Load %s %d", p.szFlagName, p.lValue); m_map_lEventFlag.insert(std::make_pair(std::string(p.szFlagName), p.lValue)); ForwardPacket(HEADER_DG_SET_EVENT_FLAG, &p, sizeof(TPacketSetEventFlag)); } } } void CClientManager::SetEventFlag(TPacketSetEventFlag* p) { ForwardPacket(HEADER_DG_SET_EVENT_FLAG, p, sizeof(TPacketSetEventFlag)); bool bChanged = false; decltype(m_map_lEventFlag.begin()) it = m_map_lEventFlag.find(p->szFlagName); if (it == m_map_lEventFlag.end()) { bChanged = true; m_map_lEventFlag.insert(std::make_pair(std::string(p->szFlagName), p->lValue)); } else if (it->second != p->lValue) { bChanged = true; it->second = p->lValue; } if (bChanged) { char szQuery[1024]; snprintf(szQuery, sizeof(szQuery), "REPLACE INTO quest%s (dwPID, szName, szState, lValue) VALUES(0, '%s', '', %d)", GetTablePostfix(), p->szFlagName, p->lValue); szQuery[1023] = '\0'; CDBManager::instance().AsyncQuery(szQuery); sys_log(0, "HEADER_GD_SET_EVENT_FLAG : Changed CClientmanager::SetEventFlag(%s %d) ", p->szFlagName, p->lValue); return; } sys_log(0, "HEADER_GD_SET_EVENT_FLAG : No Changed CClientmanager::SetEventFlag(%s %d) ", p->szFlagName, p->lValue); } void CClientManager::SendEventFlagsOnSetup(CPeer* peer) { decltype(m_map_lEventFlag.begin()) it; for (it = m_map_lEventFlag.begin(); it != m_map_lEventFlag.end(); ++it) { TPacketSetEventFlag p; strlcpy(p.szFlagName, it->first.c_str(), sizeof(p.szFlagName)); p.lValue = it->second; peer->EncodeHeader(HEADER_DG_SET_EVENT_FLAG, 0, sizeof(TPacketSetEventFlag)); peer->Encode(&p, sizeof(TPacketSetEventFlag)); } }
61af0136450606217a667d3ff474a7927254c791
b4e1ae98329725a72b10487682decd7d6e69b4c3
/highest_rating/highest_rating.cpp
eb785b953d73e8b00dfc139fbd953b9206ca69cf
[]
no_license
bhavya1224/Its-all-code
2105d543d75f8514b977d76651a8c9bfbd82bf89
be3de9edb3c23e7842466ee15bb5b36d6b7e4244
refs/heads/master
2022-09-07T00:45:22.170484
2020-05-29T11:23:22
2020-05-29T11:23:22
266,622,557
0
0
null
null
null
null
UTF-8
C++
false
false
1,127
cpp
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <CodeBlocks_project_file> <FileVersion major="1" minor="6" /> <Project> <Option title="highest_rating" /> <Option pch_mode="2" /> <Option compiler="gcc" /> <Build> <Target title="Debug"> <Option output="bin/Debug/highest_rating" prefix_auto="1" extension_auto="1" /> <Option object_output="obj/Debug/" /> <Option type="1" /> <Option compiler="gcc" /> <Compiler> <Add option="-g" /> </Compiler> </Target> <Target title="Release"> <Option output="bin/Release/highest_rating" prefix_auto="1" extension_auto="1" /> <Option object_output="obj/Release/" /> <Option type="1" /> <Option compiler="gcc" /> <Compiler> <Add option="-O2" /> </Compiler> <Linker> <Add option="-s" /> </Linker> </Target> </Build> <Compiler> <Add option="-Wall" /> <Add option="-fexceptions" /> </Compiler> <Unit filename="main.cpp" /> <Extensions> <code_completion /> <envvars /> <debugger /> <lib_finder disable_auto="1" /> </Extensions> </Project> </CodeBlocks_project_file>
729e1780af48747a6a4c9011328944410e2aff03
56ed989ec33ee6012e1a2771d5d4fd92383bd457
/app/src/main/jni/JniTest.cpp
abefd67726fb07391e27715c1a7f9210dcf7a993
[]
no_license
willhua/OpenCVStudy
19cd713b25bcb89cecb24f6403ed01d660dd1c9c
7ff1994451461fa3346ac91ddb5f3a42ba389bfa
refs/heads/master
2021-01-23T00:24:45.977647
2017-04-13T07:00:33
2017-04-13T07:00:33
84,638,753
0
0
null
null
null
null
UTF-8
C++
false
false
2,119
cpp
#include <jni.h> #include <stdio.h> #include <stdlib.h> #include <android/log.h> #include <time.h> #include <sys/system_properties.h> #ifndef JNI_TEST_H #define JNI_TEST_H #define LOG(...) __android_log_print(ANDROID_LOG_DEBUG, "lyhopencvn", __VA_ARGS__) #ifdef __cplusplus extern "C" { #endif void printfTime() { time_t now; struct tm *timenow; time(&now); timenow = localtime(&now); LOG("current time is: %s\n", asctime(timenow) ); } JNIEXPORT void JNICALL Java_com_willhua_opencvstudy_MainActivity_floatTest( JNIEnv *env, jclass obj) { char value[PROP_VALUE_MAX]; __system_property_get("ro.product.model", value); LOG("model:%s" , value); FILE *file = fopen("/data/data/com.willhua.opencvstudy/myfile.txt", "w+"); if(NULL == file) { LOG("fopen return null"); }else { LOG("fopen not return null"); } int fputs_size = fputs("fputs write\n", file); int size_fw = fwrite("frwite", sizeof(char), 5, file); char buffer[50]; fflush(file); fseek(file, -8, SEEK_CUR); //fclose(file); //file = fopen("/data/data/com.willhua.opencvstudy/myfile.txt", "r+t"); size_t size_fread = fread(buffer, sizeof(char), 6, file); LOG("fputs size:%d %d %d", fputs_size, size_fw, size_fread); int len = 10000000; int *ints = (int*)malloc(sizeof(int) * len); for(int i= 0;i<len;++i){ ints[i] = i%255 + 1; } ////// len-=4; printfTime(); for(int i = 0; i < len; i+=4) { ints[i] = (ints[len - 1 - i] / ints[i] )<<8; ints[i+1] = (ints[len - 2 - i] / ints[i+1] )<<8; ints[i+2] = (ints[len - 3 - i] / ints[i+2] )<<8; ints[i+3] = (ints[len - 4 - i] / ints[i+3] )<<8; } printfTime(); ////// float fff=255; float *floats=(float *)malloc(sizeof(int) * len); for(int i= 0;i<len;++i){ floats[i] = (i%255)/fff; } ////// printfTime(); for(int i = 0; i < len; ++i) { floats[i] = ints[i] / floats[i]; } printfTime(); ////// delete [] ints; delete [] floats; } #ifdef __cplusplus } #endif #endif //JNI_TEST_H
a17f449e48fe76a0c18dfdd4f3068ba57da3bd1f
576c5250b6be12faf9cab6fba17b10848cbbd718
/Joes_SDL_Framework/XDL_Keyboard.cpp
99b659252c76456fee2eecf909b9329fe51bd0c5
[]
no_license
JoeBentley63/XDL
6616769161cab1f1d0acfc78e987426424d9d6ec
a4146d288cc9f5222c1e4c2ea8cd2f6fc0799a0a
refs/heads/master
2021-05-31T07:25:23.235533
2016-01-24T12:53:26
2016-01-24T12:53:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
cpp
//Singleton to handle keyboard input. Again, to avoid polling for keyboard input all over our code. #include "XDL_Keyboard.h" XDL_Keyboard* XDL_Keyboard::_me; XDL_Keyboard::XDL_Keyboard(void) { } XDL_Keyboard::~XDL_Keyboard(void) { } XDL_Keyboard* XDL_Keyboard::GetInstance() { if(_me == NULL) { _me = new XDL_Keyboard(); } return _me; } /*void XDL_Keyboard::Update() { Originally this had an update that would be called in XDL_Game once a frame to keep track of keys, but SDL2 has a getKeyboardState function that simplifys everything }*/ bool XDL_Keyboard::IsKeyDown(int _key) { SDL_PumpEvents();//needs to be called before SDL_GetKeyBoardState keystate = SDL_GetKeyboardState(NULL);//returns all keys down. Passing in NULL does it for all keys. return keystate[_key];//if our keys is down, return true/false. } bool XDL_Keyboard::IsKeyUp(int _key) { if(IsKeyDown(_key) == true)//if our key is down, return false, else true. Save us repeating code,just reuse function. { return false; } return true; }
37e4fe738a13a0fa584a65d8ac093b81051b4b29
134c468c1d362bf449a26ba62e214cf82aeb533f
/PAT (Basic Level) Practice (中文)/1036 跟奥巴马一起编程.cpp
bc6823acbb10da9e6866474e3e8bd694371cf4fd
[]
no_license
JunJie957/PAT-solutions
da5685276c7c718a3bd283d7792a752b7d0cb341
42df5d7204c585c60ba5b940ded196b95a230694
refs/heads/master
2023-01-21T15:23:34.937193
2020-12-03T07:59:59
2020-12-03T07:59:59
261,340,395
0
0
null
null
null
null
UTF-8
C++
false
false
394
cpp
#include <iostream> using namespace std; int main() { int n; char c; scanf("%d %c", &n, &c); for (int i = 0; i < n; ++i) printf("%c", c); printf("\n"); for (int i = 0; i < (n + 1) / 2 - 2; ++i) { printf("%c", c); for (int j = 1; j < n - 1; ++j) printf(" "); printf("%c\n", c); } for (int i = 0; i < n; ++i) printf("%c", c); return 0; }
324a8769aa29e579fa0d15eae2576437e620bbd1
3efc50ba20499cc9948473ee9ed2ccfce257d79a
/data/code-jam/files/2437488_Simeon_2749486_0_extracted_second Stupid Small.cpp
763d497fc51af6dc973c9384c61191f5c69149c5
[]
no_license
arthurherbout/crypto_code_detection
7e10ed03238278690d2d9acaa90fab73e52bab86
3c9ff8a4b2e4d341a069956a6259bf9f731adfc0
refs/heads/master
2020-07-29T15:34:31.380731
2019-12-20T13:52:39
2019-12-20T13:52:39
209,857,592
9
4
null
2019-12-20T13:52:42
2019-09-20T18:35:35
C
UTF-8
C++
false
false
1,018
cpp
#include <fstream> using namespace std; typedef long long lld; bool MoveUpDown (lld num) { if (num<0) { printf("NS"); } else if (num>0) { printf("SN"); } } bool MoveLeftRight(lld num) { if (num<0) { printf("EW"); } else if (num>0) { printf("WE"); } else { return false; } return true; } int main () { freopen("input.txt","r",stdin); freopen ("output.txt","w",stdout); lld i,j,ii,jj,ind; lld tests,t; lld x,y,posx,posy; scanf("%I64d",&tests); for (t=1;t<=tests;t++) { scanf("%I64d %I64d",&x,&y); posx=0; posy=0; printf("Case #%I64d: ",t); while (MoveUpDown(y-posy)) { if (y-posy>0) y--; else y++; } while (MoveLeftRight(x-posx)) { if (x-posx>0) x--; else x++; } printf("\n"); } }
42fff4463630e6fdb2cd93d46040231961aa23fb
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/chrome/browser/search/most_visited_iframe_source.cc
d7641c8a84acfbbbe6040d952da8ff5f6e63545d
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
3,895
cc
// 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. #include "chrome/browser/search/most_visited_iframe_source.h" #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "build/build_config.h" #include "chrome/browser/search/local_files_ntp_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/grit/browser_resources.h" #include "url/gurl.h" namespace { // Single-iframe version, used by the local NTP and the Google remote NTP. const char kSingleHTMLPath[] = "/single.html"; const char kSingleCSSPath[] = "/single.css"; const char kSingleJSPath[] = "/single.js"; // Multi-iframe version, used by third party remote NTPs. const char kTitleHTMLPath[] = "/title.html"; const char kTitleCSSPath[] = "/title.css"; const char kTitleJSPath[] = "/title.js"; const char kThumbnailHTMLPath[] = "/thumbnail.html"; const char kThumbnailCSSPath[] = "/thumbnail.css"; const char kThumbnailJSPath[] = "/thumbnail.js"; const char kUtilJSPath[] = "/util.js"; const char kCommonCSSPath[] = "/common.css"; } // namespace MostVisitedIframeSource::MostVisitedIframeSource() = default; MostVisitedIframeSource::~MostVisitedIframeSource() = default; std::string MostVisitedIframeSource::GetSource() const { return chrome::kChromeSearchMostVisitedHost; } void MostVisitedIframeSource::StartDataRequest( const std::string& path_and_query, const content::ResourceRequestInfo::WebContentsGetter& wc_getter, const content::URLDataSource::GotDataCallback& callback) { GURL url(chrome::kChromeSearchMostVisitedUrl + path_and_query); std::string path(url.path()); #if !defined(GOOGLE_CHROME_BUILD) base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kLocalNtpReload)) { std::string rel_path = "most_visited_" + path.substr(1); if (path == kSingleJSPath) { std::string origin; if (!GetOrigin(wc_getter, &origin)) { callback.Run(nullptr); return; } local_ntp::SendLocalFileResourceWithOrigin(rel_path, origin, callback); } else { local_ntp::SendLocalFileResource(rel_path, callback); } return; } #endif if (path == kSingleHTMLPath) { SendResource(IDR_MOST_VISITED_SINGLE_HTML, callback); } else if (path == kSingleCSSPath) { SendResource(IDR_MOST_VISITED_SINGLE_CSS, callback); } else if (path == kSingleJSPath) { SendJSWithOrigin(IDR_MOST_VISITED_SINGLE_JS, wc_getter, callback); } else if (path == kTitleHTMLPath) { SendResource(IDR_MOST_VISITED_TITLE_HTML, callback); } else if (path == kTitleCSSPath) { SendResource(IDR_MOST_VISITED_TITLE_CSS, callback); } else if (path == kTitleJSPath) { SendResource(IDR_MOST_VISITED_TITLE_JS, callback); } else if (path == kThumbnailHTMLPath) { SendResource(IDR_MOST_VISITED_THUMBNAIL_HTML, callback); } else if (path == kThumbnailCSSPath) { SendResource(IDR_MOST_VISITED_THUMBNAIL_CSS, callback); } else if (path == kThumbnailJSPath) { SendJSWithOrigin(IDR_MOST_VISITED_THUMBNAIL_JS, wc_getter, callback); } else if (path == kUtilJSPath) { SendJSWithOrigin(IDR_MOST_VISITED_UTIL_JS, wc_getter, callback); } else if (path == kCommonCSSPath) { SendResource(IDR_MOST_VISITED_IFRAME_CSS, callback); } else { callback.Run(nullptr); } } bool MostVisitedIframeSource::ServesPath(const std::string& path) const { return path == kSingleHTMLPath || path == kSingleCSSPath || path == kSingleJSPath || path == kTitleHTMLPath || path == kTitleCSSPath || path == kTitleJSPath || path == kThumbnailHTMLPath || path == kThumbnailCSSPath || path == kThumbnailJSPath || path == kUtilJSPath || path == kCommonCSSPath; }
14c919813d9a293475144b60ac1baa93ab8340dd
84929a07d0c2d121cddc452e0a428f91f2ddb14d
/Saída de dados/quest.cpp
2822d35e20d55bb41308cabb07e4f47d2910c5a6
[]
no_license
JoseMateusss/Logica-de-programacao-com-Cpp
6c165aeac4a4882b6ca9eef2968ee84ec83256e9
ed253a63cc813430e14fd131d89ab140f789e922
refs/heads/master
2020-04-25T13:30:27.988228
2019-03-21T10:58:28
2019-03-21T10:58:28
172,811,620
1
0
null
null
null
null
ISO-8859-1
C++
false
false
640
cpp
//primeiro passo é fazer as importaões das bibliotecas do C++, que serão utilizadas. Algumas são obrigatórias, como as duas primeiras. #include <iostream> #include <cstdlib> #include <string> using namespace std; int main () { //Faça um progrma que exiba a o nome dos meses do ano em uma única linha". cout << "Janeiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro, "; cout << "fevereiro" <<endl; system("pause"); return 0; }
41f9a03f12d7b45211e49b0fc9441f112778cf1c
b643341b408b090e9f83e21713e14fa8b7508a80
/Source/artoolkit6-dependency/include/AR6/ARController.h
10e70f309823b73eed518d6f843e04a5b4672e64
[]
no_license
ThorstenBux/artoolkit6-calibration-android
a911fdf15efd00dbba2e95f2ae654262ced9c403
f19b3a707bb7ceef37eccb54ebd15205f1637954
refs/heads/master
2021-07-11T12:06:13.662950
2017-10-13T09:15:34
2017-10-13T09:15:34
105,212,852
1
2
null
2017-09-29T00:44:32
2017-09-29T00:44:31
null
UTF-8
C++
false
false
18,287
h
/* * ARController.h * ARToolKit6 * * A C++ class encapsulating core controller functionality of ARToolKit. * * This file is part of ARToolKit. * * ARToolKit 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 3 of the License, or * (at your option) any later version. * * ARToolKit 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 ARToolKit. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, and to * copy and distribute the resulting executable under terms of your choice, * provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module * which is neither derived from nor based on this library. If you modify this * library, you may extend this exception to your version of the library, but you * are not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. * * Copyright 2015-2016 Daqri, LLC. * Copyright 2010-2015 ARToolworks, Inc. * * Author(s): Philip Lamb, Julian Looser. * */ #ifndef __AR6_ARController_h__ #define __AR6_ARController_h__ #include <AR6/Platform.h> #include <AR6/ARVideoSource.h> #include <AR6/ARTracker2D.h> #include <AR6/ARTrackable.h> #include <AR6/ARTrackable2D.h> #include <AR6/ARTrackerSquare.h> #include <AR6/ARTrackableSquare.h> #include <AR6/ARTrackableMultiSquare.h> #if USE_INSTANTON # include <AR6/ARTrackerInstantOn.h> # include <AR6/ARTrackableInstantOn.h> #endif #include <AR6/ARView.h> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #if !defined(_WINRT) # include <pthread.h> #else # define pthread_mutex_t CRITICAL_SECTION # define pthread_mutex_init(pm, a) InitializeCriticalSectionEx(pm, 4000, CRITICAL_SECTION_NO_DEBUG_INFO) # define pthread_mutex_lock(pm) EnterCriticalSection(pm) # define pthread_mutex_unlock(pm) LeaveCriticalSection(pm) # define pthread_mutex_destroy(pm) DeleteCriticalSection(pm) #endif /** * Wrapper for ARToolKit functionality. This class handles ARToolKit initialisation, updates, * and cleanup. It maintains a collection of markers, providing methods to add and remove them. */ class ARController { private: #pragma mark Private types and instance variables // ------------------------------------------------------------------------------ // Private types and instance variables. // ------------------------------------------------------------------------------ enum class State { NOTHING_INITIALISED, ///< No initialisation yet and no resources allocated. BASE_INITIALISED, ///< Marker management initialised, markers can be added. WAITING_FOR_VIDEO, ///< Waiting for video source to become ready. DETECTION_RUNNING ///< Video running, additional initialisation occurred, marker detection running. }; State state; ///< Current state of operation, progress through initialisation bool stateWaitingMessageLogged; char* versionString; ///< Pointer to ARToolKit version string. ARVideoSource *m_videoSources[2]; ///< ARVideoSource(s) providing video frames for tracking int m_videoSourceCount; //bool m_videoSourceIsStereo; ARdouble m_transL2R[3][4]; // Virtual environment parameters. ARdouble m_projectionNearPlane; ///< Near plane distance for projection matrix calculation. ARdouble m_projectionFarPlane; ///< Far plane distance for projection matrix calculation. ARdouble m_projectionMatrix0[16]; ///< OpenGL style projection matrix computed from camera parameters. ARdouble m_projectionMatrix1[16]; ///< OpenGL style projection matrix computed from camera parameters. bool m_projectionMatrixSet; ///< True once the projection matrix has been computed, which requires an open video source. std::vector<ARTrackable *> m_trackables; ///< List of trackables. AR2VideoTimestampT m_updateFrameStamps[2]; AR2VideoTimestampT m_getFrameTextureFrameStamps[2]; // 2D tracking. bool m_do2DTracking; std::unique_ptr<ARTracker2D> m_2DTracker; // Square tracking. bool m_doSquareTracking; std::unique_ptr<ARTrackerSquare> m_squareTracker; #if USE_INSTANTON // InstantOn tracking. bool m_doInstantOnTracking; std::unique_ptr<ARTrackerInstantOn> m_instantOnTracker; #endif int m_error; // Display frame. ARView *m_arViews[2]; #pragma mark Private methods. // ------------------------------------------------------------------------------ // Private methods. // ------------------------------------------------------------------------------ // // Internal marker management. // /** * Adds a trackable to the collection. * @param trackable The trackable to add, typically created by ARTrackable::newWithConfig(). * @return true if the trackable was added successfully, otherwise false. */ bool addTrackable(ARTrackable* trackable); /** * Removes the specified trackable. * @param trackable The trackable to remove * @return true if the trackable was removed, false if an error occurred. */ bool removeTrackable(ARTrackable* trackable); public: #pragma mark Public API // ------------------------------------------------------------------------------ // Public API // ------------------------------------------------------------------------------ /** * Constructor. */ ARController(); /** * Destructor. */ ~ARController(); public: /** * Returns a pointer to a C string containing the ARToolKit version, such as "4.5.1". * The string persists as long as the ARController instance. The caller is not responsible for disposing of the returned pointer. * @return The ARToolKit version */ const char* getARToolKitVersion(); void setError(int error); int getError(); /** * Start trackable management so trackables can be added and removed. * After this call, trackables can be added and removed, any time up until shutdown() is called. * @param patternSize For any square template (pattern) markers, the number of rows and columns in the template. * @param patternCountMax For any square template (pattern) markers, the maximum number of markers that may be loaded for a single matching pass. Must be > 0. * @return true if initialisation was OK, false if an error occured. */ bool initialiseBase(const int patternSize = AR_PATT_SIZE1, const int patternCountMax = AR_PATT_NUM_MAX); ARTracker2D& get2DTracker(); ARTrackerSquare& getSquareTracker(); #if USE_INSTANTON ARTrackerInstantOn& getInstantOnTracker(); #endif void setProjectionNearPlane(const ARdouble projectionNearPlane); void setProjectionFarPlane(const ARdouble projectionFarPlane); ARdouble projectionNearPlane(void); ARdouble projectionFarPlane(void); /** * Start video capture and marker detection. (AR/NFT initialisation will begin on a subsequent call to update().) * @param vconf Video configuration string. * @param cparaName Camera parameters filename, or NULL if camera parameters file not being used. * @param cparaBuff A byte-buffer containing contents of a camera parameters file, or NULL if a camera parameters file is being used. * @param cparaBuffLen Length (in bytes) of cparaBuffLen, or 0 if a camera parameters file is being used. * @return true if video capture and marker detection was started, otherwise false. */ bool startRunning(const char* vconf, const char* cparaName, const char* cparaBuff, const long cparaBuffLen); /** * Start stereo video capture and marker detection. (AR/NFT initialisation will begin on a subsequent call to update().) * @param vconfL Video configuration string for the "left" video source. * @param cparaNameL Camera parameters filename for the "left" video source, or NULL if camera parameters file not being used. * @param cparaBuffL A byte-buffer containing contents of a camera parameters file for the "left" video source, or NULL if a camera parameters file is being used. * @param cparaBuffLenL Length (in bytes) of cparaBuffLenL, or 0 if a camera parameters file is being used. * @param vconfR Video configuration string for the "right" video source. * @param cparaNameR Camera parameters filename for the "right" video source, or NULL if camera parameters file not being used. * @param cparaBuffR A byte-buffer containing contents of a camera parameters file for the "right" video source, or NULL if a camera parameters file is being used. * @param cparaBuffLenR Length (in bytes) of cparaBuffLenR, or 0 if a camera parameters file is being used. * @param transL2RName Stereo calibration filename, or NULL if stereo calibration file not being used. * @param transL2RBuff A byte-buffer containing contents of a stereo calibration file, or NULL if a stereo calibration file is being used. * @param transL2RBuffLen Length (in bytes) of transL2RBuff, or 0 if a stereo calibration file is being used. * @return true if video capture and marker detection was started, otherwise false. */ bool startRunningStereo(const char* vconfL, const char* cparaNameL, const char* cparaBuffL, const long cparaBuffLenL, const char* vconfR, const char* cparaNameR, const char* cparaBuffR, const long cparaBuffLenR, const char* transL2RName, const char* transL2RBuff, const long transL2RBuffLen); #if TARGET_PLATFORM_ANDROID jint androidVideoPushInit(JNIEnv *env, jobject obj, jint videoSourceIndex, jint width, jint height, const char *pixelFormat, jint camera_index, jint camera_face); jint androidVideoPush1(JNIEnv *env, jobject obj, jint videoSourceIndex, jbyteArray buf, jint bufSize); jint androidVideoPush2(JNIEnv *env, jobject obj, jint videoSourceIndex, jobject buf0, jint buf0PixelStride, jint buf0RowStride, jobject buf1, jint buf1PixelStride, jint buf1RowStride, jobject buf2, jint buf2PixelStride, jint buf2RowStride, jobject buf3, jint buf3PixelStride, jint buf3RowStride); jint androidVideoPushFinal(JNIEnv *env, jobject obj, jint videoSourceIndex); #endif /** * Reports width, height and pixel format of a video source. * To retrieve the size (in bytes) of each pixel, use arUtilGetPixelSize(*pixelFormat); * To get a C-string with the name of the pixel format, use arUtilGetPixelFormatName(*pixelFormat); * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. * @param width Pointer to an int which will be filled with the width (in pixels) of the video frame, or NULL if this information is not required. * @param height Pointer to an int which will be filled with the height (in pixels) of the video frame, or NULL if this information is not required. * @param pixelFormat Pointer to an AR_PIXEL_FORMAT which will be filled with the pixel format of the video frame, or NULL if this information is not required. * @return true if the video source(s) is/are open and returning frames, otherwise false. */ bool videoParameters(const int videoSourceIndex, int *width, int *height, AR_PIXEL_FORMAT *pixelFormat); /** * Returns true if video capture and marker detection is running. * @return true if the video source(s) is/are open and returning frames, otherwise false. */ bool isRunning(); /** * Video capture and marker detection stops, but markers are still valid and can be configured. * @return true if video capture and marker detection was stopped, otherwise false. */ bool stopRunning(); /** * Stop, if running. Remove all markers, clean up all memory. * Starting again from this state requires initialiseBase() to be called again. * @return true if shutdown was successful, otherwise false */ bool shutdown(); /** * Populates the provided array with the ARToolKit projection matrix. The projection matrix is computed * once the video source has been opened, and camera parameters become available. If this method is called * before this happens, then the passed array is untouched and the method will return false. * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. * @param proj Array to populate with OpenGL compatible projection matrix * @return true if the projection matrix has been computed, otherwise false */ bool getProjectionMatrix(const int videoSourceIndex, ARdouble proj[16]); /** * Adds a trackable as specified in the given configuration string. The format of the string can be * one of: * - 2D image target: "2d;target_image_pathname;image_height", e.g. "2d;gibraltar.jpg;160.9" * - Square marker from pattern file: "square;pattern_file;pattern_width", e.g. "single;data/hiro.patt;80" * - Square marker from pattern passed in config: "square;pattern_width;buffer=[]", e.g. "square_buffer;80;buffer=234 221 237..." * - Square barcode marker: "square_barcode;barcode_id;pattern_width", e.g. "square_barcode;0;80" * - Multi-square marker: "multi;config_file", e.g. "multi;data/multi/marker.dat" * @param cfg The configuration string * @return The UID of the marker instantiated based on the configuration string, or -1 if an error occurred. */ int addTrackable(const char* cfg); /** * Removes the marker with the given ID. * @param UID The UID of the marker to remove * @return true if the marker was removed, false if an error occurred. */ bool removeTrackable(int UID); /** * Clears the collection of markers. * @return The number of markers removed */ int removeAllTrackables(); /** * Returns the number of currently loaded markers. * @return The number of currently loaded markers. */ unsigned int countTrackables(ARTrackable::TrackableType type = ARTrackable::Default); /** * Searches the collection of markers for the given ID. * @param UID The UID of the marker to find * @return The found marker, or NULL if no matching ID was found. */ ARTrackable* findTrackable(int UID); /** * Requests the capture of a new frame from the video source(s). * In the case of stereo video sources, capture from both sources will be attempted. * @return The capture succeeded, or false if no frame was captured. */ bool capture(); bool displayFrameInit(const int videoSourceIndex); bool displayFrameSettings(const int videoSourceIndex, const int width, const int height, const bool rotate90, const bool flipH, const bool flipV, const ARView::HorizontalAlignment hAlign, const ARView::VerticalAlignment vAlign, const ARView::ScalingMode scalingMode, int32_t viewport[4]); bool displayFrame(const int videoSourceIndex); bool displayFrameFinal(const int videoSourceIndex); /** * Asks the video source to push the most recent frame into the passed-in buffer. * @param videoSourceIndex Index into an array of video sources, specifying which source should * be queried. * @param buffer Pointer to a buffer of pixels (of type 'uint32_t') to be filled. It is the * caller's responsibility to ensure that the buffer is of sufficient size. The pixels are * RGBA in little-endian systems, or ABGR in big-endian systems. */ bool getFrameTextureRGBA32(const int videoSourceIndex, uint32_t *buffer); /** * Performs marker detection and updates all markers. The latest frame from the current * video source is retrieved and analysed. Each marker in the collection is updated with * new tracking information. The marker info array is * iterated over, and detected markers are matched up with those in the marker collection. Each matched * marker is updated with visibility and transformation information. Any markers not detected are considered * not currently visible. * * @return true if update completed successfully, false if an error occurred */ bool update(); /** * Populates the provided color buffer with the image for the specified pattern. * @param patternID The ARToolKit pattern ID to use * @param buffer The color buffer to populate * @return true if successful, false if an error occurred */ bool getPatternImage(int patternID, uint32_t* buffer); bool getFeatureImage(int patternID, unsigned char* &buffer, std::string fileName, std::string saveName=""); bool isInited(); bool load2DTrackerImageDatabase(const char* databaseFileName, int* &targetIds, int *targetSize, const char* destPath = nullptr); bool save2DTrackerImageDatabase(std::string fileName); }; #endif // !__AR6_ARController_h__
a3ea718872cd4d56633350cfb4134e894987239b
a5326af130d8c0f3138282e0e8f84704d662e341
/library/tracking_data/io/track_reader_kw18.cxx
4ae63b02462c6942dae0770859285a402e89d9f9
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
daniel-riehm/burn-out
98b75739400f981f7509a966da4bf449e3397a38
1d2afcd36d37127b5a3b6fa3f60bc195408ab3ea
refs/heads/master
2022-03-05T12:25:59.466369
2019-11-15T01:37:47
2019-11-15T01:37:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,480
cxx
/*ckwg +5 * Copyright 2010-2016 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "track_reader_kw18.h" #include <fstream> #include <cstdio> #include <tracking_data/tracking_keys.h> #include <vil/vil_load.h> #include <vil/vil_new.h> #include <vil/vil_image_resource.h> #include <vil/vil_crop.h> #include <vil/vil_fill.h> #include <vul/vul_file.h> #include <vul/vul_file_iterator.h> #include <utilities/shell_comments_filter.h> #include <utilities/blank_line_filter.h> #include <logger/logger.h> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> namespace vidtk { namespace ns_track_reader { namespace { VIDTK_LOGGER( "track_reader_kw18" ); typedef std::map< int, int > id_map_t; // field numbers for KW18 file format enum{ // 0: Object ID // 1: Track length (always 1 for detections) COL_FRAME = 2, COL_LOC_X, // 3 COL_LOC_Y, // 4 COL_VEL_X, // 5 COL_VEL_Y, // 6 COL_IMG_LOC_X,// 7 COL_IMG_LOC_Y,// 8 COL_MIN_X, // 9 COL_MIN_Y, // 10 COL_MAX_X, // 11 COL_MAX_Y, // 12 COL_AREA, // 13 COL_WORLD_X, // 14 COL_WORLD_Y, // 15 COL_WORLD_Z, // 16 COL_TIME, // 17 COL_CONFIDENCE// 18 }; } // end namepsace // ---------------------------------------------------------------- /** Constructor * * */ track_reader_kw18 ::track_reader_kw18() : in_stream_(0), read_pixel_data_(false), been_read_(false) { } track_reader_kw18 ::~track_reader_kw18() { } bool track_reader_kw18 ::set_path_to_images( std::string const& path ) { if ( path.empty() ) { this->read_pixel_data_ = false; return false; } std::string glob_str = path; std::string path_str = path; char lastc = *path.rbegin(); if ( ( lastc != '\\' ) && ( lastc != '/' ) ) { glob_str += "/"; path_str += "/"; } glob_str += "*"; // Collect a list of file names. There will be one file per frame. for ( vul_file_iterator iter = glob_str; iter; ++iter ) { // Check file "format" to make sure it is readable by vil_load() if ( ( vul_file::extension( iter.filename() ) == ".jpg" ) || ( vul_file::extension( iter.filename() ) == ".png" ) || ( vul_file::extension( iter.filename() ) == ".jpeg" ) ) image_names_.push_back( path_str + iter.filename() ); } this->read_pixel_data_ = ( ! image_names_.empty() ); return this->read_pixel_data_; } // ---------------------------------------------------------------- /** Open the file or die trying. * * */ bool track_reader_kw18 ::open( std::string const& filename ) { bool status( false ); if ( 0 != in_stream_ ) // meaning we are already open { return filename_ == filename; } filename_ = filename; if ( ! validate_file() ) { return false; } std::ifstream fstr( this->filename_.c_str() ); if ( ! fstr ) { LOG_ERROR( "kw18 reader could not open " << this->filename_ << " for reading." ); return false; } // build boost filter to remove comments and blank lines // order is important. in_stream_ = new boost::iostreams::filtering_istream(); in_stream_->push( vidtk::blank_line_filter() ); in_stream_->push( vidtk::shell_comments_filter() ); in_stream_->push( fstr ); // If a path to images is specified, then get images if ( ! this->reader_options_.get_path_to_images().empty() ) { status = set_path_to_images( this->reader_options_.get_path_to_images() ); if ( ! status ) { LOG_ERROR( "kw18 reader could not load images from " << this->reader_options_.get_path_to_images() ); return false; } } // Read all tracks from file if ( read_all_tracks() ) { sort_terminated( all_tracks_ ); return true; } return false; } // open bool track_reader_kw18 ::read_next_terminated( vidtk::track::vector_t& datum, unsigned& frame ) { if (this->current_terminated_ == this->terminated_at_.end() ) { return false; // end of tracks } datum = this->current_terminated_->second; frame = this->current_terminated_->first; // frame number ++this->current_terminated_; // point to next set of tracks return true; } size_t track_reader_kw18 ::read_all( vidtk::track::vector_t& datum ) { if (been_read_) { return 0; } been_read_ = true; // Tracks have already been read in by open() datum = this->all_tracks_; return datum.size(); } // ---------------------------------------------------------------- /** Read all tracks from stream. * * Return false if error; true if tracks are read and vectorized. */ bool track_reader_kw18 ::read_all_tracks() { std::string line; id_map_t id_to_index; std::vector< std::string > col; std::vector< image_object_sptr > objs( 1 ); while (std::getline(*in_stream_, line)) { col.clear(); boost::char_separator < char > sep(" "); typedef boost::tokenizer < boost::char_separator<char> > tok_t; tok_t tok( line, sep ); for(tok_t::iterator it = tok.begin(); it != tok.end(); ++it) { col.push_back( *it ); } // skip lines suppressed by filtered stream if ( col.empty() ) { continue; } if ( ( col.size() < 18 ) || ( col.size() > 20 ) ) { LOG_ERROR( "This is not a kw18 kw19 or kw20 file; found " << col.size() << " columns in\n\"" << line << "\"" ); return false; } /* * Check to see if we have seen this track before. If we have, * then retrieve the track's index into our output vector. If not * seen before, add track id -> track vector index to our map and * press on. * * This allows for track states to be written in a non-contiguous * manner as may be done by streaming writers. */ int index; int id = atoi( col[0].c_str() ); id_map_t::iterator itr = id_to_index.find( id ); if ( itr == id_to_index.end() ) { // create a new track vidtk::track_sptr to_push = new vidtk::track; to_push->set_id( id ); this->all_tracks_.push_back( to_push ); index = this->all_tracks_.size() - 1; id_to_index[id] = index; } else { index = itr->second; } vidtk::track_state_sptr new_state = new vidtk::track_state; new_state->time_.set_frame_number( atoi( col[COL_FRAME].c_str() ) ); new_state->loc_[0] = atof( col[COL_LOC_X].c_str() ); new_state->loc_[1] = atof( col[COL_LOC_Y].c_str() ); new_state->loc_[2] = 0; new_state->vel_[0] = atof( col[COL_VEL_X].c_str() ); new_state->vel_[1] = atof( col[COL_VEL_Y].c_str() ); new_state->vel_[2] = 0; image_object_sptr obj = new image_object; obj->set_image_loc( atof( col[COL_IMG_LOC_X].c_str() ), atof( col[COL_IMG_LOC_Y].c_str() )); int min_x = atoi( col[COL_MIN_X].c_str() ); int max_x = atoi( col[COL_MAX_X].c_str() ); int min_y = atoi( col[COL_MIN_Y].c_str() ); int max_y = atoi( col[COL_MAX_Y].c_str() ); obj->set_bbox( ( min_x < 0 ? 0 : min_x ), ( max_x < 0 ? 0 : max_x ), ( min_y < 0 ? 0 : min_y ), ( max_y < 0 ? 0 : max_y ) ); obj->set_area( atof( col[COL_AREA].c_str() ) ); // If specified, we need to interpret the world location as a // lat/lon coordinate if ( this->reader_options_.get_read_lat_lon_for_world() ) { new_state->set_latitude_longitude( atof( col[COL_WORLD_Y].c_str() ), // latitude atof( col[COL_WORLD_X].c_str() ) ); // longitude } else { obj->set_world_loc(atof( col[COL_WORLD_X].c_str() ), // x atof( col[COL_WORLD_Y].c_str() ), // y atof( col[COL_WORLD_Z].c_str() )); // z } if ( this->read_pixel_data_ ) { if (new_state->time_.frame_number() >= this->image_names_.size()) { LOG_ERROR( "kw18 reader does not have image file name for this frame" ); } //Read the image from file vil_image_view< vxl_byte > src_img = vil_load( this->image_names_[new_state->time_.frame_number()].c_str() ); if ( ! src_img ) { LOG_ERROR( "kw18 reader could not load image from file \"" << this->image_names_[new_state->time_.frame_number()] << "\"" ); } const vgl_box_2d< unsigned >& obj_bbox = obj->get_bbox(); vil_image_view< vxl_byte > img_crop = vil_crop( src_img, obj_bbox.min_x(), obj_bbox.max_x() - obj_bbox.min_x(), obj_bbox.min_y(), obj_bbox.max_y() - obj_bbox.min_y() ); vil_image_view< vxl_byte > bbox_pxls; bbox_pxls.deep_copy( img_crop ); vil_image_resource_sptr data = vil_new_image_resource_of_view( bbox_pxls ); obj->set_image_chip( data, 0u ); } // end read pixel data objs[0] = obj; new_state->data_.set( tracking_keys::img_objs, objs ); new_state->amhi_bbox_.set_min_x( atoi( col[COL_MIN_X].c_str() ) ); new_state->amhi_bbox_.set_min_y( atoi( col[COL_MIN_Y].c_str() ) ); new_state->amhi_bbox_.set_max_x( atoi( col[COL_MAX_X].c_str() ) ); new_state->amhi_bbox_.set_max_y( atoi( col[COL_MAX_Y].c_str() ) ); // time_ is a timestamp which keeps time in microseconds. All // kw18 files so far have time written in seconds so, convert from // seconds to microseconds. new_state->time_.set_time( atof( col[COL_TIME].c_str() ) * 1e6 ); if( col.size() == 19 ) { new_state->set_track_confidence( atof( col[COL_CONFIDENCE].c_str() ) ); } this->all_tracks_[index]->add_state( new_state ); } // ...while !eof return true; } // read_all_tracks // ---------------------------------------------------------------- /** Validate file type. * * This method inspects the file to see if it is of the expected * type. Currently, if the filename ends in '.kw18' or the first data * line has 18 fields, the file is considered o.k. * * @return \c true is returned if the file format is recognized, \c * false otherwise. */ bool track_reader_kw18 ::validate_file () { // std::string const file_ext = vul_file::extension( filename_ ); if ( boost::iequals( file_ext, ".kw18") ) { return true; } std::ifstream fstr( this->filename_.c_str() ); if( ! fstr ) { LOG_WARN( "kw18 reader could not open file \"" << this->filename_ << "\""); return false; // not valid file } // build boost filter to remove comments and blank lines // order is important. boost::iostreams::filtering_istream local_stream; local_stream.push (vidtk::blank_line_filter()); local_stream.push (vidtk::shell_comments_filter()); local_stream.push (fstr); double dbl_track_id, dbl_n_frames, dbl_frame_num; // fields 0, 1, 2 double loc_x, loc_y, vel_x, vel_y; // fields 3, 4, 5, 6 double obj_loc_x, obj_loc_y; // fields 7,8 double bb_c1_x, bb_c1_y, bb_c2_x, bb_c2_y; // fields 9, 10, 11, 12 double area, world_x, world_y, world_z; // fields 13, 14, 15, 16 double timestamp; // field 17 std::string s; // skip a few empty lines while (std::getline(local_stream, s) && s.empty()) { } // This is a little weak. There can be up to 20 numbers on a // record. At least we validate that the fields are numbers. int count = std::sscanf( s.c_str(), "%lf %lf %lf " "%lf %lf %lf %lf " "%lf %lf %lf %lf %lf %lf " "%lf %lf %lf %lf %lf", &dbl_track_id, &dbl_n_frames, &dbl_frame_num, &loc_x, &loc_y, &vel_x, &vel_y, &obj_loc_x, &obj_loc_y, &bb_c1_x, &bb_c1_y, &bb_c2_x, &bb_c2_y, &area, &world_x, &world_y, &world_z, &timestamp ); if (count != 18 ) { LOG_DEBUG( "Incorrect data format for kw18 file"); return false; } return true; } } // end namespace } // end namespace
529ed4ae74367a5c13884bb8f0c94ae194d3c157
adc8c8798aea0e06e93b621b55f000fb7a6a4345
/art/compiler/driver/dex_compilation_unit.h
24a9a5b6534ff881a23f0be9735293b4a5ec70ab
[ "Apache-2.0", "NCSA" ]
permissive
maiyao1988/my_aosp81
34bbfe1e2632a8924c25f39e59804f162390b37c
d32ab834fd9b9036b56c2715481f85bbaad38081
refs/heads/master
2022-06-16T11:13:49.694990
2020-05-14T13:42:45
2020-05-14T13:42:45
264,388,353
10
1
null
null
null
null
UTF-8
C++
false
false
3,476
h
/* * Copyright (C) 2012 The Android Open Source Project * * 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 ART_COMPILER_DRIVER_DEX_COMPILATION_UNIT_H_ #define ART_COMPILER_DRIVER_DEX_COMPILATION_UNIT_H_ #include <stdint.h> #include "base/arena_object.h" #include "dex_file.h" #include "handle.h" #include "jni.h" namespace art { namespace mirror { class ClassLoader; class DexCache; } // namespace mirror class ClassLinker; class VerifiedMethod; class DexCompilationUnit : public DeletableArenaObject<kArenaAllocMisc> { public: DexCompilationUnit(Handle<mirror::ClassLoader> class_loader, ClassLinker* class_linker, const DexFile& dex_file, const DexFile::CodeItem* code_item, uint16_t class_def_idx, uint32_t method_idx, uint32_t access_flags, const VerifiedMethod* verified_method, Handle<mirror::DexCache> dex_cache); Handle<mirror::ClassLoader> GetClassLoader() const { return class_loader_; } ClassLinker* GetClassLinker() const { return class_linker_; } const DexFile* GetDexFile() const { return dex_file_; } uint16_t GetClassDefIndex() const { return class_def_idx_; } uint32_t GetDexMethodIndex() const { return dex_method_idx_; } const DexFile::CodeItem* GetCodeItem() const { return code_item_; } const char* GetShorty() const { const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); return dex_file_->GetMethodShorty(method_id); } const char* GetShorty(uint32_t* shorty_len) const { const DexFile::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_); return dex_file_->GetMethodShorty(method_id, shorty_len); } uint32_t GetAccessFlags() const { return access_flags_; } bool IsConstructor() const { return ((access_flags_ & kAccConstructor) != 0); } bool IsNative() const { return ((access_flags_ & kAccNative) != 0); } bool IsStatic() const { return ((access_flags_ & kAccStatic) != 0); } bool IsSynchronized() const { return ((access_flags_ & kAccSynchronized) != 0); } const VerifiedMethod* GetVerifiedMethod() const { return verified_method_; } void ClearVerifiedMethod() { verified_method_ = nullptr; } const std::string& GetSymbol(); Handle<mirror::DexCache> GetDexCache() const { return dex_cache_; } private: const Handle<mirror::ClassLoader> class_loader_; ClassLinker* const class_linker_; const DexFile* const dex_file_; const DexFile::CodeItem* const code_item_; const uint16_t class_def_idx_; const uint32_t dex_method_idx_; const uint32_t access_flags_; const VerifiedMethod* verified_method_; const Handle<mirror::DexCache> dex_cache_; std::string symbol_; }; } // namespace art #endif // ART_COMPILER_DRIVER_DEX_COMPILATION_UNIT_H_
e5f5f80ccbcf52b34bebea7e9000a780c65b0d03
b6ff5e342f3675087d2704199bb5a46362b5fc20
/1GI/S2/Programmation Orienté Objet en C++/Issam/Surcharge des opérateurs (les fractions)/src/UnRationnel.cpp
1d75ea4319ef5645811d1eb3650fa46ff11b8980
[]
no_license
Ssouh/EHTP
75f5071282a1b0ed500d5c27e73b514fefe7af61
96558e59e398f652ae2e8a560b9dcd4ee3e8c6a8
refs/heads/main
2023-03-14T11:56:46.424726
2021-03-04T09:49:05
2021-03-04T09:49:05
330,687,825
0
0
null
2021-01-24T18:02:23
2021-01-18T14:15:22
null
UTF-8
C++
false
false
2,422
cpp
#include "UnRationnel.h" #include <iostream> #include <ostream> using namespace std; UnRationnel::UnRationnel(int telNum,int telDenom) { sonNum=telNum; sonDenom=telDenom; } void UnRationnel::somme(UnRationnel telX, UnRationnel telY) { sonNum = telX.sonNum*telY.sonDenom + telY.sonNum*telX.sonDenom; sonDenom = telX.sonDenom * telY.sonDenom; } void UnRationnel::produit(UnRationnel telX, UnRationnel telY) { sonNum = telX.sonNum * telY.sonNum ; sonDenom = telX.sonDenom * telY.sonDenom ; } UnRationnel& UnRationnel::operator=(const UnRationnel& telF) { if (&telF != this) { // Denominateur doit etre positif if (telF.sonDenom < 0 ) { sonDenom = -telF.sonDenom; sonNum = -telF.sonNum; } else if (telF.sonDenom > 0 ) { sonDenom = telF.sonDenom; sonNum = telF.sonNum; } } return *this; } bool UnRationnel::operator==(UnRationnel& telF) { return (sonNum*telF.sonDenom == sonDenom*telF.sonNum); } bool UnRationnel::operator!=(UnRationnel& telF) { return !(sonNum*telF.sonDenom == sonDenom*telF.sonNum); } bool UnRationnel::operator<=(UnRationnel& telF) { if (sonDenom*telF.sonDenom>0) return (sonNum*telF.sonDenom <= sonDenom*telF.sonNum); else return (sonNum*telF.sonDenom >= sonDenom*telF.sonNum); } bool UnRationnel::operator>=(UnRationnel& telF) { if (sonDenom*telF.sonDenom>0) return (sonNum*telF.sonDenom >= sonDenom*telF.sonNum); else return (sonNum*telF.sonDenom <= sonDenom*telF.sonNum); } bool UnRationnel::operator<(UnRationnel& telF) { if (sonDenom*telF.sonDenom>0) return (sonNum*telF.sonDenom < sonDenom*telF.sonNum); else return (sonNum*telF.sonDenom > sonDenom*telF.sonNum); } bool UnRationnel::operator>(UnRationnel& telF) { return !(*this < telF ); } ostream& operator<<(ostream& telFlux,const UnRationnel& telleFraction) { return telFlux << telleFraction.sonNum << "/" << telleFraction.sonDenom ; } istream& operator>>(istream& telFlux, UnRationnel& telleFraction) { cout << "Numerateur = "; telFlux >> telleFraction.sonNum; cout << "Denominateur = "; telFlux >> telleFraction.sonDenom; while (telleFraction.sonDenom == 0) {cout << "Denominateur invalide, entrer a nouveau = "; telFlux >> telleFraction.sonDenom;} return telFlux; }
c24cd23f0c6002ec83ac9dbe7832ad5825af80fb
6f90b19191415e7a30914069cc019aeef88fc450
/classes/student/student.h
42ca47b320c554b2808802ab2456efa319fa11dd
[]
no_license
script0Brand/cis202-examples
250d557584c6bba4e16a67fe50163afb748c6f76
ea3b96506b0adcd366e6c06efb15a3d89bbd7fc1
refs/heads/master
2020-05-18T21:21:22.949611
2019-04-16T23:40:52
2019-04-16T23:40:52
184,659,515
1
0
null
2019-05-02T22:16:47
2019-05-02T22:16:47
null
UTF-8
C++
false
false
263
h
#ifndef STUDENT_H #define STUDENT_H class Student { // make sure you have name and total quiz score member data public: Student(); void get_name(); void add_quiz(int score); double get_average_score();get_average_score double gpa(); }; #endif
41555917ac3cfa1842532bf2369aae07f6970d43
f953e2c4405582a804c85ebd5e8a97236ba679ed
/Chapter15/Chapter15_01/Resource.h
5057828f220cada683e6d19486bd52af02bbde15
[]
no_license
Knabin/TBCppStudy
384710f935e43bb617d07579f6cadae54732fd8e
ec7c322a035ff8c013c505bf8c64a851e66168fe
refs/heads/master
2023-04-26T05:35:14.259977
2021-06-05T12:56:10
2021-06-05T12:56:10
254,893,482
2
0
null
null
null
null
UTF-8
C++
false
false
239
h
#pragma once #include <iostream> class Resource { //private: public: int m_data[100]; public: Resource() { std::cout << "Resource constructed" << std::endl; } ~Resource() { std::cout << "Resource destroyed" << std::endl; } };
36db3c32d3553e3011e60c2847b5d4271fce9db2
cfb50418164b5fd94a6c3ef4f5bb505d61c5f171
/game_data/data_layer.h
71fedbabd6e647c5d255a531e5e6f15e7c9b888e
[]
no_license
hackerlank/NewRunfast
e56fe222936d7c47096fd57066843c1c32a8596b
50614fbbc30b84ff0549eb72a85b364c943e9ff6
refs/heads/master
2020-03-12T06:16:18.013203
2018-01-17T09:49:01
2018-01-17T09:49:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,866
h
#ifndef _XPOKER_DB_DATALAYER_H_ #define _XPOKER_DB_DATALAYER_H_ #include <set> #include <memory> #include <cpp_redis.h> #include <assistx2/singleton.h> #include <assistx2/connector.h> #include <assistx2/memcached_wrapper.h> #include "xpoker.h" #include "data_def.h" #include "membergame.pb.h" #include "memberfides.pb.h" #include "membercommongame.pb.h" class Database; class DataLayer : public Singleton<DataLayer> { public: DataLayer(void); virtual ~DataLayer(void); std::int32_t Init(boost::asio::io_service * engine); public: std::int32_t UpdateGameData(uid_type mid, std::int32_t win_count, std::int32_t round_count, std::string handstrength, const chips_type maxwin); std::int32_t UpdateRunFastScore(uid_type mid,std::int32_t score); std::int32_t SetRunFastGameRecord(std::int32_t roomid, int32_t num_of_games, int32_t player1_mid, int32_t player2_mid, int32_t player3_mid, const std::string& data_game, int32_t winner); //金币支付接口, incr 可正,可负 扣錢為正, 加錢為負 std::int32_t Pay(const uid_type mid, const chips_type incr, chips_type & amount, chips_type& real_delta, bool bForce = false); std::int32_t PayProps(const uid_type mid, std::int32_t pcate,std::int32_t pframe, std::int32_t num, bool isPay = true); std::int32_t AddProps(const uid_type mid, std::int32_t pcate, std::int32_t pframe, std::int32_t num); void AddRoomInfo(const std::int32_t roomid,const std::string& info); void RemoveRoomInfo(const std::int32_t roomid); bool GetRoomInfo(const std::int32_t roomid,std::string& info); void AddRoomRecordInfo(const std::int32_t roomid, const std::string& info); void RemoveRoomRecordInfo(const std::int32_t roomid); bool GetRoomRecordInfo(const std::int32_t roomid, std::string& info); void AddPlayerStatus(const uid_type mid, const std::int32_t game_session); void RemovePlayerStatus(const uid_type mid); void UpdateRoomsList(const std::string & type, const std::string & info, const std::int32_t sid); void UpdateRoom(std::int32_t roomid, const std::string & info); void UpdateCreatorList(const std::string& list); bool GetCreatorList(std::string& list); void UpdateCreatorRoomList(const uid_type mid,const std::string& list); bool GetCreatorRoomList(const uid_type mid,std::string& list); void DeleteCreatorRoomList(const uid_type mid); void UpdateRoomData(const uid_type mid, std::int32_t roomid, const std::string& list); bool GetRoomData(const uid_type mid, std::int32_t roomid, std::string& list); void DeleteRoomData(const uid_type mid, std::int32_t roomid); bool GetRopen(const uid_type mid,std::string& data); void removeKey(const std::string& key) const; std::int32_t GetUserProps(const uid_type uid, Props_type & props); std::int32_t GetFriends(const uid_type mid, std::set<uid_type> & friends); std::int32_t GetPokerFriends(const uid_type mid, std::set<uid_type> & friends); std::int32_t DeletePokerFriend(const uid_type mid, const uid_type fmid); std::int32_t AddPokerFriend(const uid_type mid, const uid_type fmid); std::int32_t GetLevelCfg(LevelItems_type & cfg); std::int32_t GetRank(const uid_type mid, std::int32_t & win_rank, std::int32_t & riches_rank); std::int32_t UpdateAwardPool(chips_type award, chips_type & award_pool); void GetAward(std::int32_t thousand, chips_type & award, chips_type & award_pool, chips_type & old_award_pool); void LockGold(const uid_type mid); void UnlockGold(const uid_type mid); std::int32_t GetRoomGiftCfg( RoomGiftCfg & cfgs ); std::int32_t GetLoginIP( uid_type mid, std::string & login_ip ); void GetDayData( const uid_type mid, std::string & data); void UpdateDayData( const uid_type mid, const std::string & data ); std::int32_t RedisSet(const std::string & key, const std::string & value); std::int32_t RedisGet(const std::string & key, std::string & value); std::int32_t RedisGetKeys(std::vector<std::string > & key, std::vector<std::string > & value); std::int32_t RedisDel(const std::string & key); std::int32_t RedisIncr(const std::string & key, const std::int32_t incr, std::int32_t & amount); std::int32_t IncrPoints(std::int32_t mid, const std::int32_t incr, std::int32_t & value); std::int32_t GetPoints(std::int32_t mid, std::string & value); std::int32_t StartGoldStat(chips_type carry_gold); std::int32_t GetPlayerGameInfo(uid_type mid, MemberGame & info, bool forcedflush = false); std::int32_t GetCommonGameInfo(uid_type mid, MemberCommonGame & info, bool forcedflush = false); std::int32_t GetCommonGameInfoFromDB(uid_type mid, json_spirit::Value & array); std::int32_t GetPlayerBaseInfo(uid_type mid, std::string & json_str, MemberFides & info); void set_player_gps(const uid_type mid, const std::string& data); std::string player_gps(const uid_type mid); private: std::int32_t InitMemcachedAgent(); std::int32_t GetUserPropsFromCache(const uid_type mid, Props_type & props); std::int32_t GetUserPropsFromDB(const uid_type uid, Props_type & props); std::int32_t GetMemberGameFromDB(uid_type mid, json_spirit::Value & array); std::int32_t GetGameInfoFromCache(uid_type mid, MemberGame & info); std::int32_t SyncGameDataToCache(const uid_type mid, const json_spirit::Value & json_value); std::int32_t GetCommonGameInfoFromCache(uid_type mid, MemberCommonGame & info); std::int32_t SetCommonGameInfoToCache(const uid_type mid, const json_spirit::Value & json_value); private: Database * databaseconnector_ = nullptr; cpp_redis::Requestor<cpp_redis::REQUESTOR > * redisconnector_ = nullptr; boost::asio::io_service * engine_ = nullptr; std::shared_ptr< IMemcacheHandler > memcached_agent_; std::string cfg_database_; std::string local_config_; std::string db_prefix_; }; #endif //_XPOKER_DB_DATALAYER_H_
7b12a99201c03befe66e4af11c718411196e1a64
386e4768a673cfe9e6463d3f0e3ed5cfa7e9eeb5
/new_frame/include/utils/sutils.h
34ffd77fbcf2eb84c8bcec6bcf357e57681a3c32
[]
no_license
binbin6363/Hygeia
92108269f5cb9508b42cf8d1214e891bc9236f74
62fde8f51736220846c060f0c8de64d859669bb4
refs/heads/master
2021-01-17T06:30:03.587233
2014-11-27T10:05:59
2014-11-27T10:05:59
null
0
0
null
null
null
null
GB18030
C++
false
false
43,557
h
/** * @file ISPUtils.h * @brief 公用函数库 * * 使用的一些公用函数,这个文件里包含了一些方便使用的函数 * 考虑到这里提供的函数会在多个项目中使用,因此不要包含ACE * * @author jdyu * @version 1.0 * @date 2004-6-8 * * @see * * <b>History:</b><br> * <table> * <tr> <th>Version <th>Date <th>Author <th>Notes</tr> * <tr> <td>1.0 <td>2004-6-8 <td>jdyu <td>Create this file</tr> * <tr> <td>1.1 <td>2005-9-29 <td>jdyu <td>进行了梳理</tr> * </table> * */ #ifndef __SPUTILS_H__ #define __SPUTILS_H__ #include <string> #include <vector> #include <list> #include <map> /* data type defines */ #define SP_DWORD unsigned int #define SP_UINT unsigned int #define SP_WORD unsigned short #define SP_BYTE unsigned char /// HANDLE type typedef void * IU_HANDLE; #ifdef WIN32 # define IU_INVALID_HANDLE INVALID_HANDLE_VALUE #else // NOT WIN32 # define IU_INVALID_HANDLE IU_HANDLE(-1) #endif // NOT WIN32 // MAX_PATH #ifndef MAX_PATH #define MAX_PATH 260 #endif /* MAX_PATH */ /// 计算机名长度 #define ISP_MAXCOMPUTERNAME 16 /// 斜杠定义 #define BSLASH_CHR '\\' #define BSLASH_STR "\\" #define SLASH_CHR '/' #define SLASH_STR "/" /// 路径区分符 #ifndef PATH_CHR # ifdef WIN32 # define PATH_CHR BSLASH_CHR # define PATH_STR BSLASH_STR #else # define PATH_CHR SLASH_CHR # define PATH_STR SLASH_STR # endif // WIN32 #endif // PATH_CHR // 版本号 #define SP_MAKEWORD(a, b) ((SP_WORD)(((SP_BYTE)((SP_DWORD)(a) & 0xff)) | ((SP_WORD)((SP_BYTE)((SP_DWORD)(b) & 0xff))) << 8)) #define SP_MAKELONG(a, b) ((long)(((SP_WORD)((SP_DWORD)(a) & 0xffff)) | ((SP_DWORD)((SP_WORD)((SP_DWORD)(b) & 0xffff))) << 16)) #define SP_LOWORD(l) ((SP_WORD)((SP_DWORD)(l) & 0xffff)) #define SP_HIWORD(l) ((SP_WORD)((SP_DWORD)(l) >> 16)) #define SP_LOBYTE(w) ((SP_BYTE)((SP_DWORD)(w) & 0xff)) #define SP_HIBYTE(w) ((SP_BYTE)((SP_DWORD)(w) >> 8)) #define SP_VERMAKE(maj, min, rev) SP_MAKELONG(rev, SP_MAKEWORD(min, maj)) #define SP_VERMAJOR(ver) SP_HIBYTE(SP_HIWORD(ver)) #define SP_VERMINOR(ver) SP_LOBYTE(SP_HIWORD(ver)) #define SP_VERREVISION(ver) SP_LOWORD(ver) // count of array #define SP_COUNTOF(arr) ( sizeof arr / sizeof arr[0] ) //////////////////////////////////////////////////////////////////////// // 字节序调整 //////////////////////////////////////////////////////////////////////// // 两个字节的WORD高低位倒转 #define SP_WORD_LE_BE(val) ((SP_WORD) ( (((SP_WORD) (val) & (SP_WORD) 0x00ffU) << 8) | \ (((SP_WORD) (val) & (SP_WORD) 0xff00U) >> 8))) // 四个字节的DWORD高低位倒转 #define SP_DWORD_LE_BE(val) ((SP_DWORD) ( (((SP_DWORD) (val) & (SP_DWORD) 0x000000ffU) << 24) | \ (((SP_DWORD) (val) & (SP_DWORD) 0x0000ff00U) << 8) | \ (((SP_DWORD) (val) & (SP_DWORD) 0x00ff0000U) >> 8) | \ (((SP_DWORD) (val) & (SP_DWORD) 0xff000000U) >> 24))) //////////////////////////////////////////////////////////////////////// /// 异常捕获的宏 //////////////////////////////////////////////////////////////////////// /// try ... catch #ifndef SP_CATCH_EXCEPTION_ # define SP_CATCH_BEGIN() # define SP_CATCH_END(handler) #else # define SP_CATCH_BEGIN() try { # define SP_CATCH_END(handler) } catch(...) { handler; } #endif /// try ... finally #ifndef SP_CATCH_EXCEPTION_ # define SP_FINALY_BEGIN() # define SP_FINALY_END(handler) handler; #else # if defined(WIN32) # define SP_FINALY_BEGIN() __try { # define SP_FINALY_END(handler) } __finally { handler; } # else /* linux */ # define SP_FINALY_BEGIN() # define SP_FINALY_END(handler) handler # endif /* WIN32 */ #endif /* SP_CATCH_EXCEPTION_ */ /** * ========================================================================== * 通用操作 * ========================================================================== */ /** * @brief 通用操作 * * 这个名字空间里面包含了在编码中经常用到的一些功能,分为: * 1.字符串操作 * 2.文件操作 * 3.网络操作 * 4.操作系统特性 * 几个大的分类,建议使用。 * * @author jdyu * @date 2007-7-5 * * @see * */ namespace sp { // 字符串数组 typedef std::vector<std::string> str_arr; typedef std::vector<std::wstring> wstr_arr; typedef std::list <std::string> str_list; typedef std::list <std::wstring> wstr_list; // 字符串映射表 typedef std::pair<std::string, std::string> str_pair; typedef std::pair<std::wstring, std::wstring> wstr_pair; typedef std::map <std::string, std::string> str_map; typedef str_map::value_type sm_item; typedef str_map::iterator sm_it; typedef str_map::const_iterator sm_cit; // 字符对列表 typedef std::vector<str_pair> str_pair_arr; typedef std::vector<wstr_pair> wstr_pair_arr; /** * @brief last_error * * 获得错误代码 * * @author jdyu * @date 2005-9-29 * @return int - Return 0 in success, otherwise return error code. * @see */ int last_error(void); /** * @brief get_val_in_range * * 将指定的值规范化到指定的区间 * * @author jdyu * @date 2004-7-15 * @return template<typename TYPE>TYPE * @param const TYPE& val - [in] 输入待规整的变量 * @param const TYPE& min - [in] 下限 * @param const TYPE& max - [in] 上限 * @see */ template<typename TYPE> TYPE get_val_in_range(const TYPE& val, const TYPE& min, const TYPE& max) { if ( val < min ) return min; if ( val > max ) return max; return val; } /** * @brief ln2 * * 求一个整数以2为底的整数次 * * @author jdyu * @date 2004-9-2 * @return int - Return 0 in success, otherwise return error code. * @param int pw - [in] 输入的整数 * @see */ # define IU_POW(X) (((X) == 0)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X))) inline int ln2(unsigned int pw) { int ln = 0; if ( pw != 0 && pw != 1 ) { pw = IU_POW(pw); while ( (( pw>>++ln) & 1 ) == 0 ); } return ln; } /** * @brief debugging_mode * * 设置当前是否为debuggin模式,在debugging模式下, * 一些函数会输出较多的信息 * * @author jdyu * @date 2006-2-28 * @return No return value. * @param bool mode - [in] 设置是否为调试模式 * @see */ bool debugging_mode(bool mode); bool debugging_mode(void); }; /** * ========================================================================== * 字符串相关的操作 * ========================================================================== */ namespace sp { /** * @brief is_quanjiao * * 判断是否为全角字符 * * @author jdyu * @date 2004-6-22 * @return bool - Return true in success, otherwise return false. * @param const char* pstr - [in,out] * @see */ bool is_quanjiao(const char * pstr); /** * @brief trim_str * * 去掉字符串头尾的空格或其他字符,包含控制字符 * * @author jdyu * @date 2004-6-22 * @return int 返回处处空格后的字符串长度 * @param char* pstr - [in,out] * @param const char ctrim = ' ' - [in] 需要剔除的符号 * @see */ int trim_str(char * pstr, const char trim_char = ' ', bool trim_gb = false); int trim_str(std::string & str, const char trim_char = ' ', bool trim_gb = false); int trim_str(char * pstr, const char * strim, bool trim_gb = false); int trim_str(std::string & str, const char * strim, bool trim_gb = false); int trim_str(wchar_t * pstr, const wchar_t trim_char = L' '); int trim_str(std::wstring & str, const wchar_t trim_char = L' '); int trim_str(wchar_t * pstr, const wchar_t * strim); int trim_str(std::wstring & str, const wchar_t * strim); /** * @brief search_strarr * * 获得指定字符串在数组中的索引 * * @author yigao * @date 2004年6月23日 * @return int * @param const char *str [in]需要查询的字符串 * @param const char *arr[] [in]需要查询的字符串数组 * @param int arr_size [in]数组大小 */ template <typename char_t> int search_strarr(const char_t * str, const char_t * arr [], int arr_size, bool case_sensitive = true); template <typename char_t, int row, int col> int search_strarr(const char_t * str, const char_t (&arr)[row][col], bool case_sensitive = true); template <typename char_t, template <typename T, typename A> class cont_t> int search_strarr(const char_t * str, cont_t<std::basic_string<char_t>, std::allocator<std::basic_string<char_t> > > & cont, bool case_sensitive = true); template <typename char_t, int count> inline int search_strarr(const char_t * str, const char_t * (&arr) [count]) { return search_strarr(str, arr, count, true); } template <typename char_t, int count> inline int search_strarr(const char_t * str, const char_t * const (&arr) [count]) { return search_strarr(str, (const char_t **)arr, count, true); } template <typename char_t, int count> inline int search_strarr_case(const char_t * str, const char_t * (&arr) [count]) { return search_strarr(str, arr, count, false); } template <typename char_t, int count> inline int search_strarr_case(const char_t * str, const char_t * const (&arr) [count]) { return search_strarr(str, arr, count, false); } /** * @brief str_to_time * * 将h:m:s格式的字符串转化成为数值 * * @author jdyu * @date 2004-7-15 * @return int * @param const char* strtm - [in] 待切分字符串 * @param int & hour - [out] 返回小时 * @param int & min - [out] 返回分钟 * @param int & sec - [out] 返回秒 * @see */ template <class T> int str_to_time(const char * strtm, T & hour, T & min, T & sec); template <class T> int str_to_time(const char * strtm, T & year, T & mon, T & day, T & hour, T & min, T & sec); int str_to_time(const char * strtm, time_t & tm); template <class T> int time_to_ymdhms(time_t tm, T & year, T & mon, T & day, T & hour, T & mnt, T & sec); int time_to_str(time_t tm, std::string & year, std::string & mon, std::string & day, std::string & hour, std::string & mnt, std::string & sec); // 获得月份的字符串 const char * month_str(int mon); // 把秒数转换成为天/小时/分/秒的形式 std::string sec_to_dhms(double sec); /** * @brief strsncpy * * strsncpy enhanced strncpy, more safe * * @author jdyu * @date 2005-9-29 * @return char * return destination buffer * @param char *dst - [in/out] destination string * @param const char *src - [in] source string * @param size_t maxlen - [in] max length * @see */ char * strsncpy (char * dst, const char * src, size_t maxcnt); wchar_t * strsncpy(wchar_t * dst, const wchar_t * src, size_t maxcnt); /** * @brief split_str * * 将指定的字符串切分为多个子串 * 以指定的分割字符为分界 * * @author jdyu * @date 2004-7-16 * @return int * @param const char* str - [in] 传入需要切分的字符串 * @param str_arr & subs_list - [out] 返回切分好的字符串数组 * @param const char spliter[] - [in] 分割符列表 * @param bool trim = true - [in] 是否把切分的结果去除两边的空格 * @param bool ignore_blank = false - [in] 是否忽略空的单元 * @param bool supp_quote = false - [in] 是否支持引号,引号内部不切分 * @param bool supp_quanjiao = false - [in] 是否支持全角 * @see */ int split_str(const char * str, str_arr & subs_array, const char spliter[] = ",;:", bool trim = true, bool ignore_blank = false, bool supp_quote = false, bool trim_quote = true, bool supp_quanjiao = false); int split_str(const wchar_t * str, wstr_arr & subs_array, const wchar_t spliter[] = L",;", bool trim = true, bool ignore_blank = false, bool supp_quote = false, bool trim_quote = true); int split_str(const char * str, wstr_arr & subs_array, const wchar_t spliter[] = L",;", bool trim = true, bool ignore_blank = false, bool supp_quote = false, bool trim_quote = true); int split_str(const wchar_t * str, str_arr & subs_array, const char spliter[] = ",;:", bool trim = true, bool ignore_blank = false, bool supp_quote = false, bool trim_quote = true); /** * @brief dequote_str * * 去掉字符串两边的引号,必须是对称的引号 * * @author jdyu * @date 2005-11-28 * @return char * * @param char * str - [in/out] 待去除的字符串 * @see */ char * dequote_str(char * str); wchar_t * dequote_str(wchar_t * str); // 添加引号 template<typename char_t> std::basic_string<char_t> quote_str(const char_t * cstr, char_t quote_chr = char_t('"')); /** * @brief get_attrib_and_value * * 把类似于attr="value"的属性对分解开来 * * @author jdyu * @date 2005-11-23 * @return int - Return 0 in success, otherwise return error code. * @param const char* attr_val - [in] 输入的属性对 * @param std::string & attr - [in] 属性名 * @param std::string & val - [in] 属性值 * @see */ int get_attrib_and_value(const char* attr_val, std::string & attr, std::string & val, const char * split = "=", bool trim = false); int get_attrib_and_value(const wchar_t* attr_val, std::wstring & attr, std::wstring & val, const wchar_t * split = L"=", bool trim = false); /** * @brief str_to_attr_vals * * 把类似于attr1="value1" attr2="value2"的属性对列表拆分成为 * 影射表形式 * * @author jdyu * @date 2005-11-23 * @return int - Return 0 in success, otherwise return error code. * @param const char* str - [in] 需要提取的源字符串 * @param str_map & attrs - [in] 返回提取结果 * @param bool trim = false - [in] 是否去除空格 * @param bool supp_quote = false - [in] 是否支持引号 * @see */ int str_to_attr_vals(const char* str, str_map & attrs, bool trim = false, bool supp_quote = false, const char * splt = " ;,", const char * token = "="); int str_to_attr_vals(const char* str, str_pair_arr & attrs, bool trim = false, bool supp_quote = false, const char * splt = " ;,", const char * token = "="); /** * @brief strlwr * * 字符串小写化,大写化 * * @author jdyu * @date 2007-5-30 * @return std::string * @param const std::string str - [in] 输入源字符串 * @see */ std::string & strlwr(std::string & str); std::string & strupr(std::string & str); std::wstring & strlwr(std::wstring & str); std::wstring & strupr(std::wstring & str); /** * @brief str_replace * * 字符串替换 * * @author jdyu * @date 2007-5-30 * @return std::string * @param const std::string str - [in] 输入源字符串 * @see */ std::string str_replace(const char * str, const char * src, const char * dst, bool trim = false); std::wstring str_replace(const wchar_t * str, const wchar_t * src, const wchar_t * dst, bool trim = false); /** * @fn strchr * @brief strchr * @author jdyu * @date 2008/10/5 * @see */ char * strchr(const char * str, int val); wchar_t * strchr(const wchar_t * str, int val); /** * @brief strcasecmp * * 忽略大小写的比较 * * @author jdyu * @date 2007-5-30 * @return int - 比较的结果,和strcmp相同 * @param const char * str1 - [in] 字符串一 * @param const char * str2 - [in] 字符串二 * @see */ int strcasecmp(const char * str1, const char * str2); int strcasecmp(const wchar_t * str1, const wchar_t * str2); int strcasecmp(const std::string & str1, const std::string & str2); int strcasecmp(const std::wstring & str1, const std::wstring & str2); int strcmp(const char * str1, const char * str2); int strcmp(const wchar_t * str1, const wchar_t * str2); int strncmp (const char * str1, const char * str2, size_t len); int strncmp (const wchar_t * str1, const wchar_t * str2, size_t len); size_t strlen(const char * str); size_t strlen(const wchar_t * str); int strncasecmp(const char *str1, const char *str2, size_t len); int strncasecmp(const wchar_t *str1, const wchar_t *str2, size_t len); int strncasecmp(const std::string &str1, const std::string &str2, size_t len); int strncasecmp(const std::wstring &str1, const std::wstring &str2, size_t len); /** * @brief str2ver & ver2str * * 字符串到版本和版本到字符串的转换 * * @author jdyu * @date 2007-5-30 * @return int - Return 0 in success, otherwise return error code. * @param const char * str - [in] * @param int & ver - [out] 主版本.次版本.修订号 * @param int & build - [out] 流水号 * @see */ int str2ver(const char * str, int & ver, int & build); std::string ver2str(int ver, int build); /** * @brief 带通配符'*'、'?'功能的子串查找 * * @author hjye * @date 2004-6-3 * @return bool - Returns true if matched. * @param const char* src_str - [in] 0-terminated string to search. * @param const char* match_str - [in] 0-terminated string to search for, can contain wildcards '*' or '?'. * @param bool match_case - [in] true means case sensitive. * @see */ bool strcmp_wildcard(const char* src_str, const char* match_str, bool match_case = true); /** * @brief timecmp * * 比较两个时间,如果参数为-1,表示该位无效 * * @author jdyu * @date 2004-10-18 * @return int - <0表示前面的时间早,0表示相等,>0表示前面的时间晚 * @see */ int timecmp(int hour1, int min1, int sec1, int hour2, int min2, int sec2, int day1 = -1, int day2 = -1); /** * @brief is_register_key * * 判断是否是一个注册表键名 * * @author jdyu * @date 2005-11-16 * @return bool - Return TRUE in success, otherwise return FALSE. * @param const char* key - [in] * @see */ bool is_register_key(const char* key); /** * @brief char2wchar wchar2char * * 宽字符和窄字符的互转 * * @author jdyu * @date 2007-6-6 * @return std::wstring * @param const char * str - [in] 输入带转换的字符串 * @param size_t * cvt_chrs = 0 - [out] 返回实际转换的字符数量 * @see */ std::wstring char2wchar(const char * str, size_t * cvt_chrs = 0); std::string wchar2char(const wchar_t * wstr, size_t * cvt_chrs = 0); std::string tochar(const std::string & str); std::string tochar(const std::wstring & str); std::wstring towchar(const std::string & str); std::wstring towchar(const std::wstring & str); std::string toutf8(const std::string & str); std::string toutf8(const std::wstring & str); std::wstring utf8towchar(const std::string & str); std::string utf8tochar(const std::string & str); // 宽窄转换,linux直接转 size_t mbstowcs(wchar_t *wcstr, const char *mbstr, size_t count); size_t wcstombs(char *mbstr, const wchar_t *wcstr, size_t count); /** * @brief strtoi * * 把字符串转化为值 * * @author jdyu * @date 2007-6-26 * @return int - Return 0 in success, otherwise return error code. * @param const char * str - [in] 输入字符串 * @see */ int strtoi(const char * str); int strtoi(const wchar_t * str); double strtod(const char * str); double strtod(const wchar_t * str); float strtof(const char * str); float strtof(const wchar_t * str); bool strtobool(const char * str, bool def = false); bool strtobool(const wchar_t * str, bool def = false); unsigned int strtoui(const char * str); unsigned int strtoui(const wchar_t * str); unsigned int towlower(unsigned int c); int wcscasecmp (const wchar_t * str1, const wchar_t * str2); int wcsncasecmp(const wchar_t * str1, const wchar_t * str2, size_t maxcount); const char * itostr(int val, std::string & str, const char * fmt = 0); const wchar_t * itostr(int val, std::wstring & str, const wchar_t * fmt = 0); std::string itostr(int val, const char * fmt = 0); std::wstring itowstr(int val, const wchar_t * fmt = 0); const char * ftostr(double val, std::string & str, const char * fmt = 0); const wchar_t * ftostr(double val, std::wstring & str, const wchar_t * fmt = 0); std::string ftostr(double val, const char * fmt = 0); std::wstring ftowstr(double val, const wchar_t * fmt = 0); /** * @brief cur_time * * 获得当前时间 * * @author jdyu * @date 2004年5月21日 * @return const char* * @param char times[] - [out] 返回时间信息的缓冲区 * @param bool no_path - [in] 是否不包含路径禁止的符号 * @see */ const char * cur_time(char times[], bool no_path = false, bool sht_fmt = false, bool has_msec = true, time_t start_time = 0, unsigned long start_tick = 0); const wchar_t * cur_time(wchar_t times[], bool no_path = false, bool sht_fmt = false, bool has_msec = true, time_t start_time = 0, unsigned long start_tick = 0); std::string cur_time(bool no_path = false, bool sht_fmt = false, bool has_msec = true, time_t start_time = 0, unsigned long start_tick = 0); std::wstring wcur_time(bool no_path, bool sht_fmt, bool has_msec = true, time_t start_time = 0, unsigned long start_tick = 0); /** * @fn strcopy * @brief 字符串拷贝,增强的可以进行宽窄转换的 * @author jdyu * @date 2008/10/13 * @return const char * 返回目标缓冲区 */ const char * strcopy(std::string & dest, const char * src); const wchar_t * strcopy(std::wstring & dest, const char * src); const char * strcopy(std::string & dest, const wchar_t * src); const wchar_t * strcopy(std::wstring & dest, const wchar_t * src); }; /** * ========================================================================== * 文件相关的操作 * ========================================================================== */ namespace sp { /** * @brief is_file_exist * * 检查一个文件是否存在 * * @author jdyu * @date 2004-6-22 * @return bool - Return true in success, otherwise return false. * @param const char* lpszFile - [in] 要检查的文件名 * @see */ bool is_file_exist(const char * file); bool is_file_exist(const wchar_t * file); /** * @brief is_dir_exist * * 检查一个目录是否存在 * * @author jdyu * @date 2004-6-22 * @return bool - Return true in success, otherwise return false. * @param const char* lpszDir - [in] 目录名 * @see */ bool is_dir_exist(const char * dir); bool is_dir_exist(const wchar_t * dir); // 创建目录 int create_directory(const char * dir, bool fail_if_exist = false, bool recursive = true); int path_to_dir_tree(const char * path, str_arr & dir_tree); /** * @brief normalize_path * * 将一个路径归一化,就是把所有的"\"或"/"转化为指定的路径分隔符 * 同时去处冗余的符号 * * @author jdyu * @date 2004-6-22 * @return int - Return 0 in success, otherwise return error code. * @param char* path - [in,out] 路径信息 * @param const char path_split = PATH_CHR - [in] 路径区分符号 * @see */ int normalize_path(char path[MAX_PATH], const char path_split = PATH_CHR); std::string normalize_path(const char * path, const char path_split = PATH_CHR); /** * @brief cat_path * * 将两个路径信息拼合起来,即 path + more * * @author jdyu * @date 2004-6-22 * @return const char* 返回拼接后的地址,就是lppath1 * @param char* path - [in,out] 前路径,返回拼合后的路径 * @param const char* more - [in] 后路径 * @see */ const char* cat_path(char* path, const char* more, const char path_split = PATH_CHR); std::string cat_path(const char * path, const char * more, const char path_split = PATH_CHR); /** * @brief is_abs_path * * 是否绝对路径 * * @author jdyu * @date 2004-6-22 * @return inline * @param const char* path - [in] 待检查的路径 * @see */ bool is_abs_path(const char* path); /** * @brief get_bin_path * * 获得当前可执行文件的路径 * * @author jdyu * @date 2004-6-22 * @return char* 返回可执行文件的路径 * @param char szPath[MAX_PATH] - [out] 输入缓冲区,返回可执行文件的路径 * @param IU_HANDLE hmod = 0 - [in] 输入模块的句柄,缺省为当前EXE模块, * 如果传入IU_INVALID_HANDLE则说明获取当前代码所在模块(EXE或DLL) * @see get_bin_pathname */ char* get_bin_path(char path[MAX_PATH], IU_HANDLE hmod = 0); std::string get_bin_path(IU_HANDLE hmod = 0); /** * @brief get_bin_pathname * * 获得模块的路径名 * * @author jdyu * @date 2004-6-22 * @return char* 返回模块的路径名 * @see get_bin_path */ char* get_bin_pathname(char pathname[MAX_PATH], IU_HANDLE hmod = 0); std::string get_bin_pathname(IU_HANDLE hmod = 0); /** * @brief get_bin_name * * 获得当前模块的不包含路径的文件名 * * @author jdyu * @date 2004-6-22 * @return char * 返回模块的路径名 * @see get_bin_path */ char* get_bin_name(char name[MAX_PATH], IU_HANDLE hmod = 0); std::string get_bin_name(IU_HANDLE hmod = 0); /** * @brief pathname_to_path * * 从全路径名中取出路径信息 * * @author jdyu * @date 2004-6-23 * @return char* * @param char szPath[MAX_PATH] - [out] 返回文件的路径 * @param const char* path_name - [in] 需要取得路径信息的全路径名 * @see */ char* pathname_to_path(char path[MAX_PATH], const char* path_name, const char path_split = PATH_CHR); std::string pathname_to_path(const char* path_name, const char path_split = PATH_CHR); /** * @brief pathname_to_name * * 从全路径名中取出文件名信息 * * @author jdyu * @date 2004-6-23 * @return char* * @param char name[MAX_PATH] - [out] 返回文件的名称 * @param const char* path_name - [in] 需要取得路径信息的全路径名 * @see */ char* pathname_to_name(char name[MAX_PATH], const char* path_name); std::string pathname_to_name(const char* path_name); /** * @brief pathname_to_noextname * * 从全路径名中取出不包含文件扩展名的文件名信息 * * @author jdyu * @date 2004-6-23 * @return char* * @param char name[MAX_PATH] - [out] 返回文件不包含扩展名的名称 * @param const char* path_name - [in] 需要取得路径信息的全路径名 * @see */ char* pathname_to_noextname(char name[MAX_PATH], const char* path_name); std::string pathname_to_noextname(const char* path_name); char* pathname_to_extname (char ext[MAX_PATH], const char* path_name, bool no_dot = true); std::string pathname_to_extname(const char* path_name, bool no_dot = true); /** * @brief get_file_full_path * * 得到一个文件的全路径名 * 主要目的是获取和当前模块在同一个路径下的文件的全路径名 * * @author jdyu * @date 2004-6-22 * @return char* * @param char path_name[] - [in,out] 缓冲区 * @param const char* file_name - [in] 指定的文件名 * @see */ char* get_file_full_path(char path_name[], const char* file_name, const char* rel_path = "bin"); std::string get_file_full_path(const char * file_name, const char * rel_path = "bin"); /** * @brief get_file_version * * 获得指定文件的版本号信息 * * @author jdyu * @date 2004-6-22 * @return const char* 返回文件版本 * @param const char* file - [in] 指定的文件名 * @param char* ver - [out] 返回文件版本的缓冲区 * @see */ const char* get_file_version(const char* file, char* ver); std::string get_file_version(const char* file); const char* get_prod_version(const char* file, char* ver); std::string get_prod_version(const char* file); /** * @brief get_lastest_prod_version * * 获得一个文件列表的最新的产品版本 * * @author jdyu * @date 2006-4-4 * @return const char* 返回产品版本 * @param const char* file_list - [in] 一个文件列表,以逗号区分 * @param char* ver - [out] 返回版本信息的缓冲区 * @see */ template <typename PROC> const char* get_lastest_version(const char* file_list, char* ver, PROC fn = get_prod_version) { ver[0] = 0; if ( file_list == 0 ) return 0; str_arr arr; split_str(file_list, arr, " ,", true, true, true); for ( int i = 0; i < (int)arr.size(); i++ ) { char file_ver[100]; char file[255]; sp::strsncpy(file, arr[i].c_str(), sizeof file); get_file_full_path(file, arr[i].c_str(), 0); // get version fn(file, file_ver); if ( version_compare(ver, file_ver) < 0 ) sp::strsncpy(ver, file_ver, sizeof file_ver); } return ver; } // std version template <typename PROC> std::string get_lastest_version(const char* file_list, PROC fn = get_prod_version) { char ver[200]; ver[0] = 0; return get_lastest_version(file_list, ver, fn); } /** * @brief version_compare * * 比较两个版本的大小 * * @author jdyu * @date 2006-4-4 * @return int - 返回0表明版本相同,小于零表明前面的版本小于后面的版本,否则大于 * @param const char * ver1 - [in] 第一个版本 * @param const char * ver2 - [in] 第二个版本 * @see */ int version_compare(const char * ver1, const char * ver2); /** * @brief get_file_list * * 获得一个目录下的文件列表 * * @author jdyu * @date 2005-10-11 * @return int - Return 0 in success, otherwise return error code. * @param const char* dir - [in] 指定的目录 * @param str_list & flist - [out] 返回的文件列表 * @param const char* filter = 0 - [in] 使用的过滤器 * @param bool recursive = true - [in] 是否搜索子目录 * @param ff_proc fproc = 0 - [in] 文件过滤的回调函数,如果被过滤掉返回false * @see */ struct ff_proc_default { bool operator()(const char * file) const { return true; } }; template<class LIST> int get_file_list(const char* dir, LIST & flist, const char* filter = 0, bool recursive = true); template<class LIST, class FF_PROC> int get_file_list(const char* dir, LIST & flist, const char* filter = 0, bool recursive = true, FF_PROC fproc = ff_proc_default()); template<class LIST> int get_dir_list (const char* dir, LIST & dlist, const char* filter = 0, bool recursive = true); template<class LIST, class FF_PROC> int get_dir_list (const char* dir, LIST & dlist, const char* filter = 0, bool recursive = true, FF_PROC fproc = ff_proc_default()); /** * @brief get_file_time * * 获得文件的创建时间和修改时间 * * @author jdyu * @date 2005-11-16 * @return int - Return 0 in success, otherwise return error code. * @param const char* file - [in] 文件名称 * @param time_t & tm_created - [in] 文件创建时间 * @param time_t & tm_modified - [in] 文件修改时间 * @see */ int get_file_time(const char* file, time_t & tm_created, time_t & tm_modified); time_t get_file_mtime(const char * file); time_t get_file_ctime(const char * file); /** * @brief get_file_size * * 获得文件的大小 * * @author jdyu * @date 2005-11-16 * @return int - Return 0 in success, otherwise return error code. * @param const char* file - [in] 文件名称 * @param unsigned int & size - [in] 文件大小 * @see */ int get_file_size(const char* file, unsigned int & size); unsigned int get_file_size(const char* file); /** * @brief is_text_file * * 判断一个文件是否文本类型的文件 * * @author jdyu * @date 2005-11-16 * @return bool - Return TRUE in success, otherwise return FALSE. * @param const char * file - [in] * @see */ bool is_text_file(const char * file, int maxs = 1024); /** * @brief mod_handle * * 获得当前模块的举柄,即HMODULE * * @author jdyu * @date 2007-6-6 * @return void * 返回当前模块的句柄,仅在Windows下有意义 * @see */ IU_HANDLE mod_handle(void); /** * @brief parent_path * * 获得父目录 * * @author jdyu * @date 2007-6-7 * @return std::string * @param const char * path - [in] 输入的路径 * @see */ std::string parent_path(const char * path); /** * @brief system * * 执行一个系统命令,和crt里面的system相同 * * @author jdyu * @date 2007-7-3 * @return int - Return 0 in success, otherwise return error code. * @param const char * cmd - [in] 需要执行的命令行 * @see ::system */ int system(const char * cmd); int system(const wchar_t * cmd); /** * @brief cat_audio_file * * 把音频数据追加到一个音频文件中,支持wave、alaw、ulaw音频头 * * @author jdyu * @date 2007-7-20 * @return int - Return 0 in success, otherwise return error code. * @param const char * file - [in] 音频文件名 * @param const void * data - [in] 音频数据 * @param int bytes - [in] 数据大小字节数 * @param bool fail_if_exist = false - [in] 如果文件存在是否失败 * @see */ int cat_audio_file(const char * file, const void * data, size_t bytes, bool fail_if_exist = false); /** * @fn read_text_file * @brief 读取文件内容到字符串 * * 把文件的内容放在字符串 * * @author jdyu * @date 2008/9/22 * @return int - Return 0 in success, otherwise return error code. * @param const char * file - [in] * @param std::string & text - [in] * @see */ int read_text_file(const char * file, std::string & text); int read_text_file(const char * file, std::wstring & text); int read_bin_file (const char * file, void * data, size_t bytes, size_t * readed = 0); int write_text_file(const char * file, const std::string & text, bool fail_if_exist = false, bool append = false); int write_text_file(const char * file, const std::wstring & text, bool fail_if_exist = false, bool append = false); int write_bin_file(const char* file, const void * data, size_t bytes, size_t * written = 0, bool fail_if_exist = false, bool append = false); /** * @fn getpid * @brief 获得进程ID * @author jdyu * @date 2008/10/8 * @return int - Return 0 in success, otherwise return error code. * @see */ int getpid(void); /** * @fn thr_self * @brief 获得当前线程id * @author jdyu * @date 2008/10/8 * @return int - Return 0 in success, otherwise return error code. * @see */ int thr_self(void); }; // deprecated namespace sp { /** * @brief get_module_cfg * * 获得当前模块(exe或者dll)的cfg配置文件名称 * * @author junyan * @date 2004年7月7日 * @return char* * @param char path[MAX_PATH] [out] 返回可用的配置文件名称 * @param const char* def_cfg [in] 缺省的配置文件名称(不包含路径) * @param IU_HANDLE hmod [in] 模块的句柄 * @see * @exception */ char* get_module_cfg(char path[MAX_PATH], const char* cfg_default = 0, IU_HANDLE hmod = 0); std::string get_module_cfg(const char * cfg_default = 0, IU_HANDLE hmod = 0); /** * @brief install_path * * 获得/设置当前系统的安装路径 * * @author jdyu * @date 2004-6-22 * @return const char* * @see */ const char* install_path(const char * path = 0); } /** * ========================================================================== * 网络相关的操作 * ========================================================================== */ namespace sp { /** * @brief local_hostname * * 返回当前主机名称,如果有完全限定域名(fully qualified domain name,FQDN) * 则返回FQDN,否则返回简单主机名,第三个参数指明了是简单主机名,还是FQDN * * @author jingzhang * @date 2006-10-19 * @return int - Return 0 in success, otherwise return error code. * @param char* hostname - [out] * @param size_t namelen - [in] * @param bool is_fqdn - [out] * @see */ int local_hostname(char* hostname, int namelen, bool& is_fqdn); /** * @brief ip_count * * 返回当前主机上IP的数量 * * @author jdyu * @date 2004-6-22 * @return int IP数量 * @see */ int ip_count(void); /** * @brief net_adpt_count * * 返回本机网卡的硬件数量 * Windows下准确 * * @author jdyu * @date 2005-12-26 * @return int - Return 0 in success, otherwise return error code. * @see */ int net_adpt_count(void); /** * @brief local_ip * * 获得本地unsigned long型的IP地址 * * @author jdyu * @date 2004-6-22 * @return int - Return 0 in success, otherwise return error code. * @param int& ip - [in,out] 返回本地的Ip地址,如果失败,返回INADDR_NONE * @see */ int local_ip(unsigned long & ip); /** * @brief local_ip * * 获得字串型的本地Ip地址 * * @author jdyu * @date 2004-6-22 * @return int - Return 0 in success, otherwise return error code. * @param char ip[ISP_MAX_IPADDRESS_LEN] - [in,out] 返回ip地址 * @see */ int local_ip(char ip[30]); /** * @brief local_ips * * 获得本地所有IP列表 * * @author jdyu * @date 2004-6-22 * @return int - Return 0 in success, otherwise return error code. * @param str_arr lips - [out] 返回本地所有的IP * @see */ int local_ips(str_arr& lips); int local_ips(unsigned long ipa[], int & count); /** * @brief is_local_host * * 验一个ip是否本机的IP * * @author jdyu * @date 2004-6-22 * @return bool - Return true in success, otherwise return false. * @param unsigned long dwIp - [in,out] * @see */ bool is_local_host(unsigned long ip_addr); bool is_local_host(const char* ip_addr); /** * @brief is_valid_ip_addr * * 判断IP地址是否合法,把那些保留的IP地址排除 * * @author jdyu * @date 2006-1-11 * @return bool - Return TRUE in success, otherwise return FALSE. * @param const char* ip_addr - [in] * @see */ bool is_valid_ip_addr(const char* ip_addr); const char * get_first_valid_ip_addr(const str_arr & ips); /** * @brief get_sub_net * * 得到一个ip地址的网段地址 * * @author jdyu * @date 2006-1-11 * @return int - Return 0 in success, otherwise return error code. * @param const char * ip_addr - [in] * @param std::string & sub_net - [in] * @see */ int get_sub_net_addr(const char * ip_addr, std::string & sub_net); /** * @brief is_network_alive * * 检查网络状态的函数 * * @author jdyu * @date 2006-6-2 * @return bool - Return TRUE in success, otherwise return FALSE. * @param const char * intf - [in] * @see */ bool is_network_alive(const char * intf); } /** * ========================================================================== * Windows特有的一些操作 * 操作系统相关的操作 * ========================================================================== */ namespace sp { /** * @brief get_common_path * * 获得系统Program Files\Common Files目录的路径 * * @author jdyu * @date 2004-7-23 * @return const char* 返回路径 * @see */ const char* get_common_path(void); /** * @brief get_file_strinfo * * 获得可执行文件相关信息 * * @author jdyu * @date 2004-6-22 * @return std::string * @param const char* psz_info - [in] 信息类型,取值类型有: * Comments 注释信息 * CompanyName * FileDescription * FileVersion * InternalName * LegalCopyright * LegalTrademarks * OriginalFilename * ProductName * ProductVersion * PrivateBuild * SpecialBuild * @param const char* file = 0 - [in] 文件路径名 * @see */ std::string get_file_strinfo(const char* psz_info, const char* file = 0); /** * @brief EnableDebugPrivNT * * 调整进程的优先级为Debugger级 * * @author jdyu * @date 2004-6-22 * @return bool - Return true in success, otherwise return false. * @see */ bool EnableDebugPrivNT(void); /** * @brief interact_with_user_open * * 开启本线程和指定用户桌面的交互功能,返回打开的句柄,必须在 * interact_with_user_close函数中释放 * * @author jdyu * @date 2004-11-2 * @return IU_HANDLE 返回本次打开的句柄 * @param const char* stat = "WinSta0" - [in] the user's window station name * @param const char* desk = "Default" - [in] desktop name * @see */ IU_HANDLE interact_with_user_open(const char* stat = "WinSta0", const char* desk = "Default"); /** * @brief interact_with_user_close * * 关闭本线程和指定用户桌面的交互功能 * * @author jdyu * @date 2004-11-2 * @return BOOL - Return TRUE in success, otherwise return FALSE. * @param IU_HANDLE hiwu - [in] 由interact_with_user_open函数返回的句柄 * @see */ bool interact_with_user_close(IU_HANDLE hiwu); // utsname struct utsname { char sysname [257]; char nodename[257]; char release [257]; char version [257]; char machine [257]; }; /** * @brief 获取主机信息 * * 对于Windows操作系统,部分信息是从注册表中读取 * * @author yigao * @date 2004-9-14 * @return int - Return 0 in success, otherwise return error code. * @see */ int uname(utsname * name); /** * @brief error_desc * * 返回错误信息的描述 * * @author jdyu * @date 2004-8-17 * @return const char* * @see */ std::string error_desc(void); }; /** * ========================================================================== * Linux特有的一些操作 * ========================================================================== */ namespace sp { /** * @brief make_daemon * * 生成守护进程,后台运行服务程序 * * @author hjma * @date 2006-2-6 * @see */ int make_daemon(void); /** * @brief get_daemon_pid * * 获取守护进程的id以进行操作 * * @author hjma * @date 2006-2-7 * @see */ long get_daemon_pid(const char* svc_name); }; // 字符串操作的实现放在sputils.i文件,不需要cpp文件 #pragma warning(push) #pragma warning(disable : 4996) #include "sutils.i" #pragma warning(pop) #endif /* __SPUTILS_H__ */
b59d0d124fb41feebd57587229253095b6fa102c
9a32178d3c2fdf377d84f65b55989264e67f40e9
/2002/ALL VC SAMPLES/ATLServer/Server/General/input/input/input.h
637df9ba482867d5197e5eda130f7281c554e2df
[]
no_license
philipwolfe/Samples
5e5cc1376575ac6361b62a3554c98626f153b694
7eb703287a6d07596a141c4557f271efe6c1666f
refs/heads/master
2021-12-25T12:52:52.616313
2021-12-19T04:26:29
2021-12-19T04:26:29
250,445,305
3
1
null
null
null
null
UTF-8
C++
false
false
4,997
h
// input.h : Defines the ATL Server request handler class // // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Classes Reference and related electronic // documentation provided with the library. // See these sources for detailed information regarding the // Microsoft C++ Libraries products. #pragma once #include "validation.h" #include "atlrx.h" //ATL regular expression support [ request_handler("Default") ] class CinputHandler { private: // Put private members here bool valid_input[NUMBER_OF_FORM_VARS]; CString errorMsg; protected: // Put protected members here public: // Put public members here HTTP_CODE ValidateAndExchange() { CAtlRegExp<CAtlRECharTraitsA> atlRegExp; CAtlREMatchContext<CAtlRECharTraitsA> atlRematchContext; const CHttpRequestParams& FormFields = m_HttpRequest.GetFormVars(); //loop through all of the required form variables defined in validation.h for (int i=0; i<NUMBER_OF_FORM_VARS; i++) { CValidateContext c; valid_input[i] = false; //pessimistic approach - assume the input is invalid until proven otherwise //Perform a two-part validation check against this specific form variable // (1) Length - results from built-in Validate() method to enforce string length // (2) Content - regex matching to make sure the string complies with a known good pattern // (1) This built in validation routine validates the string length FormFields.Validate(theForm[i].name, (LPCSTR*)NULL, 0, 256, &c); // (2) Sets up regular expression class to match against the pattern defined for this form variable if (atlRegExp.Parse(theForm[i].atl_regex) != REPARSE_ERROR_OK) return HTTP_FAIL; //server error - theForm[i].at_regex was not a parseable regular expression // Only mark the form variable valid if Validate was successful and the string matches the regular expression. if ( c.ParamsOK() && atlRegExp.Match(FormFields.Lookup(theForm[i].name),&atlRematchContext) ) { //it matched, so the value of this form variable is valid valid_input[i] = true; } else { //failed the test, so append corresponding error message errorMsg += "<li>"; errorMsg += theForm[i].error; errorMsg += "</li>\n"; } } // Set the content-type m_HttpResponse.SetContentType("text/html"); return HTTP_SUCCESS; } [ tag_name(name = "ValidInput") ] HTTP_CODE OnValidInput(void) { //Return true if and only if every form field was validated for (int i=0;i<NUMBER_OF_FORM_VARS;i++) { if (!valid_input[i]) { return HTTP_S_FALSE; } } return HTTP_SUCCESS; } [ tag_name("RegexTests") ] HTTP_CODE OnRegexTests(void) { //loop through and print out regex tests //now output a JScript regular expression based validation test for each form element for (int i=0; i<NUMBER_OF_FORM_VARS; i++) { m_HttpResponse << "\t\t\tif (submission.elements[i].name==\"" << theForm[i].name << "\")\n"; m_HttpResponse << "\t\t\t{\n"; m_HttpResponse << "\t\t\t if (!/" << theForm[i].regex << "/.test(submission.elements[i].value))\n"; m_HttpResponse << "\t\t\t {\n"; m_HttpResponse << "\t\t\t error_message += \"" << theForm[i].error << "\\n\";\n"; m_HttpResponse << "\t\t\t }\n"; m_HttpResponse << "\t\t\t}\n"; } return HTTP_SUCCESS; } [ tag_name(name = "ShowErrors") ] HTTP_CODE OnShowErrors(void) { //Only proceed if form variables were even submitted if ((m_HttpRequest.GetFormVars()).Lookup(theForm[0].name)) { //if an error message was constructed in ValidateAndExchange, display it if (errorMsg.GetLength()>0) { m_HttpResponse << "\n\n<b>Please correct the following errors:</b><ul>" << errorMsg << "</ul>\n\n"; } } return HTTP_SUCCESS; } [ tag_name(name="Input") ] HTTP_CODE OnInput(char * inputName) { //this function shields the HTML designer from the input element details if (!strncmp(inputName,"Title",5)) { //build a select box using the titles array (from validation.h) m_HttpResponse << "<select name=\"Title\">\n"; for (int i=0; i<(sizeof(titles)/sizeof(char*)); i++) { m_HttpResponse << "\t<option value=\"" << titles[i] << "\">" << titles[i] << "</option>\n"; } m_HttpResponse << "</select>"; return HTTP_SUCCESS; } else if (!strncmp(inputName,"State",5)) { //create a dropdown select box based on the values supplied in validation.h m_HttpResponse << "<select name=\"State\">\n"; for (int i=0; i<(sizeof(postalCodeValues)/sizeof(char*)); i++) { m_HttpResponse << "\t<option value=\"" << postalCodeValues[i] << "\">" << postalCodeNames[i] << "</option>\n"; } m_HttpResponse << "</select>"; return HTTP_SUCCESS; } else { //all the other input types in this form are simple input boxes m_HttpResponse << "<input name=\"" << inputName << "\">"; return HTTP_SUCCESS; } } }; // class CinputHandler
db14686443a788828de40858a66f9e3815d1f700
2f213caa34d1d6981b1308de71102bcc84ff38a9
/5term/EVM/lab8/Form1.h
db15e7589d9ad803a917de9a57b62d7520417eba
[]
no_license
kilel/Study
d38ad39aae77fef92e187b8f30891a3b642095fd
2d270176f61aaac96d5cab3c342622f5b3b9480d
refs/heads/master
2021-01-19T08:26:05.142277
2014-05-18T21:03:18
2014-05-18T21:03:18
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
20,664
h
#pragma once #define pi 3.14159265358979323 namespace lab1 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Сводка для Form1 /// /// Внимание! При изменении имени этого класса необходимо также изменить /// свойство имени файла ресурсов ("Resource File Name") для средства компиляции управляемого ресурса, /// связанного со всеми файлами с расширением .resx, от которых зависит данный класс. В противном случае, /// конструкторы не смогут правильно работать с локализованными /// ресурсами, сопоставленными данной форме. /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); canvas = gcnew Bitmap(pic->Height, pic->Width+10); // g = pic->CreateGraphics();; g = g->FromImage(canvas); n = 10; n_t = 10; max = n*1.25; may = 0; /*y = new double*[n_t]; for(int i = 0; i < n_t; i++) y[i] = new double[n];*/ c = gcnew Point(0,0); last_m = 1; c->X = pic->Height/6.0; c->Y = pic->Height*(5/6.); y1 = gcnew array<double>(n); y2 = gcnew array<double>(n); } protected: /// <summary> /// Освободить все используемые ресурсы. /// </summary> ~Form1() { if (components) { delete components; } } protected: protected: private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::PictureBox^ pic; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::Label^ label19; private: System::Windows::Forms::RichTextBox^ richTextBox2; private: System::Windows::Forms::NumericUpDown^ B; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::NumericUpDown^ epsilon; private: System::Windows::Forms::CheckBox^ checkBox1; private: System::Windows::Forms::Timer^ timer; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::CheckBox^ checkBox2; private: System::Windows::Forms::TrackBar^ track; private: System::Windows::Forms::NumericUpDown^ delta; private: System::ComponentModel::IContainer^ components; private: /// <summary> /// Требуется переменная конструктора. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); this->pic = (gcnew System::Windows::Forms::PictureBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->label19 = (gcnew System::Windows::Forms::Label()); this->richTextBox2 = (gcnew System::Windows::Forms::RichTextBox()); this->B = (gcnew System::Windows::Forms::NumericUpDown()); this->label6 = (gcnew System::Windows::Forms::Label()); this->epsilon = (gcnew System::Windows::Forms::NumericUpDown()); this->checkBox1 = (gcnew System::Windows::Forms::CheckBox()); this->timer = (gcnew System::Windows::Forms::Timer(this->components)); this->label3 = (gcnew System::Windows::Forms::Label()); this->button3 = (gcnew System::Windows::Forms::Button()); this->checkBox2 = (gcnew System::Windows::Forms::CheckBox()); this->track = (gcnew System::Windows::Forms::TrackBar()); this->delta = (gcnew System::Windows::Forms::NumericUpDown()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pic))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->B))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->epsilon))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->track))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->delta))->BeginInit(); this->SuspendLayout(); // // button2 // this->button2->Location = System::Drawing::Point(557, 12); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(244, 52); this->button2->TabIndex = 1; this->button2->Text = L"Неявная хема"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click); // // button4 // this->button4->Location = System::Drawing::Point(557, 70); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(244, 23); this->button4->TabIndex = 1; this->button4->Text = L"Пройти сквозь время"; this->button4->UseVisualStyleBackColor = true; this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click); // // pic // this->pic->Location = System::Drawing::Point(0, 0); this->pic->Name = L"pic"; this->pic->Size = System::Drawing::Size(537, 524); this->pic->TabIndex = 4; this->pic->TabStop = false; this->pic->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::pic_MouseMove); this->pic->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::pic_MouseDown); this->pic->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::pic_MouseUp); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(554, 156); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(53, 13); this->label1->TabIndex = 6; this->label1->Text = L"Масштаб"; // // label2 // this->label2->AutoSize = true; this->label2->Location = System::Drawing::Point(11, 499); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(0, 13); this->label2->TabIndex = 7; // // label19 // this->label19->AutoSize = true; this->label19->Location = System::Drawing::Point(554, 210); this->label19->Name = L"label19"; this->label19->Size = System::Drawing::Size(106, 13); this->label19->TabIndex = 10; this->label19->Text = L"Функция для Maple"; // // richTextBox2 // this->richTextBox2->Location = System::Drawing::Point(568, 226); this->richTextBox2->Name = L"richTextBox2"; this->richTextBox2->Size = System::Drawing::Size(224, 286); this->richTextBox2->TabIndex = 9; this->richTextBox2->Text = L""; // // B // this->B->DecimalPlaces = 1; this->B->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 65536}); this->B->Location = System::Drawing::Point(662, 154); this->B->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {9999999, 0, 0, 0}); this->B->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 65536}); this->B->Name = L"B"; this->B->Size = System::Drawing::Size(84, 20); this->B->TabIndex = 11; this->B->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 0}); this->B->ValueChanged += gcnew System::EventHandler(this, &Form1::B_ValueChanged); // // label6 // this->label6->AutoSize = true; this->label6->Location = System::Drawing::Point(554, 130); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(33, 13); this->label6->TabIndex = 6; this->label6->Text = L"Шаги"; // // epsilon // this->epsilon->DecimalPlaces = 9; this->epsilon->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 458752}); this->epsilon->Location = System::Drawing::Point(593, 128); this->epsilon->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {9999999, 0, 0, 0}); this->epsilon->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) {9999999, 0, 0, System::Int32::MinValue}); this->epsilon->Name = L"epsilon"; this->epsilon->Size = System::Drawing::Size(86, 20); this->epsilon->TabIndex = 5; this->epsilon->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 65536}); this->epsilon->ValueChanged += gcnew System::EventHandler(this, &Form1::epsilon_ValueChanged); // // checkBox1 // this->checkBox1->AutoSize = true; this->checkBox1->Location = System::Drawing::Point(716, 206); this->checkBox1->Name = L"checkBox1"; this->checkBox1->Size = System::Drawing::Size(76, 17); this->checkBox1->TabIndex = 12; this->checkBox1->Text = L"Выводить"; this->checkBox1->UseVisualStyleBackColor = true; // // timer // this->timer->Tick += gcnew System::EventHandler(this, &Form1::timer_Tick); // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(11, 463); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(0, 13); this->label3->TabIndex = 6; // // button3 // this->button3->Location = System::Drawing::Point(557, 99); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(244, 23); this->button3->TabIndex = 1; this->button3->Text = L"Стоп!"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click); // // checkBox2 // this->checkBox2->AutoSize = true; this->checkBox2->Location = System::Drawing::Point(557, 183); this->checkBox2->Name = L"checkBox2"; this->checkBox2->Size = System::Drawing::Size(185, 17); this->checkBox2->TabIndex = 12; this->checkBox2->Text = L"Результат - кривая во времени"; this->checkBox2->UseVisualStyleBackColor = true; // // track // this->track->LargeChange = 1; this->track->Location = System::Drawing::Point(0, 479); this->track->Name = L"track"; this->track->Size = System::Drawing::Size(537, 45); this->track->TabIndex = 13; this->track->Scroll += gcnew System::EventHandler(this, &Form1::track_Scroll); // // delta // this->delta->DecimalPlaces = 9; this->delta->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 458752}); this->delta->Location = System::Drawing::Point(706, 128); this->delta->Maximum = System::Decimal(gcnew cli::array< System::Int32 >(4) {9999999, 0, 0, 0}); this->delta->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) {9999999, 0, 0, System::Int32::MinValue}); this->delta->Name = L"delta"; this->delta->Size = System::Drawing::Size(86, 20); this->delta->TabIndex = 5; this->delta->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) {1, 0, 0, 65536}); this->delta->ValueChanged += gcnew System::EventHandler(this, &Form1::epsilon_ValueChanged); // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackColor = System::Drawing::Color::White; this->ClientSize = System::Drawing::Size(804, 522); this->Controls->Add(this->track); this->Controls->Add(this->checkBox2); this->Controls->Add(this->checkBox1); this->Controls->Add(this->B); this->Controls->Add(this->label19); this->Controls->Add(this->richTextBox2); this->Controls->Add(this->label2); this->Controls->Add(this->label6); this->Controls->Add(this->label3); this->Controls->Add(this->label1); this->Controls->Add(this->delta); this->Controls->Add(this->epsilon); this->Controls->Add(this->pic); this->Controls->Add(this->button3); this->Controls->Add(this->button4); this->Controls->Add(this->button2); this->Name = L"Form1"; this->Text = L"Form1"; this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load); this->Shown += gcnew System::EventHandler(this, &Form1::Form1_Load); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pic))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->B))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->epsilon))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->track))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->delta))->EndInit(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion public: Bitmap^canvas; double tau,h; Graphics^ g; bool ch_c; int n, n_t; int index; double last_m; array<double>^x, ^t, ^y1, ^y2, ^y3, ^y4; array<array<double>^>^y; Point^ c; //центр int m; double max, may; //max по x и y array<double>^p; //полином итоговый array<double>^pr; array<double>^_a,^_b,^_c; private: double evalf(double d) { return ((double)((int)(d*100000))/100000); } String^ dbl(double d) { String^s; long long k = d; long long p = Math::Abs((d-k)*100000); s = "" + k + "."; if(p < 10) s += "0000"; else if(p < 100) s += "000"; else if(p < 1000) s += "00"; else if(p < 10000) s += "0"; s+= ""+p; return s; } int pow_one(int n) { if(n%2 == 0) return 1; else return -1; } void draw_polinom(array<double>^p, int s, int f, Pen ^pen) {//отрисовка полинома double temp; int l = 2; array<Point>^res = gcnew array<Point>(l); for(int i = 0; i < l; i++) res[i].X = c->X + (x[s]+ i*(x[f]-x[s]))*m*10/max; for(int i = 0; i < l; i++) { temp = 0; for(int j = 0; j < p->Length; j++) temp = temp + Math::Pow(x[s]+ i*(x[f]-x[s]), j)*p[j]; res[i].Y = c->Y - temp*m*10/may; } g->DrawLines(pen, res); pic->Image = canvas; } void draw_coord() {//отрисовка осей m = 22; g->DrawLine(Pens::Black, c->X, pic->Width - 40, c->X, 10); g->DrawLine(Pens::Black, c->X + 5, 20, c->X, 10); g->DrawLine(Pens::Black, c->X - 5, 20, c->X, 10); g->DrawLine(Pens::Black, 10, c->Y, pic->Width - 20, c->Y); g->DrawLine(Pens::Black, pic->Width - 30, c->Y + 5, pic->Width - 20, c->Y); g->DrawLine(Pens::Black, pic->Width - 30, c->Y - 5, pic->Width - 20, c->Y); for(int i = (-c->X/m)*2; i <= 2*(pic->Width-c->X)/m; i++) { g->DrawString(""+evalf(2*i*max/10.),this->Font, Brushes::Black, c->X + 2*i*m + 5, c->Y + 7); g->DrawLine(Pens::Black, c->X + i*m, c->Y + 2, c->X +i*m, c->Y - 2); g->DrawLine(Pens::Black, c->X + 2*i*m, c->Y + 4, c->X + 2*i*m, c->Y - 4); } for(int i = - c->Y/m; i <= (pic->Width-c->Y)/m; i++) { if(i) g->DrawString(""+evalf(2*i*(-may/10.)),this->Font, Brushes::Black, c->X +4 , c->Y + 2*i*m + 5); g->DrawLine(Pens::Black, c->X + 2, c->Y + 2*i*m, c->X - 2, c->Y + 2*i*m); } pic->Image = canvas; } void Form1_Load(System::Object^ sender, System::EventArgs^ e) { button1_Click(sender,e); } void draw_y(int i_t) { if(checkBox2->Checked == true) { g->Clear(Color::White); draw_coord(); } if(n > 100) for(int i = 0; i+n/40. < n; i+=n/40.) { g->DrawLine(Pens::Red, (int)(c->X + (double)h*(i)*m*10/max), c->Y - y[i][i_t]*m*10/may, c->X+ h*(i+n/40)*m*10/max, c->Y - y[i+n/40][i_t]*m*10/may); } else for(int i = 0; i < n-1; i++) { g->DrawLine(Pens::Red, (int)(c->X + (double)h*(i)*m*10/max), c->Y - y[i][i_t]*m*10/may, c->X+ h*(i+1)*m*10/max, c->Y - y[i+1][i_t]*m*10/may); } g->DrawLine(Pens::Gray, (int)(c->X + (double)2*m*10/max), c->Y - 20*m*10/may, c->X + 2*m*10/max, c->Y ); pic->Image = canvas; } void impl(double eps, double delta) { h = eps; tau = delta; double alpha = 4*(h*h)/(tau*tau); n = 2/h + 1; n_t = 1/tau + 1; if(y) delete y; x = gcnew array<double>(n); //y = new double*[n]; y = gcnew array<array<double>^>(n); t = gcnew array<double>(n); //double y[100][100] = {0}; for(int i = 0; i < n; i++) y[i] = gcnew array<double>(n_t); for(int i = 0; i < n; i++) for(int j = 0; j < n_t; j++) y[i][j] = 0; for(int i = 0; i < n; i++) for(int j = 0; j < n_t; j++) { y[0][j] = 5*j*tau; //5*y y[i][0] = i*h; //x y[i][n_t-1] = 5 - i*h; //5-x y[n-1][j] = 2 + j*tau; //2+y /*y[0][j] = 1; //5*y y[i][0] = 1; //x y[i][n_t-1] = 1; //5-x y[n-1][j] = 1; //2+y */ } for(int k = 0; k < 1000; k++) for(int i = 1; i < n-1; i++) for(int j = 1; j < n_t-1; j++) y[i][j] = (1./(2+2*alpha))*(y[i-1][j] + alpha*(y[i][j+1] + y[i][j-1]) + y[i+1][j] - h*h*Math::Sin(i*j*tau*h)); if(checkBox1->Checked == true) { String^ s = "INTERFACE_PLOT3D(GRID(0. .. 2.,0. .. 1.,Array(1.." + n + ", 1.." + n_t +", ["; for(int i = 0; i < n-1; i++) { s+= "["; for(int j = 0; j < n_t-1; j++) s += "" + dbl(evalf(y[i][j])) + ", "; s += "" + dbl(evalf(y[i][n_t-1])); s += "],\n"; } s+= "["; for(int j = 0; j < n_t-1; j++) s += "" + dbl(evalf(y[n-1][j])) + ", "; s += "" + dbl(evalf(y[n-1][n_t-1])); s += "]\n"; s += "], datatype = float[8], order = C_order)),AXESLABELS(x,t,\"\"));"; richTextBox2->Text = s; } max = 1/last_m; may = 2/last_m; track->Maximum = n_t-1; draw_y(0); pic->Image = canvas; } void button1_Click(System::Object^ sender, System::EventArgs^ e) { g->Clear(Color::White); draw_coord(); impl(Convert::ToDouble(epsilon->Value.ToString()),Convert::ToDouble(delta->Value.ToString())); draw_coord(); track->Value = 0; } void button2_Click(System::Object^ sender, System::EventArgs^ e) { draw_coord(); g->Clear(Color::White); draw_coord(); impl(Convert::ToDouble(epsilon->Value.ToString()),Convert::ToDouble(delta->Value.ToString())); track->Value = 0; } void button3_Click(System::Object^ sender, System::EventArgs^ e) { timer->Stop(); } void button4_Click(System::Object^ sender, System::EventArgs^ e) { index = 0; timer->Start(); } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { g->Clear(Color::White); } void B_ValueChanged(System::Object^ sender, System::EventArgs^ e) { max = max*last_m; may = may*last_m; last_m = Convert::ToDouble( (B->Value.ToString())); max = max/last_m; may = may/last_m; g->Clear(Color::White); draw_coord(); draw_y(index); } void pic_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { ch_c = true; } void pic_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { if(ch_c) { c->X = e->X; c->Y = e->Y; } g->Clear(Color::White); draw_coord(); draw_y(index); } void pic_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { ch_c = false; } void timer_Tick(System::Object^ sender, System::EventArgs^ e) { if(n_t > 200) index += n_t/200; else index++; if(index >= n_t) { index = n_t-1; timer->Stop(); return; } draw_y(index); label3->Text = "t = " + (tau*(index)); track->Value = index; } void track_Scroll(System::Object^ sender, System::EventArgs^ e) { index = track->Value; draw_y(index); label3->Text = "t = " + (tau*(index)); } private: System::Void epsilon_ValueChanged(System::Object^ sender, System::EventArgs^ e) { } }; }
31f1190a8abaa5193eedbc4fc4118c84ffdcf618
ca32936825c3cbae13e4db108ad97d670e0a9264
/oce-0.17/include/oce/math_MultipleVarFunctionWithHessian.hxx
9604328b167b9b291e41e9751cd7f7a70e519d6f
[]
no_license
zqqiang/node-cad
7b783fb758dcacb5b1e1b8276c73dfe0942adfbb
739ff348b4d2c77b275c3a0fe87682c14ffd8181
refs/heads/master
2021-01-14T08:03:53.991041
2016-12-23T19:07:33
2016-12-23T19:07:33
46,592,925
5
0
null
null
null
null
UTF-8
C++
false
false
2,306
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _math_MultipleVarFunctionWithHessian_HeaderFile #define _math_MultipleVarFunctionWithHessian_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Macro.hxx> #include <math_MultipleVarFunctionWithGradient.hxx> #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> #include <math_Vector.hxx> #include <Standard_Real.hxx> class math_Matrix; class math_MultipleVarFunctionWithHessian : public math_MultipleVarFunctionWithGradient { public: DEFINE_STANDARD_ALLOC Standard_EXPORT virtual void Delete() ; Standard_EXPORT virtual ~math_MultipleVarFunctionWithHessian(){Delete();} //! returns the number of variables of the function. Standard_EXPORT virtual Standard_Integer NbVariables() const = 0; //! computes the values of the Functions <F> for the //! variable <X>. //! Returns True if the computation was done successfully, //! False otherwise. Standard_EXPORT virtual Standard_Boolean Value (const math_Vector& X, Standard_Real& F) = 0; //! computes the gradient <G> of the functions for the //! variable <X>. //! Returns True if the computation was done successfully, //! False otherwise. Standard_EXPORT virtual Standard_Boolean Gradient (const math_Vector& X, math_Vector& G) = 0; //! computes the value <F> and the gradient <G> of the //! functions for the variable <X>. //! Returns True if the computation was done successfully, //! False otherwise. Standard_EXPORT virtual Standard_Boolean Values (const math_Vector& X, Standard_Real& F, math_Vector& G) = 0; //! computes the value <F>, the gradient <G> and the //! hessian <H> of the functions for the variable <X>. //! Returns True if the computation was done //! successfully, False otherwise. Standard_EXPORT virtual Standard_Boolean Values (const math_Vector& X, Standard_Real& F, math_Vector& G, math_Matrix& H) = 0; protected: private: }; #endif // _math_MultipleVarFunctionWithHessian_HeaderFile
7b0e044a5431025ff3251abb8ae7ae82f2d4466d
46ea7fbb88f0ecb9a7e64ec9ad773dba6d67de85
/Programming_Assignments/Week_1/hexText.cpp
5d17c33b299ee677f83fff034b3d9ca7adfc7ff3
[]
no_license
dan13ram/Cryptography_Coursera
6f1ea488d29dacd72de9b893ae2f10b3875eb9fb
92ceacede2ede905b84890f1225707ee8e77015b
refs/heads/master
2021-01-17T20:57:33.359937
2016-07-22T18:44:28
2016-07-22T18:44:28
63,975,815
0
0
null
null
null
null
UTF-8
C++
false
false
6,173
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #include<string> using namespace std; int value(char c){ if(c>='0' && c<='9') return (int)(c-'0'); else if(c>='a' && c<='f') return (int)(c-'a') + 10; else if(c>='A' && c<='F') return (int)(c-'A') + 10; else return (-1); } string textHex(string str){ string a; char b[3]; for(int i=0;i<str.size();i++){ sprintf(b,"%x",(int)str[i]); a+=string(b); } return a; } string hexText(string str){ string a; int k=0; for(int i=0;i<str.size();i+=2){ //a[k++]=(char)(value(str[i])*16+value(str[i+1])); a+=string(1,(char)(value(str[i])*16+value(str[i+1]))); } return a; } string text_xor(string hex1, string hex2){ const char alphabet[] = "0123456789abcdef"; int l1=hex1.size(),l2=hex2.size(); int maxl=l1; if(l1>l2){ maxl=l1; hex2+=string(l1-l2,'0'); } else{ maxl=l2; hex1+=string(l2-l1,'0'); } for(int i=0;i<maxl;i++){ unsigned int v=value(hex1[i])^value(hex2[i]); hex1[i]=alphabet[v]; } return hex1; } int main(){ string cypher[11]; cypher[0]="315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e"; cypher[1]="234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f"; cypher[2]="32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb"; cypher[3]="32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa"; cypher[4]="3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070"; cypher[5]="32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4"; cypher[6]="32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce"; cypher[7]="315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3"; cypher[8]="271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027"; cypher[9]="466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83"; cypher[10]="32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904"; int i=0,j=0; cout<<endl<<"Enter 2 numbers: "; cin>>i>>j; string c; c=text_xor(cypher[i],cypher[j]); //cout<<"The xor of cypher["<<i<<"] and cypher ["<<j<<"] is : "<<c<<endl; //cout<<"text of xor : "<<hexText(c)<<endl; string a,the,newt,test; //a = " the "; //a = " cryptography"; //2 //a = "s theorem be"; //1 //a = "encryption algorithm"; //3 //a="w his theorem becomes"; //1 //a=" would probably enjoy that now his theorem becomes a corner "; //1 //a="p is unhappy if a wrong"; //7 //a="y - that which will kee"; //5 //a="encryption algorithm loo"; //3 //a ="6) defines crypto as the "; //9 //a="quantum computers. We can"; //0 //a=" now we cryptographers can"; //2 //a="graphy: one that allows the G"; //6 //a=" that now his theorem becomes a"; //1 //a=" cryptography - that which will keep "; //5 //a="duced by a weak encryption algorithm look"; //3 //a=" want to buy a set of car keys from a guy who speciali"; //4 //a=" cyphertext produced by a weak encryption algorithm looks as"; //3 //a="n factor the number 15 with quantum computers. We can also find "; //0 //a=" nice thing about Keeyloq is now we cryptographers can drive a "; //2 //a="We can factor the number 15 with quantum computers. We can also factor "; //0 //a="The nice thing about Keeyloq is now we cryptographers can drive a lot of "; //2 //a="You don't want to buy a set of car keys from a guy who specializes in stealing ";//4 //a="We can factor the number 15 with quantum computers. We can also factor the number "; //0 //a="There are two types of cyptography: one that allows the Government to use brute force to "; //6 //a="The ciphertext produced by a weak encryption algorithm looks as good as ciphertext produced by "; //3 a="There are two types of cyptography: one that allows the Government to use brute force to break the code, and one that requires the Government to use brute force to break you."; //6 the = textHex(a); //cout<<" the = '"<<the<<"'"<<endl<<endl; int k=0; //for(k=0; k<c.size(); k+=2) //{ newt=c.substr(k,the.size()); test=hexText(text_xor(newt,the)); cout<<"k is "<<k<<" and xor = '"<<test<<"'"<<endl<<endl; //} //cout<<"'"<<hexText(c)<<"'"<<endl; return 0; }
2e990ba7a8a06642875ace9008525637b83784b1
c6bddd88916e6c8697a9e02485bd22c58d76bcec
/GeneratedPlaceholders/SlateCore/FontProviderInterface.h
869745f511e3e334022f002597077389eb43b1c2
[]
no_license
GIRU-GIRU/Mordhau-Unofficial-SDK
18d13d62d746a838820e387907d13b0a37aed654
f831d7355cf553b81fb6e82468b3abf68f7955aa
refs/heads/master
2020-07-06T03:36:48.908227
2020-04-22T13:54:00
2020-04-22T13:54:00
202,872,898
7
4
null
null
null
null
UTF-8
C++
false
false
175
h
#pragma once #include "CoreMinimal.h" #include "FontProviderInterface.generated.h" UCLASS() class UFontProviderInterface : public UInterface { GENERATED_BODY() public: };
0e0557718d280e518b5ec2074559503404d82672
903855cbeb65affd6620ded59191c8a8b8d1df45
/Zarubin/2 sem/Sort/heap/main.cpp
516efa7fb8df29a5629d3156d38a2b5a62751e2e
[ "MIT" ]
permissive
soomrack/MR2020
260b2ff093ab39c48d3cfa18e0c1c0b3859bd1e0
2de7289665dcdac4a436eb512f283780aa78cb76
refs/heads/master
2023-04-26T15:11:08.607185
2021-05-24T11:02:34
2021-05-24T11:02:34
293,246,956
4
0
MIT
2021-02-21T10:29:12
2020-09-06T09:50:17
C++
UTF-8
C++
false
false
949
cpp
#include <iostream> using namespace std; void heapify(int arr[], int n, int root) { int largest = root; int l = 2*root + 1; int r = 2*root + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != root) { swap(arr[root], arr[largest]); heapify(arr, n, largest); } } void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i=n-1; i>=0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } } void displayArray(int arr[], int n) { for (int i=0; i<n; ++i) cout << arr[i] << " "; cout << "\n"; } int main() { int heap_arr[] = {4,17,3,12,9,6}; int n = sizeof(heap_arr)/sizeof(heap_arr[0]); cout<<"Input array"<<endl; displayArray(heap_arr,n); heapSort(heap_arr, n); cout << "Sorted array"<<endl; displayArray(heap_arr, n); }
28e578f120292051fc5161a6a700ade097cdeed2
07a6d52682a2c60730f536703a6031b4ece973bf
/librf/src/rf_task.h
9f0fc4603d48c8304e15ef8594cb255ef2a5f34e
[ "Apache-2.0" ]
permissive
tiSan2021/librf
caa1be32d86ba820424854878c7d18a8d850a307
67a3e653ed196509280e77b03fae2bc191108b49
refs/heads/master
2021-10-28T10:16:34.104642
2017-09-24T06:36:36
2017-09-24T06:36:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,488
h
#pragma once #include "def.h" #include "future.h" namespace resumef { struct task_base; struct task_base { RF_API task_base(); RF_API virtual ~task_base(); //如果返回true,则不会调用go_next() virtual bool is_suspend() = 0; //返回true,表示任务还未完成,后续还需要继续执行 //否则,任务从调度器里删除 virtual bool go_next(scheduler *) = 0; virtual void cancel() = 0; virtual void * get_id() = 0; }; //---------------------------------------------------------------------------------------------- template<class _Ty> struct task_t; //co_task接受的是一个experimental::generator<_Ty>类型,是调用一个支持异步的函数后返回的结果 template<class _Ty> struct task_t<std::experimental::generator<_Ty> > : public task_base { typedef std::experimental::generator<_Ty> future_type; typedef typename future_type::iterator iterator_type; future_type _future; iterator_type _iterator; bool _ready; task_t() : _iterator(nullptr) , _ready(false) { } task_t(future_type && f) : _future(std::forward<future_type>(f)) , _iterator(nullptr) , _ready(false) { } virtual bool is_suspend() override { return false; } virtual bool go_next(scheduler *) override { if (!this->_ready) { this->_iterator = this->_future.begin(); this->_ready = true; } if (this->_iterator != this->_future.end()) { return (++this->_iterator) != this->_future.end(); } return false; } virtual void cancel() override { } virtual void * get_id() override { return nullptr; } }; template<class _Ty> struct task_t<future_t<_Ty> > : public task_base { typedef future_t<_Ty> future_type; future_type _future; task_t() = default; task_t(future_type && f) : _future(std::forward<future_type>(f)) { } //如果返回true,则不会调用go_next() // //如果第一次运行,则state应该有: // _coro != nullptr // _ready == false //运行一次后,则state应该是: // _coro == nullptr // _ready == false //最后一次运行,则state应该是: // _coro == nullptr // _ready == true virtual bool is_suspend() override { auto * _state = _future._state.get(); return _state->is_suspend(); } //返回true,表示任务还未完成,后续还需要继续执行 //否则,任务从调度器里删除 virtual bool go_next(scheduler * schdler) override { auto * _state = _future._state.get(); _state->resume(); return !_state->ready() && !_state->_done; } virtual void cancel() override { _future.cancel(); } virtual void * get_id() override { return _future._state.get(); } }; //---------------------------------------------------------------------------------------------- //co_task_with_ctx接受的是一个'函数对象' //这个'函数对象'被调用后,返回generator<_Ty>/future_t<_Ty>类型 //然后'函数对象'作为异步执行的上下文状态保存起来 template<class _Ctx> struct ctx_task_t : public task_t<typename std::result_of<_Ctx()>::type> { typedef _Ctx context_type; context_type _context; ctx_task_t(context_type && ctx) : _context(std::forward<context_type>(ctx)) { _future = std::move(_context()); } }; }
840fb1db61c54508165225200a0160c32a3bb35d
fd557613ae16a9c8851a03a9b7216aa606fa87fc
/MGCommon/src/cbbItems/gymnastselectionlist.h
f4dfc4ed8b4c3909088331efe0d9e8238019217d
[]
no_license
Caleg74/MemorialGander
3bf7511f8cf5977521b4689b977f1f313a3b656d
df34e0b19f4a8f33113a83e5001f5467bebf969e
refs/heads/master
2023-02-22T23:14:16.426617
2023-02-15T10:25:41
2023-02-15T10:25:41
49,271,790
0
0
null
null
null
null
UTF-8
C++
false
false
490
h
#ifndef GYMNASTSELECTIONLIST_H #define GYMNASTSELECTIONLIST_H #include "comboboxmodel.h" #include <QQmlApplicationEngine> class GymnastSelectionList { public: static GymnastSelectionList* Instance(); /** Initializes the core application components */ void Init(QQmlApplicationEngine &p_qEngine); void FillList(); private: GymnastSelectionList(); static GymnastSelectionList* sm_pInstance; ComboBoxModel m_cCbbModel; }; #endif // GYMNASTSELECTIONLIST_H
38e8d71c17c30033dea61d5b6cd49214006c2923
ed1dacfb083d8344e51b9243064df9bd05e428c5
/j-1285/0060.cpp
9926edd52d086d42a77a44a71f53ea047d54c9ee
[]
no_license
2Choi/cpp
8016bb23a222407e0628d7156ffd760f2b38c873
3a5e59c1edbb1afe920fa27552cc48ef5b5c25d6
refs/heads/master
2021-01-13T00:37:19.679180
2016-04-20T12:46:52
2016-04-20T12:46:52
46,797,824
0
0
null
null
null
null
UTF-8
C++
false
false
850
cpp
#include<stdio.h> int main() { int n, i, j, x, y; int a[20][20]={}; for(i=0; i<19; i++) { for(j=0; j<19; j++) { scanf("%d", &a[i][j]); } } scanf("%d", &n); for(i=0; i<n; i++) { scanf("%d %d", &x, &y); for(j=0; j<19; j++) { if(a[x-1][j]==0) { a[x-1][j]=1; } else { a[x-1][j] = 0; } } for(j=0; j<19; j++) { if(a[j][y-1]==0) { a[j][y-1]=1; } else { a[j][y-1] = 0; } } } for(i=0; i<19; i++) { for(j=0; j<19; j++) { printf("%d ", a[i][j]); } printf("\n"); } }
2473862d737296f9ff59869082a37e91d91ef8de
627d4d432c86ad98f669214d9966ae2db1600b31
/src/tools/uic/treewalker.h
0d16d2e930813adcf03790316c3b9733fe0babe1
[]
no_license
fluxer/copperspice
6dbab905f71843b8a3f52c844b841cef17f71f3f
07e7d1315d212a4568589b0ab1bd6c29c06d70a1
refs/heads/cs-1.1
2021-01-17T21:21:54.176319
2015-08-26T15:25:29
2015-08-26T15:25:29
39,802,091
6
0
null
2015-07-27T23:04:01
2015-07-27T23:04:00
null
UTF-8
C++
false
false
4,156
h
/*********************************************************************** * * Copyright (c) 2012-2015 Barbara Geller * Copyright (c) 2012-2015 Ansel Sermersheim * Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies). * Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * This file is part of CopperSpice. * * CopperSpice is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * CopperSpice 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 CopperSpice. If not, see * <http://www.gnu.org/licenses/>. * ***********************************************************************/ #ifndef TREEWALKER_H #define TREEWALKER_H #include <QtCore/QList> QT_BEGIN_NAMESPACE class DomUI; class DomLayoutDefault; class DomLayoutFunction; class DomTabStops; class DomLayout; class DomLayoutItem; class DomWidget; class DomSpacer; class DomColor; class DomColorGroup; class DomPalette; class DomFont; class DomPoint; class DomRect; class DomSizePolicy; class DomSize; class DomDate; class DomTime; class DomDateTime; class DomProperty; class DomCustomWidgets; class DomCustomWidget; class DomAction; class DomActionGroup; class DomActionRef; class DomImages; class DomImage; class DomItem; class DomIncludes; class DomInclude; class DomString; class DomResourcePixmap; class DomResources; class DomResource; class DomConnections; class DomConnection; class DomConnectionHints; class DomConnectionHint; class DomScript; class DomButtonGroups; class DomButtonGroup; struct TreeWalker { inline virtual ~TreeWalker() {} virtual void acceptUI(DomUI *ui); virtual void acceptLayoutDefault(DomLayoutDefault *layoutDefault); virtual void acceptLayoutFunction(DomLayoutFunction *layoutFunction); virtual void acceptTabStops(DomTabStops *tabStops); virtual void acceptCustomWidgets(DomCustomWidgets *customWidgets); virtual void acceptCustomWidget(DomCustomWidget *customWidget); virtual void acceptLayout(DomLayout *layout); virtual void acceptLayoutItem(DomLayoutItem *layoutItem); virtual void acceptWidget(DomWidget *widget); virtual void acceptSpacer(DomSpacer *spacer); virtual void acceptColor(DomColor *color); virtual void acceptColorGroup(DomColorGroup *colorGroup); virtual void acceptPalette(DomPalette *palette); virtual void acceptFont(DomFont *font); virtual void acceptPoint(DomPoint *point); virtual void acceptRect(DomRect *rect); virtual void acceptSizePolicy(DomSizePolicy *sizePolicy); virtual void acceptSize(DomSize *size); virtual void acceptDate(DomDate *date); virtual void acceptTime(DomTime *time); virtual void acceptDateTime(DomDateTime *dateTime); virtual void acceptProperty(DomProperty *property); typedef QList<DomScript *> DomScripts; typedef QList<DomWidget *> DomWidgets; virtual void acceptWidgetScripts(const DomScripts &, DomWidget *node, const DomWidgets &childWidgets); virtual void acceptImages(DomImages *images); virtual void acceptImage(DomImage *image); virtual void acceptIncludes(DomIncludes *includes); virtual void acceptInclude(DomInclude *incl); virtual void acceptAction(DomAction *action); virtual void acceptActionGroup(DomActionGroup *actionGroup); virtual void acceptActionRef(DomActionRef *actionRef); virtual void acceptConnections(DomConnections *connections); virtual void acceptConnection(DomConnection *connection); virtual void acceptConnectionHints(DomConnectionHints *connectionHints); virtual void acceptConnectionHint(DomConnectionHint *connectionHint); virtual void acceptButtonGroups(const DomButtonGroups *buttonGroups); virtual void acceptButtonGroup(const DomButtonGroup *buttonGroup); }; QT_END_NAMESPACE #endif // TREEWALKER_H
6cd010ff530e91b7eee3f34d1eed1d5362a7f5f2
c844665c3a4ae3d3ce737d16c7974f729497d0ee
/include/BehaviorTree/ConditionalDecorator.h
e1e8b488f08ee7589fabc562ae76a95a7da87668
[ "BSD-2-Clause" ]
permissive
forkrp/Enjon
de642b38ab6c9cac3d69bf7a624f3588a24b8c9a
405733f1b8d05c65bc6b4f4c779d3c6845a8c12b
refs/heads/master
2022-03-14T00:34:50.930488
2019-11-18T15:58:23
2019-11-18T15:58:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,942
h
#ifndef ENJON_CONDITIONAL_DECORATOR_H #define ENJON_CONDITIONAL_DECORATOR_H #include "BehaviorNode.h" namespace BT { class ConditionalDecorator : public Decorator<ConditionalDecorator> { public: ConditionalDecorator(BlackBoard* BB, bool (*A)(BlackBoard* BB)) { Action = A; this->BB = BB; Init(); } ConditionalDecorator(BehaviorTree* BT, bool (*A)(BlackBoard* BB)) { Action = A; this->BTree = BT; Init(); } void Init() { State = BehaviorNodeState::INVALID; Child = nullptr; Type = BehaviorNodeType::DECORATOR; } std::string String() { return std::string("ConditionalDecorator"); } BehaviorNodeState Run() { // Get State Object from BlackBoard auto SO = &BTree->GetBlackBoard()->SO; auto SS = &SO->States; SO->CurrentNode = this; if (Child == nullptr) { SS->at(this->TreeIndex) = BehaviorNodeState::FAILURE; return BehaviorNodeState::FAILURE; } if (State != BehaviorNodeState::RUNNING) { Reset(); } // Run action before processing child bool B = Action(BB); if (!B) { SS->at(this->TreeIndex) = BehaviorNodeState::FAILURE; State = BehaviorNodeState::FAILURE; return BehaviorNodeState::FAILURE; } // If success, then process child auto ReturnState = Child->Run(); SS->at(this->TreeIndex) = SS->at(Child->GetIndex()); // Set state to child's state State = ReturnState; return ReturnState; } inline void Reset() { // Get State Object from BlackBoard // auto SO = BTree->GetBlackBoard()->GetComponent<StateObject*>("States"); // auto SS = &SO->GetData()->States; auto SO = &BTree->GetBlackBoard()->SO; auto SS = &SO->States; SS->at(this->TreeIndex) = BehaviorNodeState::RUNNING; State = BehaviorNodeState::RUNNING; } private: bool (*Action)(BlackBoard* BB); }; } #endif
31ff5d8c303e10e582136b1044533121f9495a4a
6494b9ccb044e61ea56c8ac9e74df6c838034ab5
/Commands/Collector/RollVar.h
44e60edf57aa9404a0ad7729e9bda8d83da2605f
[]
no_license
team2059/Dent
2949c2885effad0648de7c449057e128e8364449
4dd144d37781ca9946235d804a90bcd069c9d69e
refs/heads/master
2020-12-28T09:31:08.519284
2015-03-26T14:25:51
2015-03-26T14:25:51
28,753,919
2
0
null
2017-04-27T16:33:00
2015-01-03T20:29:36
C++
UTF-8
C++
false
false
941
h
#ifndef RollVar_H #define RollVar_H #include "Commands/Command.h" #include "../../DentRobot.h" #include "../../DentRobot.h" #include "WPILib.h" /** * @brief Rolls collector motors based on button 7 */ class RollVar: public Command{ private: double speed; //<! Speed multiplier of the collector public: /** * @brief Constructs RollVar * * @param speedVal Speed control of the collector */ RollVar(double speedVal); /** * @brief Initializes the class */ void Initialize(); /** * @brief Rolls the collector motors in variable speeds */ void Execute(); /** * @brief Checks if the command is finished * * @return True only if the timeout was reached */ bool IsFinished(); /** * @brief Sets the collector to stop */ void End(); /** * @brief Calls End() */ void Interrupted(); }; #endif // vim: ts=2:sw=2:et
987e1e13ae9142d3072da86f648f15b6c1cbc075
9f78e687daad7196494de875aa22b5ec60b5da64
/lib/YAWidgets/src/WidgetGroup.h
fb159717ed0287e469ce0376274417c252966b77
[ "GPL-3.0-only", "LGPL-2.1-only", "MIT", "BSD-3-Clause", "LGPL-3.0-only", "Apache-2.0" ]
permissive
BlueAndi/esp-rgb-led-matrix
68f28c6325385432041868ff4fcc6aadb4371457
2454575e59d70b5b51ec63b5f4856521662b1e11
refs/heads/master
2023-08-17T00:44:00.513434
2023-06-18T16:21:37
2023-06-18T16:21:37
189,284,754
230
45
MIT
2023-09-14T19:27:23
2019-05-29T19:18:13
C++
UTF-8
C++
false
false
10,166
h
/* MIT License * * Copyright (c) 2019 - 2023 Andreas Merkle <[email protected]> * * 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. */ /******************************************************************************* DESCRIPTION *******************************************************************************/ /** * @brief Widget group * @author Andreas Merkle <[email protected]> * * @addtogroup gfx * * @{ */ #ifndef WIDGET_GROUP_H #define WIDGET_GROUP_H /****************************************************************************** * Compile Switches *****************************************************************************/ /****************************************************************************** * Includes *****************************************************************************/ #include <stdint.h> #include <WString.h> #include <LinkedList.hpp> #include <Widget.hpp> /****************************************************************************** * Macros *****************************************************************************/ /****************************************************************************** * Types and Classes *****************************************************************************/ /** * This class defines a widget group and can contain several widgets. */ class WidgetGroup : public Widget, private YAGfx { public: /** * Constructs a empty widget group. * * @param[in] width Canvas width in pixels * @param[in] height Canvas height in pixels * @param[in] x x-coordinate position in the underlying canvas. * @param[in] y y-coordinate position in the underlying canvas. */ WidgetGroup(uint16_t width = 0U, uint16_t height = 0U, int16_t x = 0, int16_t y = 0) : Widget(WIDGET_TYPE, x, y), m_width(width), m_height(height), m_widgets(), m_gfx(nullptr) { } /** * Constructs a widget group by copy. * * @param[in] group Source group which to copy. */ WidgetGroup(const WidgetGroup& group) : Widget(group), m_width(group.m_width), m_height(group.m_height), m_widgets(group.m_widgets), m_gfx(group.m_gfx) { } /** * Destroys the widget group. */ ~WidgetGroup() { } /** * Assigns a widget group. * * @param[in] group Source group which to assign. * * @return Wiget group */ WidgetGroup& operator=(const WidgetGroup& group) { if (&group != this) { Widget::operator=(group); m_width = group.m_width; m_height = group.m_height; m_widgets = group.m_widgets; m_gfx = group.m_gfx; } return *this; } /** * Get canvas width in pixel. * * @return Canvas width in pixel */ uint16_t getWidth() const final { return m_width; } /** * Get canvas height in pixel. * * @return Canvas height in pixel */ uint16_t getHeight() const final { return m_height; } /** * Get pixel color at given position. * Attention, it will only return a valid color in case of active painting! * * @param[in] x x-coordinate * @param[in] y y-coordinate * * @return Color in RGB888 format. */ Color& getColor(int16_t x, int16_t y) final { static Color trash; Color* pixel = &trash; /* Underlying canvas? */ if (nullptr != m_gfx) { pixel = &m_gfx->getColor(x, y); } return *pixel; } /** * Get pixel color at given position. * Attention, it will only return a valid color in case of active painting! * * @param[in] x x-coordinate * @param[in] y y-coordinate * * @return Color in RGB888 format. */ const Color& getColor(int16_t x, int16_t y) const final { static Color trash; const Color* pixel = &trash; /* Underlying canvas? */ if (nullptr != m_gfx) { pixel = &m_gfx->getColor(x, y); } return *pixel; } /** * Set canvas width in pixels. * * @param[in] width Canvas width in pixels */ void setWidth(uint16_t width) { m_width = width; } /** * Set canvas height in pixels. * * @param[in] height Canvas height in pixels */ void setHeight(uint16_t height) { m_height = height; } /** * Set widget group position and size. * * @param[in] offsX x-coordinate position in the underlying canvas. * @param[in] offsY y-coordinate position in the underlying canvas. * @param[in] width Canvas width in pixels * @param[in] height Canvas height in pixels */ void setPosAndSize(int16_t offsX, int16_t offsY, uint16_t width, uint16_t height) { m_posX = offsX; m_posY = offsY; m_width = width; m_height = height; } /** * Add a widget to the group. * * @param[in] widget Widget * * @return If successful, it will return true, otherwise false. */ bool addWidget(Widget& widget) { Widget* ptr = &widget; return m_widgets.append(ptr); } /** * Remove a widget from the group. * * @param[in] widget Widget * * @return If successful, it will return true, otherwise false. */ bool removeWidget(const Widget& widget) { bool status = false; DLinkedListIterator<Widget*> it(m_widgets); /* Find widget in the list */ if (true == it.find(&const_cast<Widget&>(widget))) { /* Remove widget */ it.remove(); status = true; } return status; } /** * Get all widget children. * * @return Children */ const DLinkedList<Widget*>& children() const { return m_widgets; } /** * Find widget by its name. * * @param[in] name Widget name to search for * * @return If widget is found, it will be returned otherwise nullptr. */ Widget* find(const String& name) override { Widget* widget = nullptr; if (name == m_name) { widget = this; } /* If its not the group itself, continue searching in the widget list. */ if (nullptr == widget) { DLinkedListIterator<Widget*> it(m_widgets); if (true == it.first()) { do { widget = (*it.current())->find(name); } while( (nullptr == widget) && (true == it.next())); } } return widget; } /** Widget type string */ static const char* WIDGET_TYPE; private: uint16_t m_width; /**< Canvas width in pixels */ uint16_t m_height; /**< Canvas height in pixels */ DLinkedList<Widget*> m_widgets; /**< Widgets in the group */ YAGfx* m_gfx; /**< Graphics interface of the underlying layer */ /** * Paint the widget with the given graphics interface. * * @param[in] gfx Graphics interface */ void paint(YAGfx& gfx) override { DLinkedListIterator<Widget*> it(m_widgets); m_gfx = &gfx; /* Walk through all widgets and draw them in the priority as * they were added. */ if (true == it.first()) { do { (*it.current())->update(*this); } while(true == it.next()); } m_gfx = nullptr; } /** * Draw a single pixel and ensure that the drawing borders are not violated. * * @param[in] x x-coordinate * @param[in] y y-coordinate * @param[in] color Pixel color */ void drawPixel(int16_t x, int16_t y, const Color& color) final { /* Don't draw outside the canvas. */ if ((nullptr != m_gfx) && (0 <= x) && (0 <= y) && (m_width > x) && (m_height > y)) { m_gfx->drawPixel(m_posX + x, m_posY + y, color); } } }; /****************************************************************************** * Functions *****************************************************************************/ #endif /* WIDGET_GROUP_H */ /** @} */
6af69afc9acfee7602766d6c738daf6ebbf7f348
0eefc9995ce927964969cbae247e28fd98f4998e
/src/hobbits-core/bitcontainermanager.h
8bddc7c66f1f9fb838ed0d769727ce749f18ab68
[ "MIT" ]
permissive
SamuelWAnderson45/hobbits
993bde59d2fd96b1824e4f85ba1913eba12c8f3f
412f4ca50aa6aa2d26a1d05913f21f2ab0198eba
refs/heads/master
2022-12-14T09:36:46.663303
2020-08-30T17:05:53
2020-08-30T17:05:53
291,514,129
0
0
null
2020-08-30T17:02:44
2020-08-30T17:02:43
null
UTF-8
C++
false
false
1,147
h
#ifndef BITCONTAINERMANAGER_H #define BITCONTAINERMANAGER_H #include "bitcontainer.h" #include "bitcontainertreemodel.h" #include <QItemSelectionModel> #include <QSharedPointer> #include "hobbits-core_global.h" class HOBBITSCORESHARED_EXPORT BitContainerManager : public QObject { Q_OBJECT public: explicit BitContainerManager(QObject *parent = nullptr); QSharedPointer<BitContainer> getCurrentContainer(); QSharedPointer<BitContainer> getContainerById(QUuid id); QSharedPointer<BitContainerTreeModel> getTreeModel(); QSharedPointer<QItemSelectionModel> getCurrSelectionModel(); void deleteCurrentContainer(); void deleteAllContainers(); private Q_SLOTS: void manageSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); Q_SIGNALS: void currSelectionChanged(QSharedPointer<BitContainer> selected, QSharedPointer<BitContainer> deselected); void containerAdded(QSharedPointer<BitContainer>); private: QSharedPointer<BitContainerTreeModel> m_bitContainerTreeModel; QSharedPointer<QItemSelectionModel> m_currSelectionModel; }; #endif // BITCONTAINERMANAGER_H
9b8fc35c17c807c2965f516a1ff26d8c17091134
46f53e9a564192eed2f40dc927af6448f8608d13
/content/renderer/render_view_browsertest.cc
713c9767eb504864ad86320215278d86685fe238
[ "BSD-3-Clause" ]
permissive
sgraham/nope
deb2d106a090d71ae882ac1e32e7c371f42eaca9
f974e0c234388a330aab71a3e5bbf33c4dcfc33c
refs/heads/master
2022-12-21T01:44:15.776329
2015-03-23T17:25:47
2015-03-23T17:25:47
32,344,868
2
2
null
null
null
null
UTF-8
C++
false
false
95,615
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/bind.h" #include "base/callback.h" #include "base/memory/shared_memory.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/win/windows_version.h" #include "content/child/request_extra_data.h" #include "content/child/service_worker/service_worker_network_provider.h" #include "content/common/frame_messages.h" #include "content/common/ssl_status_serialization.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/content_switches.h" #include "content/public/common/page_zoom.h" #include "content/public/common/url_constants.h" #include "content/public/common/url_utils.h" #include "content/public/renderer/content_renderer_client.h" #include "content/public/renderer/document_state.h" #include "content/public/renderer/navigation_state.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/frame_load_waiter.h" #include "content/public/test/render_view_test.h" #include "content/public/test/test_utils.h" #include "content/renderer/accessibility/renderer_accessibility.h" #include "content/renderer/history_controller.h" #include "content/renderer/history_serialization.h" #include "content/renderer/render_process.h" #include "content/renderer/render_view_impl.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_browser_context.h" #include "content/test/mock_keyboard.h" #include "net/base/net_errors.h" #include "net/cert/cert_status_flags.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebData.h" #include "third_party/WebKit/public/platform/WebHTTPBody.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/platform/WebURLResponse.h" #include "third_party/WebKit/public/web/WebDataSource.h" #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" #include "third_party/WebKit/public/web/WebHistoryItem.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebPerformance.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #include "third_party/WebKit/public/web/WebView.h" #include "third_party/WebKit/public/web/WebWindowFeatures.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/gfx/range/range.h" #if defined(USE_AURA) && defined(USE_X11) #include <X11/Xlib.h> #include "ui/events/event_constants.h" #include "ui/events/keycodes/keyboard_code_conversion.h" #include "ui/events/test/events_test_utils.h" #include "ui/events/test/events_test_utils_x11.h" #endif #if defined(USE_OZONE) #include "ui/events/keycodes/keyboard_code_conversion.h" #endif using blink::WebFrame; using blink::WebInputEvent; using blink::WebLocalFrame; using blink::WebMouseEvent; using blink::WebRuntimeFeatures; using blink::WebString; using blink::WebTextDirection; using blink::WebURLError; namespace content { namespace { static const int kProxyRoutingId = 13; #if (defined(USE_AURA) && defined(USE_X11)) || defined(USE_OZONE) // Converts MockKeyboard::Modifiers to ui::EventFlags. int ConvertMockKeyboardModifier(MockKeyboard::Modifiers modifiers) { static struct ModifierMap { MockKeyboard::Modifiers src; int dst; } kModifierMap[] = { { MockKeyboard::LEFT_SHIFT, ui::EF_SHIFT_DOWN }, { MockKeyboard::RIGHT_SHIFT, ui::EF_SHIFT_DOWN }, { MockKeyboard::LEFT_CONTROL, ui::EF_CONTROL_DOWN }, { MockKeyboard::RIGHT_CONTROL, ui::EF_CONTROL_DOWN }, { MockKeyboard::LEFT_ALT, ui::EF_ALT_DOWN }, { MockKeyboard::RIGHT_ALT, ui::EF_ALT_DOWN }, }; int flags = 0; for (size_t i = 0; i < arraysize(kModifierMap); ++i) { if (kModifierMap[i].src & modifiers) { flags |= kModifierMap[i].dst; } } return flags; } #endif class WebUITestWebUIControllerFactory : public WebUIControllerFactory { public: WebUIController* CreateWebUIControllerForURL(WebUI* web_ui, const GURL& url) const override { return NULL; } WebUI::TypeID GetWebUIType(BrowserContext* browser_context, const GURL& url) const override { return WebUI::kNoWebUI; } bool UseWebUIForURL(BrowserContext* browser_context, const GURL& url) const override { return HasWebUIScheme(url); } bool UseWebUIBindingsForURL(BrowserContext* browser_context, const GURL& url) const override { return HasWebUIScheme(url); } }; } // namespace class RenderViewImplTest : public RenderViewTest { public: RenderViewImplTest() { // Attach a pseudo keyboard device to this object. mock_keyboard_.reset(new MockKeyboard()); } ~RenderViewImplTest() override {} void SetUp() override { RenderViewTest::SetUp(); // Enable Blink's experimental and test only features so that test code // does not have to bother enabling each feature. WebRuntimeFeatures::enableExperimentalFeatures(true); WebRuntimeFeatures::enableTestOnlyFeatures(true); } RenderViewImpl* view() { return static_cast<RenderViewImpl*>(view_); } int view_page_id() { return view()->page_id_; } RenderFrameImpl* frame() { return static_cast<RenderFrameImpl*>(view()->GetMainRenderFrame()); } // Sends IPC messages that emulates a key-press event. int SendKeyEvent(MockKeyboard::Layout layout, int key_code, MockKeyboard::Modifiers modifiers, base::string16* output) { #if defined(OS_WIN) // Retrieve the Unicode character for the given tuple (keyboard-layout, // key-code, and modifiers). // Exit when a keyboard-layout driver cannot assign a Unicode character to // the tuple to prevent sending an invalid key code to the RenderView // object. CHECK(mock_keyboard_.get()); CHECK(output); int length = mock_keyboard_->GetCharacters(layout, key_code, modifiers, output); if (length != 1) return -1; // Create IPC messages from Windows messages and send them to our // back-end. // A keyboard event of Windows consists of three Windows messages: // WM_KEYDOWN, WM_CHAR, and WM_KEYUP. // WM_KEYDOWN and WM_KEYUP sends virtual-key codes. On the other hand, // WM_CHAR sends a composed Unicode character. MSG msg1 = { NULL, WM_KEYDOWN, key_code, 0 }; ui::KeyEvent evt1(msg1); NativeWebKeyboardEvent keydown_event(evt1); SendNativeKeyEvent(keydown_event); MSG msg2 = { NULL, WM_CHAR, (*output)[0], 0 }; ui::KeyEvent evt2(msg2); NativeWebKeyboardEvent char_event(evt2); SendNativeKeyEvent(char_event); MSG msg3 = { NULL, WM_KEYUP, key_code, 0 }; ui::KeyEvent evt3(msg3); NativeWebKeyboardEvent keyup_event(evt3); SendNativeKeyEvent(keyup_event); return length; #elif defined(USE_AURA) && defined(USE_X11) // We ignore |layout|, which means we are only testing the layout of the // current locale. TODO(mazda): fix this to respect |layout|. CHECK(output); const int flags = ConvertMockKeyboardModifier(modifiers); ui::ScopedXI2Event xevent; xevent.InitKeyEvent(ui::ET_KEY_PRESSED, static_cast<ui::KeyboardCode>(key_code), flags); ui::KeyEvent event1(xevent); NativeWebKeyboardEvent keydown_event(event1); SendNativeKeyEvent(keydown_event); // X11 doesn't actually have native character events, but give the test // what it wants. xevent.InitKeyEvent(ui::ET_KEY_PRESSED, static_cast<ui::KeyboardCode>(key_code), flags); ui::KeyEvent event2(xevent); event2.set_character(GetCharacterFromKeyCode(event2.key_code(), event2.flags())); ui::KeyEventTestApi test_event2(&event2); test_event2.set_is_char(true); NativeWebKeyboardEvent char_event(event2); SendNativeKeyEvent(char_event); xevent.InitKeyEvent(ui::ET_KEY_RELEASED, static_cast<ui::KeyboardCode>(key_code), flags); ui::KeyEvent event3(xevent); NativeWebKeyboardEvent keyup_event(event3); SendNativeKeyEvent(keyup_event); long c = GetCharacterFromKeyCode(static_cast<ui::KeyboardCode>(key_code), flags); output->assign(1, static_cast<base::char16>(c)); return 1; #elif defined(USE_OZONE) const int flags = ConvertMockKeyboardModifier(modifiers); ui::KeyEvent keydown_event(ui::ET_KEY_PRESSED, static_cast<ui::KeyboardCode>(key_code), flags); NativeWebKeyboardEvent keydown_web_event(keydown_event); SendNativeKeyEvent(keydown_web_event); ui::KeyEvent char_event(keydown_event.GetCharacter(), static_cast<ui::KeyboardCode>(key_code), flags); NativeWebKeyboardEvent char_web_event(char_event); SendNativeKeyEvent(char_web_event); ui::KeyEvent keyup_event(ui::ET_KEY_RELEASED, static_cast<ui::KeyboardCode>(key_code), flags); NativeWebKeyboardEvent keyup_web_event(keyup_event); SendNativeKeyEvent(keyup_web_event); long c = GetCharacterFromKeyCode(static_cast<ui::KeyboardCode>(key_code), flags); output->assign(1, static_cast<base::char16>(c)); return 1; #else NOTIMPLEMENTED(); return L'\0'; #endif } void EnablePreferredSizeMode() { view()->OnEnablePreferredSizeChangedMode(); } const gfx::Size& GetPreferredSize() { view()->CheckPreferredSize(); return view()->preferred_size_; } void SetZoomLevel(double level) { view()->OnSetZoomLevelForView(false, level); } private: scoped_ptr<MockKeyboard> mock_keyboard_; }; TEST_F(RenderViewImplTest, SaveImageFromDataURL) { const IPC::Message* msg1 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_SaveImageFromDataURL::ID); EXPECT_FALSE(msg1); render_thread_->sink().ClearMessages(); const std::string image_data_url = "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="; view()->saveImageFromDataURL(WebString::fromUTF8(image_data_url)); ProcessPendingMessages(); const IPC::Message* msg2 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_SaveImageFromDataURL::ID); EXPECT_TRUE(msg2); ViewHostMsg_SaveImageFromDataURL::Param param1; ViewHostMsg_SaveImageFromDataURL::Read(msg2, &param1); EXPECT_EQ(get<1>(param1).length(), image_data_url.length()); EXPECT_EQ(get<1>(param1), image_data_url); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); const std::string large_data_url(1024 * 1024 * 10 - 1, 'd'); view()->saveImageFromDataURL(WebString::fromUTF8(large_data_url)); ProcessPendingMessages(); const IPC::Message* msg3 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_SaveImageFromDataURL::ID); EXPECT_TRUE(msg3); ViewHostMsg_SaveImageFromDataURL::Param param2; ViewHostMsg_SaveImageFromDataURL::Read(msg3, &param2); EXPECT_EQ(get<1>(param2).length(), large_data_url.length()); EXPECT_EQ(get<1>(param2), large_data_url); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); const std::string exceeded_data_url(1024 * 1024 * 10 + 1, 'd'); view()->saveImageFromDataURL(WebString::fromUTF8(exceeded_data_url)); ProcessPendingMessages(); const IPC::Message* msg4 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_SaveImageFromDataURL::ID); EXPECT_FALSE(msg4); } // Test that we get form state change notifications when input fields change. TEST_F(RenderViewImplTest, DISABLED_OnNavStateChanged) { // Don't want any delay for form state sync changes. This will still post a // message so updates will get coalesced, but as soon as we spin the message // loop, it will generate an update. view()->set_send_content_state_immediately(true); LoadHTML("<input type=\"text\" id=\"elt_text\"></input>"); // We should NOT have gotten a form state change notification yet. EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_UpdateState::ID)); render_thread_->sink().ClearMessages(); // Change the value of the input. We should have gotten an update state // notification. We need to spin the message loop to catch this update. ExecuteJavaScript("document.getElementById('elt_text').value = 'foo';"); ProcessPendingMessages(); EXPECT_TRUE(render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID)); } TEST_F(RenderViewImplTest, OnNavigationHttpPost) { // An http url will trigger a resource load so cannot be used here. CommonNavigationParams common_params; StartNavigationParams start_params; HistoryNavigationParams history_params; common_params.url = GURL("data:text/html,<div>Page</div>"); common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.transition = ui::PAGE_TRANSITION_TYPED; history_params.page_id = -1; // Set up post data. const unsigned char* raw_data = reinterpret_cast<const unsigned char*>( "post \0\ndata"); const unsigned int length = 11; const std::vector<unsigned char> post_data(raw_data, raw_data + length); start_params.is_post = true; start_params.browser_initiated_post_data = post_data; frame()->OnNavigate(common_params, start_params, CommitNavigationParams(), history_params); ProcessPendingMessages(); const IPC::Message* frame_navigate_msg = render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_DidCommitProvisionalLoad::ID); EXPECT_TRUE(frame_navigate_msg); FrameHostMsg_DidCommitProvisionalLoad::Param host_nav_params; FrameHostMsg_DidCommitProvisionalLoad::Read(frame_navigate_msg, &host_nav_params); EXPECT_TRUE(get<0>(host_nav_params).is_post); // Check post data sent to browser matches EXPECT_TRUE(get<0>(host_nav_params).page_state.IsValid()); scoped_ptr<HistoryEntry> entry = PageStateToHistoryEntry(get<0>(host_nav_params).page_state); blink::WebHTTPBody body = entry->root().httpBody(); blink::WebHTTPBody::Element element; bool successful = body.elementAt(0, element); EXPECT_TRUE(successful); EXPECT_EQ(blink::WebHTTPBody::Element::TypeData, element.type); EXPECT_EQ(length, element.data.size()); EXPECT_EQ(0, memcmp(raw_data, element.data.data(), length)); } TEST_F(RenderViewImplTest, DecideNavigationPolicy) { WebUITestWebUIControllerFactory factory; WebUIControllerFactory::RegisterFactory(&factory); DocumentState state; state.set_navigation_state(NavigationState::CreateContentInitiated()); // Navigations to normal HTTP URLs can be handled locally. blink::WebURLRequest request(GURL("http://foo.com")); blink::WebFrameClient::NavigationPolicyInfo policy_info(request); policy_info.frame = GetMainFrame(); policy_info.extraData = &state; policy_info.navigationType = blink::WebNavigationTypeLinkClicked; policy_info.defaultPolicy = blink::WebNavigationPolicyCurrentTab; blink::WebNavigationPolicy policy = frame()->decidePolicyForNavigation( policy_info); EXPECT_EQ(blink::WebNavigationPolicyCurrentTab, policy); // Verify that form posts to WebUI URLs will be sent to the browser process. blink::WebURLRequest form_request(GURL("chrome://foo")); blink::WebFrameClient::NavigationPolicyInfo form_policy_info(form_request); form_policy_info.frame = GetMainFrame(); form_policy_info.extraData = &state; form_policy_info.navigationType = blink::WebNavigationTypeFormSubmitted; form_policy_info.defaultPolicy = blink::WebNavigationPolicyCurrentTab; form_request.setHTTPMethod("POST"); policy = frame()->decidePolicyForNavigation(form_policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); // Verify that popup links to WebUI URLs also are sent to browser. blink::WebURLRequest popup_request(GURL("chrome://foo")); blink::WebFrameClient::NavigationPolicyInfo popup_policy_info(popup_request); popup_policy_info.frame = GetMainFrame(); popup_policy_info.extraData = &state; popup_policy_info.navigationType = blink::WebNavigationTypeLinkClicked; popup_policy_info.defaultPolicy = blink::WebNavigationPolicyNewForegroundTab; policy = frame()->decidePolicyForNavigation(popup_policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); } TEST_F(RenderViewImplTest, DecideNavigationPolicyHandlesAllTopLevel) { DocumentState state; state.set_navigation_state(NavigationState::CreateContentInitiated()); RendererPreferences prefs = view()->renderer_preferences(); prefs.browser_handles_all_top_level_requests = true; view()->OnSetRendererPrefs(prefs); const blink::WebNavigationType kNavTypes[] = { blink::WebNavigationTypeLinkClicked, blink::WebNavigationTypeFormSubmitted, blink::WebNavigationTypeBackForward, blink::WebNavigationTypeReload, blink::WebNavigationTypeFormResubmitted, blink::WebNavigationTypeOther, }; blink::WebURLRequest request(GURL("http://foo.com")); blink::WebFrameClient::NavigationPolicyInfo policy_info(request); policy_info.frame = GetMainFrame(); policy_info.extraData = &state; policy_info.defaultPolicy = blink::WebNavigationPolicyCurrentTab; for (size_t i = 0; i < arraysize(kNavTypes); ++i) { policy_info.navigationType = kNavTypes[i]; blink::WebNavigationPolicy policy = frame()->decidePolicyForNavigation( policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); } } TEST_F(RenderViewImplTest, DecideNavigationPolicyForWebUI) { // Enable bindings to simulate a WebUI view. view()->OnAllowBindings(BINDINGS_POLICY_WEB_UI); DocumentState state; state.set_navigation_state(NavigationState::CreateContentInitiated()); // Navigations to normal HTTP URLs will be sent to browser process. blink::WebURLRequest request(GURL("http://foo.com")); blink::WebFrameClient::NavigationPolicyInfo policy_info(request); policy_info.frame = GetMainFrame(); policy_info.extraData = &state; policy_info.navigationType = blink::WebNavigationTypeLinkClicked; policy_info.defaultPolicy = blink::WebNavigationPolicyCurrentTab; blink::WebNavigationPolicy policy = frame()->decidePolicyForNavigation( policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); // Navigations to WebUI URLs will also be sent to browser process. blink::WebURLRequest webui_request(GURL("chrome://foo")); blink::WebFrameClient::NavigationPolicyInfo webui_policy_info(webui_request); webui_policy_info.frame = GetMainFrame(); webui_policy_info.extraData = &state; webui_policy_info.navigationType = blink::WebNavigationTypeLinkClicked; webui_policy_info.defaultPolicy = blink::WebNavigationPolicyCurrentTab; policy = frame()->decidePolicyForNavigation(webui_policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); // Verify that form posts to data URLs will be sent to the browser process. blink::WebURLRequest data_request(GURL("data:text/html,foo")); blink::WebFrameClient::NavigationPolicyInfo data_policy_info(data_request); data_policy_info.frame = GetMainFrame(); data_policy_info.extraData = &state; data_policy_info.navigationType = blink::WebNavigationTypeFormSubmitted; data_policy_info.defaultPolicy = blink::WebNavigationPolicyCurrentTab; data_request.setHTTPMethod("POST"); policy = frame()->decidePolicyForNavigation(data_policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); // Verify that a popup that creates a view first and then navigates to a // normal HTTP URL will be sent to the browser process, even though the // new view does not have any enabled_bindings_. blink::WebURLRequest popup_request(GURL("http://foo.com")); blink::WebView* new_web_view = view()->createView( GetMainFrame(), popup_request, blink::WebWindowFeatures(), "foo", blink::WebNavigationPolicyNewForegroundTab, false); RenderViewImpl* new_view = RenderViewImpl::FromWebView(new_web_view); blink::WebFrameClient::NavigationPolicyInfo popup_policy_info(popup_request); popup_policy_info.frame = new_web_view->mainFrame()->toWebLocalFrame(); popup_policy_info.extraData = &state; popup_policy_info.navigationType = blink::WebNavigationTypeLinkClicked; popup_policy_info.defaultPolicy = blink::WebNavigationPolicyNewForegroundTab; policy = static_cast<RenderFrameImpl*>(new_view->GetMainRenderFrame())-> decidePolicyForNavigation(popup_policy_info); EXPECT_EQ(blink::WebNavigationPolicyIgnore, policy); // Clean up after the new view so we don't leak it. new_view->Close(); new_view->Release(); } // Ensure the RenderViewImpl sends an ACK to a SwapOut request, even if it is // already swapped out. http://crbug.com/93427. TEST_F(RenderViewImplTest, SendSwapOutACK) { LoadHTML("<div>Page A</div>"); int initial_page_id = view_page_id(); // Increment the ref count so that we don't exit when swapping out. RenderProcess::current()->AddRefProcess(); // Respond to a swap out request. view()->GetMainRenderFrame()->OnSwapOut(kProxyRoutingId, true, content::FrameReplicationState()); // Ensure the swap out commits synchronously. EXPECT_NE(initial_page_id, view_page_id()); // Check for a valid OnSwapOutACK. const IPC::Message* msg = render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_SwapOut_ACK::ID); ASSERT_TRUE(msg); // It is possible to get another swap out request. Ensure that we send // an ACK, even if we don't have to do anything else. render_thread_->sink().ClearMessages(); view()->GetMainRenderFrame()->OnSwapOut(kProxyRoutingId, false, content::FrameReplicationState()); const IPC::Message* msg2 = render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_SwapOut_ACK::ID); ASSERT_TRUE(msg2); // If we navigate back to this RenderView, ensure we don't send a state // update for the swapped out URL. (http://crbug.com/72235) CommonNavigationParams common_params; HistoryNavigationParams history_params; common_params.url = GURL("data:text/html,<div>Page B</div>"); common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.transition = ui::PAGE_TRANSITION_TYPED; history_params.current_history_list_length = 1; history_params.current_history_list_offset = 0; history_params.pending_history_list_offset = 1; history_params.page_id = -1; frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), history_params); ProcessPendingMessages(); const IPC::Message* msg3 = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); EXPECT_FALSE(msg3); } // Ensure the RenderViewImpl reloads the previous page if a reload request // arrives while it is showing swappedout://. http://crbug.com/143155. TEST_F(RenderViewImplTest, ReloadWhileSwappedOut) { // Load page A. LoadHTML("<div>Page A</div>"); // Load page B, which will trigger an UpdateState message for page A. LoadHTML("<div>Page B</div>"); // Check for a valid UpdateState message for page A. ProcessPendingMessages(); const IPC::Message* msg_A = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); ASSERT_TRUE(msg_A); ViewHostMsg_UpdateState::Param params; ViewHostMsg_UpdateState::Read(msg_A, &params); int page_id_A = get<0>(params); PageState state_A = get<1>(params); EXPECT_EQ(1, page_id_A); render_thread_->sink().ClearMessages(); // Back to page A (page_id 1) and commit. CommonNavigationParams common_params_A; HistoryNavigationParams history_params_A; common_params_A.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params_A.transition = ui::PAGE_TRANSITION_FORWARD_BACK; history_params_A.current_history_list_length = 2; history_params_A.current_history_list_offset = 1; history_params_A.pending_history_list_offset = 0; history_params_A.page_id = 1; history_params_A.page_state = state_A; frame()->OnNavigate(common_params_A, StartNavigationParams(), CommitNavigationParams(), history_params_A); EXPECT_EQ(1, view()->historyBackListCount()); EXPECT_EQ(2, view()->historyBackListCount() + view()->historyForwardListCount() + 1); ProcessPendingMessages(); // Respond to a swap out request. view()->GetMainRenderFrame()->OnSwapOut(kProxyRoutingId, true, content::FrameReplicationState()); // Check for a OnSwapOutACK. const IPC::Message* msg = render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_SwapOut_ACK::ID); ASSERT_TRUE(msg); render_thread_->sink().ClearMessages(); // It is possible to get a reload request at this point, containing the // params.page_state of the initial page (e.g., if the new page fails the // provisional load in the renderer process, after we unload the old page). // Ensure the old page gets reloaded, not swappedout://. CommonNavigationParams common_params; HistoryNavigationParams history_params; common_params.url = GURL("data:text/html,<div>Page A</div>"); common_params.navigation_type = FrameMsg_Navigate_Type::RELOAD; common_params.transition = ui::PAGE_TRANSITION_RELOAD; history_params.current_history_list_length = 2; history_params.current_history_list_offset = 0; history_params.pending_history_list_offset = 0; history_params.page_id = 1; history_params.page_state = state_A; frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), history_params); ProcessPendingMessages(); // Verify page A committed, not swappedout://. const IPC::Message* frame_navigate_msg = render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_DidCommitProvisionalLoad::ID); EXPECT_TRUE(frame_navigate_msg); // Read URL out of the parent trait of the params object. FrameHostMsg_DidCommitProvisionalLoad::Param commit_load_params; FrameHostMsg_DidCommitProvisionalLoad::Read(frame_navigate_msg, &commit_load_params); EXPECT_NE(GURL("swappedout://"), get<0>(commit_load_params).url); } // Verify that security origins are replicated properly to RenderFrameProxies // when swapping out. TEST_F(RenderViewImplTest, OriginReplicationForSwapOut) { // This test should only run with --site-per-process, since origin // replication only happens in that mode. if (!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSitePerProcess)) return; LoadHTML( "Hello <iframe src='data:text/html,frame 1'></iframe>" "<iframe src='data:text/html,frame 2'></iframe>"); WebFrame* web_frame = frame()->GetWebFrame(); RenderFrameImpl* child_frame = static_cast<RenderFrameImpl*>( RenderFrame::FromWebFrame(web_frame->firstChild())); // Swap the child frame out and pass a serialized origin to be set for // WebRemoteFrame. content::FrameReplicationState replication_state; replication_state.origin = url::Origin("http://foo.com"); child_frame->OnSwapOut(kProxyRoutingId, true, replication_state); // The child frame should now be a WebRemoteFrame. EXPECT_TRUE(web_frame->firstChild()->isWebRemoteFrame()); // Expect the origin to be updated properly. blink::WebSecurityOrigin origin = web_frame->firstChild()->securityOrigin(); EXPECT_EQ(origin.toString(), WebString::fromUTF8(replication_state.origin.string())); // Now, swap out the second frame using a unique origin and verify that it is // replicated correctly. replication_state.origin = url::Origin(); RenderFrameImpl* child_frame2 = static_cast<RenderFrameImpl*>( RenderFrame::FromWebFrame(web_frame->lastChild())); child_frame2->OnSwapOut(kProxyRoutingId + 1, true, replication_state); EXPECT_TRUE(web_frame->lastChild()->isWebRemoteFrame()); EXPECT_TRUE(web_frame->lastChild()->securityOrigin().isUnique()); } // Test that we get the correct UpdateState message when we go back twice // quickly without committing. Regression test for http://crbug.com/58082. // Disabled: http://crbug.com/157357 . TEST_F(RenderViewImplTest, DISABLED_LastCommittedUpdateState) { // Load page A. LoadHTML("<div>Page A</div>"); // Load page B, which will trigger an UpdateState message for page A. LoadHTML("<div>Page B</div>"); // Check for a valid UpdateState message for page A. ProcessPendingMessages(); const IPC::Message* msg_A = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); ASSERT_TRUE(msg_A); ViewHostMsg_UpdateState::Param param; ViewHostMsg_UpdateState::Read(msg_A, &param); int page_id_A = get<0>(param); PageState state_A = get<1>(param); EXPECT_EQ(1, page_id_A); render_thread_->sink().ClearMessages(); // Load page C, which will trigger an UpdateState message for page B. LoadHTML("<div>Page C</div>"); // Check for a valid UpdateState for page B. ProcessPendingMessages(); const IPC::Message* msg_B = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); ASSERT_TRUE(msg_B); ViewHostMsg_UpdateState::Read(msg_B, &param); int page_id_B = get<0>(param); PageState state_B = get<1>(param); EXPECT_EQ(2, page_id_B); EXPECT_NE(state_A, state_B); render_thread_->sink().ClearMessages(); // Load page D, which will trigger an UpdateState message for page C. LoadHTML("<div>Page D</div>"); // Check for a valid UpdateState for page C. ProcessPendingMessages(); const IPC::Message* msg_C = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); ASSERT_TRUE(msg_C); ViewHostMsg_UpdateState::Read(msg_C, &param); int page_id_C = get<0>(param); PageState state_C = get<1>(param); EXPECT_EQ(3, page_id_C); EXPECT_NE(state_B, state_C); render_thread_->sink().ClearMessages(); // Go back to C and commit, preparing for our real test. CommonNavigationParams common_params_C; HistoryNavigationParams history_params_C; common_params_C.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params_C.transition = ui::PAGE_TRANSITION_FORWARD_BACK; history_params_C.current_history_list_length = 4; history_params_C.current_history_list_offset = 3; history_params_C.pending_history_list_offset = 2; history_params_C.page_id = 3; history_params_C.page_state = state_C; frame()->OnNavigate(common_params_C, StartNavigationParams(), CommitNavigationParams(), history_params_C); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); // Go back twice quickly, such that page B does not have a chance to commit. // This leads to two changes to the back/forward list but only one change to // the RenderView's page ID. // Back to page B (page_id 2), without committing. CommonNavigationParams common_params_B; HistoryNavigationParams history_params_B; common_params_B.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params_B.transition = ui::PAGE_TRANSITION_FORWARD_BACK; history_params_B.current_history_list_length = 4; history_params_B.current_history_list_offset = 2; history_params_B.pending_history_list_offset = 1; history_params_B.page_id = 2; history_params_B.page_state = state_B; frame()->OnNavigate(common_params_B, StartNavigationParams(), CommitNavigationParams(), history_params_B); // Back to page A (page_id 1) and commit. CommonNavigationParams common_params; HistoryNavigationParams history_params; common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.transition = ui::PAGE_TRANSITION_FORWARD_BACK; history_params.current_history_list_length = 4; history_params.current_history_list_offset = 2; history_params.pending_history_list_offset = 0; history_params.page_id = 1; history_params.page_state = state_A; frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), history_params); ProcessPendingMessages(); // Now ensure that the UpdateState message we receive is consistent // and represents page C in both page_id and state. const IPC::Message* msg = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); ASSERT_TRUE(msg); ViewHostMsg_UpdateState::Read(msg, &param); int page_id = get<0>(param); PageState state = get<1>(param); EXPECT_EQ(page_id_C, page_id); EXPECT_NE(state_A, state); EXPECT_NE(state_B, state); EXPECT_EQ(state_C, state); } // Test that stale back/forward navigations arriving from the browser are // ignored. See http://crbug.com/86758. TEST_F(RenderViewImplTest, StaleNavigationsIgnored) { // Load page A. LoadHTML("<div>Page A</div>"); EXPECT_EQ(1, view()->history_list_length_); EXPECT_EQ(0, view()->history_list_offset_); // Load page B, which will trigger an UpdateState message for page A. LoadHTML("<div>Page B</div>"); EXPECT_EQ(2, view()->history_list_length_); EXPECT_EQ(1, view()->history_list_offset_); // Check for a valid UpdateState message for page A. ProcessPendingMessages(); const IPC::Message* msg_A = render_thread_->sink().GetUniqueMessageMatching( ViewHostMsg_UpdateState::ID); ASSERT_TRUE(msg_A); ViewHostMsg_UpdateState::Param param; ViewHostMsg_UpdateState::Read(msg_A, &param); int page_id_A = get<0>(param); PageState state_A = get<1>(param); EXPECT_EQ(1, page_id_A); render_thread_->sink().ClearMessages(); // Back to page A (page_id 1) and commit. CommonNavigationParams common_params_A; HistoryNavigationParams history_params_A; common_params_A.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params_A.transition = ui::PAGE_TRANSITION_FORWARD_BACK; history_params_A.current_history_list_length = 2; history_params_A.current_history_list_offset = 1; history_params_A.pending_history_list_offset = 0; history_params_A.page_id = 1; history_params_A.page_state = state_A; frame()->OnNavigate(common_params_A, StartNavigationParams(), CommitNavigationParams(), history_params_A); ProcessPendingMessages(); // A new navigation commits, clearing the forward history. LoadHTML("<div>Page C</div>"); EXPECT_EQ(2, view()->history_list_length_); EXPECT_EQ(1, view()->history_list_offset_); EXPECT_EQ(3, view()->page_id_); // page C is now page id 3 // The browser then sends a stale navigation to B, which should be ignored. CommonNavigationParams common_params_B; HistoryNavigationParams history_params_B; common_params_B.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params_B.transition = ui::PAGE_TRANSITION_FORWARD_BACK; history_params_B.current_history_list_length = 2; history_params_B.current_history_list_offset = 0; history_params_B.pending_history_list_offset = 1; history_params_B.page_id = 2; history_params_B.page_state = state_A; // Doesn't matter, just has to be present. frame()->OnNavigate(common_params_B, StartNavigationParams(), CommitNavigationParams(), history_params_B); // State should be unchanged. EXPECT_EQ(2, view()->history_list_length_); EXPECT_EQ(1, view()->history_list_offset_); EXPECT_EQ(3, view()->page_id_); // page C, not page B // Check for a valid DidDropNavigation message. ProcessPendingMessages(); const IPC::Message* msg = render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_DidDropNavigation::ID); ASSERT_TRUE(msg); render_thread_->sink().ClearMessages(); } // Test that our IME backend sends a notification message when the input focus // changes. TEST_F(RenderViewImplTest, OnImeTypeChanged) { // Enable our IME backend code. view()->OnSetInputMethodActive(true); // Load an HTML page consisting of two input fields. view()->set_send_content_state_immediately(true); LoadHTML("<html>" "<head>" "</head>" "<body>" "<input id=\"test1\" type=\"text\" value=\"some text\"></input>" "<input id=\"test2\" type=\"password\"></input>" "<input id=\"test3\" type=\"text\" inputmode=\"verbatim\"></input>" "<input id=\"test4\" type=\"text\" inputmode=\"latin\"></input>" "<input id=\"test5\" type=\"text\" inputmode=\"latin-name\"></input>" "<input id=\"test6\" type=\"text\" inputmode=\"latin-prose\">" "</input>" "<input id=\"test7\" type=\"text\" inputmode=\"full-width-latin\">" "</input>" "<input id=\"test8\" type=\"text\" inputmode=\"kana\"></input>" "<input id=\"test9\" type=\"text\" inputmode=\"katakana\"></input>" "<input id=\"test10\" type=\"text\" inputmode=\"numeric\"></input>" "<input id=\"test11\" type=\"text\" inputmode=\"tel\"></input>" "<input id=\"test12\" type=\"text\" inputmode=\"email\"></input>" "<input id=\"test13\" type=\"text\" inputmode=\"url\"></input>" "<input id=\"test14\" type=\"text\" inputmode=\"unknown\"></input>" "<input id=\"test15\" type=\"text\" inputmode=\"verbatim\"></input>" "</body>" "</html>"); render_thread_->sink().ClearMessages(); struct InputModeTestCase { const char* input_id; ui::TextInputMode expected_mode; }; static const InputModeTestCase kInputModeTestCases[] = { {"test1", ui::TEXT_INPUT_MODE_DEFAULT}, {"test3", ui::TEXT_INPUT_MODE_VERBATIM}, {"test4", ui::TEXT_INPUT_MODE_LATIN}, {"test5", ui::TEXT_INPUT_MODE_LATIN_NAME}, {"test6", ui::TEXT_INPUT_MODE_LATIN_PROSE}, {"test7", ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN}, {"test8", ui::TEXT_INPUT_MODE_KANA}, {"test9", ui::TEXT_INPUT_MODE_KATAKANA}, {"test10", ui::TEXT_INPUT_MODE_NUMERIC}, {"test11", ui::TEXT_INPUT_MODE_TEL}, {"test12", ui::TEXT_INPUT_MODE_EMAIL}, {"test13", ui::TEXT_INPUT_MODE_URL}, {"test14", ui::TEXT_INPUT_MODE_DEFAULT}, {"test15", ui::TEXT_INPUT_MODE_VERBATIM}, }; const int kRepeatCount = 10; for (int i = 0; i < kRepeatCount; i++) { // Move the input focus to the first <input> element, where we should // activate IMEs. ExecuteJavaScript("document.getElementById('test1').focus();"); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); // Update the IME status and verify if our IME backend sends an IPC message // to activate IMEs. view()->UpdateTextInputType(); const IPC::Message* msg = render_thread_->sink().GetMessageAt(0); EXPECT_TRUE(msg != NULL); EXPECT_EQ(ViewHostMsg_TextInputTypeChanged::ID, msg->type()); ViewHostMsg_TextInputTypeChanged::Param params; ViewHostMsg_TextInputTypeChanged::Read(msg, &params); ui::TextInputType type = get<0>(params); ui::TextInputMode input_mode = get<1>(params); bool can_compose_inline = get<2>(params); EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, type); EXPECT_EQ(true, can_compose_inline); // Move the input focus to the second <input> element, where we should // de-activate IMEs. ExecuteJavaScript("document.getElementById('test2').focus();"); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); // Update the IME status and verify if our IME backend sends an IPC message // to de-activate IMEs. view()->UpdateTextInputType(); msg = render_thread_->sink().GetMessageAt(0); EXPECT_TRUE(msg != NULL); EXPECT_EQ(ViewHostMsg_TextInputTypeChanged::ID, msg->type()); ViewHostMsg_TextInputTypeChanged::Read(msg, & params); type = get<0>(params); input_mode = get<1>(params); EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, type); for (size_t i = 0; i < arraysize(kInputModeTestCases); i++) { const InputModeTestCase* test_case = &kInputModeTestCases[i]; std::string javascript = base::StringPrintf("document.getElementById('%s').focus();", test_case->input_id); // Move the input focus to the target <input> element, where we should // activate IMEs. ExecuteJavaScriptAndReturnIntValue(base::ASCIIToUTF16(javascript), NULL); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); // Update the IME status and verify if our IME backend sends an IPC // message to activate IMEs. view()->UpdateTextInputType(); const IPC::Message* msg = render_thread_->sink().GetMessageAt(0); EXPECT_TRUE(msg != NULL); EXPECT_EQ(ViewHostMsg_TextInputTypeChanged::ID, msg->type()); ViewHostMsg_TextInputTypeChanged::Read(msg, & params); type = get<0>(params); input_mode = get<1>(params); EXPECT_EQ(test_case->expected_mode, input_mode); } } } // Test that our IME backend can compose CJK words. // Our IME front-end sends many platform-independent messages to the IME backend // while it composes CJK words. This test sends the minimal messages captured // on my local environment directly to the IME backend to verify if the backend // can compose CJK words without any problems. // This test uses an array of command sets because an IME composotion does not // only depends on IME events, but also depends on window events, e.g. moving // the window focus while composing a CJK text. To handle such complicated // cases, this test should not only call IME-related functions in the // RenderWidget class, but also call some RenderWidget members, e.g. // ExecuteJavaScript(), RenderWidget::OnSetFocus(), etc. TEST_F(RenderViewImplTest, ImeComposition) { enum ImeCommand { IME_INITIALIZE, IME_SETINPUTMODE, IME_SETFOCUS, IME_SETCOMPOSITION, IME_CONFIRMCOMPOSITION, IME_CANCELCOMPOSITION }; struct ImeMessage { ImeCommand command; bool enable; int selection_start; int selection_end; const wchar_t* ime_string; const wchar_t* result; }; static const ImeMessage kImeMessages[] = { // Scenario 1: input a Chinese word with Microsoft IME (on Vista). {IME_INITIALIZE, true, 0, 0, NULL, NULL}, {IME_SETINPUTMODE, true, 0, 0, NULL, NULL}, {IME_SETFOCUS, true, 0, 0, NULL, NULL}, {IME_SETCOMPOSITION, false, 1, 1, L"n", L"n"}, {IME_SETCOMPOSITION, false, 2, 2, L"ni", L"ni"}, {IME_SETCOMPOSITION, false, 3, 3, L"nih", L"nih"}, {IME_SETCOMPOSITION, false, 4, 4, L"niha", L"niha"}, {IME_SETCOMPOSITION, false, 5, 5, L"nihao", L"nihao"}, {IME_CONFIRMCOMPOSITION, false, -1, -1, L"\x4F60\x597D", L"\x4F60\x597D"}, // Scenario 2: input a Japanese word with Microsoft IME (on Vista). {IME_INITIALIZE, true, 0, 0, NULL, NULL}, {IME_SETINPUTMODE, true, 0, 0, NULL, NULL}, {IME_SETFOCUS, true, 0, 0, NULL, NULL}, {IME_SETCOMPOSITION, false, 0, 1, L"\xFF4B", L"\xFF4B"}, {IME_SETCOMPOSITION, false, 0, 1, L"\x304B", L"\x304B"}, {IME_SETCOMPOSITION, false, 0, 2, L"\x304B\xFF4E", L"\x304B\xFF4E"}, {IME_SETCOMPOSITION, false, 0, 3, L"\x304B\x3093\xFF4A", L"\x304B\x3093\xFF4A"}, {IME_SETCOMPOSITION, false, 0, 3, L"\x304B\x3093\x3058", L"\x304B\x3093\x3058"}, {IME_SETCOMPOSITION, false, 0, 2, L"\x611F\x3058", L"\x611F\x3058"}, {IME_SETCOMPOSITION, false, 0, 2, L"\x6F22\x5B57", L"\x6F22\x5B57"}, {IME_CONFIRMCOMPOSITION, false, -1, -1, L"", L"\x6F22\x5B57"}, {IME_CANCELCOMPOSITION, false, -1, -1, L"", L"\x6F22\x5B57"}, // Scenario 3: input a Korean word with Microsot IME (on Vista). {IME_INITIALIZE, true, 0, 0, NULL, NULL}, {IME_SETINPUTMODE, true, 0, 0, NULL, NULL}, {IME_SETFOCUS, true, 0, 0, NULL, NULL}, {IME_SETCOMPOSITION, false, 0, 1, L"\x3147", L"\x3147"}, {IME_SETCOMPOSITION, false, 0, 1, L"\xC544", L"\xC544"}, {IME_SETCOMPOSITION, false, 0, 1, L"\xC548", L"\xC548"}, {IME_CONFIRMCOMPOSITION, false, -1, -1, L"", L"\xC548"}, {IME_SETCOMPOSITION, false, 0, 1, L"\x3134", L"\xC548\x3134"}, {IME_SETCOMPOSITION, false, 0, 1, L"\xB140", L"\xC548\xB140"}, {IME_SETCOMPOSITION, false, 0, 1, L"\xB155", L"\xC548\xB155"}, {IME_CANCELCOMPOSITION, false, -1, -1, L"", L"\xC548"}, {IME_SETCOMPOSITION, false, 0, 1, L"\xB155", L"\xC548\xB155"}, {IME_CONFIRMCOMPOSITION, false, -1, -1, L"", L"\xC548\xB155"}, }; for (size_t i = 0; i < arraysize(kImeMessages); i++) { const ImeMessage* ime_message = &kImeMessages[i]; switch (ime_message->command) { case IME_INITIALIZE: // Load an HTML page consisting of a content-editable <div> element, // and move the input focus to the <div> element, where we can use // IMEs. view()->OnSetInputMethodActive(ime_message->enable); view()->set_send_content_state_immediately(true); LoadHTML("<html>" "<head>" "</head>" "<body>" "<div id=\"test1\" contenteditable=\"true\"></div>" "</body>" "</html>"); ExecuteJavaScript("document.getElementById('test1').focus();"); break; case IME_SETINPUTMODE: // Activate (or deactivate) our IME back-end. view()->OnSetInputMethodActive(ime_message->enable); break; case IME_SETFOCUS: // Update the window focus. view()->OnSetFocus(ime_message->enable); break; case IME_SETCOMPOSITION: view()->OnImeSetComposition( base::WideToUTF16(ime_message->ime_string), std::vector<blink::WebCompositionUnderline>(), ime_message->selection_start, ime_message->selection_end); break; case IME_CONFIRMCOMPOSITION: view()->OnImeConfirmComposition( base::WideToUTF16(ime_message->ime_string), gfx::Range::InvalidRange(), false); break; case IME_CANCELCOMPOSITION: view()->OnImeSetComposition( base::string16(), std::vector<blink::WebCompositionUnderline>(), 0, 0); break; } // Update the status of our IME back-end. // TODO(hbono): we should verify messages to be sent from the back-end. view()->UpdateTextInputType(); ProcessPendingMessages(); render_thread_->sink().ClearMessages(); if (ime_message->result) { // Retrieve the content of this page and compare it with the expected // result. const int kMaxOutputCharacters = 128; base::string16 output = GetMainFrame()->contentAsText(kMaxOutputCharacters); EXPECT_EQ(base::WideToUTF16(ime_message->result), output); } } } // Test that the RenderView::OnSetTextDirection() function can change the text // direction of the selected input element. TEST_F(RenderViewImplTest, OnSetTextDirection) { // Load an HTML page consisting of a <textarea> element and a <div> element. // This test changes the text direction of the <textarea> element, and // writes the values of its 'dir' attribute and its 'direction' property to // verify that the text direction is changed. view()->set_send_content_state_immediately(true); LoadHTML("<html>" "<head>" "</head>" "<body>" "<textarea id=\"test\"></textarea>" "<div id=\"result\" contenteditable=\"true\"></div>" "</body>" "</html>"); render_thread_->sink().ClearMessages(); static const struct { WebTextDirection direction; const wchar_t* expected_result; } kTextDirection[] = { { blink::WebTextDirectionRightToLeft, L"\x000A" L"rtl,rtl" }, { blink::WebTextDirectionLeftToRight, L"\x000A" L"ltr,ltr" }, }; for (size_t i = 0; i < arraysize(kTextDirection); ++i) { // Set the text direction of the <textarea> element. ExecuteJavaScript("document.getElementById('test').focus();"); view()->OnSetTextDirection(kTextDirection[i].direction); // Write the values of its DOM 'dir' attribute and its CSS 'direction' // property to the <div> element. ExecuteJavaScript("var result = document.getElementById('result');" "var node = document.getElementById('test');" "var style = getComputedStyle(node, null);" "result.innerText =" " node.getAttribute('dir') + ',' +" " style.getPropertyValue('direction');"); // Copy the document content to std::wstring and compare with the // expected result. const int kMaxOutputCharacters = 16; base::string16 output = GetMainFrame()->contentAsText(kMaxOutputCharacters); EXPECT_EQ(base::WideToUTF16(kTextDirection[i].expected_result), output); } } // see http://crbug.com/238750 #if defined(OS_WIN) #define MAYBE_OnHandleKeyboardEvent DISABLED_OnHandleKeyboardEvent #else #define MAYBE_OnHandleKeyboardEvent OnHandleKeyboardEvent #endif // Test that we can receive correct DOM events when we send input events // through the RenderWidget::OnHandleInputEvent() function. TEST_F(RenderViewImplTest, MAYBE_OnHandleKeyboardEvent) { #if !defined(OS_MACOSX) // Load an HTML page consisting of one <input> element and three // contentediable <div> elements. // The <input> element is used for sending keyboard events, and the <div> // elements are used for writing DOM events in the following format: // "<keyCode>,<shiftKey>,<controlKey>,<altKey>". // TODO(hbono): <http://crbug.com/2215> Our WebKit port set |ev.metaKey| to // true when pressing an alt key, i.e. the |ev.metaKey| value is not // trustworthy. We will check the |ev.metaKey| value when this issue is fixed. view()->set_send_content_state_immediately(true); LoadHTML("<html>" "<head>" "<title></title>" "<script type='text/javascript' language='javascript'>" "function OnKeyEvent(ev) {" " var result = document.getElementById(ev.type);" " result.innerText =" " (ev.which || ev.keyCode) + ',' +" " ev.shiftKey + ',' +" " ev.ctrlKey + ',' +" " ev.altKey;" " return true;" "}" "</script>" "</head>" "<body>" "<input id='test' type='text'" " onkeydown='return OnKeyEvent(event);'" " onkeypress='return OnKeyEvent(event);'" " onkeyup='return OnKeyEvent(event);'>" "</input>" "<div id='keydown' contenteditable='true'>" "</div>" "<div id='keypress' contenteditable='true'>" "</div>" "<div id='keyup' contenteditable='true'>" "</div>" "</body>" "</html>"); ExecuteJavaScript("document.getElementById('test').focus();"); render_thread_->sink().ClearMessages(); static const MockKeyboard::Layout kLayouts[] = { #if defined(OS_WIN) // Since we ignore the mock keyboard layout on Linux and instead just use // the screen's keyboard layout, these trivially pass. They are commented // out to avoid the illusion that they work. MockKeyboard::LAYOUT_ARABIC, MockKeyboard::LAYOUT_CANADIAN_FRENCH, MockKeyboard::LAYOUT_FRENCH, MockKeyboard::LAYOUT_HEBREW, MockKeyboard::LAYOUT_RUSSIAN, #endif MockKeyboard::LAYOUT_UNITED_STATES, }; for (size_t i = 0; i < arraysize(kLayouts); ++i) { // For each key code, we send three keyboard events. // * we press only the key; // * we press the key and a left-shift key, and; // * we press the key and a right-alt (AltGr) key. // For each modifiers, we need a string used for formatting its expected // result. (See the above comment for its format.) static const struct { MockKeyboard::Modifiers modifiers; const char* expected_result; } kModifierData[] = { {MockKeyboard::NONE, "false,false,false"}, {MockKeyboard::LEFT_SHIFT, "true,false,false"}, #if defined(OS_WIN) {MockKeyboard::RIGHT_ALT, "false,false,true"}, #endif }; MockKeyboard::Layout layout = kLayouts[i]; for (size_t j = 0; j < arraysize(kModifierData); ++j) { // Virtual key codes used for this test. static const int kKeyCodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ui::VKEY_OEM_1, ui::VKEY_OEM_PLUS, ui::VKEY_OEM_COMMA, ui::VKEY_OEM_MINUS, ui::VKEY_OEM_PERIOD, ui::VKEY_OEM_2, ui::VKEY_OEM_3, ui::VKEY_OEM_4, ui::VKEY_OEM_5, ui::VKEY_OEM_6, ui::VKEY_OEM_7, #if defined(OS_WIN) // Not sure how to handle this key on Linux. ui::VKEY_OEM_8, #endif }; MockKeyboard::Modifiers modifiers = kModifierData[j].modifiers; for (size_t k = 0; k < arraysize(kKeyCodes); ++k) { // Send a keyboard event to the RenderView object. // We should test a keyboard event only when the given keyboard-layout // driver is installed in a PC and the driver can assign a Unicode // charcter for the given tuple (key-code and modifiers). int key_code = kKeyCodes[k]; base::string16 char_code; if (SendKeyEvent(layout, key_code, modifiers, &char_code) < 0) continue; // Create an expected result from the virtual-key code, the character // code, and the modifier-key status. // We format a string that emulates a DOM-event string produced hy // our JavaScript function. (See the above comment for the format.) static char expected_result[1024]; expected_result[0] = 0; base::snprintf(&expected_result[0], sizeof(expected_result), "\n" // texts in the <input> element "%d,%s\n" // texts in the first <div> element "%d,%s\n" // texts in the second <div> element "%d,%s", // texts in the third <div> element key_code, kModifierData[j].expected_result, static_cast<int>(char_code[0]), kModifierData[j].expected_result, key_code, kModifierData[j].expected_result); // Retrieve the text in the test page and compare it with the expected // text created from a virtual-key code, a character code, and the // modifier-key status. const int kMaxOutputCharacters = 1024; std::string output = base::UTF16ToUTF8( GetMainFrame()->contentAsText(kMaxOutputCharacters)); EXPECT_EQ(expected_result, output); } } } #else NOTIMPLEMENTED(); #endif } // Test that our EditorClientImpl class can insert characters when we send // keyboard events through the RenderWidget::OnHandleInputEvent() function. // This test is for preventing regressions caused only when we use non-US // keyboards, such as Issue 10846. // see http://crbug.com/244562 #if defined(OS_WIN) #define MAYBE_InsertCharacters DISABLED_InsertCharacters #else #define MAYBE_InsertCharacters InsertCharacters #endif TEST_F(RenderViewImplTest, MAYBE_InsertCharacters) { #if !defined(OS_MACOSX) static const struct { MockKeyboard::Layout layout; const wchar_t* expected_result; } kLayouts[] = { #if 0 // Disabled these keyboard layouts because buildbots do not have their // keyboard-layout drivers installed. {MockKeyboard::LAYOUT_ARABIC, L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" L"\x0038\x0039\x0634\x0624\x064a\x062b\x0628\x0644" L"\x0627\x0647\x062a\x0646\x0645\x0629\x0649\x062e" L"\x062d\x0636\x0642\x0633\x0641\x0639\x0631\x0635" L"\x0621\x063a\x0626\x0643\x003d\x0648\x002d\x0632" L"\x0638\x0630\x062c\x005c\x062f\x0637\x0028\x0021" L"\x0040\x0023\x0024\x0025\x005e\x0026\x002a\x0029" L"\x0650\x007d\x005d\x064f\x005b\x0623\x00f7\x0640" L"\x060c\x002f\x2019\x0622\x00d7\x061b\x064e\x064c" L"\x064d\x2018\x007b\x064b\x0652\x0625\x007e\x003a" L"\x002b\x002c\x005f\x002e\x061f\x0651\x003c\x007c" L"\x003e\x0022\x0030\x0031\x0032\x0033\x0034\x0035" L"\x0036\x0037\x0038\x0039\x0634\x0624\x064a\x062b" L"\x0628\x0644\x0627\x0647\x062a\x0646\x0645\x0629" L"\x0649\x062e\x062d\x0636\x0642\x0633\x0641\x0639" L"\x0631\x0635\x0621\x063a\x0626\x0643\x003d\x0648" L"\x002d\x0632\x0638\x0630\x062c\x005c\x062f\x0637" }, {MockKeyboard::LAYOUT_HEBREW, L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" L"\x0038\x0039\x05e9\x05e0\x05d1\x05d2\x05e7\x05db" L"\x05e2\x05d9\x05df\x05d7\x05dc\x05da\x05e6\x05de" L"\x05dd\x05e4\x002f\x05e8\x05d3\x05d0\x05d5\x05d4" L"\x0027\x05e1\x05d8\x05d6\x05e3\x003d\x05ea\x002d" L"\x05e5\x002e\x003b\x005d\x005c\x005b\x002c\x0028" L"\x0021\x0040\x0023\x0024\x0025\x005e\x0026\x002a" L"\x0029\x0041\x0042\x0043\x0044\x0045\x0046\x0047" L"\x0048\x0049\x004a\x004b\x004c\x004d\x004e\x004f" L"\x0050\x0051\x0052\x0053\x0054\x0055\x0056\x0057" L"\x0058\x0059\x005a\x003a\x002b\x003e\x005f\x003c" L"\x003f\x007e\x007d\x007c\x007b\x0022\x0030\x0031" L"\x0032\x0033\x0034\x0035\x0036\x0037\x0038\x0039" L"\x05e9\x05e0\x05d1\x05d2\x05e7\x05db\x05e2\x05d9" L"\x05df\x05d7\x05dc\x05da\x05e6\x05de\x05dd\x05e4" L"\x002f\x05e8\x05d3\x05d0\x05d5\x05d4\x0027\x05e1" L"\x05d8\x05d6\x05e3\x003d\x05ea\x002d\x05e5\x002e" L"\x003b\x005d\x005c\x005b\x002c" }, #endif #if defined(OS_WIN) // On Linux, the only way to test alternate keyboard layouts is to change // the keyboard layout of the whole screen. I'm worried about the side // effects this may have on the buildbots. {MockKeyboard::LAYOUT_CANADIAN_FRENCH, L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" L"\x0038\x0039\x0061\x0062\x0063\x0064\x0065\x0066" L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" L"\x0077\x0078\x0079\x007a\x003b\x003d\x002c\x002d" L"\x002e\x00e9\x003c\x0029\x0021\x0022\x002f\x0024" L"\x0025\x003f\x0026\x002a\x0028\x0041\x0042\x0043" L"\x0044\x0045\x0046\x0047\x0048\x0049\x004a\x004b" L"\x004c\x004d\x004e\x004f\x0050\x0051\x0052\x0053" L"\x0054\x0055\x0056\x0057\x0058\x0059\x005a\x003a" L"\x002b\x0027\x005f\x002e\x00c9\x003e\x0030\x0031" L"\x0032\x0033\x0034\x0035\x0036\x0037\x0038\x0039" L"\x0061\x0062\x0063\x0064\x0065\x0066\x0067\x0068" L"\x0069\x006a\x006b\x006c\x006d\x006e\x006f\x0070" L"\x0071\x0072\x0073\x0074\x0075\x0076\x0077\x0078" L"\x0079\x007a\x003b\x003d\x002c\x002d\x002e\x00e9" L"\x003c" }, {MockKeyboard::LAYOUT_FRENCH, L"\x00e0\x0026\x00e9\x0022\x0027\x0028\x002d\x00e8" L"\x005f\x00e7\x0061\x0062\x0063\x0064\x0065\x0066" L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" L"\x0077\x0078\x0079\x007a\x0024\x003d\x002c\x003b" L"\x003a\x00f9\x0029\x002a\x0021\x0030\x0031\x0032" L"\x0033\x0034\x0035\x0036\x0037\x0038\x0039\x0041" L"\x0042\x0043\x0044\x0045\x0046\x0047\x0048\x0049" L"\x004a\x004b\x004c\x004d\x004e\x004f\x0050\x0051" L"\x0052\x0053\x0054\x0055\x0056\x0057\x0058\x0059" L"\x005a\x00a3\x002b\x003f\x002e\x002f\x0025\x00b0" L"\x00b5\x00e0\x0026\x00e9\x0022\x0027\x0028\x002d" L"\x00e8\x005f\x00e7\x0061\x0062\x0063\x0064\x0065" L"\x0066\x0067\x0068\x0069\x006a\x006b\x006c\x006d" L"\x006e\x006f\x0070\x0071\x0072\x0073\x0074\x0075" L"\x0076\x0077\x0078\x0079\x007a\x0024\x003d\x002c" L"\x003b\x003a\x00f9\x0029\x002a\x0021" }, {MockKeyboard::LAYOUT_RUSSIAN, L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" L"\x0038\x0039\x0444\x0438\x0441\x0432\x0443\x0430" L"\x043f\x0440\x0448\x043e\x043b\x0434\x044c\x0442" L"\x0449\x0437\x0439\x043a\x044b\x0435\x0433\x043c" L"\x0446\x0447\x043d\x044f\x0436\x003d\x0431\x002d" L"\x044e\x002e\x0451\x0445\x005c\x044a\x044d\x0029" L"\x0021\x0022\x2116\x003b\x0025\x003a\x003f\x002a" L"\x0028\x0424\x0418\x0421\x0412\x0423\x0410\x041f" L"\x0420\x0428\x041e\x041b\x0414\x042c\x0422\x0429" L"\x0417\x0419\x041a\x042b\x0415\x0413\x041c\x0426" L"\x0427\x041d\x042f\x0416\x002b\x0411\x005f\x042e" L"\x002c\x0401\x0425\x002f\x042a\x042d\x0030\x0031" L"\x0032\x0033\x0034\x0035\x0036\x0037\x0038\x0039" L"\x0444\x0438\x0441\x0432\x0443\x0430\x043f\x0440" L"\x0448\x043e\x043b\x0434\x044c\x0442\x0449\x0437" L"\x0439\x043a\x044b\x0435\x0433\x043c\x0446\x0447" L"\x043d\x044f\x0436\x003d\x0431\x002d\x044e\x002e" L"\x0451\x0445\x005c\x044a\x044d" }, #endif // defined(OS_WIN) {MockKeyboard::LAYOUT_UNITED_STATES, L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" L"\x0038\x0039\x0061\x0062\x0063\x0064\x0065\x0066" L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" L"\x0077\x0078\x0079\x007a\x003b\x003d\x002c\x002d" L"\x002e\x002f\x0060\x005b\x005c\x005d\x0027\x0029" L"\x0021\x0040\x0023\x0024\x0025\x005e\x0026\x002a" L"\x0028\x0041\x0042\x0043\x0044\x0045\x0046\x0047" L"\x0048\x0049\x004a\x004b\x004c\x004d\x004e\x004f" L"\x0050\x0051\x0052\x0053\x0054\x0055\x0056\x0057" L"\x0058\x0059\x005a\x003a\x002b\x003c\x005f\x003e" L"\x003f\x007e\x007b\x007c\x007d\x0022" #if defined(OS_WIN) // This is ifdefed out for Linux to correspond to the fact that we don't // test alt+keystroke for now. L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" L"\x0038\x0039\x0061\x0062\x0063\x0064\x0065\x0066" L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" L"\x0077\x0078\x0079\x007a\x003b\x003d\x002c\x002d" L"\x002e\x002f\x0060\x005b\x005c\x005d\x0027" #endif }, }; for (size_t i = 0; i < arraysize(kLayouts); ++i) { // Load an HTML page consisting of one <div> element. // This <div> element is used by the EditorClientImpl class to insert // characters received through the RenderWidget::OnHandleInputEvent() // function. view()->set_send_content_state_immediately(true); LoadHTML("<html>" "<head>" "<title></title>" "</head>" "<body>" "<div id='test' contenteditable='true'>" "</div>" "</body>" "</html>"); ExecuteJavaScript("document.getElementById('test').focus();"); render_thread_->sink().ClearMessages(); // For each key code, we send three keyboard events. // * Pressing only the key; // * Pressing the key and a left-shift key, and; // * Pressing the key and a right-alt (AltGr) key. static const MockKeyboard::Modifiers kModifiers[] = { MockKeyboard::NONE, MockKeyboard::LEFT_SHIFT, #if defined(OS_WIN) MockKeyboard::RIGHT_ALT, #endif }; MockKeyboard::Layout layout = kLayouts[i].layout; for (size_t j = 0; j < arraysize(kModifiers); ++j) { // Virtual key codes used for this test. static const int kKeyCodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ui::VKEY_OEM_1, ui::VKEY_OEM_PLUS, ui::VKEY_OEM_COMMA, ui::VKEY_OEM_MINUS, ui::VKEY_OEM_PERIOD, ui::VKEY_OEM_2, ui::VKEY_OEM_3, ui::VKEY_OEM_4, ui::VKEY_OEM_5, ui::VKEY_OEM_6, ui::VKEY_OEM_7, #if defined(OS_WIN) // Unclear how to handle this on Linux. ui::VKEY_OEM_8, #endif }; MockKeyboard::Modifiers modifiers = kModifiers[j]; for (size_t k = 0; k < arraysize(kKeyCodes); ++k) { // Send a keyboard event to the RenderView object. // We should test a keyboard event only when the given keyboard-layout // driver is installed in a PC and the driver can assign a Unicode // charcter for the given tuple (layout, key-code, and modifiers). int key_code = kKeyCodes[k]; base::string16 char_code; if (SendKeyEvent(layout, key_code, modifiers, &char_code) < 0) continue; } } // Retrieve the text in the test page and compare it with the expected // text created from a virtual-key code, a character code, and the // modifier-key status. const int kMaxOutputCharacters = 4096; base::string16 output = GetMainFrame()->contentAsText(kMaxOutputCharacters); EXPECT_EQ(base::WideToUTF16(kLayouts[i].expected_result), output); } #else NOTIMPLEMENTED(); #endif } // Crashy, http://crbug.com/53247. TEST_F(RenderViewImplTest, DISABLED_DidFailProvisionalLoadWithErrorForError) { GetMainFrame()->enableViewSourceMode(true); WebURLError error; error.domain = WebString::fromUTF8(net::kErrorDomain); error.reason = net::ERR_FILE_NOT_FOUND; error.unreachableURL = GURL("http://foo"); WebLocalFrame* web_frame = GetMainFrame(); // Start a load that will reach provisional state synchronously, // but won't complete synchronously. CommonNavigationParams common_params; common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.url = GURL("data:text/html,test data"); frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), HistoryNavigationParams()); // An error occurred. view()->GetMainRenderFrame()->didFailProvisionalLoad(web_frame, error); // Frame should exit view-source mode. EXPECT_FALSE(web_frame->isViewSourceModeEnabled()); } TEST_F(RenderViewImplTest, DidFailProvisionalLoadWithErrorForCancellation) { GetMainFrame()->enableViewSourceMode(true); WebURLError error; error.domain = WebString::fromUTF8(net::kErrorDomain); error.reason = net::ERR_ABORTED; error.unreachableURL = GURL("http://foo"); WebLocalFrame* web_frame = GetMainFrame(); // Start a load that will reach provisional state synchronously, // but won't complete synchronously. CommonNavigationParams common_params; common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.url = GURL("data:text/html,test data"); frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), HistoryNavigationParams()); // A cancellation occurred. view()->GetMainRenderFrame()->didFailProvisionalLoad(web_frame, error); // Frame should stay in view-source mode. EXPECT_TRUE(web_frame->isViewSourceModeEnabled()); } // Regression test for http://crbug.com/41562 TEST_F(RenderViewImplTest, UpdateTargetURLWithInvalidURL) { const GURL invalid_gurl("http://"); view()->setMouseOverURL(blink::WebURL(invalid_gurl)); EXPECT_EQ(invalid_gurl, view()->target_url_); } TEST_F(RenderViewImplTest, SetHistoryLengthAndOffset) { // No history to merge; one committed page. view()->OnSetHistoryOffsetAndLength(0, 1); EXPECT_EQ(1, view()->history_list_length_); EXPECT_EQ(0, view()->history_list_offset_); // History of length 1 to merge; one committed page. view()->OnSetHistoryOffsetAndLength(1, 2); EXPECT_EQ(2, view()->history_list_length_); EXPECT_EQ(1, view()->history_list_offset_); } TEST_F(RenderViewImplTest, ContextMenu) { LoadHTML("<div>Page A</div>"); // Create a right click in the center of the iframe. (I'm hoping this will // make this a bit more robust in case of some other formatting or other bug.) WebMouseEvent mouse_event; mouse_event.type = WebInputEvent::MouseDown; mouse_event.button = WebMouseEvent::ButtonRight; mouse_event.x = 250; mouse_event.y = 250; mouse_event.globalX = 250; mouse_event.globalY = 250; SendWebMouseEvent(mouse_event); // Now simulate the corresponding up event which should display the menu mouse_event.type = WebInputEvent::MouseUp; SendWebMouseEvent(mouse_event); EXPECT_TRUE(render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_ContextMenu::ID)); } TEST_F(RenderViewImplTest, TestBackForward) { LoadHTML("<div id=pagename>Page A</div>"); PageState page_a_state = HistoryEntryToPageState(view()->history_controller()->GetCurrentEntry()); int was_page_a = -1; base::string16 check_page_a = base::ASCIIToUTF16( "Number(document.getElementById('pagename').innerHTML == 'Page A')"); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_a, &was_page_a)); EXPECT_EQ(1, was_page_a); LoadHTML("<div id=pagename>Page B</div>"); int was_page_b = -1; base::string16 check_page_b = base::ASCIIToUTF16( "Number(document.getElementById('pagename').innerHTML == 'Page B')"); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_b, &was_page_b)); EXPECT_EQ(1, was_page_b); PageState back_state = HistoryEntryToPageState(view()->history_controller()->GetCurrentEntry()); LoadHTML("<div id=pagename>Page C</div>"); int was_page_c = -1; base::string16 check_page_c = base::ASCIIToUTF16( "Number(document.getElementById('pagename').innerHTML == 'Page C')"); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_c, &was_page_c)); EXPECT_EQ(1, was_page_c); PageState forward_state = HistoryEntryToPageState(view()->history_controller()->GetCurrentEntry()); GoBack(back_state); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_b, &was_page_b)); EXPECT_EQ(1, was_page_b); PageState back_state2 = HistoryEntryToPageState(view()->history_controller()->GetCurrentEntry()); GoForward(forward_state); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_c, &was_page_c)); EXPECT_EQ(1, was_page_c); GoBack(back_state2); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_b, &was_page_b)); EXPECT_EQ(1, was_page_b); forward_state = HistoryEntryToPageState(view()->history_controller()->GetCurrentEntry()); GoBack(page_a_state); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_a, &was_page_a)); EXPECT_EQ(1, was_page_a); GoForward(forward_state); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(check_page_b, &was_page_b)); EXPECT_EQ(1, was_page_b); } #if defined(OS_MACOSX) || defined(USE_AURA) TEST_F(RenderViewImplTest, GetCompositionCharacterBoundsTest) { #if defined(OS_WIN) // http://crbug.com/304193 if (base::win::GetVersion() < base::win::VERSION_VISTA) return; #endif LoadHTML("<textarea id=\"test\"></textarea>"); ExecuteJavaScript("document.getElementById('test').focus();"); const base::string16 empty_string; const std::vector<blink::WebCompositionUnderline> empty_underline; std::vector<gfx::Rect> bounds; view()->OnSetFocus(true); view()->OnSetInputMethodActive(true); // ASCII composition const base::string16 ascii_composition = base::UTF8ToUTF16("aiueo"); view()->OnImeSetComposition(ascii_composition, empty_underline, 0, 0); view()->GetCompositionCharacterBounds(&bounds); ASSERT_EQ(ascii_composition.size(), bounds.size()); for (size_t i = 0; i < bounds.size(); ++i) EXPECT_LT(0, bounds[i].width()); view()->OnImeConfirmComposition( empty_string, gfx::Range::InvalidRange(), false); // Non surrogate pair unicode character. const base::string16 unicode_composition = base::UTF8ToUTF16( "\xE3\x81\x82\xE3\x81\x84\xE3\x81\x86\xE3\x81\x88\xE3\x81\x8A"); view()->OnImeSetComposition(unicode_composition, empty_underline, 0, 0); view()->GetCompositionCharacterBounds(&bounds); ASSERT_EQ(unicode_composition.size(), bounds.size()); for (size_t i = 0; i < bounds.size(); ++i) EXPECT_LT(0, bounds[i].width()); view()->OnImeConfirmComposition( empty_string, gfx::Range::InvalidRange(), false); // Surrogate pair character. const base::string16 surrogate_pair_char = base::UTF8ToUTF16("\xF0\xA0\xAE\x9F"); view()->OnImeSetComposition(surrogate_pair_char, empty_underline, 0, 0); view()->GetCompositionCharacterBounds(&bounds); ASSERT_EQ(surrogate_pair_char.size(), bounds.size()); EXPECT_LT(0, bounds[0].width()); EXPECT_EQ(0, bounds[1].width()); view()->OnImeConfirmComposition( empty_string, gfx::Range::InvalidRange(), false); // Mixed string. const base::string16 surrogate_pair_mixed_composition = surrogate_pair_char + base::UTF8ToUTF16("\xE3\x81\x82") + surrogate_pair_char + base::UTF8ToUTF16("b") + surrogate_pair_char; const size_t utf16_length = 8UL; const bool is_surrogate_pair_empty_rect[8] = { false, true, false, false, true, false, false, true }; view()->OnImeSetComposition(surrogate_pair_mixed_composition, empty_underline, 0, 0); view()->GetCompositionCharacterBounds(&bounds); ASSERT_EQ(utf16_length, bounds.size()); for (size_t i = 0; i < utf16_length; ++i) { if (is_surrogate_pair_empty_rect[i]) { EXPECT_EQ(0, bounds[i].width()); } else { EXPECT_LT(0, bounds[i].width()); } } view()->OnImeConfirmComposition( empty_string, gfx::Range::InvalidRange(), false); } #endif TEST_F(RenderViewImplTest, ZoomLimit) { const double kMinZoomLevel = ZoomFactorToZoomLevel(kMinimumZoomFactor); const double kMaxZoomLevel = ZoomFactorToZoomLevel(kMaximumZoomFactor); // Verifies navigation to a URL with preset zoom level indeed sets the level. // Regression test for http://crbug.com/139559, where the level was not // properly set when it is out of the default zoom limits of WebView. CommonNavigationParams common_params; common_params.url = GURL("data:text/html,min_zoomlimit_test"); view()->OnSetZoomLevelForLoadingURL(common_params.url, kMinZoomLevel); frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), HistoryNavigationParams()); ProcessPendingMessages(); EXPECT_DOUBLE_EQ(kMinZoomLevel, view()->GetWebView()->zoomLevel()); // It should work even when the zoom limit is temporarily changed in the page. view()->GetWebView()->zoomLimitsChanged(ZoomFactorToZoomLevel(1.0), ZoomFactorToZoomLevel(1.0)); common_params.url = GURL("data:text/html,max_zoomlimit_test"); view()->OnSetZoomLevelForLoadingURL(common_params.url, kMaxZoomLevel); frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), HistoryNavigationParams()); ProcessPendingMessages(); EXPECT_DOUBLE_EQ(kMaxZoomLevel, view()->GetWebView()->zoomLevel()); } TEST_F(RenderViewImplTest, SetEditableSelectionAndComposition) { // Load an HTML page consisting of an input field. LoadHTML("<html>" "<head>" "</head>" "<body>" "<input id=\"test1\" value=\"some test text hello\"></input>" "</body>" "</html>"); ExecuteJavaScript("document.getElementById('test1').focus();"); frame()->OnSetEditableSelectionOffsets(4, 8); const std::vector<blink::WebCompositionUnderline> empty_underline; frame()->OnSetCompositionFromExistingText(7, 10, empty_underline); blink::WebTextInputInfo info = view()->webview()->textInputInfo(); EXPECT_EQ(4, info.selectionStart); EXPECT_EQ(8, info.selectionEnd); EXPECT_EQ(7, info.compositionStart); EXPECT_EQ(10, info.compositionEnd); frame()->OnUnselect(); info = view()->webview()->textInputInfo(); EXPECT_EQ(0, info.selectionStart); EXPECT_EQ(0, info.selectionEnd); } TEST_F(RenderViewImplTest, OnExtendSelectionAndDelete) { // Load an HTML page consisting of an input field. LoadHTML("<html>" "<head>" "</head>" "<body>" "<input id=\"test1\" value=\"abcdefghijklmnopqrstuvwxyz\"></input>" "</body>" "</html>"); ExecuteJavaScript("document.getElementById('test1').focus();"); frame()->OnSetEditableSelectionOffsets(10, 10); frame()->OnExtendSelectionAndDelete(3, 4); blink::WebTextInputInfo info = view()->webview()->textInputInfo(); EXPECT_EQ("abcdefgopqrstuvwxyz", info.value); EXPECT_EQ(7, info.selectionStart); EXPECT_EQ(7, info.selectionEnd); frame()->OnSetEditableSelectionOffsets(4, 8); frame()->OnExtendSelectionAndDelete(2, 5); info = view()->webview()->textInputInfo(); EXPECT_EQ("abuvwxyz", info.value); EXPECT_EQ(2, info.selectionStart); EXPECT_EQ(2, info.selectionEnd); } // Test that the navigating specific frames works correctly. TEST_F(RenderViewImplTest, NavigateFrame) { // Load page A. LoadHTML("hello <iframe srcdoc='fail' name='frame'></iframe>"); // Navigate the frame only. CommonNavigationParams common_params; CommitNavigationParams commit_params; HistoryNavigationParams history_params; common_params.url = GURL("data:text/html,world"); common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.transition = ui::PAGE_TRANSITION_TYPED; history_params.current_history_list_length = 1; history_params.current_history_list_offset = 0; history_params.pending_history_list_offset = 1; history_params.page_id = -1; commit_params.frame_to_navigate = "frame"; commit_params.browser_navigation_start = base::TimeTicks::FromInternalValue(1); frame()->OnNavigate(common_params, StartNavigationParams(), commit_params, history_params); FrameLoadWaiter( RenderFrame::FromWebFrame(frame()->GetWebFrame()->firstChild())).Wait(); // Copy the document content to std::wstring and compare with the // expected result. const int kMaxOutputCharacters = 256; std::string output = base::UTF16ToUTF8( GetMainFrame()->contentAsText(kMaxOutputCharacters)); EXPECT_EQ(output, "hello \n\nworld"); } // This test ensures that a RenderFrame object is created for the top level // frame in the RenderView. TEST_F(RenderViewImplTest, BasicRenderFrame) { EXPECT_TRUE(view()->main_render_frame_.get()); } TEST_F(RenderViewImplTest, GetSSLStatusOfFrame) { LoadHTML("<!DOCTYPE html><html><body></body></html>"); WebLocalFrame* frame = GetMainFrame(); SSLStatus ssl_status = view()->GetSSLStatusOfFrame(frame); EXPECT_FALSE(net::IsCertStatusError(ssl_status.cert_status)); const_cast<blink::WebURLResponse&>(frame->dataSource()->response()). setSecurityInfo( SerializeSecurityInfo(0, net::CERT_STATUS_ALL_ERRORS, 0, 0, SignedCertificateTimestampIDStatusList())); ssl_status = view()->GetSSLStatusOfFrame(frame); EXPECT_TRUE(net::IsCertStatusError(ssl_status.cert_status)); } TEST_F(RenderViewImplTest, MessageOrderInDidChangeSelection) { view()->OnSetInputMethodActive(true); view()->set_send_content_state_immediately(true); LoadHTML("<textarea id=\"test\"></textarea>"); view()->handling_input_event_ = true; ExecuteJavaScript("document.getElementById('test').focus();"); bool is_input_type_called = false; bool is_selection_called = false; size_t last_input_type = 0; size_t last_selection = 0; for (size_t i = 0; i < render_thread_->sink().message_count(); ++i) { const uint32 type = render_thread_->sink().GetMessageAt(i)->type(); if (type == ViewHostMsg_TextInputTypeChanged::ID) { is_input_type_called = true; last_input_type = i; } else if (type == ViewHostMsg_SelectionChanged::ID) { is_selection_called = true; last_selection = i; } } EXPECT_TRUE(is_input_type_called); EXPECT_TRUE(is_selection_called); // InputTypeChange shold be called earlier than SelectionChanged. EXPECT_LT(last_input_type, last_selection); } class SuppressErrorPageTest : public RenderViewTest { public: ContentRendererClient* CreateContentRendererClient() override { return new TestContentRendererClient; } RenderViewImpl* view() { return static_cast<RenderViewImpl*>(view_); } RenderFrameImpl* frame() { return static_cast<RenderFrameImpl*>(view()->GetMainRenderFrame()); } private: class TestContentRendererClient : public ContentRendererClient { public: bool ShouldSuppressErrorPage(RenderFrame* render_frame, const GURL& url) override { return url == GURL("http://example.com/suppress"); } void GetNavigationErrorStrings(content::RenderView* render_view, blink::WebFrame* frame, const blink::WebURLRequest& failed_request, const blink::WebURLError& error, std::string* error_html, base::string16* error_description) override { if (error_html) *error_html = "A suffusion of yellow."; } }; }; #if defined(OS_ANDROID) // Crashing on Android: http://crbug.com/311341 #define MAYBE_Suppresses DISABLED_Suppresses #else #define MAYBE_Suppresses Suppresses #endif TEST_F(SuppressErrorPageTest, MAYBE_Suppresses) { WebURLError error; error.domain = WebString::fromUTF8(net::kErrorDomain); error.reason = net::ERR_FILE_NOT_FOUND; error.unreachableURL = GURL("http://example.com/suppress"); WebLocalFrame* web_frame = GetMainFrame(); // Start a load that will reach provisional state synchronously, // but won't complete synchronously. CommonNavigationParams common_params; common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.url = GURL("data:text/html,test data"); frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), HistoryNavigationParams()); // An error occurred. view()->GetMainRenderFrame()->didFailProvisionalLoad(web_frame, error); const int kMaxOutputCharacters = 22; EXPECT_EQ("", base::UTF16ToASCII(web_frame->contentAsText(kMaxOutputCharacters))); } #if defined(OS_ANDROID) // Crashing on Android: http://crbug.com/311341 #define MAYBE_DoesNotSuppress DISABLED_DoesNotSuppress #else #define MAYBE_DoesNotSuppress DoesNotSuppress #endif TEST_F(SuppressErrorPageTest, MAYBE_DoesNotSuppress) { WebURLError error; error.domain = WebString::fromUTF8(net::kErrorDomain); error.reason = net::ERR_FILE_NOT_FOUND; error.unreachableURL = GURL("http://example.com/dont-suppress"); WebLocalFrame* web_frame = GetMainFrame(); // Start a load that will reach provisional state synchronously, // but won't complete synchronously. CommonNavigationParams common_params; common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; common_params.url = GURL("data:text/html,test data"); frame()->OnNavigate(common_params, StartNavigationParams(), CommitNavigationParams(), HistoryNavigationParams()); // An error occurred. view()->GetMainRenderFrame()->didFailProvisionalLoad(web_frame, error); // The error page itself is loaded asynchronously. FrameLoadWaiter(frame()).Wait(); const int kMaxOutputCharacters = 22; EXPECT_EQ("A suffusion of yellow.", base::UTF16ToASCII(web_frame->contentAsText(kMaxOutputCharacters))); } // Tests if IME API's candidatewindow* events sent from browser are handled // in renderer. TEST_F(RenderViewImplTest, SendCandidateWindowEvents) { // Sends an HTML with an <input> element and scripts to the renderer. // The script handles all 3 of candidatewindow* events for an // InputMethodContext object and once it received 'show', 'update', 'hide' // should appear in the result div. LoadHTML("<input id='test'>" "<div id='result'>Result: </div>" "<script>" "window.onload = function() {" " var result = document.getElementById('result');" " var test = document.getElementById('test');" " test.focus();" " var context = test.inputMethodContext;" " if (context) {" " context.oncandidatewindowshow = function() {" " result.innerText += 'show'; };" " context.oncandidatewindowupdate = function(){" " result.innerText += 'update'; };" " context.oncandidatewindowhide = function(){" " result.innerText += 'hide'; };" " }" "};" "</script>"); // Fire candidatewindow events. view()->OnCandidateWindowShown(); view()->OnCandidateWindowUpdated(); view()->OnCandidateWindowHidden(); // Retrieve the content and check if it is expected. const int kMaxOutputCharacters = 50; std::string output = base::UTF16ToUTF8( GetMainFrame()->contentAsText(kMaxOutputCharacters)); EXPECT_EQ(output, "\nResult:showupdatehide"); } // Ensure the render view sends favicon url update events correctly. TEST_F(RenderViewImplTest, SendFaviconURLUpdateEvent) { // An event should be sent when a favicon url exists. LoadHTML("<html>" "<head>" "<link rel='icon' href='http://www.google.com/favicon.ico'>" "</head>" "</html>"); EXPECT_TRUE(render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_UpdateFaviconURL::ID)); render_thread_->sink().ClearMessages(); // An event should not be sent if no favicon url exists. This is an assumption // made by some of Chrome's favicon handling. LoadHTML("<html>" "<head>" "</head>" "</html>"); EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_UpdateFaviconURL::ID)); } TEST_F(RenderViewImplTest, FocusElementCallsFocusedNodeChanged) { LoadHTML("<input id='test1' value='hello1'></input>" "<input id='test2' value='hello2'></input>"); ExecuteJavaScript("document.getElementById('test1').focus();"); const IPC::Message* msg1 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_FocusedNodeChanged::ID); EXPECT_TRUE(msg1); ViewHostMsg_FocusedNodeChanged::Param params; ViewHostMsg_FocusedNodeChanged::Read(msg1, &params); EXPECT_TRUE(get<0>(params)); render_thread_->sink().ClearMessages(); ExecuteJavaScript("document.getElementById('test2').focus();"); const IPC::Message* msg2 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_FocusedNodeChanged::ID); EXPECT_TRUE(msg2); ViewHostMsg_FocusedNodeChanged::Read(msg2, &params); EXPECT_TRUE(get<0>(params)); render_thread_->sink().ClearMessages(); view()->webview()->clearFocusedElement(); const IPC::Message* msg3 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_FocusedNodeChanged::ID); EXPECT_TRUE(msg3); ViewHostMsg_FocusedNodeChanged::Read(msg3, &params); EXPECT_FALSE(get<0>(params)); render_thread_->sink().ClearMessages(); } TEST_F(RenderViewImplTest, ServiceWorkerNetworkProviderSetup) { ServiceWorkerNetworkProvider* provider = NULL; RequestExtraData* extra_data = NULL; // Make sure each new document has a new provider and // that the main request is tagged with the provider's id. LoadHTML("<b>A Document</b>"); ASSERT_TRUE(GetMainFrame()->dataSource()); provider = ServiceWorkerNetworkProvider::FromDocumentState( DocumentState::FromDataSource(GetMainFrame()->dataSource())); ASSERT_TRUE(provider); extra_data = static_cast<RequestExtraData*>( GetMainFrame()->dataSource()->request().extraData()); ASSERT_TRUE(extra_data); EXPECT_EQ(extra_data->service_worker_provider_id(), provider->provider_id()); int provider1_id = provider->provider_id(); LoadHTML("<b>New Document B Goes Here</b>"); ASSERT_TRUE(GetMainFrame()->dataSource()); provider = ServiceWorkerNetworkProvider::FromDocumentState( DocumentState::FromDataSource(GetMainFrame()->dataSource())); ASSERT_TRUE(provider); EXPECT_NE(provider1_id, provider->provider_id()); extra_data = static_cast<RequestExtraData*>( GetMainFrame()->dataSource()->request().extraData()); ASSERT_TRUE(extra_data); EXPECT_EQ(extra_data->service_worker_provider_id(), provider->provider_id()); // See that subresource requests are also tagged with the provider's id. EXPECT_EQ(frame(), RenderFrameImpl::FromWebFrame(GetMainFrame())); blink::WebURLRequest request(GURL("http://foo.com")); request.setRequestContext(blink::WebURLRequest::RequestContextSubresource); blink::WebURLResponse redirect_response; frame()->willSendRequest(GetMainFrame(), 0, request, redirect_response); extra_data = static_cast<RequestExtraData*>(request.extraData()); ASSERT_TRUE(extra_data); EXPECT_EQ(extra_data->service_worker_provider_id(), provider->provider_id()); } TEST_F(RenderViewImplTest, OnSetAccessibilityMode) { ASSERT_EQ(AccessibilityModeOff, frame()->accessibility_mode()); ASSERT_EQ((RendererAccessibility*) NULL, frame()->renderer_accessibility()); frame()->OnSetAccessibilityMode(AccessibilityModeTreeOnly); ASSERT_EQ(AccessibilityModeTreeOnly, frame()->accessibility_mode()); ASSERT_NE((RendererAccessibility*) NULL, frame()->renderer_accessibility()); frame()->OnSetAccessibilityMode(AccessibilityModeOff); ASSERT_EQ(AccessibilityModeOff, frame()->accessibility_mode()); ASSERT_EQ((RendererAccessibility*) NULL, frame()->renderer_accessibility()); frame()->OnSetAccessibilityMode(AccessibilityModeComplete); ASSERT_EQ(AccessibilityModeComplete, frame()->accessibility_mode()); ASSERT_NE((RendererAccessibility*) NULL, frame()->renderer_accessibility()); } TEST_F(RenderViewImplTest, ScreenMetricsEmulation) { LoadHTML("<body style='min-height:1000px;'></body>"); blink::WebDeviceEmulationParams params; base::string16 get_width = base::ASCIIToUTF16("Number(window.innerWidth)"); base::string16 get_height = base::ASCIIToUTF16("Number(window.innerHeight)"); int width, height; params.viewSize.width = 327; params.viewSize.height = 415; view()->EnableScreenMetricsEmulation(params); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &width)); EXPECT_EQ(params.viewSize.width, width); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, &height)); EXPECT_EQ(params.viewSize.height, height); params.viewSize.width = 1005; params.viewSize.height = 1102; view()->EnableScreenMetricsEmulation(params); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &width)); EXPECT_EQ(params.viewSize.width, width); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, &height)); EXPECT_EQ(params.viewSize.height, height); view()->DisableScreenMetricsEmulation(); view()->EnableScreenMetricsEmulation(params); // Don't disable here to test that emulation is being shutdown properly. } // Sanity checks for the Navigation Timing API |navigationStart| override. We // are asserting only most basic constraints, as TimeTicks (passed as the // override) are not comparable with the wall time (returned by the Blink API). TEST_F(RenderViewImplTest, NavigationStartOverride) { // Verify that a navigation that claims to have started at the earliest // possible TimeTicks is indeed reported as one that started before // OnNavigate() is called. base::Time before_navigation = base::Time::Now(); CommonNavigationParams early_common_params; StartNavigationParams early_start_params; CommitNavigationParams early_commit_params; early_common_params.url = GURL("data:text/html,<div>Page</div>"); early_common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; early_common_params.transition = ui::PAGE_TRANSITION_TYPED; early_start_params.is_post = true; early_commit_params.browser_navigation_start = base::TimeTicks::FromInternalValue(1); frame()->OnNavigate(early_common_params, early_start_params, early_commit_params, HistoryNavigationParams()); ProcessPendingMessages(); base::Time early_nav_reported_start = base::Time::FromDoubleT(GetMainFrame()->performance().navigationStart()); EXPECT_LT(early_nav_reported_start, before_navigation); // Verify that a navigation that claims to have started in the future - 42 // days from now is *not* reported as one that starts in the future; as we // sanitize the override allowing a maximum of ::Now(). CommonNavigationParams late_common_params; CommitNavigationParams late_commit_params; StartNavigationParams late_start_params; late_common_params.url = GURL("data:text/html,<div>Another page</div>"); late_common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; late_common_params.transition = ui::PAGE_TRANSITION_TYPED; late_start_params.is_post = true; late_commit_params.browser_navigation_start = base::TimeTicks::Now() + base::TimeDelta::FromDays(42); frame()->OnNavigate(late_common_params, late_start_params, late_commit_params, HistoryNavigationParams()); ProcessPendingMessages(); base::Time after_navigation = base::Time::Now() + base::TimeDelta::FromDays(1); base::Time late_nav_reported_start = base::Time::FromDoubleT(GetMainFrame()->performance().navigationStart()); EXPECT_LE(late_nav_reported_start, after_navigation); } TEST_F(RenderViewImplTest, PreferredSizeZoomed) { LoadHTML("<body style='margin:0;'><div style='display:inline-block; " "width:400px; height:400px;'/></body>"); view()->webview()->mainFrame()->setCanHaveScrollbars(false); EnablePreferredSizeMode(); gfx::Size size = GetPreferredSize(); EXPECT_EQ(gfx::Size(400, 400), size); SetZoomLevel(ZoomFactorToZoomLevel(2.0)); size = GetPreferredSize(); EXPECT_EQ(gfx::Size(800, 800), size); } // Ensure the RenderViewImpl history list is properly updated when starting a // new browser-initiated navigation. TEST_F(RenderViewImplTest, HistoryIsProperlyUpdatedOnNavigation) { EXPECT_EQ(0, view()->historyBackListCount()); EXPECT_EQ(0, view()->historyBackListCount() + view()->historyForwardListCount() + 1); // Receive a Navigate message with history parameters. HistoryNavigationParams history_params; history_params.current_history_list_length = 2; history_params.current_history_list_offset = 1; history_params.pending_history_list_offset = 2; history_params.page_id = -1; frame()->OnNavigate(CommonNavigationParams(), StartNavigationParams(), CommitNavigationParams(), history_params); // The history list in RenderView should have been updated. EXPECT_EQ(1, view()->historyBackListCount()); EXPECT_EQ(2, view()->historyBackListCount() + view()->historyForwardListCount() + 1); } } // namespace content
62425cce5b01617d0c801a47ff33b897ebf0162d
3ef87080dd64df3b142fd264e8fe21ddac07b30f
/Source/glTFRuntime/Public/glTFRuntimeAssetActor.h
6e71a6516083f52b3b887459b1355b798ac1baba
[ "MIT" ]
permissive
chuqiuhan/glTFRuntime
8d1b1284f15282e811c924ffe618ff72f0bd1b72
ea9fd99d195accf24b11df85015565d548520730
refs/heads/master
2022-11-23T21:02:36.719771
2020-07-29T06:44:48
2020-07-29T06:44:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,846
h
// Copyright 2020, Roberto De Ioris. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "glTFRuntimeAsset.h" #include "glTFRuntimeAssetActor.generated.h" UCLASS() class GLTFRUNTIME_API AglTFRuntimeAssetActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AglTFRuntimeAssetActor(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; virtual void ProcessNode(USceneComponent* NodeParentComponent, FglTFRuntimeNode& Node); TMap<USceneComponent*, float> CurveBasedAnimationsTimeTracker; public: // Called every frame virtual void Tick(float DeltaTime) override; UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta = (ExposeOnSpawn = true), Category = "glTFRuntime") UglTFRuntimeAsset* Asset; UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta = (ExposeOnSpawn = true), Category = "glTFRuntime") FglTFRuntimeStaticMeshConfig StaticMeshConfig; UPROPERTY(EditAnywhere, BlueprintReadWrite, Meta = (ExposeOnSpawn = true), Category = "glTFRuntime") FglTFRuntimeSkeletalMeshConfig SkeletalMeshConfig; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "glTFRuntime") TMap<USceneComponent*, UglTFRuntimeAnimationCurve*> CurveBasedAnimations; UFUNCTION(BlueprintNativeEvent, Category = "glTFRuntime", meta = (DisplayName = "On StaticMeshComponent Created")) void ReceiveOnStaticMeshComponentCreated(UStaticMeshComponent* StaticMeshComponent); UFUNCTION(BlueprintNativeEvent, Category = "glTFRuntime", meta = (DisplayName = "On SkeletalMeshComponent Created")) void ReceiveOnSkeletalMeshComponentCreated(USkeletalMeshComponent* SkeletalMeshComponent); private: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category="glTFRuntime") USceneComponent* AssetRoot; };
580cf6277e45d9f1daaf1e05d1c34b8a9010b2a1
7a763ee94917fc5b220b78c4d7358c933ce77875
/media/vaapi_picture_wayland.h
9f0b1fa3c2d1d7cc681cce9a45bea71cee4b6a42
[ "BSD-3-Clause" ]
permissive
Tarnyko/ozone-wayland
bbbf990900fd595c032669f69e0fede3b072f264
3d86706dde9dd71b43e8ba246c6b4cf1414e221b
refs/heads/master
2021-01-21T19:39:57.394252
2015-01-06T16:17:38
2015-01-06T16:20:04
28,870,218
0
0
null
2015-01-06T15:48:18
2015-01-06T15:48:17
null
UTF-8
C++
false
false
1,881
h
// Copyright (c) 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. // // This file contains an implementation of VideoDecoderAccelerator // that utilizes hardware video decoder present on Intel CPUs. #ifndef OZONE_MEDIA_VAAPI_PICTURE_WAYLAND_H_ #define OZONE_MEDIA_VAAPI_PICTURE_WAYLAND_H_ #include "base/memory/linked_ptr.h" #include "base/threading/non_thread_safe.h" #include "ozone/media/vaapi_picture.h" #include "ozone/media/vaapi_wrapper.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/scoped_binders.h" namespace content { class VaapiPictureWayland : public VaapiPicture { public: VaapiPictureWayland(VaapiWrapper* vaapi_wrapper, const base::Callback<bool(void)> make_context_current, int32 picture_buffer_id, uint32 texture_id, const gfx::Size& size); ~VaapiPictureWayland(); bool Initialize() override; bool DownloadFromSurface(const scoped_refptr<VASurface>& va_surface) override; private: // Upload vaimage data to texture. Needs to be called every frame. bool Upload(VASurfaceID id); // Bind EGL image to texture. Needs to be called every frame. bool Bind(); bool UpdateEGLImage(VASurfaceID id); EGLImageKHR CreateEGLImage( EGLDisplay egl_display, VASurfaceID surface, VAImage* va_image); bool DestroyEGLImage(EGLDisplay egl_display, EGLImageKHR egl_image); base::Callback<bool(void)> make_context_current_; //NOLINT VaapiWrapper* va_wrapper_; scoped_ptr<VAImage> va_image_; EGLImageKHR egl_image_; EGLDisplay egl_display_; bool supports_valockBuffer_apis_; DISALLOW_COPY_AND_ASSIGN(VaapiPictureWayland); }; } // namespace content #endif // OZONE_MEDIA_VAAPI_TFP_PICTURE_WAYLAND_H_
0a921123b48aed7136c24f60608ad104589d3c0a
f9a26c2586d8e28313f29736b57470e81f4a74df
/impeller/renderer/backend/vulkan/capabilities_vk.cc
a09c13b568e430612588d773fc01f22c0893be2f
[ "BSD-3-Clause" ]
permissive
Yoogurt/engine
53b8f08444b958f7dc024c02fa5cf534bf410de6
9ddbea322d426b68ac95c012595a22c9e2116436
refs/heads/master
2023-07-20T14:13:33.052582
2023-07-05T15:46:18
2023-07-05T15:46:18
313,291,144
0
0
BSD-3-Clause
2023-09-12T05:03:56
2020-11-16T12:12:37
C++
UTF-8
C++
false
false
13,484
cc
// Copyright 2013 The Flutter 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 "impeller/renderer/backend/vulkan/capabilities_vk.h" #include <algorithm> #include "impeller/base/validation.h" #include "impeller/renderer/backend/vulkan/vk.h" namespace impeller { static constexpr const char* kInstanceLayer = "ImpellerInstance"; CapabilitiesVK::CapabilitiesVK(bool enable_validations) : enable_validations_(enable_validations) { if (enable_validations_) { FML_LOG(INFO) << "Vulkan validations are enabled."; } auto extensions = vk::enumerateInstanceExtensionProperties(); auto layers = vk::enumerateInstanceLayerProperties(); if (extensions.result != vk::Result::eSuccess || layers.result != vk::Result::eSuccess) { return; } for (const auto& ext : extensions.value) { exts_[kInstanceLayer].insert(ext.extensionName); } for (const auto& layer : layers.value) { const std::string layer_name = layer.layerName; auto layer_exts = vk::enumerateInstanceExtensionProperties(layer_name); if (layer_exts.result != vk::Result::eSuccess) { return; } for (const auto& layer_ext : layer_exts.value) { exts_[layer_name].insert(layer_ext.extensionName); } } is_valid_ = true; } CapabilitiesVK::~CapabilitiesVK() = default; bool CapabilitiesVK::IsValid() const { return is_valid_; } bool CapabilitiesVK::AreValidationsEnabled() const { return enable_validations_; } std::optional<std::vector<std::string>> CapabilitiesVK::GetEnabledLayers() const { std::vector<std::string> required; if (enable_validations_) { if (!HasLayer("VK_LAYER_KHRONOS_validation")) { VALIDATION_LOG << "Requested validations but the validation layer was not found."; return std::nullopt; } required.push_back("VK_LAYER_KHRONOS_validation"); } return required; } std::optional<std::vector<std::string>> CapabilitiesVK::GetEnabledInstanceExtensions() const { std::vector<std::string> required; if (!HasExtension("VK_KHR_surface")) { // Swapchain support is required and this is a dependency of // VK_KHR_swapchain. VALIDATION_LOG << "Could not find the surface extension."; return std::nullopt; } required.push_back("VK_KHR_surface"); auto has_wsi = false; if (HasExtension("VK_MVK_macos_surface")) { required.push_back("VK_MVK_macos_surface"); has_wsi = true; } if (HasExtension("VK_EXT_metal_surface")) { required.push_back("VK_EXT_metal_surface"); has_wsi = true; } if (HasExtension("VK_KHR_portability_enumeration")) { required.push_back("VK_KHR_portability_enumeration"); has_wsi = true; } if (HasExtension("VK_KHR_win32_surface")) { required.push_back("VK_KHR_win32_surface"); has_wsi = true; } if (HasExtension("VK_KHR_android_surface")) { required.push_back("VK_KHR_android_surface"); has_wsi = true; } if (HasExtension("VK_KHR_xcb_surface")) { required.push_back("VK_KHR_xcb_surface"); has_wsi = true; } if (HasExtension("VK_KHR_xlib_surface")) { required.push_back("VK_KHR_xlib_surface"); has_wsi = true; } if (HasExtension("VK_KHR_wayland_surface")) { required.push_back("VK_KHR_wayland_surface"); has_wsi = true; } if (!has_wsi) { // Don't really care which WSI extension there is as long there is at least // one. VALIDATION_LOG << "Could not find a WSI extension."; return std::nullopt; } if (enable_validations_) { if (!HasExtension("VK_EXT_debug_utils")) { VALIDATION_LOG << "Requested validations but could not find the " "VK_EXT_debug_utils extension."; return std::nullopt; } required.push_back("VK_EXT_debug_utils"); if (HasExtension("VK_EXT_validation_features")) { // It's valid to not have `VK_EXT_validation_features` available. That's // the case when using AGI as a frame debugger. FML_DLOG(INFO) << "Requested validations but could not find the " "VK_EXT_validation_features extension."; required.push_back("VK_EXT_validation_features"); } } return required; } static const char* GetDeviceExtensionName(OptionalDeviceExtensionVK ext) { switch (ext) { case OptionalDeviceExtensionVK::kEXTPipelineCreationFeedback: return VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME; case OptionalDeviceExtensionVK::kLast: return "Unknown"; } return "Unknown"; } static void IterateOptionalDeviceExtensions( const std::function<void(OptionalDeviceExtensionVK)>& it) { if (!it) { return; } for (size_t i = 0; i < static_cast<uint32_t>(OptionalDeviceExtensionVK::kLast); i++) { it(static_cast<OptionalDeviceExtensionVK>(i)); } } static std::optional<std::set<std::string>> GetSupportedDeviceExtensions( const vk::PhysicalDevice& physical_device) { auto device_extensions = physical_device.enumerateDeviceExtensionProperties(); if (device_extensions.result != vk::Result::eSuccess) { return std::nullopt; } std::set<std::string> exts; for (const auto& device_extension : device_extensions.value) { exts.insert(device_extension.extensionName); }; return exts; } std::optional<std::vector<std::string>> CapabilitiesVK::GetEnabledDeviceExtensions( const vk::PhysicalDevice& physical_device) const { auto exts = GetSupportedDeviceExtensions(physical_device); if (!exts.has_value()) { return std::nullopt; } std::vector<std::string> enabled; if (exts->find("VK_KHR_swapchain") == exts->end()) { VALIDATION_LOG << "Device does not support the swapchain extension."; return std::nullopt; } enabled.push_back("VK_KHR_swapchain"); // Required for non-conformant implementations like MoltenVK. if (exts->find("VK_KHR_portability_subset") != exts->end()) { enabled.push_back("VK_KHR_portability_subset"); } // Enable all optional extensions if the device supports it. IterateOptionalDeviceExtensions([&](auto ext) { auto ext_name = GetDeviceExtensionName(ext); if (exts->find(ext_name) != exts->end()) { enabled.push_back(ext_name); } }); return enabled; } static bool HasSuitableColorFormat(const vk::PhysicalDevice& device, vk::Format format) { const auto props = device.getFormatProperties(format); // This needs to be more comprehensive. return !!(props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eColorAttachment); } static bool HasSuitableDepthStencilFormat(const vk::PhysicalDevice& device, vk::Format format) { const auto props = device.getFormatProperties(format); return !!(props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment); } static bool PhysicalDeviceSupportsRequiredFormats( const vk::PhysicalDevice& device) { const auto has_color_format = HasSuitableColorFormat(device, vk::Format::eB8G8R8A8Unorm); const auto has_depth_stencil_format = HasSuitableDepthStencilFormat(device, vk::Format::eS8Uint) || HasSuitableDepthStencilFormat(device, vk::Format::eD24UnormS8Uint); return has_color_format && has_depth_stencil_format; } static bool HasRequiredProperties(const vk::PhysicalDevice& physical_device) { auto properties = physical_device.getProperties(); if (!(properties.limits.framebufferColorSampleCounts & (vk::SampleCountFlagBits::e1 | vk::SampleCountFlagBits::e4))) { return false; } return true; } static bool HasRequiredQueues(const vk::PhysicalDevice& physical_device) { auto queue_flags = vk::QueueFlags{}; for (const auto& queue : physical_device.getQueueFamilyProperties()) { if (queue.queueCount == 0) { continue; } queue_flags |= queue.queueFlags; } return static_cast<VkQueueFlags>(queue_flags & (vk::QueueFlagBits::eGraphics | vk::QueueFlagBits::eCompute | vk::QueueFlagBits::eTransfer)); } std::optional<vk::PhysicalDeviceFeatures> CapabilitiesVK::GetEnabledDeviceFeatures( const vk::PhysicalDevice& device) const { if (!PhysicalDeviceSupportsRequiredFormats(device)) { VALIDATION_LOG << "Device doesn't support the required formats."; return std::nullopt; } if (!HasRequiredProperties(device)) { VALIDATION_LOG << "Device doesn't support the required properties."; return std::nullopt; } if (!HasRequiredQueues(device)) { VALIDATION_LOG << "Device doesn't support the required queues."; return std::nullopt; } if (!GetEnabledDeviceExtensions(device).has_value()) { VALIDATION_LOG << "Device doesn't support the required queues."; return std::nullopt; } const auto device_features = device.getFeatures(); vk::PhysicalDeviceFeatures required; // We require this for enabling wireframes in the playground. But its not // necessarily a big deal if we don't have this feature. required.fillModeNonSolid = device_features.fillModeNonSolid; return required; } bool CapabilitiesVK::HasLayer(const std::string& layer) const { for (const auto& [found_layer, exts] : exts_) { if (found_layer == layer) { return true; } } return false; } bool CapabilitiesVK::HasExtension(const std::string& ext) const { for (const auto& [layer, exts] : exts_) { if (exts.find(ext) != exts.end()) { return true; } } return false; } void CapabilitiesVK::SetOffscreenFormat(PixelFormat pixel_format) const { color_format_ = pixel_format; } bool CapabilitiesVK::SetPhysicalDevice(const vk::PhysicalDevice& device) { if (HasSuitableDepthStencilFormat(device, vk::Format::eS8Uint)) { depth_stencil_format_ = PixelFormat::kS8UInt; } else if (HasSuitableDepthStencilFormat(device, vk::Format::eD24UnormS8Uint)) { depth_stencil_format_ = PixelFormat::kD32FloatS8UInt; } else { return false; } device_properties_ = device.getProperties(); auto physical_properties_2 = device.getProperties2<vk::PhysicalDeviceProperties2, vk::PhysicalDeviceSubgroupProperties>(); // Currently shaders only want access to arithmetic subgroup features. // If that changes this needs to get updated, and so does Metal (which right // now assumes it from compile time flags based on the MSL target version). supports_compute_subgroups_ = !!(physical_properties_2.get<vk::PhysicalDeviceSubgroupProperties>() .supportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic); { // Query texture support. // TODO(jonahwilliams): // https://github.com/flutter/flutter/issues/129784 vk::PhysicalDeviceMemoryProperties memory_properties; device.getMemoryProperties(&memory_properties); for (auto i = 0u; i < memory_properties.memoryTypeCount; i++) { if (memory_properties.memoryTypes[i].propertyFlags & vk::MemoryPropertyFlagBits::eLazilyAllocated) { supports_memoryless_textures_ = true; } } } // Determine the optional device extensions this physical device supports. { optional_device_extensions_.clear(); auto exts = GetSupportedDeviceExtensions(device); if (!exts.has_value()) { return false; } IterateOptionalDeviceExtensions([&](auto ext) { auto ext_name = GetDeviceExtensionName(ext); if (exts->find(ext_name) != exts->end()) { optional_device_extensions_.insert(ext); } }); } return true; } // |Capabilities| bool CapabilitiesVK::HasThreadingRestrictions() const { return false; } // |Capabilities| bool CapabilitiesVK::SupportsOffscreenMSAA() const { return true; } // |Capabilities| bool CapabilitiesVK::SupportsSSBO() const { return true; } // |Capabilities| bool CapabilitiesVK::SupportsBufferToTextureBlits() const { return true; } // |Capabilities| bool CapabilitiesVK::SupportsTextureToTextureBlits() const { return true; } // |Capabilities| bool CapabilitiesVK::SupportsFramebufferFetch() const { return false; } // |Capabilities| bool CapabilitiesVK::SupportsCompute() const { // Vulkan 1.1 requires support for compute. return true; } // |Capabilities| bool CapabilitiesVK::SupportsComputeSubgroups() const { // Set by |SetPhysicalDevice|. return supports_compute_subgroups_; } // |Capabilities| bool CapabilitiesVK::SupportsReadFromResolve() const { return false; } // |Capabilities| bool CapabilitiesVK::SupportsReadFromOnscreenTexture() const { return false; } bool CapabilitiesVK::SupportsDecalTileMode() const { return true; } // |Capabilities| bool CapabilitiesVK::SupportsMemorylessTextures() const { return supports_memoryless_textures_; } // |Capabilities| PixelFormat CapabilitiesVK::GetDefaultColorFormat() const { return color_format_; } // |Capabilities| PixelFormat CapabilitiesVK::GetDefaultStencilFormat() const { return depth_stencil_format_; } const vk::PhysicalDeviceProperties& CapabilitiesVK::GetPhysicalDeviceProperties() const { return device_properties_; } bool CapabilitiesVK::HasOptionalDeviceExtension( OptionalDeviceExtensionVK extension) const { return optional_device_extensions_.find(extension) != optional_device_extensions_.end(); } } // namespace impeller
8ef660d8b28f04777c4e0647f5cf6ed28e28c69b
7077b7afef51342563d1e7f462ce7d3acdb7fb6a
/Hue Master/Temp/il2cppOutput/il2cppOutput/Il2CppMetadataRegistration.cpp
32008398fc161cb2340f6d49a75b0ff3d8455782
[]
no_license
bzor/hue-master
73d46ff62568e23202d6b0703cdac55f2f3e7451
5c95e3b39a3d92cbc796f233f2c1d224a315f044
refs/heads/master
2021-01-18T19:51:10.582618
2016-09-15T02:00:42
2016-09-15T02:00:42
62,262,293
0
0
null
null
null
null
UTF-8
C++
false
false
1,094
cpp
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" extern Il2CppGenericClass* const s_Il2CppGenericTypes[]; extern const Il2CppGenericInst* const g_Il2CppGenericInstTable[]; extern const Il2CppGenericMethodFunctionsDefinitions s_Il2CppGenericMethodFunctions[]; extern const Il2CppType* const g_Il2CppTypeTable[]; extern const Il2CppMethodSpec g_Il2CppMethodSpecTable[]; extern const int32_t g_FieldOffsetTable[]; extern const Il2CppTypeDefinitionSizes g_Il2CppTypeDefinitionSizesTable[]; extern void** const g_MetadataUsages[]; extern const Il2CppMetadataRegistration g_MetadataRegistration = { 1089, s_Il2CppGenericTypes, 301, g_Il2CppGenericInstTable, 1616, s_Il2CppGenericMethodFunctions, 5483, g_Il2CppTypeTable, 1783, g_Il2CppMethodSpecTable, 5480, g_FieldOffsetTable, 1435, g_Il2CppTypeDefinitionSizesTable, 4820, g_MetadataUsages, };
de8f13caaf61daf177e58e34b9d7effa7644a582
f7b2758ba036bf7a817f21fa4f909bee2890c521
/packages/CBuilder/OrpheusCD.cpp
df807101b7f810ef7da39d8d6bb848881f30c263
[]
no_license
kputy/Orpheus
4f47d9d3c7fa22af10aa8d4fce05054038f1148c
5b5186fb59c2f791952a9c1f563eed335b6ea01c
refs/heads/master
2021-01-18T07:00:34.402335
2015-03-07T11:01:08
2015-03-07T11:01:08
41,523,922
0
1
null
2015-08-28T03:03:48
2015-08-28T03:03:48
null
UTF-8
C++
false
false
2,436
cpp
//--------------------------------------------------------------------------- #include <basepch.h> #pragma hdrstop USEFORMNS("..\..\source\ovclkou1.pas", Ovclkou1, OvcfrmLkOutEd); USEFORMNS("..\..\source\ovcoutle.pas", Ovcoutle, OvcfrmOLItemsEditor); USEFORMNS("..\..\source\ovcnfpe.pas", Ovcnfpe, OvcfrmNumericMask); USEFORMNS("..\..\source\ovcefpe.pas", Ovcefpe, OvcfrmEfRange); USEFORMNS("..\..\source\ovclbl1.pas", Ovclbl1, frmSaveScheme); USEFORMNS("..\..\source\ovclbl0.pas", Ovclbl0, frmOvcLabel); USEFORMNS("..\..\source\ovctbpe2.pas", Ovctbpe2, OvcfrmColEditor); USEFORMNS("..\..\source\ovctbpe1.pas", Ovctbpe1, OvcfrmRowEditor); USEFORMNS("..\..\source\ovctcpe.pas", Ovctcpe, OvcfrmTCRange); USEFORMNS("..\..\source\ovcxfrc1.pas", Ovcxfrc1, OvcfrmTransfer); USEFORMNS("..\..\source\ovcstat0.pas", Ovcstat0, OvcfrmPropsDlg); USEFORMNS("..\..\source\ovcpfpe.pas", Ovcpfpe, OvcfrmPictureMask); USEFORMNS("..\..\source\ovcrvced.pas", Ovcrvced, RVCmpEd); USEFORMNS("..\..\source\ovcsfpe.pas", Ovcsfpe, OvcfrmSimpleMask); USEFORMNS("..\..\source\ovcrvped.pas", Ovcrvped, RVCmpEd2); USEFORMNS("..\..\source\ovcdrpve.pas", Ovcdrpve, OvcfrmRvDataItemEditor); USEFORMNS("..\..\source\O32IGridEditor1.pas", O32igrideditor1, IGridCmpEd); USEFORMNS("..\..\source\O32ColEd.pas", O32coled, O32frmCollEditor); USEFORMNS("..\..\source\ovccmdp1.pas", Ovccmdp1, OvcfrmScanOrder); USEFORMNS("..\..\source\ovccmdp0.pas", Ovccmdp0, OvcfrmCmdTable); USEFORMNS("..\..\source\ovccole0.pas", Ovccole0, OvcfrmCollEditor); USEFORMNS("..\..\source\ovcdock0.pas", Ovcdock0, OvcfrmDock); USEFORMNS("..\..\source\O32LobEd.pas", O32lobed, O32frmLkOutEd); USEFORMNS("..\..\source\O32IGridItemEd.pas", O32igriditemed, FormIGridItemEditor); USEFORMNS("..\..\source\o32vldpe.pas", O32vldpe, TO32FrmValidatorExpression); USEFORMNS("..\..\source\ovcaepe.pas", Ovcaepe, OvcfrmAeRange); USEFORMNS("..\..\source\Ovcabot0.pas", Ovcabot0, OvcfrmAboutForm); //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- // Package source. //--------------------------------------------------------------------------- #pragma argsused int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*) { return 1; } //---------------------------------------------------------------------------
2810af983aaed84267bc335c0fe43d1733b316dd
cceaa500aeb294bb3159955e37f019c8f5544b71
/src/mainACE.cpp
3874771c47e9a89718ad5a72075ecfeceed2cb99
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
evvyter/ACE
1397d4d41e1bcd55614ee5ea2f4226242a20632f
ac6f9ae484a1557b9e69315951aa3a920d961a6c
refs/heads/master
2020-12-25T19:03:03.369452
2017-05-30T00:50:22
2017-05-30T00:50:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,284
cpp
#include <stdio.h> #include <stdlib.h> #include <string> #include "algorithm.h" // Algorithm declarations /********************************************************************* COMMAND LINE INPUT FORMAT Command line instructions tell the program where to look for input files and where to send output, as well as the setting of various parameters (gamma, theta, etc) and flags (useSparse, etc). Note that numerical parameters may be entered in either scientific (recommended) or standard decimal notation. True/false switches are off by default - if entered in the command line, the corresponding option is set to true. Defaults can be found in dataStructures.h. The conventions are given below: -(flag name): (type of input expected) -d: string Default: "." (current directory) Path to the directory where the data file is located, and where output will be written. -i: string Default: "input" The location of the file containing a set of correlations from which to infer Ising model parameters. -o: string Default: "output" The location of the file where output is to be sent. Each different type of output file will have a different file type, e.g. .j for couplings. -ss: string Default: none When the network of interactions (e.g. contact map) is known, a list of perselected 2-site clusters can be given. "string" represent the name and the location of the file from which clusters are read. The extension of the file has to be .cl. -inputcl: string Default: none When a list of interesting clusters (e.g. from previously runnings) is known, this list of perselected n-site clusters can be given and used for inference. "string" represent the name and the location of the file from which clusters are read. The extension of the file has to be .cl. -cl: none Print the list of selected clusters in a file .cl in the output folder. -cc: none Print the list of selected clusters that are not also subsets of selected clusters. This list thus gives a minimal set of selected clusters that contains all other selected clusters as subsets. In the output file, which ends with -co.dat, the first column gives the value of delta S for the cluster, while subsequent columns give the sites included in the cluster. Each row represents one cluster. -b: real number Default: 1.0e+4 Number of samples used to compute the correlations. Used to determine the inference error. -kmin: integer Default: 1 Minimum cluster size, useful for avoiding the inference of models that are too sparse. The algorithm will continue to lower the threshold until clusters of at least this size are selected. -kmax: integer Default: N (system size) Maximum cluster size. The algorithm will halt when clusters of this size are selected. -t: real number Default: none Run the algorithm at the input value of theta, in scientific or standard decimal notation. This line is intended to be used when inferrence is to be done only for a single value of theta, and will be overridden if thetaMax and thetaMin are set different from t. -tmin: real number Default: 1.0e-10 The minimum value of theta. See description of -ts below for more information. -tmax: real number Default: 1.0e+0 The maximum value of theta. See description of -ts below for more information. -ts: real number Default: 1.05 The logarithmic step size to use for successive updates of theta. When the program loops over different values of theta, it begins by running the algorithm at the largest value of the cutoff and stores the cluster information. The algorithm is then re-run for successively smaller values of the cutoff, theta_(i+1) = theta_i / thetastep, until theta < thetaMin. These re-runs use the previously stored cluster information, so they take considerably less time to run. -trec: real number Default: 0 (any intermediate recording) The logarithmic step size for theta to record the inferred parameters. Given this interval the chosen value corresponds the theta producing the minimum error on correlations. -mcb: integer Default: 4.0e+4 Number of Monte Carlo samples to take to check inference error. -mcr: integer Default: 1 Number of independent Monte Carlo runs to perform. -g0: real number Default: 1.0e-4 The L0 regularization strength. Using this flag also turns on L0 regularization. -g2: real number Default: 0.0 The L2 regularization strength. L2 regularization is enabled by setting the regularization strength to a nonzero value using this flag, or by using the -ag flag below. -gi: none Use gauge invariant L2 regularization for couplings. -ag: none Attempt to set the L0 and L2 regularization strengths to their optimal values, based on the number of samples (input) in the data. The integer input here *can be different* from the value used for determining the correlations. -l0: none If selected, L0-norm (sparse) regularization is used. -lax: none If selected, use a laxer cluster construction rule. -v: none Enable verbose output. *********************************************************************/ // MAIN PROGRAM int main(int argc, char *argv[]) { RunParameters r; // Process command line input for (int i=1;i<argc;i++) { // Location of input/output files if (strcmp(argv[i],"-d")==0) { if (++i==argc) break; else r.directory=argv[i]; } else if (strcmp(argv[i],"-i")==0) { if (++i==argc) break; else r.infile=argv[i]; } else if (strcmp(argv[i],"-o")==0) { if (++i==argc) break; else r.outfile=argv[i]; } else if (strcmp(argv[i],"-ss")==0) { if (++i==argc) break; else { r.useCmap=true; r.ssinfile=argv[i]; } } else if (strcmp(argv[i],"-inputcl")==0) { if (++i==argc) break; else { r.inputClusters=true; r.ssinfile=argv[i]; } } else if (strcmp(argv[i],"-cl")==0) { r.recClusters=true; } else if (strcmp(argv[i],"-cc")==0) { r.recClusterCover=true; } // Cluster size and threshold cutoffs else if (strcmp(argv[i],"-kmin")==0) { if (++i==argc) break; else r.kmin=strtoint(argv[i]); } else if (strcmp(argv[i],"-kmax")==0) { if (++i==argc) break; else r.kmax=strtoint(argv[i]); } else if (strcmp(argv[i],"-t")==0) { if (++i==argc) break; else { r.thetaMax=strtodouble(argv[i]); r.thetaMin=strtodouble(argv[i]); } } else if (strcmp(argv[i],"-tmin")==0) { if (++i==argc) break; else r.thetaMin=strtodouble(argv[i]); } else if (strcmp(argv[i],"-tmax")==0) { if (++i==argc) break; else r.thetaMax=strtodouble(argv[i]); } else if (strcmp(argv[i],"-ts")==0) { if (++i==argc) break; else r.thetaStep=strtodouble(argv[i]); } else if (strcmp(argv[i],"-trec")==0) { if (++i==argc) break; else r.recordStep=strtodouble(argv[i]); } else if (strcmp(argv[i],"-lax")==0) { r.useLax=true; } // Regularization strengths and settings else if (strcmp(argv[i],"-r")==0) { r.useRef=true; } else if (strcmp(argv[i],"-ag")==0) { r.computeGamma=true; } else if (strcmp(argv[i],"-l0")==0) { r.useSparse=true; } else if (strcmp(argv[i],"-g0")==0) { if (++i==argc) break; else { r.gamma0=strtodouble(argv[i]); r.useSparse=true; } } else if (strcmp(argv[i],"-g2")==0) { if (++i==argc) break; else r.gamma2=strtodouble(argv[i]); } else if (strcmp(argv[i],"-gi")==0) { r.useGI=true; } // Monte Carlo settings else if (strcmp(argv[i],"-b")==0) { if (++i==argc) break; else r.sampleB=strtodouble(argv[i]); } else if (strcmp(argv[i],"-mcb")==0) { if (++i==argc) break; else r.b=strtoint(argv[i]); } else if (strcmp(argv[i],"-mcr")==0) { if (++i==argc) break; else r.runs=strtoint(argv[i]); } //#FLAG NOT YET IMPLEMENTED // Optional output else if (strcmp(argv[i],"-v")==0) { r.useVerbose=true; } else printf("Unrecognized command! '%s'\n",argv[i]); } return run(r); }
5c7bf637eeb1c1299c938e2fc76518d2c5f52866
159a6dd1c1bd1fb7e4d5daf257b61f42d3722108
/Source/Particle/Frames/Nodes/NodeGraph.cpp
0c81a4a71dba97faa679dd793096ba8a7b04d95a
[]
no_license
potrepka/Particle
c51e2e9b9aca37f73f5fbd4241658a2c746e00c2
2aff9b218976c0f205fc1fcbf7f8fbad2ffdf41d
refs/heads/master
2023-01-19T05:01:55.459706
2020-11-20T08:18:48
2020-11-20T08:18:48
296,459,805
0
0
null
null
null
null
UTF-8
C++
false
false
73,513
cpp
#include "NodeGraph.h" const int particle::NodeGraph::PRECISION = 6; const float particle::NodeGraph::FRAME_WIDTH = 120.0f; particle::NodeGraph::FloatInt::FloatInt(dsp::Type type, dsp::Sample value) { switch (type) { case dsp::Type::RATIO: case dsp::Type::HERTZ: case dsp::Type::SECONDS: valueFloat = value; break; case dsp::Type::INTEGER: case dsp::Type::BOOLEAN: valueInt = value; break; } } particle::NodeGraph::Input::Input( Data *data, int id, std::string name, std::shared_ptr<dsp::Input> input, std::vector<std::string> values) : Named(name) , data(data) , id(id) , input(input) , value(input->getType(), input->getDefaultValue()) , values(values) {} void particle::NodeGraph::Input::draw() { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, data->getStyle().nodeFramePadding); imnodes::BeginInputAttribute(id, imnodes::PinShape::PinShape_QuadFilled); ImGui::SetNextItemWidth(FRAME_WIDTH); if (input->getConnections().size() == 0) { ImGuiIO &io = ImGui::GetIO(); switch (input->getType()) { case dsp::Type::RATIO: case dsp::Type::HERTZ: case dsp::Type::SECONDS: { if (ImGui::DragFloat(getName().c_str(), &value.valueFloat, io.KeyAlt ? 0.1f : io.KeyShift ? 100.0f : 1.0f, 0.0f, static_cast<float>(input->getRange()), ("%." + std::to_string(PRECISION) + "f").c_str(), ImGuiSliderFlags_AlwaysClamp)) { input->setAllChannelValues(value.valueFloat); input->setDefaultValue(value.valueFloat); } } break; case dsp::Type::INTEGER: { if (ImGui::DragInt(getName().c_str(), &value.valueInt, io.KeyAlt ? 1.0f : 0.1f, 0, static_cast<int>(input->getRange()), values.empty() ? "%d" : values[value.valueInt].c_str(), ImGuiSliderFlags_AlwaysClamp)) { input->setAllChannelValues(value.valueInt); input->setDefaultValue(value.valueInt); } } break; case dsp::Type::BOOLEAN: { if (ImGui::DragInt(getName().c_str(), &value.valueInt, io.KeyAlt ? 100.0f : io.KeyShift ? 0.1f : 1.0f, 0, 1, "%d", ImGuiSliderFlags_AlwaysClamp)) { input->setAllChannelValues(value.valueInt); input->setDefaultValue(value.valueInt); } } break; } } else { // TODO: Make this a button input->lock(); switch (input->getType()) { case dsp::Type::RATIO: case dsp::Type::HERTZ: case dsp::Type::SECONDS: { float lastSample = input->getWrapper().getSample(0, input->getNumSamples() - 1); lastSample = lastSample == 0.0 ? 0.0 : lastSample; lastSample = isnan(lastSample) ? std::numeric_limits<float>::quiet_NaN() : lastSample; ImGui::DragFloat(getName().c_str(), &lastSample, 0.0f, 0.0f, 0.0f, ("%." + std::to_string(PRECISION) + "f").c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); } break; case dsp::Type::INTEGER: { int lastSample = input->getWrapper().getSample(0, input->getNumSamples() - 1); ImGui::DragInt(getName().c_str(), &lastSample, 0.0f, 0, 0, values.empty() ? "%d" : values[value.valueInt].c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); } break; case dsp::Type::BOOLEAN: { int lastSample = input->getWrapper().getSample(0, input->getNumSamples() - 1); ImGui::DragInt(getName().c_str(), &lastSample, 0.0f, 0, 0, "%d", ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); } break; } input->unlock(); } imnodes::EndInputAttribute(); ImGui::PopStyleVar(); } void particle::NodeGraph::Input::drawInspector() {} // TODO: Set can edit particle::NodeGraph::Output::Output( Data *data, int id, std::string name, std::shared_ptr<dsp::Output> output, std::vector<std::string> values) : Named(name) , data(data) , id(id) , output(output) , value(output->getType(), output->getDefaultValue()) , values(values) {} void particle::NodeGraph::Output::draw() { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, data->getStyle().nodeFramePadding); imnodes::BeginOutputAttribute(id, imnodes::PinShape::PinShape_QuadFilled); ImGui::SetNextItemWidth(FRAME_WIDTH); // TODO: Make this a button output->lock(); switch (output->getType()) { case dsp::Type::RATIO: case dsp::Type::HERTZ: case dsp::Type::SECONDS: { float lastSample = output->getWrapper().getSample(0, output->getNumSamples() - 1); lastSample = lastSample == 0.0 ? 0.0 : lastSample; lastSample = isnan(lastSample) ? std::numeric_limits<float>::quiet_NaN() : lastSample; ImGui::DragFloat(getName().c_str(), &lastSample, 0.0f, 0.0f, 0.0f, ("%." + std::to_string(PRECISION) + "f").c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); break; } case dsp::Type::INTEGER: { int lastSample = output->getWrapper().getSample(0, output->getNumSamples() - 1); ImGui::DragInt(getName().c_str(), &lastSample, 0.0f, 0, 0, values.empty() ? "%d" : values[value.valueInt].c_str(), ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); break; } case dsp::Type::BOOLEAN: { int lastSample = output->getWrapper().getSample(0, output->getNumSamples() - 1); ImGui::DragInt(getName().c_str(), &lastSample, 0.0f, 0, 0, "%d", ImGuiSliderFlags_AlwaysClamp | ImGuiSliderFlags_NoInput); break; } } output->unlock(); imnodes::EndOutputAttribute(); ImGui::PopStyleVar(); } void particle::NodeGraph::Output::drawInspector() {} particle::NodeGraph::Node::Category::Category(std::string name, std::vector<Type> types) : Named(name) , types(types) {} particle::NodeGraph::Node::Node(Data *data, int id, Type type, ImVec2 position, std::shared_ptr<dsp::Node> node) : Named("") , data(data) , id(id) , type(type) , position(position) , node(node) {} void particle::NodeGraph::Node::addInput(int id, std::string name, std::shared_ptr<dsp::Input> input, std::vector<std::string> values) { inputs.emplace(id, Input(data, id, name, input, values)); } void particle::NodeGraph::Node::addOutput(int id, std::string name, std::shared_ptr<dsp::Output> output, std::vector<std::string> values) { outputs.emplace(id, Output(data, id, name, output, values)); } std::string particle::NodeGraph::Node::getTypeName() const { return getTypeName(type); } void particle::NodeGraph::Node::draw(bool selected) { if (selected) { // TODO: uncomment //imnodes::PushStyleVar(imnodes::StyleVar_NodeBorderThickness, 2.5f); imnodes::PushColorStyle(imnodes::ColorStyle_NodeOutline, imnodes::GetStyle().colors[imnodes::ColorStyle_LinkSelected]); } imnodes::BeginNode(id); imnodes::BeginNodeTitleBar(); ImGui::TextUnformatted(getTypeName(type).c_str()); imnodes::EndNodeTitleBar(); ImGui::BeginGroup(); for (auto &input : inputs) { input.second.draw(); } ImGui::EndGroup(); ImGui::SameLine(0); drawContent(); ImGui::SameLine(0); ImGui::BeginGroup(); for (auto &output : outputs) { output.second.draw(); } ImGui::EndGroup(); imnodes::EndNode(); if (selected) { imnodes::PopColorStyle(); // TODO: uncomment //imnodes::PopStyleVar(); } } void particle::NodeGraph::Node::drawContent() { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, data->getStyle().windowPadding); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, data->getStyle().nodeFramePadding); switch (type) { // TODO: this node case Type::RECORDER: { std::shared_ptr<dsp::Recorder> resetTrigger = std::dynamic_pointer_cast<dsp::Recorder>(node); } break; // TODO: this node case Type::CHANNEL_MERGER: { std::shared_ptr<dsp::ChannelMerger> merger = std::dynamic_pointer_cast<dsp::ChannelMerger>(node); } break; // TODO: this node case Type::CHANNEL_SPLITTER: { std::shared_ptr<dsp::ChannelSplitter> splitter = std::dynamic_pointer_cast<dsp::ChannelSplitter>(node); } break; case Type::COMPRESSOR_GATE: { std::shared_ptr<dsp::CompressorGate> compressorGate = std::dynamic_pointer_cast<dsp::CompressorGate>(node); const dsp::Sample noiseFloor = 0.00390625; const dsp::Sample noiseCeiling = 256.0; std::vector<dsp::Sample> x; std::vector<std::vector<dsp::Sample>> response(compressorGate->getNumChannels()); { for (dsp::Sample gain = noiseFloor; gain <= noiseCeiling; gain *= 1.0115794542598986) { x.push_back(gain); for (size_t channel = 0; channel < compressorGate->getNumChannels(); ++channel) { response[channel].push_back(compressorGate->getGainResponse(channel, gain)); } } } ImGui::BeginGroup(); drawPlot("Log Gain", x, response, noiseFloor, noiseCeiling, noiseFloor, noiseCeiling, ImVec2(getFrameHeight(8.0f), getFrameHeight(8.0f)), ImPlotAxisFlags_LogScale, ImPlotAxisFlags_LogScale); drawLabel("Log Gain"); ImGui::EndGroup(); } break; case Type::ENVELOPE: { std::shared_ptr<dsp::Envelope> envelope = std::dynamic_pointer_cast<dsp::Envelope>(node); } break; case Type::SHAPER: { std::shared_ptr<dsp::Shaper> shaper = std::dynamic_pointer_cast<dsp::Shaper>(node); std::vector<dsp::Sample> x; std::vector<std::vector<dsp::Sample>> output(shaper->getNumChannels()); { for (dsp::Sample input = -1.0; input <= 1.0; input += 0.015625) { x.push_back(input); for (size_t channel = 0; channel < shaper->getNumChannels(); ++channel) { output[channel].push_back(shaper->getOutputSignal(channel, input)); } } } ImGui::BeginGroup(); drawPlot("Gain", x, output, -1.0, 1.0, -1.0, 1.0, ImVec2(getFrameHeight(3.0f), getFrameHeight(3.0f)), ImPlotAxisFlags_None, ImPlotAxisFlags_None); drawLabel("Gain"); ImGui::EndGroup(); } break; // TODO: this node case Type::MIDI_INPUT: { std::shared_ptr<dsp::MidiInput> midiInput = std::dynamic_pointer_cast<dsp::MidiInput>(node); } break; // TODO: this node case Type::MIDI_OUTPUT: { std::shared_ptr<dsp::MidiOutput> midiOutput = std::dynamic_pointer_cast<dsp::MidiOutput>(node); } break; case Type::BIQUAD: { std::shared_ptr<dsp::Biquad> biquad = std::dynamic_pointer_cast<dsp::Biquad>(node); const dsp::Sample zero = 6.75; const dsp::Sample nyquist = 0.5 * biquad->getSampleRate(); std::vector<dsp::Sample> x; std::vector<std::vector<dsp::Sample>> magnitude(biquad->getNumChannels()); std::vector<std::vector<dsp::Sample>> phase(biquad->getNumChannels()); { dsp::Sample m; dsp::Sample p; for (dsp::Sample frequency = zero; frequency <= nyquist; frequency *= 1.0594630943592953) { x.push_back(frequency); for (size_t channel = 0; channel < biquad->getNumChannels(); ++channel) { biquad->getMagnitudeAndPhaseResponse(channel, frequency, m, p); magnitude[channel].push_back(m); phase[channel].push_back(p); } } } ImGui::BeginGroup(); drawPlot("Magnitude", x, magnitude, zero, nyquist, 0.0625, 16.0, ImVec2(2.0f * FRAME_WIDTH, getFrameHeight(3.0f)), ImPlotAxisFlags_LogScale, ImPlotAxisFlags_LogScale); drawLabel("Magnitude"); drawPlot("Phase", x, phase, zero, nyquist, 0.0, 1.0, ImVec2(2.0f * FRAME_WIDTH, getFrameHeight(2.0f)), ImPlotAxisFlags_LogScale, ImPlotAxisFlags_None); drawLabel("Phase"); ImGui::EndGroup(); } break; // TODO: this node case Type::ONE_POLE: { std::shared_ptr<dsp::OnePole> onePole = std::dynamic_pointer_cast<dsp::OnePole>(node); } break; case Type::FUNCTION_OSCILLATOR: { std::shared_ptr<dsp::FunctionOscillator> functionOscillator = std::dynamic_pointer_cast<dsp::FunctionOscillator>(node); std::string currentName; for (const auto &pair : functions) { if (pair.second == functionOscillator->getFunction()) { currentName = pair.first; break; } } ImGui::SetNextItemWidth(90.0f); if (ImGui::BeginCombo("Function", currentName.c_str())) { for (const auto &name : functionNames) { bool is_selected = currentName == name; if (ImGui::Selectable(name.c_str(), is_selected)) { functionOscillator->setFunction(functions[name]); } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } } break; // TODO: this node case Type::SAMPLE_PLAYER: { std::shared_ptr<dsp::SamplePlayer> samplePlayer = std::dynamic_pointer_cast<dsp::SamplePlayer>(node); } break; // TODO: this node case Type::TABLE_OSCILLATOR: { std::shared_ptr<dsp::TableOscillator> tableOscillator = std::dynamic_pointer_cast<dsp::TableOscillator>(node); } break; case Type::RESET_TRIGGER: { std::shared_ptr<dsp::ResetTrigger> resetTrigger = std::dynamic_pointer_cast<dsp::ResetTrigger>(node); if (ImGui::Button("Reset")) { resetTrigger->reset(); } } break; // TODO: this node case Type::SEQUENCER: { std::shared_ptr<dsp::Sequencer> sequencer = std::dynamic_pointer_cast<dsp::Sequencer>(node); } break; } ImGui::PopStyleVar(); ImGui::PopStyleVar(); } void particle::NodeGraph::Node::drawInspector() {} std::vector<particle::NodeGraph::Node::Category> particle::NodeGraph::Node::getCategories(bool isPlugin) { std::vector<Category> categories; categories.push_back(Category("Analyzers", std::vector<Type>{Type::RECORDER})); categories.push_back(Category( "Channel", std::vector<Type>{ Type::CHANNEL_MERGER, Type::CHANNEL_SPLITTER, Type::MID_SIDE, Type::SPREAD, Type::STEREO_PANNER})); categories.push_back(Category("Delays", std::vector<Type>{Type::CONVOLVER, Type::VARIABLE_DELAY})); categories.push_back(Category( "Dynamics", std::vector<Type>{ Type::CLIPPER, Type::COMPRESSOR_GATE, Type::DRY_WET, Type::ENVELOPE, Type::LAG, Type::SHAPER})); categories.push_back(Category("External", std::vector<Type>{Type::AUDIO_INPUT, Type::AUDIO_INPUT_CLIPPING, Type::AUDIO_OUTPUT, Type::AUDIO_OUTPUT_CLIPPING, Type::MIDI_INPUT, Type::MIDI_OUTPUT})); categories.push_back(Category("Filters", std::vector<Type>{Type::BIQUAD, Type::CROSSOVER, Type::ONE_POLE})); categories.push_back(Category("Generators", std::vector<Type>{Type::FUNCTION_OSCILLATOR, Type::NOISE, Type::PHASOR, Type::SAMPLE_PLAYER, Type::TABLE_OSCILLATOR})); categories.push_back(Category("Math", std::vector<Type>{Type::ABSOLUTE_VALUE, Type::BOOLEAN_MASK, Type::COMPARISON, Type::DIVISION, Type::FLOOR, Type::FORWARD_FFT, Type::FREQUENCY_TO_NOTE, Type::HYPERBOLIC, Type::INVERSE_FFT, Type::LOGARITHM, Type::MODULO, Type::MULTIPLICATION, Type::NEGATIVE, Type::NOTE_TO_FREQUENCY, Type::NOT_GATE, Type::POWER, Type::RECIPROCAL, Type::TRIGONOMETRIC})); if (isPlugin) { categories.push_back(Category( "Plugin", std::vector<Type>{Type::BEAT_DURATION, Type::BEAT_RATE, Type::TIME_SIGNATURE, Type::TRANSPORT_STATE})); } categories.push_back(Category("Trigger", std::vector<Type>{Type::CLOCK_TRIGGER, Type::DIFFERENTIATOR, Type::INTEGRATOR, Type::ON_OFF, Type::RESET_TRIGGER, Type::SAMPLE_AND_HOLD, Type::SEQUENCER, Type::TRIGGER_HOLD})); categories.push_back(Category("Variables", std::vector<Type>{Type::BUFFER_DURATION, Type::BUFFER_RATE, Type::EULER, Type::INF, Type::PHI, Type::PI, Type::SAMPLE_DURATION, Type::SAMPLE_RATE, Type::TAU, Type::VARIABLE})); return categories; } std::string particle::NodeGraph::Node::getTypeName(Type type) { switch (type) { case Type::CUSTOM: return "Custom"; case Type::RECORDER: return "Recorder"; case Type::CHANNEL_MERGER: return "Channel Merger"; case Type::CHANNEL_SPLITTER: return "Channel Splitter"; case Type::MID_SIDE: return "Mid/Side"; case Type::SPREAD: return "Spread"; case Type::STEREO_PANNER: return "Stereo Panner"; case Type::CONVOLVER: return "Convolver"; case Type::VARIABLE_DELAY: return "Variable Delay"; case Type::CLIPPER: return "Clipper"; case Type::COMPRESSOR_GATE: return "Compressor/Gate"; case Type::DRY_WET: return "Dry/Wet"; case Type::ENVELOPE: return "Envelope"; case Type::LAG: return "Lag"; case Type::SHAPER: return "Shaper"; case Type::AUDIO_INPUT: return "Audio Input"; case Type::AUDIO_INPUT_CLIPPING: return "Audio Input Clipping"; case Type::AUDIO_OUTPUT: return "Audio Output"; case Type::AUDIO_OUTPUT_CLIPPING: return "Audio Output Clipping"; case Type::MIDI_INPUT: return "MIDI Input"; case Type::MIDI_OUTPUT: return "MIDI Output"; case Type::BIQUAD: return "Biquad"; case Type::CROSSOVER: return "Crossover"; case Type::ONE_POLE: return "One-Pole"; case Type::FUNCTION_OSCILLATOR: return "Function Oscillator"; case Type::NOISE: return "Noise"; case Type::PHASOR: return "Phasor"; case Type::SAMPLE_PLAYER: return "Sample Player"; case Type::TABLE_OSCILLATOR: return "Table Oscillator"; case Type::ABSOLUTE_VALUE: return "Absolute Value"; case Type::BOOLEAN_MASK: return "Boolean Mask"; case Type::COMPARISON: return "Comparison"; case Type::DIVISION: return "Division"; case Type::FLOOR: return "Floor"; case Type::FORWARD_FFT: return "Forward FFT"; case Type::FREQUENCY_TO_NOTE: return "Frequency to Note"; case Type::HYPERBOLIC: return "Hyperbolic"; case Type::INVERSE_FFT: return "Inverse FFT"; case Type::LOGARITHM: return "Logarithm"; case Type::MODULO: return "Modulo"; case Type::MULTIPLICATION: return "Multiplication"; case Type::NEGATIVE: return "Negative"; case Type::NOTE_TO_FREQUENCY: return "Note to Frequency"; case Type::NOT_GATE: return "Not Gate"; case Type::POWER: return "Power"; case Type::RECIPROCAL: return "Reciprocal"; case Type::TRIGONOMETRIC: return "Trigonometric"; case Type::BEAT_DURATION: return "Beat Duration"; case Type::BEAT_RATE: return "Beat Rate"; case Type::TIME_SIGNATURE: return "Time Signature"; case Type::TRANSPORT_STATE: return "Transport State"; case Type::CLOCK_TRIGGER: return "Clock Trigger"; case Type::DIFFERENTIATOR: return "Differentiator"; case Type::INTEGRATOR: return "Integrator"; case Type::ON_OFF: return "On/Off"; case Type::RESET_TRIGGER: return "Reset Trigger"; case Type::SAMPLE_AND_HOLD: return "Sample & Hold"; case Type::SEQUENCER: return "Sequencer"; case Type::TRIGGER_HOLD: return "Trigger Hold"; case Type::BUFFER_DURATION: return "Buffer Duration"; case Type::BUFFER_RATE: return "Buffer Rate"; case Type::EULER: return "Euler"; case Type::INF: return "Infinity"; case Type::PHI: return "Phi"; case Type::PI: return "Pi"; case Type::SAMPLE_DURATION: return "Sample Duration"; case Type::SAMPLE_RATE: return "Sample Rate"; case Type::TAU: return "Tau"; case Type::VARIABLE: return "Variable"; } } particle::NodeGraph::Node particle::NodeGraph::Node::generate(Data *data, int &counter, int id, Type type, ImVec2 position) { switch (type) { case Type::CUSTOM: { std::shared_ptr<dsp::Node> custom = std::make_shared<dsp::Node>(); Node node(data, id, type, position, custom); return node; } case Type::RECORDER: { std::shared_ptr<dsp::Recorder> recorder = std::make_shared<dsp::Recorder>(); Node node(data, id, type, position, recorder); node.addInput(++counter, "Input", recorder->getInput()); node.addInput(++counter, "Gate", recorder->getGate()); node.addInput(++counter, "Reset", recorder->getReset()); return node; } case Type::CHANNEL_MERGER: { // TODO: handle more than 2 channels std::shared_ptr<dsp::ChannelMerger> merger = std::make_shared<dsp::ChannelMerger>(); merger->setNumOutputChannels(2); Node node(data, id, type, position, merger); node.addInput(++counter, "Channel 1", merger->getInput(0)); node.addInput(++counter, "Channel 2", merger->getInput(1)); node.addOutput(++counter, "Output", merger->getOutput()); return node; } case Type::CHANNEL_SPLITTER: { // TODO: handle more than 2 channels std::shared_ptr<dsp::ChannelSplitter> splitter = std::make_shared<dsp::ChannelSplitter>(); splitter->setNumInputChannels(2); Node node(data, id, type, position, splitter); node.addInput(++counter, "Input", splitter->getInput()); node.addOutput(++counter, "Channel 1", splitter->getOutput(0)); node.addOutput(++counter, "Channel 2", splitter->getOutput(1)); return node; } case Type::MID_SIDE: { std::shared_ptr<dsp::MidSide> midSide = std::make_shared<dsp::MidSide>(); Node node(data, id, type, position, midSide); node.addInput(++counter, "Input", midSide->getInput()); node.addInput(++counter, "Mix Amount", midSide->getMixAmount()); node.addOutput(++counter, "Mid", midSide->getMid()); node.addOutput(++counter, "Side", midSide->getSide()); return node; } case Type::SPREAD: { std::shared_ptr<dsp::Spread> spread = std::make_shared<dsp::Spread>(); Node node(data, id, type, position, spread); node.addInput(++counter, "Input", spread->getInput()); node.addInput(++counter, "Spread", spread->getSpread()); node.addInput(++counter, "Mode", spread->getMode(), std::vector<std::string>{"UNIPOLAR", "BIPOLAR"}); node.addOutput(++counter, "Output", spread->getOutput()); return node; } case Type::STEREO_PANNER: { std::shared_ptr<dsp::StereoPanner> stereoPanner = std::make_shared<dsp::StereoPanner>(); Node node(data, id, type, position, stereoPanner); node.addInput(++counter, "Input", stereoPanner->getInput()); node.addInput(++counter, "Direction", stereoPanner->getDirection()); node.addOutput(++counter, "Left", stereoPanner->getLeft()); node.addOutput(++counter, "Right", stereoPanner->getRight()); return node; } case Type::CONVOLVER: { std::shared_ptr<dsp::Convolver> convolver = std::make_shared<dsp::Convolver>(); Node node(data, id, type, position, convolver); node.addInput(++counter, "Input", convolver->getInput()); node.addOutput(++counter, "Output", convolver->getOutput()); return node; } case Type::VARIABLE_DELAY: { // TODO: implement feedback interface std::shared_ptr<dsp::VariableDelay> variableDelay = std::make_shared<dsp::VariableDelay>(); Node node(data, id, type, position, variableDelay); node.addInput(++counter, "Input", variableDelay->getInput()); node.addInput(++counter, "Delay Time", variableDelay->getDelayTime()); node.addInput(++counter, "Decay Time", variableDelay->getDecayTime()); node.addInput(++counter, "Reset", variableDelay->getReset()); node.addOutput(++counter, "Output", variableDelay->getOutput()); return node; } case Type::CLIPPER: { std::shared_ptr<dsp::Clipper> clipper = std::make_shared<dsp::Clipper>(); Node node(data, id, type, position, clipper); node.addInput(++counter, "Input", clipper->getInput()); node.addInput(++counter, "Minimum", clipper->getMinimum()); node.addInput(++counter, "Maximum", clipper->getMaximum()); node.addInput(++counter, "Mode", clipper->getMode(), std::vector<std::string>{"CLIP", "WRAP", "MIRROR"}); node.addOutput(++counter, "Output", clipper->getOutput()); return node; } case Type::COMPRESSOR_GATE: { std::shared_ptr<dsp::CompressorGate> compressorGate = std::make_shared<dsp::CompressorGate>(); Node node(data, id, type, position, compressorGate); node.addInput(++counter, "Input", compressorGate->getInput()); node.addInput(++counter, "Control", compressorGate->getControl()); node.addInput(++counter, "Threshold", compressorGate->getThreshold()); node.addInput(++counter, "Softness", compressorGate->getSoftness()); node.addInput(++counter, "Compression Ratio", compressorGate->getCompressionRatio()); node.addInput(++counter, "Gate Ratio", compressorGate->getGateRatio()); node.addInput(++counter, "Attack", compressorGate->getAttack()); node.addInput(++counter, "Release", compressorGate->getRelease()); node.addOutput(++counter, "Output", compressorGate->getOutput()); node.addOutput(++counter, "Gain", compressorGate->getGain()); return node; } case Type::DRY_WET: { std::shared_ptr<dsp::DryWet> dryWet = std::make_shared<dsp::DryWet>(); Node node(data, id, type, position, dryWet); node.addInput(++counter, "Dry", dryWet->getDry()); node.addInput(++counter, "Wet", dryWet->getWet()); node.addInput(++counter, "Mix Amount", dryWet->getMixAmount()); node.addOutput(++counter, "A", dryWet->getA()); node.addOutput(++counter, "B", dryWet->getB()); return node; } case Type::ENVELOPE: { std::shared_ptr<dsp::Envelope> envelope = std::make_shared<dsp::Envelope>(); Node node(data, id, type, position, envelope); node.addInput(++counter, "Attack", envelope->getAttack()); node.addInput(++counter, "Release", envelope->getRelease()); node.addInput(++counter, "Attack Shape", envelope->getAttackShape(), std::vector<std::string>{"LINEAR", "EXPONENTIAL"}); node.addInput(++counter, "Release Shape", envelope->getReleaseShape(), std::vector<std::string>{"LINEAR", "EXPONENTIAL"}); node.addInput(++counter, "Gate", envelope->getGate()); node.addInput(++counter, "Reset", envelope->getReset()); node.addOutput(++counter, "Output", envelope->getOutput()); return node; } case Type::LAG: { std::shared_ptr<dsp::Lag> lag = std::make_shared<dsp::Lag>(); Node node(data, id, type, position, lag); node.addInput(++counter, "Input", lag->getInput()); node.addInput(++counter, "Lag Time", lag->getLagTime()); node.addOutput(++counter, "Output", lag->getOutput()); return node; } case Type::SHAPER: { std::shared_ptr<dsp::Shaper> shaper = std::make_shared<dsp::Shaper>(); Node node(data, id, type, position, shaper); node.addInput(++counter, "Input", shaper->getInput()); node.addInput(++counter, "Drive", shaper->getDrive()); node.addInput(++counter, "Mode", shaper->getMode(), std::vector<std::string>{"HYPERBOLIC", "RATIONAL"}); node.addOutput(++counter, "Output", shaper->getOutput()); return node; } case Type::AUDIO_INPUT: { Node node(data, id, type, position, nullptr); node.addOutput(++counter, "Output", data->getNodeProcessor()->getAudioInput()); return node; } case Type::AUDIO_INPUT_CLIPPING: { Node node(data, id, type, position, nullptr); node.addOutput(++counter, "Output", data->getNodeProcessor()->getAudioInputClipping()); return node; } case Type::AUDIO_OUTPUT: { Node node(data, id, type, position, nullptr); node.addInput(++counter, "Input", data->getNodeProcessor()->getAudioOutput()); return node; } case Type::AUDIO_OUTPUT_CLIPPING: { Node node(data, id, type, position, nullptr); node.addOutput(++counter, "Output", data->getNodeProcessor()->getAudioOutputClipping()); return node; } case Type::MIDI_INPUT: { std::shared_ptr<dsp::MidiInput> midiInput = std::make_shared<dsp::MidiInput>(data->getNodeProcessor()->getInputMessages()); Node node(data, id, type, position, midiInput); node.addOutput(++counter, "Output", midiInput->getOutput()); return node; } case Type::MIDI_OUTPUT: { std::shared_ptr<dsp::MidiOutput> midiOutput = std::make_shared<dsp::MidiOutput>(data->getNodeProcessor()->getOutputMessages()); Node node(data, id, type, position, midiOutput); node.addInput(++counter, "Input", midiOutput->getInput()); return node; } case Type::BIQUAD: { std::shared_ptr<dsp::Biquad> biquad = std::make_shared<dsp::Biquad>(); Node node(data, id, type, position, biquad); node.addInput(++counter, "Input", biquad->getInput()); node.addInput(++counter, "Frequency", biquad->getFrequency()); node.addInput(++counter, "Resonance", biquad->getResonance()); node.addInput(++counter, "Amplitude", biquad->getAmplitude()); node.addInput(++counter, "Mode", biquad->getMode(), std::vector<std::string>{"LOW PASS", "HIGH PASS", "BAND PASS", "BAND STOP", "LOW SHELF", "HIGH SHELF", "PEAK EQ", "ALL PASS"}); node.addOutput(++counter, "Output", biquad->getOutput()); return node; } case Type::CROSSOVER: { std::shared_ptr<dsp::Crossover> crossover = std::make_shared<dsp::Crossover>(); Node node(data, id, type, position, crossover); node.addInput(++counter, "Input", crossover->getInput()); node.addInput(++counter, "Frequency", crossover->getFrequency()); node.addOutput(++counter, "Low", crossover->getLow()); node.addOutput(++counter, "High", crossover->getHigh()); return node; } case Type::ONE_POLE: { std::shared_ptr<dsp::OnePole> onePole = std::make_shared<dsp::OnePole>(); Node node(data, id, type, position, onePole); node.addInput(++counter, "Input", onePole->getInput()); node.addInput(++counter, "Frequency", onePole->getFrequency()); node.addInput(++counter, "Mode", onePole->getMode(), std::vector<std::string>{"LOW PASS", "HIGH PASS"}); node.addOutput(++counter, "Output", onePole->getOutput()); return node; } case Type::FUNCTION_OSCILLATOR: { std::shared_ptr<dsp::FunctionOscillator> functionOscillator = std::make_shared<dsp::FunctionOscillator>(); functionOscillator->setFunction(functions[functionNames[0]]); Node node(data, id, type, position, functionOscillator); node.addInput(++counter, "Phase", functionOscillator->getPhase()); node.addOutput(++counter, "Output", functionOscillator->getOutput()); return node; } case Type::NOISE: { std::shared_ptr<dsp::Noise> noise = std::make_shared<dsp::Noise>(); Node node(data, id, type, position, noise); node.addInput(++counter, "Mode", noise->getMode(), std::vector<std::string>{"WHITE", "PINK"}); node.addOutput(++counter, "Output", noise->getOutput()); return node; } case Type::PHASOR: { std::shared_ptr<dsp::Phasor> phasor = std::make_shared<dsp::Phasor>(); Node node(data, id, type, position, phasor); node.addInput(++counter, "Frequency", phasor->getFrequency()); node.addInput(++counter, "Mode", phasor->getMode(), std::vector<std::string>{"WRAPPED", "UNBOUNDED"}); node.addInput(++counter, "Reset", phasor->getReset()); node.addOutput(++counter, "Output", phasor->getOutput()); return node; } case Type::SAMPLE_PLAYER: { std::shared_ptr<dsp::SamplePlayer> samplePlayer = std::make_shared<dsp::SamplePlayer>(); Node node(data, id, type, position, samplePlayer); node.addInput(++counter, "Speed", samplePlayer->getSpeed()); node.addInput(++counter, "Start Time", samplePlayer->getStartTime()); node.addInput(++counter, "Sample Index", samplePlayer->getSampleIndex()); node.addInput(++counter, "Interpolation", samplePlayer->getInterpolation(), std::vector<std::string>{"NONE", "LINEAR", "SMOOTH"}); node.addInput(++counter, "Gate", samplePlayer->getGate()); node.addInput(++counter, "Reset", samplePlayer->getReset()); node.addOutput(++counter, "Output", samplePlayer->getOutput()); node.addOutput(++counter, "Current Time", samplePlayer->getCurrentTime()); return node; } case Type::TABLE_OSCILLATOR: { std::shared_ptr<dsp::TableOscillator> tableOscillator = std::make_shared<dsp::TableOscillator>(); Node node(data, id, type, position, tableOscillator); node.addInput(++counter, "Phase", tableOscillator->getPhase()); node.addInput(++counter, "Position", tableOscillator->getPosition()); node.addInput(++counter, "Phase Interpolation", tableOscillator->getPhaseInterpolation(), std::vector<std::string>{"NONE", "LINEAR", "SMOOTH"}); node.addInput(++counter, "Position Interpolation", tableOscillator->getPositionInterpolation(), std::vector<std::string>{"NONE", "LINEAR", "SMOOTH"}); node.addOutput(++counter, "Output", tableOscillator->getOutput()); return node; } case Type::ABSOLUTE_VALUE: { std::shared_ptr<dsp::AbsoluteValue> absoluteValue = std::make_shared<dsp::AbsoluteValue>(); Node node(data, id, type, position, absoluteValue); node.addInput(++counter, "Input", absoluteValue->getInput()); node.addOutput(++counter, "Output", absoluteValue->getOutput()); return node; } case Type::BOOLEAN_MASK: { std::shared_ptr<dsp::BooleanMask> booleanMask = std::make_shared<dsp::BooleanMask>(); Node node(data, id, type, position, booleanMask); node.addInput(++counter, "Input", booleanMask->getInput()); node.addInput(++counter, "Mask", booleanMask->getMask()); node.addOutput(++counter, "Output", booleanMask->getOutput()); return node; } case Type::COMPARISON: { std::shared_ptr<dsp::Comparison> comparison = std::make_shared<dsp::Comparison>(); Node node(data, id, type, position, comparison); node.addInput(++counter, "Input", comparison->getInput()); node.addInput(++counter, "Threshold", comparison->getThreshold()); node.addOutput(++counter, "Output", comparison->getOutput()); return node; } case Type::DIVISION: { std::shared_ptr<dsp::Division> division = std::make_shared<dsp::Division>(); Node node(data, id, type, position, division); node.addInput(++counter, "Input", division->getInput()); node.addInput(++counter, "Divisor", division->getDivisor()); node.addOutput(++counter, "Output", division->getOutput()); return node; } case Type::FLOOR: { std::shared_ptr<dsp::Floor> floor = std::make_shared<dsp::Floor>(); Node node(data, id, type, position, floor); node.addInput(++counter, "Input", floor->getInput()); node.addInput(++counter, "Divisor", floor->getDivisor()); node.addOutput(++counter, "Output", floor->getOutput()); return node; } case Type::FORWARD_FFT: { std::shared_ptr<dsp::ForwardFFT> forwardFFT = std::make_shared<dsp::ForwardFFT>(); Node node(data, id, type, position, forwardFFT); node.addInput(++counter, "Input", forwardFFT->getInput()); node.addOutput(++counter, "Magnitude", forwardFFT->getMagnitude()); node.addOutput(++counter, "Phase", forwardFFT->getPhase()); return node; } case Type::FREQUENCY_TO_NOTE: { std::shared_ptr<dsp::FrequencyToNote> toNote = std::make_shared<dsp::FrequencyToNote>(); Node node(data, id, type, position, toNote); node.addInput(++counter, "Frequency", toNote->getInput()); node.addInput(++counter, "Tuning Frequency", toNote->getTuningFrequency()); node.addOutput(++counter, "Note", toNote->getOutput()); return node; } case Type::HYPERBOLIC: { std::shared_ptr<dsp::Hyperbolic> hyperbolic = std::make_shared<dsp::Hyperbolic>(); Node node(data, id, type, position, hyperbolic); node.addInput(++counter, "Input", hyperbolic->getInput()); node.addInput( ++counter, "Mode", hyperbolic->getMode(), std::vector<std::string>{"SINE", "COSINE", "TANGENT"}); node.addOutput(++counter, "Output", hyperbolic->getOutput()); return node; } case Type::INVERSE_FFT: { std::shared_ptr<dsp::InverseFFT> inverseFFT = std::make_shared<dsp::InverseFFT>(); Node node(data, id, type, position, inverseFFT); node.addInput(++counter, "Magnitude", inverseFFT->getMagnitude()); node.addInput(++counter, "Phase", inverseFFT->getPhase()); node.addOutput(++counter, "Output", inverseFFT->getOutput()); return node; } case Type::LOGARITHM: { std::shared_ptr<dsp::Logarithm> logarithm = std::make_shared<dsp::Logarithm>(); Node node(data, id, type, position, logarithm); node.addInput(++counter, "Input", logarithm->getInput()); node.addInput(++counter, "Base", logarithm->getBase()); node.addOutput(++counter, "Exponent", logarithm->getOutput()); return node; } case Type::MODULO: { std::shared_ptr<dsp::Modulo> modulo = std::make_shared<dsp::Modulo>(); Node node(data, id, type, position, modulo); node.addInput(++counter, "Input", modulo->getInput()); node.addInput(++counter, "Divisor", modulo->getDivisor()); node.addOutput(++counter, "Output", modulo->getOutput()); return node; } case Type::MULTIPLICATION: { std::shared_ptr<dsp::Multiplication> multiplication = std::make_shared<dsp::Multiplication>(); Node node(data, id, type, position, multiplication); node.addInput(++counter, "Input", multiplication->getInput()); node.addInput(++counter, "Factor", multiplication->getFactor()); node.addOutput(++counter, "Output", multiplication->getOutput()); return node; } case Type::NEGATIVE: { std::shared_ptr<dsp::Negative> negative = std::make_shared<dsp::Negative>(); Node node(data, id, type, position, negative); node.addInput(++counter, "Input", negative->getInput()); node.addOutput(++counter, "Output", negative->getOutput()); return node; } case Type::NOTE_TO_FREQUENCY: { std::shared_ptr<dsp::NoteToFrequency> toFrequency = std::make_shared<dsp::NoteToFrequency>(); Node node(data, id, type, position, toFrequency); node.addInput(++counter, "Note", toFrequency->getInput()); node.addInput(++counter, "Tuning Frequency", toFrequency->getTuningFrequency()); node.addOutput(++counter, "Frequency", toFrequency->getOutput()); return node; } case Type::NOT_GATE: { std::shared_ptr<dsp::NotGate> notGate = std::make_shared<dsp::NotGate>(); Node node(data, id, type, position, notGate); node.addInput(++counter, "Input", notGate->getInput()); node.addOutput(++counter, "Output", notGate->getOutput()); return node; } case Type::POWER: { std::shared_ptr<dsp::Power> power = std::make_shared<dsp::Power>(); Node node(data, id, type, position, power); node.addInput(++counter, "Base", power->getInput()); node.addInput(++counter, "Exponent", power->getExponent()); node.addOutput(++counter, "Output", power->getOutput()); return node; } case Type::RECIPROCAL: { std::shared_ptr<dsp::Reciprocal> reciprocal = std::make_shared<dsp::Reciprocal>(); Node node(data, id, type, position, reciprocal); node.addInput(++counter, "Input", reciprocal->getInput()); node.addOutput(++counter, "Output", reciprocal->getOutput()); return node; } case Type::TRIGONOMETRIC: { std::shared_ptr<dsp::Trigonometric> trigonometric = std::make_shared<dsp::Trigonometric>(); Node node(data, id, type, position, trigonometric); node.addInput(++counter, "Input", trigonometric->getInput()); node.addInput( ++counter, "Mode", trigonometric->getMode(), std::vector<std::string>{"SINE", "COSINE", "TANGENT"}); node.addOutput(++counter, "Output", trigonometric->getOutput()); return node; } case Type::BEAT_DURATION: { std::shared_ptr<dsp::BeatDuration> beatDuration = std::make_shared<dsp::BeatDuration>(data->getAudioProcessor()); Node node(data, id, type, position, beatDuration); node.addOutput(++counter, "Output", beatDuration->getOutput()); return node; } case Type::BEAT_RATE: { std::shared_ptr<dsp::BeatRate> beatRate = std::make_shared<dsp::BeatRate>(data->getAudioProcessor()); Node node(data, id, type, position, beatRate); node.addOutput(++counter, "Output", beatRate->getOutput()); return node; } case Type::TIME_SIGNATURE: { std::shared_ptr<dsp::TimeSignature> timeSignature = std::make_shared<dsp::TimeSignature>(data->getAudioProcessor()); Node node(data, id, type, position, timeSignature); node.addOutput(++counter, "Numerator", timeSignature->getNumerator()); node.addOutput(++counter, "Denominator", timeSignature->getDenominator()); return node; } case Type::TRANSPORT_STATE: { std::shared_ptr<dsp::TransportState> transportState = std::make_shared<dsp::TransportState>(data->getAudioProcessor()); Node node(data, id, type, position, transportState); node.addOutput(++counter, "Time Elapsed", transportState->getTimeElapsed()); node.addOutput(++counter, "Is Playing", transportState->isPlaying()); node.addOutput(++counter, "Is Recording", transportState->isRecording()); return node; } case Type::CLOCK_TRIGGER: { std::shared_ptr<dsp::ClockTrigger> clockTrigger = std::make_shared<dsp::ClockTrigger>(); Node node(data, id, type, position, clockTrigger); node.addInput(++counter, "Interval", clockTrigger->getInterval()); node.addInput(++counter, "Delay Time", clockTrigger->getDelayTime()); node.addInput(++counter, "Reset", clockTrigger->getReset()); node.addOutput(++counter, "Output", clockTrigger->getOutput()); node.addOutput(++counter, "Current Time", clockTrigger->getCurrentTime()); return node; } case Type::DIFFERENTIATOR: { std::shared_ptr<dsp::Differentiator> differentiator = std::make_shared<dsp::Differentiator>(); Node node(data, id, type, position, differentiator); node.addInput(++counter, "Input", differentiator->getInput()); node.addInput(++counter, "Gate", differentiator->getGate()); node.addInput(++counter, "Reset", differentiator->getReset()); node.addOutput(++counter, "Output", differentiator->getOutput()); return node; } case Type::INTEGRATOR: { std::shared_ptr<dsp::Integrator> integrator = std::make_shared<dsp::Integrator>(); Node node(data, id, type, position, integrator); node.addInput(++counter, "Input", integrator->getInput()); node.addInput(++counter, "Gate", integrator->getGate()); node.addInput(++counter, "Reset", integrator->getReset()); node.addOutput(++counter, "Output", integrator->getOutput()); return node; } case Type::ON_OFF: { std::shared_ptr<dsp::OnOff> onOff = std::make_shared<dsp::OnOff>(); Node node(data, id, type, position, onOff); node.addInput(++counter, "On", onOff->getOnTrigger()); node.addInput(++counter, "Off", onOff->getOffTrigger()); node.addOutput(++counter, "Output", onOff->getOutput()); return node; } case Type::RESET_TRIGGER: { std::shared_ptr<dsp::ResetTrigger> resetTrigger = std::make_shared<dsp::ResetTrigger>(); Node node(data, id, type, position, resetTrigger); node.addOutput(++counter, "Output", resetTrigger->getOutput()); return node; } case Type::SAMPLE_AND_HOLD: { std::shared_ptr<dsp::SampleAndHold> sampleAndHold = std::make_shared<dsp::SampleAndHold>(); Node node(data, id, type, position, sampleAndHold); node.addInput(++counter, "Input", sampleAndHold->getInput()); node.addInput(++counter, "Gate", sampleAndHold->getGate()); node.addInput(++counter, "Reset", sampleAndHold->getReset()); node.addOutput(++counter, "Output", sampleAndHold->getOutput()); return node; } case Type::SEQUENCER: { std::shared_ptr<dsp::Sequencer> sequencer = std::make_shared<dsp::Sequencer>(); Node node(data, id, type, position, sequencer); node.addInput(++counter, "Sequence Index", sequencer->getSequenceIndex()); node.addInput(++counter, "Position Index", sequencer->getPositionIndex()); node.addOutput(++counter, "Output", sequencer->getOutput()); return node; } case Type::TRIGGER_HOLD: { std::shared_ptr<dsp::TriggerHold> triggerHold = std::make_shared<dsp::TriggerHold>(); Node node(data, id, type, position, triggerHold); node.addInput(++counter, "Input", triggerHold->getInput()); node.addInput(++counter, "Hold Time", triggerHold->getHoldTime()); node.addOutput(++counter, "Output", triggerHold->getOutput()); return node; } case Type::BUFFER_DURATION: { std::shared_ptr<dsp::BufferDuration> bufferDuration = std::make_shared<dsp::BufferDuration>(); Node node(data, id, type, position, bufferDuration); node.addOutput(++counter, "Output", bufferDuration->getOutput()); return node; } case Type::BUFFER_RATE: { std::shared_ptr<dsp::BufferRate> bufferRate = std::make_shared<dsp::BufferRate>(); Node node(data, id, type, position, bufferRate); node.addOutput(++counter, "Output", bufferRate->getOutput()); return node; } case Type::EULER: { std::shared_ptr<dsp::Variable> variable = std::make_shared<dsp::Variable>(dsp::E); Node node(data, id, type, position, variable); node.addOutput(++counter, "Output", variable->getOutput()); return node; } case Type::INF: { std::shared_ptr<dsp::Infinity> infinity = std::make_shared<dsp::Infinity>(); Node node(data, id, type, position, infinity); node.addInput(++counter, "Mode", infinity->getMode()); node.addOutput(++counter, "Output", infinity->getOutput()); return node; } case Type::PHI: { std::shared_ptr<dsp::Variable> variable = std::make_shared<dsp::Variable>(dsp::PHI); Node node(data, id, type, position, variable); node.addOutput(++counter, "Output", variable->getOutput()); return node; } case Type::PI: { std::shared_ptr<dsp::Variable> variable = std::make_shared<dsp::Variable>(dsp::PI); Node node(data, id, type, position, variable); node.addOutput(++counter, "Output", variable->getOutput()); return node; } case Type::SAMPLE_DURATION: { std::shared_ptr<dsp::SampleDuration> sampleDuration = std::make_shared<dsp::SampleDuration>(); Node node(data, id, type, position, sampleDuration); node.addOutput(++counter, "Output", sampleDuration->getOutput()); return node; } case Type::SAMPLE_RATE: { std::shared_ptr<dsp::SampleRate> sampleRate = std::make_shared<dsp::SampleRate>(); Node node(data, id, type, position, sampleRate); node.addOutput(++counter, "Output", sampleRate->getOutput()); return node; } case Type::TAU: { std::shared_ptr<dsp::Variable> variable = std::make_shared<dsp::Variable>(dsp::TAU); Node node(data, id, type, position, variable); node.addOutput(++counter, "Output", variable->getOutput()); return node; } case Type::VARIABLE: { std::shared_ptr<dsp::Identity> identity = std::make_shared<dsp::Identity>(); Node node(data, id, type, position, identity); node.addInput(++counter, "Input", identity->getInput()); node.addOutput(++counter, "Output", identity->getOutput()); return node; } } } std::vector<std::string> particle::NodeGraph::Node::functionNames = {"Sine", "Sawtooth", "Square", "Triangle"}; std::unordered_map<std::string, std::shared_ptr<std::function<dsp::Sample(dsp::Sample)>>> particle::NodeGraph::Node::functions = { {"Sine", std::make_shared<std::function<dsp::Sample(dsp::Sample)>>(std::move([](dsp::Sample x) { return sin(dsp::TAU * x); }))}, {"Sawtooth", std::make_shared<std::function<dsp::Sample(dsp::Sample)>>(std::move([](dsp::Sample x) { return dsp::wrap(x + 0.5, 1.0) * 2.0 - 1.0; }))}, {"Square", std::make_shared<std::function<dsp::Sample(dsp::Sample)>>(std::move([](dsp::Sample x) { return x < 0.5 ? 1.0 : -1.0; }))}, {"Triangle", std::make_shared<std::function<dsp::Sample(dsp::Sample)>>(std::move([](dsp::Sample x) { dsp::Sample z = dsp::wrap(x + 0.25, 1.0); return (z < 0.5 ? z : 1.0 - z) * 4.0 - 1.0; }))}}; float particle::NodeGraph::Node::getFrameHeight(float numberOfBlocks) { return floor(ImGui::GetFrameHeight()) * numberOfBlocks + ImGui::GetStyle().ItemSpacing.y * (numberOfBlocks - 1.0f); } void particle::NodeGraph::Node::drawPlot(std::string title, std::vector<dsp::Sample> x, std::vector<std::vector<dsp::Sample>> y, dsp::Sample x_min, dsp::Sample x_max, dsp::Sample y_min, dsp::Sample y_max, ImVec2 size, ImPlotAxisFlags x_flags, ImPlotAxisFlags y_flags) { ImPlot::SetNextPlotLimits(x_min, x_max, y_min, y_max); if (ImPlot::BeginPlot(("##" + title).c_str(), NULL, NULL, size, ImPlotFlags_CanvasOnly | ImPlotFlags_NoChild, x_flags | ImPlotAxisFlags_Lock | ImPlotAxisFlags_NoDecorations, y_flags | ImPlotAxisFlags_Lock | ImPlotAxisFlags_NoDecorations)) { for (size_t channel = 0; channel < y.size(); ++channel) { ImPlot::PlotLine(("Channel " + std::to_string(channel)).c_str(), x.data(), y[channel].data(), x.size(), 0, sizeof(dsp::Sample)); } ImPlot::EndPlot(); } } void particle::NodeGraph::Node::drawLabel(const char *text) { // TODO: Put this into external function ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImGui::GetStyle().ItemInnerSpacing); ImGui::SameLine(); ImGui::PopStyleVar(); ImGui::TextUnformatted(text); } particle::NodeGraph::Link::Link( Data *data, int id, int from, int to, std::shared_ptr<dsp::Output> output, std::shared_ptr<dsp::Input> input) : data(data) , id(id) , from(from) , to(to) , output(output) , input(input) {} void particle::NodeGraph::Link::draw() { imnodes::Link(id, from, to); } void particle::NodeGraph::Link::drawInspector() {} particle::NodeGraph::Link particle::NodeGraph::Link::generate(Data *data, std::map<int, Node> &nodes, int id, int from, int to) { std::shared_ptr<dsp::Output> output; std::shared_ptr<dsp::Input> input; for (const auto &nodePair : nodes) { std::map<int, Input>::const_iterator inputIterator; if ((inputIterator = nodePair.second.inputs.find(from)) != nodePair.second.inputs.end()) { input = inputIterator->second.input; break; } std::map<int, Output>::const_iterator outputIterator; if ((outputIterator = nodePair.second.outputs.find(from)) != nodePair.second.outputs.end()) { output = outputIterator->second.output; break; } } for (const auto &nodePair : nodes) { std::map<int, Input>::const_iterator inputIterator; if ((inputIterator = nodePair.second.inputs.find(to)) != nodePair.second.inputs.end()) { input = inputIterator->second.input; break; } std::map<int, Output>::const_iterator outputIterator; if ((outputIterator = nodePair.second.outputs.find(to)) != nodePair.second.outputs.end()) { output = outputIterator->second.output; break; } } return Link(data, id, from, to, output, input); } particle::NodeGraph::CreateNodes::CreateNodes(std::shared_ptr<NodeGraph> nodeGraph, std::vector<Node> nodes) : Action(nodes.size() == 1 ? "Create Node" : "Create Nodes") , nodeGraph(nodeGraph) , nodes(nodes) {} void particle::NodeGraph::CreateNodes::perform() { for (const auto &node : nodes) { // GUI nodeGraph->getNodes().emplace(node.id, node); imnodes::SetNodeGridSpacePos(node.id, node.position); // DSP if (node.node != nullptr) { // TODO: TEMPORARY! REMOVE! node.node->setNumChannels(2); nodeGraph->getContainer()->addChild(node.node); } } } void particle::NodeGraph::CreateNodes::undo() { for (const auto &node : nodes) { // DSP if (node.node != nullptr) { nodeGraph->getContainer()->removeChild(node.node); } // GUI nodeGraph->getNodes().erase(node.id); } imnodes::ClearNodeSelection(); } particle::NodeGraph::CreateLinks::CreateLinks(std::shared_ptr<NodeGraph> nodeGraph, std::vector<Link> links) : Action(links.size() == 1 ? "Create Link" : "Create Links") , nodeGraph(nodeGraph) , links(links) {} void particle::NodeGraph::CreateLinks::perform() { for (const auto &link : links) { // GUI nodeGraph->getLinks().emplace(link.id, link); // DSP link.output->connect(link.input); } nodeGraph->getContainer()->sortChildren(); } void particle::NodeGraph::CreateLinks::undo() { for (const auto &link : links) { // DSP link.output->disconnect(link.input); // GUI nodeGraph->getLinks().erase(link.id); } imnodes::ClearLinkSelection(); } particle::NodeGraph::DestroyNodes::DestroyNodes(std::shared_ptr<NodeGraph> nodeGraph, std::vector<int> ids) : Action(ids.size() == 1 ? "Destroy Node" : "Destroy Nodes") , nodeGraph(nodeGraph) , ids(ids) {} void particle::NodeGraph::DestroyNodes::perform() { for (const auto &nodeId : ids) { Node &node = nodeGraph->getNodes()[nodeId]; std::vector<int> attachedLinks; for (const auto &inputPair : node.inputs) { for (const auto &linkPair : nodeGraph->getLinks()) { if (inputPair.first == linkPair.second.to) { attachedLinks.push_back(linkPair.first); } } } for (const auto &outputPair : node.outputs) { for (const auto &linkPair : nodeGraph->getLinks()) { if (outputPair.first == linkPair.second.from) { attachedLinks.push_back(linkPair.first); } } } for (const auto &linkId : attachedLinks) { Link &link = nodeGraph->getLinks()[linkId]; // DSP link.output->disconnect(link.input); // LOCAL links.push_front(link); // GUI nodeGraph->getLinks().erase(link.id); } // DSP if (node.node != nullptr) { nodeGraph->getContainer()->removeChild(node.node); } // LOCAL node.position = imnodes::GetNodeGridSpacePos(node.id); nodes.push_front(node); // GUI nodeGraph->getNodes().erase(node.id); } imnodes::ClearNodeSelection(); imnodes::ClearLinkSelection(); } void particle::NodeGraph::DestroyNodes::undo() { for (const auto &node : nodes) { // GUI nodeGraph->getNodes().emplace(node.id, node); imnodes::SetNodeGridSpacePos(node.id, node.position); // DSP if (node.node != nullptr) { nodeGraph->getContainer()->addChild(node.node); } } for (const auto &link : links) { // GUI nodeGraph->getLinks().emplace(link.id, link); // DSP link.output->connect(link.input); } // LOCAL nodes.clear(); links.clear(); // DSP nodeGraph->getContainer()->sortChildren(); } particle::NodeGraph::DestroyLinks::DestroyLinks(std::shared_ptr<NodeGraph> nodeGraph, std::vector<int> ids) : Action(ids.size() == 1 ? "Destroy Link" : "Destroy Links") , nodeGraph(nodeGraph) , ids(ids) {} void particle::NodeGraph::DestroyLinks::perform() { for (const auto &linkId : ids) { Link &link = nodeGraph->getLinks()[linkId]; // DSP link.output->disconnect(link.input); // LOCAL links.push_front(nodeGraph->getLinks()[linkId]); // GUI nodeGraph->getLinks().erase(linkId); } imnodes::ClearLinkSelection(); } void particle::NodeGraph::DestroyLinks::undo() { for (const auto &link : links) { // GUI nodeGraph->getLinks().emplace(link.id, link); // DSP link.output->connect(link.input); } // LOCAL links.clear(); // DSP nodeGraph->getContainer()->sortChildren(); } particle::NodeGraph::NodeGraph(Data &data, std::string name, std::shared_ptr<dsp::Node> container) : Frame(data, name) , counter(0) , container(container) { context = imnodes::EditorContextCreate(); } particle::NodeGraph::~NodeGraph() { imnodes::EditorContextFree(context); } std::shared_ptr<dsp::Node> particle::NodeGraph::getContainer() { return container; } std::map<int, particle::NodeGraph::Node> &particle::NodeGraph::getNodes() { return nodes; } std::map<int, particle::NodeGraph::Link> &particle::NodeGraph::getLinks() { return links; } imnodes::EditorContext *particle::NodeGraph::getContext() const { return context; } void particle::NodeGraph::drawInternal() { ImGuiIO &io = ImGui::GetIO(); imnodes::EditorContextSet(context); ImVec2 panning = imnodes::EditorContextGetPanning(); { float speed = io.KeyAlt ? 1.0f : io.KeyShift ? 100.0f : 10.0f; int x = ImGui::IsKeyDown(io.KeyMap[ImGuiKey_LeftArrow]) - ImGui::IsKeyDown(io.KeyMap[ImGuiKey_RightArrow]); int y = ImGui::IsKeyDown(io.KeyMap[ImGuiKey_UpArrow]) - ImGui::IsKeyDown(io.KeyMap[ImGuiKey_DownArrow]); panning.x += speed * x; panning.y += speed * y; imnodes::EditorContextResetPanning(panning); } if (!ImGui::IsAnyItemActive() && ImGui::IsKeyPressed(io.KeyMap[ImGuiKey_Backspace])) { destroyNodes(); destroyLinks(); } std::set<int> selectedNodeSet; for (const int node_id : getSelectedNodes()) { selectedNodeSet.insert(node_id); } imnodes::BeginNodeEditor(); createNode(); for (auto &nodePair : nodes) { nodePair.second.draw(selectedNodeSet.find(nodePair.first) != selectedNodeSet.end()); } for (auto &linkPair : links) { linkPair.second.draw(); } imnodes::EndNodeEditor(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - ImGui::GetTextLineHeightWithSpacing()); ImGui::Text("(%.0f, %.0f)", panning.x, panning.y); createLink(); } void particle::NodeGraph::destroyNodes() { std::vector<int> selectedNodes = getSelectedNodes(); if (!selectedNodes.empty()) { getData().pushAction(std::make_shared<DestroyNodes>(shared_from_this(), selectedNodes)); } } void particle::NodeGraph::destroyLinks() { std::vector<int> selectedLinks = getSelectedLinks(); if (!selectedLinks.empty()) { getData().pushAction(std::make_shared<DestroyLinks>(shared_from_this(), selectedLinks)); } } void particle::NodeGraph::createNode() { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, getData().getStyle().windowPadding); if (!ImGui::IsAnyItemHovered() && imnodes::IsEditorHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Right)) { ImGui::OpenPopup("Create Node"); } if (ImGui::BeginPopup("Create Node")) { const ImVec2 mousePosition = ImGui::GetMousePosOnOpeningCurrentPopup(); for (const auto &category : Node::getCategories(getData().getAudioProcessor()->getPlayHead() != nullptr)) { if (ImGui::BeginMenu(category.getName().c_str())) { for (const auto &type : category.types) { if (ImGui::MenuItem(Node::getTypeName(type).c_str())) { std::vector<Node> nodes; // TODO: remove for loop here for (int i = 0; i < 1; ++i) { const int id = ++counter; imnodes::SetNodeScreenSpacePos(id, mousePosition); nodes.push_back( Node::generate(&getData(), counter, id, type, imnodes::GetNodeGridSpacePos(id))); } getData().pushAction(std::make_shared<CreateNodes>(shared_from_this(), nodes)); } } ImGui::EndMenu(); } } ImGui::EndPopup(); } ImGui::PopStyleVar(); } void particle::NodeGraph::createLink() { int from; int to; if (imnodes::IsLinkCreated(&from, &to)) { const int id = ++counter; Link link = Link::generate(&getData(), nodes, id, from, to); getData().pushAction(std::make_shared<CreateLinks>(shared_from_this(), std::vector<Link>{link})); } } std::vector<int> particle::NodeGraph::getSelectedNodes() { std::vector<int> selectedNodes; int numSelectedNodes = imnodes::NumSelectedNodes(); if (numSelectedNodes) { selectedNodes.resize(numSelectedNodes); imnodes::GetSelectedNodes(selectedNodes.data()); selectedNodes.erase(std::remove_if(selectedNodes.begin(), selectedNodes.end(), [this](int nodeId) { return nodes.find(nodeId) == nodes.end(); }), selectedNodes.end()); } return selectedNodes; } std::vector<int> particle::NodeGraph::getSelectedLinks() { std::vector<int> selectedLinks; int numSelectedLinks = imnodes::NumSelectedLinks(); if (numSelectedLinks) { selectedLinks.resize(numSelectedLinks); imnodes::GetSelectedLinks(selectedLinks.data()); selectedLinks.erase(std::remove_if(selectedLinks.begin(), selectedLinks.end(), [this](int linkId) { return links.find(linkId) == links.end(); }), selectedLinks.end()); } return selectedLinks; }
28e39f80930a85083068e8952cc895a4f0a8ad9c
f162301e95cf0595694cdc434471e1566ecfccaa
/src/DivFunNode/DivFunNode.h
55100f8aa11e0198b7b786b5408299c96618f59a
[]
no_license
TomCoded/birdFountain
57ce415ebd2299604f1389fbdd192a59e96fd469
2fb989b454a6a9c6f4312929061ad5020796e32c
refs/heads/master
2020-03-28T19:00:30.017391
2018-08-20T22:47:18
2018-08-20T22:47:18
148,935,434
1
0
null
null
null
null
UTF-8
C++
false
false
440
h
#ifndef DIVFUNNODE_H_ #define DIVFUNNODE_H_ //DivFunNode.h (C) Tom White //does leftnode / rightnode //returns leftnode / 0.00001 on divide by zero #include <FunNode/FunNode.h> class DivFunNode : public FunNode { public: DivFunNode(); DivFunNode(FunNode * leftNode, FunNode * rightNode); DivFunNode(DivFunNode &other); ~DivFunNode(); double eval(double t); protected: FunNode * leftNode; FunNode * rightNode; }; #endif
899846ad509f5e5405c57bbeed13bce102c046c3
96ad211b9f09609082b3b58b6fe9825e0f14a03f
/MapTool/MapToolView.h
5618ebb5b246898678bb1b3cf1fc3b3914d33734
[]
no_license
sophiajh/MapTool00
a1413bd8bf9b244df5a932b35ef2090c4fa56432
01f2717f49bb9f4e0a28209060d1f80c2d7e1051
refs/heads/master
2022-11-27T18:20:12.782185
2020-08-05T05:41:57
2020-08-05T05:41:57
279,045,024
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
h
 // MapToolView.h: CMapToolView 클래스의 인터페이스 // #pragma once class CMapToolView : public CView { protected: // serialization에서만 만들어집니다. CMapToolView() noexcept; DECLARE_DYNCREATE(CMapToolView) // 특성입니다. public: CMapToolDoc* GetDocument() const; // 작업입니다. public: // 재정의입니다. public: virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 구현입니다. public: virtual ~CMapToolView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); public: afx_msg void OnSize(UINT nType, int cx, int cy); }; #ifndef _DEBUG // MapToolView.cpp의 디버그 버전 inline CMapToolDoc* CMapToolView::GetDocument() const { return reinterpret_cast<CMapToolDoc*>(m_pDocument); } #endif
fcee3e87e44645b10a7156968fd5e5d3eac1d456
d976d1566e2b435ac7c84fd8f24d96440daa5c90
/ConsoleApplication19.cpp
f0b31dbaf1d83aed4dbd1a9dddc5af4154f04e5c
[]
no_license
smiromania/teme-la-info
6d90db8f22ed1462386983cd11f1e98d17f9b86f
3510f33bcf7c7efa5b11e15d959021c84ccc06ed
refs/heads/master
2021-06-25T17:48:52.909656
2021-03-31T19:08:07
2021-03-31T19:08:07
215,292,082
3
0
null
2019-10-15T12:31:24
2019-10-15T12:22:32
C++
UTF-8
C++
false
false
557
cpp
#include <iostream> #include <cstring> using namespace std; char a[256],b[256],maxim; int main() { cin.get(b, 51); for (int i = 0; i < strlen(b); i++) { if (b[i] >= 'a' && b[i] <= 'z') { a[b[i]]++; if (a[b[i]] > maxim) maxim = a[b[i]]; } } if (maxim == 0) cout << "nu"; else for (int i = 'a'; i <= 'z'; i++) { if (a[i] == maxim) { cout << (char)i; i = 'z' + 1; } } }
6bca7ad44943eff4aad06ab0c9b46bcafd5a8a70
e4ff58cd59488d5dcbd99a90d19394ab6609e745
/IRTree-building/irtree/nodes/expressions/TempExpression.h
b66569aec26781dc052fcfb7bec805e7a2bd9cc5
[]
no_license
iskander232/MINIJavaCompiler
813c81336e6a77cae32309a2bc2233a66bf6e888
9117bea0739aee1bf6fc04a6c126a772651b274d
refs/heads/master
2022-12-31T11:05:58.557324
2020-10-15T17:18:20
2020-10-15T17:18:20
246,650,995
0
0
null
null
null
null
UTF-8
C++
false
false
295
h
#pragma once #include "../expressions/Expression.h" #include "../../generators/Temporary.h" namespace IRT { class TempExpression : public Expression { public: explicit TempExpression(const IRT::Temporary &temporary); void Accept(Visitor *visitor) override; Temporary temporary_; }; }
6987c354491e5c43727e5b41fdb7385c773bed89
9452341b3252759e1a9133b5e4676993e27f4dd8
/advection/deformingOnSphere/slottedCylinder/QUICK_FCT_latLonPolarRotated_c1/latLon_120x60/constant/velocityFieldDict
b1a40013424ed9789c1318cf96f29d1069ef1afa
[]
no_license
AtmosFOAM/hilaryRun
8af184499fe2001acb659dcd8b82920c50a76dc0
6eb682dbc9498e529d690bcb4a7b9cad179e8ea4
refs/heads/master
2023-09-04T07:33:52.157194
2023-09-01T07:38:11
2023-09-01T07:38:11
113,987,213
0
0
null
null
null
null
UTF-8
C++
false
false
925
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object velocityDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // timeVaryingWind true; type deformationalNonDivergentGeodesic; earthRadius 0.99; radius 1.01; deformationScale 10; endTime 5; centre (0 0 0);
fe214acefc7d8cbd2c67801b9c58b3eb90d41c57
88ce08b3410e2ccd6fef9cd8b9c1cae89e4ab822
/sources/schrage.cpp
b9f7678083221256e8b0b4c4d6190873eac14158
[]
no_license
Klapeyron/SPD
6e982eec4c21cf10aa6fbe213ebd06be8e552cc0
05dcf38304924ae9a096c3aca13c22d95c846851
refs/heads/master
2021-03-16T05:57:11.111105
2018-03-02T17:31:09
2018-03-02T17:31:09
54,184,410
0
0
null
2016-03-18T08:05:32
2016-03-18T08:05:32
null
UTF-8
C++
false
false
316
cpp
#include "SchrageAlgorithm.hpp" #include <iostream> int main() { std::vector<Task> loadedTasks; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); for(Task task; std::cin >> task.r >> task.p >> task.q;) loadedTasks.push_back(task); std::cout << schrage(loadedTasks) << std::endl; }
890e7c1da81c0b0f367eaf09539eb06a6e8402c2
9ebca0e9e77ade41a3185fc2a40a62a4d4466854
/ivan12.4/ivan12.4.cpp
443942d752cc49733ffd5da3c30d3b9b470eb25b
[]
no_license
sedelnikova/ivan12.4
7676e6b042f426af7509726575dfc24a521f627e
7b4cee4dd7cec32f4e72c5371aaf8a60a6fd5232
refs/heads/master
2020-08-04T09:14:16.306145
2019-10-01T12:06:01
2019-10-01T12:06:01
212,086,429
0
0
null
null
null
null
UTF-8
C++
false
false
1,499
cpp
// ivan 12.4.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. //Описать функцию Quarter(x, y) целого типа, определяющую номер координатной четверти, в которой //находится точка с ненулевыми вещественными координатами (x, y). //С помощью этой функции найти номера координатных четвертей для трех точек с данными ненулевыми координатами #include <iostream> #include <cmath> using namespace std; void Quarter(double x, double y) { if (x > 0) { if (y > 0) { cout << "1 кординатная четверть" << endl; } else { cout << "4 координатная четверть" << endl; } } else { if (y > 0) { cout << "2 координатная четверть" << endl; } else { cout << "3 координатная четверть" << endl; } } } int main() { setlocale(LC_ALL, "Russian"); double a, b; cout << "Введите, пожалуйста, x, y: " << endl; cin >> a >> b; Quarter(a, b); cout << "Введите, пожалуйста, x, y: " << endl; cin >> a >> b; Quarter(a, b); cout << "Введите, пожалуйста, x, y: " << endl; cin >> a >> b; Quarter(a, b); return 0; }
b704346e6929aaf3db0b9a4db0d6e2ebce5abceb
67afe9c896d08b9fbd852c7e5e287de2a3e4d709
/71AA. Way Too Long Words.cpp
eef753521c4623431ee559fda8e30da509c4ac3b
[]
no_license
Sabila-Nawshin/CodeForces
daa04f92c483cfccadffc88ba11a807a7cd4b4a7
e974d9e34906e2e97c3a808a38a53a9dd9efcbb1
refs/heads/master
2020-04-17T23:31:35.387157
2019-01-22T17:47:34
2019-01-22T17:47:34
167,038,972
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include <iostream> using namespace std; int main(){ int T; cin >> T; while(T--){ string s; cin >> s; if (s.size() <= 10) cout << s << endl; else cout << s.at(0) << (s.size() - 2) << s.at(s.size() - 1) << endl; } return 0; }
0efff5bf2eda1b6f7c1e8f4e6dce250e0e7e4c3e
30b67fd9fabda5c1350dcd2fb29973b8fd1c518f
/hdu/hdu 2159 二维背包/hdu 2159 二维背包/main.cpp
3b321c9095dc3b783300401bbaf5b7d88f43433a
[]
no_license
Joey-Liu/online-judge
97bd3025a38117de33547fdaf0382356d22b2047
2c48d9b7aa981d6c98cf92d80d69b0ac8f2b2aa1
refs/heads/master
2021-08-01T13:29:58.631190
2021-07-26T06:29:26
2021-07-26T06:29:26
132,420,744
2
0
null
2020-01-18T13:18:31
2018-05-07T07:05:21
C++
UTF-8
C++
false
false
972
cpp
#include <iostream> #include <stdio.h> #include <string> #include <memory.h> #include <algorithm> using namespace std; const int maxn = 150; int dp[maxn][maxn]; int N, M, K, S, A[maxn], B[maxn]; int main() { freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); while (cin >> N >> M >> K >> S) { for (int i = 0; i < K; i++) { cin >> A[i] >> B[i]; } memset(dp, 0, sizeof(dp)); for (int i = 1; i <= S; i++) { for (int j = 0; j <= M; j++) { dp[i][j] = dp[i - 1][j]; for (int k = 0; k < K; k++) { if (j >= B[k]) dp[i][j] = max(dp[i - 1][j - B[k]] + A[k], dp[i][j]); } }//for int j }//for int i if (dp[S][M] < N) { cout << -1 << endl; } else { bool found = false; for (int j = 0; j <= M; j++) { for (int i = 1; i <= S; i++) { if (dp[i][j] >= N) { cout << M - j << endl; found = true; break; } } if (found) break; } } }//while cin return 0; }
c51f0a30cebfcc15e4c59a9aa945e8541c3200ed
ce87bba156f439a42679f846661bde632cb10126
/c++/src/capnp/compiler/md5.h
3085eed29f51efd83e8fba3d95bd9dee2148e0bf
[ "BSD-2-Clause" ]
permissive
bouk/capnproto
2e899e9819c9c4914cff83319a1f693eeaa2a7b4
83945f8f11053db48a770b0f9e89fdcee7ef45c4
refs/heads/master
2021-01-24T04:29:39.144398
2013-08-12T20:26:27
2013-08-12T20:26:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,127
h
// This file was modified by Kenton Varda from code placed in the public domain. // The code, which was originally C, was modified to give it a C++ interface. // The original code bore the following notice: /* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See md5.c for more information. */ // TODO(someday): Put in KJ? #ifndef CAPNP_COMPILER_MD5_H #define CAPNP_COMPILER_MD5_H #include <kj/string.h> #include <kj/array.h> namespace capnp { namespace compiler { class Md5 { public: Md5(); void update(kj::ArrayPtr<const kj::byte> data); inline void update(kj::ArrayPtr<const char> data) { return update(kj::arrayPtr(reinterpret_cast<const kj::byte*>(data.begin()), data.size())); } inline void update(kj::StringPtr data) { return update(data.asArray()); } kj::ArrayPtr<const kj::byte> finish(); kj::StringPtr finishAsHex(); private: /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; bool finished = false; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; kj::byte buffer[64]; MD5_u32plus block[16]; } MD5_CTX; MD5_CTX ctx; const kj::byte* body(const kj::byte* ptr, size_t size); }; } // namespace compiler } // namespace capnp #endif // CAPNP_COMPILER_MD5_H
44b3005fae47629a843dfeef15b187591e8f9b75
838560c8a9938b9b13a6888244e9bc856dae2403
/Job.h
cffd982fe6e8562bd1b36625bdc4687df4e05b9b
[ "MIT" ]
permissive
suyunu/Discrete-Event-Simulation
ea927156505a1be95d14f10e751bb139e8155a7f
be2da51697e546827890f502366025959975d473
refs/heads/master
2021-01-10T03:12:10.978730
2016-03-28T19:29:57
2016-03-28T19:29:57
54,913,375
6
0
null
null
null
null
UTF-8
C++
false
false
587
h
#ifndef JOB_H_ #define JOB_H_ #include <iostream> using namespace std; class Job{ public: // No of this job according to the order of appearance int no; // Enter time to the factory double enterTime; // Holds the check-out time from the last unit. double timeToGo; // No of the unit which this job has been lastly processed. // (if cond == -1, then this job has just entered to the factory). int cond; // Initialization of the variables in this class void initialize(int No, double enter_time); // Constructor Job(); // Destructor ~Job(); }; #endif
b8738a4a219c2bca9800069ca043e0ec7638ffec
9e803bf09cef9afcc86de1f157ef7fe00ae5ea02
/validAnagram.cpp
4be0ef360200946c277f3c3f9457bd9cf61a6385
[]
no_license
PratikChakraborty10/LeetCode-Problems
0a17c0a9a2aac024ff3f7ffb44af10b482f4d280
c1864ca5c6be6887cadf74f286e13028eba4bbb2
refs/heads/master
2023-05-13T21:16:13.890284
2021-06-10T18:04:24
2021-06-10T18:04:24
375,657,113
0
0
null
null
null
null
UTF-8
C++
false
false
482
cpp
#include <bits/stdc++.h> using namespace std; bool areAnagram(string str1, string str2){ int n1 = str1.length(), n2 = str2.length(); if (n1 != n2) return false; sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); for (int i = 0; i < n1; i++) if (str1[i] != str2[i]) return false; return true; } int main(){ string s = "anagram", t = "nagaram"; if(areAnagram(s,t)) cout<<"True"; else cout<<"False"; }
dd7cd972fadc8eaf7fbd24b4a218572dda577a47
0470d936ba0554a919fabc94c1471d496aad7b93
/ktbacktracking.cpp
1ae55f6813cd550027ff4c9009dd581c8f2e6db4
[]
no_license
nihalkun/programming
0aee34e22301eb0323ef06c19209b30032347236
710050b3d8025f799be58154b14525d5ad470701
refs/heads/main
2022-12-28T18:44:25.681319
2020-10-13T10:51:12
2020-10-13T10:51:12
303,614,269
0
0
null
2020-10-13T10:51:13
2020-10-13T06:52:33
C++
UTF-8
C++
false
false
2,103
cpp
#include<bits/stdc++.h> using namespace std; #define N 8 int valid(int nx,int ny,int arr[N][N]) { return (nx>=0 && nx<N && ny>=0 && ny<N && arr[nx][ny]==-1); } /*int valid(int x, int y, int arr[N][N]) { return (x >= 0 && x < N && y >= 0 && y < N && arr[x][y] == -1); } */ /*void printSolution(int arr[N][N]) { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) cout << " " << setw(2) << arr[x][y] << " "; cout << endl; } } */ /*int solve(int arr[N][N],int x, int y, int mv, int dx[N], int dy[N]) { int k, nx, ny; if (mv == N*N) return 1; for (k = 0; k < 8; k++) { nx = x + dx[k]; ny = x + dy[k]; if (valid(nx,ny,arr)) { arr[nx][ny]=mv; if (solve(arr,nx, ny, mv + 1, dx, dy) == 1) return 1; else arr[nx][ny] = -1; } } return 0; }*/ int solve(int arr[N][N],int x, int y, int mv, int dx[N], int dy[N]) { int k, nx, ny; if (mv == N*N) return 1; for (k = 0; k < 8; k++) { nx = x + dx[k]; ny = y + dy[k]; if (valid(nx,ny, arr)) { arr[nx][ny] = mv; if (solve(arr,nx, ny, mv + 1,dx, dy) == 1) return 1; else arr[nx][ny] = -1; } } return 0; } /*int solveprob() { int arr[N][N]; memset(arr,-1,sizeof(arr)); int dx[8]={2,1,-1,-2,-2,-1,1,2}; int dy[8]={1,2,2,1,-1,-2,-2,-1}; arr[0][0]=0; if(solve(arr,0,0,1,dx,dy)==0); { cout<<"not"; return 0; } printSolution(arr); return 1; }*/ int main() { int arr[N][N]; memset(arr,-1,sizeof(arr)); int dx[N] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int dy[N] = { 1, 2, 2, 1, -1, -2, -2, -1 }; arr[0][0] = 0; if (solve(arr,0, 0, 1, dx, dy) == 0) { cout << "Solution does not exist"; return 0; } else /*printSolution(arr);*/ for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) cout << " " << setw(2) << arr[x][y] << " "; cout << endl; } return 1; return 0; } /*int main() { solveprob(); return 0; }*/
c161334a4062b90f530c19dfbee1c3eca1746f3d
91b1313a9c6c5b9ddeb85a87ee7d2e2f84348225
/ttplayer_eclipse_workspace/tiktok_player/src/tt_player_effect.cpp
851b7230b1dc47df3c61ec9045bbd28cb3a4496e
[]
no_license
Alfredo-Giani/music_player_assignment
2c100db553736349f465045724f66b219c7e584a
927b9e4593720f8c9a51ee14ca564ad0643110ad
refs/heads/main
2023-01-13T23:36:12.577870
2020-11-18T11:38:41
2020-11-18T11:38:41
311,407,825
0
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
/* * tt_player_effect.cpp * * Created on: 9 Nov 2020 * Author: alfre */ #include "tt_player_effect.h" TTPlayerEffect::TTPlayerEffect() { pStatelessTransferFunction = new TTPlayerStatelessTransferFunction(); // TODO Auto-generated constructor stub } TTPlayerEffect::~TTPlayerEffect() { delete(pStatelessTransferFunction); // TODO Auto-generated destructor stub } TTPlayerEffect::TTPlayerEffect(const TTPlayerEffect &other) { pStatelessTransferFunction = new TTPlayerStatelessTransferFunction(); //(&(other.pStatelessTransferFunction)); }
fa16687fdfa19d03769ed7e1532a7845f2c67d22
d0773ede555c28a4d89ee026264a1d807c4cb294
/CS3520/Project2_Deliverable/Bird.cpp
cc123b6593a887ded594c43069a2fc8aa095dcce
[]
no_license
raymondyou97/NEU_Coursework
85c4b9fc5757cad3af7d01e957da38efbb29ee54
2595a059c6f44829a7fea093223469265f77dadc
refs/heads/master
2021-04-07T03:17:56.288518
2020-04-21T21:47:08
2020-04-21T21:47:08
257,722,947
0
1
null
2020-04-30T16:07:36
2020-04-21T21:44:06
Java
UTF-8
C++
false
false
1,208
cpp
#include "Bird.hpp" #include "Constants.hpp" #include <SFML/Graphics.hpp> #include <string> #include <iostream> Bird::Bird(int initial_x, int initial_y) { sf::CircleShape * model = new sf::CircleShape(20.f); model->setFillColor(sf::Color::Blue); model->setPosition(initial_x, initial_y); this->model = model; this->x = initial_x; this->y = initial_y; } Bird::~Bird() { delete this->model; } sf::CircleShape Bird::get_model() { return *(this->model); } void Bird::move_up() { if (this->can_move(std::string("up"))) { this->model->move(0, -bird_step); this->y -= bird_step; } } void Bird::move_down() { if (this->can_move(std::string("down"))) { this->model->move(0, bird_step); this->y += bird_step; } } bool Bird::can_move(std::string direction) { int current_y = this->model->getPosition().y; if (direction == std::string("up")) { return current_y - bird_step >= 0 ? true : false; } else if (direction == std::string ("down")) { return current_y + bird_step <= window_height - bird_step ? true : false; } else { return false; } } bool Bird::collision() { return false; }
728f2e34db4b0e1991cd4f0e5be5b58452cb21a0
bc2854d446b06b114a5d7447d2b8f7a8661c6d8f
/src/widgets/helper/EffectLabel.cpp
1f2960d77d6a5a19a957af11ab04b765896b7c25
[ "MIT" ]
permissive
rexim/chatterino2
814aec375725e11d8460d04499f8258e02c25297
476825dc35c34e72729d07fa5661c53fd9db60d8
refs/heads/master
2020-12-12T09:21:44.014123
2020-01-12T17:41:02
2020-01-12T17:41:02
234,098,518
3
1
MIT
2020-01-15T14:29:50
2020-01-15T14:29:49
null
UTF-8
C++
false
false
919
cpp
#include "widgets/helper/EffectLabel.hpp" #include <QBrush> #include <QPainter> namespace chatterino { EffectLabel::EffectLabel(BaseWidget *parent, int spacing) : Button(parent) , label_(this) { setLayout(&this->hbox_); this->label_.setAlignment(Qt::AlignCenter); this->hbox_.setMargin(0); this->hbox_.addSpacing(spacing); this->hbox_.addWidget(&this->label_); this->hbox_.addSpacing(spacing); } EffectLabel2::EffectLabel2(BaseWidget *parent, int padding) : Button(parent) , label_(this) { auto *hbox = new QHBoxLayout(this); this->setLayout(hbox); // this->label_.setAlignment(Qt::AlignCenter); this->label_.setCentered(true); hbox->setMargin(0); // hbox.addSpacing(spacing); hbox->addWidget(&this->label_); // hbox.addSpacing(spacing); } Label &EffectLabel2::getLabel() { return this->label_; } } // namespace chatterino
35cba7ab64af034d56847f536e7f4cc97b185659
6d7660307d22b638f718806e65f8846ec75159ae
/src/BulletPool.h
57ad5a89d1dc3f3c2580f49efa0badf97590535b
[]
no_license
lazynorie/GAME2005-Assignment3
e23aad1224dd203cf5ee3a9fed9b5f1932e22486
f3846049bff093041d75af44a8afec8f1d79a91c
refs/heads/main
2023-01-16T01:57:04.844378
2020-11-28T04:07:24
2020-11-28T04:07:24
316,635,011
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
#pragma once #ifndef __BulletPool__ #define __BulletPool__ #include"Bullet.h" #include<iostream> using namespace std; class BulletPool { public: BulletPool(int); ~BulletPool(); Bullet* spawn(); void Despawn(Bullet*); vector<Bullet*> all; private: vector<Bullet*> inactive; vector<Bullet*>active; }; #endif
43838257d8c83c527ef212d45f3df66ba46cc08d
4365c15c699d6cfdd42fd6f5a7148cce408e9bdd
/Tugas 5/Union.cpp
af4afb0ef751e1f04b43c4c693277115b0e76ebf
[]
no_license
Rial26/Tugas-LMS-Algoritma-Pemrograman-2
ac8b343b23edf280cd31250085855e30e8a4533a
36a8aae02ba080607cbd4bd8677b15f516cdbd7e
refs/heads/master
2022-11-07T20:56:20.306550
2020-06-26T12:45:30
2020-06-26T12:45:30
255,818,737
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
#include <iostream> using namespace std; union orang{ int gaji; int umur; }; int main(){ union orang pegawai; pegawai.gaji = 1500000; pegawai.umur = 21; cout <<"gaji pegawai = " << pegawai.gaji << endl; cout <<"umur pegawai = " << pegawai.umur <<endl; }
d86425905c3eaf2cee6faaed5fbd399a741572cf
5b41e312db8aeb5532ba59498c93e2ec1dccd4ff
/Tools/IBAS_Server/IBas_Server_Frame/cIbas_Server.cpp
40498f429b3bc34321ede70286759c68635a8803
[]
no_license
frankilfrancis/KPO_HMI_vs17
10d96c6cb4aebffb83254e6ca38fe6d1033eba79
de49aa55eccd8a7abc165f6057088a28426a1ceb
refs/heads/master
2020-04-15T16:40:14.366351
2019-11-14T15:33:25
2019-11-14T15:33:25
164,845,188
0
1
null
null
null
null
UTF-8
C++
false
false
1,261
cpp
// ---------------------------------------------------------------------------- // // S M S D e m a g A G // // All Rights Reserved // // // project : StraGang // filename : // originator : // department : // creation date : 03.03.2005 10:49 // description : Server for IBAS // // ---------------------------------------------------------------------------- // // change notes: // // version dd-mmm-yyyy author remarks // 0.1 03.03.2005 10:49 Uli Bellgardt First Version // // ---------------------------------------------------------------------------- // #pragma warning (disable:4503) #include "cIBAS_Component.h" #include "cIBAS_Server.h" cIBAS_Server::~cIBAS_Server() { if (m_pComponent) { delete m_pComponent; } } cIBAS_Server::cIBAS_Server( int argc, const char** argv, const char* compName, const char* serverName) : cCBS_StdServer( argc, argv) , m_pComponent(0) { m_pComponent = new cIBAS_Component(this); } void cIBAS_Server::createTasks() { if (m_pComponent) { m_pComponent->activate(s_componentPOA, getComponentName()); } }
29ea2695a45900bf51480a8eb57e2d51d6af7820
3e5dde764a0a6e32fee73fbb51cf03a775461cbf
/references/soft shadows/示例/soft_shadows_nvidia_v2_0_src/bleifrei/gfx/PixelBuffer.hpp
5aaecc1302285963504f3828a6c8851159bb1c2b
[]
no_license
elblogbruno/ptam-gr
e50fb1bb34d4620f362f3611915e25c2508b6093
2f9eca8d9903882b9731fdff431581ebd146ae94
refs/heads/master
2021-10-10T23:04:30.986185
2015-09-26T14:11:28
2015-09-26T14:11:28
43,207,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,012
hpp
/** * bleifrei utility library * * Copyright (C) 2003 Ulf Borgenstam, Jonas Svensson. * * Do not distribute. If you know someone interested in obtaining these sources * please have them contact us. */ #ifndef _include_bleifrei_PixelBuffer_hpp_ #define _include_bleifrei_PixelBuffer_hpp_ // includes #include "../gfx/opengl.hpp" namespace bleifrei { namespace gfx { class PixelBuffer { public: enum Format { rgba8, rgb16f }; PixelBuffer(void) {} PixelBuffer(const PixelBuffer &p); PixelBuffer(int width, int height, Format format = rgba8); void destroy(void); void enable(void); void disable(void); void bind(void) { wglBindTexImageARB(pb, WGL_FRONT_LEFT_ARB); } void release(void) { wglReleaseTexImageARB(pb, WGL_FRONT_LEFT_ARB); } protected: int width, height; HPBUFFERARB pb; // Handle HDC dc; // Device context }; } } #endif //_include_bleifrei_PixelBuffer_hpp_
[ "cxychina@a223138c-6483-11de-8e29-e9b457f63bae" ]
cxychina@a223138c-6483-11de-8e29-e9b457f63bae
7604f05672456fca1700519be68c21526f896222
a5712fbea11ea2f697739f366f18732380e0dc23
/include/WaveFile.h
cc5051f7c83a22b23aabcb1171edf1d774837d9f
[]
no_license
danstronoid/Simple-Wave-File
8cac21c66ed697b397fecce250d76253464dcef6
6060190e66be5f4639efcb6eefc36103aa1dfd99
refs/heads/master
2020-12-30T02:42:52.061286
2020-02-07T03:36:53
2020-02-07T03:36:53
238,834,279
0
0
null
null
null
null
UTF-8
C++
false
false
1,987
h
#ifndef WAVEFILE_H #define WAVEFILE_H /* Simple Wave File Author: Daniel Schwartz -- WaveFile -- The WaveFile class creates objects that hold all data pertaining to a particular wave file. WaveFile objects can be created by opening and reading a wave file into memory, or by creating a new empty wave file. The audio data in a wave file can be manipulated using the getSample() and setSample() methods. After processing, a WaveFile object can be written to a new wave file using the write method. */ #include <iostream> #include <fstream> #include <string> #include <cstdint> #include <memory> #include "WaveFileHeaders.h" #include "AudioSample.h" using namespace std; class WaveFile { private: // header info RiffHeader m_riffHeader; WaveFormatHeader m_formatHeader; WaveDataHeader m_dataHeader; // audio data unique_ptr<uint8_t[]> m_data; // the core attributes of an audio file uint32_t m_length; uint32_t m_sampleRate; uint16_t m_nChannels; uint16_t m_bitDepth; public: WaveFile(); WaveFile(uint32_t length, uint32_t sampleRate = 44100, uint16_t nChannels = 2, uint16_t bitDepth = 16); WaveFile(const WaveFile &other); WaveFile(string fileName); WaveFile& operator=(const WaveFile &other); // read and write, returns true if successful bool read(string inFileName); bool write(string outFileName); // get and set methods for an audio sample AudioSample getSample(uint32_t sample); void setSample(uint32_t sample, const AudioSample &audio); // print methods void print(); void printHeaderInfo(); // get methods uint32_t length() const { return m_length; } uint32_t sampleRate() const { return m_sampleRate; } uint16_t nChannels() const { return m_nChannels; } uint16_t bitDepth() const { return m_bitDepth; } private: // used to recalculate header values void setHeaders(); }; #endif // WAVEFILE_H
4947eb11972fe3cc329bba05351cededb73609b0
1f85378b76b91b2c6b927e753446fe0c98b4f50e
/office/office_user.cpp
9dcd33479d00457a4ef12e438337dcaf2a89a8bd
[]
no_license
matts1/comp6771finalexam
a654bdee7942d3b4980cdad6d63c7b26e35c16ec
2c3e321f74aca8ac72d9bc0b3da67256cf1ff96e
refs/heads/master
2021-08-19T16:51:44.720704
2017-11-24T22:59:08
2017-11-24T22:59:08
111,961,243
2
2
null
null
null
null
UTF-8
C++
false
false
80
cpp
#include "office.h" int main() { Spreadsheet s; s.setIntCell(1, 10); }
03a1418883c507c94a63dc49110c90ea5eee407b
daf78a1336ef68ad949055e9c5e9bc236c2014ff
/chess/bpawn.h
6ed009d280c380d934a4495b58388e2fdcdccd4c
[ "Apache-2.0" ]
permissive
xliux/chess
7968b31bc6edeb1fc263b59d8e43631ecfee1ec4
1f236aff0afff04b3617bc6eaee16934589fdb62
refs/heads/master
2020-05-17T19:21:17.644027
2014-12-04T01:41:17
2014-12-04T01:41:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
#ifndef B_PAWN_H #define B_PAWN_H #include <vector> #include "piece.h" namespace chess { class BPawn : public Piece { public: BPawn(int8_t row=-1, int8_t col=-1) : Piece(Type::B_PAWN, row, col) {} bool canAttack(const Board& board, Position pos) const; protected: std::vector<Move> getMoves(const Board& board) const; private: void addMove(const Board& board, Position newPos, std::vector<Move>* moves) const; }; } #endif
eecf66c97315cdc70f49c0add332c4033d8ff84d
1afc8cdbd3a6d627415b346293416ede54bf31e2
/codeforces/600/C.cpp
0fc162763fac46dec073ae24cd1cb0bc6b6fee16
[]
no_license
umangja/CompetitiveProgrammingSolution
bf6944b81373061124179db5ba2ce2612032e1fe
d622398e40dadadde191c0d9b34a9fcd4735c69c
refs/heads/master
2023-03-25T23:05:09.596577
2021-02-23T09:07:00
2021-03-14T15:22:40
341,297,361
0
0
null
null
null
null
UTF-8
C++
false
false
3,749
cpp
/*input */ // assic value of ('0'-'9') is(48 - 57) and (a-z) is (97-122) and (A-Z) is(65-90) and 32 for space // #pragma GCC target ("avx2") // #pragma GCC optimization ("O3") // #pragma GCC optimization ("unroll-loops") #include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; // order_of_key (k) : Number of items strictly smaller than k . // find_by_order(k) : K-th element in a set (counting from zero). using namespace __gnu_pbds; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define ll long long int #define pb push_back #define pii pair<ll ,ll > #define vpii vector< pii > #define vi vector<ll > #define vs vector< string > #define vvi vector< vector< ll > > #define inf (ll)1e18 #define all(it,a) for(auto it=(a).begin();it!=(a).end();it++) #define F first #define S second #define sz(x) (ll )x.size() #define rep(i,a,b) for(ll i=a;i<b;i++) #define repr(i,a,b) for(ll i=a;i>b;i--) #define lbnd lower_bound #define ubnd upper_bound #define mp make_pair #define whatis(x) cout << #x << " is " << x << "\n"; #define graph(n) adj(n,vector< ll > () ) //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); #define debug(x) cout << #x << " " << x << endl; #define debug_p(x) cout << #x << " " << x.F << " " << x.S << endl; #define debug_v(x) {cout << #x << " "; for (auto ioi : x) cout << ioi << " "; cout << endl;} #define debug_vp(x) {cout << #x << " "; for (auto ioi : x) cout << '[' << ioi.F << " " << ioi.S << ']'; cout << endl;} #define debug_v_v(x) {cout << #x << "/*\n"; for (auto ioi : x) { for (auto ioi2 : ioi) cout << ioi2 << " "; cout << '\n';} cout << "*/" << #x << endl;} vvi fun(ll k) { vvi ans; if(k==0) { vi t; t.pb(1); ans.pb(t); return ans; } if(k==1) { vi t1 = {1,1}; vi t2 = {1,-1}; ans.pb(t1); ans.pb(t2); return ans; } vvi prev=fun(k-1); for(ll i=0;i<sz(prev);i+=2) { vi t1,t2; rep(j,0,sz(prev[i])) t1.pb(prev[i][j]); rep(j,0,sz(prev[i+1])) t2.pb(prev[i+1][j]); // debug_v(t1); // debug_v(t2); vi t; rep(j,0,sz(t1)) t.pb(t1[j]); rep(j,0,sz(t2)) t.pb(t2[j]); ans.pb(t); t.clear(); rep(j,0,sz(t1)) t.pb(-1*t1[j]); rep(j,0,sz(t2)) t.pb(t2[j]); ans.pb(t); t.clear(); rep(j,0,sz(t1)) t.pb(t2[j]); rep(j,0,sz(t2)) t.pb(t1[j]); ans.pb(t); t.clear(); rep(j,0,sz(t1)) t.pb(-1*t2[j]); rep(j,0,sz(t2)) t.pb(t1[j]); ans.pb(t); } return ans; } int solve() { string s;cin>>s; ll n = sz(s); vi fq(26,0); ll o=0,e=0; rep(i,0,n) fq[s[i]-'a']++; rep(i,0,26) if(fq[i]&1) o++; else e++; while(o>1) { ll id1=-1,id2=-1; rep(i,0,26) if(fq[i]&1) {id1=i; break;} repr(i,25,-1) if(fq[i]&1) {id2=i; break;} if(id1!=-1) fq[id1]++,fq[id2]--,o-=2; } string ansl = "",ansr = ""; rep(i,0,26) { rep(j,0,fq[i]/2) ansl+=(char)('a'+i); rep(j,0,(fq[i])/2) ansr+=(char)('a'+i); } rep(i,0,26) if(fq[i]&1) ansl+=(char)('a'+i); reverse(ansr.begin(), ansr.end()); string ans = ansl+ansr; cout<<ans<<"\n"; return 0; } int main() { auto start = chrono::high_resolution_clock::now(); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll test_cases=1; //cin>>test_cases; while(test_cases--) solve(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::milliseconds>(stop-start); //cout<<"\nduration: "<<(double)duration.count()<<" milliseconds"; }
51d4774b40a4eee54adda5dde0249b0f1f18c257
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/enduser/zone_internetgames/src/shared/components/zoneutil/eventlog.cpp
a9261faf36401c4249c24a2d844f372c4cf059eb
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,553
cpp
#include <windows.h> #include "eventlog.h" #include "zonemsg.h" #include "zonedebug.h" #ifndef ASSERT #define ASSERT(X) #endif CEventLog::CEventLog() : m_hLog(NULL), m_RefCnt(0) { } CEventLog::~CEventLog() { Deregister( TRUE ); } BOOL CEventLog::Register( LPCTSTR pSource ) { BOOL bRet = FALSE; if ( m_RefCnt == 0 ) { ASSERT( !m_hLog ); m_hLog = RegisterEventSource( NULL, pSource ); if ( m_hLog ) { InterlockedIncrement( &m_RefCnt ); bRet = TRUE; } } else { ASSERT( m_hLog ); InterlockedIncrement( &m_RefCnt ); bRet = TRUE; } return bRet; } void CEventLog::Deregister( BOOL bForceUnregister ) { InterlockedDecrement( &m_RefCnt ); if ( bForceUnregister || (m_RefCnt <= 0) ) { if ( m_hLog ) DeregisterEventSource( m_hLog ); m_hLog = NULL; InterlockedExchange( &m_RefCnt, 0 ); } } WORD CEventLog::EventTypeFromID( DWORD dwEventID ) { switch ( dwEventID >> 30 ) { case STATUS_SEVERITY_ERROR: return EVENTLOG_ERROR_TYPE; case STATUS_SEVERITY_WARNING: return EVENTLOG_WARNING_TYPE; case STATUS_SEVERITY_SUCCESS: case STATUS_SEVERITY_INFORMATIONAL: return EVENTLOG_INFORMATION_TYPE; default: ASSERT( !"Invalid Severity" ); return 0; }; } BOOL CEventLog::Report( DWORD dwEventID, WORD wNumStrings, LPTSTR* lpStrings, DWORD dwDataSize, LPVOID lpData ) { if( m_hLog ) return ReportEvent( m_hLog, EventTypeFromID( dwEventID ), 0, dwEventID, NULL, wNumStrings, dwDataSize, (LPCTSTR *)lpStrings, lpData ); else return FALSE; } CEventLog gLog; BOOL ZoneEventLogStartup(LPCTSTR pSource) { return gLog.Register( pSource ); } void ZoneEventLogShutdown() { gLog.Deregister(); } BOOL ZoneEventLogReport( DWORD dwEventID, WORD wNumStrings, LPTSTR* lpStrings, DWORD dwDataSize, LPVOID lpData ) { return gLog.Report( dwEventID, wNumStrings, lpStrings, dwDataSize, lpData ); } BOOL EventLogAssertHandler( TCHAR* buf ) { LPTSTR ppStr[] = { buf }; ZoneEventLogReport( ZONE_E_ASSERT, 1, ppStr, 0, NULL ); return TRUE; } BOOL EventLogAssertWithDialogHandler( TCHAR* buf ) { EventLogAssertHandler( buf ); return ZAssertDefaultHandler( buf ); }
9a9fc4154be3070a6213bb2088b97b0c1b84bc2b
65f9576021285bc1f9e52cc21e2d49547ba77376
/LINUX/android/vendor/qcom/proprietary/interfaces/gnss/1.0/impl/LocHidlWiFiDBReceiver.h
51a850273b27a9fd1d7b12ee5d58db90bf699044
[ "Apache-2.0" ]
permissive
AVCHD/qcs605_root_qcom
183d7a16e2f9fddc9df94df9532cbce661fbf6eb
44af08aa9a60c6ca724c8d7abf04af54d4136ccb
refs/heads/main
2023-03-18T21:54:11.234776
2021-02-26T11:03:59
2021-02-26T11:03:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
h
/* * Copyright (c) 2017 Qualcomm Technologies, Inc. * All Rights Reserved. * Confidential and Proprietary - Qualcomm Technologies, Inc. */ #ifndef VENDOR_QTI_GNSS_V1_0_LOCHIDLWIFIDBRECEIVER_H #define VENDOR_QTI_GNSS_V1_0_LOCHIDLWIFIDBRECEIVER_H #include <vendor/qti/gnss/1.0/ILocHidlWiFiDBReceiver.h> #include <hidl/MQDescriptor.h> #include <hidl/Status.h> #include <location_interface.h> namespace vendor { namespace qti { namespace gnss { namespace V1_0 { namespace implementation { using ::android::hidl::base::V1_0::DebugInfo; using ::android::hidl::base::V1_0::IBase; using ::vendor::qti::gnss::V1_0::ILocHidlWiFiDBReceiver; using ::vendor::qti::gnss::V1_0::ILocHidlWiFiDBReceiverCallback; using ::android::hardware::hidl_array; using ::android::hardware::hidl_memory; using ::android::hardware::hidl_string; using ::android::hardware::hidl_vec; using ::android::hardware::Return; using ::android::hardware::Void; using ::android::hardware::hidl_death_recipient; using ::android::sp; using ::android::wp; struct LocHidlDeathRecipient; struct LocHidlWiFiDBReceiver : public ILocHidlWiFiDBReceiver { LocHidlWiFiDBReceiver(); ~LocHidlWiFiDBReceiver(); // Methods from ::vendor::qti::gnss::V1_0::ILocHidlWiFiDBReceiver follow. Return<bool> init(const sp<ILocHidlWiFiDBReceiverCallback>& callback) override; Return<void> registerWiFiDBUpdater(const sp<ILocHidlWiFiDBReceiverCallback>& callback) override; Return<void> unregisterWiFiDBUpdater() override; Return<void> sendAPListRequest(int32_t expireInDays) override; Return<void> pushAPWiFiDB(const hidl_vec<ILocHidlWiFiDBReceiver::LocHidlApLocationData>& apLocationDataList, int16_t apLocationDataListSize, const hidl_vec<ILocHidlWiFiDBReceiver::LocHidlApSpecialInfo>& apSpecialInfoList, int16_t apSpecialInfoListSize, int32_t daysValid) override; private: void* mIzatWiFiDBReceiverApiClient = nullptr; sp<ILocHidlWiFiDBReceiverCallback> mCallbackIface = nullptr; sp<LocHidlDeathRecipient> mDeathRecipient = nullptr; }; extern "C" ILocHidlWiFiDBReceiver* HIDL_FETCH_ILocHidlWiFiDBReceiver(const char* name); } // namespace implementation } // namespace V1_0 } // namespace gnss } // namespace qti } // namespace vendor #endif // VENDOR_QTI_GNSS_V1_0_LOCHIDLWIFIDBRECEIVER_H
40bfe1c10a2a0608d738c098f17e9f57124b270d
5d384c6ecbd9b1201b1e60f1ebde8f193fcc153b
/src/podcast/intranet/UBIntranetPodcastPublisher.h
af4515026351bc84b6b9a64961fc4d582b494267
[]
no_license
GamalMohamed/RGB_IWB
2cf5e7f7e0418a8dfd5797be0bbf22eda6d46810
cd26e8413f7167fe2fad526cbebbc992659dbca8
refs/heads/master
2021-01-22T15:34:43.804749
2016-09-02T09:23:43
2016-09-02T09:23:43
63,418,651
0
0
null
null
null
null
UTF-8
C++
false
false
2,266
h
/* * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA) * * This file is part of Open-Sankoré. * * Open-Sankoré is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License, * with a specific linking exception for the OpenSSL project's * "OpenSSL" library (or with modified versions of it that use the * same license as the "OpenSSL" library). * * Open-Sankoré is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. */ #ifndef UBUNILPUBLISHER_H_ #define UBUNILPUBLISHER_H_ #include <QtGui> #include "ui_intranetPodcastPublishingDialog.h" class UBServerXMLHttpRequest; class UBIntranetPodcastPublisher : public QObject { Q_OBJECT; public: UBIntranetPodcastPublisher(QObject* pParent = 0); virtual ~UBIntranetPodcastPublisher(); public slots: void publishVideo(const QString& videoFilePath, long durationInMs); void postVideoPublishingRequest(); void postVideoPublishingResponse(bool success, const QByteArray& pPayload); void progress(qint64 bytesSent, qint64 bytesTotal); private: QString metadata(); QString mVideoFilePath; QString mTitle; QString mDescription; QString mAuthor; long mVideoDurationInMs; UBServerXMLHttpRequest *mPublishingRequest; }; class UBIntranetPodcastPublishingDialog : public QDialog, public Ui::IntranetPodcastPublishingDialog { Q_OBJECT; public: UBIntranetPodcastPublishingDialog(const QString& videoFilePath, QWidget *parent = 0); ~UBIntranetPodcastPublishingDialog(){}; private slots: void updateUIState(const QString& = QString("")); }; #endif /* UBUNILPUBLISHER_H_ */
7568ac3110f9819510b159515e4588a807d043f4
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/Wrapping/ClientServer/vtkContingencyStatisticsClientServer.cxx
6eafdccd60e9493f6d2eed179c58637076f3a800
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
4,512
cxx
// ClientServer wrapper for vtkContingencyStatistics object // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkContingencyStatistics.h" #include "vtkSystemIncludes.h" #include "vtkClientServerInterpreter.h" #include "vtkClientServerStream.h" vtkObjectBase *vtkContingencyStatisticsClientServerNewCommand(void* /*ctx*/) { return vtkContingencyStatistics::New(); } int VTK_EXPORT vtkContingencyStatisticsCommand(vtkClientServerInterpreter *arlu, vtkObjectBase *ob, const char *method, const vtkClientServerStream& msg, vtkClientServerStream& resultStream, void* /*ctx*/) { vtkContingencyStatistics *op = vtkContingencyStatistics::SafeDownCast(ob); if(!op) { vtkOStrStreamWrapper vtkmsg; vtkmsg << "Cannot cast " << ob->GetClassName() << " object to vtkContingencyStatistics. " << "This probably means the class specifies the incorrect superclass in vtkTypeMacro."; resultStream.Reset(); resultStream << vtkClientServerStream::Error << vtkmsg.str() << 0 << vtkClientServerStream::End; return 0; } (void)arlu; if (!strcmp("GetClassName",method) && msg.GetNumberOfArguments(0) == 2) { const char *temp20; { temp20 = (op)->GetClassName(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("IsA",method) && msg.GetNumberOfArguments(0) == 3) { char *temp0; int temp20; if(msg.GetArgument(0, 2, &temp0)) { temp20 = (op)->IsA(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("NewInstance",method) && msg.GetNumberOfArguments(0) == 2) { vtkContingencyStatistics *temp20; { temp20 = (op)->NewInstance(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("SafeDownCast",method) && msg.GetNumberOfArguments(0) == 3) { vtkObject *temp0; vtkContingencyStatistics *temp20; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkObject")) { temp20 = (op)->SafeDownCast(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("New",method) && msg.GetNumberOfArguments(0) == 2) { vtkContingencyStatistics *temp20; { temp20 = (op)->New(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("Aggregate",method) && msg.GetNumberOfArguments(0) == 4) { vtkDataObjectCollection *temp0; vtkMultiBlockDataSet *temp1; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkDataObjectCollection") && vtkClientServerStreamGetArgumentObject(msg, 0, 3, &temp1, "vtkMultiBlockDataSet")) { op->Aggregate(temp0,temp1); return 1; } } { const char* commandName = "vtkStatisticsAlgorithm"; if (arlu->HasCommandFunction(commandName) && arlu->CallCommandFunction(commandName, op, method, msg, resultStream)) { return 1; } } if(resultStream.GetNumberOfMessages() > 0 && resultStream.GetCommand(0) == vtkClientServerStream::Error && resultStream.GetNumberOfArguments(0) > 1) { /* A superclass wrapper prepared a special message. */ return 0; } vtkOStrStreamWrapper vtkmsg; vtkmsg << "Object type: vtkContingencyStatistics, could not find requested method: \"" << method << "\"\nor the method was called with incorrect arguments.\n"; resultStream.Reset(); resultStream << vtkClientServerStream::Error << vtkmsg.str() << vtkClientServerStream::End; vtkmsg.rdbuf()->freeze(0); return 0; } //-------------------------------------------------------------------------auto void VTK_EXPORT vtkContingencyStatistics_Init(vtkClientServerInterpreter* csi) { static vtkClientServerInterpreter* last = NULL; if(last != csi) { last = csi; csi->AddNewInstanceFunction("vtkContingencyStatistics", vtkContingencyStatisticsClientServerNewCommand); csi->AddCommandFunction("vtkContingencyStatistics", vtkContingencyStatisticsCommand); } }
f2074d70b276ba3168a7f17e599f37fe15ef59fd
7b460bd397fcc365973d063657b15a7bde6ed795
/source/d3d11/d3d11_command_list.hpp
5f580640d2c5b8984998a28170452c7720e5826b
[ "BSD-3-Clause" ]
permissive
Redundanz/reshade
6f05d8105adb9add0516db380bfe6da859514478
c1d826febc23fc2b18dfc8fc18ac7806169b85dd
refs/heads/main
2023-03-18T02:58:40.769804
2021-05-24T20:00:32
2021-05-24T20:00:32
353,998,079
1
0
BSD-3-Clause
2021-04-02T11:24:59
2021-04-02T11:24:59
null
UTF-8
C++
false
false
1,260
hpp
/* * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include "reshade_api_device_context.hpp" struct D3D11Device; struct DECLSPEC_UUID("592F5E83-A17B-4EEB-A2BF-7568DA2A3728") D3D11CommandList final : ID3D11CommandList, public reshade::d3d11::command_list_impl { D3D11CommandList(D3D11Device *device, ID3D11CommandList *original); #pragma region IUnknown HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObj) override; ULONG STDMETHODCALLTYPE AddRef() override; ULONG STDMETHODCALLTYPE Release() override; #pragma endregion #pragma region ID3D11DeviceChild void STDMETHODCALLTYPE GetDevice(ID3D11Device **ppDevice) override; HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData) override; HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT DataSize, const void *pData) override; HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown *pData) override; #pragma endregion #pragma region ID3D11CommandList UINT STDMETHODCALLTYPE GetContextFlags() override; #pragma endregion bool check_and_upgrade_interface(REFIID riid); ULONG _ref = 1; D3D11Device *const _device; };
8474973bd69c305414cf88e958b5b1161f1e099c
ce9a92b666c7d77af69c19fd8982288315d8a02d
/server/SessionServer.cpp
c06e026761f593cb8c8ed082288aaf3ac727f485
[ "MIT" ]
permissive
drclaws/Simple_ClientServer
a7aee2801b2f10aa2dc218b12db38ab420d83c3a
e6ee5807b2d3b634c7a1e715e1be97aa5831e725
refs/heads/main
2023-01-09T17:38:17.936577
2020-11-06T10:34:22
2020-11-06T10:34:22
308,782,341
1
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
#include "SessionServer.hpp" #include <sys/socket.h> #include <sys/epoll.h> #include <unistd.h> namespace simpleApp { SessionServer::SessionServer(int epollfd, std::string name) : Session(), epollfd(epollfd), _name(name) { } SessionServer::~SessionServer() { } std::string SessionServer::getName() { return this->_name; } void SessionServer::sessionClose() { if (this->_socket != -1) { epoll_ctl(this->epollfd, EPOLL_CTL_DEL, this->_socket, 0); } Session::sessionClose(); } std::string addressToString(sockaddr_in& address) { auto portConverted = ntohs(address.sin_port); uint8_t* addressByBytes = reinterpret_cast<uint8_t*>(&address.sin_addr.s_addr); return std::to_string(static_cast<int>(addressByBytes[0])) + std::string(".") + std::to_string(static_cast<int>(addressByBytes[1])) + std::string(".") + std::to_string(static_cast<int>(addressByBytes[2])) + std::string(".") + std::to_string(static_cast<int>(addressByBytes[3])) + std::string(":") + std::to_string(portConverted); } }
b777b3b0432d09d8c857055b7313b6546ae8c374
696221bce2a5f2424cc7ee76c5b2fa42204741b4
/source/code/scratch/old_repos/Jstd/Jstd-Bootstrap/bootstrap_progs/git-it/project/src/.pulls/program_options.pulled/program_options.cpp
366e33ef3d3c44c03024da0e386175c7feb285e0
[]
no_license
advaitsangle/unilang
b325cc8cc42c719ad7182f47fc28d38aedf1bbfa
365965159c1c997b4f02a5d3704daf2dae986eb4
refs/heads/master
2022-11-09T19:57:34.624803
2020-06-28T23:57:34
2020-06-28T23:57:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,725
cpp
#include "program_options.hpp" #include <string> #include <iostream> //constructor Program_Options::Program_Options(int const& argc, char** const& argv){ using namespace boost::program_options; //build all the possible flags and add description. options_description desc (Get_Options_Description()); //set positional arguments positional_options_description pod; pod.add("url", -1); //build variable map Build_Variable_Map(argc,argv,desc,pod); //process immediate options Process_Immediate_Options(desc); //validate the mandatory flags Check_For_Mandatory_Flags_Not_Passed(); } boost::program_options::options_description Program_Options::Get_Options_Description(void){ using namespace boost::program_options; //Program Description options_description desc(DESCRIPTION); //Program Flags desc.add_options() //these are flag descriptions of that can be passed into the class. //the code inserted, are the flags added by the user through the //program_options_maker flag interface ("url",value<std::string>()->multitoken(),"the url of the repository to download") ("no_deps","download the repository, but don't apply the symbolic pull-ins") ("recursive","apply the symbolic pull-ins to the current directory and all sub directories") ("all","apply the symbolic pull-ins to all parts of the repository") ("symfile",value<std::vector<std::string>>(),"apply specified symbolic pull-in") ("clean","perform a clean instead of an update") ("no-ignore","stops git-it from creating a global .gitignore file") ("wipe-local","deletes all of the locally downloaded repos") ("allow-nested-git","allows downloading git repos inside git repos. Although not recomended, and generally attempted by acccident, it can be overridden for times when it needs to be done.") //+----------------------------------------------------------+ //| Obligatory | //+----------------------------------------------------------+ ("help,h","produce this help message") ("version,v","display version") ; return desc; } void Program_Options::Build_Variable_Map(int const& argc, char** const& argv, boost::program_options::options_description const& desc, boost::program_options::positional_options_description const& pod){ using namespace boost::program_options; //store user flag data. crash elegantly if they pass incorrect flags. try{ store(command_line_parser(argc, argv).options(desc).positional(pod).run(), vm); notify(vm); } catch(error& e){ std::cerr << "ERROR: " << e.what() << std::endl; std::cerr << desc << std::endl; exit(EXIT_FAILURE); } return; } void Program_Options::Process_Immediate_Options( boost::program_options::options_description const& desc){ //do not continue the program if the user wanted to see the version or help data if (vm.count("version")){ std::cout << "\nThis is version " << VERSION_NUMBER << " of the " + TOOL_NAME + ".\n\n"; exit(EXIT_SUCCESS); } else if (vm.count("help")){ std::cout << '\n' << desc << '\n'; exit(EXIT_SUCCESS); } return; } void Program_Options::Check_For_Mandatory_Flags_Not_Passed(){ std::vector<std::string> flags_not_passed; if (!flags_not_passed.empty()){ std::cerr << "you need to pass the following flags still:\n"; for (auto it: flags_not_passed){ std::cerr << '\t' << it << '\n'; } exit(EXIT_FAILURE); } return; } bool Program_Options::No_Flags_Were_Passed() const{ if (vm.count("url")){return false;} if (vm.count("no_deps")){return false;} if (vm.count("recursive")){return false;} if (vm.count("all")){return false;} if (vm.count("symfile")){return false;} if (vm.count("clean")){return false;} if (vm.count("no-ignore")){return false;} if (vm.count("wipe-local")){return false;} if (vm.count("allow-nested-git")){return false;} return true; } std::string Program_Options::URL() const{ std::string data= ""; if (vm.count("url")){ data = vm["url"].as<std::string>(); } return data; } bool Program_Options::Deps() const{ return !vm.count("no_deps");} bool Program_Options::Recursive() const{ return vm.count("recursive");} bool Program_Options::All() const{ return vm.count("all");} std::vector<std::string> Program_Options::Symfiles() const{ std::vector<std::string> data= std::vector<std::string>(); if (vm.count("symfile")){ data = vm["symfile"].as<std::vector<std::string>>(); } return data; } bool Program_Options::Clean() const{ return vm.count("clean");} bool Program_Options::Generate_Ignore() const{ return !vm.count("no-ignore");} bool Program_Options::Clear_Local_Repo_Cache() const{ return vm.count("wipe-local");} bool Program_Options::Allow_Nested_Git_Repos() const{ return vm.count("allow-nested-git");}
eecc9065b17c232ae1b9a1dfe35a7cf536f6f08d
2b5fb4af4abcfa8c03c62c162534aadfa2802d6b
/Game/Scripts/hud/PlayerEconHUDElement.h
a87b721a4c362b34e7f285f17425a6b10187daa9
[ "MIT" ]
permissive
JohnHonkanen/ProjectM
08691b0c350268f1f7e74d1d03ae456188dfe0de
881171ad749e8fe7db6188ee9486239a37256569
refs/heads/master
2021-03-27T11:14:14.264184
2018-04-12T20:49:13
2018-04-12T20:49:13
118,777,372
0
0
null
null
null
null
UTF-8
C++
false
false
774
h
#pragma once #include "hud\HUDWidget.h" #include "hud\HUDRect.h" #include <string> // Namespace Alias class PlayerEconHUD; namespace EHUD = Engine::HUD; namespace Engine { namespace HUD { class TextWidget; } } class PlayerEconHUDElement : public EHUD::HUDWidget{ public: static PlayerEconHUDElement* Create(HUDElement* element, EHUD::HUDRect rect, class PlayerEconomy* playerEconomy); //static PlayerEconHUDElement* Create(HUDElement* element, EHUD::HUDRect rect); void Start(); void Update(); void DrawWidget(unsigned int shader); void SetPlayerEcon(PlayerEconomy* economyToSet); class PlayerEconomy* GetPlayerEcon(); private: class PlayerEconomy* playerEconomy; EHUD::TextWidget* text, *playerGold; EHUD::HUDElement* playerEconHUD, *resourceIcon; };
b9b2d7084331ec5b4b9acdca3a39ba6045b8e5b3
05dee134ef4e552fecd0d39dea5d6cdc3a82965c
/HDU/HDU-4121.cpp
fb5c3175850781021e6ca537f2f582ccd22f5832
[]
no_license
yliu-cs/ACM
35239420f36baf336e17a5c45d2c7a5ae9317413
f67ca3e6de900afabe38201e19c74d0e1c6a40a3
refs/heads/master
2022-03-20T10:10:25.787434
2019-12-05T16:30:29
2019-12-05T16:30:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,399
cpp
#include <bits/stdc++.h> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) #define pb push_back #define mp make_pair #define lowbit(x) (x&(-x)) typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> PII; typedef pair<double,double> PDD; const int INF = 0x3f3f3f3f; const int maxn = 1e5 + 5; const int mod = 1e9 + 7; const double eps = 1e-8; const double pi = asin(1.0) * 2; const double e = 2.718281828459; bool Finish_read; template<class T>inline void read(T &x) { Finish_read = 0; x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') { f = -1; } if (ch == EOF) { return; } ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); } x *= f; Finish_read = 1; }; // 模拟 int main(int argc, char *argv[]) { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif int n, BlackGY, BlackGX; // while (~scanf("%d %d %d", &n, &BlackGY, &BlackGX) && n + BlackGY + BlackGX) { while (cin >> n >> BlackGY >> BlackGX) { if (!n && !BlackGY && !BlackGX) { break; } bool move[11][10]; mem(move, 1); char pieces[11][10]; mem(pieces, ' '); bool flag = 0; for (int i = 0; i < n; ++i) { char piece; int y, x; // scanf("%c %d %d", &piece, &y, &x); cin >> piece >> y >> x; pieces[y][x] = piece; } for (int i = 1; i <= 10; ++i) { for (int j = 1; j <= 9; ++j) { if (pieces[i][j] != ' ') { // printf("pieces[%d][%d]=%c\n", i, j, pieces[i][j]); if (pieces[i][j] == 'G' || pieces[i][j] == 'R') { for (int k = i - 1; k > 0; --k) { if (pieces[k][j] == ' ') { move[k][j] = 0; } else { move[k][j] = 0; break; } } for (int k = i + 1; k <= 10; ++k) { if (pieces[k][j] == ' ') { move[k][j] = 0; } else { move[k][j] = 0; break; } } for (int k = j - 1; k > 0; --k) { if (pieces[i][k] == ' ') { move[i][k] = 0; } else { move[i][k] = 0; break; } } for (int k = j + 1; k <= 9; ++k) { if (pieces[i][k] == ' ') { move[i][k] = 0; } else { move[i][k] = 0; break; } } } else if (pieces[i][j] == 'C') { int cnt = 0; for (int k = i - 1; k > 0; --k) { if (pieces[k][j] == ' ') { if (cnt) { move[k][j] = 0; } } else { if (!cnt) { cnt++; } else { move[k][j] = 0; break; } } } cnt = 0; for (int k = i + 1; k <= 10; ++k) { if (pieces[k][j] == ' ') { if (cnt) { move[k][j] = 0; } } else { if (!cnt) { cnt++; } else { move[k][j] = 0; break; } } } cnt = 0; for (int k = j - 1; k > 0; --k) { if (pieces[i][k] == ' ') { if (cnt) { move[i][k] = 0; } } else { if (!cnt) { cnt++; } else { move[i][k] = 0; break; } } } cnt = 0; for (int k = j + 1; k <= 9; ++k) { if (pieces[i][k] == ' ') { if (cnt) { move[i][k] = 0; } } else { if (!cnt) { cnt++; } else { move[i][k] = 0; break; } } } } else if (pieces[i][j] == 'H') { if (i >= 3) { if (pieces[i - 1][j] == ' ') { if (j >= 2) { move[i - 2][j - 1] = 0; } if (j <= 8) { move[i - 2][j + 1] = 0; } } } if (j >= 3) { if (pieces[i][j - 1] == ' ') { if (i >= 2) { move[i - 1][j - 2] = 0; } if (i <= 9) { move[i + 1][j - 2] = 0; } } } if (i <= 8) { if (pieces[i + 1][j] == ' ') { if (j >= 2) { move[i + 2][j - 1] = 0; } if (j <= 8) { move[i + 2][j + 1] = 0; } } } if (j <= 7) { if(pieces[i][j + 1] == ' ') { if (i >= 2) { move[i - 1][j + 2] = 0; } if (i <= 9) { move[i + 1][j + 2] = 0; } } } } } } } if (BlackGY == 1) { if (BlackGX == 4) { if (move[1][5] || move[2][4]) { flag = 1; } } else if (BlackGX == 5) { if (move[1][4] || move[1][6] || move[2][5]) { flag = 1; } } else if (BlackGX == 6) { if (move[1][5] || move[2][6]) { flag = 1; } } } else if (BlackGY == 2) { if (BlackGX == 4) { if (move[1][4] || move[2][5] || move[3][4]) { flag = 1; } } else if (BlackGX == 5) { if (move[1][5] || move[2][4] || move[2][6] || move[3][5]) { flag = 1; } } else if (BlackGX == 6) { if (move[1][6] || move[2][5] || move[3][6]) { flag = 1; } } } else if (BlackGY == 3) { if (BlackGX == 4) { if (move[2][4] || move[3][5]) { flag = 1; } } else if (BlackGX == 5) { if (move[3][4] || move[2][5] || move[3][6]) { flag = 1; } } else if (BlackGX == 6) { if (move[3][5] || move[2][6]) { flag = 1; } } } bool ok = 1; for (int i = BlackGY + 1; i <= 10; ++i) { if (pieces[i][BlackGX] != ' ') { if (pieces[i][BlackGX] == 'G' && ok) { flag = 1; } break; } } if (flag) { // printf("NO\n"); cout << "NO" << endl; } else { // printf("YES\n"); cout << "YES" << endl; } } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); system("gedit out.txt"); #endif return 0; }
2283311e0064d3d70117e8c773c745f115b40def
5a60d60fca2c2b8b44d602aca7016afb625bc628
/aws-cpp-sdk-application-insights/source/model/ListApplicationsResult.cpp
0b1f730ffa218070e60293792e52cfa3da142f0e
[ "Apache-2.0", "MIT", "JSON" ]
permissive
yuatpocketgems/aws-sdk-cpp
afaa0bb91b75082b63236cfc0126225c12771ed0
a0dcbc69c6000577ff0e8171de998ccdc2159c88
refs/heads/master
2023-01-23T10:03:50.077672
2023-01-04T22:42:53
2023-01-04T22:42:53
134,497,260
0
1
null
2018-05-23T01:47:14
2018-05-23T01:47:14
null
UTF-8
C++
false
false
1,414
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/application-insights/model/ListApplicationsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::ApplicationInsights::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListApplicationsResult::ListApplicationsResult() { } ListApplicationsResult::ListApplicationsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListApplicationsResult& ListApplicationsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ApplicationInfoList")) { Aws::Utils::Array<JsonView> applicationInfoListJsonList = jsonValue.GetArray("ApplicationInfoList"); for(unsigned applicationInfoListIndex = 0; applicationInfoListIndex < applicationInfoListJsonList.GetLength(); ++applicationInfoListIndex) { m_applicationInfoList.push_back(applicationInfoListJsonList[applicationInfoListIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
fb8656f5c0271be61d88d7d7a092769c9a5d3d55
6f45a7c0656311e6e15a7c343b2fc9d1aebe4fd0
/src/qt/sendcoinsdialog.cpp
ed4b095afe83891be4e6b37ddbf7db7283ad79a3
[ "MIT" ]
permissive
zugcoin/crypto
da75f3abc8dd5ae003a4d922d2dc4f0f1dc11293
6be50a55d98e1471fa6991419aa23456fa1724f1
refs/heads/master
2020-03-22T23:18:30.854279
2018-07-16T18:14:30
2018-07-16T18:14:30
140,802,339
5
0
null
null
null
null
UTF-8
C++
false
false
17,896
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 zugcoin address (e.g. 18gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); #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 zugcoin 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(); } }
35aac28299b0d554ce817e9720802e287f0211e3
7d79c5492bb44872622b11abbbb6e955f29516c0
/Code/Client/ClientUI/Source/GifImage.cpp
ad80dc0b9274593cc76908c6b08da16589046b87
[ "MIT" ]
permissive
asdlei99/TinyIM
7ffe5c7d0314118c12e0e8c8495d304393d5d1bd
48c0328cc114bc5f05a5a687d56f1513cdb630b8
refs/heads/master
2021-01-02T14:55:42.932510
2020-02-10T04:07:41
2020-02-10T04:07:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,127
cpp
#include "stdafx.h" #include "GifImage.h" CGifImage::CGifImage(void) { m_pImage = NULL; m_nFrameCnt = 0; m_nFramePos = 0; m_pFrameDelay = NULL; } CGifImage::~CGifImage(void) { Destroy(); } BOOL CGifImage::LoadFromFile(LPCTSTR pszFileName) { Destroy(); if (NULL == pszFileName || NULL ==*pszFileName) return FALSE; m_pImage = new Gdiplus::Image(pszFileName); if (NULL == m_pImage) return FALSE; if (m_pImage->GetLastStatus() != Gdiplus::Ok) { delete m_pImage; m_pImage = NULL; return FALSE; } return ReadGifInfo(); } BOOL CGifImage::LoadFromIStream(IStream* pStream) { Destroy(); if (NULL == pStream) return FALSE; m_pImage = new Gdiplus::Image(pStream); if (NULL == m_pImage) return FALSE; if (m_pImage->GetLastStatus() != Gdiplus::Ok) { delete m_pImage; m_pImage = NULL; return FALSE; } return ReadGifInfo(); } BOOL CGifImage::LoadFromBuffer(const BYTE* lpBuf, DWORD dwSize) { if (NULL == lpBuf || dwSize <= 0) return FALSE; HGLOBAL hGlobal = ::GlobalAlloc(GHND, dwSize); if (NULL == hGlobal) return FALSE; LPVOID lpBuffer = ::GlobalLock(hGlobal); if (NULL == lpBuffer) { ::GlobalFree(hGlobal); return FALSE; } memcpy(lpBuffer, lpBuf, dwSize); ::GlobalUnlock(hGlobal); LPSTREAM lpStream = NULL; HRESULT hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, &lpStream); if (hr != S_OK) { ::GlobalFree(hGlobal); return FALSE; } BOOL bRet = LoadFromIStream(lpStream); lpStream->Release(); return bRet; } BOOL CGifImage::LoadFromResource(HINSTANCE hInstance, LPCTSTR pszResourceName, LPCTSTR pszResType) { return TRUE; } BOOL CGifImage::LoadFromResource(HINSTANCE hInstance, UINT nIDResource, LPCTSTR pszResType) { return TRUE; } BOOL CGifImage::SaveAsFile(LPCTSTR pszFileName) { if (NULL == pszFileName || NULL == m_pImage) return FALSE; LPCTSTR lpExtension = _tcsrchr(pszFileName, _T('.')); if (NULL == lpExtension) return FALSE; CLSID clsid = GetEncoderClsidByExtension(lpExtension); if (CLSID_NULL == clsid) return FALSE; Gdiplus::Status status = m_pImage->Save(pszFileName, &clsid, NULL); return (status != Gdiplus::Ok) ? FALSE : TRUE; } void CGifImage::Destroy() { m_nFrameCnt = 0; m_nFramePos = 0; if (m_pFrameDelay != NULL) { delete []m_pFrameDelay; m_pFrameDelay = NULL; } if (m_pImage != NULL) { delete m_pImage; m_pImage = NULL; } } UINT CGifImage::GetFrameCount() { return m_nFrameCnt; } BOOL CGifImage::IsAnimatedGif() { return m_nFrameCnt > 1; } long CGifImage::GetFrameDelay(int nFramePos/* = -1*/) { if (!IsAnimatedGif() || NULL == m_pFrameDelay) return 0; int nFramePos2; if (nFramePos != -1) nFramePos2 = nFramePos; else nFramePos2 = m_nFramePos; if (nFramePos2 >= 0 && nFramePos2 < (int)m_nFrameCnt) return m_pFrameDelay[nFramePos2]; else return 0; } void CGifImage::ActiveNextFrame() { if (m_pImage != NULL && IsAnimatedGif()) { m_nFramePos++; if (m_nFramePos == m_nFrameCnt) m_nFramePos = 0; if (m_nFramePos >= 0 && m_nFramePos < m_nFrameCnt) { static GUID Guid = Gdiplus::FrameDimensionTime; Gdiplus::Status status = m_pImage->SelectActiveFrame(&Guid, m_nFramePos); } } } void CGifImage::SelectActiveFrame(int nFramePos) { if (m_pImage != NULL && IsAnimatedGif() && nFramePos >= 0 && nFramePos < (int)m_nFrameCnt) { static GUID Guid = Gdiplus::FrameDimensionTime; Gdiplus::Status status = m_pImage->SelectActiveFrame(&Guid, nFramePos); m_nFramePos = nFramePos; } } BOOL CGifImage::Draw(HDC hDestDC, int xDest, int yDest, int nFramePos/* = -1*/) { // HDC hMemDC; // HBITMAP hBitmap = NULL, hOldBmp; // Gdiplus::Bitmap* pBitmap; // int nWidth, nHeight; // // if (NULL == m_pImage) // return FALSE; // // if (nFramePos != -1) // SelectActiveFrame(nFramePos); // // nWidth = m_pImage->GetWidth(); // nHeight = m_pImage->GetHeight(); // // pBitmap = (Gdiplus::Bitmap*)m_pImage; // pBitmap->GetHBITMAP(Gdiplus::Color::Transparent, &hBitmap); // // hMemDC = ::CreateCompatibleDC(hDestDC); // hOldBmp = (HBITMAP)::SelectObject(hMemDC, hBitmap); // // BLENDFUNCTION stBlendFunction = {0}; // stBlendFunction.BlendOp= AC_SRC_OVER; // stBlendFunction.SourceConstantAlpha = 255; // stBlendFunction.AlphaFormat = AC_SRC_ALPHA; // // BOOL bStat = ::AlphaBlend(hDestDC, xDest, yDest, nWidth, nHeight, // hMemDC, 0, 0, nWidth, nHeight, stBlendFunction); // // ::SelectObject(hMemDC, hOldBmp); // ::DeleteObject(hBitmap); // ::DeleteDC(hMemDC); // // return TRUE; Gdiplus::Graphics graphics(hDestDC); Gdiplus::Status status = graphics.DrawImage(m_pImage, xDest, yDest); if(status != Gdiplus::Ok) return FALSE; else return TRUE; } BOOL CGifImage::Draw(HDC hDestDC, const RECT& rectDest, int nFramePos/* = -1*/) { // HDC hMemDC; // HBITMAP hBitmap = NULL, hOldBmp; // Gdiplus::Bitmap* pBitmap; // int nWidth, nHeight; // // if (NULL == m_pImage) // return FALSE; // // if (nFramePos != -1) // SelectActiveFrame(nFramePos); // // nWidth = m_pImage->GetWidth(); // nHeight = m_pImage->GetHeight(); // // pBitmap = (Gdiplus::Bitmap*)m_pImage; // pBitmap->GetHBITMAP(Gdiplus::Color::Transparent, &hBitmap); // // hMemDC = ::CreateCompatibleDC(hDestDC); // hOldBmp = (HBITMAP)::SelectObject(hMemDC, hBitmap); // // BLENDFUNCTION stBlendFunction = {0}; // stBlendFunction.BlendOp= AC_SRC_OVER; // stBlendFunction.SourceConstantAlpha = 255; // stBlendFunction.AlphaFormat = AC_SRC_ALPHA; // // BOOL bStat = ::AlphaBlend(hDestDC, rectDest.left, rectDest.top, // rectDest.right - rectDest.left, rectDest.bottom - rectDest.top, // hMemDC, 0, 0, nWidth, nHeight, stBlendFunction); // // ::SelectObject(hMemDC, hOldBmp); // ::DeleteObject(hBitmap); // ::DeleteDC(hMemDC); // // return TRUE; if (NULL == m_pImage) return FALSE; if (nFramePos != -1) SelectActiveFrame(nFramePos); int nWidth = rectDest.right-rectDest.left; int nHeight = rectDest.bottom-rectDest.top; Gdiplus::Graphics graphics(hDestDC); Gdiplus::Status status = graphics.DrawImage(m_pImage, Gdiplus::Rect(rectDest.left, rectDest.top, nWidth, nHeight)); if(status != Gdiplus::Ok) return FALSE; else return TRUE; } int CGifImage::GetWidth() { if (m_pImage != NULL) return m_pImage->GetWidth(); else return 0; } int CGifImage::GetHeight() { if (m_pImage != NULL) return m_pImage->GetHeight(); else return 0; } UINT CGifImage::GetCurFramePos() { return m_nFramePos; } BOOL CGifImage::GetRawFormat(GUID* lpGuid) { Gdiplus::Status status = m_pImage->GetRawFormat(lpGuid); return (Gdiplus::Ok == status) ? TRUE : FALSE; } CLSID CGifImage::GetEncoderClsidByExtension(const WCHAR* lpExtension) { CLSID clsid = CLSID_NULL; if (NULL == lpExtension) return clsid; UINT numEncoders = 0, size = 0; Gdiplus::Status status = Gdiplus::GetImageEncodersSize(&numEncoders, &size); if (status != Gdiplus::Ok) return clsid; Gdiplus::ImageCodecInfo* lpEncoders = (Gdiplus::ImageCodecInfo*)(malloc(size)); if (NULL == lpEncoders) return clsid; status = Gdiplus::GetImageEncoders(numEncoders, size, lpEncoders); if (Gdiplus::Ok == status) { for (UINT i = 0; i < numEncoders; i++) { BOOL bFind = FALSE; const WCHAR* pStart = lpEncoders[i].FilenameExtension; const WCHAR* pEnd = wcschr(pStart, L';'); do { if (NULL == pEnd) { LPCWSTR lpExt = ::wcsrchr(pStart, L'.'); if ((lpExt != NULL) && (_wcsicmp(lpExt, lpExtension) == 0)) { clsid = lpEncoders[i].Clsid; bFind = TRUE; } break; } int nLen = pEnd-pStart; if (nLen < MAX_PATH) { WCHAR cBuf[MAX_PATH] = {0}; wcsncpy(cBuf, pStart, nLen); LPCWSTR lpExt = ::wcsrchr(cBuf, L'.'); if ((lpExt != NULL) && (_wcsicmp(lpExt, lpExtension) == 0)) { clsid = lpEncoders[i].Clsid; bFind = TRUE; break; } } pStart = pEnd+1; if (L'\0' ==*pStart) break; pEnd = wcschr(pStart, L';'); } while (1); if (bFind) break; } } free(lpEncoders); return clsid; } BOOL CGifImage::ReadGifInfo() { if (NULL == m_pImage) return FALSE; UINT nCount = 0; nCount = m_pImage->GetFrameDimensionsCount(); if (nCount <= 0) return FALSE; GUID* pDimensionIDs = new GUID[nCount]; if (NULL == pDimensionIDs) return FALSE; m_pImage->GetFrameDimensionsList(pDimensionIDs, nCount); m_nFrameCnt = m_pImage->GetFrameCount(&pDimensionIDs[0]); delete pDimensionIDs; if (m_nFrameCnt <= 1) return TRUE; UINT nSize = m_pImage->GetPropertyItemSize(PropertyTagFrameDelay); if (nSize <= 0) return FALSE; Gdiplus::PropertyItem* pPropertyItem = (Gdiplus::PropertyItem*)malloc(nSize); if (NULL == pPropertyItem) return FALSE; m_pImage->GetPropertyItem(PropertyTagFrameDelay, nSize, pPropertyItem); m_pFrameDelay = new long[m_nFrameCnt]; if (NULL == m_pFrameDelay) { free(pPropertyItem); return FALSE; } for (int i = 0; i < (int)m_nFrameCnt; i++) { m_pFrameDelay[i] = ((long*)pPropertyItem->value)[i]* 10; // 帧切换延迟时间,以1/100秒为单位 if (m_pFrameDelay[i] < 100) m_pFrameDelay[i] = 100; } free(pPropertyItem); return TRUE; }
2f459973b131ae46af06a157e9ece3d307e952a3
84c9664add913cbd7b64dbcff85b5fb44513d9b4
/src/qt/clientmodel.cpp
97fa233a47f36a5eba8027ca43bbce1f8fe81d56
[ "MIT" ]
permissive
NaniteCurrency/Nanite
cbf3affcb44f1f0475052670049a3e5bef7a2ad9
f30178931f922d088e5317f95522dfdf02c02116
refs/heads/master
2021-04-06T01:54:59.218615
2018-04-27T07:39:29
2018-04-27T07:39:29
125,361,873
0
2
MIT
2018-04-10T22:14:18
2018-03-15T12:09:36
C++
UTF-8
C++
false
false
9,802
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The NANITE developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientmodel.h" #include "bantablemodel.h" #include "guiconstants.h" #include "peertablemodel.h" #include "alert.h" #include "chainparams.h" #include "checkpoints.h" #include "clientversion.h" #include "main.h" #include "masternode-sync.h" #include "masternodeman.h" #include "net.h" #include "ui_interface.h" #include "util.h" #include <stdint.h> #include <QDateTime> #include <QDebug> #include <QTimer> static const int64_t nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel* optionsModel, QObject* parent) : QObject(parent), optionsModel(optionsModel), peerTableModel(0), banTableModel(0), cachedNumBlocks(0), cachedMasternodeCountString(""), cachedReindexing(0), cachedImporting(0), numBlocksAtStartup(-1), pollTimer(0) { peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); pollMnTimer = new QTimer(this); connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer())); // no need to update as frequent as data for balances/txes/blocks pollMnTimer->start(MODEL_UPDATE_DELAY * 4); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { LOCK(cs_vNodes); if (flags == CONNECTIONS_ALL) // Shortcut if we want total return vNodes.size(); int nNum = 0; BOOST_FOREACH (CNode* pnode, vNodes) if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) nNum++; return nNum; } QString ClientModel::getMasternodeCountString() const { int ipv4 = 0, ipv6 = 0, onion = 0; mnodeman.CountNetworks(ActiveProtocol(), ipv4, ipv6, onion); int nUnknown = mnodeman.size() - ipv4 - ipv6 - onion; if(nUnknown < 0) nUnknown = 0; return tr("Total: %1 (IPv4: %2 / IPv6: %3 / Tor: %4 / Unknown: %5)").arg(QString::number((int)mnodeman.size())).arg(QString::number((int)ipv4)).arg(QString::number((int)ipv6)).arg(QString::number((int)onion)).arg(QString::number((int)nUnknown)); } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } quint64 ClientModel::getTotalBytesRecv() const { return CNode::GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { return CNode::GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); else return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } double ClientModel::getVerificationProgress() const { LOCK(cs_main); return Checkpoints::GuessVerificationProgress(chainActive.Tip()); } void ClientModel::updateTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); static int prevAttempt = -1; static int prevAssets = -1; // check for changed number of blocks we have, number of blocks peers claim to have, reindexing state and importing state if (cachedNumBlocks != newNumBlocks || cachedReindexing != fReindex || cachedImporting != fImporting || masternodeSync.RequestedMasternodeAttempt != prevAttempt || masternodeSync.RequestedMasternodeAssets != prevAssets) { cachedNumBlocks = newNumBlocks; cachedReindexing = fReindex; cachedImporting = fImporting; prevAttempt = masternodeSync.RequestedMasternodeAttempt; prevAssets = masternodeSync.RequestedMasternodeAssets; emit numBlocksChanged(newNumBlocks); } emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateMnTimer() { // Get required lock upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; QString newMasternodeCountString = getMasternodeCountString(); if (cachedMasternodeCountString != newMasternodeCountString) { cachedMasternodeCountString = newMasternodeCountString; emit strMasternodesChanged(cachedMasternodeCountString); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString& hash, int status) { // Show error message notification for new alert if (status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if (!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel* ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel* ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel* clientmodel, const std::string& title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel* clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel* clientmodel, const uint256& hash, ChangeType status) { qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); }
c7ba1ad59b9e897afd340d9292191524efb3c8be
697d8dcb9b39ef858cad57d7eced694590821ded
/Omkar and Infinity Clock.cpp
1ef213ce3267193bf6f0dcbc0747705dd0aca4af
[]
no_license
KevinMathewT/Competitive-Programming
e1dcdffd087f8a1d5ca29ae6189ca7fddbdc7754
e7805fe870ad9051d53cafcba4ce109488bc212d
refs/heads/master
2022-02-14T09:37:31.637330
2020-09-26T16:15:26
2020-09-26T16:15:26
147,362,660
4
4
null
2022-02-07T11:13:38
2018-09-04T14:52:29
C++
UTF-8
C++
false
false
2,564
cpp
// Kevin Mathew T // Birla Institute of Technology, Mesra // LinkedIn - https://www.linkedin.com/in/KevinMathewT/ // GitHub - https://github.com/KevinMathewT // CodeForces - https://codeforces.com/profile/KevinMathew // CodeChef - https://www.codechef.com/users/KevinMathew // HackerRank - https://www.hackerrank.com/KevinMathew #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double ld; #define F first #define S second #define fi(a, b) for(ll i=(a);i<=b;i++) #define fj(a, b) for(ll j=(a);j<=b;j++) #define fid(a, b) for(ll i=(a);i>=b;i--) #define fjd(a, b) for(ll j=(a);j>=b;j--) // #include <ext/pb_ds/assoc_container.hpp> // Common file // #include <ext/pb_ds/tree_policy.hpp> // #include <functional> // for less // #include <iostream> // using namespace __gnu_pbds; // using namespace std; // typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // find_by_order(k) : Value at kth index in sorted array. // order_of_key(k) : Index of the value k. template<class T> ostream& operator<<(ostream &os, vector<T> V) { os << "[ "; for(auto v : V) os << v << " "; os << "]"; return os; } template<class T> ostream& operator<<(ostream &os, set<T> S){ os << "{ "; for(auto s:S) os<<s<<" "; return os<<"}"; } template<class T> ostream& operator<<(ostream &os, multiset<T> S){ os << "{ "; for(auto s:S) os<<s<<" "; return os<<"}"; } template<class L, class R> ostream& operator<<(ostream &os, pair<L,R> P) { return os << "(" << P.first << "," << P.second << ")"; } template<class L, class R> ostream& operator<<(ostream &os, map<L,R> M) { os << "{ "; for(auto m:M) os<<"("<<m.F<<":"<<m.S<<") "; return os<<"}"; } template<class L, class R> ostream& operator<<(ostream &os, unordered_map<L,R> M) { os << "{ "; for(auto m:M) os<<"("<<m.F<<":"<<m.S<<") "; return os<<"}"; } const ll N = 200010, M = 1e9 + 7; ll n, k, a[N], b[N]; void solve(){ cin >> n >> k; fi (0, n - 1) cin >> a[i]; ll m = *max_element(a, a + n); fi (0, n - 1) a[i] = m - a[i]; m = *max_element(a, a + n); fi (0, n - 1) b[i] = m - a[i]; if (k % 2 == 1) { fi (0, n - 1) cout << a[i] << ' '; cout << "\n"; } else { fi (0, n - 1) cout << b[i] << ' '; cout << "\n"; } } int main(){ // freopen("input.txt", "r", stdin); //Comment // freopen("output.txt", "w", stdout); //this out. ios::sync_with_stdio(false); //Not cin.tie(NULL); //this. cout.tie(0); //or this. ll T; cin >> T; while(T--) solve(); return 0; }
6e959aedd6f707d308bcaf4ae4e8072ce8dec27f
dbe4c0f546c497c4b74772cd9cc5a94f3a81996b
/Code/AMP/reactphysics3d/collision/broadphase/DynamicAABBTree.h
1317a020acc821bc65f1c86bca229bb60d499725
[]
no_license
lectorguard/AMP_Engine_Demo
43c8a83c3c0b4f915240ea86cd6532f09683b6fe
443ea45d1eb8768d87f5f806624b0d471de4840f
refs/heads/master
2021-01-04T04:51:08.793701
2020-02-14T02:03:18
2020-02-14T02:03:18
240,393,852
0
0
null
null
null
null
UTF-8
C++
false
false
10,502
h
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2019 Daniel Chappuis * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ #ifndef REACTPHYSICS3D_DYNAMIC_AABB_TREE_H #define REACTPHYSICS3D_DYNAMIC_AABB_TREE_H // Libraries #include "../../configuration.h" #include "../../collision/shapes/AABB.h" /// Namespace ReactPhysics3D namespace reactphysics3d { // Declarations class BroadPhaseAlgorithm; class BroadPhaseRaycastTestCallback; class DynamicAABBTreeOverlapCallback; class CollisionBody; struct RaycastTest; class AABB; class Profiler; class MemoryAllocator; // Structure TreeNode /** * This structure represents a node of the dynamic AABB tree. */ struct TreeNode { // -------------------- Constants -------------------- // /// Null tree node constant const static int NULL_TREE_NODE; // -------------------- Attributes -------------------- // // A node is either in the tree (has a parent) or in the free nodes list // (has a next node) union { /// Parent node ID int32 parentID; /// Next allocated node ID int32 nextNodeID; }; // A node is either a leaf (has data) or is an internal node (has children) union { /// Left and right child of the node (children[0] = left child) int32 children[2]; /// Two pieces of data stored at that node (in case the node is a leaf) union { int32 dataInt[2]; void* dataPointer; }; }; /// Height of the node in the tree int16 height; /// Fat axis aligned bounding box (AABB) corresponding to the node AABB aabb; // -------------------- Methods -------------------- // /// Return true if the node is a leaf of the tree bool isLeaf() const; }; // Class DynamicAABBTreeOverlapCallback /** * Overlapping callback method that has to be used as parameter of the * reportAllShapesOverlappingWithNode() method. */ class DynamicAABBTreeOverlapCallback { public : // Called when a overlapping node has been found during the call to // DynamicAABBTree:reportAllShapesOverlappingWithAABB() virtual void notifyOverlappingNode(int nodeId)=0; // Destructor virtual ~DynamicAABBTreeOverlapCallback() = default; }; // Class DynamicAABBTreeRaycastCallback /** * Raycast callback in the Dynamic AABB Tree called when the AABB of a leaf * node is hit by the ray. */ class DynamicAABBTreeRaycastCallback { public: // Called when the AABB of a leaf node is hit by a ray virtual decimal raycastBroadPhaseShape(int32 nodeId, const Ray& ray)=0; virtual ~DynamicAABBTreeRaycastCallback() = default; }; // Class DynamicAABBTree /** * This class implements a dynamic AABB tree that is used for broad-phase * collision detection. This data structure is inspired by Nathanael Presson's * dynamic tree implementation in BulletPhysics. The following implementation is * based on the one from Erin Catto in Box2D as described in the book * "Introduction to Game Physics with Box2D" by Ian Parberry. */ class DynamicAABBTree { private: // -------------------- Attributes -------------------- // /// Memory allocator MemoryAllocator& mAllocator; /// Pointer to the memory location of the nodes of the tree TreeNode* mNodes; /// ID of the root node of the tree int mRootNodeID; /// ID of the first node of the list of free (allocated) nodes in the tree that we can use int mFreeNodeID; /// Number of allocated nodes in the tree int mNbAllocatedNodes; /// Number of nodes in the tree int mNbNodes; /// Extra AABB Gap used to allow the collision shape to move a little bit /// without triggering a large modification of the tree which can be costly decimal mExtraAABBGap; #ifdef IS_PROFILING_ACTIVE /// Pointer to the profiler Profiler* mProfiler; #endif // -------------------- Methods -------------------- // /// Allocate and return a node to use in the tree int allocateNode(); /// Release a node void releaseNode(int nodeID); /// Insert a leaf node in the tree void insertLeafNode(int nodeID); /// Remove a leaf node from the tree void removeLeafNode(int nodeID); /// Balance the sub-tree of a given node using left or right rotations. int balanceSubTreeAtNode(int nodeID); /// Compute the height of a given node in the tree int computeHeight(int nodeID); /// Internally add an object into the tree int addObjectInternal(const AABB& aabb); /// Initialize the tree void init(); #ifndef NDEBUG /// Check if the tree structure is valid (for debugging purpose) void check() const; /// Check if the node structure is valid (for debugging purpose) void checkNode(int nodeID) const; #endif public: // -------------------- Methods -------------------- // /// Constructor DynamicAABBTree(MemoryAllocator& allocator, decimal extraAABBGap = decimal(0.0)); /// Destructor ~DynamicAABBTree(); /// Add an object into the tree (where node data are two integers) int addObject(const AABB& aabb, int32 data1, int32 data2); /// Add an object into the tree (where node data is a pointer) int addObject(const AABB& aabb, void* data); /// Remove an object from the tree void removeObject(int nodeID); /// Update the dynamic tree after an object has moved. bool updateObject(int nodeID, const AABB& newAABB, const Vector3& displacement, bool forceReinsert = false); /// Return the fat AABB corresponding to a given node ID const AABB& getFatAABB(int nodeID) const; /// Return the pointer to the data array of a given leaf node of the tree int32* getNodeDataInt(int nodeID) const; /// Return the data pointer of a given leaf node of the tree void* getNodeDataPointer(int nodeID) const; /// Report all shapes overlapping with the AABB given in parameter. void reportAllShapesOverlappingWithAABB(const AABB& aabb, DynamicAABBTreeOverlapCallback& callback) const; /// Ray casting method void raycast(const Ray& ray, DynamicAABBTreeRaycastCallback& callback) const; /// Compute the height of the tree int computeHeight(); /// Return the root AABB of the tree AABB getRootAABB() const; /// Clear all the nodes and reset the tree void reset(); #ifdef IS_PROFILING_ACTIVE /// Set the profiler void setProfiler(Profiler* profiler); #endif }; // Return true if the node is a leaf of the tree inline bool TreeNode::isLeaf() const { return (height == 0); } // Return the fat AABB corresponding to a given node ID inline const AABB& DynamicAABBTree::getFatAABB(int nodeID) const { assert(nodeID >= 0 && nodeID < mNbAllocatedNodes); return mNodes[nodeID].aabb; } // Return the pointer to the data array of a given leaf node of the tree inline int32* DynamicAABBTree::getNodeDataInt(int nodeID) const { assert(nodeID >= 0 && nodeID < mNbAllocatedNodes); assert(mNodes[nodeID].isLeaf()); return mNodes[nodeID].dataInt; } // Return the pointer to the data pointer of a given leaf node of the tree inline void* DynamicAABBTree::getNodeDataPointer(int nodeID) const { assert(nodeID >= 0 && nodeID < mNbAllocatedNodes); assert(mNodes[nodeID].isLeaf()); return mNodes[nodeID].dataPointer; } // Return the root AABB of the tree inline AABB DynamicAABBTree::getRootAABB() const { return getFatAABB(mRootNodeID); } // Add an object into the tree. This method creates a new leaf node in the tree and // returns the ID of the corresponding node. inline int DynamicAABBTree::addObject(const AABB& aabb, int32 data1, int32 data2) { int nodeId = addObjectInternal(aabb); mNodes[nodeId].dataInt[0] = data1; mNodes[nodeId].dataInt[1] = data2; return nodeId; } // Add an object into the tree. This method creates a new leaf node in the tree and // returns the ID of the corresponding node. inline int DynamicAABBTree::addObject(const AABB& aabb, void* data) { int nodeId = addObjectInternal(aabb); mNodes[nodeId].dataPointer = data; return nodeId; } #ifdef IS_PROFILING_ACTIVE // Set the profiler inline void DynamicAABBTree::setProfiler(Profiler* profiler) { mProfiler = profiler; } #endif } #endif
7b301b74a20470131b91a36595416627c33ced9e
59a7c0628b730b8503346e8cbfbbc21e9aea26f5
/LAB10/PC_01/test.cpp
d27281c86f20e06ff36a44f26c7873b1f2522210
[]
no_license
GeorgeZhuo/homework
7c31fbf86468464ce9fa58582aee5e3fbecae780
a917ed98930fcebc88db47c4ab7122b8528b8cf9
refs/heads/master
2016-09-02T01:13:57.906727
2014-03-12T14:37:13
2014-03-12T14:37:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
// LAB_10 PC_01 // ZHUOZHAOJIN 12330443 #include <iostream> using namespace std; int main () { int value1 = 12345; float value2 = 1.2345; for ( int i = 0; i <= 10; i++ ) { cout.width( i ); cout << right << value1 << endl; } for ( int i = 0; i <= 10; i++ ) { cout.width( i ); cout << right << value2 << endl; } return 0; }
2342897d65dab46a926ce51eda1da46e67d15b5e
f7dd60801cd52f370dd18fbc95aa0b800a16ea8a
/main.cpp
8d0ab3cc358289eb880bfea8be9c602544930671
[]
no_license
haydenmc/TelnetBlackjack
7855f30fb95fc083024c4a203fd8f75d736dbd30
bfedcb1cc50b5dff2bd0891fab826e20c2dc20a5
refs/heads/master
2020-09-16T18:15:51.015741
2019-12-03T05:35:15
2019-12-03T05:35:15
223,850,045
0
0
null
null
null
null
UTF-8
C++
false
false
835
cpp
#include <iostream> #include <thread> #include <memory> #include <climits> #include "Card.h" #include "Deck.h" #include "TelnetServer.h" #include "WinsockTelnetServer.h" const short DEFAULT_PORT = 23; int main(int argc, char* argv[]) { short port = DEFAULT_PORT; if (argc > 1) { int portArg = std::stoi(argv[1]); if (portArg < 1 || portArg > SHRT_MAX) { std::cerr << "Must provide a valid port number between 1 and " << SHRT_MAX << std::endl; throw std::invalid_argument("Invalid port number"); } port = static_cast<short>(portArg); } std::cout << "Starting server on port " << port << "..." << std::endl; auto server = std::make_shared<WinsockTelnetServer>(port); std::thread(&WinsockTelnetServer::Start, server).join(); return 0; }
8c55bc6cc1c3f600d84a9b54a555d5f42b11a513
4462c1bc573e102180eee554c155d54fd6b4022d
/lite/operators/lookup_table_dequant_op.h
3a9683d5ca0d87365cb240b91dccab07cf26ca71
[ "Apache-2.0" ]
permissive
ysh329/Paddle-Lite-1
65f95ee1e18871d5c0c8fb8da12aab7d8e9adb61
2f280f536dcf5f4f9e6e841d767082cd929c944e
refs/heads/develop
2021-06-22T20:43:17.437053
2020-03-14T02:10:01
2020-03-14T02:10:01
205,050,556
1
0
Apache-2.0
2019-10-13T12:40:09
2019-08-29T00:54:40
C++
UTF-8
C++
false
false
1,435
h
// Copyright (c) 2020 PaddlePaddle 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. #pragma once #include <string> #include <vector> #include "lite/core/op_lite.h" #include "lite/core/scope.h" #include "lite/utils/all.h" namespace paddle { namespace lite { namespace operators { class LookupTableDequantOpLite : public OpLite { public: LookupTableDequantOpLite() {} explicit LookupTableDequantOpLite(const std::string &op_type) : OpLite(op_type) {} bool CheckShape() const override; bool InferShape() const override; bool AttachImpl(const cpp::OpDesc &opdesc, lite::Scope *scope) override; void AttachKernel(KernelBase *kernel) override { kernel->SetParam(param_); } std::string DebugString() const override { return "LookupTableDequant"; } private: mutable LookupTableDequantParam param_; }; } // namespace operators } // namespace lite } // namespace paddle
bcba32de1197ba2dee996d7be76e5e4bf615b477
4045e2a8274c067f7b99fbe5a690cd7f7042aba1
/gctp/include/gctp/scene/worldrenderer.hpp
81d5fdf90da0a28f63a61150c21dc864742f684c
[ "BSD-3-Clause" ]
permissive
Emulyator/gamecatapult
78b48efdae3e13e20eb3176c104e7432161362e0
d937e2a94d7156f040d34609e554991dc3a1cc47
refs/heads/master
2016-09-05T19:32:35.028735
2014-03-22T22:44:47
2014-03-22T22:44:47
41,599,252
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
6,586
hpp
#ifndef _GCTP_SCENE_WORLDRENDERER_HPP_ #define _GCTP_SCENE_WORLDRENDERER_HPP_ #ifdef GCTP_ONCE #pragma once #endif // GCTP_ONCE /** @file * GameCatapult 簡易効果ノードクラスヘッダファイル * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/08 11:18:38 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ #include <gctp/class.hpp> #include <gctp/tuki.hpp> #include <gctp/handlelist.hpp> #include <gctp/graphic.hpp> #include <gctp/scene/renderer.hpp> #include <gctp/scene/drawpacket.hpp> #include <gctp/matrix.hpp> namespace gctp { namespace graphic { namespace dx { class StateBlockRsrc; } } } namespace gctp { namespace scene { class World; class Camera; class Flesh; /** ソート済み描画パケットを保持するノードクラス * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/16 1:05:32 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ class WorldSorter : public Renderer { public: WorldSorter(); virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; /// 描画対象設定 void attach(Handle<World> target) { target_ = target; } /// ワールド取得 Handle<World> target() const { return target_; } mutable DrawPacketVector packets; protected: mutable Handle<World> target_; bool LuaCtor(luapp::Stack &L); void attach(luapp::Stack &L); GCTP_DECLARE_CLASS; TUKI_DECLARE(WorldSorter); }; /** 簡易ワールド描画ノードクラス * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/16 1:05:32 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ class WorldRenderer : public WorldSorter { public: WorldRenderer(); virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; private: Pointer<graphic::dx::StateBlockRsrc> sb_; GCTP_DECLARE_CLASS; TUKI_DECLARE(WorldRenderer); }; /** 簡易鏡像ワールド描画ノードクラス * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/16 1:05:32 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ class MirrorWorldRenderer : public WorldSorter { public: MirrorWorldRenderer(); virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; private: Pointer<graphic::dx::StateBlockRsrc> sb_; mutable Matrix vmat_bak_; GCTP_DECLARE_CLASS; TUKI_DECLARE(MirrorWorldRenderer); }; /** 不透明体描画効果ノードクラス * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/16 1:05:32 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ class OpequeWorldRenderer : public Renderer { public: OpequeWorldRenderer(); virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; void attach(Handle<WorldSorter> target) { target_ = target; } protected: Handle<WorldSorter> target_; bool LuaCtor(luapp::Stack &L); void attach(luapp::Stack &L); private: Pointer<graphic::dx::StateBlockRsrc> sb_; GCTP_DECLARE_CLASS; TUKI_DECLARE(OpequeWorldRenderer); }; /** 半透明体描画ノードクラス * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/16 1:05:32 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ class TranslucentWorldRenderer : public Renderer { public: TranslucentWorldRenderer(); virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; void attach(Handle<WorldSorter> target) { target_ = target; } protected: Handle<WorldSorter> target_; bool LuaCtor(luapp::Stack &L); void attach(luapp::Stack &L); private: Pointer<graphic::dx::StateBlockRsrc> sb_; GCTP_DECLARE_CLASS; TUKI_DECLARE(TranslucentWorldRenderer); }; /** Zフィル用 * * ソートしないでとにかく書く */ class ZFillRenderer : public Renderer { public: ZFillRenderer(); virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; /// 描画対象追加 void add(Handle<World> world); /// 描画対象削除 void remove(Handle<World> world); protected: HandleList<World> worlds_; mutable const char *backup_tech_; bool LuaCtor(luapp::Stack &L); void add(luapp::Stack &L); void remove(luapp::Stack &L); private: Pointer<graphic::dx::StateBlockRsrc> sb_; GCTP_DECLARE_CLASS; TUKI_DECLARE(ZFillRenderer); }; /** レンダリングノードのフラスタムカリング用 * */ class IsVisibleOperator : public Renderer { public: virtual bool onReach(float delta) const; /// 対象のカメラを指定 void set(Handle<Camera> camera); /// チェック対象追加 void add(Handle<Flesh> flesh); /// チェック対象削除 void remove(Handle<Flesh> flesh); protected: Handle<Camera> camera_; HandleList<Flesh> fleshies_; bool LuaCtor(luapp::Stack &L); void set(luapp::Stack &L); void add(luapp::Stack &L); void remove(luapp::Stack &L); GCTP_DECLARE_CLASS; TUKI_DECLARE(IsVisibleOperator); }; /** 遠景ワールド描画ノードクラス * * @author SAM (T&GG, Org.)<[email protected]> * @date 2004/02/16 1:05:32 * Copyright (C) 2001,2002,2003,2004 SAM (T&GG, Org.). All rights reserved. */ class DistantViewRenderer : public Renderer { public: DistantViewRenderer(); /// 描画対象設定 void attach(Handle<World> target) { target_ = target; } /// ワールド取得 Handle<World> target() const { return target_; } virtual bool onReach(float delta) const; virtual bool onLeave(float delta) const; float nearclip_; float farclip_; private: Pointer<graphic::dx::StateBlockRsrc> sb_; Handle<World> target_; mutable Matrix vmat_bak_; mutable Matrix pmat_bak_; mutable graphic::ViewPort view_port_bak_; bool LuaCtor(luapp::Stack &L); void attach(luapp::Stack &L); void setClip(luapp::Stack &L); GCTP_DECLARE_CLASS; TUKI_DECLARE(DistantViewRenderer); }; }} // namespace gctp::scene #endif // _GCTP_SCENE_WORLDRENDERER_HPP_
[ "osamu.takasugi@fdeeef8c-811c-0410-9bc5-e1f93fa3fba2" ]
osamu.takasugi@fdeeef8c-811c-0410-9bc5-e1f93fa3fba2
277fb1011c57bd2701106b77f00a90749d06a6b0
bf91c382483c735a64b685c7fded2a8436a84ac7
/src/history/HistoryArchiveManager.cpp
0e47cc46cb9b23f9b6fc64996f3fd4dd0c7dd7e8
[ "MIT", "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
tangchain/tang-core
e85f5065217f9a289693c6c28d00bb80f5367b35
b112fc43f7df6153406810fc0ffb6676418d20c8
refs/heads/master
2020-04-14T19:25:02.133375
2019-01-04T04:21:38
2019-01-04T04:21:38
163,907,824
0
0
null
null
null
null
UTF-8
C++
false
false
7,582
cpp
// Copyright 2018 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "history/HistoryArchiveManager.h" #include "history/HistoryArchive.h" #include "historywork/GetHistoryArchiveStateWork.h" #include "historywork/PutHistoryArchiveStateWork.h" #include "main/Application.h" #include "main/Config.h" #include "util/Logging.h" #include "util/Math.h" #include "work/WorkManager.h" #include <lib/json/json.h> #include <vector> namespace tang { HistoryArchiveManager::HistoryArchiveManager(Application& app) : mApp{app} { for (auto const& archiveConfiguration : mApp.getConfig().HISTORY) mArchives.push_back( std::make_shared<HistoryArchive>(archiveConfiguration.second)); } bool HistoryArchiveManager::checkSensibleConfig() const { // Check reasonable-ness of history archive definitions std::vector<std::string> readOnlyArchives; std::vector<std::string> readWriteArchives; std::vector<std::string> writeOnlyArchives; std::vector<std::string> inertArchives; for (auto const& archive : mArchives) { if (archive->hasGetCmd()) { if (archive->hasPutCmd()) { readWriteArchives.push_back(archive->getName()); } else { readOnlyArchives.push_back(archive->getName()); } } else { if (archive->hasPutCmd()) { writeOnlyArchives.push_back(archive->getName()); } else { inertArchives.push_back(archive->getName()); } } } bool badArchives = false; for (auto const& a : inertArchives) { CLOG(FATAL, "History") << "Archive '" << a << "' has no 'get' or 'put' command, will not function"; badArchives = true; } for (auto const& a : writeOnlyArchives) { CLOG(FATAL, "History") << "Archive '" << a << "' has 'put' but no 'get' command, will be unwritable"; badArchives = true; } for (auto const& a : readWriteArchives) { CLOG(INFO, "History") << "Archive '" << a << "' has 'put' and 'get' commands, will be read and written"; } for (auto const& a : readOnlyArchives) { CLOG(INFO, "History") << "Archive '" << a << "' has 'get' command only, will not be written"; } if (readOnlyArchives.empty() && readWriteArchives.empty()) { CLOG(FATAL, "History") << "No readable archives configured, catchup will fail."; badArchives = true; } if (readWriteArchives.empty()) { CLOG(WARNING, "History") << "No writable archives configured, history will not be written."; } if (badArchives) { CLOG(ERROR, "History") << "History archives misconfigured."; return false; } return true; } std::shared_ptr<HistoryArchive> HistoryArchiveManager::selectRandomReadableHistoryArchive() const { std::vector<std::shared_ptr<HistoryArchive>> archives; // First try for archives that _only_ have a get command; they're // archives we're explicitly not publishing to, so likely ones we want. std::copy_if(std::begin(mArchives), std::end(mArchives), std::back_inserter(archives), [](std::shared_ptr<HistoryArchive> const& x) { return x->hasGetCmd() && !x->hasPutCmd(); }); // If we have none of those, accept those with get+put if (archives.size() == 0) { std::copy_if(std::begin(mArchives), std::end(mArchives), std::back_inserter(archives), [](std::shared_ptr<HistoryArchive> const& x) { return x->hasGetCmd(); }); } if (archives.size() == 0) { throw std::runtime_error("No GET-enabled history archive in config"); } else if (archives.size() == 1) { CLOG(DEBUG, "History") << "Fetching from sole readable history archive '" << archives[0]->getName() << "'"; return archives[0]; } else { std::uniform_int_distribution<size_t> dist(0, archives.size() - 1); size_t i = dist(gRandomEngine); CLOG(DEBUG, "History") << "Fetching from readable history archive #" << i << ", '" << archives[i]->getName() << "'"; return archives[i]; } } bool HistoryArchiveManager::initializeHistoryArchive(std::string const& arch) const { auto archive = getHistoryArchive(arch); if (!archive) { CLOG(FATAL, "History") << "Can't initialize unknown history archive '" << arch << "'"; return false; } auto& wm = mApp.getWorkManager(); // First check that there's no existing HAS in the archive HistoryArchiveState existing; CLOG(INFO, "History") << "Probing history archive '" << arch << "' for existing state"; auto getHas = wm.executeWork<GetHistoryArchiveStateWork>( "get-history-archive-state", existing, 0, archive, 0); if (getHas->getState() == Work::WORK_SUCCESS) { CLOG(ERROR, "History") << "History archive '" << arch << "' already initialized!"; return false; } CLOG(INFO, "History") << "History archive '" << arch << "' appears uninitialized"; HistoryArchiveState has; CLOG(INFO, "History") << "Initializing history archive '" << arch << "'"; has.resolveAllFutures(); auto putHas = wm.executeWork<PutHistoryArchiveStateWork>(has, archive); if (putHas->getState() == Work::WORK_SUCCESS) { CLOG(INFO, "History") << "Initialized history archive '" << arch << "'"; return true; } else { CLOG(FATAL, "History") << "Failed to initialize history archive '" << arch << "'"; return false; } } bool HistoryArchiveManager::hasAnyWritableHistoryArchive() const { return std::any_of(std::begin(mArchives), std::end(mArchives), [](std::shared_ptr<HistoryArchive> const& x) { return x->hasGetCmd() && x->hasPutCmd(); }); } std::shared_ptr<HistoryArchive> HistoryArchiveManager::getHistoryArchive(std::string const& name) const { auto it = std::find_if(std::begin(mArchives), std::end(mArchives), [&name](std::shared_ptr<HistoryArchive> const& x) { return x->getName() == name; }); return it == std::end(mArchives) ? nullptr : *it; } std::vector<std::shared_ptr<HistoryArchive>> HistoryArchiveManager::getWritableHistoryArchives() const { auto result = std::vector<std::shared_ptr<HistoryArchive>>{}; std::copy_if(std::begin(mArchives), std::end(mArchives), std::back_inserter(result), [](std::shared_ptr<HistoryArchive> const& x) { return x->hasGetCmd() && x->hasPutCmd(); }); return result; } Json::Value HistoryArchiveManager::getJsonInfo() const { auto info = Json::Value{}; for (auto archive : mArchives) { info[archive->getName()] = archive->getJsonInfo(); } return info; } }
d433ce55f977d1e4b90dca4d2f9db499bfbf61a2
7a9916351bce69d773521ddf1a15a63fd31c0834
/fixedsrc/a43/strings/strings.h
f7fa7f5702b2c2241225023ad0a5b8f75fe2c698
[]
no_license
franksnightmare/c-1week5
e367c64842c4738d451d2c05473afaacc05f242e
0fb5eeb7a5ba3efe2f41fa4f7830d96f70e7617b
refs/heads/master
2021-01-10T23:28:06.910538
2016-10-19T13:09:30
2016-10-19T13:09:30
70,584,094
0
0
null
null
null
null
UTF-8
C++
false
false
544
h
#ifndef STRINGS_H #define STRINGS_H #include <cstddef> #include <string> class Strings { std::string **d_str = new std::string*[1]; size_t d_size = 0; size_t d_capacity = 1; public: Strings(size_t argc, char **argv); Strings(char **environ); ~Strings(); size_t size(); size_t capacity(); void resize(size_t size); void reserve(size_t size); void addString(char *charArray); std::string at(size_t index); std::string const at(size_t index) const; std::string **rawPointers(size_t amount); }; #endif
35e13f22d87637975c10c0377fe5b4bcaee47e25
ec67b8a0169ec24556d133dfe4f449ecd7e1c752
/timer/PostProcessing/GaussianBlur.hpp
24f7d7b42de8013417aa7bae8b919b7d594a6ae9
[ "MIT" ]
permissive
MaticVrtacnik/ProceduralnaAnimacija
a593bbc9de8da39b5bd100a2841a171bd3c2211e
bc47ccc721d1bedb31ed5949eb740892f094897a
refs/heads/master
2020-04-16T11:20:04.497556
2019-02-15T03:08:36
2019-02-15T03:08:36
165,531,866
0
0
null
null
null
null
UTF-8
C++
false
false
1,966
hpp
/* MIT License Copyright (c) 2019 MaticVrtacnik 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. */ #ifndef GAUSSIAN_BLUR_HPP #define GAUSSIAN_BLUR_HPP #include "PostProcessingBase.hpp" #include "../Texture/Texture.hpp" namespace Engine{ namespace Graphics{ namespace PostProcessing{ class GaussianBlur : public PostProcessingBase{ private: static const unsigned int MAX_MIPMAP_LEVEL = 7; private: GLint m_format = GL_RGB16F; GLint m_internalFormat = GL_RGB; public: std::vector<unsigned int> m_blurPingTextures; std::vector<unsigned int> m_blurPongTextures; public: GaussianBlur(std::shared_ptr<Shaders::Shader> shader, unsigned int width, unsigned int height, GLint format = GL_RGB16F, GLint internalFormat = GL_RGB); ~GaussianBlur(); unsigned int useEffect(unsigned int inputTexture, unsigned int numPasses, unsigned int mipmapLevel = 0, bool changeInput = false); }; } } } #endif //GAUSSIAN_BLUR_HPP
00abc75bbf1d13e9967ed904a60942fbe22627af
f05155d1c9c41fcc6e31686505f856fd2fbc06de
/2019/octobor 2019/stl bangla 16 part 2.cpp
5fa1acdf72df89cea47c72a17a7befd2312ebbc6
[]
no_license
T-tasir/Competetive-Programming
22308db58c827a8dfa9d2f879f7a1c135f3ab96a
b56ab712fd2147a69b90b7300e281b9b6ed85852
refs/heads/main
2023-08-18T07:35:22.656508
2021-10-14T13:20:33
2021-10-14T13:20:33
368,572,215
0
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
#include<bits/stdc++.h> #include<stdio.h> #include<iostream> #include<stack> using namespace std; int main() { stack<string>s; s.push("dipto"); s.push("nabil"); s.push("arnob"); while(!s.empty()){ string x; x=s.top(); cout<<x<<endl; s.pop(); } }
421a64755ac926235d99e8b8ed354016be132ba1
09758b2c38602027ee15c32aafe834bdd010f2ca
/projectEuler/q6.cpp
20e755ae8eed1d534cb917a0dcbc71239c167eff
[]
no_license
manjot96/Cpp
c33d2385187aabefb3755295bdfcf6a3fa6ba9dd
a82ad90e705f8c6229c3e71cb89e50690a504b3d
refs/heads/master
2021-01-10T07:50:09.190154
2016-03-14T21:06:53
2016-03-14T21:06:53
53,767,975
0
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
#include <iostream> #include <cmath> using namespace std; int main() { //sum of squares: (starting from 11); int sumSquares = 0, sum = 0; for(int i = 1; i <= 100; ++i) { sumSquares += pow(i, 2); sum += i; } int squareSum = pow(sum, 2); cout << (squareSum - sumSquares) << endl; }
ac2062c4a01062b1daf93ed16d0f9cbf2fa56334
d92af119d13b9af9afa3f6effa057c1f07cdb7c6
/Project/Libs/TrinityEngine/VideoPlayerControl.h
411cd4d97ec48b7b3a044206c8db9bf42c57896c
[ "MIT" ]
permissive
fromasmtodisasm/Vivid3D
b0e89cd6ea859f579f9fae2b4cabcbebff3bacbc
66b429cae3290e1953552263e02b43a8c96f7bcb
refs/heads/main
2023-03-21T09:50:15.571173
2021-03-17T13:06:47
2021-03-17T13:06:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
929
h
#pragma once #include "UIControl.h" #include <queue> #include "Texture2D.h" #include <mutex> #include <thread> class VideoFrame { public: Texture2D* tex; long PTS, PKPTS, DTS; int W, H; void* Data; long clock; double DPTS; double DDelay; long pict; int CacheID; }; class VideoPlayerControl : public UIControl { public: VideoPlayerControl(); void SetVideo(const char* path); void Play(); void Stop(); void Render(); void StopAudio(); // void Stop(); void Pause(); void DecodeFrame(); Texture2D* GetCurrentImage(); VideoFrame* GetCurrentFrame(); bool gotAudioTime = false; double timeDelta = 0.0; bool Paused = false; long audioStartTime = 0; double CLOCK = 0.0; double AUDIOCLOCK = 0.0; std::queue<VideoFrame*> Frames; VideoFrame* CurrentFrame = NULL; int Width, Height; Texture2D* CurrentTex; VideoFrame* UpFrame = NULL; long LastTick = 0; double timeDelay = 0.0; std::mutex frameG; };
c03c82754566dbce430199a79fcbd50f19944904
67f988dedfd8ae049d982d1a8213bb83233d90de
/external/chromium/content/browser/renderer_host/backing_store_win.cc
c9ce07a86bb51564fb08af9a96ac05132395fe6e
[ "BSD-3-Clause" ]
permissive
opensourceyouthprogramming/h5vcc
94a668a9384cc3096a365396b5e4d1d3e02aacc4
d55d074539ba4555e69e9b9a41e5deb9b9d26c5b
refs/heads/master
2020-04-20T04:57:47.419922
2019-02-12T00:56:14
2019-02-12T00:56:14
168,643,719
1
1
null
2019-02-12T00:49:49
2019-02-01T04:47:32
C++
UTF-8
C++
false
false
6,578
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/backing_store_win.h" #include "base/command_line.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/public/common/content_switches.h" #include "skia/ext/platform_canvas.h" #include "ui/gfx/gdi_util.h" #include "ui/gfx/rect_conversions.h" #include "ui/surface/transport_dib.h" namespace content { namespace { // Creates a dib conforming to the height/width/section parameters passed in. HANDLE CreateDIB(HDC dc, int width, int height, int color_depth) { BITMAPV5HEADER hdr = {0}; ZeroMemory(&hdr, sizeof(BITMAPV5HEADER)); // These values are shared with gfx::PlatformDevice hdr.bV5Size = sizeof(BITMAPINFOHEADER); hdr.bV5Width = width; hdr.bV5Height = -height; // minus means top-down bitmap hdr.bV5Planes = 1; hdr.bV5BitCount = color_depth; hdr.bV5Compression = BI_RGB; // no compression hdr.bV5SizeImage = 0; hdr.bV5XPelsPerMeter = 1; hdr.bV5YPelsPerMeter = 1; hdr.bV5ClrUsed = 0; hdr.bV5ClrImportant = 0; if (BackingStoreWin::ColorManagementEnabled()) { hdr.bV5CSType = LCS_sRGB; hdr.bV5Intent = LCS_GM_IMAGES; } void* data = NULL; HANDLE dib = CreateDIBSection(dc, reinterpret_cast<BITMAPINFO*>(&hdr), 0, &data, NULL, 0); DCHECK(data); return dib; } void CallStretchDIBits(HDC hdc, int dest_x, int dest_y, int dest_w, int dest_h, int src_x, int src_y, int src_w, int src_h, void* pixels, const BITMAPINFO* bitmap_info) { // When blitting a rectangle that touches the bottom, left corner of the // bitmap, StretchDIBits looks at it top-down! For more details, see // http://wiki.allegro.cc/index.php?title=StretchDIBits. int rv; int bitmap_h = -bitmap_info->bmiHeader.biHeight; int bottom_up_src_y = bitmap_h - src_y - src_h; if (bottom_up_src_y == 0 && src_x == 0 && src_h != bitmap_h) { rv = StretchDIBits(hdc, dest_x, dest_h + dest_y - 1, dest_w, -dest_h, src_x, bitmap_h - src_y + 1, src_w, -src_h, pixels, bitmap_info, DIB_RGB_COLORS, SRCCOPY); } else { rv = StretchDIBits(hdc, dest_x, dest_y, dest_w, dest_h, src_x, bottom_up_src_y, src_w, src_h, pixels, bitmap_info, DIB_RGB_COLORS, SRCCOPY); } DCHECK(rv != GDI_ERROR); } } // namespace BackingStoreWin::BackingStoreWin(RenderWidgetHost* widget, const gfx::Size& size) : BackingStore(widget, size), backing_store_dib_(NULL), original_bitmap_(NULL) { HDC screen_dc = ::GetDC(NULL); color_depth_ = ::GetDeviceCaps(screen_dc, BITSPIXEL); // Color depths less than 16 bpp require a palette to be specified. Instead, // we specify the desired color depth as 16 which lets the OS to come up // with an approximation. if (color_depth_ < 16) color_depth_ = 16; hdc_ = CreateCompatibleDC(screen_dc); ReleaseDC(NULL, screen_dc); } BackingStoreWin::~BackingStoreWin() { DCHECK(hdc_); if (original_bitmap_) { SelectObject(hdc_, original_bitmap_); } if (backing_store_dib_) { DeleteObject(backing_store_dib_); backing_store_dib_ = NULL; } DeleteDC(hdc_); } // static bool BackingStoreWin::ColorManagementEnabled() { static bool enabled = false; static bool checked = false; if (!checked) { checked = true; const CommandLine& command = *CommandLine::ForCurrentProcess(); enabled = command.HasSwitch(switches::kEnableMonitorProfile); } return enabled; } size_t BackingStoreWin::MemorySize() { return size().GetArea() * (color_depth_ / 8); } void BackingStoreWin::PaintToBackingStore( RenderProcessHost* process, TransportDIB::Id bitmap, const gfx::Rect& bitmap_rect, const std::vector<gfx::Rect>& copy_rects, float scale_factor, const base::Closure& completion_callback, bool* scheduled_completion_callback) { *scheduled_completion_callback = false; if (!backing_store_dib_) { backing_store_dib_ = CreateDIB(hdc_, size().width(), size().height(), color_depth_); if (!backing_store_dib_) { NOTREACHED(); return; } original_bitmap_ = SelectObject(hdc_, backing_store_dib_); } TransportDIB* dib = process->GetTransportDIB(bitmap); if (!dib) return; gfx::Rect pixel_bitmap_rect = gfx::ToEnclosedRect( gfx::ScaleRect(bitmap_rect, scale_factor)); BITMAPINFOHEADER hdr; gfx::CreateBitmapHeader(pixel_bitmap_rect.width(), pixel_bitmap_rect.height(), &hdr); // Account for a bitmap_rect that exceeds the bounds of our view gfx::Rect view_rect(size()); for (size_t i = 0; i < copy_rects.size(); i++) { gfx::Rect paint_rect = gfx::IntersectRects(view_rect, copy_rects[i]); gfx::Rect pixel_copy_rect = gfx::ToEnclosedRect( gfx::ScaleRect(paint_rect, scale_factor)); CallStretchDIBits(hdc_, paint_rect.x(), paint_rect.y(), paint_rect.width(), paint_rect.height(), pixel_copy_rect.x() - pixel_bitmap_rect.x(), pixel_copy_rect.y() - pixel_bitmap_rect.y(), pixel_copy_rect.width(), pixel_copy_rect.height(), dib->memory(), reinterpret_cast<BITMAPINFO*>(&hdr)); } } bool BackingStoreWin::CopyFromBackingStore(const gfx::Rect& rect, skia::PlatformBitmap* output) { if (!output->Allocate(rect.width(), rect.height(), true)) return false; HDC temp_dc = output->GetSurface(); BitBlt(temp_dc, 0, 0, rect.width(), rect.height(), hdc(), rect.x(), rect.y(), SRCCOPY); return true; } void BackingStoreWin::ScrollBackingStore(const gfx::Vector2d& delta, const gfx::Rect& clip_rect, const gfx::Size& view_size) { // TODO(darin): this doesn't work if delta x() and y() are both non-zero! DCHECK(delta.x() == 0 || delta.y() == 0); RECT damaged_rect, r = clip_rect.ToRECT(); ScrollDC(hdc_, delta.x(), delta.y(), NULL, &r, NULL, &damaged_rect); } } // namespace content