blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
d21f85164345da209526ec1d9a4779f9da26394c
224eb10a967bdf308f836fa0cdd8977af4b4e80a
/ripemd.h
8321086f2579bf1b1dacd965ea391b1f13392962
[]
no_license
ollolo4/xxx
bddaec394c1e37ba55e420081b2a406e9d1cd391
5d030abc3c355423ee9c9d129a6b501dca0ece39
refs/heads/master
2021-01-01T18:07:49.171720
2013-06-13T16:59:42
2013-06-13T16:59:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
225
h
ripemd.h
#ifndef RIPEMD_H #define RIPEMD_H #include <QFile> #include <iostream> #include <QByteArray> #include <QtEndian> #define SIZE_OF_BLOCK 64 using namespace std; QString ripemd(char *str); #endif // RIPEMD_H
91e9ae4520d850a1ed933428da82426fc763d672
fef54c29030db6575348c2865b5ade21cb536d40
/module_03/ex02/ScavTrap.cpp
094ae47e357f9df0d5c0e97e1c3beeae65326f51
[]
no_license
lionariman/cpp_modules
6c9ace87659ae6f349af26241c1df6ef2d2455f9
efc203b95c1041841f14b54a6773b65ffabd873c
refs/heads/main
2023-06-04T20:04:14.578822
2021-06-28T17:52:38
2021-06-28T17:52:38
369,099,464
0
1
null
null
null
null
UTF-8
C++
false
false
2,456
cpp
ScavTrap.cpp
#include "ScavTrap.hpp" ScavTrap::ScavTrap(std::string name) : ClapTrap(name) { this->name = name; const int length(3); std::string msgs[length] = { " was just born", " escaped from the factory", " has been updated" }; int index = std::rand() % length; std::cout << BLUE << this->name << msgs[index] << BLUE << std::endl; this->setDefaultValues(); } ScavTrap::ScavTrap(const ScavTrap &scavTrapInstance) { this->name = scavTrapInstance.name; this->hitPoints = scavTrapInstance.hitPoints; this->maxHitPoints = scavTrapInstance.maxHitPoints; this->energyPoints = scavTrapInstance.energyPoints; this->maxEnergyPoints = scavTrapInstance.maxEnergyPoints; this->level = scavTrapInstance.level; this->meleeAttackDamage = scavTrapInstance.meleeAttackDamage; this->rangedAttackDamage = scavTrapInstance.rangedAttackDamage; this->armorDamageReduction = scavTrapInstance.armorDamageReduction; const int length(3); std::string msgs[length] = { " was just born", " escaped from the factory", " has been updated" }; int index = std::rand() % length; std::cout << BLUE << this->name << msgs[index] << BLUE << std::endl; } ScavTrap::~ScavTrap() { const int length(3); std::string msgs[length] = { " was destroyed by laser", " lost his mind", " was riddled with bullets" }; int index = std::rand() % length; std::cout << RED << this->name << msgs[index] << RED << std::endl; } ScavTrap &ScavTrap::operator=(const ScavTrap &scavTrapInstance) { this->name = scavTrapInstance.name; this->hitPoints = scavTrapInstance.hitPoints; this->maxHitPoints = scavTrapInstance.maxHitPoints; this->energyPoints = scavTrapInstance.energyPoints; this->maxEnergyPoints = scavTrapInstance.maxEnergyPoints; this->level = scavTrapInstance.level; this->meleeAttackDamage = scavTrapInstance.meleeAttackDamage; this->rangedAttackDamage = scavTrapInstance.rangedAttackDamage; this->armorDamageReduction = scavTrapInstance.armorDamageReduction; return *this; } void ScavTrap::challengeNewscomer() { const int eventNum(10); std::string typeOfEvents[eventNum] = { "We got a badass here!", "Badass on the way!", "Badass incoming!", "Heads up! Incoming badass!", "Look out! Badass!", "Target acquired! It's a badass!", "Badass! Lock 'n load!", "We've got a badass incoming!", "BADASS!", "Got a badass here!" }; int ev = std::rand() % eventNum; std::cout << PINK << this->name + ": " + typeOfEvents[ev] << PINK << std::endl; }
51127bc06d04c5339842d5372c688b5795e50c16
41f7e74b2cd679545068b049d23256e77ef864f7
/src/negative.cpp
2b84893d1f4f4c4d4f20a2b600ce102042b8841c
[]
no_license
karimalami7/MSSD
f842772a332df195a816f5a470fe53839afc79dd
70d2950f9937bac4dfcc3bdff82b97d44bd4e2ca
refs/heads/master
2021-07-13T07:20:29.393147
2020-06-12T14:59:27
2020-06-12T14:59:27
166,392,405
5
1
null
null
null
null
UTF-8
C++
false
false
34,440
cpp
negative.cpp
#include "negative.h" using namespace std; namespace NEG{ void triScore(TableTuple &donnees, Space d){ // Cette procédure trie les données suivant le score (somme des valeurs des attributs) DataType i, n=donnees.size(); Space j; vector<DataType> aux(n); TableTuple auxT=donnees; for (i=0;i<n;i++){ aux[i]=donnees[i][1]; for (j=2;j<=d;j++) aux[i]+=donnees[i][j]; } vector<DataType> index(donnees.size()); for (i = 0; i != (DataType)index.size(); ++i) index[i] = i; sortIndexes(aux, index); for (i=0;i<n;i++){ donnees[i]=auxT[index[i]]; } } int tuple_position (int tuple_id, vector<int> &blocks_startId){ //cout <<"tuple position"<<endl; int position=0; for (auto startId : blocks_startId){ // cout << startId<<endl; if (tuple_id < startId) return position-1; position++; } return position-1; } void visualisation_pairs(vector<USetDualSpace> listUSetDualSpace){ cout <<"*****visualisation_pairs*****"<<endl; for(int i=0; i<listUSetDualSpace.size(); i++){ cout <<"t"<<i<<": "; for (auto it_uset = listUSetDualSpace[i].begin(); it_uset!=listUSetDualSpace[i].end(); it_uset++){ cout <<it_uset->dom <<" "<<it_uset->equ <<" ; "; } cout <<endl; } } bool pet_pair(const DualSpace &sp1, const DualSpace &sp2 ){ //retourne TRUE si la paire sp1 contient plus de dimensions que sp2 //ça sert à trier les listes/vecteurs de paires par ordre décroissant de ce nombre //pour ensuite faciliter les tests d'inclusion auto n1=sp1.dom + sp1.equ; auto n2=sp2.dom + sp2.equ; return __builtin_popcount(n1) >__builtin_popcount(n2); } inline DualSpace domDualSubspace_1(const Point &t1, const Point &t2, const Space &d){ // retourne le sous espace dans lequel t1 domine t2//je pense que c'est t2 qui domine t1 // les sous espaces sont codés en un nombre décimal // exemples (codage) quand d=4, ABCD->15, AD->9, A->1, B->2, C->4, BC -> 5 Space j; Space poids1=0, poids2=0; DualSpace sortie; sortie.dom=0; sortie.equ=0; long pow=1; unsigned int dec=1; if (t1[0]==t2[0]) return sortie; for(j = 1; j <= d ; ++j){ if(t1[j] < t2[j]) {sortie.dom+=pow;++poids1;} else if(t1[j] == t2[j]) {sortie.equ+=pow;++poids2;} pow*=2; //pow = (pow << 1); } sortie.poids=(1<<(poids1+poids2))-(1<<poids2); return sortie; } void insertDualSpaceToUSet(DualSpace sp, const Space &d, USetDualSpace &uSetDualSpace, Space &all, Space &maxDom, Space &sizeMaxDom, bool &sortie){ //retourne true si le tuple est completement dominé (ne plus le comparer à d'autres tuples) if (sp.dom==all){ USetDualSpace sp1; sp1.insert(sp); uSetDualSpace.swap(sp1); sortie=true; return; }else if (sp.dom!=0){ if (!estInclusDans(sp.dom+sp.equ, maxDom)){ if (spaceSize(sp.dom)>sizeMaxDom){ maxDom=sp.dom; sizeMaxDom=spaceSize(sp.dom); } uSetDualSpace.insert(sp); } } } long creationStructureNSC(NegSkyStrAux &structure, ListVectorListUSetDualSpace &list_Vc_lt_UsDs, Space d){ Space all=(1<<d)-1; long structSize=0; DataType idTuple=0; auto iterator_list=list_Vc_lt_UsDs.rbegin(); while (iterator_list!=list_Vc_lt_UsDs.rend()){ for (int i=0;i<iterator_list->size();++i){ // on boucle sur tous les tuples taille n auto it_us=(*iterator_list)[i].rbegin();//it_us++; for (;it_us!=(*iterator_list)[i].rend();++it_us){ for (auto it=(*it_us).begin();it!=(*it_us).end();++it){ // on boucle sur tous les paris (X|Y) de ce tuple Space spaceXY=it->dom+it->equ; Space spaceY=it->equ; auto it2=structure.find(spaceXY); if (it2==structure.end()){ unordered_map<Space,vector<DataType>> mapAux; vector<DataType> vectAux; vectAux.push_back(idTuple); mapAux.insert(pair<Space,vector<DataType>>(spaceY,vectAux)); structure.insert(pair<Space,unordered_map<Space,vector<DataType>>>(spaceXY,mapAux)); }else{ auto it3=(it2->second).find(spaceY); if (it3==(it2->second).end()){ vector<DataType> vectAux; vectAux.push_back(idTuple); (it2->second).insert(pair<Space,vector<DataType>>(spaceY,vectAux)); }else{ (it3->second).push_back(idTuple); } } structSize++; } } idTuple++; } iterator_list++; } return structSize; } // down , transform NegSkyStrAux to NegSkyStr, map -> vector long negativeSkycube(NegSkyStr &structure, ListVectorListUSetDualSpace &list_Vc_lt_UsDs, Space d){ long structSize; Space spXY, spY; NegSkyStrAux structure0; structSize = creationStructureNSC(structure0, list_Vc_lt_UsDs, d); for (auto itXY=structure0.begin();itXY!=structure0.end();itXY++){ spXY=itXY->first; vector<pair<Space,vector<DataType>>> vY; for (auto itY=(itXY->second).begin();itY!=(itXY->second).end();itY++){ spY=itY->first; vector<Space> vId; for (auto itId=(itY->second).begin();itId!=(itY->second).end();itId++){ vId.push_back(*itId); } vY.push_back(pair<Space, vector<DataType>>(spY, vId)); } structure.push_back(pair<Space, vector<pair<Space,vector<DataType>>>>(spXY, vY)); } return structSize; } bool pet(const pair<Space, TableTuple> &p1, const pair<Space, TableTuple> &p2 ){ return __builtin_popcount(p1.first) >__builtin_popcount(p2.first); } void choixPivot(TableTuple &topmost, Space d){ DataType n= topmost.size(); DataType iMinMax=-1, minMax=n, maxVal; for (auto i=0;i<n;i++){ maxVal=topmost[i][0]; for (auto j=1;j<d;j++) if (maxVal<topmost[i][j]) maxVal=topmost[i][j]; if (maxVal<minMax){ iMinMax=i; minMax=maxVal; } } Point pointAux=topmost[0]; topmost[0]=topmost[iMinMax]; topmost[iMinMax]=pointAux; } bool* subspaceSkyline_NSC(NegSkyStr &structure, int size_data, const Space subspace){ DataType i; bool* tableSkyline=new bool[size_data]; for (i=0;i<size_data;i++) tableSkyline[i]=true; //for (auto itXY=structure.rbegin();itXY!=structure.rend() && subspace<=(itXY->first);++itXY){ for (auto itXY=structure.rbegin();itXY!=structure.rend();++itXY){ if (estInclusDans(subspace, itXY->first)){ for (auto itY=(itXY->second).begin();itY!=(itXY->second).end();++itY) { if (!estInclusDans(subspace, itY->first)) { for (auto itId=(itY->second).begin();itId!=(itY->second).end();++itId){ tableSkyline[*itId]=false; } } } } } return tableSkyline; } bool* subspaceSkylineSize_NSC(NegSkyStr &structure, int size_data, Space subspace){ DataType skySize; bool* skyline=subspaceSkyline_NSC(structure, size_data, subspace); skySize=compteLesMarques(skyline, size_data); //delete[] skyline; return skyline; } DataType compteLesMarques(bool* table, DataType length){ /* function qui compte le nombre de cellules valant 'vrai' dans une table de booleens utile pour calculer la taille du skyline*/ DataType i, total=0; for (i=0; i<length; i++) total+=table[i]; return total; } void displayResult(string dataName, DataType n, Space d, DataType k, string step, long structSize, double timeToPerform){ cerr<<dataName<<" "<<n<<" "<<d<<" "<<k<<" "<<"NSCt"<<" "<<step<<" "<<structSize<<" "<<timeToPerform<<endl; } void skylinequery(string dataName, NegSkyStr &structure0, int indexedDataSize, Space d, DataType k, vector<Space> subspaceN){ int N=subspaceN.size(); string nombreRequete ="N="+to_string(N); int structSize=0; double timeToPerform; timeToPerform=debut(); for (int i=0; i<N; i++){ bool *skyline_NSC; skyline_NSC=subspaceSkylineSize_NSC(structure0, indexedDataSize, subspaceN[i]); for (int j=0;j<indexedDataSize;j++){ if (skyline_NSC[j]==true) { structSize++; } } } timeToPerform=duree(timeToPerform); displayResult(dataName, indexedDataSize, d, k, nombreRequete, structSize, timeToPerform); } void updateNSCt_step1(list<TableTuple> &mainDataset, TableTuple &valid_topmost, int decalage, ListVectorListUSetDualSpace &ltVcLtUsDs, Space d){ Space All=(1<<d)-1; int number_batch=mainDataset.size(); TableTuple buffer=(*mainDataset.begin()); int size_buffer=buffer.size(); VectorListUSetDualSpace buffer_pairs(buffer.size()); bool completely_dominated[buffer.size()]; for (int k=0;k<size_buffer;k++) completely_dominated[k]=false; //*********************************************************** // for each tuple t in the buffer #pragma omp parallel for schedule(dynamic) for (int k=0; k<buffer.size(); k++){ int smaller_position_all=number_batch; vector<list<DualSpace>> pairsToCompress(number_batch); vector<unordered_set<DualSpace>> pairsToCompress_in_set(number_batch); //for each tuple t' in topmost for (int j=0; j<valid_topmost.size(); j++) { DualSpace ds; ds=NEG::domDualSubspace_1(valid_topmost[j], buffer[k], d); if(ds.dom==All){ //t completely dominated by t' if((number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1)==0){ // if t older than t' completely_dominated[k]=true; pairsToCompress_in_set[number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1].clear(); pairsToCompress_in_set[number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1].insert(ds); smaller_position_all=0; break; } else{// if t' older than t if((number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1)<smaller_position_all){ smaller_position_all=number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1; pairsToCompress_in_set[number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1].clear(); pairsToCompress_in_set[number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1].insert(ds); } } } else{ pairsToCompress_in_set[number_batch - (valid_topmost[j][0] / size_buffer - decalage) -1].insert(ds); } } // if t not completely dominated, we compress its pairs if(!completely_dominated[k]){ //empty buckets followed by buckets having ds.All for (int i=smaller_position_all+1;i<number_batch;i++){ pairsToCompress_in_set[i].clear(); } // move pairs in pairToCompress structure for (int i=0;i<number_batch;i++){ pairsToCompress[i].insert(pairsToCompress[i].begin(), pairsToCompress_in_set[i].begin(), pairsToCompress_in_set[i].end()); } CompresserParInclusion_cascade(pairsToCompress,d,buffer_pairs[k]); } } //************************************************************** //*************************************************************** // delete tuples completely dominated int nb_non_domines=0; for (int i = 0; i<size_buffer;i++){if(!completely_dominated[i]) nb_non_domines++;} VectorListUSetDualSpace buffer_pairs_to_swap(nb_non_domines); TableTuple batch_data_to_swap(nb_non_domines); auto it_bloc_data=mainDataset.begin(); int j=0; for (int i = 0; i<size_buffer;i++){ if(!completely_dominated[i]){ buffer_pairs_to_swap[j]=buffer_pairs[i]; batch_data_to_swap[j]=(*it_bloc_data)[i]; j++; } } buffer_pairs.swap(buffer_pairs_to_swap); it_bloc_data->swap(batch_data_to_swap); //*************************************************************** ltVcLtUsDs.push_front(buffer_pairs); } void updateNSCt_step1_real_data(list<TableTuple> &mainDataset, TableTuple &valid_topmost, int decalage, ListVectorListUSetDualSpace &ltVcLtUsDs, Space d, vector<int> &blocks_startId){ Space All=(1<<d)-1; int number_batch=mainDataset.size(); TableTuple buffer=(*mainDataset.begin()); int size_buffer=buffer.size(); VectorListUSetDualSpace buffer_pairs(buffer.size()); bool completely_dominated[buffer.size()]; for (int k=0;k<size_buffer;k++) completely_dominated[k]=false; //*********************************************************** // for each tuple t in the buffer #pragma omp parallel for schedule(dynamic) for (int k=0; k<buffer.size(); k++){ int smaller_position_all=number_batch; vector<list<DualSpace>> pairsToCompress(number_batch); vector<unordered_set<DualSpace>> pairsToCompress_in_set(number_batch); //cout << "here"<<endl; //for each tuple t' in topmost for (int j=0; j<valid_topmost.size(); j++) { DualSpace ds; ds=NEG::domDualSubspace_1(valid_topmost[j], buffer[k], d); int position_topmost=tuple_position(valid_topmost[j][0], blocks_startId)-decalage; // cout << " position topmost : "<<position_topmost<<endl; if(ds.dom==All){ //t completely dominated by t' // cout << "here2"<<endl; if(position_topmost==number_batch-1){ // if t older than t' // cout << "here21"<<endl; completely_dominated[k]=true; pairsToCompress_in_set[number_batch - position_topmost -1].clear(); pairsToCompress_in_set[number_batch - position_topmost -1].insert(ds); smaller_position_all=0; break; } else{// if t' older than t // cout << "here22"<<endl; if((number_batch - position_topmost -1)<smaller_position_all){ smaller_position_all=number_batch - position_topmost -1; // cout << "smaller_position_all: "<<smaller_position_all<< " position to put : "<<number_batch - position_topmost -1<<endl; pairsToCompress_in_set[number_batch - position_topmost -1].clear(); pairsToCompress_in_set[number_batch - position_topmost -1].insert(ds); } } } else{ //cout << "here3"<<endl; //cout << " position to put : "<<number_batch - position_topmost -1<<endl; pairsToCompress_in_set[number_batch - position_topmost -1].insert(ds); } } // cout << "here4"<<endl; // if t not completely dominated, we compress its pairs if(!completely_dominated[k]){ //empty buckets followed by buckets having ds.All for (int i=smaller_position_all+1;i<number_batch;i++){ pairsToCompress_in_set[i].clear(); } // move pairs in pairToCompress structure for (int i=0;i<number_batch;i++){ pairsToCompress[i].insert(pairsToCompress[i].begin(), pairsToCompress_in_set[i].begin(), pairsToCompress_in_set[i].end()); } CompresserParInclusion_cascade(pairsToCompress,d,buffer_pairs[k]); } } //************************************************************** //*************************************************************** // delete tuples completely dominated int nb_non_domines=0; for (int i = 0; i<size_buffer;i++){if(!completely_dominated[i]) nb_non_domines++;} VectorListUSetDualSpace buffer_pairs_to_swap(nb_non_domines); TableTuple batch_data_to_swap(nb_non_domines); auto it_bloc_data=mainDataset.begin(); int j=0; for (int i = 0; i<size_buffer;i++){ if(!completely_dominated[i]){ buffer_pairs_to_swap[j]=buffer_pairs[i]; batch_data_to_swap[j]=(*it_bloc_data)[i]; j++; } } buffer_pairs.swap(buffer_pairs_to_swap); it_bloc_data->swap(batch_data_to_swap); //*************************************************************** ltVcLtUsDs.push_front(buffer_pairs); } void updateNSCt_step2(list<TableTuple> &mainDataset, TableTuple &valid_topmost, TableTuple &old_topmost, int decalage, ListVectorListUSetDualSpace &ltVcLtUsDs, Space d, int buffer_size){ Space All=(1<<d)-1; // compute useful topmost: tuples that were not in the topmost in the previous maintenance time TableTuple useful_topmost; unordered_set<Point> old; old.insert(old_topmost.begin(),old_topmost.end()); for(auto it=valid_topmost.begin();it!=valid_topmost.end();it++) if(old.find((*it))==old.end()) useful_topmost.push_back(*it); auto it_bloc_data=mainDataset.begin();//iterator on the most recent tuples auto it_bloc_pair=ltVcLtUsDs.begin();//iterator on the most recent tuples it_bloc_data++;it_bloc_pair++; // the first one does not need to be updated //****************************************************************************** // loop on all existing transactions int block_position=1; while (it_bloc_data!=mainDataset.end()){ bool completely_dominated[it_bloc_data->size()]; for (int k=0;k<it_bloc_data->size();k++) completely_dominated[k]=false; //************************************************************************** // for each tuple t of a transaction #pragma omp parallel for schedule(dynamic) for (int i=0; i<(*it_bloc_data).size(); i++){ USetDualSpace usDS; int smaller_position_all=(*it_bloc_pair)[i].size(); // for each tuple t' in useful_topmost for (int j=0; j <useful_topmost.size();j++){ DualSpace ds; ds=NEG::domDualSubspace_1(useful_topmost[j], (*it_bloc_data)[i], d); // compute where to put the pair int pair_position=mainDataset.size() - block_position - (useful_topmost[j][0]/buffer_size) +decalage; if (pair_position-1>=0) { auto it=(*it_bloc_pair)[i].begin(); for (int m=0;m<pair_position-1;m++) it++; if (ds.dom==All) { if(smaller_position_all>pair_position) smaller_position_all=pair_position; it->clear(); } it->insert(ds); } else{ auto it=(*it_bloc_pair)[i].begin(); if (ds.dom==All) {completely_dominated[i]=true;break;} it->insert(ds); } } // compress only if the tuple is not totally dominated if(!completely_dominated[i]){ vector<list<DualSpace>> pairsToCompress((*it_bloc_pair)[i].size()); int indice=0; for (auto it_list = (*it_bloc_pair)[i].begin() ; it_list!=(*it_bloc_pair)[i].end();it_list++){ pairsToCompress[indice].insert(pairsToCompress[indice].begin(),it_list->begin(),it_list->end()); indice++; } for (int m=smaller_position_all+1;m<pairsToCompress.size();m++) pairsToCompress[m].clear(); (*it_bloc_pair)[i].clear(); CompresserParInclusion_cascade(pairsToCompress, d, (*it_bloc_pair)[i]); } } //********************************************************************* //******************************************************************** // delete completely dominated tuples int nb_non_domines=0; for (int i = 0; i<(*it_bloc_data).size();i++){if(!completely_dominated[i]) nb_non_domines++;} VectorListUSetDualSpace bloc_pairs_to_swap(nb_non_domines); TableTuple dataset_to_swap(nb_non_domines); int j=0; for (int i = 0; i<(*it_bloc_data).size();i++){ if(!completely_dominated[i]){ bloc_pairs_to_swap[j]=(*it_bloc_pair)[i]; dataset_to_swap[j]=(*it_bloc_data)[i]; j++; } } (*it_bloc_pair).swap(bloc_pairs_to_swap); (*it_bloc_data).swap(dataset_to_swap); //******************************************************************** it_bloc_data++; it_bloc_pair++; block_position++; } //******************************************************************************* } void updateNSCt_step2_real_data(list<TableTuple> &mainDataset, TableTuple &valid_topmost, TableTuple &old_topmost, int decalage, ListVectorListUSetDualSpace &ltVcLtUsDs, Space d, vector<int> &blocks_startId){ Space All=(1<<d)-1; // compute useful topmost: tuples that were not in the topmost in the previous maintenance time TableTuple useful_topmost; unordered_set<Point> old; old.insert(old_topmost.begin(),old_topmost.end()); for(auto it=valid_topmost.begin();it!=valid_topmost.end();it++) if(old.find((*it))==old.end()) useful_topmost.push_back(*it); auto it_bloc_data=mainDataset.begin();//iterator on the most recent tuples auto it_bloc_pair=ltVcLtUsDs.begin();//iterator on the most recent tuples it_bloc_data++;it_bloc_pair++; // the first one does not need to be updated //****************************************************************************** // loop on all existing transactions int block_position=1; while (it_bloc_data!=mainDataset.end()){ bool completely_dominated[it_bloc_data->size()]; for (int k=0;k<it_bloc_data->size();k++) completely_dominated[k]=false; //************************************************************************** // for each tuple t of a transaction #pragma omp parallel for schedule(dynamic) for (int i=0; i<(*it_bloc_data).size(); i++){ USetDualSpace usDS; int smaller_position_all=(*it_bloc_pair)[i].size(); // for each tuple t' in useful_topmost for (int j=0; j <useful_topmost.size();j++){ DualSpace ds; ds=NEG::domDualSubspace_1(useful_topmost[j], (*it_bloc_data)[i], d); // compute where to put the pair int pair_position=mainDataset.size() - block_position - tuple_position(useful_topmost[j][0],blocks_startId) +decalage; if (pair_position-1>=0) { auto it=(*it_bloc_pair)[i].begin(); for (int m=0;m<pair_position-1;m++) it++; if (ds.dom==All) { if(smaller_position_all>pair_position) smaller_position_all=pair_position; it->clear(); } it->insert(ds); } else{ auto it=(*it_bloc_pair)[i].begin(); if (ds.dom==All) {completely_dominated[i]=true;break;} it->insert(ds); } } // compress only if the tuple is not totally dominated if(!completely_dominated[i]){ vector<list<DualSpace>> pairsToCompress((*it_bloc_pair)[i].size()); int indice=0; for (auto it_list = (*it_bloc_pair)[i].begin() ; it_list!=(*it_bloc_pair)[i].end();it_list++){ pairsToCompress[indice].insert(pairsToCompress[indice].begin(),it_list->begin(),it_list->end()); indice++; } for (int m=smaller_position_all+1;m<pairsToCompress.size();m++) pairsToCompress[m].clear(); (*it_bloc_pair)[i].clear(); CompresserParInclusion_cascade(pairsToCompress, d, (*it_bloc_pair)[i]); } } //********************************************************************* //******************************************************************** // delete completely dominated tuples int nb_non_domines=0; for (int i = 0; i<(*it_bloc_data).size();i++){if(!completely_dominated[i]) nb_non_domines++;} VectorListUSetDualSpace bloc_pairs_to_swap(nb_non_domines); TableTuple dataset_to_swap(nb_non_domines); int j=0; for (int i = 0; i<(*it_bloc_data).size();i++){ if(!completely_dominated[i]){ bloc_pairs_to_swap[j]=(*it_bloc_pair)[i]; dataset_to_swap[j]=(*it_bloc_data)[i]; j++; } } (*it_bloc_pair).swap(bloc_pairs_to_swap); (*it_bloc_data).swap(dataset_to_swap); //******************************************************************** it_bloc_data++; it_bloc_pair++; block_position++; } //******************************************************************************* } void expiration(ListVectorListUSetDualSpace &listVcUSetDualSpace){ for (auto it_list = listVcUSetDualSpace.begin(); it_list != listVcUSetDualSpace.end(); it_list++){ for (auto it_vector = it_list->begin(); it_vector!=it_list->end(); it_vector++){ it_vector->pop_back(); } } } void CompresserParInclusion(list<DualSpace> &l){ l.sort(NEG::pet_pair); for(auto it=l.begin(); it!=l.end();it++){ auto it1=it; it1++; while(it1!=l.end() ){ if (estInclusDans((*it1).dom,(*it).dom) && (estInclusDans((*it1).equ, (*it).dom + (*it).equ))){ it1=l.erase(it1); } else{ it1++; } } } } void compresserParInclusion2liste(list<DualSpace> &l,list<DualSpace> &s){ s.sort(NEG::pet_pair); auto it=l.begin(); while(it!=l.end()){ auto it1=s.begin(); bool comp=(spacePair(*it)<=spacePair(*it1)); while(it1!=s.end() && comp){ if (estInclusDans((*it).dom,(*it1).dom) && (estInclusDans((*it).equ, (*it1).dom + (*it1).equ))){ it=l.erase(it); break; } it1++; } if(it1==s.end() || !comp){ it++; } } } void CompresserParInclusion_cascade(vector<list<DualSpace>> &toCompress, Space d, ListUSetDualSpace &l){ list<DualSpace> lds; for (int i=0;i<toCompress.size();i++){ USetDualSpace usDs; CompresserParInclusion(toCompress[i]); if(i>0){ lds.insert(lds.begin(),toCompress[i-1].begin(),toCompress[i-1].end()); lds.sort(pet_pair); auto it=toCompress[i].begin(); while(it!=toCompress[i].end()){ auto it1=lds.begin(); bool comp=(spacePair(*it)<=spacePair(*it1)); while(it1!=lds.end() && comp){ if (estInclusDans((*it).dom,(*it1).dom) && (estInclusDans((*it).equ, (*it1).dom + (*it1).equ))){ it=toCompress[i].erase(it); break; } it1++; } if(it1==lds.end() || !comp){ it++; } } } fusionGloutonne(toCompress[i],d); usDs.insert(toCompress[i].begin(),toCompress[i].end()); l.push_back(usDs); } } void InitStructure (list<TableTuple> &mainDataset, TableTuple &topmost, ListVectorListUSetDualSpace &ltVcLtUsDs, Space d, vector<int> &blocks_size){ int block_position=0; Space All=(1<<d)-1; int number_batch=mainDataset.size(); for (auto it_listDataset=mainDataset.rbegin();it_listDataset!=mainDataset.rend();it_listDataset++){ VectorListUSetDualSpace bloc_pairs(blocks_size[block_position]); bool all_yes[blocks_size[block_position]]; for (int k=0;k<blocks_size[block_position];k++) all_yes[k]=false; //*************************************************************************** //for each record of the current transaction #pragma omp parallel for schedule(dynamic) for (int i = 0; i<blocks_size[block_position];i++){ vector<list<DualSpace>> pairsToCompress(block_position+1); vector<unordered_set<DualSpace>> pairsToCompress_in_set(block_position+1); USetDualSpace usDs; //for each record of the topmost for (int j=0; j<topmost.size();j++){ int position_topmost=topmost[j][0]/blocks_size[block_position]; DualSpace ds; ds=NEG::domDualSubspace_1(topmost[j], (*it_listDataset)[i], d); //if the tuple is older than the topmost tuple and ds= All then the tuple is dominated during its lifetime if(block_position <= position_topmost && ds.dom==All){all_yes[i]=true;break;} if(position_topmost <= block_position){ pairsToCompress_in_set[block_position- position_topmost].insert(ds); } else{ pairsToCompress_in_set[0].insert(ds); } } //compress pairs of non completely dominated tuples if(!all_yes[i]){ for(int j=0;j<block_position+1;j++) { pairsToCompress[j].insert(pairsToCompress[j].begin(), pairsToCompress_in_set[j].begin(), pairsToCompress_in_set[j].end()); } CompresserParInclusion_cascade(pairsToCompress,d,bloc_pairs[i]); } } //******************************************************************************** //******************************************************* //delete completely dominated tuples VectorListUSetDualSpace bloc_pairs_to_swap; TableTuple dataset_to_swap; for (int i = 0; i<blocks_size[block_position];i++){ if(!all_yes[i]){ bloc_pairs_to_swap.push_back(bloc_pairs[i]); dataset_to_swap.push_back((*it_listDataset)[i]); } } (*it_listDataset).swap(dataset_to_swap); bloc_pairs.swap(bloc_pairs_to_swap); //******************************************************* ltVcLtUsDs.push_front(bloc_pairs); block_position++; } } void InitStructure_real_data (list<TableTuple> &mainDataset, TableTuple &topmost, ListVectorListUSetDualSpace &ltVcLtUsDs, Space d, vector<int> &blocks_size, vector<int> &blocks_startId){ int block_position=0; Space All=(1<<d)-1; int number_batch=mainDataset.size(); for (auto it_listDataset=mainDataset.rbegin();it_listDataset!=mainDataset.rend();it_listDataset++){ VectorListUSetDualSpace bloc_pairs(blocks_size[block_position]); bool all_yes[blocks_size[block_position]]; for (int k=0;k<blocks_size[block_position];k++) all_yes[k]=false; //*************************************************************************** //for each record of the current transaction #pragma omp parallel for schedule(dynamic) for (int i = 0; i<blocks_size[block_position];i++){ vector<list<DualSpace>> pairsToCompress(block_position+1); vector<unordered_set<DualSpace>> pairsToCompress_in_set(block_position+1); USetDualSpace usDs; //for each record of the topmost for (int j=0; j<topmost.size();j++){ int position_topmost=tuple_position(topmost[j][0], blocks_startId); DualSpace ds; ds=NEG::domDualSubspace_1(topmost[j], (*it_listDataset)[i], d); //if the tuple is older than the topmost tuple and ds= All then the tuple is dominated during its lifetime if(block_position <= position_topmost && ds.dom==All){all_yes[i]=true;break;} if(position_topmost <= block_position){ pairsToCompress_in_set[block_position- position_topmost].insert(ds); } else{ pairsToCompress_in_set[0].insert(ds); } } //compress pairs of non completely dominated tuples if(!all_yes[i]){ for(int j=0;j<block_position+1;j++) { pairsToCompress[j].insert(pairsToCompress[j].begin(), pairsToCompress_in_set[j].begin(), pairsToCompress_in_set[j].end()); } CompresserParInclusion_cascade(pairsToCompress,d,bloc_pairs[i]); } } //******************************************************************************** //******************************************************* //delete completely dominated tuples VectorListUSetDualSpace bloc_pairs_to_swap; TableTuple dataset_to_swap; for (int i = 0; i<blocks_size[block_position];i++){ if(!all_yes[i]){ bloc_pairs_to_swap.push_back(bloc_pairs[i]); dataset_to_swap.push_back((*it_listDataset)[i]); } } (*it_listDataset).swap(dataset_to_swap); bloc_pairs.swap(bloc_pairs_to_swap); //******************************************************* ltVcLtUsDs.push_front(bloc_pairs); block_position++; } } }
c020fa62b75de24c63d7076e291128c925303c5e
6efe859757d37f5f20693c5e47508f4c6fcf3666
/uhunt/11504.cpp
91b6a920f7f1544781d2a344e41931afcdcbcccc
[]
no_license
uvafan/ICPC_Practice
6665309b05937f9980a69a342eb917d793d415ae
3b6d84bacc0a72d18cc4ba5a2b0e7478b6eb6fc5
refs/heads/master
2021-07-06T15:08:46.299846
2019-04-01T22:29:42
2019-04-01T22:29:42
104,101,562
1
0
null
null
null
null
UTF-8
C++
false
false
1,829
cpp
11504.cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<int> vi; #define INF 1000000000 vector<vi> adjList, adjListSCCS, sccs; vi visited, dfs_low, dfs_num, S, indegree, sccID; int dfsNumberCounter; void SCC(int u){ dfsNumberCounter++; dfs_low[u] = dfs_num[u] = dfsNumberCounter; S.push_back(u); visited[u] = 1; for(int i=0;i<adjList[u].size();i++){ int v = adjList[u][i]; if(!dfs_num[v])SCC(v); if(visited[v]) dfs_low[u] = min(dfs_low[u],dfs_low[v]); } if(dfs_low[u] == dfs_num[u]){ vi toAdd; while(1){ int v = S.back(); S.pop_back(); visited[v]=0; toAdd.push_back(v); sccID[v] = sccs.size(); if(u==v)break; } sccs.push_back(toAdd); } } int main(){ int i,j,V,E,N,a,b; cin>>N; while(N--){ cin >> V >> E; adjList.assign(V,vi(0,0)); while(E--){ cin >> a >> b; adjList[a-1].push_back(b-1); } dfs_num.assign(V,0);dfs_low.assign(V,0);visited.assign(V,0); dfsNumberCounter = 0; sccID.assign(V,0); sccs.clear(); for(i=0;i<V;i++) if(!dfs_num[i]){ SCC(i); } vi sccIndegree(sccs.size(),0); for(i=0;i<sccs.size();i++){ for(int k=0;k<sccs[i].size();k++){ int v = sccs[i][k]; for(j=0;j<adjList[v].size();j++){ if(sccID[adjList[v][j]]!=i) sccIndegree[sccID[adjList[v][j]]]++; } } } int count = 0; for(i=0;i<sccIndegree.size();i++) if(!sccIndegree[i]) count++; cout << count << endl; } return 0; }
540c584f0f40aea5dd9ea89d91ff4836942e172c
b84ea42839237dd1c6cfa85267dc663cbc103516
/src/include/Video/Shader.h
888a6c63718d2ffc3a06bbfabe1c5ac071509712
[]
no_license
MaximumOverflow/TwigEngine
6d37d7b5e47af7151535189d39d2ca5dbd5e2882
2bdb998da7a9f3cb40dd7919a228f962c9def499
refs/heads/master
2020-06-22T19:26:16.061198
2019-10-02T21:26:15
2019-10-02T21:26:15
186,144,360
0
0
null
null
null
null
UTF-8
C++
false
false
1,175
h
Shader.h
// // Created by max on 19/07/19. // #ifndef TWIG_ENGINE_SHADER_H #define TWIG_ENGINE_SHADER_H #include <string> #include <unordered_map> #include <memory> #include "Types/Types.h" #include "External/robin_hood.h" #include "Asset.h" namespace TE { class Shader : public Asset { protected: robin_hood::unordered_map<std::string, int> uniformCache; int GetUniformFromCache(std::string name); void AddUniformToCache(std::string name, int id); public: static std::shared_ptr<Shader> Create(std::string vertexSource, std::string fragmentSource); static std::shared_ptr<Shader> CreateFromFile(std::string vertexPath, std::string fragmentPath); virtual void Bind() = 0; virtual void Unbind() = 0; virtual void SetUniformMat4f(std::string name, const Mat4& matrix) = 0; virtual void SetUniformVec3f(std::string name, const Vec3& vec3) = 0; virtual void SetUniformVec4f(std::string name, const Vec4& vec4) = 0; virtual void SetUniformVec1i(std::string name, int vec1) = 0; Shader() = default; virtual ~Shader() = default; }; } #endif //TWIG_ENGINE_SHADER_H
e4e0354007956e23c2c2fb63f71275f70235fef9
b3b39a553ec4f92d5631090090094348deddec3e
/practice/graph/kruskalMST(practice)/kruskalMST(practice)/checkCycle.cpp
7fb6bddb0c9ce45fe3f645132eea6e2b65eb0fdf
[]
no_license
halloTheCoder/Algorithm
1015dfcfecd97234d6984aad1126ce6dfee8af06
6b0ade9a4432e5dd96ab846fc42fdaa426cf207b
refs/heads/master
2021-05-15T09:44:48.161700
2017-11-03T08:02:16
2017-11-03T08:02:16
108,151,138
1
0
null
2017-11-03T08:02:17
2017-10-24T16:03:15
C++
UTF-8
C++
false
false
1,042
cpp
checkCycle.cpp
#include "stdafx.h" #include "checkCycle.h" #include <algorithm> checkCycle::checkCycle() { } checkCycle::checkCycle(int v) { this->v = v; adjL = new std::vector<int>[v]; visited = std::vector<bool>(v, false); hasCycle = false; } void checkCycle::addEdge(int src, int dest) { adjL[src].push_back(dest); adjL[dest].push_back(src); } bool checkCycle::detectCycle() { hasCycle = false; visited = std::vector<bool>(v, false); for (int i = 0; i < v; i++) { if (!visited[i]) { detectCycleUtil(i, -1); if (hasCycle) return true; } } return false; } void checkCycle::detectCycleUtil(int i,int parent) { visited[i] = true; for (auto &n : adjL[i]) { if (visited[n] && n != parent) { hasCycle = true; return; } else if (!visited[n]) { detectCycleUtil(n, i); } } } void checkCycle::deleteEdge(int src, int dest) { adjL[src].erase(std::remove(adjL[src].begin(), adjL[src].end(), dest), adjL[src].end()); adjL[dest].erase(std::remove(adjL[dest].begin(), adjL[dest].end(), src), adjL[dest].end()); }
9d9c9ea65c1222ef9c41fe9aa87f0a1175e12ab0
86955fc67a788438dc7629b7da6598051c381703
/FlashReader/VendorRecordsDlg.h
7214160cb883d871db375f8c2d5574777d24d59d
[]
no_license
isliulin/WorkProjects
d1cc87cf39a85c678dd2fff0637ff7b7095f8134
81a44104d9f59fdffe85efe1990dbce5b9d036e6
refs/heads/master
2023-03-15T20:07:57.011722
2015-03-16T15:59:39
2015-03-16T15:59:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
734
h
VendorRecordsDlg.h
#pragma once #include "FlashDatabase.h" #include "OxGridList.h" class CVendorRecordsDlg : public CDialog { public: enum { IDD = IDD_VENDOR_RECORDS }; protected: CFlashDatabase& m_Database; COXGridList m_gridVendor; BOOL m_bModified; public: CVendorRecordsDlg(CWnd* pParent, CFlashDatabase& database); virtual ~CVendorRecordsDlg(); protected: virtual void DoDataExchange(CDataExchange* pDX); virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void OnCancel(); afx_msg void OnClose(); afx_msg void OnClickedVendorNew(); afx_msg void OnClickedVendorRemove(); private: int InsertVendor(CVendorRecord* pVendor); DECLARE_DYNAMIC(CVendorRecordsDlg) DECLARE_MESSAGE_MAP() };
8518ef2b5e11facdac13b1533ea0686ac93f2b89
54d6f4e07ce667130c59726d281cfe511f535d0f
/LeetCodeTest05.12.2019.cpp
044ec4bab46d1b3b5d74d4616c837d34353f552a
[]
no_license
G33k1973/CodingGames
36285caf48fb33c7947d3596f3446929b3a0a1ab
7fa55622c9ee525ac3974cd2036cd61ec448802b
refs/heads/master
2021-07-08T14:35:14.183733
2020-09-05T08:39:08
2020-09-05T08:39:08
184,714,072
0
0
null
null
null
null
UTF-8
C++
false
false
2,650
cpp
LeetCodeTest05.12.2019.cpp
#define pb push_back class Solution { protected: unordered_set<std::string> seen; unordered_map<std::string, int> dict; void parse(string& s) { s += " "; int l = static_cast<int>(s.length()); string sub = ""; int i = 0; while (i < l) { char x = s.at(i); if (isalpha(x)) { if (isupper(x))x = tolower(x); sub.pb(x); } else { if (!sub.empty()) { if (seen.count(sub) == 0) { ++dict[sub]; sub.clear(); } else sub.clear(); } } ++i; } } string res; public: string mostCommonWord(string paragraph, vector<string>& banned) { res = ""; for (auto& x : banned)seen.insert(x); parse(paragraph); pair<string, int> ans("", INT_MIN); for (auto& x : dict) { if (x.second > ans.second)ans = make_pair(x.first, x.second); } return res = ans.first; } }; typedef pair<int, int> ip; typedef pair<ip, int> iip; #define pb push_back #define mp make_pair int X[4] = { 1,-1,0,0 }; int Y[4] = { 0,0,1,-1 }; class Solution { protected: bool isgood(int i, int j) { return (i >= 0 && j >=0 &&i < n&&j < m); } int n, m; std::map<int, pair<int, int>> trees; int bfs(int itr, int jtr, int& ipos, int& jpos, vector<vector<int>>& grid) { vector<vector<bool>> v(n, vector<bool>(m, false)); v[ipos][jpos] = true; std::queue<iip> pile; pile.push(mp(mp(ipos, jpos), 0)); while (!pile.empty()) { int sz = int(pile.size()); int k = 0; while (k < sz) { iip current = pile.front(); pile.pop(); int oi = current.first.first; int oj = current.first.second; int w = current.second; if (oi == itr && oj == jtr) { grid[itr][jtr] = 1; ipos = itr, jpos = jtr; return w; } for (int u = 0; u < 4; ++u) { int ni = oi + X[u]; int nj = oj + Y[u]; if (isgood(ni, nj) && !v[ni][nj] && grid[ni][nj] > 0) { pile.push(mp(mp(ni, nj), w + 1)); v[ni][nj] = 1; } } ++k; } } return -1; } public: int cutOffTree(vector<vector<int>>& forest) { n = int(forest.size()); if (n == 0)return 0; m = int(forest.front().size()); if (m == 0)return 0; int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { if (forest[i][j] > 1) { trees.insert(make_pair(forest[i][j], make_pair(i, j))); } } } auto ptr = begin(trees); int res = 0; pair<int, int> pos(0, 0); while (ptr != end(trees)) { int sub=bfs(ptr->second.first, ptr->second.second, pos.first, pos.second, forest); if (sub == -1)return -1; res += sub; ++ptr; } return res; } };
40b11473afef5584dafe6eb7a8718c7aae1ad317
d41a12992bbdd7b2b9626bf1bb1466b4b793840e
/cpp_basic/cpprimer_2013/026_copy_control/Folder.h
6154ca40553df8dc782893d434a7cf36f5d93668
[]
no_license
FrankBlues/c-cpp-study
e81975f97a0b0bcdcaff68b9a108241732340b76
a49971365a506e06405a7fc51494cbe6ea282eed
refs/heads/master
2023-01-23T10:53:26.420934
2023-01-19T03:10:14
2023-01-19T03:10:14
179,606,300
0
0
null
null
null
null
UTF-8
C++
false
false
519
h
Folder.h
#ifndef FOLDER_H #define FOLDER_H #include <iostream> #include "Message.h" class Folder { friend void swap(Folder &, Folder &); friend class Message; public: Folder() = default; Folder(const Folder &); Folder& operator=(const Folder &); ~Folder(); void print_debug(); void addMsg(Message *m) { msgs.insert(m); } void remMsg(Message *m) { msgs.erase(m); } private: std::set<Message*> msgs; void add_to_Message(const Folder&); void remove_from_Message(); }; #endif
d6744cf95b0964879555b01b317f49b384f13b16
8433e87fb98d6dfdacb435820823c602ae61f03c
/OpenGL/src/Mesh.cpp
ce1062ddff8e8ebc2161027c34883f10d587ad94
[]
no_license
Qwerkykk/OpenGL
dd1ed2a1e57158248be7bb1d52025ea3a7fc6c26
144f4c9250933f6cd30a43c016a3009de43f4883
refs/heads/master
2023-03-24T15:34:40.528948
2021-03-13T09:07:41
2021-03-13T09:07:41
347,320,243
1
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
Mesh.cpp
#include "Mesh.h" #include <utility> Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<std::shared_ptr<TextureBasic>> textures) : m_Textures(std::move(textures)), m_VBO(&vertices[0], vertices.size() * sizeof(Vertex)), m_EBO(&indices[0], indices.size()) { setupMesh(); } void Mesh::BindTexture(unsigned int i) const { m_Textures[i]->Bind(i); } void Mesh::Bind() const { m_VAO.Bind(); } void Mesh::Unbind() const { m_VAO.Unbind(); } void Mesh::setupMesh() { VertexBufferLayout VBOLayout; m_VAO.Bind(); m_VBO.Bind(); m_EBO.Bind(); VBOLayout.Push<float>(3); VBOLayout.Push<float>(3); VBOLayout.Push<float>(2); VBOLayout.Push<float>(3); VBOLayout.Push<float>(3); m_VAO.AddBuffer(m_VBO, VBOLayout); m_VAO.Unbind(); m_VBO.Unbind(); m_EBO.Unbind(); }
e6bb023dff0f5c97933f87068e2720e6998e00c8
43e4b745d8fcf0b28d988986e0ba1394ea289f2d
/module1/homework/calculate/main.cpp
1008079b7dc6f9769845d780a5cc4c139bc8b40f
[ "MIT" ]
permissive
kszytko/kurs_cpp_podstawowy
b45969d4feb9b964ac4f38bbd7fa3fce23ec38fc
3447581d11f990077b38e4ec58da607aeec6db8f
refs/heads/master
2022-09-24T01:10:15.298002
2020-05-15T16:22:11
2020-05-15T16:22:11
263,965,921
1
0
MIT
2020-05-15T16:22:12
2020-05-14T16:20:32
JavaScript
UTF-8
C++
false
false
564
cpp
main.cpp
#include <iostream> #include <string> #include "calculate.hpp" int main() { while (true) { std::cout << "Provide command: \"add\", \"subtract\"," << " multiply\", divide\" or \"quit\" to exit\n"; std::string command{}; std::cin >> command; if (command == "quit") break; int first{}; int second{}; std::cout << "Provide two numbers: "; std::cin >> first >> second; std::cout << "Result: " << calculate(command, first, second) << "\n"; } return 0; }
893b9986d28a7c0da6fa12e08f6b1112bfe3221b
c015e4bc4cd913a6a02feb67802676892fd63414
/Lesson_1/01_WinApi/01_WinApi.cpp
f3fa5f7b4a781a3301bf5bd7594c02badb3a4700
[]
no_license
Annushka34/WIN_FORM_2019
aa07b898c1183aa7847ec31b80454e1f0879285d
9630d1b4ebc6c0795c8c36da6b168ab4f2545ef1
refs/heads/master
2020-06-12T20:11:03.208851
2019-09-08T21:23:20
2019-09-08T21:23:20
194,411,047
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
7,235
cpp
01_WinApi.cpp
// 01_WinApi.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "01_WinApi.h" LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { wchar_t szNameOfApplication[] = L"Моє перше справжнє вікно"; wchar_t szNameOfWindowClass[] = L"MyWindowClass"; ////////////////////// I. описуємо віконний клас /////////////////////////// WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); // розмір структури у байтах wc.style = CS_VREDRAW | CS_HREDRAW; // стиль вікна : хочемо щоб вікно перемальовувалося при зміні розмірів по горизонталі і вертикалі wc.lpfnWndProc = WindowProcedure; // вказівник на віконну процедуру wc.cbClsExtra = 0; // к-ть байт, що резервуються слідом за структурою класу wc.cbWndExtra = 0; // к-ть байт, що резервуються слідом за екземпляном вікна wc.hInstance = hInstance; // хендл додатку, що створив вікно (нашої проги) wc.hIcon = LoadIcon(NULL, IDI_QUESTION); // визначає значок вікна wc.hIconSm = LoadIcon(NULL, IDI_WARNING); // визначає малий значок вікна wc.hCursor = LoadCursor(NULL, IDC_HAND); // визначає вигляд курсора миші wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // визначає тло вікна //wc.hbrBackground= (HBRUSH)GetStockObject( GRAY_BRUSH); // визначає тло вікна //wc.hbrBackground= CreateSolidBrush( RGB( 255, 255, 0 ) ); //wc.hbrBackground= CreateSolidBrush( RGB( 24, 77, 111 ) ); wc.lpszMenuName = NULL; // визначає меню вікна wc.lpszClassName = szNameOfWindowClass; // визначає ім'я віконного класу if (!RegisterClassEx(&wc)) { MessageBox(NULL, L"Не вдалося зареєструвати віконний клас!", L"Хана!", MB_ICONERROR | MB_OK); return 0; } ///////////////////// III. Створюємо вікно на основі зареєєстрованого віконного класу ///////////////////// HWND hWindow = CreateWindow( szNameOfWindowClass, // ім'я віконного класу, на основі якого створити вікно szNameOfApplication, // Ім'я вікна WS_OVERLAPPEDWINDOW /*| WS_VSCROLL*/, // стиль вікна CW_USEDEFAULT, // х лівого верхнього кута вікна (CW_USEDEFAULT - визначаються системою обидва ) 0, // y лівого верхнього кута вікна CW_USEDEFAULT, // розмір по X вікна (CW_USEDEFAULT - визначаються системою обидва ) 0, // розмір по Y вікна NULL, // хендл батьківського вікна, якщо в третьому параметрі вказно WS_CHILD або WS_CHILDWINDOW NULL, // хендл меню hInstance, // хендл екземпляра програми NULL // lParam для повідомлення WM_CREATE ); ///////////////////// IV. Відображаємо вікно /////////////////////////////////// ShowWindow(hWindow, nCmdShow); MSG msg; // ексземпляр структури повідомлення while (GetMessage(&msg, NULL, 0, 0)) // GetMessage() повертає завжди TRUE, крім коли зловить WM_QUIT { TranslateMessage(&msg); // "перекладає" повідомлення клавіатури відповідно до поточної розкладки DispatchMessage(&msg); // кладе повідомлення у чергу вікна } return 0; int res = MessageBox(NULL, L"Hello", L"My msg box", MB_YESNOCANCEL | MB_ICONASTERISK); switch (res) { case IDYES: { MessageBox(NULL, L"Hello", L"You press yes", MB_YESNO | MB_ICONASTERISK); break; } default: break; } } LRESULT CALLBACK WindowProcedure (HWND hWindow, // хендл вікна, для котрого надійшла мессага (тобто, одна ВП може обробляти мессаги декількох вікон?) UINT iMsg, // ID повідомлення WPARAM wParam, // параметр одержаного повідомлення LPARAM lParam // ще один параметр одержаного повідомлення ) { switch(iMsg) { case WM_KEYDOWN: { MessageBox(NULL, L"You press some button", L"bla-bla", MB_ICONERROR | MB_OK); break; } case WM_PAINT: // надсилається щоразу, коли потрібно перемалювати ціле вікно, або його частину { // 1. отримуємо контекст пристрою ( hdc ) PAINTSTRUCT ps; HDC hdc; RECT rectClient; COLORREF col = RGB(255, 100, 100); //// 2. Малюємо по отриманому контексту //hdc = BeginPaint(hWindow, &ps); //HBRUSH hBrush; //hBrush = CreateHatchBrush(HS_FDIAGONAL, RGB(255, 0, 0)); //SelectObject(hdc, hBrush); //Ellipse(hdc, 100, 100, 200, 300); //эллипс будет заштрихован // //обновляем окно //ValidateRect(hWindow, NULL); const wchar_t * lpText = L"Уря-а-а-а! Я\n вмію писати у вікні!!!"; hdc = BeginPaint(hWindow, &ps); GetClientRect(hWindow, &rectClient); SetTextColor(hdc, col); DrawText(hdc, lpText, -1, &rectClient, DT_CENTER | DT_VCENTER /*| DT_SINGLELINE*/); // малюємо текст у прямокутнику rcText (уже посередині вікна) // 3. звільняємо контекст пристрою EndPaint(hWindow, &ps); break; } case WM_LBUTTONDOWN: { MessageBox(NULL, L"You press mouse", L"bla-bla", MB_ICONERROR | MB_OK); break; } { MessageBox(NULL, L"You press some button", L"bla-bla", MB_ICONERROR | MB_OK); break; } case WM_DESTROY: // надсилається коли вікна уже не видно, перед вивільненням пам'яті струтури вікна // MessageBox(NULL, L"Обробляється повідомлення WM_DESTROY", L"WM_DESTROY", MB_ICONINFORMATION | MB_OK); PostQuitMessage(0); // якщо закриття вікна означає закриття програми --- викликом PostQuitMessage() надсилаємо повідомлення WM_QUIT break; } return DefWindowProc(hWindow, iMsg, wParam, lParam); // хай стандартна процедура обробить ті повідомлення, які не обробили ми ! }// LRESULT CALLBACK WindowProcedure( HWND, UINT, WPARAM, LPARAM )
05b36fc8cc5c2da1777e37cd79b11522a524685a
102beccb4a386876dfeaea493209537c9a0db742
/TelepathyIMModule/TelepathyIM/Connection.cpp
d50dcd5def0596d6d059203be8833bcd876f7823
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Chiru/naali
cc4150241d37849dde1b9a1df983e41a53bfdab1
b0fb756f6802ac09a7cd9733e24e4db37d5c1b7e
refs/heads/master
2020-12-25T05:03:47.606650
2010-09-16T14:08:42
2010-09-17T08:34:19
1,290,932
1
1
null
null
null
null
UTF-8
C++
false
false
31,974
cpp
Connection.cpp
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/StreamedMediaChannel> #include "Connection.h" #include "ChatSession.h" #include "FriendRequest.h" #include "OutgoingFriendRequest.h" #include "VoiceSession.h" #include "Contact.h" #include "CredentialsInterface.h" #include "CoreDefines.h" #include "CoreException.h" #include "MemoryLeakCheck.h" namespace TelepathyIM { Connection::Connection(Tp::ConnectionManagerPtr tp_connection_manager, const Communication::CredentialsInterface &credentials) : tp_connection_manager_(tp_connection_manager), name_("Gabble"), protocol_("jabber"), state_(STATE_INITIALIZING), friend_list_("friend list"), self_contact_(0), tp_pending_connection_(0) { CreateTpConnection(credentials); } Connection::~Connection() { Close(); } void Connection::DeleteContacts() { for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i) { SAFE_DELETE(*i); } contacts_.clear(); } void Connection::DeleteFriendRequests() { for (FriendRequestVector::iterator i = received_friend_requests_.begin(); i != received_friend_requests_.end(); ++i) { SAFE_DELETE(*i); } received_friend_requests_.clear(); for (OutgoingFriendRequestVector::iterator i = sent_friend_requests_.begin(); i != sent_friend_requests_.end(); ++i) { SAFE_DELETE(*i); } sent_friend_requests_.clear(); } void Connection::CloseSessions() { // todo: disconnect any signals left for (ChatSessionVector::iterator i = private_chat_sessions_.begin(); i != private_chat_sessions_.end(); ++i) { (*i)->Close(); SAFE_DELETE(*i); } private_chat_sessions_.clear(); for (ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i) { (*i)->Close(); SAFE_DELETE(*i); } public_chat_sessions_.clear(); for (VoiceSessionVector::iterator i = voice_sessions_.begin(); i != voice_sessions_.end(); ++i) { VoiceSession* session = *i; SAFE_DELETE(session); } voice_sessions_.clear(); } void Connection::CreateTpConnection(const Communication::CredentialsInterface &credentials) { QVariantMap params; params.insert("account", credentials.GetUserID()); params.insert("password", credentials.GetPassword()); params.insert("server", credentials.GetServer()); params.insert("port", QVariant( (unsigned int)credentials.GetPort() )); Tp::PendingConnection *pending_connection = tp_connection_manager_->requestConnection(credentials.GetProtocol(), params); QObject::connect(pending_connection, SIGNAL( finished(Tp::PendingOperation *) ), SLOT( OnConnectionCreated(Tp::PendingOperation *) )); server_ = credentials.GetServer(); user_id_ = credentials.GetUserID(); } QString Connection::GetName() const { return name_; } QString Connection::GetProtocol() const { return protocol_; } Communication::ConnectionInterface::State Connection::GetState() const { return state_; } QString Connection::GetServer() const { return server_; } QString Connection::GetUserID() const { return user_id_; } QString Connection::GetReason() const { return reason_; } Communication::ContactGroupInterface& Connection::GetContacts() { return friend_list_; } QStringList Connection::GetPresenceStatusOptionsForContact() const { if (state_ != STATE_OPEN) throw Exception("Connection is not open."); QStringList options; Tp::SimpleStatusSpecMap map = tp_connection_->allowedPresenceStatuses(); for (Tp::SimpleStatusSpecMap::iterator i = map.begin(); i != map.end(); ++i) { QString o = i.key(); options.append(o); } return options; } QStringList Connection::GetPresenceStatusOptionsForUser() const { if (state_ != STATE_OPEN) throw Exception("Connection is not open."); QStringList options; Tp::SimpleStatusSpecMap map = tp_connection_->allowedPresenceStatuses(); for (Tp::SimpleStatusSpecMap::iterator i = map.begin(); i != map.end(); ++i) { QString o = i.key(); if ( o.compare("offline") == 0 || o.compare("unknown") == 0 || o.compare("error") == 0 ) continue; // HACK: Gabble crash if presence status is set to 'offline', 'unknown' or 'error' options.append(o); } return options; } Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const Communication::ContactInterface &contact) { if (state_ != STATE_OPEN) throw Exception("Connection is not open."); //! todo check if there is already open chat session with given contact //! and return that ChatSession* session = new ChatSession(*self_contact_, (Contact&)contact, tp_connection_); private_chat_sessions_.push_back(session); return session; } Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const QString& user_id) { //! @todo IMPLEMENT //! - Request Tp::Contact object from Tp::Connection //! - Create ChatSession object and return it throw Exception("NOT IMPLEMENTED"); } Communication::ChatSessionInterface* Connection::OpenChatSession(const QString &channel_id) { if (state_ != STATE_OPEN) throw Exception("Connection is not open."); ChatSession* session = new ChatSession(channel_id, tp_connection_); public_chat_sessions_.push_back(session); return session; } Communication::VoiceSessionInterface* Connection::OpenVoiceSession(const Communication::ContactInterface &contact) { VoiceSession* session = new VoiceSession(dynamic_cast<Contact const*>(&contact)->GetTpContact()); voice_sessions_.push_back(session); return session; } void Connection::RemoveContact(const Communication::ContactInterface &contact) { const Contact* c = dynamic_cast<const Contact*>(&contact); friend_list_.RemoveContact(c); c->GetTpContact()->removePresencePublication(); c->GetTpContact()->removePresenceSubscription(); emit ContactRemoved(contact); } void Connection::SendFriendRequest(const QString &target, const QString &message) { if (state_ != STATE_OPEN) throw Exception("Connection is not open."); OutgoingFriendRequest* request = new OutgoingFriendRequest(target, message, tp_connection_); sent_friend_requests_.push_back(request); connect(request, SIGNAL( Error(OutgoingFriendRequest*) ), SLOT( OnSendingFriendRequestError(OutgoingFriendRequest*) )); connect(request, SIGNAL( Accepted(OutgoingFriendRequest*) ), SLOT( OnSendingFriendAccepted(OutgoingFriendRequest*) )); connect(request, SIGNAL( Rejected(OutgoingFriendRequest*) ), SLOT( OnSendingFriendRejected(OutgoingFriendRequest*) )); } Communication::FriendRequestVector Connection::GetFriendRequests() const { if (state_ != STATE_OPEN) throw Exception("Connection is not open."); Communication::FriendRequestVector requests; for (FriendRequestVector::const_iterator i = received_friend_requests_.begin(); i != received_friend_requests_.end(); ++i) { requests.push_back(*i); } return requests; } void Connection::SetPresenceStatus(const QString &status) { if (state_ != STATE_OPEN ) throw Exception("Connection is not open."); presence_status_ = status; Tp::PendingOperation* op = tp_connection_->setSelfPresence(presence_status_,presence_message_); //! @todo Check success } void Connection::SetPresenceMessage(const QString &message) { if (state_ != STATE_OPEN ) throw Exception("Connection is not open."); presence_message_ = message; Tp::PendingOperation* op = tp_connection_->setSelfPresence(presence_status_,presence_message_); //! @todo Check success } void Connection::Close() { if ( tp_connection_.isNull() ) return; // nothing to close CloseSessions(); DeleteFriendRequests(); DeleteContacts(); DisconnectSignals(); Tp::PendingOperation* op = tp_connection_->requestDisconnect(); tp_connection_.reset(); } void Connection::DisconnectSignals() { // todo: Check that all signals are disconnected disconnect(tp_connection_->requestConnect(), SIGNAL(finished(Tp::PendingOperation *)), this, SLOT(OnConnectionConnected(Tp::PendingOperation *))); disconnect(tp_connection_.data(), SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)), this, SLOT(OnConnectionInvalidated(Tp::DBusProxy *, const QString &, const QString &))); if (tp_pending_connection_) disconnect(tp_pending_connection_, SIGNAL(finished(Tp::PendingOperation *)), this, SLOT(OnConnectionReady(Tp::PendingOperation *))); disconnect(tp_connection_.data(), SIGNAL( statusChanged(uint , uint) ), this, SLOT( OnConnectionStatusChanged(uint , uint ) ) ); disconnect(tp_connection_.data(), SIGNAL( selfHandleChanged(uint) ), this, SLOT( OnSelfHandleChanged(uint) )); } void Connection::OnConnectionCreated(Tp::PendingOperation *op) { if (op->isError()) { QString error_name = op->errorName(); // == Tp::ConnectionStatusReasonAuthenticationFailed) state_ = STATE_ERROR; reason_ = op->errorMessage(); emit( ConnectionError(*this) ); return; } Tp::PendingConnection *c = qobject_cast<Tp::PendingConnection *>(op); tp_connection_ = c->connection(); QObject::connect(tp_connection_->requestConnect(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(OnConnectionConnected(Tp::PendingOperation *))); QObject::connect(tp_connection_.data(), SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)), SLOT(OnConnectionInvalidated(Tp::DBusProxy *, const QString &, const QString &))); } void Connection::OnConnectionConnected(Tp::PendingOperation *op) { if (op->isError()) { state_ = STATE_ERROR; reason_ = op->errorMessage(); LogError(QString("Cannot established connection to IM server: ").append(reason_).toStdString()); emit( ConnectionError(*this) ); return; } LogDebug("Connection to IM server established successfully."); QStringList interfaces = tp_connection_->interfaces(); QString message = "Interfaces (tp_connection): "; if (interfaces.size() == 0) { message.append(" None"); } else { for(QStringList::iterator i = interfaces.begin(); i != interfaces.end(); ++i) { message.append(" "); message.append(*i); } } LogDebug(message.toStdString()); Tp::Features features; features.insert(Tp::Connection::FeatureCore); features.insert(Tp::Connection::FeatureSelfContact); features.insert(Tp::Connection::FeatureRoster); features.insert(Tp::Connection::FeatureSimplePresence); if ( !tp_connection_->isReady(features) ) { QString message = "Establishing connection to IM server. Waiting for these features: "; if ( !tp_connection_->isReady(Tp::Connection::FeatureSimplePresence) ) message.append("SimplePresence"); if ( !tp_connection_->isReady(Tp::Connection::FeatureRoster) ) message.append(", Roster"); if ( !tp_connection_->isReady(Tp::Connection::FeatureSelfContact) ) message.append(", SelfContact"); if ( !tp_connection_->isReady(Tp::Connection::FeatureCore) ) message.append(", Core"); LogDebug(message.toStdString()); } if (tp_connection_->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CAPABILITIES)) { Tp::CapabilityPair capability = { TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA, Tp::ChannelMediaCapabilityAudio | Tp::ChannelMediaCapabilityVideo | Tp::ChannelMediaCapabilityNATTraversalSTUN | // Tp::ChannelMediaCapabilityNATTraversalICEUDP | // added 15.12.2009 mattiku Tp::ChannelMediaCapabilityNATTraversalGTalkP2P }; tp_connection_->capabilitiesInterface()->AdvertiseCapabilities( Tp::CapabilityPairList() << capability, QStringList()); LogDebug("Advertising capabilities."); } else { LogWarning("Capabilities interface is not supported!"); } if( tp_connection_->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS) ) QObject::connect(tp_connection_->requestsInterface(), SIGNAL( NewChannels(const Tp::ChannelDetailsList&) ), SLOT( OnNewChannels(const Tp::ChannelDetailsList&) )); else LogWarning("Requests interface is not supported!"); tp_pending_connection_ = tp_connection_->becomeReady(features); connect(tp_pending_connection_, SIGNAL( finished(Tp::PendingOperation *) ), SLOT( OnConnectionReady(Tp::PendingOperation *) )); connect(tp_connection_.data(), SIGNAL( statusChanged(uint , uint) ), SLOT( OnConnectionStatusChanged(uint , uint ) )); connect(tp_connection_.data(), SIGNAL( selfHandleChanged(uint) ), SLOT( OnSelfHandleChanged(uint) )); } void Connection::OnConnectionReady(Tp::PendingOperation *op) { tp_pending_connection_ = 0; if (state_ == STATE_CLOSED) return; if (op->isError()) { state_ = STATE_ERROR; reason_ = op->errorMessage(); LogError(QString("Connection establision failed: ").append(reason_).toStdString()); emit( ConnectionError(*this) ); return; } if (!tp_connection_->isReady( tp_connection_->requestedFeatures() )) { state_ = STATE_ERROR; reason_ = "Cannot get all requested connection features."; LogDebug(QString("Login to IM server failed: ").append(reason_).toStdString()); emit ConnectionError(*this); return; } else LogDebug("Login to IM server successed."); self_contact_ = new Contact(tp_connection_->selfContact()); connect(tp_connection_.data(), SIGNAL( statusChanged(uint, uint) ), SLOT( OnTpConnectionStatusChanged(uint, uint) )); connect(tp_connection_->contactManager(), SIGNAL( presencePublicationRequested(const Tp::Contacts &) ), SLOT( OnPresencePublicationRequested(const Tp::Contacts &) )); connect(tp_connection_->contactManager(), SIGNAL( groupMembersChanged(const QString &, const Tp::Contacts &, const Tp::Contacts &) ), SLOT( OnGroupMembersChanged(const QString &, const Tp::Contacts &, const Tp::Contacts &) )); ContactVector new_contacts = HandleAllKnownTpContacts(); for (ContactVector::iterator i = new_contacts.begin(); i != new_contacts.end(); ++i) { Contact* c = *i; contacts_.push_back(c); friend_list_.AddContact(c); } if (tp_connection_.isNull() || tp_connection_->selfContact().isNull()) { LogError("Selfcontact is NULL"); presence_status_ = ""; presence_message_ = ""; state_ = STATE_ERROR; reason_ = "Cannot get all self contact object."; LogDebug(QString("Login to IM server failed: ").append(reason_).toStdString()); emit ConnectionError(*this); return; } else { presence_status_ = tp_connection_->selfContact()->presenceStatus(); presence_message_ = tp_connection_->selfContact()->presenceMessage(); } state_ = STATE_OPEN; emit( ConnectionReady(*this) ); } void Connection::OnTpConnectionStatusChanged(uint new_status, uint reason) { // todo: IMPLEMENT switch (new_status) { case Tp::Connection::StatusConnected: break; case Tp::Connection::StatusUnknown: break; case Tp::Connection::StatusDisconnected: break; case Tp::Connection::StatusConnecting: break; } } ContactVector Connection::HandleAllKnownTpContacts() { ContactVector new_contacts; //! Check every known telepathy contact and determinate their nature by state of subscribtionState and publistState values //! Combinations are: //! subscription: publish: //! - Normal contact YES YES //! - friend request (sended) //! - friend request (received) ASK YES //! - banned contact NO * //! - unknow (all the other combinations) foreach (const Tp::ContactPtr &tp_contact, tp_connection_->contactManager()->allKnownContacts()) { switch ( tp_contact->subscriptionState() ) { case Tp::Contact::PresenceStateNo: // The user doesn't subscribe presence status of this contact switch ( tp_contact->publishState() ) { case Tp::Contact::PresenceStateAsk: //! Open situation, we do nothing { FriendRequest* request = new FriendRequest(tp_contact); received_friend_requests_.push_back(request); pending_friend_requests_.append(request); emit FriendRequestReceived(*request); } break; case Tp::Contact::PresenceStateYes: //! Contact have published the presence status break; case Tp::Contact::PresenceStateNo: //! Contact have denied to publish presence status break; } break; case Tp::Contact::PresenceStateYes: { // A friend list item switch ( tp_contact->publishState() ) { case Tp::Contact::PresenceStateNo: { //! We have subsribed presence status of this contact //! but we have not published our own presence! //! -> We unsubsribe this contact tp_contact->removePresenceSubscription(); } break; case Tp::Contact::PresenceStateYes: { //! This is a normal friendship state, both the user and the contact have subsribed each others //! presence statuses. Contact* contact = GetContact(tp_contact); if (contact == 0) { //QSet<Tp::Contact::Feature> features; //features << Tp::Contact::FeatureAlias; //features << Tp::Contact::FeatureAvatarToken; //features << Tp::Contact::FeatureSimplePresence; contact = new Contact(tp_contact); new_contacts.push_back(contact); } break; } case Tp::Contact::PresenceStateAsk: //! We have subscribed presence of this contact //! but we don't publish our? //! Publicity level should be same to the both directions Tp::PendingOperation* op = tp_contact->authorizePresencePublication(""); connect(op, SIGNAL( finished(Tp::PendingOperation*) ), SLOT( PresencePublicationFinished(Tp::PendingOperation*) )); //Contact* contact = GetContact(tp_contact); //if (contact == 0) //{ // contact = new Contact(tp_contact); // new_contacts.push_back(contact); //} //new_contacts.push_back(&contact); break; } } break; case Tp::Contact::PresenceStateAsk: //! The user have not yet decided if (s)he wants to subscribe presence of this contact //! { switch ( tp_contact->publishState() ) { case Tp::Contact::PresenceStateAsk: //! Open situation, we do nothing break; case Tp::Contact::PresenceStateYes: //! Contact have published the presence status break; case Tp::Contact::PresenceStateNo: //! Contact have denied to publish presence status break; } // User have not yet made the decision to accept or reject presence subscription // So we create a FriendRequest obeject FriendRequest* request = new FriendRequest(tp_contact); received_friend_requests_.push_back(request); emit FriendRequestReceived(*request); } break; } } return new_contacts; } void Connection::OnNewChannels(const Tp::ChannelDetailsList& channels) { if (state_ == STATE_CLOSED) return; foreach (const Tp::ChannelDetails &details, channels) { QString channelType = details.properties.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString(); bool requested = details.properties.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Requested")).toBool(); if (channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT && !requested) { //! todo check if there is already open chat session with given contact //! and return that LogDebug("Text chat request received."); Tp::TextChannelPtr tp_text_channel = Tp::TextChannel::create(tp_connection_, details.channel.path(), details.properties); LogDebug("Text channel object created."); ChatSession* session = new ChatSession(*self_contact_, tp_text_channel); private_chat_sessions_.push_back(session); connect(session, SIGNAL( Ready(ChatSession*) ), SLOT( IncomingChatSessionReady(ChatSession*) )); } if (channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_LIST && !requested) { LogDebug("Contact list channel"); //TextChannelPtr tp_text_channel = Tp::TextChannel::create(tp_connection_, details.channel.path(), details.properties); } if (channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA && !requested) { LogDebug("Voice chat request received."); Tp::StreamedMediaChannelPtr tp_streamed_media_channel = Tp::StreamedMediaChannel::create(tp_connection_, details.channel.path(), details.properties); if ( !tp_streamed_media_channel->initiatorContact().isNull() ) { Contact* initiator = GetContact(tp_streamed_media_channel->initiatorContact()); //! @todo get the actual contact object VoiceSession* session = new VoiceSession(tp_streamed_media_channel); voice_sessions_.push_back(session); //emit( VoiceSessionReceived(*session) ); connect(session, SIGNAL( Ready(ChatSession*) ), SLOT( IncomingVoiceSessionReady(VoiceSession*) )); } else { Contact* null_contact = new Contact(tp_streamed_media_channel->initiatorContact()); // we don't have the contact! VoiceSession* session = new VoiceSession(tp_streamed_media_channel); connect(session, SIGNAL( Ready(VoiceSession*) ), SLOT( IncomingVoiceSessionReady(VoiceSession*) )); voice_sessions_.push_back(session); //emit( VoiceSessionReceived(*session) ); } } } } void Connection::OnConnectionInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage) { //! We don't have to report about error here. //! OnConnectionReady() will be called after this with error information state_ = STATE_ERROR; reason_ = errorMessage; emit( ConnectionError(*this) ); } void Connection::OnConnectionClosed(Tp::PendingOperation *op) { state_ = STATE_CLOSED; emit( ConnectionClosed(*this) ); } void Connection::OnPresencePublicationRequested(const Tp::Contacts &contacts) { for (Tp::Contacts::const_iterator i = contacts.begin(); i != contacts.end(); ++i) { Tp::ContactPtr c = *i; LogDebug(QString("Presence publication request from ").append(c->id()).toStdString()); if ( c->subscriptionState() == Tp::Contact::PresenceStateNo ) { FriendRequest* friend_request = new FriendRequest(c); connect(friend_request, SIGNAL( Accepted(FriendRequest*) ), SLOT( IncomingFriendRequestAccepted(FriendRequest*) )); received_friend_requests_.push_back(friend_request); emit FriendRequestReceived(*friend_request); return; } if ( c->subscriptionState() == Tp::Contact::PresenceStateYes && c->publishState() == Tp::Contact::PresenceStateAsk ) { c->authorizePresencePublication(); Contact* contact = new Contact(c); contacts_.push_back(contact); friend_list_.AddContact(contact); emit FriendRequestAccepted(contact->GetID()); emit NewContact(*contact); return; } if ( c->subscriptionState() == Tp::Contact::PresenceStateYes && c->publishState() == Tp::Contact::PresenceStateNo ) { LogDebug(QString("User have already rejected this contact so we ignore this request.").toStdString()); return; } Tp::Contact::PresenceState state1 = c->subscriptionState(); Tp::Contact::PresenceState state2 = c->publishState(); } } Contact* Connection::GetContact(Tp::ContactPtr tp_contact) { for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i) { Contact* c = *i; if (c->GetID().compare(tp_contact->id()) == 0) return c; } return 0; } void Connection::OnSendingFriendRequestError(OutgoingFriendRequest* request) { QString message = "Cannot send a friend request to "; LogError(message.toStdString()); } void Connection::IncomingChatSessionReady(ChatSession* session) { emit( ChatSessionReceived(*session) ); } void Connection::IncomingFriendRequestAccepted(FriendRequest *request) { ContactVector new_contacts = HandleAllKnownTpContacts(); for (ContactVector::iterator i = new_contacts.begin(); i != new_contacts.end(); ++i) { Contact* c = *i; contacts_.push_back(c); friend_list_.AddContact(c); emit NewContact(*c); } } void Connection::PresencePublicationFinished(Tp::PendingOperation* op) { ContactVector new_contacts = HandleAllKnownTpContacts(); for (ContactVector::iterator i = new_contacts.begin(); i != new_contacts.end(); ++i) { Contact* c = *i; contacts_.push_back(c); friend_list_.AddContact(c); emit NewContact(*c); } } void Connection::AddContact(Contact* contact) { contacts_.push_back(contact); friend_list_.AddContact(contact); connect(contact, SIGNAL( PresenceSubscriptionCanceled(Contact*) ), SLOT( OnPresenceSubscriptionCanceled(Contact* ) )); } void Connection::OnPresenceSubscriptionCanceled(Contact* contact) { //! We remove the contact just from friend list //! Actual contact object is deleted at deconstructor of connection object friend_list_.RemoveContact(contact); emit ContactRemoved(*contact); } void Connection::IncomingVoiceSessionReady(VoiceSession *session) { emit( VoiceSessionReceived(*session) ); } void Connection::OnConnectionStatusChanged(uint status, uint reason) { // TODO: IMPLEMENT } void Connection::OnSelfHandleChanged(uint handle) { // TODO: IMPLEMENT } void Connection::OnSendingFriendAccepted(OutgoingFriendRequest* request) { TelepathyIM::Contact* c = request->GetContact(); Contact* contact = new Contact(c->GetTpContact()); for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i) { Contact* vc = *i; if (vc->GetID().compare(contact->GetID()) == 0) { return; } } contacts_.push_back(contact); emit NewContact(*contact); } void Connection::OnSendingFriendRejected(OutgoingFriendRequest* request) { // TODO: IMPLEMENT } void Connection::OnGroupMembersChanged(const QString &group, const Tp::Contacts &groupMembersAdded, const Tp::Contacts &groupMembersRemoved) { // TODO: IMPLEMENT } void Connection::CheckPendingFriendRequests() { foreach (FriendRequest *request, pending_friend_requests_) emit FriendRequestReceived(*request); pending_friend_requests_.clear(); } } // end of namespace: TelepathyIM
536d07d306ac7367b1a018dd5cda65e76bf30761
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/SOC/2007/graphs/libs/graph/test/runtime/io.hpp
858b4a337cf00fadaa9020f7728630125472c3d2
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
4,058
hpp
io.hpp
// (C) Copyright Andrew Sutton 2007 // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0 (See accompanying file // LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <boost/graph/properties.hpp> template <typename V, typename G> struct vertex_printer { vertex_printer(V v, const G& g) : vert(v), graph(g) { } V vert; const G& graph; }; template <typename V, typename G> inline vertex_printer<V,G> print_vertex(V v, const G& g) { return vertex_printer<V,G>(v, g); } template <typename V, typename G> inline std::ostream& operator << (std::ostream& os, const vertex_printer<V, G>& vp) { os << boost::get(boost::vertex_index, vp.graph, vp.vert); return os; } template <typename E, typename G> struct edge_printer { edge_printer(E e, const G& g) : edge(e), graph(g) { } E edge; const G& graph; }; template <typename E, typename G> inline edge_printer<E,G> print_edge(E e, const G& g) { return edge_printer<E,G>(e, g); } template <typename E, typename G> inline std::ostream& operator <<(std::ostream& os, const edge_printer<E,G>& ep) { os << "(" << print_vertex(source(ep.edge, ep.graph), ep.graph) << "," << print_vertex(target(ep.edge, ep.graph), ep.graph) << ")"; return os; } template <typename P, typename G> struct path_printer { path_printer(const P& p, const G& g) : path(p), graph(g) { } P path; const G& graph; }; template <typename P, typename G> inline path_printer<P,G> print_path(const P& p, const G& g) { return path_printer<P,G>(p, g); } template <typename P, typename G> inline std::ostream& operator <<(std::ostream& os, const path_printer<P,G>& pp) { typename P::const_iterator i, end = pp.path.end(); for(i = pp.path.begin(); i != end; ++i) { os << print_vertex(*i, pp.graph) << " "; } return os; } template <typename M, typename G> struct vertex_map_printer { vertex_map_printer(M m, const G& g) : map(m), graph(g) { } M map; const G& graph; }; template <typename M, typename G> inline vertex_map_printer<M,G> print_vertex_map(const M& m, const G& g) { return vertex_map_printer<M,G>(m, g); } template <typename M, typename G> inline std::ostream& operator <<(std::ostream& os, const vertex_map_printer<M,G>& mp) { typename boost::graph_traits<G>::vertex_iterator i, end; os << "{\n"; for(tie(i, end) = boost::vertices(mp.graph); i != end; ++i) { os << print_vertex(*i, mp.graph) << ": " << mp.map[*i] << "\n"; } os << "}\n"; return os; } template <typename M, typename G> struct edge_map_printer { edge_map_printer(M m, const G& g) : map(m), graph(g) { } M map; const G& graph; }; template <typename M, typename G> inline edge_map_printer<M,G> print_edge_map(const M& m, const G& g) { return edge_map_printer<M,G>(m, g); } template <typename M, typename G> inline std::ostream& operator <<(std::ostream& os, const edge_map_printer<M,G>& mp) { typename boost::graph_traits<G>::edge_iterator i, end; os << "{\n"; for(tie(i, end) = boost::edges(mp.graph); i != end; ++i) { os << print_edge(*i, mp.graph) << mp.map[*i] << "\n"; } os << "}\n"; return os; } template <typename M, typename G> struct vertex_matrix_printer { vertex_matrix_printer(const M& m, const G& g) : matrix(m), graph(g) { } const M& matrix; const G& graph; }; template <typename M, typename G> inline vertex_matrix_printer<M,G> print_vertex_matrix(const M& m, const G& g) { return vertex_matrix_printer<M,G>(m, g); } template <typename M, typename G> inline std::ostream& operator <<(std::ostream& os, const vertex_matrix_printer<M,G>& mp) { typename boost::graph_traits<G>::vertex_iterator i, j, end; os << "{\n"; for(tie(i, end) = boost::vertices(mp.graph); i != end; ++i) { os << "{ "; for(j = boost::vertices(mp.graph).first; j != end; ++j) { os << mp.matrix[*i][*j] << " "; } os << "}\n"; } os << "}\n"; return os; }
b2cf6e6bcf0b6eb6645fc8dac2e4547ebf77aaac
147509bf421099186f7dd673e9ee69a98d0b878c
/src/M5-13.cpp
ecc2e3fe636fc08e10bb4f70294fffd917cfac6b
[]
no_license
merlyescalona/indelible-ngsphy
32a77986ba1970424046dabe7d9b69d8e8116e52
59e0477b18dd3946a56c8c4967e1dc045310d3ba
refs/heads/master
2021-01-15T22:46:35.842954
2020-11-27T19:21:59
2020-11-27T19:21:59
99,913,444
2
0
null
null
null
null
UTF-8
C++
false
false
49,272
cpp
M5-13.cpp
/* INDELible V1.03 "A comprehensive and flexible simulator of molecular sequence evolution" Copyright (C) 2009 William Fletcher If using this software please cite the following reference: Fletcher, W. and Yang, Z. 2009. "INDELible: a flexible simulator of biological sequence evolution." Mol. Biol. and Evol. (in press). If you need to contact me with any queries, questions, problems or (god-forbid) bugs then please go to http://abacus.gene.ucl.ac.uk/software/indelible/bug.php This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Please visit http://www.gnu.org/licenses/ for a full copy of the license. */ #include <math.h> #include <string> #include <sstream> #include <vector> #include "float.h" #include <iostream> #include <fstream> #include <time.h> #include <string> using namespace std; /* //script to calculate discrete M3 values for M4 to M13 5 gamma 2: alpha, beta 6 2gamma 4: p0, alpha1,beta1, alpha2=beta2 7 beta 2: p_beta, q_beta 8 beta&w 4: p0, p_beta, q_beta, w estimated 9 beta&gamma 5: p0, p_beta, q_beta, alpha, beta 10 beta&1+gamma 5: p0, p_beta, q_beta, alpha, beta (1+gamma used) 11 beta&1>normal 5: p0, p_beta, q_beta, mu, s (normal truncated w>1) 12 0&2normal 5: p0, p1, mu2, s1, s2 13 3normal 6: p0, p1, mu2, s0, s1, s2 14 M8a:beta&w=1 3: p0, p_beta, q_beta, w=1 fixed 15 M8a:beta&w>=1 4: p0, p_beta, q_beta, w>=1 estimated */ ///////////////////////////////////////////////////////////////////////////////////////////////////// // code below is to do with codon models discrete rates... used by scipting function to set up M3 ///////////////////////////////////////////////////////////////////////////////////////////////////// const int NSnneutral=1; const int NSpselection=2; const int NSdiscrete=3; const int NSfreqs=4; const int NSgamma=5; const int NS2gamma=6; const int NSbeta=7; const int NSbetaw=8; const int NSbetagamma=9; const int NSbeta1gamma=10; const int NSbeta1normal=11; const int NS02normal=12; const int NS3normal=13; int LASTROUND; void error2 (char * message) { printf("\nError: %s.\n", message); exit(-1); } #define FOR(i,n) for(i=0; i<n; i++) #define square(a) ((a)*(a)) #define min2(a,b) ((a)<(b)?(a):(b)) #define max2(a,b) ((a)>(b)?(a):(b)) #define NS 5000 #define NBRANCH (NS*2-2) #define MAXNSONS 20 #define LSPNAME 50 #define NCODE 64 #define NCATG 40 #define FPN(file) fputc('\n', file) #define F0 stdout double LnGamma (double alpha); double IncompleteGamma (double x, double alpha, double ln_gamma_alpha); double PointNormal (double prob); double PointChi2 (double prob, double v); struct CommonInfo { char *z[2*NS-1], spname[NS][LSPNAME+1], daafile[96], cleandata, readpattern; int ns, ls, npatt, np, ntime, ncode, clock, rooted, model, icode; int seqtype, *pose, ncatG, NSsites, fix_omega; double *fpatt, kappa, omega, alpha, pi[64], *conP, daa[20*20]; double freqK[NCATG], rK[NCATG]; char *siteID; /* used if ncatG>1 */ double *siterates, omega_fix; /* rates for gamma or omega for site or branch-site models */ double *omegaBS, *QfactorBS; /* omega IDs for branch-site models */ } com; double CDFNormal (double x) { // Hill ID (1973) The normal integral. Applied Statistics, 22:424-427. // Algorithm AS 66. // adapted by Z. Yang, March 1994. Hill's routine is quite bad, and I // haven't consulted // Adams AG (1969) Algorithm 39. Areas under the normal curve. // Computer J. 12: 197-198. int invers=0; double p, limit=10, t=1.28, y=x*x/2; if (x<0) { invers=1; x*=-1; } if (x>limit) return (invers?0:1); if (x<1.28) p = .5 - x * ( .398942280444 - .399903438504 * y /(y + 5.75885480458 - 29.8213557808 /(y + 2.62433121679 + 48.6959930692 /(y + 5.92885724438)))); else p = 0.398942280385 * exp(-y) / (x - 3.8052e-8 + 1.00000615302 / (x + 3.98064794e-4 + 1.98615381364 / (x - 0.151679116635 + 5.29330324926 / (x + 4.8385912808 - 15.1508972451 / (x + 0.742380924027 + 30.789933034 / (x + 3.99019417011)))))); return invers ? p : 1-p; } double LnGamma (double alpha) { // returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places. // Stirling's formula is used for the central polynomial part of the procedure. // Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function. // Communications of the Association for Computing Machinery, 9:684 double x=alpha, f=0, z; if (x<7) { f=1; z=x-1; while (++z<7) f*=z; x=z; f=-log(f); } z = 1/(x*x); return f + (x-0.5)*log(x) - x + .918938533204673 + (((-.000595238095238*z+.000793650793651)*z-.002777777777778)*z +.083333333333333)/x; } double LnGammaFunction (double alpha) { /* returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places. Stirling's formula is used for the central polynomial part of the procedure. Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function. Communications of the Association for Computing Machinery, 9:684 */ double x=alpha, f=0, z; if (x<7) { f=1; z=x-1; while (++z<7) f*=z; x=z; f=-log(f); } z = 1/(x*x); return f + (x-0.5)*log(x) - x + .918938533204673 + (((-.000595238095238*z+.000793650793651)*z-.002777777777778)*z +.083333333333333)/x; } double IncompleteGamma (double x, double alpha, double ln_gamma_alpha) { /* returns the incomplete gamma ratio I(x,alpha) where x is the upper limit of the integration and alpha is the shape parameter. returns (-1) if in error ln_gamma_alpha = ln(Gamma(alpha)), is almost redundant. (1) series expansion if (alpha>x || x<=1) (2) continued fraction otherwise RATNEST FORTRAN by Bhattacharjee GP (1970) The incomplete gamma integral. Applied Statistics, 19: 285-287 (AS32) */ int i; double p=alpha, g=ln_gamma_alpha; double accurate=1e-8, overflow=1e30; double factor, gin=0, rn=0, a=0,b=0,an=0,dif=0, term=0, pn[6]; if (x==0) return (0); if (x<0 || p<=0) return (-1); factor=exp(p*log(x)-x-g); if (x>1 && x>=p) goto l30; /* (1) series expansion */ gin=1; term=1; rn=p; l20: rn++; term*=x/rn; gin+=term; if (term > accurate) goto l20; gin*=factor/p; goto l50; l30: /* (2) continued fraction */ a=1-p; b=a+x+1; term=0; pn[0]=1; pn[1]=x; pn[2]=x+1; pn[3]=x*b; gin=pn[2]/pn[3]; l32: a++; b+=2; term++; an=a*term; for (i=0; i<2; i++) pn[i+4]=b*pn[i+2]-an*pn[i]; if (pn[5] == 0) goto l35; rn=pn[4]/pn[5]; dif=fabs(gin-rn); if (dif>accurate) goto l34; if (dif<=accurate*rn) goto l42; l34: gin=rn; l35: for (i=0; i<4; i++) pn[i]=pn[i+2]; if (fabs(pn[4]) < overflow) goto l32; for (i=0; i<4; i++) pn[i]/=overflow; goto l32; l42: gin=1-factor*gin; l50: return (gin); } /* functions concerning the CDF and percentage points of the gamma and Chi2 distribution */ double PointNormal (double prob) { /* returns z so that Prob{x<z}=prob where x ~ N(0,1) and (1e-12)<prob<1-(1e-12) returns (-9999) if in error Odeh RE & Evans JO (1974) The percentage points of the normal distribution. Applied Statistics 22: 96-97 (AS70) Newer methods: Wichura MJ (1988) Algorithm AS 241: the percentage points of the normal distribution. 37: 477-484. Beasley JD & Springer SG (1977). Algorithm AS 111: the percentage points of the normal distribution. 26: 118-121. */ double a0=-.322232431088, a1=-1, a2=-.342242088547, a3=-.0204231210245; double a4=-.453642210148e-4, b0=.0993484626060, b1=.588581570495; double b2=.531103462366, b3=.103537752850, b4=.0038560700634; double y, z=0, p=prob, p1; p1 = (p<0.5 ? p : 1-p); if (p1<1e-20) return (-9999); y = sqrt (log(1/(p1*p1))); z = y + ((((y*a4+a3)*y+a2)*y+a1)*y+a0) / ((((y*b4+b3)*y+b2)*y+b1)*y+b0); return (p<0.5 ? -z : z); } double PointChi2 (double prob, double v) { /* returns z so that Prob{x<z}=prob where x is Chi2 distributed with df=v returns -1 if in error. 0.000002<prob<0.999998 RATNEST FORTRAN by Best DJ & Roberts DE (1975) The percentage points of the Chi2 distribution. Applied Statistics 24: 385-388. (AS91) Converted into C by Ziheng Yang, Oct. 1993. */ double e=.5e-6, aa=.6931471805, p=prob, g; double xx, c, ch, a=0,q=0,p1=0,p2=0,t=0,x=0,b=0,s1,s2,s3,s4,s5,s6; if (p<.000002 || p>.999998 || v<=0) return (-1); g = LnGamma (v/2); xx=v/2; c=xx-1; if (v >= -1.24*log(p)) goto l1; ch=pow((p*xx*exp(g+xx*aa)), 1/xx); if (ch-e<0) return (ch); goto l4; l1: if (v>.32) goto l3; ch=0.4; a=log(1-p); l2: q=ch; p1=1+ch*(4.67+ch); p2=ch*(6.73+ch*(6.66+ch)); t=-0.5+(4.67+2*ch)/p1 - (6.73+ch*(13.32+3*ch))/p2; ch-=(1-exp(a+g+.5*ch+c*aa)*p2/p1)/t; if (fabs(q/ch-1)-.01 <= 0) goto l4; else goto l2; l3: x=PointNormal (p); p1=0.222222/v; ch=v*pow((x*sqrt(p1)+1-p1), 3.0); if (ch>2.2*v+6) ch=-2*(log(1-p)-c*log(.5*ch)+g); l4: q=ch; p1=.5*ch; if ((t=IncompleteGamma (p1, xx, g))<0) { return (-1); } p2=p-t; t=p2*exp(xx*aa+g+p1-c*log(ch)); b=t/ch; a=0.5*t-b*c; s1=(210+a*(140+a*(105+a*(84+a*(70+60*a))))) / 420; s2=(420+a*(735+a*(966+a*(1141+1278*a))))/2520; s3=(210+a*(462+a*(707+932*a)))/2520; s4=(252+a*(672+1182*a)+c*(294+a*(889+1740*a)))/5040; s5=(84+264*a+c*(175+606*a))/2520; s6=(120+c*(346+127*c))/5040; ch+=t*(1+0.5*t*s1-b*c*(s1-b*(s2-b*(s3-b*(s4-b*(s5-b*s6)))))); if (fabs(q/ch-1) > e) goto l4; return (ch); } #define PointGamma(prob,alpha,beta) PointChi2(prob,2.0*(alpha))/(2.0*(beta)) double PDFBeta(double x, double p, double q) { /* Returns pdf of beta(p,q) */ double y, small=1e-20; if(x<small || x>1-small) error2("bad x in PDFbeta"); y = (p-1)*log(x) + (q-1)*log(1-x); y-= LnGamma(p)+LnGamma(q)-LnGamma(p+q); return(exp(y)); } double CDFBeta(double x, double pin, double qin, double lnbeta) { /* Returns distribution function of the standard form of the beta distribution, that is, the incomplete beta ratio I_x(p,q). lnbeta is log of the complete beta function; provide it if known, and otherwise use 0. This is called from InverseCDFBeta() in a root-finding loop. This routine is a translation into C of a Fortran subroutine by W. Fullerton of Los Alamos Scientific Laboratory. Bosten and Battiste (1974). Remark on Algorithm 179, CACM 17, p153, (1974). */ double ans, c, finsum, p, ps, p1, q, term, xb, xi, y, small=1e-15; int n, i, ib; static double eps = 0, alneps = 0, sml = 0, alnsml = 0; if(x<small) return 0; else if(x>1-small) return 1; if(pin<=0 || qin<=0) { printf("p=%.4f q=%.4f: parameter outside range in CDFBeta",pin,qin); return (-1); } if (eps == 0) {/* initialize machine constants ONCE */ eps = pow((double)FLT_RADIX, -(double)DBL_MANT_DIG); alneps = log(eps); sml = DBL_MIN; alnsml = log(sml); } y = x; p = pin; q = qin; /* swap tails if x is greater than the mean */ if (p / (p + q) < x) { y = 1 - y; p = qin; q = pin; } if(lnbeta==0) lnbeta=LnGamma(p)+LnGamma(q)-LnGamma(p+q); if ((p + q) * y / (p + 1) < eps) { /* tail approximation */ ans = 0; xb = p * log(max2(y, sml)) - log(p) - lnbeta; if (xb > alnsml && y != 0) ans = exp(xb); if (y != x || p != pin) ans = 1 - ans; } else { /* evaluate the infinite sum first. term will equal */ /* y^p / beta(ps, p) * (1 - ps)-sub-i * y^i / fac(i) */ ps = q - floor(q); if (ps == 0) ps = 1; xb=LnGamma(ps)+LnGamma(p)-LnGamma(ps+p); xb = p * log(y) - xb - log(p); ans = 0; if (xb >= alnsml) { ans = exp(xb); term = ans * p; if (ps != 1) { n = (int)max2(alneps/log(y), 4.0); for(i=1 ; i<= n ; i++) { xi = i; term = term * (xi - ps) * y / xi; ans = ans + term / (p + xi); } } } /* evaluate the finite sum. */ if (q > 1) { xb = p * log(y) + q * log(1 - y) - lnbeta - log(q); ib = (int) (xb/alnsml); if(ib<0) ib=0; term = exp(xb - ib * alnsml); c = 1 / (1 - y); p1 = q * c / (p + q - 1); finsum = 0; n = (int) q; if (q == (double)n) n = n - 1; for(i=1 ; i<=n ; i++) { if (p1 <= 1 && term / eps <= finsum) break; xi = i; term = (q - xi + 1) * c * term / (p + q - xi); if (term > 1) { ib = ib - 1; term = term * sml; } if (ib == 0) finsum = finsum + term; } ans = ans + finsum; } if (y != x || p != pin) ans = 1 - ans; if(ans>1) ans=1; if(ans<0) ans=0; } return ans; } double InverseCDFBeta(double prob, double p, double q, double lnbeta) { /* This calculates the inverseCDF of the beta distribution Cran, G. W., K. J. Martin and G. E. Thomas (1977). Remark AS R19 and Algorithm AS 109, Applied Statistics, 26(1), 111-114. Remark AS R83 (v.39, 309-310) and correction (v.40(1) p.236). My own implementation of the algorithm did not bracket the variable well. This version is Adpated from the pbeta and qbeta routines from "R : A Computer Language for Statistical Data Analysis". It fails for extreme values of p and q as well, although it seems better than my previous version. Ziheng Yang, May 2001 */ double fpu=3e-308, acu_min=1e-300, lower=fpu, upper=1-2.22e-16; /* acu_min>= fpu: Minimal value for accuracy 'acu' which will depend on (a,p); */ int swap_tail, i_pb, i_inn, niterations=2000; double a, adj, g, h, pp, prev=0, qq, r, s, t, tx=0, w, y, yprev; double acu, xinbta; if(prob<0 || prob>1 || p<0 || q<0) error2("out of range in InverseCDFBeta"); /* define accuracy and initialize */ xinbta = prob; /* test for admissibility of parameters */ if(p<0 || q<0 || prob<0 || prob>1) error2("beta par err"); if (prob == 0 || prob == 1) return prob; if(lnbeta==0) lnbeta=LnGamma(p)+LnGamma(q)-LnGamma(p+q); /* change tail if necessary; afterwards 0 < a <= 1/2 */ if (prob <= 0.5) { a = prob; pp = p; qq = q; swap_tail = 0; } else { a = 1. - prob; pp = q; qq = p; swap_tail = 1; } /* calculate the initial approximation */ r = sqrt(-log(a * a)); y = r - (2.30753+0.27061*r)/(1.+ (0.99229+0.04481*r) * r); if (pp > 1. && qq > 1.) { r = (y * y - 3.) / 6.; s = 1. / (pp*2. - 1.); t = 1. / (qq*2. - 1.); h = 2. / (s + t); w = y * sqrt(h + r) / h - (t - s) * (r + 5./6. - 2./(3.*h)); xinbta = pp / (pp + qq * exp(w + w)); } else { r = qq*2.; t = 1. / (9. * qq); t = r * pow(1. - t + y * sqrt(t), 3.); if (t <= 0.) xinbta = 1. - exp((log((1. - a) * qq) + lnbeta) / qq); else { t = (4.*pp + r - 2.) / t; if (t <= 1.) xinbta = exp((log(a * pp) + lnbeta) / pp); else xinbta = 1. - 2./(t+1.); } } /* solve for x by a modified newton-raphson method, using CDFBeta */ r = 1. - pp; t = 1. - qq; yprev = 0.; adj = 1.; /* Changes made by Ziheng to fix a bug in qbeta() qbeta(0.25, 0.143891, 0.05) = 3e-308 wrong (correct value is 0.457227) */ if(xinbta<=lower || xinbta>=upper) xinbta=(a+.5)/2; /* Desired accuracy should depend on (a,p) * This is from Remark .. on AS 109, adapted. * However, it's not clear if this is "optimal" for IEEE double prec. * acu = fmax2(acu_min, pow(10., -25. - 5./(pp * pp) - 1./(a * a))); * NEW: 'acu' accuracy NOT for squared adjustment, but simple; * ---- i.e., "new acu" = sqrt(old acu) */ acu = pow(10., -13. - 2.5/(pp * pp) - 0.5/(a * a)); acu = max2(acu, acu_min); for (i_pb=0; i_pb<niterations; i_pb++) { y = CDFBeta(xinbta, pp, qq, lnbeta); y = (y - a) * exp(lnbeta + r * log(xinbta) + t * log(1. - xinbta)); if (y * yprev <= 0) prev = max2(fabs(adj),fpu); for (i_inn=0,g=1; i_inn<niterations; i_inn++) { adj = g * y; if (fabs(adj) < prev) { tx = xinbta - adj; /* trial new x */ if (tx >= 0. && tx <= 1.) { if (prev <= acu || fabs(y) <= acu) goto L_converged; if (tx != 0. && tx != 1.) break; } } g /= 3.; } if (fabs(tx-xinbta)<fpu) goto L_converged; xinbta = tx; yprev = y; } // if(!PAML_RELEASE) // printf("\nInverseCDFBeta(%.2f, %.5f, %.5f) = %.6e\t%d rounds\n", // prob,p,q, (swap_tail ? 1. - xinbta : xinbta), niterations); L_converged: return (swap_tail ? 1. - xinbta : xinbta); } double LineSearch (double(*fun)(double x),double *f,double *x0,double xb[2],double step, double e) { /* linear search using quadratic interpolation From Wolfe M. A. 1978. Numerical methods for unconstrained optimization: An introduction. Van Nostrand Reinhold Company, New York. pp. 62-73. step is used to find the bracket (a1,a2,a3) This is the same routine as LineSearch2(), but I have not got time to test and improve it properly. Ziheng note, September, 2002 */ int ii=0, maxround=100, i; double factor=2, step1, percentUse=0; double a0,a1,a2,a3,a4=-1,a5,a6, f0,f1,f2,f3,f4=-1,f5,f6; /* find a bracket (a1,a2,a3) with function values (f1,f2,f3) so that a1<a2<a3 and f2<f1 and f2<f3 */ if(step<=0) return(*x0); a0=a1=a2=a3=f0=f1=f2=f3=-1; if(*x0<xb[0]||*x0>xb[1]) error2("err LineSearch: x0 out of range"); f2=f0=fun(a2=a0=*x0); step1=min2(step,(a0-xb[0])/4); step1=max2(step1,e); for(i=0,a1=a0,f1=f0; ; i++) { a1-=(step1*=factor); if(a1>xb[0]) { f1=fun(a1); if(f1>f2) break; else { a3=a2; f3=f2; a2=a1; f2=f1; } } else { a1=xb[0]; f1=fun(a1); if(f1<=f2) { a2=a1; f2=f1; } break; } /* if(noisy>2) printf("\ta = %.6f\tf = %.6f %5d\n", a2, f2, NFunCall); */ } if(i==0) { /* *x0 is the best point during the previous search */ step1=min2(step,(xb[1]-a0)/4); for(i=0,a3=a2,f3=f2; ; i++) { a3+=(step1*=factor); if(a3<xb[1]) { f3=fun(a3); if(f3>f2) break; else { a1=a2; f1=f2; a2=a3; f2=f3; } } else { a3=xb[1]; f3=fun(a3); if(f3<f2) { a2=a3; f2=f3; } break; } // if(noisy>2) printf("\ta = %.6f\tf = %.6f %5d\n", a3, f3, NFunCall); } } /* iteration by quadratic interpolation, fig 2.2.9-10 (pp 71-71) */ for (ii=0; ii<maxround; ii++) { /* a4 is the minimum from the parabola over (a1,a2,a3) */ if (a1>a2+1e-99 || a3<a2-1e-99 || f2>f1+1e-99 || f2>f3+1e-99) /* for linux */ { printf("\npoints out of order (ii=%d)!",ii+1); break; } a4 = (a2-a3)*f1+(a3-a1)*f2+(a1-a2)*f3; if (fabs(a4)>1e-100) a4=((a2*a2-a3*a3)*f1+(a3*a3-a1*a1)*f2+(a1*a1-a2*a2)*f3)/(2*a4); if (a4>a3 || a4<a1) a4=(a1+a2)/2; /* out of range */ else percentUse++; f4=fun(a4); /* if (noisy>2) printf("\ta = %.6f\tf = %.6f %5d\n", a4, f4, NFunCall); */ if (fabs(f2-f4)*(1+fabs(f2))<=e && fabs(a2-a4)*(1+fabs(a2))<=e) break; if (a1<=a4 && a4<=a2) { /* fig 2.2.10 */ if (fabs(a2-a4)>.2*fabs(a1-a2)) { if (f1>=f4 && f4<=f2) { a3=a2; a2=a4; f3=f2; f2=f4; } else { a1=a4; f1=f4; } } else { if (f4>f2) { a5=(a2+a3)/2; f5=fun(a5); if (f5>f2) { a1=a4; a3=a5; f1=f4; f3=f5; } else { a1=a2; a2=a5; f1=f2; f2=f5; } } else { a5=(a1+a4)/2; f5=fun(a5); if (f5>=f4 && f4<=f2) { a3=a2; a2=a4; a1=a5; f3=f2; f2=f4; f1=f5; } else { a6=(a1+a5)/2; f6=fun(a6); if (f6>f5) { a1=a6; a2=a5; a3=a4; f1=f6; f2=f5; f3=f4; } else { a2=a6; a3=a5; f2=f6; f3=f5; } } } } } else { /* fig 2.2.9 */ if (fabs(a2-a4)>.2*fabs(a2-a3)) { if (f2>=f4 && f4<=f3) { a1=a2; a2=a4; f1=f2; f2=f4; } else { a3=a4; f3=f4; } } else { if (f4>f2) { a5=(a1+a2)/2; f5=fun(a5); if (f5>f2) { a1=a5; a3=a4; f1=f5; f3=f4; } else { a3=a2; a2=a5; f3=f2; f2=f5; } } else { a5=(a3+a4)/2; f5=fun(a5); if (f2>=f4 && f4<=f5) { a1=a2; a2=a4; a3=a5; f1=f2; f2=f4; f3=f5; } else { a6=(a3+a5)/2; f6=fun(a6); if (f6>f5) { a1=a4; a2=a5; a3=a6; f1=f4; f2=f5; f3=f6; } else { a1=a5; a2=a6; f1=f5; f2=f6; } } } } } } /* for (ii) */ if (f2<=f4) { *f=f2; a4=a2; } else *f=f4; return (*x0=(a4+a2)/2); } static double prob_InverseCDF, *par_InverseCDF; static double (*cdf_InverseCDF)(double x,double par[]); double diff_InverseCDF(double x); double diff_InverseCDF(double x) { // This is the difference between the given p and the CDF(x), the // objective function to be minimized. double px=(*cdf_InverseCDF)(x,par_InverseCDF); return(square(prob_InverseCDF-px)); } double InverseCDF(double(*cdf)(double x,double par[]), double p,double x,double par[],double xb[2]) { // Use x for initial value if in range // int noisy0=noisy; double sdiff,step=min2(0.05,(xb[1]-xb[0])/100), e=1e-15; // noisy=0; prob_InverseCDF=p; par_InverseCDF=par; cdf_InverseCDF=cdf; if(x<=xb[0]||x>=xb[1]) x=.5; LineSearch(diff_InverseCDF, &sdiff, &x, xb, step, e); // noisy=noisy0; return(x); } #define CDFGamma(x,alpha,beta) IncompleteGamma((beta)*(x),alpha,LnGammaFunction(alpha)) int matout (FILE *fout, double x[], int n, int m) { int i,j; for (i=0,FPN(fout); i<n; i++,FPN(fout)) FOR(j,m) fprintf(fout," %11.6f", x[i*m+j]); return (0); } double CDFdN_dS(double x,double p[]) { /* This calculates the CDF of the continuous dN/dS distribution over sites, to be used as argument to the routine InverseCDF(). When the distribution has spikes, the spikes are ignored in this routine, and the scaling is done outside this routine, for example, in DiscreteNSsites(). All parameters (par) for the w distribution are passed to this routine, although some (p0 for the spike at 0) are not used in this routine. Parameters are arranged in the following order: NSgamma (2): alpha, beta NS2gamma (4): p0, alpha1, beta1, alpha2 (=beta2) NSbeta (2): p_beta, q_beta NSbetaw (4): p0, p_beta, q_beta, w (if !com.fix_omega, not used here) NSbetagamma (5): p0, p_beta, q_beta, alpha, beta NSbeta1gamma (5): p0, p_beta, q_beta, alpha, beta (1+gamma) NSbeta1normal (5): p0, p_beta, q_beta, mu, s (normal>1) NS02normal (5): p0, p1, mu2, s1, s2 (s are sigma's) NS3normal (6): p0, p1, mu2, s0, s1, s2 (s are sigma's) Parameters p0 & p1 are transformed if (!LASTROUND) */ double cdf=-1; double z, f[3],mu[3]={0,1,2},sig[3]; /* 3normal: mu0=0 fixed. mu2 estimated */ switch(com.NSsites) { case(NSgamma): cdf=CDFGamma(x,p[0],p[1]); break; case(NS2gamma): cdf=p[0] *CDFGamma(x,p[1],p[2])+(1-p[0])*CDFGamma(x,p[3],p[3]); break; case(NSbeta): cdf=CDFBeta(x,p[0],p[1],0); break; case(NSbetaw): cdf=CDFBeta(x,p[1],p[2],0); break; case(NSbetagamma): cdf=p[0]*CDFBeta(x,p[1],p[2],0)+(1-p[0])*CDFGamma(x,p[3],p[4]); break; case(NSbeta1gamma): if(x<=1) cdf=p[0]*CDFBeta(x,p[1],p[2],0); else cdf=p[0]+(1-p[0])*CDFGamma(x-1,p[3],p[4]); break; case(NSbeta1normal): if(x<=1) cdf=p[0]*CDFBeta(x,p[1],p[2],0); else { cdf=CDFNormal((p[3]-1)/p[4]); if(cdf<1e-9) { matout(F0,p,1,5);; printf("PHI(%.6f)=%.6f\n",(p[3]-1)/p[4],cdf); getchar(); } cdf=p[0]+(1-p[0])*(1- CDFNormal((p[3]-x)/p[4])/cdf); } break; case(NS02normal): mu[2]=p[2]; sig[1]=p[3]; sig[2]=p[4]; f[1]=p[1]; f[2]=1-f[1]; cdf = 1 - f[1]* CDFNormal(-(x-mu[1])/sig[1])/CDFNormal(mu[1]/sig[1]) - f[2]* CDFNormal(-(x-mu[2])/sig[2])/CDFNormal(mu[2]/sig[2]); break; case(NS3normal): mu[2]=p[2]; sig[0]=p[3]; sig[1]=p[4]; sig[2]=p[5]; if(LASTROUND) { f[0]=p[0]; f[1]=p[1]; } else { z=(f[0]=exp(p[0]))+(f[1]=exp(p[1]))+1; f[0]/=z; f[1]/=z;} f[2]=1-f[0]-f[1]; cdf = 1 - f[0]* 2*CDFNormal(-x/sig[0]) - f[1]* CDFNormal(-(x-mu[1])/sig[1])/CDFNormal(mu[1]/sig[1]) - f[2]* CDFNormal(-(x-mu[2])/sig[2])/CDFNormal(mu[2]/sig[2]); break; } return(cdf); } /* (*) Codon models for variable dN/dS ratios among sites (com.nrate includes kappa & omega) (see also CDFdN_dS) NSsites npara 0 one-ratio 0: one ratio for all sites 1 neutral 1: p0 (w0=0, w1=1) 2 selection 3: p0, p1, w2 (w0=0, w1=1) 3 discrete 2K-1: p0,p1,..., and w0,w1,... 4 freqs K: p's (w's are fixed) 5 gamma 2: alpha, beta 6 2gamma 4: p0, alpha1,beta1, alpha2=beta2 7 beta 2: p_beta, q_beta 8 beta&w 4: p0, p_beta, q_beta, w estimated 9 beta&gamma 5: p0, p_beta, q_beta, alpha, beta 10 beta&1+gamma 5: p0, p_beta, q_beta, alpha, beta (1+gamma used) 11 beta&1>normal 5: p0, p_beta, q_beta, mu, s (normal truncated w>1) 12 0&2normal 5: p0, p1, mu2, s1, s2 13 3normal 6: p0, p1, mu2, s0, s1, s2 14 M8a:beta&w=1 3: p0, p_beta, q_beta, w=1 fixed 15 M8a:beta&w>=1 4: p0, p_beta, q_beta, w>=1 estimated */ /* int DiscreteNSsites(vector<double> &params, int &ncatG, int &NSsites, vector<double> &output)//double a, double b, double c,double d) //double par[]) { /* This discretizes the continuous distribution for dN/dS ratios among sites and calculates freqK[] and rK[], using the median method. par[] contains all paras in the w distribution. par[0] is the proportion of beta if (NSsites==betaw), or the proportion of w=0 if (NSsites=NS02normal). This routine uses NSsites, ncatG, freqK, rK. betaw has ncatG-1 site classes in the beta distribution, and 02normal has ncatG-1 site classes in the mixed normal distribution. See the function CDFdN_dS() for definitions of parameters. */ /* // double par[4]={a,b,c,d}; int thesize=params.size(); double *par; par=new double[thesize]; double *rK; rK=new double[thesize]; double *freqK; freqK=new double[thesize]; for(int gv=1; gv<params.size(); gv++) par[gv]=params.at(gv); for( gv=1; gv<params.size(); gv++) cout<<" WEWE "<<par[gv]<<endl; cout<<ncatG<<" EWEWE "<<NSsites<<endl; int status=0, j,off, K=ncatG-(NSsites==NSbetaw || NSsites==NS02normal); double xb[2]={1e-7,99}; // bounds for omega. int K1=6, K2=4, UseK1K2=0; double p01=0, p,w0, lnbeta; if(NSsites==NSbeta || NSsites==NSbetaw) xb[1]=1; #ifdef NSSITES_K1_K2_CLASSES // cout<<"A"<<endl; if((NSsites==NSgamma||NSsites==NS2gamma||NSsites>=NSbetagamma)){ K2=max2(K2,K/3); K1=K-K2; UseK1K2=1; p01=CDFdN_dS(1.,par); // printf("\nK:%3d%3d\t p01=%9.5f\n",K1,K2,p01); FOR(j,K) { if(j<K1) { p=p01*(j*2.+1)/(2.*K1); w0=p; } else { p=p01+(1-p01)*((j-K1)*2.+1)/(2.*K2); w0=1.01+(j-K1)/K2; } rK[j]=InverseCDF(CDFdN_dS,p,w0,par,xb); freqK[j]=(j<K1 ? p01/K1 : (1-p01)/K2); thread } } #endif if(!UseK1K2) { // this is currently used cout<<"B"<<endl; if(NSsites==NSbeta || NSsites==NSbetaw) { off=(NSsites==NSbetaw); // par[0] is proportion for beta for M8 lnbeta=LnGamma(par[off])+LnGamma(par[off+1])-LnGamma(par[off]+par[off+1]); for(j=0; j<K; j++) { p=(j*2.+1)/(2.*K); rK[j]=InverseCDFBeta(p, par[off], par[off+1], lnbeta); } } else { cout<<"C"<<endl; FOR(j,K) { p=(j*2.+1)/(2.*K); w0=.01+j/K; if(rK[j]) w0=(w0+rK[j])/2; rK[j]=InverseCDF(CDFdN_dS,p,w0,par,xb); cout<<"WDWD "<<InverseCDF(CDFdN_dS,p,w0,par,xb)<<endl; } } FOR(j,K) freqK[j]=1./K; } if(NSsites==NSbetaw) { //if(!fix_omega) rK[ncatG-1]=par[3]; rK[ncatG-1]=par[3]; //else rK[ncatG-1]=omega_fix; freqK[K]=1-par[0]; FOR(j,K) freqK[j]*=par[0]; } if(NSsites==NS02normal) { for(j=K-1;j>=0;j--) // shift to right by 1 to make room for spike at 0 { rK[j+1]=rK[j]; freqK[j+1]=freqK[j]; } rK[0]=0; freqK[0]=par[0]; for(j=1;j<K+1;j++) freqK[j]*=(1-par[0]); } if(NSsites>=NSgamma){ if(!status && NSsites==NSbeta) for(j=1;j<ncatG;j++) if(rK[j]+1e-7<rK[j-1]) status=1; if(status) { printf("\nwarning: DiscreteNSsites\nparameters: "); FOR(j,(NSsites==7?2:4)) printf(" %12.6f", par[j]); FPN(F0); FOR(j,ncatG) printf("%13.5f", freqK[j]); FPN(F0); FOR(j,ncatG) printf("%13.5e", rK[j]); FPN(F0); } } output.clear(); cout<<"WOWOWOWOW "<<ncatG<<endl; for(int jk=0; jk<ncatG; jk++) {output.push_back(rK[jk]); cout<<rK[jk]<<" WEGFQEGEG"<<endl;} return(0); }*/ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // note from WF - not really used any more as options for models M4-M13 have been disabled. int DiscreteNSsites(double par[], int ngamcat, int model, vector<double> &output, vector<double> &freqs) { /* Yang, Z., Nielsen, R., Goldman, N. and Pedersen, A-M. K. (2000) Codon-Substitution Models for Heterogeneous Selection Pressure at Amino Acid Sites. Genetics 155: 431-439 (May 2000) This discretizes the continuous distribution for dN/dS ratios among sites and calculates freqK[] and rK[], using the median method. par[] contains all paras in the w distribution. par[0] is the proportion of beta if (com.NSsites==betaw), or the proportion of w=0 if (com.NSsites=NS02normal). This routine uses com.NSsites, com.ncatG, com.freqK, com.rK. betaw has com.ncatG-1 site classes in the beta distribution, and 02normal has com.ncatG-1 site classes in the mixed normal distribution. See the function CDFdN_dS() for definitions of parameters. */ // cout<<"!!!!!!!!!! !"<<endl; com.ncatG=ngamcat; com.NSsites=model; int status=0, j,off, K=com.ncatG-(com.NSsites==NSbetaw || com.NSsites==NS02normal); //cout<<"KKKKKKKKKKKKKKKKKKK "<<K<<" "<<model<<endl; double xb[2]={1e-7,99}; /* bounds for omega. */ int K1=6, K2=4, UseK1K2=0; double p01=0, p,w0, lnbeta; if(com.NSsites==NSbeta || com.NSsites==NSbetaw) xb[1]=1; #ifdef NSSITES_K1_K2_CLASSES if((com.NSsites==NSgamma||com.NSsites==NS2gamma||com.NSsites>=NSbetagamma)){ K2=max2(K2,K/3); K1=K-K2; UseK1K2=1; p01=CDFdN_dS(1.,par); /* printf("\nK:%3d%3d\t p01=%9.5f\n",K1,K2,p01); */ FOR(j,K) { if(j<K1) { p=p01*(j*2.+1)/(2.*K1); w0=p; } else { p=p01+(1-p01)*((j-K1)*2.+1)/(2.*K2); w0=1.01+(j-K1)/K2; } com.rK[j]=InverseCDF(CDFdN_dS,p,w0,par,xb); com.freqK[j]=(j<K1 ? p01/K1 : (1-p01)/K2); thread } } #endif if(!UseK1K2) { /* this is currently used */ if(com.NSsites==NSbeta || com.NSsites==NSbetaw) { off=(com.NSsites==NSbetaw); /* par[0] is proportion for beta for M8 */ lnbeta=LnGamma(par[off])+LnGamma(par[off+1])-LnGamma(par[off]+par[off+1]); for(j=0; j<K; j++) { p=(j*2.+1)/(2.*K); com.rK[j]=InverseCDFBeta(p, par[off], par[off+1], lnbeta); } } else { FOR(j,K) { p=(j*2.+1)/(2.*K); w0=.01+j/K; if(com.rK[j]) w0=(w0+com.rK[j])/2; com.rK[j]=InverseCDF(CDFdN_dS,p,w0,par,xb); } } FOR(j,K) com.freqK[j]=1./K; } if(com.NSsites==NSbetaw) { if(!com.fix_omega) com.rK[com.ncatG-1]=par[3]; else com.rK[com.ncatG-1]=com.omega_fix; com.freqK[K]=1-par[0]; FOR(j,K) com.freqK[j]*=par[0]; } if(com.NSsites==NS02normal) { for(j=K-1;j>=0;j--) /* shift to right by 1 to make room for spike at 0*/ { com.rK[j+1]=com.rK[j]; com.freqK[j+1]=com.freqK[j]; } com.rK[0]=0; com.freqK[0]=par[0]; for(j=1;j<K+1;j++) com.freqK[j]*=(1-par[0]); } if(com.NSsites>=NSgamma){ if(!status && com.NSsites==NSbeta) for(j=1;j<com.ncatG;j++) if(com.rK[j]+1e-7<com.rK[j-1]) status=1; if(status) { printf("\nwarning: DiscreteNSsites\nparameters: "); FOR(j,(com.NSsites==7?2:4)) printf(" %12.6f", par[j]); FPN(F0); FOR(j,com.ncatG) printf("%13.5f", com.freqK[j]); FPN(F0); FOR(j,com.ncatG) printf("%13.5e", com.rK[j]); FPN(F0); } } for(int i=0; i<ngamcat; i++) output.push_back(com.rK[i]); for(int pp=0; pp<ngamcat; pp++) freqs.push_back(com.freqK[pp]); return(0); } /* //script to calculate discrete M3 values for M4 to M13 5 gamma 2: alpha, beta 6 2gamma 4: p0, alpha1,beta1, alpha2=beta2 7 beta 2: p_beta, q_beta 8 beta&w 4: p0, p_beta, q_beta, w estimated 9 beta&gamma 5: p0, p_beta, q_beta, alpha, beta 10 beta&1+gamma 5: p0, p_beta, q_beta, alpha, beta (1+gamma used) 11 beta&1>normal 5: p0, p_beta, q_beta, mu, s (normal truncated w>1) 12 0&2normal 5: p0, p1, mu2, s1, s2 13 3normal 6: p0, p1, mu2, s0, s1, s2 14 M8a:beta&w=1 3: p0, p_beta, q_beta, w=1 fixed 15 M8a:beta&w>=1 4: p0, p_beta, q_beta, w>=1 estimated */ bool itis(string test, string check) { bool result=true; for(int p=0; p<test.size(); p++) { char c1=test[p]; bool minitest=false; for(int y=0; y<check.size(); y++) { char c2=check[y]; if(c2==c1) {minitest=true; break;} } if(minitest==false) {result=false; break;} } return result; } int main(int argc, char* argv[]) { /* if(modelnumber==4) { //as K-1 for 4, 2K-1 for 3, but is K and 2K because of kappa, difference of K // for modelnumber 4, K=5 means size is 5 (kappa, p0, p1, p2, p3) with p4=1-p1-p2-p3 etc double sum=0, mysize=myparams.size()-2; // mysize is 3 for(int yf=1; yf<mysize+2; yf++) //from 1 in the list (p0 after kappa) to mysize+2=5 goes up to p3 { //cout<<yf<<" "<<"1"<<endl; omega=(yf-1)/mysize; //omega is 0, 1/3, 2/3. 1 //cout<<yf<<" "<<"2 "<<endl; Qvec=getCOD(name,basefreqs, modelnumber,kappa,omega); Qvecs.push_back(Qvec); //cout<<yf<<" "<<"3"<<endl; sum+=myparams.at(yf); //cout<<yf<<" "<<"4"<<endl; cumfreqs.push_back(myparams.at(yf)); //cout<<yf<<" "<<"5 "<<myparams.at(yf)<<" "<<omega<<endl; } if(sum<=1) { //cout<<"BLAH"<<endl; omega=mysize; //omega is 3 Qvec=getCOD(name,basefreqs, modelnumber,kappa,omega); Qvecs.push_back(Qvec); cumfreqs.push_back(1-sum); //cout<<"BLAH "<<1-sum<<" "<<omega<<endl; } else cout<<"Error in sum of category frequencies in codon model 4"<<endl; double S=0; for(int y1=0; y1<cumfreqs.size(); y1++) S+=(scalefactors.at(y1)*cumfreqs.at(y1)); for(int yf0=0; yf0<Qvecs.size(); yf0++) {d(Qvecs.at(yf0),S); getJvec(S,name,myrates,Qvecs.at(yf0),Jvec,basefreqs); Jvecs.push_back(Jvec); } } else { if(modelnumber==12 || modelnumber==8) { if(modelnumber==12) { omega=0; Qvec=getCOD(name,basefreqs, modelnumber,kappa,omega); Qvecs.push_back(Qvec); cumfreqs.push_back(myparams.at(1)); for(int hfd=0; hfd<ngamcat; hfd++) cumfreqs.push_back((1-myparams.at(1))/double(ngamcat)); } else { omega=myparams.at(4); Qvec=getCOD(name,basefreqs, modelnumber,kappa,omega); Qvecs.push_back(Qvec); cumfreqs.push_back(1-myparams.at(1)); for(int hfd=0; hfd<ngamcat; hfd++) cumfreqs.push_back(myparams.at(1)/double(ngamcat)); } } else cumfreqs.assign(ngamcat,1/double(ngamcat)); //for(int hfd=0; hfd<ngamcat; hfd++) cumfreqs.push_back(1/ngamcat); vector<double> output; //double *mypar; mypar=new double[myparams.size()]; double mypar[10]={0,0,0,0,0,0,0,0,0,0}; //mypar[0]=0; for(int iu=1; iu<myparams.size(); iu++) {mypar[iu-1]=myparams.at(iu); } // this function of Ziheng's calculates the discrete rates for different site classes from the model parameters DiscreteNSsites(mypar, ngamcat, modelnumber, output); for(int i=0; i<ngamcat; i++) { omega=output.at(i); Qvec=getCOD(name,basefreqs, modelnumber,kappa,omega); Qvecs.push_back(Qvec); } double S=0; for(int y1=0; y1<cumfreqs.size(); y1++) S+=(scalefactors.at(y1)*cumfreqs.at(y1)); for(int yf0=0; yf0<Qvecs.size(); yf0++) {d(Qvecs.at(yf0),S); getJvec(S,name,myrates,Qvecs.at(yf0),Jvec,basefreqs); Jvecs.push_back(Jvec); } } */ /* //script to calculate discrete M3 values for M4 to M13 5 gamma 2: alpha, beta 6 2gamma 4: p0, alpha1,beta1, alpha2=beta2 7 beta 2: p_beta, q_beta 8 beta&w 4: p0, p_beta, q_beta, w estimated 9 beta&gamma 5: p0, p_beta, q_beta, alpha, beta 10 beta&1+gamma 5: p0, p_beta, q_beta, alpha, beta (1+gamma used) 11 beta&1>normal 5: p0, p_beta, q_beta, mu, s (normal truncated w>1) 12 0&2normal 5: p0, p1, mu2, s1, s2 13 3normal 6: p0, p1, mu2, s0, s1, s2 14 M8a:beta&w=1 3: p0, p_beta, q_beta, w=1 fixed 15 M8a:beta&w>=1 4: p0, p_beta, q_beta, w>=1 estimated */ ofstream of1; of1.open("M5-13_output.txt"); while(true) { double mypar[11]={0,0,0,0,0,0,0,0,0,0,0}; int nparams[11]={2,4,2,4,5,5,5,5,6,3,4}; vector<string> modelnames; modelnames.push_back("gamma"); modelnames.push_back("2gamma"); modelnames.push_back("beta"); modelnames.push_back("beta&w"); modelnames.push_back("beta&gamma"); modelnames.push_back("beta&1+gamma"); modelnames.push_back("beta&1>normal"); modelnames.push_back("0&2normal"); modelnames.push_back("3normal"); modelnames.push_back("M8a:beta&w=1"); modelnames.push_back("M8a:beta&w>=1"); vector<vector<string> > paramlist; vector<string> blah; blah.push_back("alpha"); blah.push_back("beta"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("alpha1"); blah.push_back("beta1"); blah.push_back("alpha2 (=beta2)"); paramlist.push_back(blah); blah.clear(); blah.push_back("p_beta"); blah.push_back("q_beta"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p_beta"); blah.push_back("q_beta"); blah.push_back("w"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p_beta"); blah.push_back("q_beta"); blah.push_back("alpha"); blah.push_back("beta"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p_beta"); blah.push_back("q_beta"); blah.push_back("alpha"); blah.push_back("beta"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p_beta"); blah.push_back("q_beta"); blah.push_back("mu"); blah.push_back("s"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p1"); blah.push_back("mu2"); blah.push_back("s1"); blah.push_back("s2"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p1"); blah.push_back("mu2"); blah.push_back("s0"); blah.push_back("s1"); blah.push_back("s2"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p_beta"); blah.push_back("q_beta"); blah.push_back("w=1 fixed"); paramlist.push_back(blah); blah.clear(); blah.push_back("p0"); blah.push_back("p_beta"); blah.push_back("q_beta"); blah.push_back("w>=1 estimated"); paramlist.push_back(blah); blah.clear(); int modelnumber; string test="!"; while(true) { cout<<endl<<" Please enter an integer between 5 and 13 (e.g. 5 for M5, 6 for M6 etc): "<<flush; cin>>test; if(itis(test,"0123456789")) { modelnumber=atoi(test.c_str()); // model number 5 to 13 if(modelnumber>4 && modelnumber<14) break; else cout<<endl<<" That integer is outside the accepted range."<<endl; } else cout<<endl<<" That is not an integer! "<<endl; } int mysize=nparams[modelnumber-5]; cout<<endl<<" Model chosen: M"<<modelnumber<<" ("<<modelnames.at(modelnumber-5)<<")"<<endl<<endl; cout<<" This model has "<<mysize<<" parameters."<<endl<<endl; cout<<" The parameters are: "<<endl<<endl; //blah=paramlist.at(modelnumber-5); cout<<blah.at(0); for(int yg=1; yg<blah.size(); yg++) cout<<", "<<blah.at(yg); blah=paramlist.at(modelnumber-5); for(int yg2=0; yg2<blah.size(); yg2++) cout<<" Parameter "<<yg2+1<<":\t"<<blah.at(yg2)<<endl; cout<<endl; vector<double> params; cout<<" Please enter them in this order pressing enter after each parameter"<<endl<<endl; params.assign(mysize,0); for(int pi=0; pi<mysize; pi++) { // get input double temp; string readin; cout<<" Parameter "<<pi+1<<": "<<flush; cin>>readin; // check string does not contain illegal characters string check="0123456789."; if( modelnumber==11 && pi==3) check+="-"; if( (modelnumber==12 || modelnumber==13) && pi==2) check+="-"; if(!itis(readin,check)) { if( (modelnumber==12 || modelnumber==13) && pi==2) cout<<endl<<" ERROR: this parameter must be a real number. Allowed characters are:"<<endl<<" -.0123456789"<<endl; else if( modelnumber==11 && pi==3) cout<<endl<<" ERROR: this parameter must be a real number. Allowed characters are:"<<endl<<" -.0123456789"<<endl; else cout<<endl<<" ERROR: this parameter must be a decimal number. Allowed characters are:"<<endl<<" .0123456789"<<endl; cout<<" Try again."<<endl<<endl; pi--; continue; } else temp=atof(readin.c_str()); // check value is not incorrect if(modelnumber==5 || modelnumber==7) { if(temp==0) {cout<<endl<<" ERROR: this parameter must be greater than zero. Try again."<<endl<<endl; pi--; continue;}} else { if( (modelnumber==12 || modelnumber==13) && pi==2) {} //mu_2 else if( modelnumber==11 && pi==3) {} // mu else if( modelnumber==8 && pi==3) {} // omega else { if(pi==0) {if(temp>1) {cout<<endl<<" ERROR: proportion p0 must be between 0 and 1. You entered "<<temp<<endl<<" Try again."<<endl<<endl; pi--; continue;}} else if(pi==1) { if(modelnumber==12 || modelnumber==13) { if(temp>1) {cout<<endl<<" ERROR: proportion p1 must be between 0 and 1. You entered "<<temp<<endl<<" Try again."<<endl<<endl; pi--; continue;} if(temp+params.at(0)>1) {cout<<endl<<" ERROR: sum of proportions p0 and p1 must be between 0 and 1.\n You entered "<<temp+params.at(0)<<endl<<" Try again."<<endl<<endl; pi--; continue;} } else if(temp==0) {cout<<endl<<" ERROR: this parameter must be greater than zero. Try again."<<endl<<endl; pi--; continue;} } else if(temp==0) {cout<<endl<<" ERROR: this parameter must be greater than zero. Try again."<<endl<<endl; pi--; continue;} } } params.at(pi)=temp; } int ngamcat; test=""; cout<<endl<<endl; cout<<" I also need to know how many categories you want to use for"<<endl; cout<<" the discrete approximation to the continuous distribution."<<endl<<endl; while(true) { cout<<endl<<" Please enter an integer between 4 and 40: "<<flush; cin>>test; if(itis(test,"0123456789")) { ngamcat=atoi(test.c_str()); if(ngamcat>3 && ngamcat<41) break; else cout<<endl<<" That integer is outside the accepted range."<<endl; } else cout<<endl<<" That is not an integer! "<<endl; } cout<<endl<<endl<<"******************************************************"<<endl<<endl; vector<double> output2, cumfreqs, freqs2; for(int iu=0; iu<params.size(); iu++) {mypar[iu]=params.at(iu); } DiscreteNSsites(mypar, ngamcat, modelnumber, output2, freqs2); vector<string> output,freqs; for(int tg=0; tg<ngamcat; tg++) { stringstream sd1; sd1<<output2.at(tg); output.push_back(sd1.str()); stringstream sd2; sd2<<freqs2.at(tg); freqs.push_back(sd2.str()); } /* if(modelnumber==12 || modelnumber==8) { if(modelnumber==12) { vector<double> temp=output; output.clear(); output.push_back(0); for(int y=0; y<temp.size(); y++) output.push_back(temp.at(y)); cumfreqs.push_back(params.at(0)); for(int hfd=0; hfd<ngamcat; hfd++) cumfreqs.push_back((1-params.at(0))/double(ngamcat)); } else { vector<double> temp=output; output.clear(); output.push_back(params.at(3)); for(int y=0; y<temp.size(); y++) output.push_back(temp.at(y)); cumfreqs.push_back(1-params.at(0)); for(int hfd=0; hfd<ngamcat; hfd++) cumfreqs.push_back(params.at(0)/double(ngamcat)); } } else cumfreqs.assign(ngamcat,1/double(ngamcat)); */ cout<<"Your [submodel] command for INDELible has been output in the file:"<<endl<<"M5-13_output.txt"<<endl<<endl; of1<<"/*"<<endl; of1<<" M3 approximation to M"<<modelnumber<<" ("<<modelnames.at(modelnumber-5)<<") with "<<ngamcat<<" categories used in discrete approximation"<<endl<<endl; of1<<" You chose the following values:"<<endl<<endl; blah=paramlist.at(modelnumber-5); for(int yg1=0; yg1<blah.size(); yg1++) of1<<" Parameter "<<yg1+1<<":\t"<<blah.at(yg1)<<"\t"<<params.at(yg1)<<endl; of1<<"*/"<<endl<<endl; of1<<" [submodel]\tkappa // use your own value for kappa here!"<<endl; of1<<"\t\t"; for(int s=0; s<freqs.size(); s++) { string s1=output.at(s), s2=freqs.at(s); if(s==freqs.size()-1) s2=""; int diff=s1.size()-s2.size(); of1<<s2<<" "; if(diff>0) for(int fd=0; fd<diff; fd++) of1<<" "; } of1<<" // proportions"<<endl; of1<<"\t\t"; for(int t=0; t<output.size(); t++) { string s1=output.at(t), s2=freqs.at(t); int diff=s2.size()-s1.size(); of1<<s1<<" "; if(diff>0) for(int fd=0; fd<diff; fd++) of1<<" "; } of1<<" // omega values"<<endl; // cout<<" "kappa"<<endl; of1<<endl<<endl<<"/*********************************************/"<<endl<<endl; } //script to calculate discrete M3 values for M4 to M13 /* 5 "gamma" 2: alpha, beta 6 "2gamma" 4: p0, alpha1,beta1, alpha2=beta2 7 "beta" 2: p_beta, q_beta 8 "beta&w" 4: p0, p_beta, q_beta, w estimated 9 "beta&gamma" 5: p0, p_beta, q_beta, alpha, beta 10 "beta&1+gamma" 5: p0, p_beta, q_beta, alpha, beta (1+gamma used) 11 "beta&1>normal" 5: p0, p_beta, q_beta, mu, s (normal truncated w>1) 12 "0&2normal" 5: p0, p1, mu2, s1, s2 13 "3normal" 6: p0, p1, mu2, s0, s1, s2 14 "M8a:beta&w=1" 3: p0, p_beta, q_beta, w=1 fixed 15 "M8a:beta&w>=1" 4: p0, p_beta, q_beta, w>=1 estimated */ return 0; }
d5013f7d53301fd54a29b52a4eaf430fce7f9eaf
8df7e6646ba3fc6f70916f330a5bcc53d8760d61
/SDLXX/test/main.cpp
60312e451d4b51084511c68f8ca132093bb95ea1
[]
no_license
BobDeng1974/SDLXX
8fe916b8c0f4c8988841369b7095348faebed920
eaca322647cdb2adfabe960cd7c6c168924caf8f
refs/heads/master
2020-04-03T12:03:41.453901
2018-01-23T21:18:59
2018-01-23T21:18:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
cpp
main.cpp
#include "../SDLXX.h" #include "../SDLXX_image.h" #include "../SDLXX_net.h" #include "../ttf/SDLXX_ttf.h" #include "../SDLXX_mixer.h" #include "../base/Window.h" #include "../base/SceneManager.h" #include "Menu.h" using namespace SDLXX; int main(int argc, char *args[]) { try { SDL sdl(SDL_INIT_VIDEO); sdl.setHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"); SDL_image sdl_image(IMG_INIT_PNG | IMG_INIT_JPG); SDL_mixer sdl_mixer(0/*MIX_INIT_FLAC | MIX_INIT_MP3 | MIX_INIT_OGG*/); SDL_net sdl_net; SDL_ttf sdl_ttf; #ifndef SDLXX_RELEASE sdl.printDebugInfo(); #endif Window window("The Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); Renderer renderer = window.setRenderer(-1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); renderer.setColor(Color(0xFFFFFFFF)); //SDL_RenderSetLogicalSize(renderer.getSDLRenderer(), 800, 600); SceneManager manager(window); manager.push(new Menu("MENU", window)); manager.run(); } catch (std::exception &e) { Log::error(e.what()); } return 0; }
79a33733680e2e10c86851b578633295ac0ace2c
7a172ffea7f3ef1c2cd868d961e01cd8515d9886
/RocketFuel/D1.cpp
229ed4871b8aef3a0060db904213b4cad539dfe9
[]
no_license
rituraj0/OtherCompetitions
e37ba5ff02998c76aad95cf174bb856ad6766d9e
2054a6376caa3258c9db56f634a54228f4f1a412
refs/heads/master
2020-06-05T21:59:41.811711
2015-02-17T16:28:08
2015-02-17T16:28:08
26,070,295
0
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
D1.cpp
#include <iostream> #include <cmath> #include <algorithm> #include <string> #include <cstdio> #include <vector> #include <queue> using namespace std; int n, m, x[5000], y[5000], l[5000]; int main() { cin >> n >> m; for (int i = 1; i <= n + m; i++) cin >> x[i] >> y[i] >> l[i]; int maxi = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { int q = 0; q = max(min(min(x[i] - x[n + j], x[n + j] + l[n + j] - x[i]), min(y[n + j] - y[i], y[i] + l[i] - y[n + j])), 0); maxi = max(q, maxi); } cout << maxi; return 0; }
aaa39c0e18e1dc9327fa97f9e15a0c28cbc41175
141871424dffc6df8a2ac00513bcb99803cd48aa
/Level_1/폰켓몬.cpp
f2398eee0657d59e675d94fd6f6fb9410ed23084
[]
no_license
s4055/Programmers
d4f0ef8785e9fffbdf0bcb9c8ca89b6d1a15a233
8672e91a5a6311daac356c78acc99c101ccae4d3
refs/heads/main
2023-04-23T16:53:14.453040
2021-04-30T14:59:00
2021-04-30T14:59:00
363,170,188
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
폰켓몬.cpp
#include <vector> #include <algorithm> using namespace std; int solution(vector<int> nums) { int answer = 0, N; N = nums.size(); sort(nums.begin(), nums.end()); nums.erase(unique(nums.begin(), nums.end()), nums.end()); if(N/2 <= nums.size()) answer = N/2; else answer = nums.size(); return answer; }
1cc911253591eabb7f8f763ef5b098eb2c213bcc
da1500e0d3040497614d5327d2461a22e934b4d8
/net/cookies/cookie_store.cc
2b2eb7edbfa212f76f417377dd409b582b7179e5
[ "BSD-3-Clause" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C++
false
false
1,458
cc
cookie_store.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 "net/cookies/cookie_store.h" #include "base/bind.h" #include "base/callback.h" #include "net/cookies/cookie_options.h" namespace net { CookieStore::~CookieStore() = default; void CookieStore::DeleteAllAsync(DeleteCallback callback) { DeleteAllCreatedInTimeRangeAsync(CookieDeletionInfo::TimeRange(), std::move(callback)); } void CookieStore::SetForceKeepSessionState() { // By default, do nothing. } void CookieStore::GetAllCookiesForURLAsync(const GURL& url, GetCookieListCallback callback) { CookieOptions options; options.set_include_httponly(); options.set_same_site_cookie_mode( CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX); options.set_do_not_update_access_time(); GetCookieListWithOptionsAsync(url, options, std::move(callback)); } void CookieStore::SetChannelIDServiceID(int id) { DCHECK_EQ(-1, channel_id_service_id_); channel_id_service_id_ = id; } int CookieStore::GetChannelIDServiceID() { return channel_id_service_id_; } void CookieStore::DumpMemoryStats( base::trace_event::ProcessMemoryDump* pmd, const std::string& parent_absolute_name) const {} CookieStore::CookieStore() : channel_id_service_id_(-1) {} } // namespace net
6edc33919c9ed9767755065a04f140026503bcb2
621ab4417c0980be2a8f0ed891cf74888f68c064
/263A - Beautiful Matrix.cpp
94dbb0c9db6b2c7b45763105b4c3ce08e56a5838
[]
no_license
Niharika0612/Codeforcessolutions
5f0380504defe39e277b260945ecc102e2df324d
bbb04454885e2148016219e4dbb88b2e76f0cf65
refs/heads/main
2023-06-28T13:33:56.216727
2021-07-29T09:03:50
2021-07-29T09:03:50
390,652,435
0
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
263A - Beautiful Matrix.cpp
#include <bits/stdc++.h> using namespace std; int main() { int x,y,i,j,a[6][6],ans; for(i=0;i<5;i++) { for(j=0;j<5;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<5;i++) { for(j=0;j<5;j++) { if(a[i][j]==1) { x=i+1; y=j+1; } } } ans=abs(x-3)+abs(y-3); printf("%d\n",ans); return 0; }
9e30a7f9c29a9f6a2d5526d4b2ffe0d72e4e6264
3d39e8b632cb0b3387985c81c2aeee218f09ed0a
/school-31/coding/acmp.ru/0059.cpp
e48272df355bebb68146125f25b6c9b3372ea4e6
[]
no_license
eshlykov/junk
6defecb3f0f3470f32fbdf04c547242201bddf7b
10f161fd11193c9a543f772621cf104425532e1e
refs/heads/master
2022-02-12T05:48:04.650567
2019-07-16T17:29:02
2019-07-16T17:29:02
82,374,202
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
0059.cpp
#include <fstream> using namespace std; int main() { ifstream in("input.txt"); ofstream out("output.txt"); long int n, m = 1; int k, s = 0; in >> n >> k; while (n > 0) { s += n % k; m *= n % k; n /= k; } out << m - s; in.close(); out.close(); return 0; }
4f3e2c139f83662a98627f45d4401687df4b3758
466312390c8800d8afc6d1f0eb78b5a46b891965
/git-c++/git-alone/输入左奇数右偶数.cpp
64c6e965f4f09e1369052415125b032d097c232f
[]
no_license
ambitiousCC/Work-c
e360ecf717cc1ff68c4b1019425fc5f49c9ced89
d85b63ff0cc350afb75057ea2206a08791161132
refs/heads/master
2020-04-27T07:42:52.441559
2019-07-11T05:30:17
2019-07-11T05:30:17
174,145,284
1
0
null
null
null
null
UTF-8
C++
false
false
958
cpp
输入左奇数右偶数.cpp
#include <bits/stdc++.h> using namespace std; int main() { string input; cin>>input; vector<int> num; char* s_input = (char*)input.c_str(); const char* split = ","; char* p = strtok(s_input, split); int n; while(p!=NULL) { sscanf(p,"%d",&n); num.push_back(n); p = strtok(NULL, split); } for(int i = 0; i < num.size(); i++) { for(int j = i+1; j < num.size(); j++) { if(num[i]%2==0&&num[j]%2!=0) { int temp = num[j]; num[j] = num[i]; num[i] = temp; } } } int begin = 0; for(int k = 0; k < num.size(); k++) { if(num[k]%2==0) { begin = k; break; } } for(int l = begin; l < num.size(); l++) { for(int m = l+1; m < num.size(); m++) { if(num[l]>num[m]) { int temp2 = num[l]; num[l] = num[m]; num[m] = temp2; } } } vector<int>::iterator it; for(it=num.begin();it!=num.end();it++) { if(it!=num.end()-1) cout<<*it<<","; else cout<<*it; } return 0; }
b7357df87a394faa4e3ef3696e05bd3d11ff1ac6
b734362fa21bd2b3edf06fab97b4d090570b6fe4
/tree.h
71ff57ac8025bfc7effd6ed5cd3ae996b0dadb08
[]
no_license
BorisTab/treeAndAkinator
9ec014a15654d1f4db9bc359ed8a5fdcb9f2bbbe
3d3e771df096ae36016d63d4285d9f40480edd18
refs/heads/master
2020-09-09T20:19:01.225439
2019-11-15T09:35:14
2019-11-15T09:35:14
221,557,666
0
0
null
null
null
null
UTF-8
C++
false
false
6,435
h
tree.h
// // Created by boristab on 08.11.2019. // #include <iostream> #include <fstream> #include <cassert> #include <cstring> #include "fileRead.h" enum errors { SUCCESS = 0, FILE_OPEN_FAILED = 1, NOT_FOUND_TREE_IN_FILE = 2, }; const char dumpFilePath[FILENAME_MAX] = "../TreeDumpFile.txt"; int spaceN (const char *buffer); template <class elemType> class Node { public: Node <elemType> *leftChild = nullptr; Node <elemType> *rightChild = nullptr; elemType value = {}; explicit Node(elemType value) { this->value = value; } }; template <class elemType> class Tree { private: Node <elemType> *root = nullptr; void printNodeInit(std::ofstream *dumpFile, Node <elemType> *node) { assert(node); assert(dumpFile); *dumpFile << "node_" << node << " [shape=record, label=\" { "<< node << " | Val: " << node->value << " | { left: " << node->leftChild << " | right: " << node->rightChild << " } } \"];\n"; if (node->leftChild) printNodeInit(dumpFile, node->leftChild); if (node->rightChild) printNodeInit(dumpFile, node->rightChild); } void printNodeRel(std::ofstream *dumpFile, Node <elemType> *node) { if (node->leftChild) *dumpFile << "node_" << node << "-- node_" << node->leftChild << ";\n"; if (node->rightChild) *dumpFile << "node_" << node << "-- node_" << node->rightChild << ";\n"; if (node->leftChild) printNodeRel(dumpFile, node->leftChild); if (node->rightChild) printNodeRel(dumpFile, node->rightChild); } void saveNode(std::ofstream *outFile, Node <elemType> *node) { assert(outFile); assert(node); *outFile << "{ \"" << node->value << "\" "; if (!node->leftChild && !node->rightChild) { *outFile << "} "; return; } if (node->leftChild) saveNode(outFile, node->leftChild); else *outFile << "$ "; if (node->rightChild) saveNode(outFile, node->rightChild); else *outFile << "$ "; *outFile << "} "; } void writeNode(char **buffer, Node <elemType> *node) { if (**buffer == '$') (*buffer) += 2; else if (**buffer == '{'){ (*buffer) += 2 + spaceN((*buffer) + 1); *(strchr(*buffer, '"')) = '\0'; insertLeft(node, *buffer); (*buffer) += strlen(*buffer) + 2; writeNode(buffer, node->leftChild); } if (**buffer == '$') (*buffer) += 2; else if (**buffer == '{'){ (*buffer) += 2 + spaceN((*buffer) + 1); *(strchr(*buffer, '"')) = '\0'; insertRight(node, *buffer); (*buffer) += strlen(*buffer) + 2; writeNode(buffer, node->rightChild); } if (**buffer == '}') { (*buffer) += 2; return; } } public: explicit Tree(elemType val) { auto *node = newNode(val); root = node; } Tree(char load, const char *inPath) { assert(load == 'L'); int fileSize = getFileSize(inPath); char *buffer = new char[fileSize] (); char *bufferStart = buffer; readFile(inPath, buffer, fileSize); if (*buffer != '{') { printf("Error: No tree in file"); exit(NOT_FOUND_TREE_IN_FILE); } if (*(buffer + spaceN(buffer + 1)) == '}') { printf("Error: tree is empty"); exit(NOT_FOUND_TREE_IN_FILE); } buffer += 2 + spaceN(buffer + 1); *(strchr(buffer + 1, '"')) = '\0'; auto *node = newNode(buffer); root = node; buffer += strlen(buffer); buffer += spaceN(buffer + 1) + 1; writeNode(&buffer, root); } Node <elemType> *newNode(elemType val) { return new Node <elemType> (val); } void insertNodeLeft(Node <elemType> *parent, Node <elemType> *node) { parent->leftChild = node; } void insertNodeRight(Node <elemType> *parent, Node <elemType> *node) { parent->rightChild = node; } void insertLeft(Node <elemType> *parentNode, elemType val) { auto *node = newNode(val); parentNode->leftChild = node; } void insertRight(Node <elemType> *parentNode, elemType val) { auto *node = newNode(val); parentNode->rightChild = node; } void deleteSubTree(Node <elemType> *node) { if (!node) return; if (node->leftChild) { deleteSubTree(node->leftChild); } else if (node->rightChild) { deleteSubTree(node->rightChild); } else { delete node; } } Node <elemType> *getRoot() { return root; } Node <elemType> *getLeftChild(Node <elemType> *node) { assert(node); return node->leftChild; } Node <elemType> *getRightChild(Node <elemType> *node) { assert(node); return node->rightChild; } elemType getVal(Node <elemType> *node) { return node->value; } Node <elemType> *findElem(Node <elemType> *subtree, elemType val) { assert(subtree); if(subtree->value == val) return subtree; if (subtree->leftChild) findElem(subtree->leftChild); if (subtree->rightChild) findElem(subtree->rightChild); } void changeVal(Node <elemType> *node, elemType val) { node->value = val; } void dump() { std::ofstream dumpFile (dumpFilePath); if (!dumpFile) { printf("File isn't open\n"); exit(FILE_OPEN_FAILED); } dumpFile << "graph G{\n"; if (root) { Node <elemType> *currentNode = root; printNodeInit(&dumpFile, root); printNodeRel(&dumpFile, root); } dumpFile << "}\n"; dumpFile.close(); char dotCommand[FILENAME_MAX] = ""; sprintf(dotCommand, "dot -Tpng -O %s", dumpFilePath); std::system(dotCommand); } void saveTo(const char *path) { std::ofstream outFile (path); if (!outFile) { printf("File isn't open\n"); exit(FILE_OPEN_FAILED); } saveNode(&outFile, root); outFile.close(); } }; int spaceN (const char *buffer) { int count = 0; while (*buffer + count == ' ') { count++; } return count; }
851f72ad00e4a41418043922668164ff36afab93
24a96f106c7e1d7e231b61ceda433c7bbf5c7d22
/numerical/srng.h
70dbf745b31790a60d44a722a3aaad0ac0e3b4b2
[]
no_license
cbshiles/KALX-libbms
fc0e85c5edbafe4e439fa80417421df7ba85ab32
fb20be56d9e0ad9f5c8045185c572f7e1083702f
refs/heads/master
2021-07-22T04:10:46.063754
2013-02-22T19:34:25
2013-02-22T19:34:25
109,080,282
0
1
null
null
null
null
UTF-8
C++
false
false
2,904
h
srng.h
// srng.h - simple random number generator with optionally stored seed // Copyright (c) 2011 KALX, LLC. All rights reserved. No warranty is made. #pragma once #include <ctime> #include <cstdint> #ifdef _WIN32 #include "../win/registry.h" #define SRNG_SUBKEY _T("Software\\KALX\\bms") #else #include <fstream> #endif #include <utility> using namespace std::rel_ops; namespace numerical { class srng { static const uint32_t min = 0; static const uint32_t max = 0xFFFFFFFF; uint32_t s_[2]; public: srng(bool stored = false) { if (stored) { load(); } else { s_[0] = static_cast<uint32_t>(::time(0)); s_[1] = ~s_[0]; save(); } } srng(uint32_t s0, uint32_t s1) { s_[0] = s0; s_[1] = s1; } srng(const srng& rng) { s_[0] = rng.s_[0]; s_[1] = rng.s_[1]; } srng& operator=(const srng& rng) { if (this != &rng) { s_[0] = rng.s_[0]; s_[1] = rng.s_[1]; } return *this; } ~srng() { } bool operator==(const srng& rng) const { return s_[0] == rng.s_[0] && s_[1] == rng.s_[1]; } bool operator<(const srng& rng) const { return s_[0] < rng.s_[0] || (s_[0] == rng.s_[0] && s_[1] < rng.s_[1]); } #ifdef _WIN32 // store state in registry void save(void) const { Reg::CreateKey<TCHAR>(HKEY_CURRENT_USER, SRNG_SUBKEY).SetValue<DWORD>(_T("seed0"), s_[0]); Reg::CreateKey<TCHAR>(HKEY_CURRENT_USER, SRNG_SUBKEY).SetValue<DWORD>(_T("seed1"), s_[1]); } void load(void) { Reg::Object<TCHAR, DWORD> s0(HKEY_CURRENT_USER, SRNG_SUBKEY, _T("seed0"), 521288629); Reg::Object<TCHAR, DWORD> s1(HKEY_CURRENT_USER, SRNG_SUBKEY, _T("seed1"), 362436069); s_[0] = s0; s_[1] = s1; } #else void save(void) const { std::ofstream ofs("srng.seed"); ofs << s_[0] << " " << s_[1]; } void load(void) { std::ifstream ifs("srng.seed"); if (ifs.good()) ifs >> s_[0] >> s_[1]; else { s_[0] = 521288629; s_[1] = 362436069; save(); } } #endif // _WIN32 void seed(uint32_t s0, uint32_t s1) { s_[0] = s0; s_[1] = s1; save(); } void seed(uint32_t s[2]) { s_[0] = s[0]; s_[1] = s[1]; save(); } const uint32_t* seed(void) const { return s_; } // uniform unsigned int in the range [0, 2^32) // See http://www.bobwheeler.com/statistics/Password/MarsagliaPost.txt uint32_t uint() { s_[1] = 36969 * (s_[1] & 0xFFFF) + (s_[1] >> 0x10); s_[0] = 18000 * (s_[0] & 0xFFFF) + (s_[0] >> 0x10); return (s_[1] << 0x10) + s_[0]; } // uniform double in the range [0, 1) double real() { // 0 <= u < 2^32 double u = uint(); return u/max; } // uniform int in [a, b] int between(int a, int b) { return static_cast<int>(a + ((b - a + 1)*real())); } // uniform double in [a, b) double uniform(double a = 0, double b = 1) { return a + (b - a)*real(); } }; } // namespace utility
a63765fd6862795eef47eda3934609fe1ab614d6
906f33f6e8d6ff6395579f37c2da25e100494948
/public/gal/expr.hpp
e655f0648757a7336ec4a4b2313cca1985e5dd32
[ "MIT" ]
permissive
tweakoz/gal
56d7bb15ced383beb072e956da2920b89f46b886
e859994aeb826acaf912b3efe5813582b0648291
refs/heads/master
2023-03-20T04:04:31.203473
2019-11-30T03:37:50
2019-11-30T03:46:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,218
hpp
expr.hpp
#pragma once // expr.hpp // Defines operators for constructing expression template trees as an intermediate structure for // computation. // // Node checksums: // Each expr node exposes a static constant corresponding to a checksum of itself along with its // children. Checksums are computed recursively by summing child node checksums to produce the // parent checksum. Afterwards, the operation represented by the node is written into the result. #include "algebra.hpp" #include "crc.hpp" #include "null_algebra.hpp" #include "tuple.hpp" #include <type_traits> #ifdef GAL_DEBUG # include <sstream> # include <string> #endif namespace gal { namespace detail { enum op : uint32_t { // Utility ops op_id, // (00) Specifies a leaf of the expression tree referring to an input op_cse, // (01) This is used during DFA (data flow analysis) for referring to computed // intermediate values op_se, // (02) Indicate the start of a subexpression in the subexpression list. This is used // for polyadic operators such as sum and the exterior product op_noop, // (03) Noop used to indicate that current arg on the stack should be evaluated as // a temporary // Algebraic ops op_rev, // (04) Reversion op_pd, // (05) Poincare dual op_sum, // (06) Sum op_gp, // (07) Geometric product op_ep, // (08) Exterior product op_lc, // (09) Left contraction op_sip, // (10) Symmetric inner product op_comp, // (11) Extract an individual component as a scalar op_div, // (12) Division by scalar indeterminant op_grd, // (13) Select all components that match a particular grade // Scalar ops (these ops are applied term by term) op_sqrt, // (14) Square root op_sin, // (15) Sine op_cos, // (16) Cosine op_tan, // (17) Tangent // Constants c_zero = 1 << 16, // multivector that is exactly zero c_const_start, c_pi = c_const_start, // The constant pi c_e, // The Euler constant c_const_end, c_scalar, // scalar component of a multivector // c_scalar + E corresponds to the unit constant element E // For example, c_scalar + (1 << (dim - 1)) represents the pseudoscalar }; constexpr bool is_read_op(uint32_t o) noexcept { switch (static_cast<op>(o)) { case op_comp: case op_grd: return true; default: break; } return false; } // RPN node struct node { uint32_t o = 0; // For an expression reference, the checksum is used as a placeholder to skip to a // subsequent node in the expression. crc_t checksum = 0; // Ex is an overloaded member variable (unions are not modifiable in a constexpr context) // // For op summands, the ex corresponds to the number of nodes contained in the summand (not // including this one). // // For exterior product factors, ex holds the number of operands (useful for computing the // merge parity). // // For the sum and exterior operators, ex refers to the number of arguments. // // For the id op (used for an input with an identifier), ex is the index of the input in the // input list. // // For extractions, ex refers to the element we wish to extract. // // For subexpression references (during DFA), ex is an index to the subexpression. width_t ex = 0; // This rational scaling constant can be used for sum subexpressions. If this is zero for a // subexpression, the subexpression is part of an exterior product. // // For sum and exterior product nodes, the denominator here contains the total length of the // expression that constitutes the subexpression up to and including the op_sum/op_ep. rat q{0, 0}; constexpr bool operator==(node const& other) const { return o == other.o && checksum == other.checksum && ex == other.ex; } constexpr bool operator!=(node const& other) const { return !(*this == other); } }; // Reverse-Polish notation expression // A := Algebra which defines dimensionality, metric tensor, product evaluation functions // S := Size template <typename A, width_t S> struct rpne { using algebra_t = A; constexpr static width_t capacity = S; // To simplify processing, we arrange this structure so that each node maps to exactly one // factor node nodes[S]; // The count here can easily diverge from the capacity due to CSE and term elimination width_t count = 0; rat q{1, 1}; constexpr auto operator[](elem_t e) noexcept { rpne<A, S + 1> out; out.append(*this); // Using operator[] successfully is not expected behavior, so we don't bother computing // the checksum in a fancy manner. out.nodes[out.count++] = node{op_comp, back().checksum + e, e}; out.q = q; return out; } constexpr auto select_grade(elem_t g) noexcept { rpne<A, S + 1> out; out.append(*this); out.nodes[out.count++] = node{op_grd, back().checksum + ~g, g}; out.q = q; return out; } constexpr node* begin() noexcept { return nodes; } constexpr node const* begin() const noexcept { return nodes; } constexpr node* end() noexcept { return nodes + count; } constexpr node const* end() const noexcept { return nodes + count; } constexpr node pop() noexcept { return nodes[count--]; } constexpr void pop(width_t n) noexcept { count -= n; } template <width_t S1> constexpr void append(rpne<A, S1> const& src) noexcept { for (width_t i = 0; i != src.count; ++i) { nodes[count++] = src.nodes[i]; } } constexpr void append(node const& in) noexcept { nodes[count++] = in; } template <width_t S1> constexpr void append_omit_ends(rpne<A, S1> const& src) noexcept { for (width_t i = 0; i != src.count - 1; ++i) { nodes[count++] = src.nodes[i]; } } constexpr void append_cse(width_t i) noexcept { // The index to the ref passed here is 1-indexed (disambiguates it from a not-found // result). nodes[count++] = node{op_cse, 0, i - 1, zero}; } constexpr void append_noop() noexcept { nodes[count++] = node{op_noop, 0, 0, zero}; } template <width_t S1> constexpr void append_as_se(rpne<A, S1> const& src) noexcept { nodes[count++] = node{op_se, 0, src.count, src.q}; for (width_t i = 0; i != src.count; ++i) { nodes[count++] = src.nodes[i]; } } constexpr void append(op o) noexcept { nodes[count++] = {o, crc32((o << 8) + back().checksum)}; } constexpr void append(op o, crc_t c) noexcept { nodes[count++] = {o, c}; } constexpr node& back() noexcept { return nodes[count - 1]; } constexpr node const& back() const noexcept { return nodes[count - 1]; } template <width_t S1> constexpr bool operator==(rpne<A, S1> const& other) const noexcept { if (count != other.count) { return false; } for (width_t i = 0; i != count; ++i) { if (nodes[i] != other.nodes[i]) { return false; } } return true; } }; template <typename A, size_t S, typename D, typename... Ds> constexpr auto rpne_entities(std::array<rpne<A, 1>, S>& out, uint32_t current_id, size_t i) noexcept { out[i].nodes[0] = node{op_id, current_id, i}; out[i].count = 1; if constexpr (sizeof...(Ds) > 0) { if (std::is_floating_point_v<D>) { return rpne_entities<A, S, Ds...>(out, current_id + 1, i + 1); } else { return rpne_entities<A, S, Ds...>(out, current_id + D::size(), i + 1); } } else { if constexpr (std::is_floating_point_v<D>) { return ::gal::make_pair(current_id + 1, i + 1); } else { return ::gal::make_pair(current_id + D::size(), i + 1); } } } template <typename A, typename... D> constexpr auto rpne_entities() noexcept { std::array<rpne<A, 1>, sizeof...(D)> out; auto next = rpne_entities<A, sizeof...(D), D...>(out, 0, 0); return ::gal::make_pair(out, next); } template <typename A> constexpr rpne<A, 1> rpne_pseudoscalar(int n) noexcept { uint32_t op = detail::c_scalar + (1 << A::metric_t::dimension) - 1; return {{detail::node{op, op}}, 1, rat{static_cast<num_t>(n), 1}}; } template <typename A> constexpr auto rpne_from_constant(num_t n, den_t d) noexcept { rpne<A, 1> out; out.nodes[0] = node{c_scalar, c_scalar}; out.q = rat{n, d}; out.count = 1; return out; } template <typename T, size_t... I> constexpr auto rpne_total_capacity(T const&, std::index_sequence<I...>) noexcept { return (std::decay_t<decltype(static_cast<T*>(nullptr)->template get<I>())>::capacity + ...); } // Concatenate a variadic number of expressions in the input tuple as subexpressions template <auto const& input> constexpr auto rpne_concat() noexcept { using type = std::decay_t<decltype(input)>; if constexpr (is_tuple_v<type>) { using A = typename decltype(input.template get<0>())::algebra_t; constexpr width_t capacity = input.apply([](auto const&... args) { return (std::decay_t<decltype(args)>::capacity + ...); }) + static_cast<width_t>(std::decay_t<decltype(input)>::size()); return input.apply([capacity](auto const&... args) { rpne<A, capacity> out; (out.append_as_se(args), ...); return out; }); } else { return input; } } struct rpne_constant { width_t id; rat q = one; template <typename A> constexpr rpne<A, 1> convert() const noexcept { return {{node{c_pi, c_pi}}, 1, q}; } }; } // namespace detail constexpr inline detail::rpne_constant PI{detail::pi_ind}; constexpr inline detail::rpne_constant E{detail::e_ind}; template <typename A, width_t S1, width_t S2> constexpr detail::rpne<A, S1 + S2 + 3> operator+(detail::rpne<A, S1> lhs, detail::rpne<A, S2> rhs) { using detail::op_sum; using detail::rpne; // Conservative size accounts for 2 summand ops, 1 sum op, and the inputs. rpne<A, S1 + S2 + 3> out; // Early out if either the lhs or the rhs is exactly zero if (lhs.count == 0 || rhs.count == 0) { if (lhs.count == 0) { out.append(rhs); } else { out.append(lhs); } return out; } // If the trailing operation of the lhs is a summation, we can move the summation op to the // right of the rhs. By the same token, if the trailing operation on the rhs is a summation, // that can be coalesced as well. auto const& lhs_final = lhs.back(); auto const& rhs_final = rhs.back(); bool lhs_sum = lhs_final.o == op_sum; bool rhs_sum = rhs_final.o == op_sum; width_t lhs_index = 0; width_t rhs_index = 0; uint32_t summand_count = 0; if (lhs_sum && rhs_sum) { // Merge the lhs and rhs summands while (true) { // Note that we subtract 1 from the upper limit to avoid the final sum op if (lhs_index == lhs.count - 1) { // Copy remaining rhs nodes. (exclude final sum op) while (rhs_index != rhs.count - 1) { auto rhs_summand = rhs.nodes[rhs_index++]; ++summand_count; rhs_summand.q *= rhs.q; out.nodes[out.count++] = rhs_summand; for (width_t i = 0; i != rhs_summand.ex; ++i) { out.nodes[out.count++] = rhs.nodes[rhs_index++]; } } break; } else if (rhs_index == rhs.count - 1) { // Copy remaining lhs nodes. while (lhs_index != lhs.count - 1) { auto lhs_summand = lhs.nodes[lhs_index++]; ++summand_count; lhs_summand.q *= rhs.q; out.nodes[out.count++] = lhs_summand; for (width_t i = 0; i != lhs_summand.ex; ++i) { out.nodes[out.count++] = lhs.nodes[lhs_index++]; } } break; } auto const& lhs_summand = lhs.nodes[lhs_index]; auto const& rhs_summand = rhs.nodes[rhs_index]; detail::crc_t lhs_checksum = lhs_summand.checksum; detail::crc_t rhs_checksum = rhs_summand.checksum; if (lhs_checksum == rhs_checksum && lhs_summand.ex == rhs_summand.ex) { bool equal = true; // Check if the two summands are in fact equivalent for (width_t i = 0; i != lhs_summand.ex; ++i) { if (lhs.nodes[lhs_index + 1 + i] != rhs.nodes[rhs_index + 1 + i]) { equal = false; break; } } if (equal) { rat q = lhs_summand.q * lhs.q + rhs_summand.q * rhs.q; if (!q.is_zero()) { auto& s = out.nodes[out.count++]; s.q = q; s.o = detail::op_se; s.checksum = lhs_checksum; s.ex = lhs_summand.ex; ++summand_count; for (width_t i = 0; i != lhs_summand.ex; ++i) { out.nodes[out.count++] = lhs.nodes[lhs_index + 1 + i]; } } lhs_index += 1 + lhs_summand.ex; rhs_index += 1 + rhs_summand.ex; continue; } } // We let the if statement above *fall through* to the cases below in case of checksum // equality but term inequality if (lhs_checksum < rhs_checksum) { out.nodes[out.count] = lhs.nodes[lhs_index++]; out.nodes[out.count++].q *= lhs.q; for (width_t i = 0; i != lhs_summand.ex; ++i) { out.nodes[out.count++] = lhs.nodes[lhs_index++]; } } else { out.nodes[out.count] = rhs.nodes[rhs_index++]; out.nodes[out.count++].q *= rhs.q; for (width_t i = 0; i != rhs_summand.ex; ++i) { out.nodes[out.count++] = rhs.nodes[rhs_index++]; } } ++summand_count; } // Merge of sums complete } else if (lhs_sum || rhs_sum) { // Indicator for whether the "non-sum" term has been merged bool written = false; rat sum_q = lhs_sum ? lhs.q : rhs.q; rat non_sum_q = lhs_sum ? rhs.q : lhs.q; auto const* sum_nodes = lhs_sum ? lhs.nodes : rhs.nodes; auto sum_count = lhs_sum ? lhs.count : rhs.count; auto const* non_sum_nodes = lhs_sum ? rhs.nodes : lhs.nodes; auto non_sum_count = lhs_sum ? rhs.count : lhs.count; auto& sum_index = lhs_sum ? lhs_index : rhs_index; auto& non_sum_index = lhs_sum ? rhs_index : lhs_index; auto const& non_sum_final = lhs_sum ? rhs_final : lhs_final; while (true) { if (sum_index == sum_count - 1) { if (!written) { out.nodes[out.count++] = detail::node{ detail::op_se, non_sum_final.checksum, non_sum_count, non_sum_q}; ++summand_count; for (width_t i = 0; i != non_sum_count; ++i) { out.nodes[out.count++] = non_sum_nodes[i]; } } break; } auto& summand = sum_nodes[sum_index]; if (!written && summand.checksum == non_sum_final.checksum && summand.ex == non_sum_count) { // Compare summand equality to non-sum bool equal = true; for (width_t i = 0; i != non_sum_count; ++i) { if (sum_nodes[sum_index + 1 + i] != non_sum_nodes[i]) { equal = false; break; } } if (equal) { rat q = summand.q * sum_q + non_sum_q; written = true; if (q.is_zero()) { // The terms cancel sum_index += 1 + summand.ex; } else { out.nodes[out.count++] = detail::node{detail::op_se, non_sum_final.checksum, non_sum_count, q}; ++summand_count; for (width_t i = 0; i != non_sum_count; ++i) { out.nodes[out.count++] = non_sum_nodes[i]; } sum_index += 1 + summand.ex; } continue; } } if (!written && summand.checksum > non_sum_final.checksum) { // Insert the non-sum into the summand list written = true; out.nodes[out.count++] = detail::node{detail::op_se, non_sum_final.checksum, non_sum_count, non_sum_q}; for (width_t i = 0; i != non_sum_count; ++i) { out.nodes[out.count++] = non_sum_nodes[i]; } } else { out.nodes[out.count] = summand; out.nodes[out.count++].q *= sum_q; for (width_t i = 0; i != summand.ex; ++i) { out.nodes[out.count++] = sum_nodes[sum_index + 1 + i]; } sum_index += summand.ex + 1; } ++summand_count; } } else { // Neither the lhs nor the rhs are sums. Add both as new summands. auto& final_lhs = lhs.back(); auto& final_rhs = rhs.back(); if (final_lhs.checksum == final_rhs.checksum && lhs.count == rhs.count) { if (lhs == rhs) { // No summation is necessary. rat q = lhs.q + rhs.q; if (q.is_zero()) { out.count = 0; return out; } else { for (width_t i = 0; i != lhs.count; ++i) { out.nodes[i] = lhs.nodes[i]; } out.q = q; out.count = lhs.count; return out; } } } if (final_lhs.checksum < final_rhs.checksum) { out.nodes[out.count++] = detail::node{detail::op_se, final_lhs.checksum, lhs.count, lhs.q}; out.append(lhs); out.nodes[out.count++] = detail::node{detail::op_se, final_rhs.checksum, rhs.count, rhs.q}; out.append(rhs); } else { out.nodes[out.count++] = detail::node{detail::op_se, final_rhs.checksum, rhs.count, rhs.q}; out.append(rhs); out.nodes[out.count++] = detail::node{detail::op_se, final_lhs.checksum, lhs.count, lhs.q}; out.append(lhs); } summand_count = 2; } // Do a final pass to see if the sum has been collapsed to a single term if (summand_count == 1) { // Copy-erase the initial subexpression op out.q = out.nodes[0].q; for (width_t i = 0; i != out.count - 1; ++i) { out.nodes[i] = out.nodes[i + 1]; } --out.count; return out; } // Combine all summand CRCs into a pseudo bloom filter width_t i = 0; detail::crc_t c = 0; while (i < out.count) { auto const& summand = out.nodes[i]; // The lowest 5 bits of the summand map directly to a bit in the crc c |= 1 << (summand.checksum & 31); i += 1 + summand.ex; } auto& sum_node = out.nodes[out.count++]; sum_node.o = op_sum; // NOTE: we don't bother applying a crc function here as the checksum acts as a simple bloom // filter sum_node.checksum = c; sum_node.ex = summand_count; sum_node.q.den = out.count; return out; } template <typename A, width_t S> constexpr auto operator*(int n, detail::rpne<A, S> rhs) { if (n == 0 || rhs.count == 0) { rhs.count = 0; return rhs; } else { rhs.q *= rat{n, 1}; return rhs; } } constexpr auto operator*(int n, detail::rpne_constant c) noexcept { c.q *= rat{n, 1}; return c; } constexpr auto operator*(detail::rpne_constant c, int n) noexcept { c.q *= rat{n, 1}; return c; } constexpr auto operator/(detail::rpne_constant c, int d) noexcept { c.q *= rat{1, d}; return c; } template <typename A, width_t S> constexpr auto operator-(detail::rpne<A, S> in) { if (in.count > 0) { in.q *= minus_one; } return in; } template <typename A, width_t S1, width_t S2> constexpr auto operator-(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { return lhs + -rhs; } template <typename A, width_t S> constexpr auto operator/(detail::rpne<A, S> lhs, int d) { if (lhs.count > 0) { lhs.q *= rat{1, d}; } return lhs; } template <typename A, width_t S> constexpr auto operator/(int lhs, detail::rpne<A, S> const& rhs) { detail::rpne<A, S + 2> out; out.append(detail::rpne_from_constant<A>(lhs, 1)); out.append(rhs); out.append(detail::op_div); out.back().q = rhs.q.reciprocal(); out.q = one; return out; } template <typename A, width_t S1, width_t S2> constexpr auto operator/(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { detail::rpne<A, S1 + S2 + 1> out; out.append(lhs); out.append(rhs); out.append(detail::op_div); out.back().q = lhs.q / rhs.q; out.q = one; return out; } template <typename A, width_t S> constexpr auto operator/(detail::rpne_constant const& lhs, detail::rpne<A, S> const& rhs) { return lhs.template convert<A>() / rhs; } template <typename A, width_t S> constexpr auto operator/(detail::rpne<A, S> const& lhs, detail::rpne_constant const& rhs) { return lhs / rhs.template convert<A>(); } template <typename A, width_t S> constexpr auto operator+(int n, detail::rpne<A, S> const& rhs) { return detail::rpne_from_constant<A>(n, 1) + rhs; } template <typename A, width_t S> constexpr auto operator-(int n, detail::rpne<A, S> const& rhs) { return detail::rpne_from_constant<A>(n, 1) + -rhs; } template <typename A, width_t S> constexpr auto operator+(detail::rpne<A, S> const& lhs, int n) { return detail::rpne_from_constant<A>(n, 1) + lhs; } template <typename A, width_t S> constexpr auto operator-(detail::rpne<A, S> const& lhs, int n) { return detail::rpne_from_constant<A>(-n, 1) + lhs; } template <typename A, width_t S> constexpr auto operator~(detail::rpne<A, S> const& in) { detail::rpne<A, S + 1> out; if (in.count == 0) { return out; } out.append(in); if (in.back().o == detail::op_rev) { --out.count; } else { out.append(detail::op_rev); } return out; } template <typename A, width_t S> constexpr auto operator!(detail::rpne<A, S> const& in) { detail::rpne<A, S + 1> out; if (in.count == 0) { return out; } out.append(in); out.append(detail::op_pd); return out; } template <typename A, width_t S> constexpr auto sqrt(detail::rpne<A, S> const& in) { detail::rpne<A, S + 1> out; out.append(in); out.append(detail::op_sqrt); out.back().q = in.q; out.q = one; return out; } template <typename A, width_t S> constexpr auto sin(detail::rpne<A, S> const& in) { detail::rpne<A, S + 1> out; out.append(in); out.append(detail::op_sin); out.back().q = in.q; out.q = one; return out; } template <typename A, width_t S> constexpr auto cos(detail::rpne<A, S> const& in) { detail::rpne<A, S + 1> out; out.append(in); out.append(detail::op_cos); out.back().q = in.q; out.q = one; return out; } template <typename A, width_t S> constexpr auto tan(detail::rpne<A, S> const& in) { detail::rpne<A, S + 1> out; out.append(in); out.append(detail::op_tan); out.back().q = in.q; out.q = one; return out; } // Closed-form exponential function // NOTE: results are *undefined* when the arg is not a bivector template <typename A, width_t S> constexpr auto exp(detail::rpne<A, S> const& in) { auto s = (in | in)[0]; auto p = (in ^ in)[(1 << A::metric_t::dimension) - 1]; auto u = sqrt(-s); auto v = -p / (2 * u); auto inv_norm = 1 / u + v / s * ::gal::detail::rpne_pseudoscalar<A>(1); auto cosu = cos(u); auto sinu = sin(u); auto real = cosu - v * sinu * ::gal::detail::rpne_pseudoscalar<A>(1); auto ideal = sinu + v * cosu * ::gal::detail::rpne_pseudoscalar<A>(1); return real + ideal * inv_norm * in; } // Closed-form logarithmic function // NOTE: results are *undefined* when the arg is not a member of the even subalgebra // template <typename A, width_t S> // constexpr auto log(detail::rpne<A, S> const& in) // { // detail::rpne<A, S + 1> out; // out.append(in); // out.append(detail::op_log); // return out; // } template <typename A, width_t S1, width_t S2> constexpr auto operator*(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { detail::rpne<A, S1 + S2 + 1> out; if (lhs.count == 0) { out.append(rhs); return out; } else if (rhs.count == 0) { out.append(lhs); return out; } auto q = lhs.q * rhs.q; if (q.is_zero()) { return out; } out.q = q; out.append(lhs); out.append(rhs); out.append(detail::op_gp); out.nodes[out.count - 1].checksum = detail::crc32(lhs.back().checksum + ~rhs.back().checksum + (detail::op_gp << 8)); return out; } template <typename A, width_t S> constexpr auto operator*(detail::rpne<A, S> const& lhs, detail::rpne_constant const& rhs) { return lhs * rhs.template convert<A>(); } template <typename A, width_t S> constexpr auto operator*(detail::rpne_constant const& lhs, detail::rpne<A, S> const& rhs) { return rhs * lhs.template convert<A>(); } template <typename A, width_t S1, width_t S2> constexpr auto operator^(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { detail::rpne<A, S1 + S2 + 3> out; if (lhs.count == 0 || rhs.count == 0 || rhs.q.is_zero() || lhs.q.is_zero()) { return out; } bool lhs_ep = lhs.back().o == detail::op_ep; bool rhs_ep = rhs.back().o == detail::op_ep; width_t lhs_index = 0; width_t rhs_index = 0; uint32_t factor_count = 0; if (lhs_ep && rhs_ep) { factor_count = lhs.back().ex + rhs.back().ex; out.append_omit_ends(lhs); out.append_omit_ends(rhs); } else if (lhs_ep || rhs_ep) { if (lhs_ep) { factor_count = lhs.back().ex + 1; // Omit final op out.append_omit_ends(lhs); out.nodes[out.count++] = detail::node{detail::op_se, rhs.back().checksum, rhs.count, zero}; out.append(rhs); } else { factor_count = rhs.back().ex + 1; out.nodes[out.count++] = detail::node{detail::op_se, lhs.back().checksum, lhs.count, zero}; out.append(lhs); out.append_omit_ends(rhs); } // Merged non-ep factor into ep } else { // Neither the lhs nor the rhs is an exterior product. factor_count = 2; // Check first for equivalency auto lhs_checksum = lhs.back().checksum; auto rhs_checksum = rhs.back().checksum; out.nodes[out.count++] = detail::node{detail::op_se, lhs_checksum, lhs.count, zero}; out.append(lhs); out.nodes[out.count++] = detail::node{detail::op_se, rhs_checksum, rhs.count, zero}; out.append(rhs); out.q = lhs.q * rhs.q; } // Loop through all ep factors to compute the bloom filter width_t i = 1; detail::crc_t c = 0; while (i < out.count) { auto const& ep_f = out.nodes[i]; c |= 1 << (ep_f.checksum & 31); i += 1 + ep_f.ex; } auto& ep_node = out.nodes[out.count++]; ep_node.o = detail::op_ep; ep_node.checksum = c; ep_node.ex = factor_count; ep_node.q.den = out.count; return out; } template <typename A, width_t S1, width_t S2> constexpr auto operator&(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { return !(!lhs ^ !rhs); } template <typename A, width_t S1, width_t S2> constexpr auto operator>>(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { detail::rpne<A, S1 + S2 + 1> out; if (lhs.count == 0) { out.append(rhs); return out; } else if (rhs.count == 0) { out.append(lhs); return out; } auto q = lhs.q * rhs.q; if (q.is_zero()) { return out; } out.q = q; out.append(lhs); out.append(rhs); out.append(detail::op_lc); out.nodes[out.count - 1].checksum = detail::crc32(lhs.back().checksum + ~rhs.back().checksum + (detail::op_lc << 8)); return out; } template <typename A, width_t S1, width_t S2> constexpr auto operator|(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { detail::rpne<A, S1 + S2 + 1> out; if (lhs.count == 0) { out.append(rhs); return out; } else if (rhs.count == 0) { out.append(lhs); return out; } auto q = lhs.q * rhs.q; if (q.is_zero()) { return out; } out.q = q; if (lhs.back().checksum < rhs.back().checksum) { out.append(lhs); out.append(rhs); } else { out.append(rhs); out.append(lhs); } out.append(detail::op_sip); out.nodes[out.count - 1].checksum = detail::crc32(lhs.back().checksum + rhs.back().checksum + (detail::op_sip << 8)); return out; } template <typename A, width_t S1, width_t S2> constexpr auto operator%(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { return rhs * lhs * (~rhs); } template <typename A, width_t S1, width_t S2> constexpr auto scalar_product(detail::rpne<A, S1> const& lhs, detail::rpne<A, S2> const& rhs) { detail::rpne<A, S1 + S2 + 2> out; if (lhs.count == 0) { out.append(rhs); return out; } else if (rhs.count == 0) { out.append(lhs); return out; } auto q = lhs.q * rhs.q; if (q.is_zero()) { return out; } out.q = q; if (lhs.back().checksum < rhs.back().checksum) { out.append(lhs); out.append(rhs); } else { out.append(rhs); out.append(lhs); } // Implement the scalar product as the scalar component of the symmetric inner product out.append(detail::op_sip); out.nodes[out.count - 1].checksum = detail::crc32(lhs.back().checksum + rhs.back().checksum + (detail::op_sip << 8)); out.append(detail::op_comp); out.nodes[out.count - 1].ex = 0; out.nodes[out.count - 1].checksum = out.nodes[out.count - 2].checksum; return out; } #ifdef GAL_DEBUG template <typename A, width_t S> std::string to_string(detail::rpne<A, S> const& in, bool show_checksums = false, bool index = false) { using namespace gal::detail; std::stringstream str; str << in.count << " node(s): " << in.q.num << '/' << in.q.den << '*'; if (index) { str << '\n'; } for (width_t i = 0; i != in.count; ++i) { if (index) { str << '[' << i << "] - "; } auto const& n = in.nodes[i]; switch (n.o) { case op_id: str << "id(" << n.checksum << ") "; break; case op_cse: str << "cse(" << n.ex << ") "; break; case op_se: str << "se(" << n.q.num << '/' << n.q.den << " count: " << n.ex << ") "; break; case op_noop: str << "noop "; break; case op_rev: if (show_checksums) { str << "~(" << n.checksum << ") "; } else { str << "~ "; } break; case op_pd: if (show_checksums) { str << "!(" << n.checksum << ") "; } else { str << "! "; } break; case op_sum: if (show_checksums) { str << "+(" << n.ex << ", " << n.checksum << ") "; } else { str << "+(" << n.ex << ") "; } break; case op_gp: if (show_checksums) { str << "*(" << n.checksum << ") "; } else { str << "* "; } break; case op_ep: if (show_checksums) { str << "^(" << n.ex << ", " << n.checksum << ") "; } else { str << "^ "; } break; case op_lc: if (show_checksums) { str << "<<(" << n.checksum << ") "; } else { str << "<< "; } break; case op_sip: if (show_checksums) { str << "|(" << n.checksum << ") "; } else { str << "| "; } break; case op_comp: str << "[" << n.ex << "] "; break; case op_grd: str << '<' << n.ex << "> "; break; case op_div: if (show_checksums) { str << "/(" << n.checksum << ") "; } else { str << "/" << "(" << n.q.num << '/' << n.q.den << ") "; } break; case op_sqrt: str << "sqrt" << "(" << n.q.num << '/' << n.q.den << ") "; break; case op_sin: str << "sin" << "(" << n.q.num << '/' << n.q.den << ") "; break; case op_cos: str << "cos" << "(" << n.q.num << '/' << n.q.den << ") "; break; case op_tan: str << "tan" << "(" << n.q.num << '/' << n.q.den << ") "; break; case c_zero: str << "0 "; break; case c_pi: str << "pi "; break; case c_e: str << "e "; break; default: uint32_t c = n.o - c_scalar; str << "e_" << c << ' '; break; } if (index) { str << '\n'; } } str << std::endl; return str.str(); } #endif } // namespace gal
64716895c95d3665b516ab89e5c0995a648acad2
b9795d3caf15349f5c81d685492ad99bd6f2ca64
/Comunication Master and Slave/UART/SLAVE-_MEGA_correct/UART.ino
ce1b65265007aa2b34d7993ec3ef8f40406012c7
[]
no_license
RobAmorim/OBR-terceiro-ano-EM
240cb3b11e938cb90a9acecb226747d99c3bea75
b0fee16e20e0b64559b465063bfe54ce2061d28b
refs/heads/master
2022-12-03T01:35:18.658302
2020-08-15T04:32:42
2020-08-15T04:32:42
287,676,359
0
0
null
null
null
null
UTF-8
C++
false
false
287
ino
UART.ino
void Mega_begin(long speed) { Mega.begin(speed); } void Mega_send(int value) { delayMicroseconds(200); Mega.write(value); } int Mega_receive() { int received = 0; if (Serial3.available() > 0){ received = Mega.read(); } return received; }
f1c465960e1940891bc5914e0d34da88ff6b3d00
394baa93338a6510a34700a953d1119594efd36a
/tempCodeRunnerFile.cpp
585eb2f8591e5d70234156f863ec2bf9cf4c1954
[]
no_license
anusjc/CPP
43dfe1680a5b1a00d363bff56319549db1992d40
e7b29634d2c36b8e28013d0f10c3ed47cb6a674f
refs/heads/master
2023-06-24T15:24:41.929533
2021-07-26T15:35:43
2021-07-26T15:35:43
275,631,954
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
tempCodeRunnerFile.cpp
out << "Inorder"; // Inorder(root); // cout << "Inorder Without Recursion"; // Inorder_without_Recursion(root); // cout << "Pre"; // PreOrder(root); // cout << "PreOrder without Recursion"; // Preorder_without_Recursion(root); // cout << "Post"; // PostOrder(root); // cout << "PostOrder without Recursion"; // P
5814727de7157fbfe953b46e9d18060fa451fd7a
52e05d8943a90960923d84c1c0068abf52c66faf
/homework/HW8_midterm2/src/find_visitor.h
435a1477e6efc309761b2cbe0bc8099a2075a1a0
[]
no_license
babe18/10901_ntut_posd
878896d9f99fcc86945b0b7385eef539ece7791f
6c4fd99b696b171c32e14f68a13d3816da764e24
refs/heads/main
2023-02-19T20:19:56.816458
2021-01-20T15:40:49
2021-01-20T15:40:49
300,562,526
0
0
null
null
null
null
UTF-8
C++
false
false
2,046
h
find_visitor.h
#ifndef FIND_VISITOR_H #define FIND_VISITOR_H #include <cmath> #include <vector> #include "iterator.h" #include "node_iterator.h" #include "app.h" #include "node.h" #include "folder.h" #include "visitor.h" class FindVisitor : public Visitor { public: FindVisitor(std::string name):_name(name) {} void visitApp(App* app) { if(_name==app->name()){ result = app->route(); } } void visitFolder(Folder* folder) { if(_name==folder->name()) result = folder->route(); Iterator * it = folder->createIterator(); if(!it->isDone()){ for(it->first();!it->isDone();it->next()){ if(it->currentItem()->name()==_name) { if(result!="") result +="\n"; result += it->currentItem()->route(); } if(!it->currentItem()->createIterator()->isDone()){ Iterator * it2 = it->currentItem()->createIterator(); for(it2->first(); !it2->isDone(); it2->next()){ if(it2->currentItem()->name()==_name) { if(result!="") result +="\n"; result += it2->currentItem()->route(); } if(!it2->currentItem()->createIterator()->isDone()){ Iterator * it3 = it2->currentItem()->createIterator(); for(it3->first(); !it3->isDone(); it3->next()){ if(it3->currentItem()->name()==_name) { if(result!="") result +="\n"; result += it3->currentItem()->route(); } } } } } } } } std::string getResult() const { return result; } private: string result =""; string _name; }; #endif
f8ff08e07aecb2b68ba79e783a67082474073ecf
a382b8a6ed180ffdb9dc8fb1f2443398e2b9cf94
/wk4dpointsofview.cpp
b53fdccb76df1530922249cd90d28de2a5dbc51b
[ "MIT" ]
permissive
WhaleKit/4d-cube-Slicer
863a9e47ff08509a1507667da9556eda85d28c2b
6a45df6ad211d9a7c564bc52a4093c2a51b6ebdb
refs/heads/master
2020-06-25T10:13:55.001866
2017-10-02T02:50:12
2017-10-02T02:50:12
96,973,226
1
0
null
null
null
null
UTF-8
C++
false
false
95
cpp
wk4dpointsofview.cpp
#include "wk4dpointsofview.h" WK4d::vec4 WK4d::FPSPointOfView::myUp = WK4d::vec4{0,0,1,0};
87bf1e38d452ce6af8b609bebe36c12522b471a3
e8be5e13152f1ccfece36ba47569614a87842d96
/GameSanGuo/GameSanGuo/Classes/game/main/first/help/SGLiuyanLayer.cpp
edefa995c90fe777c147c4ae644e06bdb566d601
[]
no_license
Crasader/warCraft
571ed9a3181b0eb52940cdd2965b7445c004d58f
b9cf69828c61bdf55b2af3b587f3be06de93768c
refs/heads/master
2020-12-13T18:05:17.592831
2016-01-19T13:42:19
2016-01-19T13:42:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,691
cpp
SGLiuyanLayer.cpp
// // SGLiuyanLayer.cpp // GameSanGuo // // Created by kanata on 14-1-6. // // #include "SGLiuyanLayer.h" #include "ResourceManager.h" #include "SGMainManager.h" #include "SGCCTextFieldTTF.h" #include "SGChatInputBox.h" #include "SGComplainLayer.h" #include "CCTextFieldTTF.h" #include "SGNikeNameBox.h" #include "SGStringConfig.h" SGLiuyanLayer::SGLiuyanLayer() :quexian(NULL), jianyi(NULL), jubao (NULL), chongzhi(NULL), m_pEditTitle(NULL), m_pTextField(NULL), m_pTextFieldqq(NULL), now_tag(0), label1(NULL), label2(NULL), label3(NULL), label4(NULL), ttf(NULL) { now_tag=0; } SGLiuyanLayer::~SGLiuyanLayer() { ResourceManager::sharedInstance()->unBindLayerTexture(sg_liuyan); SGMainLayer *layer = (SGMainLayer*)SGMainManager::shareMain()->getMainScene()->getChildByTag(sg_mainLayer); layer->getChildByTag(10000)->setVisible(true); SGNotificationCenter *sgnc = SGNotificationCenter::sharedNotificationCenter(); sgnc->removeObserver(this, MSG_SUBQA); } SGLiuyanLayer *SGLiuyanLayer::create() { SGLiuyanLayer *Layer = new SGLiuyanLayer(); if (Layer && Layer->init(NULL, sg_liuyan)) { Layer->initView(); Layer->autorelease(); return Layer; } CC_SAFE_DELETE(Layer); return NULL; } void SGLiuyanLayer::initView() { ResourceManager::sharedInstance()->bindTexture("sgfirstlayer/sgfirstlayer.plist", RES_TYPE_LAYER_UI, sg_liuyan, LIM_PNG_AS_PNG); ResourceManager::sharedInstance()->bindTexture("sgfindhelplayer/sgfindhelplayer.plist", RES_TYPE_LAYER_UI, sg_liuyan); ResourceManager::sharedInstance()->bindTexture("sggeneralslayer/sggeneralslayer.plist", RES_TYPE_LAYER_UI, sg_liuyan); //////////////////// SGNotificationCenter *sgnc = SGNotificationCenter::sharedNotificationCenter(); sgnc->addObserver(MSG_SUBQA, this, callfuncO_selector(SGLiuyanLayer::sbumitsuccess)); ////////////////// SGMainLayer *layer = (SGMainLayer*)SGMainManager::shareMain()->getMainScene()->getChildByTag(sg_mainLayer); layer->getChildByTag(10000)->setVisible(false); float bottomH = SGMainManager::shareMain()->getBottomHeight(); float headH = SGMainManager::shareMain()->getTotleHdHgt(); CCPoint center = SGLayout::getPoint(kMiddleCenter); float headhgt = SGMainManager::shareMain()->getTotleHdHgt(); CCSize s = CCDirector::sharedDirector()->getWinSize(); float discY = s.height-headH-bottomH+65; //////手动加一个bg ResourceManager::sharedInstance()->bindTexture("sanguobigpic/barrack_bg.plist", RES_TYPE_LAYER_UI, sg_liuyan); CCSprite *background2 = CCSprite::createWithSpriteFrameName("barrack_bg.png"); background2->setScaleX(s.width/background2->getContentSize().width * 1.01); background2->setAnchorPoint(ccp(0.5, 0.5)); background2->setPosition(ccpAdd(center, ccp(0, 0))); this->addChild(background2,-10); ////方形大bg // CCSprite *infoBg = CCSprite::createWithSpriteFrameName("fight_over_bg_n.png"); CCScale9Sprite *infoBg = CCScale9Sprite::createWithSpriteFrameName("fight_over_bg_n.png"); infoBg->setPreferredSize(CCSizeMake(skewing(300) + 10, discY*0.85)); //infoBg->setPosition(center); infoBg->setPosition(ccpAdd(center, ccp( 7 , -infoBg->getContentSize().height*0.1))); CCSize sizefd= infoBg->getContentSize(); // infoBg->setPosition(ccp(s.width*.5f, bottomH + discY*.49f-20)); this->addChild(infoBg); //线 CCSprite *line = CCSprite::createWithSpriteFrameName("uplevel_fontline_n.png"); line->setPosition(ccpAdd(infoBg->getPosition(), ccp(infoBg->getContentSize().width*0.0, infoBg->getContentSize().height*0.37))); this->addChild(line); CCSprite *title_bg = CCSprite::createWithSpriteFrameName("title_bg.png"); title_bg->setAnchorPoint(ccp(0.5, 1)); title_bg->setPosition(ccpAdd(SGLayout::getPoint(kUpCenter), ccp(0, -headhgt + title_bg->getContentSize().height-2))); this->addChild(title_bg,-1); CCSprite *titlecenter = CCSprite::createWithSpriteFrameName("title_bg_2.png"); titlecenter->setAnchorPoint(ccp(0.5, 0)); titlecenter->setPosition(ccpAdd(title_bg->getPosition(), ccp(0, - title_bg->getContentSize().height -10))); this->addChild(titlecenter,10); titlecenter->setScaleX(4); CCSprite *title_bg_l = CCSprite::createWithSpriteFrameName("title_bg_LR.png"); title_bg_l->setAnchorPoint(ccp(0, 0)); title_bg_l->setPosition(ccpAdd(title_bg->getPosition(), ccp(-s.width/2, - title_bg->getContentSize().height -10))); this->addChild(title_bg_l,10); CCSprite *title_bg_r = CCSprite::createWithSpriteFrameName("title_bg_LR.png"); title_bg_r->setFlipX(true); title_bg_r->setAnchorPoint(ccp(1, 0)); title_bg_r->setPosition(ccpAdd(title_bg->getPosition(), ccp(s.width/2, - title_bg->getContentSize().height -10))); this->addChild(title_bg_r,10); SGButton *backBtn = SGButton::createFromLocal("store_exchangebtnbg.png", str_back, this, menu_selector(SGLiuyanLayer::backHandler),CCPointZero,FONT_PANGWA,ccWHITE,32); this->addBtn(backBtn); backBtn->setPosition(ccp(backBtn->getContentSize().width*.55,title_bg->getPosition().y -title_bg->getContentSize().height*.5f)); // CCSprite *title = CCSprite::createWithSpriteFrameName("help_font_kptj.png"); SGCCLabelTTF *title = SGCCLabelTTF::create(str_LiuyanLayer_str1, FONT_XINGKAI, 36 , COLOR_UNKNOW_TAN); //modify by:zyc. merge into create. //title->setColor(ccc3(0xff, 0x95, 0x0c)); title->setPosition(ccp(s.width/2, backBtn->getPosition().y)); this->addChild(title); ////提交按钮 SGButton *tijiao = SGButton::createFromLocal("box_btnbg.png", str_LiuyanLayer_str2, this,menu_selector(SGLiuyanLayer::submit),CCPointZero,FONT_BOXINFO,ccWHITE,28); tijiao->setPosition(ccpAdd(infoBg->getPosition(), ccp(0, -infoBg->getContentSize().height*0.42))); this->addBtn(tijiao); //////////////////////////////////////// quexian = SGButton::create("anDian.png", "anDian.png", this, menu_selector(SGLiuyanLayer::setWhiteAndDark), ccp(0, 0), false, true); quexian->setPosition(ccpAdd(ccp(0,line->getPositionY()), ccp(s.width*0.15, backBtn->getContentSize().height*0.6))); this->addBtn(quexian); quexian->setTag(100); ///缺陷本体字 label1=SGCCLabelTTF::create(str_LiuyanLayer_str3, FONT_BOXINFO, 30); label1->setAnchorPoint(ccp(0, 0.5)); label1->setPosition(ccpAdd(quexian->getPosition(), ccp(quexian->getContentSize().width*0.3, 0))); this->addChild(label1); /////////建议 jianyi = SGButton::create("anDian.png", "anDian.png", this, menu_selector(SGLiuyanLayer::setWhiteAndDark), ccp(0, 0), false, true); jianyi->setPosition(ccpAdd(quexian->getPosition(), ccp(s.width*0.2,0))); this->addBtn(jianyi); jianyi->setTag(101); ///建议本体字 label2=SGCCLabelTTF::create(str_LiuyanLayer_str4, FONT_BOXINFO, 30); label2->setPosition(ccpAdd(jianyi->getPosition(), ccp(jianyi->getContentSize().width*0.3, 0))); label2->setAnchorPoint(ccp(0, 0.5)); this->addChild(label2); //////////////举报 jubao = SGButton::create("anDian.png", "anDian.png", this, menu_selector(SGLiuyanLayer::setWhiteAndDark), ccp(0, 0), false, true); jubao->setPosition(ccpAdd(jianyi->getPosition(), ccp(s.width*0.2,0))); this->addBtn(jubao); jubao->setTag(102); ///举报本体字 label3=SGCCLabelTTF::create(str_LiuyanLayer_str5, FONT_BOXINFO, 30); label3->setPosition(ccpAdd(jubao->getPosition(), ccp(jubao->getContentSize().width*0.3, 0))); label3->setAnchorPoint(ccp(0, 0.5)); this->addChild(label3); /////////////储值 chongzhi = SGButton::create("anDian.png", "anDian.png", this, menu_selector(SGLiuyanLayer::setWhiteAndDark), ccp(0, 0), false, true); chongzhi->setPosition(ccpAdd(jubao->getPosition(), ccp(s.width*0.2, 0))); this->addBtn(chongzhi); chongzhi->setTag(103); ///储值本体字 label4=SGCCLabelTTF::create(str_LiuyanLayer_str6, FONT_BOXINFO, 30); label4->setPosition(ccpAdd(chongzhi->getPosition(), ccp(chongzhi->getContentSize().width*0.3, 0))); label4->setAnchorPoint(ccp(0, 0.5)); this->addChild(label4); ////输入框前的字 SGCCLabelTTF*labelkuang_1=SGCCLabelTTF::create(str_LiuyanLayer_str7, FONT_BOXINFO, 30); labelkuang_1->setAnchorPoint(ccp(1, 0.5)); labelkuang_1->setPosition(ccpAdd(quexian->getPosition(), ccp(quexian->getContentSize().width*0.8, -quexian->getContentSize().height*0.9))); this->addChild(labelkuang_1); SGCCLabelTTF*labelkuang_2=SGCCLabelTTF::create(str_LiuyanLayer_str8, FONT_BOXINFO, 30); labelkuang_2->setAnchorPoint(ccp(0, 0.5)); labelkuang_2->setPosition(ccpAdd(labelkuang_1->getPosition(), ccp(-labelkuang_1->getContentSize().width, -quexian->getContentSize().height*0.9+5))); this->addChild(labelkuang_2); /////详细描述输入框 CCScale9Sprite *m_detailinput = CCScale9Sprite::create("sanguobigpic/tipsinside.png"); #if (PLATFORM == IOS) m_detailinput->setPreferredSize(CCSizeMake(s.width-20, discY*0.5)); m_detailinput->setPosition(ccpAdd(ccp(s.width/2 +30, 0), ccp(0, tijiao->getPosition().y+m_detailinput->getContentSize().height*0.57)));//0.77))); #else m_detailinput->setPreferredSize(CCSizeMake(s.width -20, discY*0.5)); m_detailinput->setPosition(ccpAdd(ccp(s.width/2 + 30, 0), ccp(0, tijiao->getPosition().y+m_detailinput->getContentSize().height*0.57))); #endif addChild(m_detailinput); m_pTextFieldqq = MYtextfieldttf::createWithPlaceHolder(ccpAdd(center, ccp(0, -200)),str_LiuyanLayer_str9, CCSizeMake(s.width*0.9, discY*0.4),kCCTextAlignmentLeft,FONT_BOXINFO, 35); m_pTextFieldqq->setKType(1); m_pTextFieldqq->setColor(ccBLACK); m_pTextFieldqq->setLength(100); m_pTextFieldqq->setKeyboardType(KEY_BOARD_TYPE_NORMAL); m_pTextFieldqq->setPosition(ccpAdd(m_detailinput->getPosition() , ccp(-12 , 0) )); this->addChild(m_pTextFieldqq); ///字数限制 SGCCLabelTTF*labelxianzhi=SGCCLabelTTF::create(str_LiuyanLayer_str10, FONT_BOXINFO, 30 , ccc3(0xc9, 0xa1, 0x5f)); labelxianzhi->setAnchorPoint(ccp(0, 0)); //labelxianzhi->setPosition(ccpAdd(m_detailinput->getPosition(), ccp(m_detailinput->getContentSize().width*0.5 - labelxianzhi->getContentSize().width/2 + 22, -m_detailinput->getContentSize().height*0.5))); labelxianzhi->setPosition(ccp(tijiao->getPositionX() + tijiao->getContentSize().width*0.5 + 20, tijiao->getPositionY() ) ); this->addChild(labelxianzhi); // CCTextFieldTTF * CCTextFieldTTF::textFieldWithPlaceHolder(const char *placeholder, const CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float fontSize) // ttf=CCTextFieldTTF::textFieldWithPlaceHolder("啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊",CCSizeMake(s.width*0.9, discY*0.4),kCCTextAlignmentLeft,FONT_BOXINFO, 35); // ttf->setColor(ccRED); // ttf->setPosition(m_detailinput->getPosition()); // this->addChild(ttf); //标题输入框 m_pEditTitle = CCEditBox::create(CCSizeMake(s.width*0.7, 50), CCScale9Sprite::createWithSpriteFrameName("public_kuang_input.png")); m_pEditTitle->setPlaceHolder(str_LiuyanLayer_str11); m_pEditTitle->setMaxLength(14); m_pEditTitle->setReturnType(kKeyboardReturnTypeDone); m_pEditTitle->setInputMode(kEditBoxInputModeEmailAddr); m_pEditTitle->setReturnType(kKeyboardReturnTypeDone); // m_pEditTitle->setDelegate(this); this->addChild(m_pEditTitle,9); m_pEditTitle->setAnchorPoint(ccp(0, 0.5)); m_pEditTitle->setPosition(ccpAdd(labelkuang_1->getPosition(), ccp(10, 0))); m_pEditTitle->setFontColor(ccRED); } void SGLiuyanLayer::backHandler() { EFFECT_PLAY(MUSIC_BTN); SGPlayerInfo *playerInfo = SGPlayerInfo::sharePlayerInfo(); SGComplainLayer *layer = SGComplainLayer::create(playerInfo->getQAContent()); SGMainManager::shareMain()->showLayer(layer); // m_pTextField->detachWithIME(); // SGMainManager::shareMain()->showcomplainlayer(); } void SGLiuyanLayer::setWhiteAndDark(CCNode*node)///////四个按钮 tag是100 101 102 103 { now_tag=node->getTag(); // SGButton*btn= (SGButton*) getBtnByTag(now_tag); changestate(now_tag); } /////// void SGLiuyanLayer::setWhiteAndDarktouch(int btntype)///////cctouch { now_tag=btntype; // SGButton*btn= (SGButton*) getBtnByTag(now_tag); changestate(now_tag); } /////// void SGLiuyanLayer::changestate(int tag) { SGButton*btn100= (SGButton*) getBtnByTag(100); SGButton*btn101= (SGButton*) getBtnByTag(101); SGButton*btn102= (SGButton*) getBtnByTag(102); SGButton*btn103= (SGButton*) getBtnByTag(103); SGButton*temp=(SGButton*) getBtnByTag(tag); temp->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("liangDian.png")->getCString())->displayFrame()); if(tag==100) { btn101->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn102->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn103->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); } if(tag==101) { btn100->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn102->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn103->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); } if(tag==102) { btn101->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn100->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn103->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); } if(tag==103) { btn101->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn102->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); btn100->setFontImage(CCSprite::createWithSpriteFrameName(CCString::create("anDian.png")->getCString())->displayFrame()); } } void SGLiuyanLayer::submit() /////提交的内容 { long nowtime=getCurrentTime(); SGPlayerInfo *player = SGPlayerInfo::sharePlayerInfo(); long oldtime=player->getoldtime(); long distance=nowtime-oldtime; if(distance<120) { SG_SHOW_WINDOW(str_LiuyanLayer_str12); return; } // const char *str=m_pEditTitle->getText(); // const char *str2= m_pTextFieldqq->getString(); CCLOG("%s88888888888888%s",m_pEditTitle->getText(),m_pTextFieldqq->getString()); if(now_tag==0) { SG_SHOW_WINDOW(str_LiuyanLayer_str13); return; } char buffer[1024] = {}; strcpy(buffer, m_pEditTitle->getText()); if (GameConfig::isContainsEmoji(buffer)) { SG_SHOW_WINDOW(str_NikeNameBox_str3); return; } if(SGNikeNameBox::utf8StrLength(buffer)==0) { SG_SHOW_WINDOW(str_LiuyanLayer_str14); return; } char temp[1024] = {}; strcpy(temp, m_pTextFieldqq->getString()); if (GameConfig::isContainsEmoji(temp)) { SG_SHOW_WINDOW(str_NikeNameBox_str3); return; } if(SGNikeNameBox::utf8StrLength(temp)==0) { SG_SHOW_WINDOW(str_LiuyanLayer_str15); return; } CCString*question=CCString::create(m_pTextFieldqq->getString()); CCString*title=CCString::create(m_pEditTitle->getText());; main::SubQARequest*request=new main::SubQARequest(); request->set_type(now_tag-99); request->set_question(question->m_sString); request->set_title(title->m_sString); SGSocketClient::sharedSocketClient()->send(MSG_SUBQA, request); } void SGLiuyanLayer::sbumitsuccess(CCObject*obj) { SGSocketRequest *sr = (SGSocketRequest *)obj; main::SubQAResponse *response = (main::SubQAResponse *)sr->m_msg; int m= response->state(); if(m) { SG_SHOW_WINDOW(str_LiuyanLayer_str16); //////// long oldtime=getCurrentTime(); SGPlayerInfo *playerinfo = SGPlayerInfo::sharePlayerInfo(); playerinfo->setoldtime(oldtime); /////// SGQAConcent *player = new SGQAConcent(); player->setID(response->id()); std::string str(response->title()); CCString* ns=CCString::createWithFormat("%s",str.c_str()); player->setTitle(ns); player->setType(response->type()); std::string str2(response->createdate()); CCString* nn=CCString::createWithFormat("%s",str2.c_str()); player->setcreateDate(nn); //////////////////////// std::vector<SGQAConcent*> vec; vec.push_back(player); //////////////////////////////////////////////////////////////////手动刷新列表顺序,将刚提交的放在最上方 SGMainLayer *mainlayer = (SGMainLayer*)SGMainManager::shareMain()->getMainScene()->getChildByTag(sg_mainLayer); mainlayer->updateqa(player); // // CCArray *temp = SGPlayerInfo::sharePlayerInfo()->getQAContent(); // CCArray* array=CCArray::create(); // int m=temp->count(); // // for(int i=0;i<m;i++) // { // // SGQAConcent * qa = (SGQAConcent*)temp->objectAtIndex(i); // // array->addObject(qa); // // } // // SGPlayerInfo::sharePlayerInfo()->getQAContent()->removeAllObjects();////清空原有信息 // // ////////添加新信息 // // int qqq=1; // if(qqq==1) // { // SGPlayerInfo::sharePlayerInfo()->addQAContent(player); // qqq=0; // } // // for(int i=0;i<m;i++) // { // // SGQAConcent * qa = (SGQAConcent*)array->objectAtIndex(i); // // // // newtemp->addObject(qa); /////////新顺序 // // // SGPlayerInfo::sharePlayerInfo()->addQAContent(qa); // // } // // //////////////// SGPlayerInfo *playerInfo = SGPlayerInfo::sharePlayerInfo(); SGComplainLayer *layer = SGComplainLayer::create(playerInfo->getQAContent()); SGMainManager::shareMain()->showLayer(layer); ///////////////// } else { SG_SHOW_WINDOW(str_LiuyanLayer_str17); } } #pragma mark editBox delegate void SGLiuyanLayer::editBoxEditingDidBegin(cocos2d::extension::CCEditBox* editBox) { CCLog("editBox %p DidBegin !", editBox); } void SGLiuyanLayer::editBoxEditingDidEnd(cocos2d::extension::CCEditBox* editBox) { CCLog("editBox %p DidEnd !", editBox); } void SGLiuyanLayer::editBoxTextChanged(cocos2d::extension::CCEditBox* editBox, const std::string& text) { CCLog("editBox %p TextChanged, text: %s ", editBox, text.c_str()); } void SGLiuyanLayer::editBoxReturn(cocos2d::extension::CCEditBox* editBox) { } ///////////////// void SGLiuyanLayer::onEnter() { SGBaseLayer::onEnter(); CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 99, true); } void SGLiuyanLayer::onExit() { SGBaseLayer::onExit(); CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); } // void SGLiuyanLayer::registerWithTouchDispatcher() //{ // CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, -222, false); //} bool SGLiuyanLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { return true; } void SGLiuyanLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { // CCPoint touchPos = pTouch->getLocation(); // if(buttonSend->boundingBox().containsPoint(touchPos)) // { // if(buttonSend->isSelected()) // { // buttonSend->unselected(); // buttonSend->activate(); // } // } // // if(buttonCancel->boundingBox().containsPoint(touchPos)) // { // if(buttonCancel->isSelected()) // { // buttonCancel->unselected(); // buttonCancel->activate(); // } // } // // // CCRect faceRect = CCRectMake(item->getPosition().x - item->getContentSize().width * .5 , // item->getPosition().y - 54, // skewing(320), // 108); CCRect labelrect1 = CCRectMake(label1->getPosition().x ,label1->getPosition().y- label1->getContentSize().height * .5,label1->getContentSize().width,label1->getContentSize().height) ; CCRect labelrect2 = CCRectMake(label2->getPosition().x ,label2->getPosition().y- label2->getContentSize().height * .5,label2->getContentSize().width,label2->getContentSize().height) ; CCRect labelrect3 = CCRectMake(label3->getPosition().x,label3->getPosition().y - label3->getContentSize().height * .5,label3->getContentSize().width,label3->getContentSize().height) ; CCRect labelrect4 = CCRectMake(label4->getPosition().x ,label4->getPosition().y- label4->getContentSize().height * .5,label4->getContentSize().width,label4->getContentSize().height) ; CCPoint touchpoint=pTouch->getLocation(); if(labelrect1.containsPoint(touchpoint)) { setWhiteAndDarktouch(100); } if (labelrect2.containsPoint(touchpoint)) { setWhiteAndDarktouch(101); } if (labelrect3.containsPoint(touchpoint)) { setWhiteAndDarktouch(102); } if (labelrect4.containsPoint(touchpoint)) { setWhiteAndDarktouch(103); } } ///////////////////////// long SGLiuyanLayer::getCurrentTime() { struct cc_timeval tv; CCTime::gettimeofdayCocos2d(&tv, NULL); return tv.tv_sec; } /////////////////////////
094615afc7958ed63f61ad1f3bdee84ae725270f
35cd9b31b72055eaec45965f5ca5cfd1db8366f0
/90_SubsetsII.cpp
cd13bd78c89721960367691e20194e29c17cb4af
[]
no_license
ZhengweiLi/_LeetCode
f15ba4b0bf3bb2b3a3b0fd5f102cb1c8637df013
e6fe66299b81275caa003413be49a13becbe7db8
refs/heads/master
2020-12-05T16:19:26.433445
2020-04-07T16:45:11
2020-04-07T16:45:11
232,170,332
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
90_SubsetsII.cpp
/* Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. Example: Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] */ class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { if(nums.empty()) return {}; vector<vector<int>> res(1); sort(nums.begin(), nums.end()); int size = 1, last = nums[0]; for(int i = 0; i < nums.size(); i++){ if(last != nums[i]){ last = nums[i]; size = res.size(); } int newSize = res.size(); for(int j = newSize - size; j < newSize; j++){ res.push_back(res[j]); res.back().push_back(nums[i]); } } return res; } };
2889045dac00cf77cbbc5bc703c88baed29db414
780148a92032625cf51463d40d933c686b8be046
/codeforces/round480_div2/c2.cpp
d10f8ae6421cedc81df4b3120c3d7349fbccb451
[]
no_license
Shaofanl/alg
30a980177eb6cbc2cf36f0e434bc7db8c8f937b5
55c721451731c8941a7b0ce4c286be02d2cbef31
refs/heads/master
2020-03-16T09:53:33.928100
2019-04-14T04:29:24
2019-04-14T04:29:24
132,624,809
0
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
c2.cpp
// summary: // should use greedy on the correct direction // early or over-strict greedy might cause error #include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> g(259, -1); vector<bool> took(258, false); vector<int> ans; g[0] = 0; while (n--) { int t; cin >> t; int ptr = t; while (ptr>=1 && !took[ptr]) ptr--; ptr = g[ptr]; if (t-ptr+1>k) { ptr = t; while (ptr>=1 && !took[ptr-1] && t-ptr+1<k) ptr--; } for (int i = ptr; i <= t; ++i) { took[i] = true; g[i] = ptr; } cout << g[t] << ' '; } cout << endl; }
5e6f65977ad05b2cd4bb755b467236bb68eb4bbf
8c85d929c8855337c39db8772e6b26c669451a7f
/Source/Engine/Scripting/ScriptThread.hpp
9fddc8ffca80e576c7689bf14d601d177a09e196
[]
no_license
grokitgames/giga
6d908c2a12a6e95e6d22ef2c37520bf6d666142d
83ec3b023cebc5762f117dd35da57379d3e4b2a9
refs/heads/master
2021-01-01T19:45:49.625486
2017-11-28T02:02:37
2017-11-28T02:02:37
98,677,734
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
hpp
ScriptThread.hpp
#ifndef scriptthread_hpp #define scriptthread_hpp class GIGA_API ScriptThread : public TaskThread { public: ScriptThread(); ~ScriptThread(); /** * Thread initialization */ void Initialize(); /** * Thread shutdown */ void Shutdown(); /** * Get isolate */ v8::Isolate* GetIsolate() { return m_isolate; } /** * Lock thread */ void Lock(ScriptThread* thread); /** * Check lock */ bool IsLocked(); /** * Unlock */ void Unlock(); /** * Get an implementation by name */ ScriptableObjectImpl* GetScriptableImpl(std::string name); /** * The currently executing script (so events can be proxied back in) */ void SetCurrentScript(ScriptComponent* component) { m_currentScript = component; } ScriptComponent* GetCurrentScript() { return m_currentScript; } protected: // V8 isolated execution environment (own heap, stack, GC, etc.) v8::Isolate* m_isolate; v8::Locker* m_locker; // Scriptable object types initialized in this isolate std::vector<ScriptableObjectImpl*> m_impls; // Currently executing script component ScriptComponent* m_currentScript; // The thread which is currently locking this ScriptThread* m_currentLocker; }; #endif
c3f7ad4fb935ffb6a432571c3e83afb6ea3ec679
4e154f27fad2f07d007aa96015d9d276fcd68d06
/NetWorkFrame/lib/net/TestMain.h
15e3ba308833c0d96102dd8aa470dea7bc861e77
[]
no_license
00675901/netTest
1ac06c47ad1f5e7ae69ff31b021892cec4b8d01f
bb0e45466aac2f73ac04c611da8c654832cfd21d
refs/heads/master
2016-09-06T16:46:21.333534
2015-07-12T16:10:40
2015-07-12T16:10:40
38,488,020
0
0
null
null
null
null
UTF-8
C++
false
false
202
h
TestMain.h
// // TestMain.h // #include "GUtils.h" class TestMain{ public: TestMain(){ printf("TestMain Begin\n"); } ~TestMain(){ printf("TestMain End\n"); } void begin(); };
2bd31ee36a9f930b08b739c7814aa311ea9b1596
c68b819f5254ddf8fb2ff6596538fc294226df38
/src/Arguments/TemplateReqArg_P.cpp
d752ae05fcda3e36e311b9fc2a79e11d3cebae16
[ "MIT" ]
permissive
peterfarouk01/SimpleCLI
76f14206b308eb7fd73036ea6cb0ce0764a89fd0
f8a61c541955971fa7b140033def8173d353d40a
refs/heads/master
2020-03-27T04:43:36.541073
2018-08-09T15:13:18
2018-08-09T15:13:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,816
cpp
TemplateReqArg_P.cpp
#include "TemplateReqArg_P.h" namespace simpleCLI { TemplateReqArg_P::TemplateReqArg_P(const char* _template) { TemplateReqArg_P::_template = _template; reset(); } TemplateReqArg_P::~TemplateReqArg_P() { if (value) delete value; if (next) delete next; } bool TemplateReqArg_P::equals(const char* name) { return strlen_P(name) == 0; } bool TemplateReqArg_P::equals(String name) { return name.length() == 0; } void TemplateReqArg_P::setValue(String value) { if (value.length() > 0) { char* tmpTemplate = NULL; if (_template) { int strLen = strlen_P(_template); tmpTemplate = new char[strLen + 1]; strcpy_P(tmpTemplate, _template); tmpTemplate[strLen] = '\0'; } index = simpleCLI::equals(value.c_str(), tmpTemplate); if (index >= 0) { if (TemplateReqArg_P::value) delete TemplateReqArg_P::value; int strLen = value.length() + 1; TemplateReqArg_P::value = new char[strLen]; value.toCharArray(TemplateReqArg_P::value, strLen); set = true; } delete tmpTemplate; } } void TemplateReqArg_P::reset() { if (value) { delete value; value = NULL; } index = -1; Arg::reset(); } String TemplateReqArg_P::getValue() { return value ? String(value) : String(); } bool TemplateReqArg_P::isRequired() { return true; } int TemplateReqArg_P::getValueIndex() { return index; } String TemplateReqArg_P::toString() { return '<' + readTemplate(_template) + '>'; } }
9e28a6ee5346f3c7a84ec588f154da07f22506a5
81bf548ee9a4a9bc506782ba4b8e5632d16bf86a
/src/utils/shadercompile/subprocess.cpp
0072fd3865caabd3cb55102c85b14343dac0d12d
[]
no_license
hackovh/-
f6b83e6a1c514f8b452d4d14f932d452e4b4110d
72286069ef9dd5975448cc6fe4c5911734edabe6
refs/heads/master
2020-05-19T06:12:56.778623
2019-05-04T07:57:52
2019-05-04T07:57:52
184,868,637
4
1
null
null
null
null
UTF-8
C++
false
false
7,556
cpp
subprocess.cpp
//====== Copyright c 1996-2007, Valve Corporation, All rights reserved. =======// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include <windows.h> #include "cmdsink.h" #include "subprocess.h" #include "d3dxfxc.h" #include "tools_minidump.h" ////////////////////////////////////////////////////////////////////////// // // Base implementation of the shaderd kernel objects // ////////////////////////////////////////////////////////////////////////// SubProcessKernelObjects::SubProcessKernelObjects( void ) : m_hMemorySection( NULL ), m_hMutex( NULL ) { ZeroMemory( m_hEvent, sizeof( m_hEvent ) ); } SubProcessKernelObjects::~SubProcessKernelObjects( void ) { Close(); } BOOL SubProcessKernelObjects::Create( char const *szBaseName ) { char chBufferName[0x100] = { 0 }; sprintf( chBufferName, "%s_msec", szBaseName ); m_hMemorySection = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4 * 1024 * 1024, chBufferName ); // 4Mb for a piece if ( NULL != m_hMemorySection ) { if ( ERROR_ALREADY_EXISTS == GetLastError() ) { CloseHandle( m_hMemorySection ); m_hMemorySection = NULL; Assert( 0 && "CreateFileMapping - already exists!\n" ); } } sprintf( chBufferName, "%s_mtx", szBaseName ); m_hMutex = CreateMutex( NULL, FALSE, chBufferName ); for ( int k = 0; k < 2; ++ k ) { sprintf( chBufferName, "%s_evt%d", szBaseName, k ); m_hEvent[k] = CreateEvent( NULL, FALSE, ( k ? TRUE /* = master */ : FALSE ), chBufferName ); } return IsValid(); } BOOL SubProcessKernelObjects::Open( char const *szBaseName ) { char chBufferName[0x100] = { 0 }; sprintf( chBufferName, "%s_msec", szBaseName ); m_hMemorySection = OpenFileMapping( FILE_MAP_ALL_ACCESS, FALSE, chBufferName ); sprintf( chBufferName, "%s_mtx", szBaseName ); m_hMutex = OpenMutex( MUTEX_ALL_ACCESS, FALSE, chBufferName ); for ( int k = 0; k < 2; ++ k ) { sprintf( chBufferName, "%s_evt%d", szBaseName, k ); m_hEvent[k] = OpenEvent( EVENT_ALL_ACCESS, FALSE, chBufferName ); } return IsValid(); } BOOL SubProcessKernelObjects::IsValid( void ) const { return m_hMemorySection && m_hMutex && m_hEvent; } void SubProcessKernelObjects::Close( void ) { if ( m_hMemorySection ) CloseHandle( m_hMemorySection ); if ( m_hMutex ) CloseHandle( m_hMutex ); for ( int k = 0; k < 2; ++ k ) if ( m_hEvent[k] ) CloseHandle( m_hEvent[k] ); } ////////////////////////////////////////////////////////////////////////// // // Helper class to send data back and forth // ////////////////////////////////////////////////////////////////////////// void * SubProcessKernelObjects_Memory::Lock( void ) { // Wait for our turn to act for ( unsigned iWaitAttempt = 0; iWaitAttempt < 13u; ++ iWaitAttempt ) { DWORD dwWait = ::WaitForSingleObject( m_pObjs->m_hEvent[ m_pObjs->m_dwCookie ], 10000 ); switch ( dwWait ) { case WAIT_OBJECT_0: { m_pLockData = MapViewOfFile( m_pObjs->m_hMemorySection, FILE_MAP_ALL_ACCESS, 0, 0, 0 ); if ( * ( const DWORD * ) m_pLockData != m_pObjs->m_dwCookie ) { // Yes, this is our turn, set our cookie in that memory segment * ( DWORD * ) m_pLockData = m_pObjs->m_dwCookie; m_pMemory = ( ( byte * ) m_pLockData ) + 2 * sizeof( DWORD ); return m_pMemory; } else { // We just acted, still waiting for result UnmapViewOfFile( m_pLockData ); m_pLockData = NULL; SetEvent( m_pObjs->m_hEvent[ !m_pObjs->m_dwCookie ] ); Sleep( 1 ); continue; } } break; case WAIT_TIMEOUT: { char chMsg[0x100]; sprintf( chMsg, "th%08X> WAIT_TIMEOUT in Memory::Lock (attempt %d).\n", GetCurrentThreadId(), iWaitAttempt ); OutputDebugString( chMsg ); } continue; // retry default: OutputDebugString( "WAIT failure in Memory::Lock\n" ); SetLastError( ERROR_BAD_UNIT ); return NULL; } } OutputDebugString( "Ran out of wait attempts in Memory::Lock\n" ); SetLastError( ERROR_NOT_READY ); return NULL; } BOOL SubProcessKernelObjects_Memory::Unlock( void ) { if ( m_pLockData ) { // Assert that the memory hasn't been spoiled Assert( m_pObjs->m_dwCookie == * ( const DWORD * ) m_pLockData ); UnmapViewOfFile( m_pLockData ); m_pMemory = NULL; m_pLockData = NULL; SetEvent( m_pObjs->m_hEvent[ !m_pObjs->m_dwCookie ] ); Sleep( 1 ); return TRUE; } return FALSE; } ////////////////////////////////////////////////////////////////////////// // // Implementation of the command subprocess: // // MASTER ---- command -------> SUB // string - zero terminated command string. // // // MASTER <---- result -------- SUB // dword - 1 if succeeded, 0 if failed // dword - result buffer length, 0 if failed // <bytes> - result buffer data, none if result buffer length is 0 // string - zero-terminated listing string // ////////////////////////////////////////////////////////////////////////// CSubProcessResponse::CSubProcessResponse( void const *pvMemory ) : m_pvMemory( pvMemory ) { byte const *pBytes = ( byte const * ) pvMemory; m_dwResult = * ( DWORD const * ) pBytes; pBytes += sizeof( DWORD ); m_dwResultBufferLength = * ( DWORD const * ) pBytes; pBytes += sizeof( DWORD ); m_pvResultBuffer = pBytes; pBytes += m_dwResultBufferLength; m_szListing = ( char const * ) ( *pBytes ? pBytes : NULL ); } void ShaderCompile_Subprocess_ExceptionHandler( unsigned long exceptionCode, void *pvExceptionInfo ) { // Subprocesses just silently die in our case, then this case will be detected by the worker process and an error code will be passed to the master Assert( !"ShaderCompile_Subprocess_ExceptionHandler" ); ::TerminateProcess( ::GetCurrentProcess(), exceptionCode ); } int ShaderCompile_Subprocess_Main( char const *szSubProcessData ) { // Set our crash handler SetupToolsMinidumpHandler( ShaderCompile_Subprocess_ExceptionHandler ); // Get our kernel objects SubProcessKernelObjects_Open objs( szSubProcessData ); if ( !objs.IsValid() ) return -1; // Enter the command pumping loop SubProcessKernelObjects_Memory shrmem( &objs ); for ( void *pvMemory = NULL; NULL != ( pvMemory = shrmem.Lock() ); shrmem.Unlock() ) { // The memory is actually a command char const *szCommand = ( char const * ) pvMemory; if ( !stricmp( "keepalive", szCommand ) ) { ZeroMemory( pvMemory, 4 * sizeof( DWORD ) ); continue; } if ( !stricmp( "quit", szCommand ) ) { ZeroMemory( pvMemory, 4 * sizeof( DWORD ) ); return 0; } CmdSink::IResponse *pResponse = NULL; if ( InterceptFxc::TryExecuteCommand( szCommand, &pResponse ) ) { byte *pBytes = ( byte * ) pvMemory; // Result DWORD dwSucceededResult = pResponse->Succeeded() ? 1 : 0; * ( DWORD * ) pBytes = dwSucceededResult; pBytes += sizeof( DWORD ); // Result buffer len DWORD dwBufferLength = pResponse->GetResultBufferLen(); * ( DWORD * ) pBytes = dwBufferLength; pBytes += sizeof( DWORD ); // Result buffer const void *pvResultBuffer = pResponse->GetResultBuffer(); memcpy( pBytes, pvResultBuffer, dwBufferLength ); pBytes += dwBufferLength; // Listing - copy string const char *szListing = pResponse->GetListing(); if ( szListing ) { while ( 0 != ( * ( pBytes ++ ) = * ( szListing ++ ) ) ) { NULL; } } else { * ( pBytes ++ ) = 0; } } else { ZeroMemory( pvMemory, 4 * sizeof( DWORD ) ); } } return -2; }
59154fd2aaffcd98c40721aaccba44e1ff50ebc0
39bcafc5f6b1672f31f0f6ea9c8d6047ee432950
/extension/jemalloc/jemalloc/include/jemalloc/internal/arena_stats.h
3d37da186b6611ccb61dd2371d0987e618f95b47
[ "BSD-2-Clause", "MIT" ]
permissive
duckdb/duckdb
315270af6b198d26eb41a20fc7a0eda04aeef294
f89ccfe0ec01eb613af9c8ac7c264a5ef86d7c3a
refs/heads/main
2023-09-05T08:14:21.278345
2023-09-05T07:28:59
2023-09-05T07:28:59
138,754,790
8,964
986
MIT
2023-09-14T18:42:49
2018-06-26T15:04:45
C++
UTF-8
C++
false
false
3,631
h
arena_stats.h
#ifndef JEMALLOC_INTERNAL_ARENA_STATS_H #define JEMALLOC_INTERNAL_ARENA_STATS_H #include "jemalloc/internal/atomic.h" #include "jemalloc/internal/lockedint.h" #include "jemalloc/internal/mutex.h" #include "jemalloc/internal/mutex_prof.h" #include "jemalloc/internal/pa.h" #include "jemalloc/internal/sc.h" namespace duckdb_jemalloc { JEMALLOC_DIAGNOSTIC_DISABLE_SPURIOUS typedef struct arena_stats_large_s arena_stats_large_t; struct arena_stats_large_s { /* * Total number of allocation/deallocation requests served directly by * the arena. */ locked_u64_t nmalloc; locked_u64_t ndalloc; /* * Number of allocation requests that correspond to this size class. * This includes requests served by tcache, though tcache only * periodically merges into this counter. */ locked_u64_t nrequests; /* Partially derived. */ /* * Number of tcache fills / flushes for large (similarly, periodically * merged). Note that there is no large tcache batch-fill currently * (i.e. only fill 1 at a time); however flush may be batched. */ locked_u64_t nfills; /* Partially derived. */ locked_u64_t nflushes; /* Partially derived. */ /* Current number of allocations of this size class. */ size_t curlextents; /* Derived. */ }; /* * Arena stats. Note that fields marked "derived" are not directly maintained * within the arena code; rather their values are derived during stats merge * requests. */ typedef struct arena_stats_s arena_stats_t; struct arena_stats_s { LOCKEDINT_MTX_DECLARE(mtx) /* * resident includes the base stats -- that's why it lives here and not * in pa_shard_stats_t. */ size_t base; /* Derived. */ size_t resident; /* Derived. */ size_t metadata_thp; /* Derived. */ size_t mapped; /* Derived. */ atomic_zu_t internal; size_t allocated_large; /* Derived. */ uint64_t nmalloc_large; /* Derived. */ uint64_t ndalloc_large; /* Derived. */ uint64_t nfills_large; /* Derived. */ uint64_t nflushes_large; /* Derived. */ uint64_t nrequests_large; /* Derived. */ /* * The stats logically owned by the pa_shard in the same arena. This * lives here only because it's convenient for the purposes of the ctl * module -- it only knows about the single arena_stats. */ pa_shard_stats_t pa_shard_stats; /* Number of bytes cached in tcache associated with this arena. */ size_t tcache_bytes; /* Derived. */ size_t tcache_stashed_bytes; /* Derived. */ mutex_prof_data_t mutex_prof_data[mutex_prof_num_arena_mutexes]; /* One element for each large size class. */ arena_stats_large_t lstats[SC_NSIZES - SC_NBINS]; /* Arena uptime. */ nstime_t uptime; }; static inline bool arena_stats_init(tsdn_t *tsdn, arena_stats_t *arena_stats) { if (config_debug) { for (size_t i = 0; i < sizeof(arena_stats_t); i++) { assert(((char *)arena_stats)[i] == 0); } } if (LOCKEDINT_MTX_INIT(arena_stats->mtx, "arena_stats", WITNESS_RANK_ARENA_STATS, malloc_mutex_rank_exclusive)) { return true; } /* Memory is zeroed, so there is no need to clear stats. */ return false; } static inline void arena_stats_large_flush_nrequests_add(tsdn_t *tsdn, arena_stats_t *arena_stats, szind_t szind, uint64_t nrequests) { LOCKEDINT_MTX_LOCK(tsdn, arena_stats->mtx); arena_stats_large_t *lstats = &arena_stats->lstats[szind - SC_NBINS]; locked_inc_u64(tsdn, LOCKEDINT_MTX(arena_stats->mtx), &lstats->nrequests, nrequests); locked_inc_u64(tsdn, LOCKEDINT_MTX(arena_stats->mtx), &lstats->nflushes, 1); LOCKEDINT_MTX_UNLOCK(tsdn, arena_stats->mtx); } } // namespace duckdb_jemalloc #endif /* JEMALLOC_INTERNAL_ARENA_STATS_H */
c1ea357dd1229f5920acc48536e1c392b6e7aa9c
8e7a1c1a6cc11cb04837aceaa3067eb36d3999f7
/zap-2.3.0-windows/papilio-zap-ide/hardware/zpuino/libraries/ZPUino_Examples/examples/RetroCade_Sketch/RetroCade.h
3ee762010c11a0dd5b2dbde80589941f694a7499
[ "MIT" ]
permissive
chcbaram/FPGA
daaabfb82fce0883e4c12c57b517ec09b7652cf3
fe5b8014ccdaac3122de0e62011afbd20c183eb4
refs/heads/master
2016-09-15T22:19:43.780509
2015-11-01T15:09:42
2015-11-01T15:09:42
42,006,252
3
0
null
null
null
null
UTF-8
C++
false
false
2,483
h
RetroCade.h
/*! * @file RetroCade.h * Project RetroCade Library * @brief RetroCade Library for the ZPUino * Version 1.0 * @author Jack Gassett * @date 9/11/12 * License GPL */ #ifndef LIB_RetroCade_H_ #define LIB_RetroCade_H_ #include <inttypes.h> #include <zpuino-types.h> #include <zpuino.h> #include "Arduino.h" #include "LiquidCrystal.h" #include <SD.h> #include "SmallFS.h" #include "modplayer.h" #include "ymplayer.h" #include "sidplayer.h" #include "SID.h" #include "YM2149.h" #define AUDIO_J1_L WING_B_1 #define AUDIO_J1_R WING_B_0 #define AUDIO_J2_L WING_B_3 #define AUDIO_J2_R WING_B_2 #define SERIAL1RXPIN WING_C_1 #define SERIAL1TXPIN WING_C_0 //Joystick #define JSELECT WING_B_15 #define JDOWN WING_B_14 #define JUP WING_B_13 #define JRIGHT WING_B_12 #define JLEFT WING_B_11 //For SPI ADC1 #define SELPIN WING_C_9 //Selection Pin #define DATAOUT WING_C_8 //MOSI #define DATAIN WING_C_7 //MISO #define SPICLOCK WING_C_6 //Clock //For SPI ADC2 #define SELPIN2 WING_C_5 //Selection Pin #define DATAOUT2 WING_C_4 //MOSI #define DATAIN2 WING_C_3 //MISO #define SPICLOCK2 WING_C_2 //Clock //SD Card #define CSPIN WING_C_13 #define SDIPIN WING_C_12 #define SCKPIN WING_C_11 #define SDOPIN WING_C_10 enum kButtonDirection { Left = 0, Right = 1, Up = 2, Down = 3, Select = 4, None = 5 }; class RETROCADE { public: YMPLAYER ymplayer; MODPLAYER modplayer; SIDPLAYER sidplayer; YM2149 ym2149; SID sid; void setupMegaWing(); void handleJoystick(); void setTimeout(); byte getActiveChannel(); void printDirectory(File dir, int numTabs); void printFile(const char* ext); boolean sdFsActive(); boolean smallFsActive(); void spaceInvadersLCD(); private: void initSD(); int fileExtension(const char* name, const char* extension, size_t length); void smallfsModFileJoystick(byte type); void instrumentJoystick(); void modFileJoystick(); void ymFileJoystick(); void sidFileJoystick(); byte lcdMode; kButtonDirection buttonPressed; byte activeChannel; int activeInstrument; byte smallfsActiveTrack; unsigned long timeout; boolean smallFs; boolean sdFs; byte invadersCurLoc; byte invadersCurSeg; int invadersTimer; File root; File curFile; File curYMFile; File curMODFile; char * fileName; }; #endif // LIB_RetroCade_H_
33e2f3a18745a0d1b35dd9bbf2654343aa18abf5
55c438a5113d1287dc9dc82b6bdface0cf2e1e54
/Button.h
6a230c4afcc36e42509ead010afc5c15d7a1176a
[]
no_license
helloqiu/electronic
0f1c6a5628592282e18bbd71e6d225c25caa8b7d
c0638f4db24322de9f96de34126049677481802b
refs/heads/master
2020-05-30T20:10:44.508568
2015-05-12T03:06:25
2015-05-12T03:06:25
35,463,662
0
0
null
null
null
null
UTF-8
C++
false
false
283
h
Button.h
#ifndef BUTTON_H #define BUTTON_H // #include "Circuit.h" class Button{ public: // friend class Circuit; Button(bool status); void turnOn(); void turnOff(); bool getStatus(); // void setCircuit(Circuit &circuit); private: bool status; // Circuit *circuit; }; #endif
21dc8fec671cb107aaecae7234305c76febe781a
7fbb8b09b086cf431d5b13eac3883f2ef5f966eb
/casinoomania/Classes/Shoe.cpp
f287187cc96678f321501b9f948cee7091115037
[]
no_license
Crasader/f
7cd841f02642a233090820fbba73a130fcc27231
a028fed42373261e9aa0c9064661fa5ac2c073bb
refs/heads/master
2020-12-04T17:39:51.816398
2018-10-01T02:01:46
2018-10-01T02:01:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
888
cpp
Shoe.cpp
// // Shoe.cpp // DovemobiCasino // // Created by Stanislav Zheronkin on 07.03.17. // // #include "Shoe.h" #include <vector> Shoe::Shoe(int decksNumber) : decksnum(1) { setDecksNumber(decksNumber); } void Shoe::setDecksNumber(int decksNumber) { if (decksNumber < 1 || decksNumber > 6) { printf("%s", "Error: attempt set wrong decks number in shoe"); return; } decksnum = decksNumber; cards.clear(); Deck standardDeck; for (int i = 0; i < decksNumber; i++) { cards.insert(cards.end(), standardDeck.cards.begin(), standardDeck.cards.end()); } } bool Shoe::CanPlay() { return (cards.size() >= 26 * decksnum); } std::list<CardObject> Shoe::DrawHand() { std::list<CardObject> result; result.push_back(DrawCard()); result.push_back(DrawCard()); return result; }
03bc18611631b2fa8603ad47593c1282c58c8f8f
41f546ad89c405957d0f25963b985e136442caaf
/ui-terminal/csi_sequence.h
5af303bf7905284b7acef98a40e83d42712fc1b7
[ "MIT" ]
permissive
redrye/PowershellTerminal
e704a757c337de10a17305a58bd3fa1295cc657b
0dc1e771b7505d4f005cbd33d668d49cc2627eec
refs/heads/master
2023-05-06T05:18:24.658854
2021-05-28T15:50:12
2021-05-28T15:50:12
371,746,553
0
0
null
null
null
null
UTF-8
C++
false
false
3,338
h
csi_sequence.h
#pragma once #include <vector> #include <ostream> namespace ui { class CSISequence { public: CSISequence(): firstByte_{0}, finalByte_{0} { } bool valid() const { return firstByte_ != INVALID; } bool complete() const { return firstByte_ != INCOMPLETE; } char firstByte() const { return firstByte_; } char finalByte() const { return finalByte_; } size_t numArgs() const { return args_.size(); } int operator [] (size_t index) const { if (index >= args_.size()) return 0; // the default value for argument if not given return args_[index].first; } CSISequence & setDefault(size_t index, int value) { while (args_.size() <= index) args_.push_back(std::make_pair(0, false)); std::pair<int, bool> & arg = args_[index]; // because we set default args after parsing, we only change default value if it was not supplied if (!arg.second) arg.first = value; return *this; } /** If the given argument has the specified value, it is replaced with the new value given. Returns true if the replace occured, false otherwise. */ bool conditionalReplace(size_t index, int value, int newValue) { if (index >= args_.size()) return false; if (args_[index].first != value) return false; args_[index].first = newValue; return true; } /** Parses the CSI sequence from given input. */ static CSISequence Parse(char const * & buffer, char const * end); private: char firstByte_; char finalByte_; std::vector<std::pair<int, bool>> args_; static constexpr char INVALID = -1; static constexpr char INCOMPLETE = -2; static constexpr int DEFAULT_ARG_VALUE = 0; static bool IsParameterByte(char c) { return (c >= 0x30) && (c <= 0x3f); } static bool IsIntermediateByte(char c) { return (c >= 0x20) && (c <= 0x2f); } static bool IsFinalByte(char c) { // no need to check the upper bound - char is signed return (c >= 0x40) /*&& (c <= 0x7f) */; } friend std::ostream & operator << (std::ostream & s, CSISequence const & seq) { if (!seq.valid()) { s << "Invalid CSI Sequence"; } else if (!seq.complete()) { s << "Incomplete CSI Sequence"; } else { s << "\x1b["; if (seq.firstByte_ != 0) s << seq.firstByte_; if (!seq.args_.empty()) { for (size_t i = 0, e = seq.args_.size(); i != e; ++i) { if (seq.args_[i].second) s << seq.args_[i].first; if (i != e - 1) s << ';'; } } s << seq.finalByte(); } return s; } }; // ui::CISSequence } // namespace ui
9234d99d42a1a324dbb1a60ceb9a15d4928abd84
6a42841765f2356da99d9844cab8f3f3353eaebf
/Game/开发库/Include/CHeadPortrait.h
35d5ab562ae48cf8e3ee75b4eae5f38881ee9697
[]
no_license
Ivanhan2018/wh6602_zhuque
d904e1d7136ed7db6cd9b46d65ab33797f400a74
b0e7e574786eac927d109967618ba2a3af5bbee3
refs/heads/master
2020-04-05T17:28:14.739789
2018-12-24T07:36:47
2018-12-24T07:36:47
157,062,380
2
8
null
null
null
null
GB18030
C++
false
false
3,308
h
CHeadPortrait.h
#pragma once #ifndef _CHEAD_PORTRAIT_H #define _CHEAD_PORTRAIT_H #include "stdafx.h" /// 人物头像动画类 class CHeadPortrait : public CWnd { DECLARE_DYNAMIC(CHeadPortrait) friend class CHeadPortraitManager; private: CWnd * m_pParent; CDC * m_pParentDC; CImage * m_pParentImage; CGDIPlus_Image * m_pImage; WORD m_wID; ///< 动画ID UINT m_uActionCount; ///< 动作数目 UINT m_uFrameCount; ///< 帧数目 vector<BOOL> m_vFrames; ///< 帧集 UINT m_uCurAction; ///< 当前动作 UINT m_uCurFrame; ///< 当前帧 UINT m_uDefaultAction; ///< 默认动作 UINT m_uIntervalTime; ///< 间隔时间 UINT m_uFrameTime; ///< 当前时间 UINT m_uRunCount; ///< 动作执次数 POINT m_ptCurPos; ///< 当前位置 public: CHeadPortrait(); virtual ~CHeadPortrait(); virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); protected: DECLARE_MESSAGE_MAP() public: /// 设置动作集 /// [@param bLine in] 动作数目(一张图片由很多动画组成),例:普通动作,高兴,哭泣,生气,窃喜,掉线,逃跑 /// [@param bRow in] 多少帧,一个动作由多少帧组成 /// [@param pAction in] 动作帧集 (默认值是 7*2 维数组) void SetAction(UINT bLine=1, UINT bRow=1, BOOL *pAction=NULL); void PlayAction(UINT uIndex, UINT uFrameTime=150, UINT uIntervalTime=0, UINT uResultTime=0, UINT uDefaultAction=0); protected: afx_msg void OnPaint(); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnTimer(UINT nIDEvent); }; typedef vector<CHeadPortrait *> VCHeadPortrait; ////////////////////////////////////////////////////////////////////////////////// /// 人物头像动画管理类 class GAME_FRAME_CLASS CHeadPortraitManager { public: CHeadPortraitManager(); virtual ~CHeadPortraitManager(); /// 初始化人物头像数目 /// [@param pParent in] 父窗口指针 /// [@param uCount in] 动画数目 void Init(CWnd *pParent, UINT uCount); /// 调整坐标 /// [@param pt in] 动画位置集 void SetPos(CPoint pt[]); /// 刷新动画 /// [@param pDC in] 父窗口 DC /// [@param pImage in] 父窗口背景缓存图片指针 void Refresh(CDC *pDC); void Refresh(CImage *pImage); /// 播放动作 /// [@param uID in] 动画 ID(类似玩家ID) /// [@param bWoman in] 性别,真为女,假为男 /// [@param uIndex in] 动作索引 /// [@param uFrameTime in] 动作每帧的时间,如果默认帧有效,也是默认帧的时间(毫秒) /// [@param uIntervalTime in] 动画间隔时间 (毫秒) /// [@param uResultTime in] 动作总共时间,小于等于 0 无时间限制(毫秒) /// [@param uDefaultAction in] 默认动作(当 uIndex 动作播放完,自动播放默认动作) void PlayAction(WORD wID, BOOL bWoman, UINT uIndex, UINT uFrameTime=150, UINT uIntervalTime=0, UINT uResultTime=0, UINT uDefaultAction=0); /// 隐藏所有动画 void Hide(WORD uID, BOOL bAllHide=FALSE); private: VCHeadPortrait m_vHeadPortrait; ///< 人物头像动画管理指针集 }; #endif
07c7eb471979c892dcbf6157871ee784caf7af1f
57b069396bd4201c236e8076ca2ac0551a283f2f
/5_21(2) 2017-2018(1).cpp
b5a8435235043d1c824c74e47b25a64c4d5fca13
[]
no_license
permanentbelief/Cplusplus_practice
96301564cd03d1904b18aea02a0499ffadee1510
858588a3b0752c7fcec6437558d601dd4eef4ec3
refs/heads/master
2021-07-02T21:51:48.597023
2020-10-19T14:00:17
2020-10-19T14:00:17
183,547,105
2
0
null
null
null
null
GB18030
C++
false
false
5,379
cpp
5_21(2) 2017-2018(1).cpp
#define _CRT_SECURE_NO_WARNINGS 1 //#include <iostream> //using namespace std; //#include <iostream> //#include <cmath> //using namespace std; //class Line //{ //private: // int x1, y1, x2, y2; // double length; //public: // Line(int = 0, int b = 0, int = 1, int = 1); // Line(Line &); // //添加某函数的声明 // // //重载插入运算符函数 // friend ostream &operator<<( ostream & output, Line & p) // { // output << "start Point:(" << p.x1 << "," << p.y1 << ")\tend Point:(" << p.x2 // << "," << p.y2 << ")\tlength:" << p.length << endl; // return output; // } //}; //Line::Line(int x1, int y1, int x2, int y2 ) //{ // this->x1 = x1; this->y1 = y1; // this->x2 = x2; this->y2 = y2; // length = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)); //} ////拷贝构造函数的实现 //Line::Line(Line&copy) //{ // x1 = copy.x1; // x2 = copy.x2; // y1 = copy.y1; // y2 = copy.y2; // length = copy.length; //} //int main() { // Line l1, l2(30, 40); // cout << "l1:" << l1; // cout << "l2:" << l2; // Line l3(l2); // cout << "l3:" << l3; // Line l4(20, 20, 20, 40); // cout << "l4:" << l4; // system("pause"); // return 0; //} // //8.设计一个能够表示年月日的Date类,并且要保证月份在1 - 12之间, //否则为1,日在1 - 31之间,否则为1,输出年月日按“xxxx - xx - xx” //格式。参考输出结果如下: //#include <iostream> //using namespace std; //class Date //{ //private: // int year, month, day; //public: // Date(int y = 2018, int m = 1, int d = 1) // { // year = y; // month = (m>12 || m<1) ? 1 : m; // day = (d>31 || d<1) ? 1 : d; // } // void show() // { cout << year << "-" << month << "-" << day << endl; } //}; // //int main() { // Date d1, d2(2017, 15, 23); // cout << "d1:"; // d1.show(); // cout << "d2:"; // d2.show(); // system("pause"); // return 0; //} // 方法二: //#include <iostream> //using namespace std; //class Date //{ //private: // int year; // int month; // int day; //public: // Date(int y, int m, int d) // :year(y), month(m), day(d){} // void Setyear(int y) // { // year = y; // // } // void Setmonth(int m) // { // month = ((m >= 1 && m <= 12) ? m : 1); // // } // void Setday(int d) // { // day = ((d >= 1 && d <= 31) ? d : 1); // } // int Getyear() // { // return year; // } // int Getmonth() // { // return month; // } // int Getday() // { // return day; // } // friend ostream&operator <<(ostream&output, Date&p) // { // output << p.Getyear() << "-" << p.Getmonth() << "-" << p.Getday() << endl; // return output; // } // //}; //int main() //{ // Date r1(10, 21, 90); // cout << r1; // system("pause"); //} //9.设计一个分数Fraction,可以实现分数的加、减、乘法运算,并重载插入运算符operator << (), //分数输出格式为b / a,分数的乘法规则为:(b / a)*(d / c) = (bd / ac),不需要化简。在主函数 //中创建两个分数对象,先输出这两个分数,然后分别输出两个分数的加、减、乘运算结果。 //参考输出结果: //class Fraction //{ //private: // int a; // int b; //public: // Fraction(int x1 = 0, int x2 = 1) // { // this->a = x1; // this->b = x2; // } // friend ostream&operator<<(ostream&out, Fraction & p) // { // out << p.a << "/" << p.b << endl; // return out; // } // //Fraction operator+(Fraction &p) // //{ return Fraction(a*p.b + p.a*b, b*p.b); } // Fraction operator-(Fraction &p) // { return Fraction(a*p.b - p.a*b, a*p.b); } // Fraction operator*(Fraction &p) // { return Fraction(a*p.a, b*p.b); } // friend Fraction operator+(Fraction&x1, Fraction&x2) // { // Fraction p; // p.a = x1.a + x2.a; // p.b = x1.b + x2.b; // return p; // } //}; //int main() //{ // Fraction a(10, 20); // Fraction b(20, 10); // Fraction c; // c = a + b; // cout << a; // cout << b; // cout << "a+b:" << c << endl; // system("pause"); //} //#include <iostream> //using namespace std; //class Fraction //{ //private: // int tor; // int demon; //public: // Fraction(int tor = 0, int demon = 1) // // { // this->tor = tor; // this->demon = demon; // } // /*{ if (demon != 0) // { // this->tor = tor; this->demon = demon; // } // else // cout << "This is an invalid number!" << endl; // }*/ // Fraction operator+(Fraction &a) // { return Fraction(tor*a.demon + a.tor*demon, demon*a.demon); } // Fraction operator-(Fraction &a) // { return Fraction(tor*a.demon - a.tor*demon, demon*a.demon); } // Fraction operator*(Fraction &a) // { return Fraction(tor*a.tor, demon*a.demon); } // friend ostream& operator<<(ostream& out, Fraction& a) // { // out << a.tor << "/" << a.demon; // return out; // } //}; // //int main() { // // Fraction f1(3, 5), f2(2, 7), f3; // cout << "f1=" << f1 << "\tf2=" << f2 << endl; // f3 = f1 + f2; cout << "f1+f2=" << f3 << endl; // f3 = f1 - f2; cout << "f1-f2=" << f3 << endl; // f3 = f1*f2; cout << "f1xf2=" << f3 << endl; // system("pause"); // return 0; //} //10.定义一个Student类模板,包含学号、姓名、高数、英语、程序设计、总分等信息,学号、姓名和各分数都为可变类型, //总分 = 数学 + 英语 + 程序设计。在主函数中创建一个学号为int型,姓名为string型,各分数为int型的学生对象 //,并输该学生信息,再创建一个学号和姓名都是string型,各分数都是double型的学生对象,并输出该学生信息。 //参考输出结果:
934608d1b7dabbe85d050a2e4f2b2a6a6cfd662d
a42f7bc14667769c58413d940e80a0177270937e
/linux/test/MH_Base.h
fa8d4f5bd68c5118d76e8d674f6bba0e2c80d16f
[]
no_license
yangyefeng/linux-study
21c41647d5506253d47c85b2b31eb5a82149e485
9c02580df840b7a016a6a664b98b689660c41c99
refs/heads/master
2020-04-07T13:10:40.991211
2018-11-20T14:24:25
2018-11-20T14:24:25
158,395,853
0
0
null
null
null
null
UTF-8
C++
false
false
525
h
MH_Base.h
// MH_Base.h #ifndef __MH_Base_h__ #define __MH_Base_h__ // 消息处理者基类 class MH_Base { public: virtual ~MH_Base() {}; virtual void operator()(const void* data, size_t len) = 0; }; /// 全局或者静态函数 class MH_Function : public MH_Base { public: typedef void (Function1)(const void* data, size_t len); public: MH_Function(Function1* func) : _func1(func) {} virtual void operator()( const void* data, size_t len) { _func1( data, len); } private: union { Function1* _func1; }; }; #endif
884f3dd3a8eeb99f70100590460ecff5938a54d9
599d32cdc9dbd15806b0e7d2bb77e8fd904b5caf
/c++/0061.h
8a7afac39b1857cb216836d8f93b223ff25132d1
[]
no_license
maximusyoung007/LeetCode
03776bc6191864469a9a30a391cf49a909b9b9a8
fe4a6186d4e039c271efda0ddb05965bdde1f172
refs/heads/master
2023-07-15T23:21:05.796959
2023-07-02T15:18:12
2023-07-02T15:18:12
176,424,589
0
0
null
null
null
null
UTF-8
C++
false
false
104
h
0061.h
#include "listnode.h" class Solution0061 { public: ListNode* rotateRight(ListNode* head, int k); };
8aebe27d9fe835d8c3e6bea0f0e41b5bff967aaa
dbf381e932f1e2845fde9706c1c80f45746f608a
/include/protocolo.h
00b3c879bfb248446f68044799a6422a7eb57afc
[]
no_license
hcyoo93/vilma_ma
98662182a0d4d27c7d29a2c78b59fcf7ae5cdb9c
bd056279f35052799bb3163a8259324ef5ab590e
refs/heads/master
2020-07-30T07:31:18.818757
2014-09-12T17:45:11
2014-09-12T17:45:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,100
h
protocolo.h
/* * protocolo.h * library to encode and decode an array of double in bynary * with the possibility to encoding this variable in * @ref datos {manull,maboolean,maint8,mauint8,maint16,mauint16,maint32,mauint32,mafloat,madouble} * * it is based of the example of Dspace microautobox II to communicate by udp * * FILE: * ds867c_eth_encode32_sfcn.c * * DESCRIPTION: * Encoding of data in various input format to 32bit WORD format * it should work both in Simulink as well as in RT Application with dSPACE HW * LaszloJ * FILE: * ds867c_eth_decode32_sfcn.c * * DESCRIPTION: * decodes the 32bit WORD-coded data into selected data types * * Used and changed by LaszloJ * * @author olmer Garcia olmerg@gmail.com * Copyright 2013 Olmer Garcia Bedoya * * 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 PROTOCOLO_H_ #define PROTOCOLO_H_ #include <vector> namespace microautobox { /** * types of variables available in the microautobox * Datatype Codes: BOOLEAN: 1 // INT8 : 2 // UINT8 : 3 INT16 : 4 // UINT16 : 5 // INT32 : 6 UINT32 : 7 // FLOAT : 8 // DOUBLE: 9 */ enum datos{manull,maboolean,maint8,mauint8,maint16,mauint16,maint32,mauint32,mafloat,madouble}; enum { max_length = 1024 }; enum { bigendian=1, litleendian=2}; /*template <typename T> int typeofi(T&) {return manull;} template<> int typeofi(bool&) { return maboolean; } template<> int typeofi(char&) { return maint8; } template<> int typeofi(unsigned char&) { return mauint8; } template<> int typeofi(short &) { return maint16; } template<> int typeofi(unsigned short&) { return mauint16; } template<> int typeofi(int&) { return maint32; } template<> int typeofi(unsigned int&) { return mauint32; } template<> int typeofi(float&) { return mafloat; } template<> int typeofi(double&) { return madouble; }*/ typedef struct { unsigned char byte7; unsigned char byte6; unsigned char byte5; unsigned char byte4; unsigned char byte3; unsigned char byte2; unsigned char byte1; unsigned char byte0; } uint64_by_uint8_t; typedef struct { unsigned char byte3; unsigned char byte2; unsigned char byte1; unsigned char byte0; } uint32_by_uint8_t; /*===============================*/ typedef struct { unsigned char byte1; unsigned char byte0; } uint16_by_uint8_t; /*===============================*/ typedef union { uint32_by_uint8_t uint32_r ; float float32_r; } float32_t; /*===============================*/ typedef union { uint64_by_uint8_t uint64_r ; double float64_r; } float64_t; /*===============================*/ typedef union { uint32_by_uint8_t uint32_r ; unsigned int int32_r ; } ds_uint32_t; /*===============================*/ typedef union { uint16_by_uint8_t uint16_r ; unsigned short int16_r ; } ds_uint16_t; /** * class to encode and decode an array of double in binary * with the possibility to encoding this variable in * @ref datos {manull,maboolean,maint8,mauint8,maint16,mauint16,maint32,mauint32,mafloat,madouble} * * it is based of the example of the microautobox II to communicate by udp */ class protocolo { int PROCESSORTYPE; public: /** * * @param PROCESSORTYPE bigendian or litleendian */ protocolo(int PROCESSORTYPE=bigendian); virtual ~protocolo(); /*** * @brief function to convert an array of double to unsigned char in binary representation * @param data is vector of double with the data to encode in unsigned char * @param type @ref datos {manull,maboolean,maint8,mauint8,maint16,mauint16,maint32,mauint32,mafloat,madouble} * @return the vector with the data encoded in unsigned char to be transmited in binary form */ std::vector<unsigned char> maencode(std::vector<double> data,std::vector<int> type); /*** * * @param data * @param tipe @ref datos {manull,maboolean,maint8,mauint8,maint16,mauint16,maint32,mauint32,mafloat,madouble} * @return */ std::vector<double> decode(std::vector<unsigned char> data,std::vector<int> tipe); }; } #endif /* PROTOCOLO_H_ */
0834a1df24989f08533364354278cad9a0bad51f
3a62544c93e3aa19ce616bfd0978a98886fff79e
/blinker.cpp
c59622c68099bc1c3e8463dc47e784dac6731db3
[]
no_license
icwhatuc/eye-see-what-you-see
8853e2f708c1770820a28cd9855e3b69ab9695c9
98d36962fe0a77868ca34f9c2ae7e9eddeaa0195
refs/heads/master
2020-05-18T17:29:02.337918
2015-07-05T16:59:32
2015-07-05T16:59:32
38,576,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,140
cpp
blinker.cpp
#include <iostream> #include <fstream> #include <cv.h> #include <highgui.h> #include <ctime> #include <sys/time.h> #define flip(x) ((x == '0')?x='1':x='0') #define isOn(x) (x == '1') // currently, when off -> bright pupil image #define changeledstate() {flip(arduino_state); arduino << arduino_state; arduino.flush();} using namespace std; float delay(float millisec) { clock_t timesec; timesec = clock(); while((clock() - timesec) < millisec*1000){} return millisec*1000; } void timing(bool start, string what="") { static struct timeval starttime, endtime; static long mtime, seconds, useconds; if (start) { gettimeofday(&starttime, NULL); cout << "timing " << what << endl; } else { gettimeofday(&endtime, NULL); seconds = endtime.tv_sec - starttime.tv_sec; useconds = endtime.tv_usec - starttime.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; printf("Elapsed time: %ld milliseconds\n", mtime); } } main() { char arduino_state = '0'; ofstream arduino("/dev/ttyUSB0"); float f; while(1) { flip(arduino_state); arduino << arduino_state; arduino.flush(); delay(25); } }
be15091150506bbc96a744d12c0c1eae4b1cc083
487772ecc40082541ea963dda4939eddb842a275
/lispino/Define.cc
d11f511e50daf3e7bd5d1b867c8a3bf8105c3f55
[]
no_license
GuglielmoS/Lispino
9b72fb9bc33c129563e60739387fbd75b98a5d08
51c16ebca60d52b39d7bd92fc4a4b903db6a143d
refs/heads/master
2020-06-02T13:10:48.346377
2014-12-12T21:00:50
2014-12-12T21:00:50
10,824,913
8
0
null
null
null
null
UTF-8
C++
false
false
644
cc
Define.cc
#include "Define.h" #include "Environment.h" namespace lispino { Define::Define() : Object(ObjectType::DEFINE), name(nullptr), value(nullptr) { /* DO NOTHING */ } Define::Define(Symbol* name, Object* value) : Object(ObjectType::DEFINE), name(name), value(value) { /* DO NOTHING */ } void Define::setName(Symbol* name) { this->name = name; } void Define::setValue(Object* value) { this->value = value; } std::string Define::getName() const { return name->getValue(); } Symbol* Define::getSymbol() { return name; } Object* Define::getValue() { return value; } std::string Define::toString() const { return "DEFINE"; } }
278b85177c4b9af8517358a898f2ab2f06802dd8
d8932b64db58f64d7e187cf42203313b147f1947
/objects_demos/constant_variables.cpp
e4d71360b114866217de448064a3488f4b2ff600
[ "MIT" ]
permissive
jason-vega/Introduction-to-Programming-with-Cpp
d65d90f6a562e9660d366b93d0e2bcde64849bf1
cc016b122a23800c7616a6e3158288706a2cb752
refs/heads/master
2021-08-14T09:03:40.232737
2017-11-15T07:10:57
2017-11-15T07:10:57
106,961,194
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
constant_variables.cpp
#include <iostream> #include <string> using namespace std; /* Constant variables are usually declared globally (outside of any function.) Add const keyword in front of definition to make variable constant. */ const double PI = 3.1416; const string CAPITAL_OF_SPAIN = "Madrid"; // Now these variables can never be changed later on in our program! int main() { // PI = 9.80; <-- Would this work? // CAPITAL_OF_SPAIN = "Mars"; <-- How about this? Try it out! cout << "I like pie! But I also like pi (" << PI << ")." << endl << "Marvelous Mary makes mochas in " << CAPITAL_OF_SPAIN << '.' << endl; return 0; }
8e7ce1b038adc73cab8cb81822e2fbdd057115a9
41817fa657db2c3c650613a9b92c869677cd3b87
/UVa/10048.cpp
1787bce8e6a02b959e92608ca69039d4f24517f1
[]
no_license
judmorenomo/Competitive-Programming
15cfa2f5a3e57c7e28920ed3b202093bebf1b25f
d16624fbfaa95f7629374cfe8f05603fbd50b3fb
refs/heads/master
2021-07-22T22:50:40.158499
2020-04-27T17:55:43
2020-04-27T17:55:43
149,539,981
0
0
null
null
null
null
UTF-8
C++
false
false
2,116
cpp
10048.cpp
#include<bits/stdc++.h> using namespace std; vector<pair<int, pair<int, int> > > EdgeList; int graf[110][110], ans = -1, ini, dest; bool pos = false, vis[110]; vector<int> path; class UnionFind{ private: vector<int> p, rank; public: UnionFind(int N){ rank.assign(N, 0); p.assign(N, 0); for(int i = 0; i < N; i++)p[i] = i; } int findSet(int i){ return (p[i] == i) ? i : (p[i] = findSet(p[i])); } bool isSameSet(int i, int j){ return findSet(i) == findSet(j); } void unionSet(int i, int j){ if(!isSameSet(i, j)){ int x = findSet(i), y = findSet(j); if(rank[x] > rank[y])p[y] = x; else{ p[x] = y; if(rank[x] == rank[y])rank[y]++; } } } }; void dfs(int u){ if(u == dest){ pos = true; for(int i = 0; i < path.size()-1; i++){ ans = max(ans, graf[path[i]][path[i+1]]); } return; } vis[u] = 1; for(int i = 0; i < 105; i++){ if(graf[u][i] != -1 && !vis[i]){ path.push_back(i); dfs(i); path.pop_back(); } } } int main(){ bool flag = false; int c, s, q, cont = 1; scanf("%d %d %d", &c, &s, &q); while(c || s || q){ EdgeList.clear(); memset(graf, 0, sizeof graf); for(int i = 0; i < s; i++){ int ori, fin, w; scanf("%d %d %d", &ori, &fin, &w); ori--; fin--; EdgeList.push_back({w, {ori, fin}}); } sort(EdgeList.begin(), EdgeList.end()); UnionFind UF(c); memset(graf, -1, sizeof graf); for(int i = 0; i < EdgeList.size(); i++){ pair<int, pair<int, int > > front = EdgeList[i]; if(!UF.isSameSet(front.second.first, front.second.second)){ graf[front.second.first][front.second.second] = graf[front.second.second][front.second.first] = front.first; UF.unionSet(front.second.first, front.second.second); } } if(!flag)flag = true; else puts(""); printf("Case #%d\n", cont); cont++; for(int i = 0; i < q; i++){ path.clear(); memset(vis, 0, sizeof vis); ans = -1; pos = false; scanf("%d %d", &ini, &dest); ini--; dest--; path.push_back(ini); dfs(ini); if(!pos)puts("no path"); else printf("%d\n", ans); } scanf("%d %d %d", &c, &s, &q); } }
5f72d503ca2296d24c49b42df86cf290ea94f9ac
e7cce1419625465719b6aa9b2869678130b1f523
/globals.hpp
36c362765583b9b4324c6226b66c36afa48f94aa
[]
no_license
samedcildir/mlp_dream
b7a4056b7e704be1aa3816a454d7fae70d72bec5
81634eac7e17da29dd8c99bc967ca513ff9f0a56
refs/heads/master
2020-03-20T03:23:47.698654
2018-06-13T01:08:48
2018-06-13T01:08:48
137,144,670
0
0
null
null
null
null
UTF-8
C++
false
false
253
hpp
globals.hpp
#ifndef GLOBALS_HPP #define GLOBALS_HPP extern int save_cnt; constexpr int my_min(int x, int y){ return x > y ? x : y; } #define NETWORK_MAX_OUTPUT_SIZE 10 // this is 1 for BW, 3 for color but 10 makes it solid #endif // GLOBALS_HPP
a1ef220d80d745b12812b2866ff5d14cbf52b91b
df656efce3d1e2ecb739625a193b5b60d5efbaee
/PAT1053/PAT1053/main.cpp
c0f8cb99f407beacda38730a9f844a2381d281c2
[]
no_license
crabyh/PAT
7a7cd4ada976197ce8069beb06485982624ccb5e
c9d6db4d9373f2ea840fc7436226509638645e4f
refs/heads/master
2020-04-04T14:48:00.416075
2015-03-20T08:13:36
2015-03-20T08:13:36
31,304,360
0
0
null
null
null
null
UTF-8
C++
false
false
2,267
cpp
main.cpp
// // main.cpp // PAT1053 // // Created by Myh on 2/15/15. // Copyright (c) 2015 Myh. All rights reserved. // #include <iostream> #include <algorithm> #include <vector> #include <deque> using namespace std; class Node{ public: int ID; int weight; int total_weight; vector<Node *> child; vector<Node *> brother; Node * parent=NULL; bool is_leaf=1; }; vector<Node *> nodes; deque<deque<int>> res; void trace(deque<int>& x){ while(x.front()!=0){ x.push_front(nodes[x.front()]->parent->ID); } } int compare(deque<int> x,deque<int> y){ int i=0; // cout<<nodes[x[i]]->ID<<" "<<nodes[y[i]]->ID<<endl; while(nodes[x[i]]->weight==nodes[y[i]]->weight&&nodes[x[i]]->child.size()!=0&&nodes[y[i]]->child.size()!=0){ i++; } return nodes[x[i]]->weight>nodes[y[i]]->weight; } int main(int argc, const char * argv[]) { // insert code here... int N,M,K; cin>>N>>M>>K; for(int i=0;i<N;++i){ Node* node=new Node; node->ID=i; cin>>node->weight; nodes.push_back(node); } for(int i=0;i<M;++i){ int ID,n; cin>>ID>>n; Node* node=nodes[ID]; node->is_leaf=0; for(int j=0;j<n;++j){ int id; cin>>id; node->child.push_back(nodes[id]); nodes[id]->parent=node; } } deque<Node *> tree; tree.push_back(nodes[0]); nodes[0]->total_weight=nodes[0]->weight; while(!tree.empty()){ Node* node=tree.front(); tree.pop_front(); for(int i=0;i<node->child.size();++i){ node->child[i]->total_weight=node->total_weight+node->child[i]->weight; tree.push_back(node->child[i]); } } for(int i=0;i<N;++i){ if(nodes[i]->total_weight==K&&nodes[i]->is_leaf==1){ deque<int> res1; res1.push_front(i); trace(res1); res.push_back(res1); } } sort(res.begin(), res.end(), compare); for(int i=0;i<res.size();++i){ cout<<nodes[res[i][0]]->weight; for(int j=1;j<res[i].size();++j){ cout<<" "<<nodes[res[i][j]]->weight; } cout<<endl; } return 0; }
29f2b52156d773d1fb8a852e77225972e2ea0910
fdcae9bcce8ee53d572a351a6811047edbbd3b3e
/code/Singularity_Engine/include/graphics/components/MeshRenderer.inc
8aa972a2dfcf9c185762e7631f236dfa3fcfca03
[]
no_license
jobelobes/Ultragon.Games.TriggerHappy
d4378e34946759e4f19db14fc09120e4086dc3b8
f438b5d3af4ff2173f9b02a489a8c907c48a9bf5
refs/heads/master
2021-03-24T12:44:34.589323
2012-06-28T22:37:04
2012-06-28T22:37:04
4,823,923
0
0
null
null
null
null
UTF-8
C++
false
false
350
inc
MeshRenderer.inc
#pragma region Properties inline Mesh* MeshRenderer::Get_Mesh() const { return this->m_pMesh; } inline void MeshRenderer::Set_Mesh(Mesh* value) { this->m_pMesh = value; } inline unsigned MeshRenderer::Get_Layer() const { return this->m_pLayer; } inline void MeshRenderer::Set_Layer(unsigned value) { this->m_pLayer = value; } #pragma endregion
163cc9f086dae5c5caee95a5fcc9aa8e9cce96f6
fe22b7a0f9ab10170c513afb062d69cfba128ec2
/src/services/roctracer/RocTracer.cpp
b1e07e9f2732f549fda4a068f2023a6239b82e92
[ "BSD-3-Clause" ]
permissive
LLNL/Caliper
ef5e9a6f408610dab404b58d29b53ddff2ce9708
764e5b692b2569f3ba4405f8e75126a0c35c3fab
refs/heads/master
2023-09-04T00:11:12.741726
2023-08-30T14:10:20
2023-08-30T14:10:20
45,953,649
283
55
BSD-3-Clause
2023-09-14T01:34:46
2015-11-11T02:02:00
C++
UTF-8
C++
false
false
23,177
cpp
RocTracer.cpp
// Copyright (c) 2015-2022, Lawrence Livermore National Security, LLC. // See top-level LICENSE file for details. #include "caliper/CaliperService.h" #include "../Services.h" #include "caliper/Caliper.h" #include "caliper/SnapshotRecord.h" #include "caliper/common/Attribute.h" #include "caliper/common/Log.h" #include "caliper/common/RuntimeConfig.h" #include "caliper/common/c-util/unitfmt.h" #include "../../common/util/demangle.h" #include <roctracer.h> #include <roctracer_hip.h> #include <roctracer_ext.h> #include <mutex> #include <map> using namespace cali; namespace { class RocTracerService { Attribute m_api_attr; Attribute m_activity_start_attr; Attribute m_activity_end_attr; Attribute m_activity_duration_attr; Attribute m_activity_name_attr; Attribute m_activity_queue_id_attr; Attribute m_activity_device_id_attr; Attribute m_activity_bytes_attr; Attribute m_kernel_name_attr; Attribute m_host_starttime_attr; Attribute m_host_duration_attr; Attribute m_host_timestamp_attr; Attribute m_flush_region_attr; unsigned m_num_records; unsigned m_num_flushed; unsigned m_num_flushes; unsigned m_num_correlations_stored; unsigned m_num_correlations_found; unsigned m_num_correlations_missed; std::mutex m_correlation_map_mutex; std::map<uint64_t, cali::Node*> m_correlation_map; roctracer_pool_t* m_roctracer_pool; Channel* m_channel; bool m_enable_tracing; bool m_record_names; bool m_record_host_duration; bool m_record_host_timestamp; static RocTracerService* s_instance; void create_callback_attributes(Caliper* c) { Attribute subs_attr = c->get_attribute("subscription_event"); Variant v_true(true); m_api_attr = c->create_attribute("rocm.api", CALI_TYPE_STRING, CALI_ATTR_NESTED, 1, &subs_attr, &v_true); } void create_activity_attributes(Caliper* c) { m_activity_start_attr = c->create_attribute("rocm.starttime", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS); m_activity_end_attr = c->create_attribute("rocm.endtime", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS); m_activity_duration_attr = c->create_attribute("rocm.activity.duration", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS | CALI_ATTR_AGGREGATABLE); m_activity_name_attr = c->create_attribute("rocm.activity", CALI_TYPE_STRING, CALI_ATTR_SKIP_EVENTS); m_activity_queue_id_attr = c->create_attribute("rocm.activity.queue", CALI_TYPE_UINT, CALI_ATTR_SKIP_EVENTS); m_activity_device_id_attr = c->create_attribute("rocm.activity.device", CALI_TYPE_UINT, CALI_ATTR_SKIP_EVENTS); m_activity_bytes_attr = c->create_attribute("rocm.activity.bytes", CALI_TYPE_UINT, CALI_ATTR_SKIP_EVENTS); m_kernel_name_attr = c->create_attribute("rocm.kernel.name", CALI_TYPE_STRING, CALI_ATTR_SKIP_EVENTS); m_flush_region_attr = c->create_attribute("roctracer.flush", CALI_TYPE_STRING, CALI_ATTR_DEFAULT); } void create_host_attributes(Caliper* c) { m_host_starttime_attr = c->create_attribute("rocm.host.starttime", CALI_TYPE_UINT, CALI_ATTR_SCOPE_PROCESS | CALI_ATTR_SKIP_EVENTS); if (!(m_record_host_duration || m_record_host_timestamp)) return; int hide_offset = m_record_host_timestamp ? 0 : CALI_ATTR_HIDDEN; m_host_timestamp_attr = c->create_attribute("rocm.host.timestamp", CALI_TYPE_UINT, CALI_ATTR_SCOPE_THREAD | CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS | hide_offset); if (m_record_host_duration) { m_host_duration_attr = c->create_attribute("rocm.host.duration", CALI_TYPE_UINT, CALI_ATTR_SCOPE_THREAD | CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS | CALI_ATTR_AGGREGATABLE); } } void subscribe_attributes(Caliper* c, Channel* channel) { channel->events().subscribe_attribute(c, channel, m_api_attr); } void push_correlation(uint64_t id, cali::Node* node) { std::lock_guard<std::mutex> g(m_correlation_map_mutex); m_correlation_map[id] = node; } cali::Node* pop_correlation(uint64_t id) { cali::Node* ret = nullptr; std::lock_guard<std::mutex> g(m_correlation_map_mutex); auto it = m_correlation_map.find(id); if (it != m_correlation_map.end()) { ret = it->second; m_correlation_map.erase(it); } return ret; } static void hip_api_callback(uint32_t domain, uint32_t cid, const void* callback_data, void* arg) { // skip unneeded callbacks if (cid == HIP_API_ID___hipPushCallConfiguration || cid == HIP_API_ID___hipPopCallConfiguration) return; auto instance = static_cast<RocTracerService*>(arg); auto data = static_cast<const hip_api_data_t*>(callback_data); Caliper c; if (data->phase == ACTIVITY_API_PHASE_ENTER) { c.begin(instance->m_api_attr, Variant(roctracer_op_string(ACTIVITY_DOMAIN_HIP_API, cid, 0))); if (instance->m_enable_tracing) { // When tracing, store a correlation id with the kernel name and the // current region context. We only store correlation IDs for the subset // of calls that produce activities. std::string kernel; cali::Node* node = nullptr; switch (cid) { case HIP_API_ID_hipLaunchKernel: case HIP_API_ID_hipExtLaunchKernel: { Entry e = c.get(instance->m_api_attr); if (e.is_reference()) node = e.node(); if (instance->m_record_names) { kernel = hipKernelNameRefByPtr(data->args.hipLaunchKernel.function_address, data->args.hipLaunchKernel.stream); } } break; case HIP_API_ID_hipModuleLaunchKernel: case HIP_API_ID_hipExtModuleLaunchKernel: case HIP_API_ID_hipHccModuleLaunchKernel: { Entry e = c.get(instance->m_api_attr); if (e.is_reference()) node = e.node(); if (instance->m_record_names) { kernel = hipKernelNameRef(data->args.hipExtModuleLaunchKernel.f); } } break; case HIP_API_ID_hipMemcpy: case HIP_API_ID_hipMemcpy2D: case HIP_API_ID_hipMemcpy2DAsync: case HIP_API_ID_hipMemcpy2DFromArray: case HIP_API_ID_hipMemcpy2DFromArrayAsync: case HIP_API_ID_hipMemcpy2DToArray: case HIP_API_ID_hipMemcpy2DToArrayAsync: case HIP_API_ID_hipMemcpy3D: case HIP_API_ID_hipMemcpy3DAsync: case HIP_API_ID_hipMemcpyAsync: case HIP_API_ID_hipMemcpyAtoH: case HIP_API_ID_hipMemcpyDtoD: case HIP_API_ID_hipMemcpyDtoDAsync: case HIP_API_ID_hipMemcpyDtoH: case HIP_API_ID_hipMemcpyDtoHAsync: case HIP_API_ID_hipMemcpyFromArray: case HIP_API_ID_hipMemcpyFromSymbol: case HIP_API_ID_hipMemcpyFromSymbolAsync: case HIP_API_ID_hipMemcpyHtoA: case HIP_API_ID_hipMemcpyHtoD: case HIP_API_ID_hipMemcpyHtoDAsync: case HIP_API_ID_hipMemcpyParam2D: case HIP_API_ID_hipMemcpyParam2DAsync: case HIP_API_ID_hipMemcpyPeer: case HIP_API_ID_hipMemcpyPeerAsync: case HIP_API_ID_hipMemcpyToArray: case HIP_API_ID_hipMemcpyToSymbol: case HIP_API_ID_hipMemcpyToSymbolAsync: case HIP_API_ID_hipMemcpyWithStream: case HIP_API_ID_hipMemset: case HIP_API_ID_hipMemset2D: case HIP_API_ID_hipMemset2DAsync: case HIP_API_ID_hipMemset3D: case HIP_API_ID_hipMemset3DAsync: case HIP_API_ID_hipMemsetAsync: case HIP_API_ID_hipMemsetD16: case HIP_API_ID_hipMemsetD32: case HIP_API_ID_hipMemsetD32Async: case HIP_API_ID_hipMemsetD8: case HIP_API_ID_hipMemsetD8Async: { Entry e = c.get(instance->m_api_attr); if (e.is_reference()) node = e.node(); } default: break; } if (!kernel.empty()) { kernel = util::demangle(kernel.c_str()); node = c.make_tree_entry(instance->m_kernel_name_attr, Variant(kernel.c_str()), node); } if (node) { instance->push_correlation(data->correlation_id, node); ++instance->m_num_correlations_stored; } } } else { c.end(instance->m_api_attr); } } unsigned flush_record(Caliper* c, const roctracer_record_t* record) { unsigned num_records = 0; if (record->domain == ACTIVITY_DOMAIN_HIP_OPS || record->domain == ACTIVITY_DOMAIN_HCC_OPS) { Attribute attr[7] = { m_activity_name_attr, m_activity_start_attr, m_activity_end_attr, m_activity_duration_attr, m_activity_device_id_attr, m_activity_queue_id_attr, m_activity_bytes_attr }; Variant data[7] = { Variant(roctracer_op_string(record->domain, record->op, record->kind)), Variant(cali_make_variant_from_uint(record->begin_ns)), Variant(cali_make_variant_from_uint(record->end_ns)), Variant(cali_make_variant_from_uint(record->end_ns - record->begin_ns)), Variant(cali_make_variant_from_uint(record->device_id)), Variant(cali_make_variant_from_uint(record->queue_id)), Variant() }; size_t num = 6; if (record->op == HIP_OP_ID_COPY) data[num++] = Variant(cali_make_variant_from_uint(record->bytes)); cali::Node* parent = pop_correlation(record->correlation_id); if (parent) { ++m_num_correlations_found; } else { ++m_num_correlations_missed; } FixedSizeSnapshotRecord<8> snapshot; c->make_record(num, attr, data, snapshot.builder(), parent); m_channel->events().process_snapshot(c, m_channel, SnapshotView(), snapshot.view()); ++num_records; } return num_records; } void flush_activity_records(Caliper* c, const char* begin, const char* end) { c->begin(m_flush_region_attr, Variant("ROCTRACER FLUSH")); unsigned num_flushed = 0; unsigned num_records = 0; const roctracer_record_t* record = reinterpret_cast<const roctracer_record_t*>(begin); const roctracer_record_t* end_record = reinterpret_cast<const roctracer_record_t*>(end); while (record < end_record) { num_flushed += flush_record(c, record); ++num_records; if (roctracer_next_record(record, &record) != 0) break; } if (Log::verbosity() >= 2) { Log(2).stream() << m_channel->name() << ": roctracer: Flushed " << num_records << " records (" << num_flushed << " flushed, " << num_records - num_flushed << " skipped).\n"; } m_num_flushed += num_flushed; m_num_records += num_records; m_num_flushes++; c->end(m_flush_region_attr); } void pre_flush_cb() { roctracer_flush_activity_expl(m_roctracer_pool); } void snapshot_cb(Caliper* c, Channel* channel, const SnapshotView, SnapshotBuilder& snapshot) { uint64_t timestamp = 0; roctracer_get_timestamp(&timestamp); Variant v_now(cali_make_variant_from_uint(timestamp)); Variant v_prev = c->exchange(m_host_timestamp_attr, v_now); if (m_record_host_duration) snapshot.append(Entry(m_host_duration_attr, Variant(cali_make_variant_from_uint(timestamp - v_prev.to_uint())))); } #if 0 static void rt_alloc(char** ptr, size_t size, void* arg) { auto instance = static_cast<RocTracerService*>(arg); char* buffer = new char[size]; instance->m_trace_buffers.push_back(buffer); ++instance->m_num_buffers; *ptr = buffer; if (Log::verbosity() >= 2) { unitfmt_result bytes = unitfmt(size, unitfmt_bytes); Log(2).stream() << "roctracer: Allocated " << bytes.val << bytes.symbol << " trace buffer" << std::endl; } } #endif static void rt_activity_callback(const char* begin, const char* end, void* arg) { auto instance = static_cast<RocTracerService*>(arg); Caliper c; instance->flush_activity_records(&c, begin, end); if (Log::verbosity() >= 2) { unitfmt_result bytes = unitfmt(end-begin, unitfmt_bytes); Log(2).stream() << instance->m_channel->name() << ": roctracer: processed " << bytes.val << bytes.symbol << " buffer" << std::endl; } } void init_tracing(Channel* channel) { roctracer_properties_t properties {}; memset(&properties, 0, sizeof(roctracer_properties_t)); properties.buffer_size = 0x800000; // properties.alloc_fun = rt_alloc; // properties.alloc_arg = this; properties.buffer_callback_fun = rt_activity_callback; properties.buffer_callback_arg = this; if (roctracer_open_pool_expl(&properties, &m_roctracer_pool) != 0) { Log(0).stream() << channel->name() << ": roctracer: roctracer_open_pool_expl(): " << roctracer_error_string() << std::endl; return; } if (roctracer_default_pool_expl(m_roctracer_pool) != 0) { Log(0).stream() << channel->name() << ": roctracer: roctracer_default_pool_expl(): " << roctracer_error_string() << std::endl; return; } if (roctracer_enable_domain_activity_expl(ACTIVITY_DOMAIN_HIP_OPS, m_roctracer_pool) != 0) { Log(0).stream() << channel->name() << ": roctracer: roctracer_enable_activity_expl(): " << roctracer_error_string() << std::endl; return; } if (roctracer_enable_domain_activity_expl(ACTIVITY_DOMAIN_HCC_OPS, m_roctracer_pool) != 0) { Log(0).stream() << channel->name() << ": roctracer: roctracer_enable_activity_expl(): " << roctracer_error_string() << std::endl; return; } channel->events().pre_flush_evt.connect( [this](Caliper*, Channel*, SnapshotView){ this->pre_flush_cb(); }); Log(1).stream() << channel->name() << ": roctracer: Tracing initialized" << std::endl; } void init_callbacks(Channel* channel) { roctracer_set_properties(ACTIVITY_DOMAIN_HIP_API, NULL); if (roctracer_enable_domain_callback(ACTIVITY_DOMAIN_HIP_API, RocTracerService::hip_api_callback, this) != 0) { Log(0).stream() << channel->name() << ": roctracer: enable callback (HIP): " << roctracer_error_string() << std::endl; return; } Log(1).stream() << channel->name() << ": roctracer: Callbacks initialized" << std::endl; } void finish_tracing(Channel* channel) { roctracer_disable_domain_activity(ACTIVITY_DOMAIN_HCC_OPS); roctracer_disable_domain_activity(ACTIVITY_DOMAIN_HIP_OPS); roctracer_close_pool_expl(m_roctracer_pool); m_roctracer_pool = nullptr; Log(1).stream() << channel->name() << ": roctracer: Tracing stopped" << std::endl; } void finish_callbacks(Channel* channel) { roctracer_disable_domain_callback(ACTIVITY_DOMAIN_HIP_API); Log(1).stream() << channel->name() << ": roctracer: Callbacks stopped" << std::endl; } void post_init_cb(Caliper* c, Channel* channel) { subscribe_attributes(c, channel); uint64_t starttime = 0; roctracer_get_timestamp(&starttime); c->set(m_host_starttime_attr, cali_make_variant_from_uint(starttime)); if (m_record_host_timestamp || m_record_host_duration) { c->set(m_host_timestamp_attr, cali_make_variant_from_uint(starttime)); channel->events().snapshot.connect( [](Caliper* c, Channel* chn, SnapshotView info, SnapshotBuilder& rec){ s_instance->snapshot_cb(c, chn, info, rec); }); } init_callbacks(channel); // apparently must happen before init_tracing() if (m_enable_tracing) init_tracing(channel); } void pre_finish_cb(Caliper* c, Channel* channel) { finish_callbacks(channel); if (m_enable_tracing) finish_tracing(channel); } void finish_cb(Caliper* c, Channel* channel) { if (m_enable_tracing) { Log(1).stream() << channel->name() << ": roctracer: " << m_num_flushes << " activity flushes, " << m_num_records << " records processed, " << m_num_flushed << " records flushed." << std::endl; if (Log::verbosity() >= 2) { Log(2).stream() << channel->name() << ": roctracer: " << m_num_correlations_stored << " correlations stored; " << m_num_correlations_found << " correlations found, " << m_num_correlations_missed << " missed." << std::endl; } } } RocTracerService(Caliper* c, Channel* channel) : m_api_attr { Attribute::invalid }, m_num_records { 0 }, m_num_flushed { 0 }, m_num_flushes { 0 }, m_num_correlations_stored { 0 }, m_num_correlations_found { 0 }, m_num_correlations_missed { 0 }, m_roctracer_pool { nullptr }, m_channel { channel } { auto config = services::init_config_from_spec(channel->config(), s_spec); m_enable_tracing = config.get("trace_activities").to_bool(); m_record_names = config.get("record_kernel_names").to_bool(); m_record_host_duration = config.get("snapshot_duration").to_bool(); m_record_host_timestamp = config.get("snapshot_timestamps").to_bool(); create_callback_attributes(c); create_activity_attributes(c); create_host_attributes(c); } ~RocTracerService() { #if 0 for (char* buffer : m_trace_buffers) delete[] buffer; #endif } public: static const char* s_spec; static void register_roctracer(Caliper* c, Channel* channel) { if (s_instance) { Log(0).stream() << channel->name() << ": roctracer service is already active, disabling!" << std::endl; } s_instance = new RocTracerService(c, channel); channel->events().post_init_evt.connect( [](Caliper* c, Channel* channel){ s_instance->post_init_cb(c, channel); }); channel->events().pre_finish_evt.connect( [](Caliper* c, Channel* channel){ s_instance->pre_finish_cb(c, channel); }); channel->events().finish_evt.connect( [](Caliper* c, Channel* channel){ s_instance->finish_cb(c, channel); delete s_instance; s_instance = nullptr; }); Log(1).stream() << channel->name() << ": Registered roctracer service." << " Activity tracing is " << (s_instance->m_enable_tracing ? "on" : "off") << std::endl; } }; const char* RocTracerService::s_spec = R"json( { "name": "roctracer", "description": "Record ROCm API and GPU activities", "config": [ { "name": "trace_activities", "type": "bool", "description": "Enable ROCm GPU activity tracing", "value": "true" }, { "name": "record_kernel_names", "type": "bool", "description": "Record kernel names when activity tracing is enabled", "value": "false" }, { "name": "snapshot_duration", "type": "bool", "description": "Record duration of host-side activities using ROCm timestamps", "value": "false" }, { "name": "snapshot_timestamps", "type": "bool", "description": "Record host-side timestamps with ROCm", "value": "false" } ] } )json"; RocTracerService* RocTracerService::s_instance = nullptr; } // namespace [anonymous] namespace cali { CaliperService roctracer_service { ::RocTracerService::s_spec, ::RocTracerService::register_roctracer }; }
501ddcb74bb73357cd39e8240414badf4ddaebe4
a97a75e570ea1e21e85e8bf7c75aac6b7bd7df26
/Srishti5/Srishti5.ino
02b49737b80cd97d222154b992f3ba6359eb8af6
[]
no_license
shawnalexsony/Srishti-projects
d77e8772022f701431f5d76ebef92c978df29393
be888cd49238af1de342b841b43c79ee2594eb91
refs/heads/master
2020-03-23T09:15:25.767349
2018-07-18T03:40:14
2018-07-18T03:40:14
141,376,867
0
0
null
null
null
null
UTF-8
C++
false
false
628
ino
Srishti5.ino
/*Scrolling text in an LED display*/ #include <LiquidCrystal.h> LiquidCrystal lcd(8,9,10,11,12,13);/*initialize LCD pins*/ void setup() { // put your setup code here, to run once: lcd.begin(16,2);/*Initialize the no of active characters in LCD*/ } void loop() { // put your main code here, to run repeatedly: for(int i=0;i<16;i++) { lcd.setCursor(i,0); lcd.print("LCD scrolling"); delay(500); lcd.setCursor(i,0); lcd.print(" "); delay(1); } for(int i=0;i<16;i++) { lcd.setCursor(i,1); lcd.print("LCD scrolling"); delay(500); lcd.setCursor(i,1); lcd.print(" "); delay(1); } }
3b814c7aa88069e515d1938823020fdbc8484e3a
0a20f0403c1cd35b480ab7a5b96f2cf25e74982a
/allinall10340/src/main.cpp
524bd9bebc3e73f6117f461109f3cd94abda09dd
[]
no_license
OskarOG/UVA
b00fbd4348e35ceb2064dbf6ab34998879111b2c
53c0552b3133d046c74a2873a2d01cd38ad3fa98
refs/heads/master
2020-04-24T10:11:33.338338
2019-02-21T14:42:58
2019-02-21T14:42:58
171,885,086
0
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
main.cpp
#include <iostream> #include <string> using namespace std; int main() { string sstring, text; while(cin>>sstring>>text) { size_t sspos = 0; for(size_t i = 0; i < text.size(); i++) { if (sspos < sstring.size() && sstring[sspos] == text[i]) { sspos++; } } if (sspos == sstring.size()) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
fb73d3f057d2210773b9f7bf12da86f8ddfaa496
d51e54dccbb594a056005cb50a9dbad472ddb034
/Volume_13/Number_3/Brodu2008/src/neighand_structures.hpp
102db0f3fb11b6fb9488b4484011151c3773737a
[ "MIT", "LGPL-2.0-only", "LGPL-2.1-only" ]
permissive
skn123/jgt-code
4aa8d39d6354a1ede9b141e5e7131e403465f4f7
1c80455c8aafe61955f61372380d983ce7453e6d
refs/heads/master
2023-08-30T22:54:09.412136
2023-08-28T20:54:09
2023-08-28T20:54:09
217,573,703
0
0
MIT
2023-08-29T02:29:29
2019-10-25T16:27:56
MATLAB
UTF-8
C++
false
false
3,988
hpp
neighand_structures.hpp
/* Neighand: Neighborhood Handling library The goal of this project is to find 3D neighbors efficiently. Read the documentation contained in the article "Query Sphere Indexing for Neighborhood Requests" for details. This file defines the data structures that are used for this project. Nicolas Brodu, 2006/7 Code released according to the GNU LGPL, v2 or above. */ #ifndef NEIGHAND_STRUCTURES_HPP #define NEIGHAND_STRUCTURES_HPP // concat the arguments #define COMPILE_TIME_ASSERT_CONCAT_HELPER(X,Y) X ## Y // expand the macro arguments, including __LINE__ #define COMPILE_TIME_ASSERT_CONCAT(X,Y) COMPILE_TIME_ASSERT_CONCAT_HELPER(X,Y) template<int line, bool x> struct AssertionFailedLine; template<int line> struct AssertionFailedLine<line, true> {}; #define COMPILE_TIME_ASSERT(x) \ struct COMPILE_TIME_ASSERT_CONCAT(CompileTimeAssertionFailed_Line,__LINE__) : public AssertionFailedLine<__LINE__,bool(x)> { }; // Assert a few assumptions COMPILE_TIME_ASSERT(sizeof(FloatType)==4) // sizeof(char) is always 1, but char is not always 8 bits... => reject these machines COMPILE_TIME_ASSERT(sizeof(uint32_t)==4) // We need memory pointers to be 4 bytes too COMPILE_TIME_ASSERT(sizeof(void*)==4) // We would need to check that float endianity is the same as integer endianity // This apparently cannot be done at compile time according to current language specs // Specific system flags could be used, like FLOAT_BYTE_ORDER and BYTE_ORDER macros. template <typename UserObject> struct CellEntry; // What is passed to the DB user template <typename UserObject> struct ObjectProxy { FloatType x; // align x/y/z on 16-bytes boundary, plan for SSE2 extension FloatType y; // FloatType z; // ObjectProxy* next; // next proxy in the cell list UserObject* object; // user object ObjectProxy* prev; // prev proxy in the cell list uint32_t cellIndex; // index of the top-level cell CellEntry<UserObject>* cell; }; // COMPILE_TIME_ASSERT(sizeof(ObjectProxy)==32) // Main object for the array of cells. Also maintains the non-empty lists // DESIGN CHOICE: // - This cell size is limited to 8 because array addressing *8 is builtin on x86, *16 is not // - The linked list was initially double-linked, which forces cell size 16 // It is now single-linked, and ordered in increasing cell indices. // => the memory access is much faster when running through the non-empty list template <typename UserObject> struct CellEntry { ObjectProxy<UserObject>* objects; // 0 if empty cell CellEntry* nextNonEmpty; // single-linked list }; // COMPILE_TIME_ASSERT(sizeof(CellEntry)==8) template <typename UserObject> struct NearestNeighbor { UserObject* object; FloatType squaredDistance; }; // Example of remapper for objects that have a "proxy" field template<typename UserObject> struct ProxiedObjectRemapper { void operator()(UserObject* object, ObjectProxy<UserObject>* updated_proxy){ object->proxy = updated_proxy; } }; enum QueryMethod {Auto, Sphere, Cube, NonEmpty, Brute}; // Previous version used reinterpret_cast, which is C++ way // However this badly interferes with aliasing, and -fno-strict-aliasing was necessary // Using a union is handled by the compiler and allows to assume aliasing // hence the compiler can optimize better union FloatConverter { FloatType f; uint32_t i; // C++ support for union constructors is good, avoids declare/affect/retrieve syntax NEIGHAND_INLINE FloatConverter(FloatType _f) : f(_f) {} // initialized constructor: used for neighand_apply.hpp NEIGHAND_INLINE FloatConverter() : i(0) {} // avoid confusion when multiple implicit conversions would be possible. NEIGHAND_INLINE explicit FloatConverter(uint32_t _i) : i(_i) {} }; COMPILE_TIME_ASSERT(sizeof(FloatConverter)==4) #endif
b4fd00997ef0666d5802c9adf1b20648bf60dbcd
61e5bd64d62378db18d979dff5f28b3d61ddeab7
/ClntN0.cpp
4e9f7b5b7744f5064d558ae4cd65c5d9bec14bc9
[]
no_license
Zhmur-Amir/Zadacha3-4-semester
3329069ae18f68805ac9425d268b8b98f3ca95f2
eb01d6a0fd24742a1b89aed607490d0236647041
refs/heads/main
2023-03-28T04:08:27.363785
2021-04-02T08:28:02
2021-04-02T08:28:02
353,135,301
0
0
null
null
null
null
UTF-8
C++
false
false
7,213
cpp
ClntN0.cpp
#include "ClntN0.h" /*ClntN0 :: ClntN0(const bool r,const int m, const vector<int> brr, const string filename) { n=m; s=r; FileName=filename; arr=new int[n]; for(int i=0; i<n; i++) { if(brr[i]>=0 && brr[i]<10) arr[i]=brr[i]; else throw 2; } } ClntN0 :: ClntN0(const bool r,const int m, const vector<int> brr) { n=m; s=r; arr=new int[n]; for(int i=0; i<n; i++) { if(brr[i]>=0 && brr[i]<10) arr[i]=brr[i]; else throw 2; } } */ /* void ClntN0 :: CopyOnly(const ClntN &b) { n=b.len(); s=b.sign(); arr=new int[n]; for(int i=0; i<n; i++) { if(b[i]>=0 && b[i]<10) arr[i]=b[i]; else { cout<<"Too big number in CopyOnly(1)"<<endl; throw 2; } } } void ClntN0 :: CopyOnly(const ClntN0 &b) { n=b.n; s=b.s; FileName=b.FileName; arr=new int[n]; for(int i=0; i<n; i++) { if(b.arr[i]>=0 && b.arr[i]<10) arr[i]=b.arr[i]; else { cout<<"Too big number in CopyOnly(2)"<<endl; throw 2; } } } */ ClntN0 operator+(const ClntN&a,const ClntN&b) { bool h; if(b.len()!=a.len()) { cout<<"Error! Different length..."<<endl; throw 1; } else{} if(b.len()==0 || a.len()==0) { cout<<"Error! Zero length..."<<endl; throw 1; } ClntN0 f; f.s=a.sign(); f.n=a.len(); f.arr=new int[a.len()]; auto start=chrono::system_clock::now(); omp_set_dynamic(0); omp_set_num_threads(10); if(b.sign()==a.sign()) { vector<int> j; j.resize(a.len()); #pragma omp parallel for for(int i=0; i<a.len(); i++) { j[i]=(a[i]+b[i]); } if(j[0]>9) { cout<<"Too big number"<<endl; throw 5; } for(int i=a.len()-1; i>=0; i--) { if (j[i]>9) { j[i]=j[i]-10; j[i-1]=j[i-1]+1; } } #pragma omp parallel for for(int i=0; i<a.len(); i++) { f.arr[i]=j[i]; } } else { for(int i=0; i<a.len(); i++) { if(a[i]!=b[i]) { if(a[i]>b[i]) {h=true;} else {h=false;} break; } } if(h==true) { vector<int> g; g.resize(a.len()); #pragma omp parallel for for(int i=0; i<a.len(); i++) { g[i]=(a[i]-b[i]); } for(int i=a.len()-1; i>=0; i--) { if (g[i]<0) { g[i]=g[i]+10; g[i-1]=g[i-1]-1; } } #pragma omp parallel for for(int i=0; i<a.len(); i++) { f.arr[i]=g[i]; } } if(h==false) { f.s=!a.sign(); vector<int> p; p.resize(a.len()); #pragma omp parallel for for(int i=a.len()-1; i>=0; i--) { p[i]=(-a[i]+b[i]); } for(int i=a.len()-1; i>=0; i--) { if (p[i]<0) { p[i]=p[i]+10; p[i-1]=p[i-1]-1; } } #pragma omp parallel for for(int i=0; i<a.len(); i++) { f.arr[i]=p[i]; } } } auto end=chrono::system_clock::now(); int elapsed_ms=static_cast<int>(chrono::duration_cast<chrono::milliseconds>(end-start).count()); cout<<"Addition operator + runtime is "<<elapsed_ms<<" ms"<<endl; return f; } ClntN0 operator-(const ClntN&a,const ClntN&b) { bool h; if(b.len()!=a.len()) { cout<<"Error! Different length..."<<endl; throw 1; } else{} if(b.len()==0 || a.len()==0) { cout<<"Error! Zero length..."<<endl; throw 1; } ClntN0 f; f.s=a.sign(); f.n=a.len(); f.arr=new int[a.len()]; auto start=chrono::system_clock::now(); omp_set_dynamic(0); omp_set_num_threads(10); if(b.sign()!=a.sign()) { vector<int> j; j.resize(a.len()); #pragma omp parallel for for(int i=0; i<a.len(); i++) { j[i]=(a[i]+b[i]); } if(j[0]>9) { cout<<"Too big number"<<endl; throw 5; } for(int i=a.len()-1; i>=0; i--) { if (j[i]>9) { j[i]=j[i]-10; j[i-1]=j[i-1]+1; } } #pragma omp parallel for for(int i=0; i<a.len(); i++) { f.arr[i]=j[i]; } } else { for(int i=0; i<a.len(); i++) { if(a[i]!=b[i]) { if(a[i]>b[i]) {h=true;} else {h=false;} break; } } if(h==true) { vector<int> g; g.resize(a.len()); #pragma omp parallel for for(int i=0; i<a.len(); i++) { g[i]=(a[i]-b[i]); } for(int i=a.len()-1; i>=0; i--) { if (g[i]<0) { g[i]=g[i]+10; g[i-1]=g[i-1]-1; } } #pragma omp parallel for for(int i=0; i<a.len(); i++) { f.arr[i]=g[i]; } } if(h==false) { f.s=!a.sign(); vector<int> p; p.resize(a.len()); #pragma omp parallel for for(int i=0; i<a.len(); i++) { p[i]=(-a[i]+b[i]); } for(int i=a.len()-1; i>=0; i--) { if (p[i]<0) { p[i]=p[i]+10; p[i-1]=p[i-1]-1; } } #pragma omp parallel for for(int i=0; i<a.len(); i++) { f.arr[i]=p[i]; } } } auto end=chrono::system_clock::now(); int elapsed_ms=static_cast<int>(chrono::duration_cast<chrono::milliseconds>(end-start).count()); cout<<"Addition operator - runtime is "<<elapsed_ms<<" ms"<<endl; return f; }
247de181be2cb9469edfcc35e780670bab413e84
a28685455e9f5c46d561ab9f02129fbec4e24294
/Cpp/Hello_world_2.cpp
504babfb40b86842129978642e2eaf9e426015aa
[]
no_license
surabhikanade/DataStructure
02f40c041c46ecbbc16a91c8fab2bad2187416c1
da3112d8a3e187c4a5afb7ce0a460a633124418e
refs/heads/master
2023-09-04T08:12:44.469500
2021-09-18T09:24:42
2021-09-18T09:24:42
375,299,444
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
Hello_world_2.cpp
#include<iostream> using namespace std; int main() { if(cout<<"Hello World") { //without using semicolon; } }
e0cebf3c64b32d2e29b3a66204af298bc442275b
f33b926bb4dcbab90e727de1c40c95174beca9cc
/SSTM32/8_Sensor_GPS/8_Sensor_GPS.ino
9b4facf31ff244e091de73c5e195cb69f71fc17c
[]
no_license
bagus-rataha/Pelatihan-Di-DELAMETA
a5e5176dcaf9b4a0f1ee30dfdec17cf1b1e329bf
74c73d6ae880ed7fe563684b1e40ef893cef8b66
refs/heads/main
2023-09-05T11:14:29.073007
2021-11-25T00:55:04
2021-11-25T00:55:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
566
ino
8_Sensor_GPS.ino
//Inisialisasi #include <TinyGPS++.h> int GPSBaud=9600; //Tiny GPS TinyGPSPlus gps; String latitude, longitude; void setup() { Serial.begin(9600); Serial2.begin(115200); } void loop() { // Baca while ( Serial2.available() > 0){ gps.encode(Serial2.read()); } if (gps.location.isValid()){ latitude = String(gps.location.lat(), 6); longitude = String(gps.location.lng(), 6); String link = ("www.google.com/maps/place/" + String(latitude) + "," + String(longitude)); Serial.println(link); delay(500); } }
95fd033b7e7d97f27d9b51e4d323737f45818c3f
13a1091034461938ca5a3872b93a90a03c08e0b2
/Engine/Source/Shared/System/Scene/Rendering/ScnLightComponent.h
03bc8149a0278274656bd348b92416c4604aa36c
[ "LicenseRef-scancode-public-domain", "Zlib", "MIT", "BSD-3-Clause" ]
permissive
Kimau/Psybrus
48bcd404a65e69a32bb5f8b2d1dce4e495d38b78
c9cd7ce4f1aa1e3b9a0fc4f32942e05a95291202
refs/heads/develop
2020-05-20T22:25:28.289005
2015-12-14T02:19:23
2015-12-14T02:19:23
47,588,608
0
0
null
2015-12-08T00:41:38
2015-12-08T00:41:37
null
UTF-8
C++
false
false
2,161
h
ScnLightComponent.h
/************************************************************************** * * File: Rendering/ScnLightComponent.h * Author: Neil Richardson * Ver/Date: 11/01/13 * Description: * * * * * **************************************************************************/ #ifndef __ScnLightComponent_H__ #define __ScnLightComponent_H__ #include "System/Renderer/RsCore.h" #include "System/Scene/ScnTypes.h" #include "System/Scene/ScnSpatialComponent.h" ////////////////////////////////////////////////////////////////////////// // ScnLightType enum ScnLightType { scnLT_POINT, scnLT_SPOT }; ////////////////////////////////////////////////////////////////////////// // ScnLightComponent class ScnLightComponent: public ScnSpatialComponent { public: REFLECTION_DECLARE_DERIVED( ScnLightComponent, ScnSpatialComponent ); DECLARE_VISITABLE( ScnLightComponent ); public: ScnLightComponent(); virtual ~ScnLightComponent(); void onAttach( ScnEntityWeakRef Parent ) override; void onDetach( ScnEntityWeakRef Parent ) override; /** * Get ambient colour. */ const RsColour& getAmbientColour() const; /** * Get diffuse colour. */ const RsColour& getDiffuseColour() const; /** * Find attenuation of light by a distance. */ BcF32 findAttenuationByDistance( BcF32 Distance ) const; /** * Find distance from light by an attenuation. */ BcF32 findDistanceByAttenuation( BcF32 Attenuation ) const; /** * Create attenuation values using min, mid and max distances. */ void createAttenuationValues( BcF32 MinDistance, BcF32 MidDistance, BcF32 MaxDistance ); /** * Set material parameters. */ void setMaterialParameters( BcU32 LightIndex, class ScnMaterialComponent* MaterialComponent ); /** * Set the light tree node we are in. */ void setLightTreeNode( class ScnLightTreeNode* Node ); /** * Get the light tree node we are in. */ class ScnLightTreeNode* getLightTreeNode(); /** * Get light AABB. */ MaAABB getAABB() const override; private: ScnLightType Type_; RsColour AmbientColour_; RsColour DiffuseColour_; BcF32 Min_; BcF32 Mid_; BcF32 Max_; BcF32 AttnC_; BcF32 AttnL_; BcF32 AttnQ_; }; #endif
f81a7773c4098553a45b50df6bd5628b037808a8
e3e7c57fc413e3b6bb79166b686d2210c82beb71
/stgui/src/ui/slider.cpp
dcc07d609be3f53cd89be08846d9a860fd1cf253
[]
no_license
pronebel/fork-imgui-imdesigner
65a5c7550162ea1bd1002949598013dc8fed474f
62d90eb90cda54190407da680a1e979842d96503
refs/heads/master
2023-03-16T20:00:10.274984
2019-02-16T16:37:23
2019-02-16T16:37:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
56
cpp
slider.cpp
#include "slider.hpp" using namespace st::ui;
27ad9dd425f9b5ac858228df8054d80817ce58da
cc17eb854019ceafb8b9d5a7a80d88b14363fee6
/1412Star.cpp
5f6353aa117525c10ae9c99b8b1a80774f6478ef
[]
no_license
kuronekonano/OJ_Problem
76ec54f16c4711b0abbc7620df5519b3fff4e41b
ea728084575620538338368f4b6526dfdd6847db
refs/heads/master
2021-06-23T02:19:59.735873
2020-12-30T03:52:59
2020-12-30T03:52:59
166,183,278
0
0
null
null
null
null
GB18030
C++
false
false
307
cpp
1412Star.cpp
#include<stdio.h> int main() { int n,i; while(scanf("%d",&n)!=EOF)//第一个图形只有一个 { int sum=1;//第二个图型外围增加了12个 for(i=2;i<=n;i++) { sum=sum+(i-1)*12; } printf("%d\n",sum); } return 0; }
1f86888867995049d39f39d4aa22a6a73811fb44
7ee1d46e0113cb79a7187678a09a799be74efb98
/union find.cpp
7d3d67477a1e2ed32ddc28da63f74717a1ff647e
[]
no_license
aayush1010/Codes
bc7646bded879d8dc23e9bd132491be4f17c85b8
32d87f01f1ae071f171283d623e2780fb9cef910
refs/heads/master
2021-01-22T10:15:07.090072
2019-01-25T11:50:47
2019-01-25T11:50:47
102,337,184
0
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
union find.cpp
#include <iostream> using namespace std; class uf{ private: int a[]; public: void quickfind(int n){ for(int i = 0; i < n; i++){ a[i] = i; } } bool connected(int p, int q){ if(a[p] == a[q]){ return true; } return false; } void unionf(int p, int q){ int pid = a[p]; int qid = a[q]; for(int i = 0; i < n; i++){ if(pid == a[i]){ a[i] = qid; } } } } int main(){ return 0; }
532ddb3e7bfcccd301e4e0ff94f739f9c997de0d
db108683e72b17e76ad5bd1ce3c63083cffee95b
/ObjetoGeometrico.cpp
58e940ee13c263a8df64fec81ddcb078014d9c02
[]
no_license
Julia1297/texturas
9f99edf0528ef1b6446976940fbf38b180b31d37
8fcb3f95bbf6a6f2f665e2f57fa1d7dc21aee925
refs/heads/master
2020-05-27T17:41:43.213155
2019-06-17T21:35:11
2019-06-17T21:35:11
188,725,576
0
0
null
null
null
null
UTF-8
C++
false
false
86
cpp
ObjetoGeometrico.cpp
#include "ObjetoGeometrico.h" ObjetoGeometrico::ObjetoGeometrico(bool s){sombra = s;}
2444f9813e23cf9c1fac429f05d58ee59b0e8737
0149ed842327e3133fc2fe7b49d6ee2e27c22021
/opencl/test/unit_test/command_queue/enqueue_kernel_mt_tests.cpp
a8a10a1daeb76c268ed52056e0f974e9f02be19f
[ "MIT" ]
permissive
intel/compute-runtime
17f1c3dd3e1120895c6217b1e6c311d88a09902e
869e3ec9f83a79ca4ac43a18d21847183c63e037
refs/heads/master
2023-09-03T07:28:16.591743
2023-09-02T02:04:35
2023-09-02T02:24:33
105,299,354
1,027
262
MIT
2023-08-25T11:06:41
2017-09-29T17:26:43
C++
UTF-8
C++
false
false
19,675
cpp
enqueue_kernel_mt_tests.cpp
/* * Copyright (C) 2018-2023 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/test/common/helpers/kernel_binary_helper.h" #include "shared/test/common/mocks/mock_csr.h" #include "shared/test/common/mocks/mock_submissions_aggregator.h" #include "opencl/source/command_queue/command_queue_hw.h" #include "opencl/test/unit_test/command_queue/enqueue_fixture.h" #include "opencl/test/unit_test/fixtures/hello_world_fixture.h" typedef HelloWorldFixture<HelloWorldFixtureFactory> EnqueueKernelFixture; typedef Test<EnqueueKernelFixture> EnqueueKernelTest; HWTEST_F(EnqueueKernelTest, givenCsrInBatchingModeWhenFinishIsCalledThenBatchesSubmissionsAreFlushed) { auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); pDevice->resetCommandStreamReceiver(mockCsr); auto mockedSubmissionsAggregator = new MockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); std::atomic<bool> startEnqueueProcess(false); MockKernelWithInternals mockKernel(*pClDevice); size_t gws[3] = {1, 0, 0}; auto enqueueCount = 10; auto threadCount = 4; auto function = [&]() { // wait until we are signalled while (!startEnqueueProcess) ; for (int enqueue = 0; enqueue < enqueueCount; enqueue++) { pCmdQ->enqueueKernel(mockKernel.mockKernel, 1, nullptr, gws, nullptr, 0, nullptr, nullptr); } }; std::vector<std::thread> threads; for (auto thread = 0; thread < threadCount; thread++) { threads.push_back(std::thread(function)); } int64_t currentTaskCount = 0; startEnqueueProcess = true; // call a flush while other threads enqueue, we can't drop anything while (currentTaskCount < enqueueCount * threadCount) { clFlush(pCmdQ); auto locker = mockCsr->obtainUniqueOwnership(); currentTaskCount = mockCsr->peekTaskCount(); } for (auto &thread : threads) { thread.join(); } pCmdQ->finish(); EXPECT_GE(mockCsr->flushCalledCount, 1); EXPECT_LE(mockCsr->flushCalledCount, enqueueCount * threadCount); EXPECT_EQ(mockedSubmissionsAggregator->peekInspectionId() - 1, (uint32_t)mockCsr->flushCalledCount); } template <typename GfxFamily> struct MockCommandQueueHw : public CommandQueueHw<GfxFamily> { using CommandQueue::bcsInitialized; }; HWTEST_F(EnqueueKernelTest, givenTwoThreadsAndBcsEnabledWhenEnqueueWriteBufferAndEnqueueNDRangeKernelInLoopThenIsNoRace) { DebugManagerStateRestore debugRestorer; DebugManager.flags.ForceCsrLockInBcsEnqueueOnlyForGpgpuSubmission.set(1); HardwareInfo hwInfo = *pDevice->executionEnvironment->rootDeviceEnvironments[0]->getMutableHardwareInfo(); hwInfo.capabilityTable.blitterOperationsSupported = true; REQUIRE_FULL_BLITTER_OR_SKIP(*pDevice->executionEnvironment->rootDeviceEnvironments[0]); std::atomic<bool> startEnqueueProcess(false); auto iterationCount = 40; auto threadCount = 2; constexpr size_t n = 256; unsigned int data[n] = {}; constexpr size_t bufferSize = n * sizeof(unsigned int); size_t gws[3] = {1, 0, 0}; size_t gwsSize[3] = {n, 1, 1}; size_t lws[3] = {1, 1, 1}; cl_uint workDim = 1; KernelBinaryHelper kbHelper("CopyBuffer_simd16", false); std::string testFile; testFile.append(clFiles); testFile.append("CopyBuffer_simd16.cl"); size_t sourceSize = 0; auto pSource = loadDataFromFile(testFile.c_str(), sourceSize); EXPECT_NE(0u, sourceSize); EXPECT_NE(nullptr, pSource); MockClDevice mockClDevice{MockDevice::createWithExecutionEnvironment<MockDevice>(&hwInfo, pDevice->executionEnvironment, 0)}; const cl_device_id deviceId = &mockClDevice; auto context = clCreateContext(nullptr, 1, &deviceId, nullptr, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, context); auto queue = clCreateCommandQueue(context, deviceId, 0, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, queue); const char *sources[1] = {pSource.get()}; auto program = clCreateProgramWithSource( context, 1, sources, &sourceSize, &retVal); ASSERT_NE(nullptr, program); retVal = clBuildProgram( program, 1, &deviceId, nullptr, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, retVal); auto kernel = clCreateKernel(program, "CopyBuffer", &retVal); ASSERT_NE(nullptr, kernel); EXPECT_EQ(CL_SUCCESS, retVal); cl_mem_flags flags = CL_MEM_READ_WRITE; auto buffer0 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); auto buffer1 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 0, sizeof(cl_mem), &buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 1, sizeof(cl_mem), &buffer1); EXPECT_EQ(CL_SUCCESS, retVal); auto function = [&]() { while (!startEnqueueProcess) ; cl_int fRetVal; for (int i = 0; i < iterationCount; i++) { fRetVal = clEnqueueWriteBuffer(queue, buffer0, false, 0, bufferSize, data, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); fRetVal = clEnqueueNDRangeKernel(queue, kernel, workDim, gws, gwsSize, lws, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); } }; std::vector<std::thread> threads; for (auto thread = 0; thread < threadCount; thread++) { threads.push_back(std::thread(function)); } startEnqueueProcess = true; for (auto &thread : threads) { thread.join(); } EXPECT_TRUE(NEO::castToObject<MockCommandQueueHw<FamilyType>>(queue)->bcsInitialized); retVal = clFinish(queue); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseMemObject(buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseMemObject(buffer1); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseKernel(kernel); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseProgram(program); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseCommandQueue(queue); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseContext(context); EXPECT_EQ(CL_SUCCESS, retVal); } HWTEST_F(EnqueueKernelTest, givenBcsEnabledWhenThread1EnqueueWriteBufferAndThread2EnqueueNDRangeKernelInLoopThenIsNoRace) { DebugManagerStateRestore debugRestorer; DebugManager.flags.ForceCsrLockInBcsEnqueueOnlyForGpgpuSubmission.set(1); HardwareInfo hwInfo = *pDevice->executionEnvironment->rootDeviceEnvironments[0]->getMutableHardwareInfo(); hwInfo.capabilityTable.blitterOperationsSupported = true; REQUIRE_FULL_BLITTER_OR_SKIP(*pDevice->executionEnvironment->rootDeviceEnvironments[0]); std::atomic<bool> startEnqueueProcess(false); auto iterationCount = 40; constexpr size_t n = 256; unsigned int data[n] = {}; constexpr size_t bufferSize = n * sizeof(unsigned int); size_t gws[3] = {1, 0, 0}; size_t gwsSize[3] = {n, 1, 1}; size_t lws[3] = {1, 1, 1}; cl_uint workDim = 1; KernelBinaryHelper kbHelper("CopyBuffer_simd16", false); std::string testFile; testFile.append(clFiles); testFile.append("CopyBuffer_simd16.cl"); size_t sourceSize = 0; auto pSource = loadDataFromFile(testFile.c_str(), sourceSize); EXPECT_NE(0u, sourceSize); EXPECT_NE(nullptr, pSource); MockClDevice mockClDevice{MockDevice::createWithExecutionEnvironment<MockDevice>(&hwInfo, pDevice->executionEnvironment, 0)}; const cl_device_id deviceId = &mockClDevice; auto context = clCreateContext(nullptr, 1, &deviceId, nullptr, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, context); auto queue = clCreateCommandQueue(context, deviceId, 0, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, queue); const char *sources[1] = {pSource.get()}; auto program = clCreateProgramWithSource( context, 1, sources, &sourceSize, &retVal); ASSERT_NE(nullptr, program); retVal = clBuildProgram( program, 1, &deviceId, nullptr, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, retVal); auto kernel = clCreateKernel(program, "CopyBuffer", &retVal); ASSERT_NE(nullptr, kernel); EXPECT_EQ(CL_SUCCESS, retVal); cl_mem_flags flags = CL_MEM_READ_WRITE; auto buffer0 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); auto buffer1 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 0, sizeof(cl_mem), &buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 1, sizeof(cl_mem), &buffer1); EXPECT_EQ(CL_SUCCESS, retVal); std::vector<std::thread::id> threadsIds; auto functionEnqueueWriteBuffer = [&]() { while (!startEnqueueProcess) ; cl_int fRetVal; for (int i = 0; i < iterationCount; i++) { fRetVal = clEnqueueWriteBuffer(queue, buffer0, false, 0, bufferSize, data, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); } }; auto functionEnqueueNDRangeKernel = [&]() { while (!startEnqueueProcess) ; cl_int fRetVal; for (int i = 0; i < iterationCount; i++) { fRetVal = clEnqueueNDRangeKernel(queue, kernel, workDim, gws, gwsSize, lws, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); } }; std::vector<std::thread> threads; threads.push_back(std::thread(functionEnqueueWriteBuffer)); threads.push_back(std::thread(functionEnqueueNDRangeKernel)); startEnqueueProcess = true; for (auto &thread : threads) { thread.join(); } EXPECT_TRUE(NEO::castToObject<MockCommandQueueHw<FamilyType>>(queue)->bcsInitialized); retVal = clFinish(queue); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseMemObject(buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseMemObject(buffer1); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseKernel(kernel); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseProgram(program); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseCommandQueue(queue); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseContext(context); EXPECT_EQ(CL_SUCCESS, retVal); } HWTEST_F(EnqueueKernelTest, givenBcsEnabledAndQueuePerThreadWhenEnqueueWriteBufferAndEnqueueNDRangeKernelInLoopThenIsNoRace) { DebugManagerStateRestore debugRestorer; DebugManager.flags.ForceCsrLockInBcsEnqueueOnlyForGpgpuSubmission.set(1); DebugManager.flags.EnableCmdQRoundRobindEngineAssign.set(0); HardwareInfo hwInfo = *pDevice->executionEnvironment->rootDeviceEnvironments[0]->getMutableHardwareInfo(); hwInfo.capabilityTable.blitterOperationsSupported = true; REQUIRE_FULL_BLITTER_OR_SKIP(*pDevice->executionEnvironment->rootDeviceEnvironments[0]); std::atomic<bool> startEnqueueProcess(false); auto iterationCount = 40; const auto threadCount = 10; constexpr size_t n = 256; unsigned int data[n] = {}; constexpr size_t bufferSize = n * sizeof(unsigned int); size_t gws[3] = {1, 0, 0}; size_t gwsSize[3] = {n, 1, 1}; size_t lws[3] = {1, 1, 1}; cl_uint workDim = 1; KernelBinaryHelper kbHelper("CopyBuffer_simd16", false); std::string testFile; testFile.append(clFiles); testFile.append("CopyBuffer_simd16.cl"); size_t sourceSize = 0; auto pSource = loadDataFromFile(testFile.c_str(), sourceSize); EXPECT_NE(0u, sourceSize); EXPECT_NE(nullptr, pSource); MockClDevice mockClDevice{MockDevice::createWithExecutionEnvironment<MockDevice>(&hwInfo, pDevice->executionEnvironment, 0)}; const cl_device_id deviceId = &mockClDevice; auto context = clCreateContext(nullptr, 1, &deviceId, nullptr, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, context); const char *sources[1] = {pSource.get()}; auto program = clCreateProgramWithSource( context, 1, sources, &sourceSize, &retVal); ASSERT_NE(nullptr, program); retVal = clBuildProgram( program, 1, &deviceId, nullptr, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, retVal); auto kernel = clCreateKernel(program, "CopyBuffer", &retVal); ASSERT_NE(nullptr, kernel); EXPECT_EQ(CL_SUCCESS, retVal); cl_mem_flags flags = CL_MEM_READ_WRITE; auto buffer0 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); auto buffer1 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 0, sizeof(cl_mem), &buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 1, sizeof(cl_mem), &buffer1); EXPECT_EQ(CL_SUCCESS, retVal); auto function = [&]() { while (!startEnqueueProcess) ; cl_int fRetVal; auto queue = clCreateCommandQueue(context, deviceId, 0, &fRetVal); EXPECT_EQ(CL_SUCCESS, fRetVal); EXPECT_NE(nullptr, queue); for (int i = 0; i < iterationCount; i++) { fRetVal = clEnqueueWriteBuffer(queue, buffer0, false, 0, bufferSize, data, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); fRetVal = clEnqueueNDRangeKernel(queue, kernel, workDim, gws, gwsSize, lws, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); } fRetVal = clFinish(queue); EXPECT_EQ(CL_SUCCESS, fRetVal); fRetVal = clReleaseCommandQueue(queue); EXPECT_EQ(CL_SUCCESS, fRetVal); }; std::vector<std::thread> threads; for (auto thread = 0; thread < threadCount; thread++) { threads.push_back(std::thread(function)); } startEnqueueProcess = true; for (auto &thread : threads) { thread.join(); } retVal = clReleaseMemObject(buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseMemObject(buffer1); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseKernel(kernel); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseProgram(program); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseContext(context); EXPECT_EQ(CL_SUCCESS, retVal); } HWTEST_F(EnqueueKernelTest, givenBcsEnabledAndQueuePerThreadWhenHalfQueuesEnqueueWriteBufferAndSecondHalfEnqueueNDRangeKernelInLoopThenIsNoRace) { DebugManagerStateRestore debugRestorer; DebugManager.flags.ForceCsrLockInBcsEnqueueOnlyForGpgpuSubmission.set(1); HardwareInfo hwInfo = *pDevice->executionEnvironment->rootDeviceEnvironments[0]->getMutableHardwareInfo(); hwInfo.capabilityTable.blitterOperationsSupported = true; REQUIRE_FULL_BLITTER_OR_SKIP(*pDevice->executionEnvironment->rootDeviceEnvironments[0]); std::atomic<bool> startEnqueueProcess(false); auto iterationCount = 40; const auto threadCount = 10; constexpr size_t n = 256; unsigned int data[n] = {}; constexpr size_t bufferSize = n * sizeof(unsigned int); size_t gws[3] = {1, 0, 0}; size_t gwsSize[3] = {n, 1, 1}; size_t lws[3] = {1, 1, 1}; cl_uint workDim = 1; KernelBinaryHelper kbHelper("CopyBuffer_simd16", false); std::string testFile; testFile.append(clFiles); testFile.append("CopyBuffer_simd16.cl"); size_t sourceSize = 0; auto pSource = loadDataFromFile(testFile.c_str(), sourceSize); EXPECT_NE(0u, sourceSize); EXPECT_NE(nullptr, pSource); MockClDevice mockClDevice{MockDevice::createWithExecutionEnvironment<MockDevice>(&hwInfo, pDevice->executionEnvironment, 0)}; const cl_device_id deviceId = &mockClDevice; auto context = clCreateContext(nullptr, 1, &deviceId, nullptr, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, context); const char *sources[1] = {pSource.get()}; auto program = clCreateProgramWithSource( context, 1, sources, &sourceSize, &retVal); ASSERT_NE(nullptr, program); retVal = clBuildProgram( program, 1, &deviceId, nullptr, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, retVal); auto kernel = clCreateKernel(program, "CopyBuffer", &retVal); ASSERT_NE(nullptr, kernel); EXPECT_EQ(CL_SUCCESS, retVal); cl_mem_flags flags = CL_MEM_READ_WRITE; auto buffer0 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); auto buffer1 = clCreateBuffer(context, flags, bufferSize, nullptr, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 0, sizeof(cl_mem), &buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clSetKernelArg(kernel, 1, sizeof(cl_mem), &buffer1); EXPECT_EQ(CL_SUCCESS, retVal); std::vector<std::thread::id> threadsIds; auto functionEnqueueWriteBuffer = [&]() { while (!startEnqueueProcess) ; cl_int fRetVal; auto queue = clCreateCommandQueue(context, deviceId, 0, &fRetVal); EXPECT_EQ(CL_SUCCESS, fRetVal); EXPECT_NE(nullptr, queue); for (int i = 0; i < iterationCount; i++) { fRetVal = clEnqueueWriteBuffer(queue, buffer0, false, 0, bufferSize, data, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); } fRetVal = clFinish(queue); EXPECT_EQ(CL_SUCCESS, fRetVal); EXPECT_TRUE(NEO::castToObject<MockCommandQueueHw<FamilyType>>(queue)->bcsInitialized); fRetVal = clReleaseCommandQueue(queue); EXPECT_EQ(CL_SUCCESS, fRetVal); }; auto functionEnqueueNDRangeKernel = [&]() { while (!startEnqueueProcess) ; cl_int fRetVal; auto queue = clCreateCommandQueue(context, deviceId, 0, &fRetVal); EXPECT_EQ(CL_SUCCESS, fRetVal); EXPECT_NE(nullptr, queue); for (int i = 0; i < iterationCount; i++) { fRetVal = clEnqueueNDRangeKernel(queue, kernel, workDim, gws, gwsSize, lws, 0, nullptr, nullptr); EXPECT_EQ(CL_SUCCESS, fRetVal); } fRetVal = clFinish(queue); EXPECT_EQ(CL_SUCCESS, fRetVal); EXPECT_TRUE(NEO::castToObject<MockCommandQueueHw<FamilyType>>(queue)->bcsInitialized); fRetVal = clReleaseCommandQueue(queue); EXPECT_EQ(CL_SUCCESS, fRetVal); }; std::vector<std::thread> threads; for (auto thread = 0; thread < threadCount; thread++) { if (thread < threadCount / 2) { threads.push_back(std::thread(functionEnqueueNDRangeKernel)); } else { threads.push_back(std::thread(functionEnqueueWriteBuffer)); } } startEnqueueProcess = true; for (auto &thread : threads) { thread.join(); } retVal = clReleaseMemObject(buffer0); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseMemObject(buffer1); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseKernel(kernel); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseProgram(program); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clReleaseContext(context); EXPECT_EQ(CL_SUCCESS, retVal); }
6cb1e80a2241e503213c2aa7ddc7533d10011cc2
54560d42aab27bd862b353d975659cf59411ec87
/Z2170P/SRC/DRIVERS/PM/DLL/pmdisplay.cpp
7cd72c92087fa0c71e82291fb7fcaabde5000105
[]
no_license
zizilala/projects_wince_BB
306a5c0e33e0b4e11faef61224335c0bd3086e4c
4d7b5717a424354dd6d38a52f9fcb3efa712a906
refs/heads/master
2020-05-17T23:01:14.292063
2013-08-09T09:59:49
2013-08-09T09:59:49
11,998,092
2
0
null
null
null
null
UTF-8
C++
false
false
9,612
cpp
pmdisplay.cpp
// All rights reserved ADENEO EMBEDDED 2010 // // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES. // // // This module implements the APIs the power manager uses to send power // requests to display devices. It's defined in the MDD, but OEMs can // override it or remove it from their image by not referencing // gDisplayInterface in their code -- that will keep it from being pulled // in by the linker. // #include <pmimpl.h> #include <wingdi.h> // disable PREFAST warning for use of EXCEPTION_EXECUTE_HANDLER #pragma warning (disable: 6320) typedef HDC (WINAPI *PFN_CreateDCW)(LPCWSTR, LPCWSTR , LPCWSTR , CONST DEVMODEW *); typedef BOOL (WINAPI *PFN_DeleteDC)(HDC); typedef int (WINAPI *PFN_ExtEscape)(HDC, int, int, LPCSTR, int, LPSTR); // global function pointers static PFN_CreateDCW gpfnCreateDCW = NULL; static PFN_DeleteDC gpfnDeleteDC = NULL; static PFN_ExtEscape gpfnExtEscape = NULL; static HANDLE ghevGwesAPISetReady = NULL; static BOOL gfGwesReady = FALSE; // This routine arranges for initialization of the API used to communicate // with devices of this class. It may be called more than once. If // successful it returns TRUE. Otherwise it returns FALSE. static BOOL InitDisplayDeviceInterface(VOID) { BOOL fOk = FALSE; #ifndef SHIP_BUILD SETFNAME(_T("InitDisplayDeviceInterface")); #endif if(gpfnCreateDCW == NULL) { HMODULE hmCore = (HMODULE) LoadLibrary(_T("coredll.dll")); PMLOGMSG(ZONE_WARN && hmCore == NULL, (_T("%s: LoadLibrary() failed %d\r\n"), pszFname, GetLastError())); if(hmCore != NULL) { // get procedure addresses gpfnCreateDCW = (PFN_CreateDCW) GetProcAddress(hmCore, _T("CreateDCW")); gpfnDeleteDC = (PFN_DeleteDC) GetProcAddress(hmCore, _T("DeleteDC")); gpfnExtEscape = (PFN_ExtEscape) GetProcAddress(hmCore, _T("ExtEscape")); if(gpfnCreateDCW == NULL || gpfnExtEscape == NULL || gpfnDeleteDC == NULL) { PMLOGMSG(ZONE_WARN, (_T("%s: can't get APIs: pfnCreateDCW 0x%08x, pfnDeleteDC 0x%08x, pfnExtEscape 0x%08x\r\n"), pszFname, gpfnCreateDCW, gpfnDeleteDC, gpfnExtEscape)); gpfnCreateDCW = NULL; gpfnDeleteDC = NULL; gpfnExtEscape = NULL; FreeLibrary(hmCore); } } } // do we have the endpoints we need? if(gpfnCreateDCW != NULL && gpfnExtEscape != NULL && gpfnDeleteDC != NULL) { // yes, get a handle to the GWES API set event if(ghevGwesAPISetReady == NULL) { ghevGwesAPISetReady = OpenEvent(EVENT_ALL_ACCESS, FALSE, _T("SYSTEM/GweApiSetReady")); DEBUGCHK(ghevGwesAPISetReady != NULL); // shouldn't happen since we have GWES APIs if(ghevGwesAPISetReady == NULL) { PMLOGMSG(ZONE_WARN, (_T("%s: can't open GWES API set ready event handle\r\n"), pszFname)); } } } // did we get all the resources we'll need to eventually access // devices of this type? if(ghevGwesAPISetReady != NULL) { // yes, return a good status fOk = TRUE; } PMLOGMSG(ZONE_INIT || (ZONE_WARN && !fOk), (_T("%s: returning %d\r\n"), pszFname, fOk)); return fOk; } // This routine opens a handle to a given device, or to the parent device // that is its proxy. The return value is the device's handle, or // INVALID_HANDLE_VALUE if there's an error. static HANDLE OpenDisplayDevice(PDEVICE_STATE pds) { #ifndef SHIP_BUILD SETFNAME(_T("OpenDisplayDevice")); #endif HANDLE hRet = NULL; // Get a handle to the client device. The client's name will generally be "DISPLAY" for // the default display, but it could be anything that CreateDC supports. PREFAST_DEBUGCHK(gpfnCreateDCW != NULL); PREFAST_DEBUGCHK(gpfnDeleteDC != NULL); PREFAST_DEBUGCHK(gpfnExtEscape != NULL); // Make sure GWES is ready for us to access this device if(!gfGwesReady) { // We need to wait for GWES to finish -- since this is happening // at boot time, we shouldn't have to wait for long. DEBUGCHK(ghevGwesAPISetReady != NULL); PMLOGMSG(ZONE_INIT, (_T("%s: waiting for GWES to initialize\r\n"), pszFname)); DWORD dwStatus = WaitForSingleObject(ghevGwesAPISetReady, INFINITE); if(dwStatus != WAIT_OBJECT_0) { PMLOGMSG(ZONE_WARN, (_T("%s: WaitForSingleObject() returned %d (error %d) on GWES ready event\r\n"), pszFname, GetLastError())); } else { PMLOGMSG(ZONE_INIT, (_T("%s: GWES API sets are ready\r\n"), pszFname)); // we don't need to access the event, but keep the handle value non-NULL // in case more than one display registers itself CloseHandle(ghevGwesAPISetReady); gfGwesReady = TRUE; } } if(gfGwesReady) { hRet = gpfnCreateDCW(pds->pszName, NULL, NULL, NULL); if(hRet == NULL) { PMLOGMSG(ZONE_WARN || ZONE_IOCTL, (_T("%s: CreateDC('%s') failed %d (0x%08x)\r\n"), pszFname, pds->pszName, GetLastError(), GetLastError())); hRet = INVALID_HANDLE_VALUE; } else { // determine whether the display driver really supports the PM IOCTLs DWORD dwIoctl[] = { IOCTL_POWER_CAPABILITIES, IOCTL_POWER_SET, IOCTL_POWER_GET }; int i; for(i = 0; i < dim(dwIoctl); i++) { if(gpfnExtEscape((HDC) hRet, QUERYESCSUPPORT, sizeof(dwIoctl[i]), (LPCSTR) &dwIoctl[i], 0, NULL) <= 0) { break; } } if(i < dim(dwIoctl)) { PMLOGMSG(ZONE_WARN, (_T("%s: '%s' doesn't support all power manager control codes\r\n"), pszFname, pds->pszName)); gpfnDeleteDC((HDC) hRet); hRet = INVALID_HANDLE_VALUE; } } } PMLOGMSG(ZONE_DEVICE || ZONE_IOCTL, (_T("%s: handle to '%s' is 0x%08x\r\n"), \ pszFname, pds->pszName, hRet)); return hRet; } // This routine closes a handle opened with OpenDisplayDevice(). It returns TRUE // if successful, FALSE if there's a problem. static BOOL CloseDisplayDevice(HANDLE hDevice) { #ifndef SHIP_BUILD SETFNAME(_T("CloseDisplayDevice")); #endif DEBUGCHK(gpfnCreateDCW != NULL); DEBUGCHK(gpfnDeleteDC != NULL); DEBUGCHK(gpfnExtEscape != NULL); DEBUGCHK(hDevice != NULL && hDevice != INVALID_HANDLE_VALUE); DEBUGCHK(gfGwesReady); PMLOGMSG(ZONE_DEVICE || ZONE_IOCTL, (_T("%s: closing 0x%08x\r\n"), pszFname, hDevice)); BOOL fOk = gpfnDeleteDC((HDC) hDevice); PMLOGMSG(!fOk && (ZONE_WARN || ZONE_IOCTL), (_T("%s: DeleteDC(0x%08x) failed %d (0x%08x)\r\n"), pszFname, hDevice, GetLastError(), GetLastError())); return fOk; } // This routine issues a request to a device. It returns TRUE if successful, // FALSE if there's a problem. static BOOL RequestDisplayDevice(HANDLE hDevice, DWORD dwRequest, LPVOID pInBuf, DWORD dwInSize, LPVOID pOutBuf, DWORD dwOutSize, LPDWORD pdwBytesRet) { BOOL fOk = FALSE; int iStatus; #ifndef SHIP_BUILD SETFNAME(_T("RequestDisplayDevice")); #endif DEBUGCHK(gpfnCreateDCW != NULL); PREFAST_DEBUGCHK(gpfnDeleteDC != NULL); PREFAST_DEBUGCHK(gpfnExtEscape != NULL); DEBUGCHK(hDevice != NULL && hDevice != INVALID_HANDLE_VALUE); DEBUGCHK(gfGwesReady); __try { PMLOGMSG(ZONE_IOCTL, (_T("%s: calling ExtEscape(0x%08x) w/ request %d ('%s')\r\n"), pszFname, hDevice, dwRequest, dwRequest == IOCTL_POWER_CAPABILITIES ? _T("IOCTL_POWER_CAPABILITIES") : dwRequest == IOCTL_POWER_GET ? _T("IOCTL_POWER_GET") : dwRequest == IOCTL_POWER_SET ? _T("IOCTL_POWER_SET") : dwRequest == IOCTL_POWER_QUERY ? _T("IOCTL_POWER_QUERY") : dwRequest == IOCTL_REGISTER_POWER_RELATIONSHIP ? _T("IOCTL_REGISTER_POWER_RELATIONSHIP") : _T("<UNKNOWN>"))); iStatus = gpfnExtEscape((HDC) hDevice, dwRequest, dwInSize, (LPCSTR) pInBuf, dwOutSize, (LPSTR) pOutBuf); if(iStatus > 0) { fOk = TRUE; if(pdwBytesRet != NULL) { // need to fill this in with something *pdwBytesRet = dwOutSize; } } } __except(EXCEPTION_EXECUTE_HANDLER) { PMLOGMSG(ZONE_WARN || ZONE_IOCTL, (_T("%s: exception in DeviceIoControl(%d)\r\n"), pszFname, dwRequest)); fOk = FALSE; } PMLOGMSG(!fOk && (ZONE_WARN || ZONE_IOCTL), (_T("%s: DeviceIoControl(%d) to 0x%08x failed %d (0x%08x)\r\n"), pszFname, dwRequest, hDevice, GetLastError(), GetLastError())); return fOk; } // create a data structure to encapsulate this interface EXTERN_C DEVICE_INTERFACE gDisplayInterface = { InitDisplayDeviceInterface, OpenDisplayDevice, CloseDisplayDevice, RequestDisplayDevice };
3a34bc8e2b2f314e20ddda79edcea780c0531e7c
2e359b413caee4746e931e01807c279eeea18dca
/2481. Minimum Cuts to Divide a Circle.cpp
d096303c34d0b59f7349be9216656eec81099a27
[]
no_license
fsq/leetcode
3a8826a11df21f8675ad1df3632d74bbbd758b71
70ea4138caaa48cc99bb6e6436afa8bcce370db3
refs/heads/master
2023-09-01T20:30:51.433499
2023-08-31T03:12:30
2023-08-31T03:12:30
117,914,925
7
3
null
null
null
null
UTF-8
C++
false
false
123
cpp
2481. Minimum Cuts to Divide a Circle.cpp
class Solution { public: int numberOfCuts(int n) { if (n==1) return 0; return (n&1) ? n : n/2; } };
cf00e98d07aa9ccd3c238bb714dc30f1dcdd930e
309fceba389acdb74c4de9570bfc7c43427372df
/Project2010/Bishamon/include/bm3/core/policy/Transform/bm3_policy_Transform_SwitchResource.h
c9071079844ae772ad27ff31d51204dc3f6cf052
[]
no_license
Mooliecool/DemiseOfDemon
29a6f329b4133310d92777a6de591e9b37beea94
f02f7c68d30953ddcea2fa637a8ac8f7c53fc8b9
refs/heads/master
2020-07-16T06:07:48.382009
2017-06-08T04:21:48
2017-06-08T04:21:48
null
0
0
null
null
null
null
IBM852
C++
false
false
2,524
h
bm3_policy_Transform_SwitchResource.h
#ifndef BM3_SDK_INC_BM3_CORE_TRANSFORM_BM3_POLICY_TRANSFORM_SWITCHRESOURCE_H #define BM3_SDK_INC_BM3_CORE_TRANSFORM_BM3_POLICY_TRANSFORM_SWITCHRESOURCE_H #include "../../bm3_Const.h" #include "../../bm3_CoreType.h" namespace bm3{ BM3_BEGIN_PLATFORM_NAMESPACE class DrawInfo; namespace policy{ namespace impl{ /// @brief Transform_SwitchResourceâNâëâX class Transform_SwitchResource{ public: template<typename ResourceType> static BM3_FORCEINLINE void Switch(const ResourceType &res, const ResourceType & /*old_res*/, ml::random &random, ml::vector3d &left_top, ml::vector3d &right_top, ml::vector3d &left_bottom, ml::vector3d &right_bottom){ // switch(res.Deformation_Basic_TransformType()){ // case TransformTypeConst_Constant: switch(res.Deformation_Basic_TransformType()){ case TransformTypeConst_Constant: Transform_Constant::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_Curve: Transform_Curve::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_Vertex: Transform_Vertex::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_MAX: case TransformTypeConst_FORCE32: break; } /* break; case TransformTypeConst_Curve: switch(res.Deformation_Basic_TransformType()){ case TransformTypeConst_Constant: Transform_Constant::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_Curve: Transform_Curve::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_Vertex: Transform_Vertex::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; } break; case TransformTypeConst_Vertex: switch(res.Deformation_Basic_TransformType()){ case TransformTypeConst_Constant: Transform_Constant::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_Curve: Transform_Curve::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; case TransformTypeConst_Vertex: Transform_Vertex::Initialize( res, random, left_top, right_top, left_bottom, right_bottom); break; } break; */ // } } }; } // namespace impl } // namespace policy BM3_END_PLATFORM_NAMESPACE } // namespace bm3 #endif // #ifndef BM3_SDK_INC_BM3_CORE_TRANSFORM_BM3_POLICY_TRANSFORM_SWITCHRESOURCE_H
71ddd7ad9e20290dade2396d4388d6f223511113
cb1a7da63be4dfdfced9be4cb82ce892de4ce09b
/src/modules/px4_simulink_app/MW_uORB_Read.cpp
fcd0dd1284c4138098108496804685933b2dae17
[ "BSD-3-Clause" ]
permissive
MatDias97/Firmware-FST
b266eeabffd57f4914af1b667a3a46dd7f166a45
27c7b83aebbb16715c1eac813a85fd25c317eae2
refs/heads/master
2022-01-07T22:49:06.138318
2019-06-05T08:39:02
2019-06-05T08:39:02
190,356,951
0
0
null
null
null
null
UTF-8
C++
false
false
1,913
cpp
MW_uORB_Read.cpp
/* Copyright 2018 The MathWorks, Inc. */ #include "nuttxinitialize.h" #include "MW_PX4_TaskControl.h" #include "MW_uORB_Read.h" #define DEBUG 0 void uORB_read_initialize(orb_metadata_t* orbData, pollfd_t* eventStructObj, double sampleTime) { int fd = orb_subscribe(orbData); eventStructObj->fd = fd; eventStructObj->events = POLLIN; orb_set_interval(fd, sampleTime); #if DEBUG PX4_INFO("* Subscribed to topic: %s (fd = %d)*\n", orbData->o_name, fd); #endif } boolean_T uORB_read_step(orb_metadata_t* orbData, pollfd_t* eventStructObj, void* busData, boolean_T blockingMode, double blockingTimeout) { boolean_T updated = 0; if (blockingMode) { int poll_ret = px4_poll(eventStructObj, 1, blockingTimeout); static int error_counter = 0; if (poll_ret == 0) { #if DEBUG PX4_ERR("Got no data within %.9lf second", blockingTimeout / 1000.0); #endif } else if (poll_ret < 0) { if (error_counter < 10 || error_counter % 500 == 0) { /* use a counter to prevent flooding and slowing the system down */ #if DEBUG PX4_ERR("ERROR return value from poll(): %d", poll_ret); #endif } error_counter++; } else { if (eventStructObj->revents & POLLIN) { orb_copy(orbData, eventStructObj->fd, busData); updated = 1 ; } } } else { bool isUpdated = false; orb_check(eventStructObj->fd, &isUpdated); if (isUpdated) { orb_copy(orbData, eventStructObj->fd, busData); } updated = isUpdated?1:0; } return updated; } void uORB_read_terminate(const pollfd_t* eventStructObj) { orb_unsubscribe(eventStructObj->fd); }
001db46183a16d059bb803a04e0f587102d7d654
e9f4a4b5b191fe8163ea1f4f211e241069b2c237
/src/moving_det/include/real_time_scanline.h
b10447d1b44036cce3760d3365a48fc2468411af
[]
no_license
wine3603/motion_detection
c2b066721c96f3e2f83e5bd2acf16922e1803e74
6a7dbc2b10b225417c0fc07e047d382808a10771
refs/heads/master
2020-09-14T05:58:42.217237
2016-09-20T06:27:59
2016-09-20T06:27:59
66,825,635
2
1
null
null
null
null
UTF-8
C++
false
false
3,594
h
real_time_scanline.h
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 2016 05 01 @ the Univ. of Tokyo % Tianwei Zhang % file: real_time_scanline.h %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifndef REAL_TIME_SCANLINE_H #define REAL_TIME_SCANLINE_H #include<math.h> #include<time.h> #include<ros/ros.h> #include<iostream> #include<pcl/point_types.h> #include<pcl/common/time.h> #include<pcl/pcl_base.h> #include<pcl/point_cloud.h> #include<pcl/common/eigen.h> #include<pcl/io/pcd_io.h> #include<pcl/console/parse.h> #include<pcl/filters/filter.h> #include<pcl_ros/point_cloud.h> #include<pcl_ros/transforms.h> #include<sensor_msgs/PointCloud2.h> #include<sensor_msgs/LaserScan.h> #include<sensor_msgs/Imu.h> #include<std_msgs/Float64.h> #include<tf/transform_listener.h> #include<tf/transform_broadcaster.h> #include<tf/transform_datatypes.h> #include<dynamixel_msgs/JointState.h> #include<nav_msgs/Odometry.h> #include<visualization_msgs/Marker.h> //#include<list> using namespace Eigen; namespace region_growing{ typedef pcl::PointXYZI PointT; typedef pcl::PointCloud<PointT> PointCloudT; typedef struct {PointT point_s; size_t index_s; PointT point_e; size_t index_e; size_t height;} split_point; typedef std::vector <split_point> split_line; typedef std::vector <split_line> split_image; typedef struct { float RMS; size_t size; //number of line segs //Eigen::Vector3f n; split_line lines; Vector3f n; float dis;} Plane;//save planes para typedef std::vector <Plane> Planes; static split_image image_helper; /////save plane seg candidant static Plane patch; ////save plane maps // static split_image patch_map; ////plane parameters d and n(vector) static size_t min_size = 5; /// min seeding line distance and length ///plane fitting threshod static float theta_grow = 0.03; static float theta_seed = 0.02; // static PointCloudT plane_cloud; static float RMS; // static Plane plane; static Planes planes; static int patch_no, patchmap_no, comtru_no, extend_, seeds_; class region_grow { public: bool prepare (split_image &image) ; split_image grow(split_image &image_vec); PointCloudT get_normals(); split_image merge_plane(); inline float sq(float x) {return x * x;} private: ////get data from split pt struct split_point get_data(split_line::iterator &itr); ///comp if a b are coplanar bool compare(split_line::iterator & a, split_line::iterator &b); /////compute plane formular A*m = b /2016/02/16 bool coplanar_or_not(split_line::iterator &c); bool coplanar_or_not(split_line::iterator &a,split_line::iterator &b,split_line::iterator &c); //////add a b to same plane candidante void add_into_patch(split_line::iterator &a); ////comput plane formular, return vec_m, n is nor(m), d is reciprocal(m), input is the point cloud of query pt bool plane_formular(PointCloudT &sigma); bool recom_plane(PointCloudT &sigma); float det(PointT &a, PointT &b, PointT &c); void extend (split_line::iterator &itr); void seeding (); void make_patch(split_line::iterator &a,split_line::iterator &b, split_line::iterator &c, float &RMS, Vector3f &n, float &d); bool a_is_in_patch(split_line::iterator &a); PointT minus ( PointT &a, PointT &b); ///martrix product 3x3 return in R1 float mar_mul_R1(PointT &n_3, PointT &b_3 ); public: // split_image::iterator extend_line; split_image::iterator query_line; split_line::iterator query_pt_itr; // split_line::iterator extend_pt_itr; }; } #endif
73879b06a4570a10cdcf3ab2093d4dbca20ac361
00aea0af71ea42d3fc98f78da4252aa832a25e51
/Solace/SolaceRun/DrawablePath.cpp
21006539822a704c1d77091ebcb4226034816b29
[]
no_license
tectronics/dysnomia
adfe2dcc5162a35c8650e530fa26938b8ae2f8ec
a496d4044e5e2f01c121d608dac088b95b988619
refs/heads/master
2018-01-11T15:15:21.764562
2012-10-12T00:12:01
2012-10-12T00:12:01
49,559,357
0
0
null
null
null
null
UTF-8
C++
false
false
12,960
cpp
DrawablePath.cpp
#include "DrawablePath.h" DrawablePath::DrawablePath( ISceneNode *node ) : node( node ), totalPathNodes( 500 ), currentPathNode( 0 ), targetPathNode( 0 ), flyAngle( 360 ), currentDistance( 0 ), distanceBetween( 450 ), drawing( false ), closing( false ) { initPath(); } DrawablePath::~DrawablePath() { // cursor->remove(); destroyPath(); } void DrawablePath::initPath() { cursor = new BillboardButton( "../images/square.png", dimension2d<f32>( 300, 300 ) ); // cursor = IRRLICHT->scene->addCubeSceneNode( 150 ); // cursor->setMaterialFlag( EMF_LIGHTING, false ); cursor->setVisible( false ); addTask( cursor ); for( int i = 0; i < totalPathNodes; i++ ) { BillboardButton *button = new BillboardButton( "../images/square.png", dimension2d<f32>( 200, 200 ) ); button->setVisible( false ); button->setTimes( 0.25, 0.25 ); pathNodes.push_back( button ); addPausedTask( button ); } closeSequence = new Sequence( false ); addPausedTask( closeSequence ); resetPath(); } Status DrawablePath::resetPath() { drawing = false; pathPositions.clear(); for( int i = 0; i < (int)pathNodes.size(); i++ ) { pathNodes[ i ]->setVisible( false ); pathNodes[ i ]->getBillboard()->setColor( SColor( 255, 255, 255, 255 ) ); } currentPathNode = 0; targetPathNode = 0; previousPosition = node->getPosition(); currentDistance = 0; //float turnLength = 100.0f; maxDistance = 200000; /* float timeToMax = turnLength;//node->maxSpeed = time * ( node->currentSpeed + node->acceleration ); //should be time to get to max speed at current acceleration if ( node->currentSpeed >= node->maxSpeed ) { maxDistance = node->currentSpeed * turnLength; } else if ( timeToMax < turnLength ) { maxDistance = node->currentSpeed * timeToMax + 0.5f * node->acceleration * timeToMax * timeToMax; maxDistance += ( turnLength - timeToMax ) * node->maxSpeed; } else { maxDistance = node->currentSpeed * turnLength + 0.5f * node->acceleration * turnLength * turnLength; } //LOG( node->currentSpeed, " < ", node->maxSpeed, " -- ", timeToMax, ", ", maxDistance, "\n" ); if ( node->currentSpeed >= node->maxSpeed ) { maxDistance = node->maxSpeed * turnLength; }*/ return FINISHED; } Status DrawablePath::destroyPath() { pathPositions.clear(); while( (int)pathNodes.size() > 0 ) { //pathNodes.back()->remove(); pathNodes.pop_back(); } return FINISHED; } void DrawablePath::closePath() { closeSequence->killAllTasks(); closing = true; for( int i = currentPathNode - 1; i >= 0; i-- ) { if( pathNodes[ i ]->isClosed() ) { break; } closeSequence->addTask( new SequenceTask( boost::bind( &BillboardButton::close, pathNodes[ i ] ) ) ); closeSequence->addTask( new SequenceTask( boost::bind( &DrawablePath::unpauseTask, this, pathNodes[ i ] ) ) ); if ( i != currentPathNode - 1 ) { closeSequence->addDelay( 0.015f ); } } closeSequence->addDelay( 0.0125f ); closeSequence->addTask( new SequenceTask( boost::bind( &DrawablePath::resetPath, this ) ) ); closeSequence->setVariable( &closing, false ); closeSequence->start(); unpauseTask( closeSequence ); } void DrawablePath::closePathUpto( int target ) { closeSequence->killAllTasks(); closing = true; for( int i = target - 1; i >= 0; i-- ) { closeSequence->addTask( new SequenceTask( boost::bind( &BillboardButton::close, pathNodes[ i ] ) ) ); closeSequence->addTask( new SequenceTask( boost::bind( &DrawablePath::unpauseTask, this, pathNodes[ i ] ) ) ); if ( i != target - 1 ) { closeSequence->addDelay( 0.025f ); } } closeSequence->addDelay( 0.125f ); closeSequence->setVariable( &closing, false ); closeSequence->start(); unpauseTask( closeSequence ); } void DrawablePath::setPath( vector<vector3df> &path, bool showPath ) { resetPath(); pathPositions.assign( path.begin(), path.end() ); for( int i = 0; i < (int)pathPositions.size(); i++ ) { pathNodes[ i ]->setPosition( pathPositions[ i ] ); pathNodes[ i ]->setVisible( showPath ); if ( showPath ) { //pathNodes[ i ]->setMaterialFlag( EMF_LIGHTING, false ); } } } vector3df DrawablePath::nextTarget() { return pathPositions[ targetPathNode ]; } Status DrawablePath::update( float elapsed ) { runTasks( elapsed ); if ( drawing && currentPathNode < totalPathNodes /*&& currentDistance < maxDistance*/ ) { vector3df shipPosition = node->getPosition(); line3d<f32> ray = IRRLICHT->scene->getSceneCollisionManager()->getRayFromScreenCoordinates( EVENTS->mousePosition ); triangle3df galacticPlane( shipPosition + vector3df( -1000, 0, 1000 ), shipPosition + vector3df( 0, 0, -1000 ), shipPosition + vector3df( 1000, 0, 1000 ) ); vector3df closestPoint; galacticPlane.getIntersectionOfPlaneWithLine( ray.start, ray.getVector(), closestPoint ); //if distance is too great calculate positions inbetween //if turn angle is too great, reverse a point, and try that one, keep trying and recalculating points inbetween vector3df rotation = ( closestPoint - previousPosition ).getHorizontalAngle(); int size = (int)pathPositions.size(); vector3df heading; if ( size == 0 ) { heading = rotation; } else if ( size > 1 ) { heading = ( pathPositions[ size - 1 ] - pathPositions[ size - 2 ] ).getHorizontalAngle(); } float angle = 0; if ( rotation.Y > heading.Y ) { angle = ( rotation - heading ).Y; } else { angle = ( heading - rotation ).Y; } float distance = closestPoint.getDistanceFrom( previousPosition ); if ( distance < distanceBetween && ( angle < flyAngle || angle > 360 - flyAngle ) ) { cursor->setPosition( closestPoint ); } else if ( distance > distanceBetween && distance < distanceBetween + 50 && ( angle < flyAngle || angle > 360 - flyAngle ) ) { currentDistance += distance; pathPositions.push_back( closestPoint ); pathNodes[ currentPathNode ]->setPosition( closestPoint ); pathNodes[ currentPathNode ]->setVisible( true ); pathNodes[ currentPathNode ]->open(); unpauseTask( pathNodes[ currentPathNode ] ); previousPosition = closestPoint; currentPathNode++; } else if ( distance > distanceBetween ) { int pointsBetween = (int)distance / distanceBetween; if ( pointsBetween > 1 ) { for( int i = 0; i < pointsBetween && currentPathNode < totalPathNodes; i++ ) { vector3df pointPosition = previousPosition + ( closestPoint - previousPosition ).normalize() * (f32)distanceBetween; vector3df pointDirection = ( pointPosition - previousPosition ).getHorizontalAngle(); angle = 0; if ( pointDirection.Y > heading.Y ) { angle = ( pointDirection - heading ).Y; } else { angle = ( heading - pointDirection ).Y; } if ( angle < flyAngle || angle > 360 - flyAngle ) { float pointDistance = pointPosition.getDistanceFrom( previousPosition ); if ( currentDistance + pointDistance < maxDistance ) { currentDistance += pointDistance; pathPositions.push_back( pointPosition ); pathNodes[ currentPathNode ]->setPosition( pointPosition ); pathNodes[ currentPathNode ]->setVisible( true ); pathNodes[ currentPathNode ]->open(); unpauseTask( pathNodes[ currentPathNode ] ); previousPosition = pointPosition; currentPathNode++; } } } } else { vector3df cursorPosition = previousPosition + ( closestPoint - previousPosition ).normalize() * 500; vector3df cursorDirection = ( cursorPosition - previousPosition ).getHorizontalAngle(); angle = 0; if ( cursorDirection.Y > heading.Y ) { angle = ( cursorDirection - heading ).Y; } else { angle = ( heading - cursorDirection ).Y; } if ( angle < flyAngle || angle > 360 - flyAngle ) { cursor->setPosition( cursorPosition ); } } } } return RUNNING; } void DrawablePath::setVisibleShipPath( int node, int points ) { int start = 0; if ( node - points > 0 ) { start = node - points; } for( int i = 0; i < (int)pathPositions.size(); i++ ) { pathNodes[ i ]->setVisible( false ); } int color = 0; for( int i = start; i < node + points; i++ ) { pathNodes[ i ]->setVisible( true ); //pathNodes[ i ]->getMaterial( 0 ).EmissiveColor = SColor( 255, 110 + color, color, 0 ); color += 20; } } vector3df DrawablePath::getClosestPoint( vector3df position ) { int size = (int)pathPositions.size(); if ( size == 0 ) { return pathPositions[ 0 ]; } else if ( size > 1 ) { line3d<f32> line = line3d<f32>( pathPositions[ 0 ], pathPositions[ 1 ] ); vector3df closestPoint = line.getClosestPoint( position ); vector3df newPoint; float closestDistance = position.getDistanceFrom( closestPoint ); float newDistance = 0; for( int i = 1; i < size; i++ ) { line.setLine( pathPositions[ i - 1 ], pathPositions[ i ] ); newPoint = line.getClosestPoint( position ); newDistance = position.getDistanceFrom( newPoint ); if ( newDistance < closestDistance ) { closestDistance = newDistance; closestPoint = newPoint; } } return closestPoint; } return position; } int DrawablePath::getClosestNode( vector3df position ) { int size = (int)pathPositions.size(); if ( size > 0 ) { float closestDistance = pathPositions[ 0 ].getDistanceFrom( position ); float newDistance = 0; int target = 0; for( int i = 1; i < size; i++ ) { newDistance = pathPositions[ i ].getDistanceFrom( position ); if ( newDistance <= closestDistance ) { closestDistance = newDistance; target = i; } } return target; } return -1; } std::vector<vector3df> DrawablePath::getPathBetween( vector3df start, vector3df end ) { std::vector<vector3df> path; int startNode = getClosestNode( start ); int endNode = getClosestNode( end ); path.push_back( getClosestPoint( start ) ); if ( startNode != -1 && endNode != -1 ) { if ( startNode < endNode ) { for( int i = startNode; i <= endNode; i++ ) { pathNodes[ i ]->setVisible( false ); path.push_back( pathPositions[ i ] ); } } else { for( int i = startNode; i >= endNode; i-- ) { pathNodes[ i ]->setVisible( false ); path.push_back( pathPositions[ i ] ); } } } path.push_back( getClosestPoint( end ) ); return path; } std::vector<vector3df> DrawablePath::getPathBetween( int start, int end ) { std::vector<vector3df> path; if ( start != -1 && end != -1 ) { if ( start < end ) { for( int i = start; i <= end; i++ ) { path.push_back( pathPositions[ i ] ); } } else { for( int i = start; i >= end; i-- ) { path.push_back( pathPositions[ i ] ); } } } return path; } void DrawablePath::setPathVisibilityBetween( bool visible, int start, int end ) { if ( start != -1 && end != -1 ) { if ( start < end ) { for( int i = start; i <= end; i++ ) { pathNodes[ i ]->setVisible( visible ); } } else { for( int i = start; i >= end; i-- ) { pathNodes[ i ]->setVisible( visible ); } } } } void DrawablePath::scalePathColorBetween( int start, int end, SColor startColor, SColor endColor ) { if ( start != -1 && end != -1 ) { int j = 0; if ( start < end ) { for( int i = start; i <= end; i++ ) { pathNodes[ i ]->getBillboard()->setColor( startColor.getInterpolated( endColor, (float)i / end ) ); } } else { for( int i = start; i >= end; i-- ) { pathNodes[ i ]->getBillboard()->setColor( startColor.getInterpolated( endColor, (float)i / start ) ); } } } } BillboardButton *DrawablePath::getPathBillboard( int node ) { if ( node >= 0 && node < (int)pathPositions.size() ) { return pathNodes[ node ]; } return 0; } vector3df DrawablePath::getPathNode( int node ) { if ( node >= 0 && node < (int)pathPositions.size() ) { return pathPositions[ node ]; } return vector3df(); } float DrawablePath::getDistanceFrom( vector3df start, vector3df end ) { float distance = 0; int startNode = getClosestNode( start ); int endNode = getClosestNode( end ); if ( startNode != -1 && endNode != -1 ) { if ( startNode < endNode ) { for( int i = startNode; i < endNode; i++ ) { distance += pathPositions[ i ].getDistanceFrom( pathPositions[ i + 1 ] ); } } else { for( int i = startNode; i > endNode; i-- ) { distance += pathPositions[ i ].getDistanceFrom( pathPositions[ i - 1 ] ); } } } return distance; }
9e6358b9485939dffa55596ef41eb5c7181c6fbb
a6a479d266622bc5f2558fa11992069e3d4827db
/BMS_2/Demodulator.h
63419c62191e977cf402a073be5d1e546ab03f73
[]
no_license
Klarksonnek/FIT
1c8831b3af40a191576b10144a829ed6d9d0027d
c6a041aa8305cda244f8ac691479004789f8fe06
refs/heads/master
2021-03-27T09:49:30.377896
2019-07-04T15:03:08
2019-07-04T15:03:08
107,965,893
0
0
null
null
null
null
UTF-8
C++
false
false
740
h
Demodulator.h
#pragma once #include <string> #include <vector> #include "sndfile.hh" /** * Class containing information and methods needed * for demodulation. */ class Demodulator { public: Demodulator(); void demodulation(); void setInputWavFile(const std::string &file); private: std::string makeTxtFile(); void setEps(); void loadSamples(SndfileHandle &input); bool checkSyncSeq(unsigned int *numOfSamples); unsigned int determineNumOfSample(); std::string determinePhase(unsigned int count, unsigned int startPosition); std::string obtainPhase(unsigned int position); void demodulate(unsigned int numOfSamples); std::string m_inputFile; int m_format; int m_eps; std::vector<int> m_samples; std::vector<std::string> m_bits; };
7f9437e80c58e9e437ef8f3fa730e5176bb58bce
5f67658f61d03a786005752583077a40b42d03b1
/UtilityClasses/MemoryPipe.h
eed0cb5c5db1f6ab8ee4ea08c49df3ba83b4e1b5
[]
no_license
newtonresearch/newton-framework
d0e5c23dfdc5394e0c94e7e1b7de756eac4ed212
f922bb3ac508c295b155baa0d4dc7c7982b9e2a2
refs/heads/master
2022-06-26T21:20:18.121059
2022-06-01T17:39:47
2022-06-01T17:39:47
31,951,762
22
7
null
null
null
null
UTF-8
C++
false
false
671
h
MemoryPipe.h
/* File: MemoryPipe.h Contains: External interface to the Newton ROM memory buffer pipe class. Written by: Newton Research Group, 2010. */ #if !defined(__MEMORYPIPE_H) #define __MEMORYPIPE_H #include "BufferPipe.h" /*---------------------------------------------------------------------- C M e m o r y P i p e ----------------------------------------------------------------------*/ class CMemoryPipe : public CBufferPipe { public: CMemoryPipe(); virtual ~CMemoryPipe(); // pipe interface void flushRead(void); void flushWrite(void); void reset(void); void overflow(); void underflow(long, bool&); private: }; #endif /* __MEMORYPIPE_H */
5bd26f0cce4647c3e01d87cc424da9cf106b3c66
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_4534_squid-3.5.27.cpp
ba7c0429c202a085263c39d9c2d09b223f0927ea
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,238
cpp
squid_repos_function_4534_squid-3.5.27.cpp
void Ssl::Helper::Init() { assert(ssl_crtd == NULL); // we need to start ssl_crtd only if some port(s) need to bump SSL *and* generate certificates // TODO: generate host certificates for SNI enabled accel ports bool found = false; for (AnyP::PortCfgPointer s = HttpPortList; !found && s != NULL; s = s->next) found = s->flags.tunnelSslBumping && s->generateHostCertificates; for (AnyP::PortCfgPointer s = HttpsPortList; !found && s != NULL; s = s->next) found = s->flags.tunnelSslBumping && s->generateHostCertificates; if (!found) return; ssl_crtd = new helper("ssl_crtd"); ssl_crtd->childs.updateLimits(Ssl::TheConfig.ssl_crtdChildren); ssl_crtd->ipc_type = IPC_STREAM; // The crtd messages may contain the eol ('\n') character. We are // going to use the '\1' char as the end-of-message mark. ssl_crtd->eom = '\1'; assert(ssl_crtd->cmdline == NULL); { char *tmp = xstrdup(Ssl::TheConfig.ssl_crtd); char *tmp_begin = tmp; char *token = NULL; while ((token = strwordtok(NULL, &tmp))) { wordlistAdd(&ssl_crtd->cmdline, token); } safe_free(tmp_begin); } helperOpenServers(ssl_crtd); }
012fa942e0010e8100b93404b846df8b6c7c9402
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5636311922769920_1/C++/pps789/2016QD_Fractiles.cpp
514b8e2e0c355cbaac337b6debe5214afb7557d2
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
891
cpp
2016QD_Fractiles.cpp
#include<iostream> #include<algorithm> #include<vector> using namespace std; typedef long long ll; ll gen(const vector<ll>& v, int K){ ll ret = 0; for (ll c : v){ ret *= K; ret += c; } return ret + 1; } int main(){ freopen("large.in", "r", stdin); freopen("large.out", "w", stdout); int T; cin >> T; for (int tc = 1; tc <= T; tc++){ cout << "Case #" << tc << ": "; int K, C, S; cin >> K >> C >> S; if (S*C < K) cout << "IMPOSSIBLE" << endl; else{ vector<ll> v; for (int i = 0; i < S*C; i++){ v.push_back(i%K); } vector<ll> ans; for (int i = 0; i < S; i++){ ans.push_back(gen(vector<ll>(v.begin() + (i*C), v.begin() + (i*C + C)), K)); } sort(ans.begin(), ans.end()); ans.erase(unique(ans.begin(), ans.end()), ans.end()); for (ll a : ans) cout << a << ' '; cout << endl; } } }
2c573ada93017d8e7122fa404fcda5597892dd03
da741c443fd6bdf19dfcfc1193ce198aff66505c
/Funciones/Ejercicio12.cpp
cb818d1be286b9c2c3a05ac473f7b2bfe0d01980
[]
no_license
AbrahamFB/Programaci-n-en-C-B-sico---Intermedio---Avanzado-
d5dad53a83f844d93dc3fe772c6ecb80d1fd04de
9f3c312c39a60dc7b2ca437d24cc7607055f40b0
refs/heads/master
2022-07-19T19:15:19.342667
2020-05-17T01:53:53
2020-05-17T01:53:53
264,562,774
0
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
Ejercicio12.cpp
#include <iostream> #include <conio.h> using namespace std; int vec[100], tam; void pedirDatos(){ cout << "Ingresa el numero de elementos del vector:" << endl; cin >> tam; for(int i = 0; i < tam; i++){ cout << i+1 << ". Ingresa un numero:" << endl; cin >> vec[i]; } } void verificarOrden(int vec[], int tam){ char band = 'F'; int i = 0; while((band == 'F') && (i < tam-1)){ if(vec[i] > vec[i+1]){ band = 'V'; } i++; } if(band == 'F'){ cout << "El arreglo esta ordenado ascendentemente" << endl; } else{ cout << "El arreglo no esta ordenado ascendentemente" << endl; } } int main(){ pedirDatos(); verificarOrden(vec, tam); getch(); return 0; }
d8f824522c44341592d326a5c0fc518067a01028
92489191d6b7c829dfc134e0aa2e65ec4d31abcb
/Handel/chooseapersondialog.cpp
fa067da9a4f17b81bf57de86e6654ba9691fec8b
[]
no_license
hergerr/POProject
f0d22ac2dbb767377cee28114b8062402b9b4b03
3c51dc6627529d50d86d08c3bf8be5740e95073d
refs/heads/master
2020-03-06T23:02:58.014703
2018-04-11T14:27:53
2018-04-11T14:27:53
127,121,918
0
0
null
null
null
null
UTF-8
C++
false
false
762
cpp
chooseapersondialog.cpp
#include "chooseapersondialog.h" #include "ui_chooseapersondialog.h" #include <QMessageBox> ChooseAPersonDialog::ChooseAPersonDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ChooseAPersonDialog) { ui->setupUi(this); } ChooseAPersonDialog::~ChooseAPersonDialog() { delete ui; } //definicja metody oblugijacej wybor fachowca lub handlowca void ChooseAPersonDialog::on_okPushButton_clicked() { //decyzja ktore okno zostanie otwarte if(ui->professionalRadioButton->isChecked()){ hide(); professionalDialog = new ProfessionalDialog(this); professionalDialog->show(); } else { hide(); traderDialog = new TraderDialog(this); traderDialog->show(); } }
084b3a596e0395d41998914824e8dc7335e05717
60aa54a3969a506a275ac033471f3d15b8c4ae68
/event/OurEvent.cpp
0e6de610feafdd7a078fa4dae4cb022b3ef7fb1b
[]
no_license
IRETD/TestSystemServer
5e9cf9bb7a3d6825523dfe52d435fca3d8876cdb
78ec19579c363d99dae9ecd36f01483d05335fcc
refs/heads/master
2021-09-10T02:36:31.703918
2018-03-20T18:47:24
2018-03-20T18:47:24
126,066,409
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
OurEvent.cpp
#include "event/OurEvent.h" OurEvent::OurEvent() : QEvent( ( Type ) eventType ) { } void OurEvent::setRequest( Request *pRequest ) { m_pRequest = pRequest; } Request *OurEvent::getRequest() { return m_pRequest; }
58e40e648f3699e54869b4a7065fea09900cdfa8
da34178acfaf567a7faa0fb10ea9d50c8ddf0d98
/usacogift1.cpp
72eef0f0fa35d2340a1f0fbc1fab06ab8f13182e
[]
no_license
csgregorian/competition
d81890b940a8912aefd3c724760bef421dcea38e
bd87ca6b104ede1d36b8d3fc475c96694078ebfb
refs/heads/master
2020-05-31T03:56:51.174808
2015-10-15T19:44:17
2015-10-15T19:44:17
24,005,009
0
0
null
null
null
null
UTF-8
C++
false
false
894
cpp
usacogift1.cpp
/* ID: csgregorian PROG: gift1 LANG: C++ */ #include <bits/stdc++.h> using namespace std; int main() { ofstream fout("gift1.out"); ifstream fin("gift1.in"); int np; fin >> np; map<string, int> people; string people1[np+1]; for (int i = 0; i < np; i++) { string person; fin >> person; people1[i] = person; people[person] = 0; } for (int i = 0; i < np; i++) { string giver; fin >> giver; int total; fin >> total; // cout << giver << " has " << total << endl; int receivers; fin >> receivers; for (int x = 0; x < receivers; x++) { string receiver; fin >> receiver; // cout << giver << " gives " << total/receivers << " to " << receiver << endl; people[receiver] += total / receivers; people[giver] -= total / receivers; } } for (int i = 0; i < np; i++) { fout << people1[i] << " " << people[people1[i]] << endl; } return 0; }
5b2416ff9a3f3514bebfe8150990a1f74d2112b8
c5f3f36394557254c105ba229ced551851e29712
/source/oishii/Endian.hxx
19e46b397427e611dc0a8d0e6e685525e9422a2d
[ "LicenseRef-scancode-public-domain" ]
permissive
riidefi/RiiStudio
78a21b002f639863fb7c4d18608efac39107a098
22d35de909cfce53e49415c693eb2ba65fde2859
refs/heads/master
2023-08-22T17:51:38.192281
2023-08-21T19:48:29
2023-08-21T19:48:29
206,892,230
85
21
null
2023-09-06T20:14:21
2019-09-07T00:16:23
C++
UTF-8
C++
false
false
2,410
hxx
Endian.hxx
#pragma once #include <bit> #include <stdint.h> namespace oishii { template <typename T1, typename T2> union enumCastHelper { // Switch above means this always is instantiated // static_assert(sizeof(T1) == sizeof(T2), "Sizes of types must match."); T1 _t; T2 _u; enumCastHelper(T1 _) : _t(_) {} }; #if OISHII_PLATFORM_LE == 1 #define MAKE_BE32(x) std::byteswap(x) #define MAKE_LE32(x) x #else #define MAKE_BE32(x) x #define MAKE_LE32(x) std::byteswap(x) #endif //! @brief Fast endian swapping. //! //! @tparam T Type of value to swap. Must be sized 1, 2, or 4 //! //! @return T endian swapped. template <typename T> inline T swapEndian(T v) { static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4, "T must of size 1, 2, or 4"); switch (sizeof(T)) { case 4: { enumCastHelper<T, uint32_t> tmp(v); tmp._u = std::byteswap(tmp._u); return tmp._t; } case 2: { enumCastHelper<T, uint16_t> tmp(v); tmp._u = std::byteswap(tmp._u); return tmp._t; } case 1: { return v; } } // Never reached return T{}; } enum class EndianSelect { Current, // Grab current endian // Explicitly use endian Big, Little }; template <uint32_t size> struct integral_of_equal_size; template <> struct integral_of_equal_size<1> { using type = uint8_t; }; template <> struct integral_of_equal_size<2> { using type = uint16_t; }; template <> struct integral_of_equal_size<4> { using type = uint32_t; }; template <typename T> using integral_of_equal_size_t = typename integral_of_equal_size<sizeof(T)>::type; template <typename T, EndianSelect E = EndianSelect::Current> inline T endianDecode(T val, std::endian fileEndian) { if constexpr (E == EndianSelect::Big) { return std::endian::native != std::endian::big ? swapEndian<T>(val) : val; } else if constexpr (E == EndianSelect::Little) { return std::endian::native != std::endian::little ? swapEndian<T>(val) : val; } else if constexpr (E == EndianSelect::Current) { return std::endian::native != fileEndian ? swapEndian<T>(val) : val; } return val; } constexpr uint32_t roundDown(uint32_t in, uint32_t align) { return align ? in & ~(align - 1) : in; } constexpr uint32_t roundUp(uint32_t in, uint32_t align) { return align ? roundDown(in + (align - 1), align) : in; } } // namespace oishii
bae6ed9bba26e1333bbbbb979e04904d0b0b806c
eee583c09ba2ce603a8295749e02fcba3a54d0c6
/Chipset/keyboard.cpp
115b4188159a822269dca8161bfa1abb6a13c02a
[]
no_license
zyq8709/tower-pc
04966a619a09d60128ea46a6d99f3e8d18be5439
60231139835ecf5410bf0036d2a7414108bc993b
refs/heads/master
2021-01-17T23:39:02.129443
2013-02-01T14:28:47
2013-02-05T07:17:44
59,875,726
0
1
null
2016-05-28T03:38:01
2016-05-28T03:38:00
null
UTF-8
C++
false
false
11,317
cpp
keyboard.cpp
#include "stdafx.h" #include "keyboard.h" #include "Piston\String.h" #include "Piston\Win32\ui.h" #include "keyboard_codes.h" namespace Tower { namespace Chipset { int8 KBC::last_command; int8 KBC::port61_toggle; int8 KBC::chip_ram[0x20]; int8 KBC::out_bfr[16]; // status byte int8 KBC::out_bfr_len; int8 KBC::system_flag; int8 KBC::in_bfr_is_command; int8 KBC::kbd_switched_off; int8 KBC::transmit_timeout; int8 KBC::receive_timeout; int8 KBC::even_parity; // command byte int8 KBC::enable_irq1; int8 KBC::enable_irq12; int8 KBC::system_flag_2; int8 KBC::ignore_kbd_lock; int8 KBC::kbd_clock_off; int8 KBC::aux_clock_off; int8 KBC::translation_on; int8 Keyboard::last_command; int8 Keyboard::scancode_set; int8 Keyboard::LEDs; TOWER_EXPORT void tower_KeyDown(int32 keyInfo) { Keyboard::tower_KeyEvent(keyInfo); } TOWER_EXPORT void tower_KeyUp(int32 keyInfo) { Keyboard::tower_KeyEvent(keyInfo); } void Keyboard::tower_KeyEvent(int32 keyInfo) { ZSSERT((int16)keyInfo <= 0xff); int16 vkey; if((int16)keyInfo == Piston::Win32::VK_SHIFT) vkey = (keyInfo & (1 << 24) ? Piston::Win32::VK_SHIFT_L : Piston::Win32::VK_SHIFT_R); else if((int16)keyInfo == Piston::Win32::VK_CTRL) vkey = (keyInfo & (1 << 24) ? Piston::Win32::VK_CTRL_L : Piston::Win32::VK_CTRL_R); else if((int16)keyInfo == Piston::Win32::VK_ALT) vkey = (keyInfo & (1 << 24) ? Piston::Win32::VK_ALT_L : Piston::Win32::VK_ALT_R); else vkey = (int16)keyInfo; ZSSERT(Scancodes[vkey][0].make[0] != 0); plug->Log(plug_persist, LOG_DEBUG, L"[KBC] keyInfo = 0x" + Piston::String::Renderhex(keyInfo).PadLeft(8, L'0') + L": v-key 0x" + Piston::String::Renderhex(vkey).PadLeft(2, L'0') + (keyInfo & (1 << 31) ? L" down" : L" up")); if(keyInfo & (1 << 31)) KBC::FromKbd((int8 *)Scancodes[vkey][scancode_set].make); else KBC::FromKbd((int8 *)Scancodes[vkey][scancode_set].brake); } int8 KBC::Buffer::Read() { int8 ret; if(out_bfr_len > 0) { ret = out_bfr[0]; for(int i = 1; i < out_bfr_len; ++i) out_bfr[i - 1] = out_bfr[i]; --out_bfr_len; plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Read 0x" + Piston::String::Renderhex(ret).PadLeft(2, L'0') + L" from buffer (remaining bytes: " + Piston::String::Render(out_bfr_len) + L")"); } else { ret = 0; plug->Log(plug_persist, LOG_ERROR, L"[KBC] Buffer read while buffer is empty! Returning 0x" + Piston::String::Renderhex(ret).PadLeft(2, L'0')); } return ret; } void KBC::Buffer::WriteRaw(int8 byte) { ZSSERT(out_bfr_len < sizeof(out_bfr)); out_bfr[out_bfr_len++] = byte; } void KBC::Buffer::Write(int8 byte) { ZSSERT(out_bfr_len < sizeof(out_bfr)); if(translation_on) { ZSSERT(byte != 0xf0); out_bfr[out_bfr_len++] = translate[byte]; plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Wrote 0x" + Piston::String::Renderhex(out_bfr[out_bfr_len - 1]).PadLeft(2, L'0') + L" into buffer (was 0x" + Piston::String::Renderhex(byte).PadLeft(2, L'0') + L" before translation)"); } else { out_bfr[out_bfr_len++] = byte; plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Wrote 0x" + Piston::String::Renderhex(out_bfr[out_bfr_len - 1]).PadLeft(2, L'0') + L" into buffer"); } } void KBC::Buffer::Write(int8 *bytes) { for(; *bytes; ++bytes) { if(out_bfr_len >= sizeof(out_bfr)) { plug->Log(plug_persist, LOG_ERROR, L"[KBC] No room for keyboard data in buffer; ignoring."); return; } if(translation_on) { if(*bytes == 0xf0) { // convert prefix ZSSERT(*(bytes + 1)); out_bfr[out_bfr_len++] = translate[*++bytes] | 0x80; plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Wrote 0x" + Piston::String::Renderhex(out_bfr[out_bfr_len - 1]).PadLeft(2, L'0') + L" into buffer (was 0xf0 0x" + Piston::String::Renderhex(*bytes).PadLeft(2, L'0') + L" before translation)"); } else { out_bfr[out_bfr_len++] = translate[*bytes]; plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Wrote 0x" + Piston::String::Renderhex(out_bfr[out_bfr_len - 1]).PadLeft(2, L'0') + L" into buffer (was 0x" + Piston::String::Renderhex(*bytes).PadLeft(2, L'0') + L" before translation)"); } } else { out_bfr[out_bfr_len++] = *bytes; plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Wrote 0x" + Piston::String::Renderhex(out_bfr[out_bfr_len - 1]).PadLeft(2, L'0') + L" into buffer"); } } } void KBC::FromKbd(int8 *sequence) { if(kbd_clock_off || (kbd_switched_off & !ignore_kbd_lock)) return; Buffer::Write(sequence); if(enable_irq1) plug_dev->RaiseIRQ(1); } void KBC::FromKbd(int8 byte) { if(kbd_clock_off || (kbd_switched_off & !ignore_kbd_lock)) return; Buffer::Write(byte); if(enable_irq1) plug_dev->RaiseIRQ(1); } void Keyboard::FromKbc(int8 byte) { switch(last_command) { // expecting a write from previous command? case 0xed: // set LEDs LEDs = byte; plug->StatusItems.SetText(plug_status_scrl, (LEDs & 1 ? L"SCRL on" : L"SCRL off")); plug->StatusItems.SetText(plug_status_num, (LEDs & 2 ? L"NUM on" : L"NUM off")); plug->StatusItems.SetText(plug_status_caps, (LEDs & 4 ? L"CAPS on" : L"CAPS off")); SendACK(); last_command = 0; break; case 0xf0: // set scancode set if(byte == 0) { int8 resp[3] = {0xfa, scancode_set + 1, 0}; Send(resp); } else if(byte <= 3) { plug->Log(plug_persist, LOG_INFO, L"[KBD] Scancode set " + Piston::String::Render(byte) + L" selected"); scancode_set = byte - 1; } else { plug->Log(plug_persist, LOG_ERROR, L"[KBD] Invalid scancode set 0x" + Piston::String::Renderhex(byte).PadLeft(2, L'0') + L" requested"); ZSSERT(0); SendERR(); } last_command = 0; break; default: switch(last_command = byte) { case 0x05: // ??? (win 3.0 setup) plug->Log(plug_persist, LOG_INFO, L"[KBD] Received unknown byte 0x05, ERR'd"); SendERR(); break; case 0xed: // set LEDs SendACK(); // ack break; case 0xee: // diagnostic echo Send(0xee); break; case 0xf0: // select scancode set SendACK(); break; case 0xf2: // read keyboard ID Send((int8 *)"\xFA\x83\xAB"); // FA=ack, 83AB=id break; case 0xf4: // enable keyboard plug->Log(plug_persist, LOG_INFO, L"[KBD] Keyboard enabled"); SendACK(); break; case 0xf5: // disable keyboard plug->Log(plug_persist, LOG_INFO, L"[KBD] Keyboard disabled"); SendACK(); break; default: plug->Log(plug_persist, LOG_ERROR, L"[KBD] Unknown byte received from controller: 0x" + Piston::String::Renderhex(byte).PadLeft(2, L'0')); ZSSERT(0); SendERR(); } } } int8 TOWER_CC KBC::Read8(int16 port) { switch(port) { case 0x60: return Buffer::Read(); case 0x61: // ignore for now port61_toggle ^= 0x10; return port61_toggle; case 0x64: plug->Log(plug_persist, LOG_TRACE, L"[KBC] Read status byte, out_bfr_len = " + Piston::String::Render(out_bfr_len)); return (out_bfr_len ? 1 : 0) | (system_flag << 2) | (in_bfr_is_command << 3) | (kbd_switched_off << 4) | (transmit_timeout << 5) | (receive_timeout << 6) | (even_parity << 7); } plug->Log(plug_persist, LOG_WARNING, L"[KBC] Invalid 8-bit read from port 0x" + Piston::String::Render(port).PadLeft(4, L'0')); ZSSERT(0); return 0xff; } int16 TOWER_CC KBC::Read16(int16 port) { plug->Log(plug_persist, LOG_WARNING, L"[KBC] Invalid 16-bit read from port 0x" + Piston::String::Render(port).PadLeft(4, L'0')); ZSSERT(0); return 0xffff; } int32 TOWER_CC KBC::Read32(int16 port) { plug->Log(plug_persist, LOG_WARNING, L"[KBC] Invalid 32-bit read from port 0x" + Piston::String::Render(port).PadLeft(4, L'0')); ZSSERT(0); return 0xffffffff; } void TOWER_CC KBC::Write8(int16 port, int8 value) { switch(port) { case 0x60: // write command byte in_bfr_is_command = 0; switch(last_command) { case 0x60: enable_irq1 = value & 1 ? 1 : 0; enable_irq12 = value & 2 ? 1 : 0; system_flag = value & 4 ? 1 : 0; ignore_kbd_lock = value & 8 ? 1 : 0; kbd_clock_off = value & 16 ? 1 : 0; aux_clock_off = value & 32 ? 1 : 0; translation_on = value & 64 ? 1 : 0; ZSSERT((value & 0x84) == 0); // unknown bytes last_command = 0; break; case 0xd1: // write output port ZSSERT(value & 1); // system reset line MUST BE 1 (active low) if(value & 2) plug->Log(plug_persist, LOG_WARNING, L"[KBC] Enable A20: unimplemented."); last_command = 0; break; default: Keyboard::FromKbc(value); } break; case 0x61: // (?) ignore for now plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Write of 0x" + Piston::String::Renderhex(value) + L" to port 0x61"); break; case 0x64: in_bfr_is_command = 1; switch(last_command = value) { case 0x20: // read command byte Buffer::WriteRaw( (enable_irq1 << 0) | (enable_irq12 << 1) | (system_flag_2 << 2) | (ignore_kbd_lock << 3) | (kbd_clock_off << 4) | (aux_clock_off << 5) | (translation_on << 6)); break; case 0x60: // write command byte to port 0x60 break; case 0xa7: // disable aux if(!aux_clock_off) plug->Log(plug_persist, LOG_INFO, L"[KBC] Aux clock disabled"); aux_clock_off = 1; break; case 0xa8: // enable aux if(aux_clock_off) plug->Log(plug_persist, LOG_INFO, L"[KBC] Aux clock enabled"); aux_clock_off = 0; break; case 0xad: // disable keyboard if(!kbd_clock_off) plug->Log(plug_persist, LOG_INFO, L"[KBC] Keyboard clock disabled"); kbd_clock_off = 1; break; case 0xae: // enable keyboard if(kbd_clock_off) plug->Log(plug_persist, LOG_INFO, L"[KBC] Keyboard clock enabled"); kbd_clock_off = 0; break; case 0xd1: // write output port to port 0x60 break; case 0xf0: case 0xf1: case 0xf2: case 0xf3: case 0xf4: case 0xf5: case 0xf6: case 0xf7: case 0xf8: case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff: // pulse low bits low if(!(value & 1)) { plug->Log(plug_persist, LOG_INFO, L"[KBC] Output port bits " + Piston::String::Render(~value & 15) + L" pulsed low; system reset."); ZSSERT(0); // put reset code in? } else { plug->Log(plug_persist, LOG_INFO, L"[KBC] Output port bits " + Piston::String::Render(~value & 15) + L" pulsed low"); } break; default: plug->Log(plug_persist, LOG_DEBUG, L"[KBC] Write of 0x" + Piston::String::Renderhex(value) + L" to port 0x64"); ZSSERT(0); } break; default: plug->Log(plug_persist, LOG_WARNING, L"[KBC] Invalid 8-bit write of " + Piston::String::Render(value).PadLeft(2, L'0') + L" to port 0x" + Piston::String::Render(port).PadLeft(4, L'0')); ZSSERT(0); } } void TOWER_CC KBC::Write16(int16 port, int16 value) { plug->Log(plug_persist, LOG_WARNING, L"[KBC] Invalid 16-bit write of " + Piston::String::Render(value).PadLeft(4, L'0') + L" to port 0x" + Piston::String::Render(port).PadLeft(4, L'0')); ZSSERT(0); } void TOWER_CC KBC::Write32(int16 port, int32 value) { plug->Log(plug_persist, LOG_WARNING, L"[KBC] Invalid 32-bit write of " + Piston::String::Render(value).PadLeft(8, L'0') + L" to port 0x" + Piston::String::Render(port).PadLeft(4, L'0')); ZSSERT(0); } }}
5f62287c0525d8160c7a7fb229835af316fc7673
73bd731e6e755378264edc7a7b5d16132d023b6a
/UVA/575 (skew binary).cpp
231a393ad2683ae48173531eee5565351107a970
[]
no_license
IHR57/Competitive-Programming
375e8112f7959ebeb2a1ed6a0613beec32ce84a5
5bc80359da3c0e5ada614a901abecbb6c8ce21a4
refs/heads/master
2023-01-24T01:33:02.672131
2023-01-22T14:34:31
2023-01-22T14:34:31
163,381,483
0
3
null
null
null
null
UTF-8
C++
false
false
538
cpp
575 (skew binary).cpp
#include <iostream> #include <math.h> #include <string.h> using namespace std; long int skewBinary(char *input) { int n; long int number=0; int len=strlen(input); for(int i=0; input[i]; i++){ n=input[i]-48; number+=n*(pow(2, len)-1); len--; } return number; } int main() { char str[1000]; int len, i; long int result; while(cin>>str){ if(strcmp(str, "0")==0) break; result=skewBinary(str); cout<<result<<endl; } return 0; }
7283c884b1a636f8881c109b32f4f016f769b162
8f5f758a83ebc26b57c06ef364d6a8fa59d91830
/src/classes/AllNothing.cpp
941bfc67bd53ceb0dea4014baf1529ecc265235b
[]
no_license
cdconn00/GamblerGame
8f40e6bd375bf29d5ed099e6b6e23e4eefc9f402
a9c74e153ab312ffd791d21e301be3d61662ae38
refs/heads/master
2022-11-28T07:10:14.427007
2018-12-31T17:13:33
2018-12-31T17:13:33
163,685,249
0
0
null
null
null
null
UTF-8
C++
false
false
1,601
cpp
AllNothing.cpp
/* * AllNothing.cpp * * Created on: Jun 19, 2018 * Author: cdcon */ #include "AllNothing.h" AllNothing::AllNothing() {numberpick = 0, tempnbr = 0;} void AllNothing::setup(Gambler& Player) { bool isvalid; std::cout << "Welcome to all or nothing! You wager a amount 0-100! \n"; std::cout << "We then print 16 numbers 0-100 if your number is not present \n"; std::cout << "You win that amount!"; while (!isvalid) // Logic to handle wager entry and ensure the player has enough credits { std::cout << "Please enter a valid wager amount: \n"; std::cin >> wager; if (wager <= Player.showcredits() && wager <= 100) isvalid = true; else std::cout << "Sorry, that wager amount isnt valid"; } play_game(Player); } void AllNothing::play_game(Gambler& Player) { int i = 0; bool win = true; srand(time(NULL)); for (i = 0; i < 17; i++) { numberpick = rand() % 100; std::cout << numberpick << " "; if (wager == numberpick) { win = false; } } if (win == true) game_won(Player); else game_lost(Player); } void AllNothing::game_won(Gambler& Player) { std::cout << "Congrats! You correctly guessed! \n"; std::cout << "You are awarded " << wager << " credits! \n"; Player.AddCredits(wager); } void AllNothing::game_lost(Gambler& Player) { std::cout << "Sorry! You have not guessed correctly.\n"; std::cout << "You are penalized " << wager << " credits." << std::endl; Player.RmvCredits(wager); if (Player.showcredits() <= 0) { Player.Bankrupt(); } }
7cb6224959da0cd6dabc9d5cdede5eda04550e4a
54d2eab607e20b2c58328eecb4ad9a3f055516c4
/spoj/(combinatorics)marbles.cpp
020d64373d3a9096478d7d4a461d9b1c390dc594
[]
no_license
pk2809/cp_alg
c9528b2d179dc72fe0c4ae0631b36c78e48946c2
dbd1a7f0c040fb4dd0c325d6e3ab8977511f69a8
refs/heads/master
2022-07-29T01:15:18.536661
2020-05-09T20:19:57
2020-05-09T20:19:57
256,322,739
0
0
null
null
null
null
UTF-8
C++
false
false
1,127
cpp
(combinatorics)marbles.cpp
/*Sun May 10 01:46:10 2020 This is written by @pk_2809*/ #include <bits/stdc++.h> #define ll long long int #define vi vector<int> #define vl vector<long long> #define fin(ar,k,n) for(int i=k;i<n;i++) cin>>ar[i] #define fout(ar,k,n) for(int i=k;i<n;i++) cout<<ar[i]<<' ' #define vs vector<string> #define mx INT_MAX #define mn INT_MIN #define all(z) z.begin(),z.end() #define mcc 1000000007 #define mcf 998244353 #define mi map<int,int> #define mem(a,n) memset(a,n,sizeof(a)) using namespace std; ll minl(ll a,ll b) {return (a<b)? a:b;} ll gcd(ll a,ll b) { return b ? gcd(b,a%b):a; } ll ncr(ll n,ll r) { ll p=1,k=1; r=minl(r,n-r); if (r==0) return 1; else { while (r) { p*=n; k*=r; ll m=gcd(p,k); p/=m; k/=m; n--;r--; } return p; } } void solve() { ll n,k; cin>>n>>k; cout<<ncr(n-1,n-k)<<endl; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); #endif ios_base::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--) solve(); return 0; }
b3f372a28f83c46759f08355f0d7f0327c36f160
9c001762d4571b0cf4c1209459b305876ee15b20
/ProFun Week4.1/Source.cpp
64fbb408e0d5fa4fb7b60bbdc17bf36ae8258a3e
[]
no_license
maimoke/ProFun-Week4.1
0b1595b5428c97fc0e70be7b4855154ce5bfc58e
a478d07d36bf1f90bccf750b84a8a1ecd0d76bba
refs/heads/master
2022-12-09T23:07:20.257101
2020-09-03T17:55:45
2020-09-03T17:55:45
292,642,252
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
Source.cpp
#include<stdio.h> int main() { float a; scanf_s("%f",&a); if (a < 0) printf("Please insert the number that is greater or equal zero"); else if (a >= 80) printf("A"); else if (a >= 70)printf("B"); else if (a >= 60)printf("C"); else if (a >= 50) printf("D"); else printf("F"); return 0; }
ab60211e4087a80b04085098a7d893553edcb0c1
c6114798112d8c4c6b7fd8e7c8dbf31d11301bf0
/TSOJ/timu1395.cpp
63ed399bb50992b77c96ddd26d4cab4ecfb34c07
[]
no_license
jiangtao1234ji/ACM-code
fb2b321d116a5f61b7771a8086862f886ed61935
b549bbdf0aae7214e840ab0e15f9e484c5494781
refs/heads/master
2020-04-16T02:58:47.307497
2019-03-10T05:53:00
2019-03-10T05:53:00
165,215,632
1
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
timu1395.cpp
#include<iostream> #include<algorithm> #include<vector> #include<string> using namespace std; vector<int> v; void permutation(int N) { if(v.size()==N) { for(int i = 0; i<N; i++) { cout<<v[i]; } cout<<endl; } for(int i = 1; i<=N; i++) { if(find(v.begin(),v.end(),i)==v.end()) { v.push_back(i); permutation(N); v.pop_back(); } } } int main() { int N; while(cin>>N) { permutation(N); } return 0; }
a508add71e3885fca18a47489dda68be070775d3
8799d3e93f6edb753d09616651067af2346e0016
/比赛/2019秦皇岛Camp/camp1/训练营1K.cpp
9eee0c970275effcda69787e09a69a29461e2db6
[]
no_license
StarPolygen/Code_Library
560b6c07af9f975e81efdeda60ce031b5dff3a22
a259f4e003817b317d4847222235edc09e4e5380
refs/heads/master
2021-07-13T06:18:09.796797
2020-07-24T13:03:11
2020-07-24T13:03:11
184,305,507
1
0
null
null
null
null
UTF-8
C++
false
false
1,602
cpp
训练营1K.cpp
#include <bits/stdc++.h> const int maxn = 4000300; using std::vector; struct edge{ bool operator <(const edge& edg) const{ return dis < edg.dis; } int from=0,to=0,dis=0; edge(int from,int to,int dis){ this->dis=dis; this->from=from; this->to=to; }; }; int father[maxn]; int find(int x); void unite(int x,int y); int main() { vector<edge> vecto; vecto.clear(); int n,m,ans; ans=0; scanf("%d%d", &n, &m); int sta[n+2]; for (int i = 0; i <=n;i++){ father[i] = i; } for(int i=0;i<=n;i++) sta[i]=0; for(int p=0;p<m;p++){ int x, y, w; scanf("%d%d%d", &x, &y, &w); vecto.push_back(edge(x, y, -w)); } std::sort(vecto.begin(), vecto.end()); for (int j=0;j<vecto.size();j++) { edge len=vecto[j]; int lll=find(len.from); int rrr=find(len.to); if(lll==rrr){ if(sta[lll]==0) { ans+=len.dis; sta[lll]=1; } } else{ if((sta[lll]==0&&sta[rrr]==1)||(sta[lll]==1&&sta[rrr]==0)){ ans+=len.dis; unite(len.from,len.to); sta[find(len.from)]=1; }else if(sta[lll]==0&&sta[rrr]==0){ ans+=len.dis; unite(len.from,len.to); sta[find(len.from)]=0; } } } printf("%d\n", -ans); } int find(int x){ if(x==father[x]) return x; return father[x] = find(father[x]); } void unite(int x,int y){ int l=find(x); int r=find(y); father[r] = l; }
fb5ac60ea63b4a9b861e5d82a0f1dd1d97a46b01
b07495b9d5b6761ea277f4d64e1ef9524a41e8b4
/Metin2OpenFileManager-d3v/LogHandler.cpp
ecd72570c5a4233a44fa6a3d6c34a8cf26dfa671
[]
no_license
cret91/metin2-open-file-manager
ed684e36b246670cd6842b8ed5e2109c33685d49
849acae3a5c2029f84a544624a3e4d4a996ab4ab
refs/heads/master
2021-01-10T13:16:07.258179
2013-08-20T13:16:56
2013-08-20T13:16:56
43,668,727
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
LogHandler.cpp
#include "LogHandler.h" void LogHandler::PrintMessage(char Message[],bool IsError) { if (!(Out = fopen("OFMLogs.txt","w+"))) { printf("[ERROR] Unable to write to the log file.\n"); _getch(); exit((int)Out); } char FinalMessage[500]; memset(FinalMessage,0,sizeof(FinalMessage)); if (!IsError) sprintf(FinalMessage,"[INFO] %s",Message); else sprintf(FinalMessage,"[ERROR] %s",Message); fwrite(Message,sizeof(char),strlen(Message),Out); fclose(Out); }
ce78bd6c2b62bc8164b6e818a6f0c2edcc4da538
6749c9b296682be2c7ecfbdd9ecc77bf04416086
/Player.hpp
d2efb5e3b7617d5c072c1d8263979b762f454111
[]
no_license
JViggiani/Game-Theory
59cd85ac57b6c9a9fa5c4ef2c8f362e11a1876e2
f93bc90fcaf556665c2faa7c26f18b706ff78a4d
refs/heads/master
2023-01-12T04:14:57.976205
2020-11-12T23:04:27
2020-11-12T23:04:27
302,991,816
0
0
null
null
null
null
UTF-8
C++
false
false
2,110
hpp
Player.hpp
#pragma once #include <memory> #include <string> #include <typeinfo> #include "Personality.hpp" #include "RoundResults.hpp" #include "eDecisionType.hpp" #include "ePlayerNumber.hpp" #include "ePersonalityType.hpp" namespace Core { //! This class is a wrapper Proxy around the polymorphic Personality pointer. Decisions should be delegated to the Personality. class Player { protected: //! Main constructor. /* Use the static templated create function */ Player(); public: /// Constructors and Destructors /// template <typename T> static Player create() { Player aPlayer; aPlayer._personality = std::make_unique<T>(); return aPlayer; }; //! Default destructor. ~Player() = default; //! Copy constructor Player(const Player& aPlayer); //! Default move constructor Player(Player&&) = default; /// Operators /// //! Default copy assignment Player& operator=(const Player& aPlayer); //! Default move assignment Player& operator=(const Player&& aPlayer) noexcept; /// Functions /// //Calls the polymorphic Personality makeDecision() function /* aMistakeChance is a int between 0 and 100 */ Data::eDecisionType makeDecision(const Data::GameResults& aDecisionData, const Data::ePlayerNumber& aPlayerNumber, unsigned int aMistakeChance); int getId() const { return _id; } Data::ePersonalityType getPersonalityType() const { return _personality->getPersonalityType(); } int getCumulativeReward() const { return _cumulativeReward; } void updateGameReward(const Data::GameResults& aGameResults, const Data::ePlayerNumber& aPlayerNumber); void resetGameReward(); private: /* This Personality makes the important decisions. It does not hold any data. This must be a pointer because Personality is abstract We want to be able to polymorphically use the correct personality child here Perhaps C++23 will have polymorphic_value<T> :( */ std::unique_ptr<Implementation::Personality> _personality; unsigned int _id; unsigned static int _idCounter; int _cumulativeReward; }; }
8a29e2a08e2e7f05ae8ab2ae39c88f1be40149d9
a0c4ed3070ddff4503acf0593e4722140ea68026
/source/NET/UI/COMMON/SRC/BLT/TESTAPPS/DIALOG.CXX
20cc9e7cdfd8b90fccbed07ef3033fab9ddaf2f0
[]
no_license
cjacker/windows.xp.whistler
a88e464c820fbfafa64fbc66c7f359bbc43038d7
9f43e5fef59b44e47ba1da8c2b4197f8be4d4bc8
refs/heads/master
2022-12-10T06:47:33.086704
2020-09-19T15:06:48
2020-09-19T15:06:48
299,932,617
0
1
null
2020-09-30T13:43:42
2020-09-30T13:43:41
null
UTF-8
C++
false
false
3,414
cxx
DIALOG.CXX
#include "tester.hxx" /**********************************************************\ NAME: DIALOG_OBJECT SYNOPSIS: Test the dialog package in the BLT. INTERFACE: DIALOG_OBJECT() - consturctor. PARENT: DIALOG_WINDOW_WITH_END HISTORY: terryk 29-1-2000 created \**********************************************************/ class DIALOG_OBJECT: public DIALOG_WINDOW_WITH_END { protected: virtual BOOL OnCommand( const CONTROL_EVENT & e ); SLN _slnOnCommand; SLT _sltOnOther; BOOL OnOK( void ); BOOL OnCancel( void ); public: DIALOG_OBJECT( TCHAR * pszResourceName, HWND hwndOwner ); }; /**********************************************************\ NAME: DIALOG_OBJECT::OnOK() SYNOPSIS: Disply the OK string if the user hits OK NOTES: Set the oncommand string to OK. HISTORY: terryk 3-14-2000 created \**********************************************************/ BOOL DIALOG_OBJECT::OnOK() { _slnOnCommand.SetText("OK"); return TRUE; } /**********************************************************\ NAME: DIALOG_OBJECT::OnCancel() SYNOPSIS: Set the display string to Cancel. NOTES: Set the onCommand string to cancel. HISTORY: terryk 3-14-2000 created \**********************************************************/ BOOL DIALOG_OBJECT::OnCancel() { _slnOnCommand.SetText("Cancel"); return TRUE; } /**********************************************************\ NAME: DIALOG_OBJECT::DIALOG_OBJECT SYNOPSIS: Use the dialog box to test the BLT DIALOG class. ENTRY: TCHAR * - resource name. HWND - the window handle for the window EXIT: NONE. NOTES: Create the DIALOG class object and set the variables. HISTORY: terryk 3-14-2000 created \**********************************************************/ DIALOG_OBJECT::DIALOG_OBJECT( TCHAR * pszResourceName, HWND hwndOwner ) : DIALOG_WINDOW_WITH_END( pszResourceName, hwndOwner ), _slnOnCommand( this, IDD_D_STATIC_1 ), _sltOnOther( this, IDD_D_STATIC_2 ) { _slnOnCommand.SetText( "NONE" ); _sltOnOther.SetText( "NONE" ); } /**********************************************************\ NAME: DIALOG_OBJECT::OnCommand SYNOPSIS: Set the display string if the input is other than OK and CANCEL ENTRY: CID - command id ULONG - lParam EXIT: NONE. NOTES: Dismiss if cid == IDD_END HISTORY: terryk 3-14-2000 created \**********************************************************/ BOOL DIALOG_OBJECT::OnCommand( const CONTROL_EVENT & e ) { switch (e.QueryWParam()) { default: _slnOnCommand.SetNum( e.QueryWParam() ); return (DIALOG_WINDOW_WITH_END::OnCommand( e )); } } /**********************************************************\ NAME: DIALOG_Tester SYNOPSIS: To test the DIALOG_OBJECT object ENTRY: HWND the window handle for the window EXIT: NONE. NOTES: It calls up the dialog box and do a Process call. It will wait until the user hits the END button. HISTORY: terryk 3-14-2000 created \**********************************************************/ void DIALOG_Tester(HWND hwnd) { DIALOG_OBJECT dialog_class( "D_DIALOG", hwnd ); dialog_class.Process(); }
6d2726852cc9d535ba9965651654d8b8bb62d737
a4e8150feea2a799c2a8d918b215c10192429f89
/src/plan.cpp
eac599262a61881c2f0b9f0efea0e19d1837352e
[]
no_license
sebastianstock/chimp_jni
2ad7d5e5a4288b4b74e8c013d651e133491a59a5
504eb1bff97397f0068a4268a5719796c63bb64e
refs/heads/master
2020-09-04T12:50:05.560005
2019-04-24T10:09:57
2019-04-24T10:09:57
219,736,392
1
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
plan.cpp
#include <chimp_jni/plan.hpp> namespace chimp_jni { std::ostream &operator<<(std::ostream &os, const Plan &plan) { os << "found plan? " << plan.found_plan << "\n"; os << "Actions:\n"; for (ChimpFluent fluent : plan.fluents) { os << fluent << "\n"; } os << "All fluents: \n"; for (ChimpFluent fluent : plan.all_fluents) { os << fluent << "\n"; } // os << "Constraints:\n"; // for (FluentConstraint con : plan.constraints) // { // os << con << "\n"; // } return os; } }
2162d0138dade8bf7b0ed6b019caf0713a59f4ec
5f43184e7afdb76e5b99ea6dfed9426db021442c
/minisql/BPlusTree.cpp
e102e0a4c7acf1fb68b4cb72f05a8d53ab3dadd3
[]
no_license
zzhyzzh/MiniSQL
68f8525c52d4c8a1498a865ef5cace2f2e2e2a3f
384f33e05a597b8594bdeb94ad25152821f2c561
refs/heads/master
2020-04-02T10:38:33.845783
2018-10-23T15:07:51
2018-10-23T15:07:51
154,348,044
0
0
null
null
null
null
GB18030
C++
false
false
25,213
cpp
BPlusTree.cpp
#include"BPlusTree.h" #include<iostream> using namespace std; extern BufferManager bufferManager; extern CatalogManager *catalogManager; BPlusTree::BPlusTree(Index indexInfo) { order = (BLOCK_SIZE - 12) / (indexInfo.length + 8) + 1; //计算B+树的度 myIndexInfo = indexInfo; leaf_least = ceil((order-1) / 2.0); nonleaf_least = ceil((order)/ 2.0 ) - 1; //cout << nonleaf_least << endl; //cout << order << endl; //myIndexInfo = indexInfo; } void BPlusTree::insert(string key, int blockOff, int offset) //key 注意扩展 { string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; Block *root = new Block; int blockNum; root = bufferManager.readBlock(fileName,0); //读取fileName中第一个block当作root的block; //cout << root->CBlock + 4 << endl; if (root->charNum == 0) //根节点为空 { string temp = "!0001"; temp += "fff"; temp += toLength(intToStr(blockOff),4); temp += toLength(intToStr(offset),4); temp += toLength(key,myIndexInfo.length); write(root, temp); //赋值给CBlock return; } blockNum = searchLeaf(key); //cout << blockNum << endl; Block *node = new Block; node = bufferManager.readBlock(fileName, blockNum); //读取叶节点 string info = node->CBlock; if (getValueNum(info.substr(1, 4)) < order - 1) insertInLeaf(node, key, blockOff, offset); else { Block *L1 = new Block; L1 = bufferManager.getBlankBlock(fileName); //读取一个空块 // Block *L2 = new Block; // L2 = bufferManager.getBlankBlock(fileName); //读取一个空块,L2临时存储 // strcpy(L2->CBlock, info.c_str()); string pn; if (info.substr(5,3) == "fff") { pn = ""; } else { pn = info.substr(node->charNum - 4, 4); } insertInLeaf(node, key, blockOff, offset); string tmpT = node->CBlock; int halfn = ceil((getValueNum(info.substr(1, 4)) + 1) / 2.0); string tmpL; tmpL = "!" + toLength(intToStr(halfn),4); tmpL += tmpT.substr(5, 3 + halfn*(8+myIndexInfo.length)); tmpL += toLength(intToStr(L1->blockNum), 4); write(node, tmpL); //复制前半个节点 int n = getValueNum(tmpT.substr(1, 4)); //value总数 string tmpL1; tmpL1 = "!" + toLength(intToStr(n-halfn), 4) + tmpT.substr(5,3); //保存父节点,此处还未初始化 tmpL1+= tmpT.substr(8 + halfn*(8 + myIndexInfo.length), (n - halfn)*(8 + myIndexInfo.length)); tmpL1 += pn; write(L1, tmpL1); string K1 = tmpL1.substr(16, myIndexInfo.length); catalogManager->addIndexBlockNum(myIndexInfo.value); //blockNum增加1 insertInParent(blockNum, L1->blockNum,K1); } } void BPlusTree::insertInParent(int blockNum, int blockNum1,string key) { int i; string info1, info2; string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; Block *root = new Block; root = bufferManager.readBlock(fileName, 0); //读取根块 if (root->blockNum == blockNum) //交换之前的节点和根节点 { Block *R = new Block; R = bufferManager.getBlankBlock(fileName); catalogManager->addIndexBlockNum(myIndexInfo.value); //blockNum增加1 int r = R->blockNum; Block *node1 = new Block; Block *node2 = new Block; node1 = bufferManager.readBlock(fileName,blockNum); node2 = bufferManager.readBlock(fileName,blockNum1); string info = "?0001fff" + toLength(intToStr(r),4) + key + toLength(intToStr(blockNum1), 4); //父节点可能需要更新,注意 R->blockNum = node1->blockNum; node1->blockNum = r; //交换block info1 = node1->CBlock; info2 = node2->CBlock; info1.replace(5, 3, toLength(intToStr(R->blockNum), 3)); //更新父节点字符,有争议,待定 info2.replace(5, 3, toLength(intToStr(R->blockNum), 3)); write(node1, info1); write(node2, info2); write(R, info); fatherUpdate(node1->blockNum); return; } else { Block *N0 = new Block; string nodeInfo; N0 = bufferManager.readBlock(fileName, blockNum); nodeInfo = N0->CBlock; int p = getValueNum(nodeInfo.substr(5,3)); //获取父节点 Block *PNode = new Block; PNode = bufferManager.readBlock(fileName, p); string pInfo = PNode->CBlock; if (getValueNum(pInfo.substr(1, 4)) < order - 1) //父节点可以插入 { int start; string temp = PNode->CBlock; int num = getValueNum(temp.substr(1, 4)); temp.replace(1, 4, toLength(intToStr(num+1), 4)); for (i = 0; i <= num; i++) // =号有争议 { start = 8 + (4 + myIndexInfo.length)*i; if (getValueNum(temp.substr(start, 4)) == blockNum) { string insert = key + toLength(intToStr(blockNum1), 4); temp.insert(start + 4, insert); write(PNode, temp); break; //注意,父节点未更新 } } Block *node1 = new Block; Block *node2 = new Block; node1 = bufferManager.readBlock(fileName,blockNum); node2 = bufferManager.readBlock(fileName,blockNum1); info1 = node1->CBlock; info2 = node2->CBlock; info1.replace(5, 3, toLength(intToStr(PNode->blockNum), 3)); //更新父节点字符,有争议,待定 info2.replace(5, 3, toLength(intToStr(PNode->blockNum), 3)); write(node1, info1); write(node2, info2); return; } else //父节点已满 { //Block *newBlock = new Block; //newBlock = bufferManager.getBlankBlock(fileName); //获得新的块 //strcpy(newBlock->CBlock, pInfo.c_str()); //string tmpT = newBlock->CBlock; string tmpT = pInfo; int num = getValueNum(tmpT.substr(1, 4)); int start, end; tmpT.replace(1, 4, toLength(intToStr(num+1), 4)); for (int i = 0; i<=num; i++) { //等号有争议 start = (4 + myIndexInfo.length)*i + 8; string insert = key + toLength(intToStr(blockNum1), 4); /*找到了匹配的块号*/ if (getValueNum(tmpT.substr(start, 4)) == blockNum) { tmpT.insert(start + 4, insert); break; } } PNode->CBlock = NULL; Block *P1 = new Block; P1 = bufferManager.getBlankBlock(fileName); //获取空块 catalogManager->addIndexBlockNum(myIndexInfo.value); //blockNum增加1 int pnum = P1->blockNum; /*copy 1 to n/2 from T to P*/ int halfn = ceil((order - 1) / 2.0); string tempP = "?" + toLength(intToStr(halfn), 4); tempP += tmpT.substr(5, 7 + halfn*(4 + myIndexInfo.length)); //父节点未更新 write(PNode, tempP); /*let K11=T.K n/2*/ fatherUpdate(PNode->blockNum); //更新父节点 string K11 = tmpT.substr(12 + halfn*(4 + myIndexInfo.length), myIndexInfo.length); /*copy n/2 +1 to n from T to P1*/ string tempP1 = "?" + toLength(intToStr(order-halfn-1), 4) + tmpT.substr(5,3); tempP1 += tmpT.substr(8 + (4+myIndexInfo.length)*(halfn + 1), (4 + myIndexInfo.length)*(order - halfn - 1)+4); //cout << tempP1 << endl; write(P1, tempP1); fatherUpdate(P1->blockNum); //更新父节点 insertInParent(PNode->blockNum, P1->blockNum, K11); //bufferManager.deleteBlock(fileName, P1->blockNum); return; } } } string BPlusTree::intToStr(int value) //待测,int 转 string { string temp; char ch; int i; while(value) { ch = value%10 + '0'; temp = ch + temp; value = value / 10; } return temp; } string BPlusTree::toLength(string str,int length) //待测 位扩展 { int i; while (str.length() < length) { str = "0" + str; } return str; } void BPlusTree::write(Block *b, string s) { b->CBlock = new char[s.size() + 1]; strcpy(b->CBlock, s.c_str()); b->charNum = strlen(b->CBlock); b->isDirty = 1; } void BPlusTree::writeRootBlock(Block b) { string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; Block root; //root = readBlock(fileName, 0); } void BPlusTree::insertInLeaf(Block* node, string key, int blockNum, int offset) //向叶节点插入,,有待商榷 { int i; int start, end; int length = myIndexInfo.length; string bnum, off,tmp; string info = node->CBlock; tmp = info; int num = getValueNum(info.substr(1, 4)); bnum = toLength(intToStr(blockNum), 4); off = toLength(intToStr(offset), 4); string insert = bnum + off + toLength(key, myIndexInfo.length); tmp.replace(1, 4, toLength(intToStr(getValueNum(info.substr(1, 4)) + 1),4)); //value数量+1 for (i = 0; i < num; i++) { start = 8 + i*(8 + length); if (key.compare(tmp.substr(start + 8, length)) < 0) { tmp.insert(start,insert); write(node, tmp); return; } } start = 8 + i*(8 + length); tmp.insert(start, insert); //有待商榷,指向下一块的指针位置不确定 write(node, tmp); return; } int BPlusTree::searchLeaf(string key) //寻找子叶节点 { string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; Block *root = new Block; Block *node = new Block; root = bufferManager.readBlock(fileName,0); //读取fileName中第一个block当作root的block; node = bufferManager.readBlock(fileName,root->blockNum); string info = node->CBlock; int num = 0;//每个节点的索引值个数 int start,i; string nodeValue; int length = myIndexInfo.length; while (node->CBlock[0] != '!') //找到叶节点 { num = getValueNum(info.substr(1, 4)); int nextBlock = 0; info = node->CBlock; int end; for (i = 0; i < num; i++) { start = 8 + i*(4 + length); end = start + length + 3; nodeValue = info.substr(start + 4, length); if (key.compare(nodeValue) >= 0) //此处比较直接用字符串比较 { if (i + 1 == num) { nextBlock = getValueNum(info.substr(end + 1, 4)); break; } else continue; } else { nextBlock = getValueNum(info.substr(start, 4)); break; } } node = bufferManager.readBlock(fileName, nextBlock); //寻找下一个块号 info = node->CBlock; } info = node->CBlock; if (info[0] == '!') return node->blockNum; else return -1; } Offset BPlusTree::searchEqual(string key) { string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; int bnum,i,start; Offset off; off.blockNum = -1; off.offset = -1; bnum = searchLeaf(key); Block *leaf = new Block; leaf = bufferManager.readBlock(fileName, bnum); string info = leaf->CBlock; int num = getValueNum(info.substr(1, 4)); for (i = 0; i < num; i++) { start = 8 + i*(8 + myIndexInfo.length); if (key == info.substr(start + 8, myIndexInfo.length)) { off.blockNum = getValueNum(info.substr(start, 4)); off.offset = getValueNum(info.substr(start + 4, 4)); return off; } } return off; } int BPlusTree::getValueNum(string snum) {//将节点value值的个数转化成int int num = 0; for (int i = 0; i < snum.length(); i++) num = 10 * num + snum[i] - '0'; return num; } void BPlusTree::fatherUpdate(int blockNum) { int i; string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; Block *node = new Block; Block *childBlock = new Block; node = bufferManager.readBlock(fileName, blockNum); string info = node->CBlock; if (info[0] == '!') return; string cinfo; int num = getValueNum(info.substr(1, 4)); int start,length,bnum; length = 4 + myIndexInfo.length; for (i = 0; i <=num; i++) { start = 8 + i*length; bnum = getValueNum(info.substr(start, 4)); childBlock = bufferManager.readBlock(fileName, bnum); cinfo = childBlock->CBlock; cinfo.replace(5, 3, toLength(intToStr(blockNum),3)); write(childBlock, cinfo); } } void BPlusTree::deleteOne(string key) { int bnum = searchLeaf(key); deleteEntry(bnum, key, bnum); } void BPlusTree::deleteEntry(int blockNum, string key, int deletedNum) { string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; Block *node = new Block; node = bufferManager.readBlock(fileName, blockNum); string info = node->CBlock; string tempN; tempN = info; int j, startF; int num = getValueNum(info.substr(1, 4)); tempN.replace(1, 4, toLength(intToStr(num-1),4)); //删掉后的value int length,i,start; if (info[0] == '?') length = 4; else if (info[0] == '!') length = 8; for (i = 0; i < num; i++) { start = 8 + i*(length + myIndexInfo.length); if (info.substr(start + length, myIndexInfo.length) == key) { if (info[0] == '!') { if (i == 0 && info.substr(5, 3) != "fff") //如果删掉了第一个节点,要更新路标 { int fatherTmpNum = getValueNum(tempN.substr(5, 3)); Block *fatherTmp = new Block; fatherTmp = bufferManager.readBlock(fileName, fatherTmpNum); string fatherin = fatherTmp->CBlock; for (j = 0; j <= getValueNum(fatherin.substr(1, 4)); j++) { startF = 8 + j*(4 + myIndexInfo.length); if (fatherin.substr(startF + 4, myIndexInfo.length) == tempN.substr(start + 8, myIndexInfo.length)) //有争议,度为3时 { fatherin.replace(startF + 4, myIndexInfo.length, tempN.substr(start + myIndexInfo.length + 16, myIndexInfo.length)); write(fatherTmp, fatherin); break; } } } tempN.replace(start, length + myIndexInfo.length, ""); //有争议,分情况?如果删除头节点,更新路标 } else if (info[0] == '?') { if (getValueNum(info.substr(start, length)) == deletedNum) { tempN.replace(start,length+myIndexInfo.length,""); } else if (getValueNum(info.substr(start + length + myIndexInfo.length, length)) == deletedNum) { tempN.replace(start + length, length + myIndexInfo.length, ""); } } break; } } //cout << tempN << endl; write(node, tempN); int father = getValueNum(info.substr(5,3)); if (node->blockNum == 0 && info.substr(1, 4) == "0001") { /*make the child of N the root*/ int childNum = getValueNum(tempN.substr(8, 4)); Block *child = new Block; child = bufferManager.readBlock(fileName, childNum); string childInfo = child->CBlock; childInfo.replace(5,3,"fff"); /*交换块号*/ node->blockNum = child->blockNum; child->blockNum = 0; write(child, childInfo); fatherUpdate(child->blockNum); //writeRootBlock(dbName, name, Child); /*delete N*/ bufferManager.deleteBlock(fileName, node->blockNum); catalogManager->subIndexBlockNum(myIndexInfo.value); } else { info = node->CBlock; tempN = node->CBlock; if (info[0] == '!' && info.substr(5,3)!="fff") { if (getValueNum(info.substr(1, 4)) < leaf_least) //如果叶子value数量小于下界,则合并 { string sibInfo; int begin,sibling; int father = getValueNum(info.substr(5, 3)); Block *fatherNode = new Block; Block *sibNode = new Block; fatherNode = bufferManager.readBlock(fileName, father); string fatherInfo = fatherNode->CBlock; int valueNum = getValueNum(fatherInfo.substr(1, 4)); for (i = 0; i <= valueNum; i++) { begin = 8 + i*(4 + myIndexInfo.length); if (getValueNum(fatherInfo.substr(begin, 4)) == blockNum) { sibling = begin; break; } } if (sibling == 8) //如果是第一个子节点 { sibling += 4 + myIndexInfo.length; sibling = getValueNum(fatherInfo.substr(sibling, 4)); sibNode = bufferManager.readBlock(fileName, sibling); sibInfo = sibNode->CBlock; string firstKey = sibInfo.substr(16, myIndexInfo.length); if (getValueNum(sibInfo.substr(1, 4)) + getValueNum(info.substr(1, 4)) <= order - 1) //2个节点可以合并 { int totalNum = getValueNum(sibInfo.substr(1, 4)) + getValueNum(info.substr(1, 4)); sibInfo.replace(1, 4, toLength(intToStr(totalNum), 4)); tempN.replace(tempN.length() - 4, 4, ""); string part1 = tempN.substr(8, tempN.length() - 8); sibInfo.insert(8, part1); write(sibNode, sibInfo); deleteEntry(father, firstKey, blockNum); //递归删除父节点的元素 bufferManager.deleteBlock(fileName,node->blockNum); catalogManager->subIndexBlockNum(myIndexInfo.value); } else //2个节点无法合并,从一个兄弟节点中借一个节点 { int i, start; int nodeNum = getValueNum(tempN.substr(1, 4)); int sibValueNum = getValueNum(sibInfo.substr(1, 4)); string first = sibInfo.substr(8, 8 + myIndexInfo.length); sibInfo.replace(1, 4, toLength(intToStr(sibValueNum - 1), 4)); sibInfo.replace(8, myIndexInfo.length + 8, ""); write(sibNode, sibInfo); tempN.replace(1, 4, toLength(intToStr(nodeNum + 1), 4)); tempN.insert(tempN.length()-4, first); write(node, tempN); string km = sibInfo.substr(16, myIndexInfo.length); string tmp = fatherInfo; int fatherNum = getValueNum(tmp.substr(1, 4)); for (i = 0; i < fatherNum; i++) { start = 8 + i*(4 + myIndexInfo.length); if (tmp.substr(start + 4, myIndexInfo.length) == firstKey) { tmp.replace(start + 4, myIndexInfo.length, km); write(fatherNode, tmp); } } } } else { sibling -= (4 + myIndexInfo.length); sibling = getValueNum(fatherInfo.substr(sibling, 4)); sibNode = bufferManager.readBlock(fileName, sibling); sibInfo = sibNode->CBlock; //cout << sibInfo << endl; string firstKey = info.substr(16, myIndexInfo.length); //cout << firstKey << endl; if (getValueNum(sibInfo.substr(1, 4)) + getValueNum(info.substr(1, 4)) <= order - 1) //2个节点可以合并 { int totalNum = getValueNum(sibInfo.substr(1, 4)) + getValueNum(info.substr(1, 4)); sibInfo.replace(1, 4, toLength(intToStr(totalNum),4)); sibInfo.replace(sibInfo.length() - 4, 4, ""); string tail = info.substr(8, info.length() - 8); sibInfo += tail; //cout << sibInfo << endl; write(sibNode, sibInfo); deleteEntry(father, info.substr(16, myIndexInfo.length),node->blockNum); //递归删除父节点的元素 bufferManager.deleteBlock(fileName,node->blockNum); catalogManager->subIndexBlockNum(myIndexInfo.value); } else //2个节点无法合并,从一个兄弟节点中借一个节点 { int i,start; int nodeNum = getValueNum(tempN.substr(1, 4)); int sibValueNum = getValueNum(sibInfo.substr(1, 4)); string last = sibInfo.substr(8+(sibValueNum-1)*(8 + myIndexInfo.length),myIndexInfo.length + 8); sibInfo.replace(1, 4, toLength(intToStr(sibValueNum - 1), 4)); sibInfo.replace(8 + (sibValueNum - 1)*(8 + myIndexInfo.length), myIndexInfo.length + 8, ""); write(sibNode, sibInfo); tempN.replace(1, 4, toLength(intToStr(nodeNum + 1), 4)); tempN.insert(8, last); write(node, tempN); string km = last.substr(8, myIndexInfo.length); string tmp = fatherInfo; int fatherNum = getValueNum(tmp.substr(1, 4)); for (i = 0; i < fatherNum; i++) { start = 8 + i*(4 + myIndexInfo.length); if (tmp.substr(start + 4, myIndexInfo.length) == firstKey) { tmp.replace(start + 4, myIndexInfo.length, km); write(fatherNode, tmp); } } } } } } else if (info[0] == '?') { if (getValueNum(info.substr(1, 4)) < nonleaf_least) { //cout << "reach" << endl; int father = getValueNum(info.substr(5, 3)); Block *fatherNode = new Block; Block *interSib = new Block; fatherNode = bufferManager.readBlock(fileName, father); string fatherInfo = fatherNode->CBlock; string keyFlag; num = getValueNum(fatherInfo.substr(1, 4)); int pre = 1; int siblingNum; for (i = 0; i <= num; i++) //有争议=号 { start = 8 + i*(myIndexInfo.length + 4); if (getValueNum(fatherInfo.substr(start, 4)) == node->blockNum) { if (i == 0) { siblingNum = getValueNum(fatherInfo.substr(start + myIndexInfo.length + 4, 4)); keyFlag = fatherInfo.substr(start + 4, myIndexInfo.length); pre = 0; } else { siblingNum = getValueNum(fatherInfo.substr(start - myIndexInfo.length - 4, 4)); keyFlag = fatherInfo.substr(start - myIndexInfo.length, myIndexInfo.length); } break; } } interSib = bufferManager.readBlock(fileName, siblingNum); //读取相邻节点 string sibInfo = interSib->CBlock; if (pre == 1) //如果读取的是前一个兄弟节点 { if (getValueNum(tempN.substr(1, 4)) + getValueNum(sibInfo.substr(1, 4) ) + 1 <= order - 1) { //如果可以合并,此处+1有争议 /*append K1 and all in N to N1 */ int totalNum = getValueNum(sibInfo.substr(1, 4)) + getValueNum(tempN.substr(1, 4)) + 1; sibInfo.replace(1, 4, toLength(intToStr(totalNum), 4)); string tail = tempN.substr(8, node->charNum - 8); sibInfo = sibInfo + keyFlag + tail; write(interSib, sibInfo); fatherUpdate(interSib->blockNum); //更新父节点 deleteEntry(father, keyFlag, node->blockNum); bufferManager.deleteBlock(fileName, node->blockNum); catalogManager->subIndexBlockNum(myIndexInfo.value); } else //无法合并,向兄弟借节点 { string tail = sibInfo.substr(interSib->charNum - 4, 4); string tailKey = sibInfo.substr(interSib->charNum - 4 - myIndexInfo.length, myIndexInfo.length); /*remove N1.Km-1,N1.pm from N1*/ sibInfo.replace(1, 4, toLength(intToStr(getValueNum(sibInfo.substr(1, 4)) - 1),4)); sibInfo.replace(interSib->charNum - 4 - myIndexInfo.length, myIndexInfo.length + 4, ""); write(interSib, sibInfo); /*insert N1.pm,K1 as the first in N*/ tempN.replace(1, 4, toLength(intToStr(getValueNum(tempN.substr(1, 4)) + 1), 4)); tempN.insert(8, tail + keyFlag); write(node, tempN); /*replace K1 in parent(N) by N1.Km-1*/ fatherInfo.replace(start - myIndexInfo.length, myIndexInfo.length, tailKey); write(fatherNode, fatherInfo); int childNum = getValueNum(tail); Block *child = new Block; child = bufferManager.readBlock(fileName, childNum); string chInfo = child->CBlock; chInfo.replace(5, 3, toLength(intToStr(node->blockNum), 4)); write(child, chInfo); } } else if (pre == 0) { if (getValueNum(tempN.substr(1, 4)) + getValueNum(sibInfo.substr(1, 4)) + 1 <=order - 1) { //如果可以合并 /*append K1 and all in N to N1 */ int totalNum = getValueNum(sibInfo.substr(1, 4)) + getValueNum(tempN.substr(1, 4)) + 1; sibInfo.replace(1, 4, toLength(intToStr(totalNum), 4)); string head = tempN.substr(8, node->charNum - 8); sibInfo.insert(8, head + keyFlag); write(interSib, sibInfo); fatherUpdate(interSib->blockNum); //更新父节点 deleteEntry(father, keyFlag, node->blockNum); bufferManager.deleteBlock(fileName, node->blockNum); catalogManager->subIndexBlockNum(myIndexInfo.value); } else //无法合并,向兄弟借节点 { //cout << "reach" << endl; string head = sibInfo.substr(8, 4); string headKey = sibInfo.substr(12, myIndexInfo.length); /*remove N1.Km-1,N1.pm from N1*/ sibInfo.replace(1, 4, toLength(intToStr(getValueNum(sibInfo.substr(1, 4)) - 1), 4)); sibInfo.replace(8, myIndexInfo.length + 4, ""); //cout << sibInfo << endl; write(interSib, sibInfo); /*insert N1.pm,K1 as the first in N*/ tempN.replace(1, 4, toLength(intToStr(getValueNum(tempN.substr(1, 4)) + 1), 4)); tempN = tempN + keyFlag + head; write(node, tempN); /*replace K1 in parent(N) by N1.Km-1*/ fatherInfo.replace(start + 4, myIndexInfo.length, headKey); write(fatherNode, fatherInfo); int childNum = getValueNum(head); Block *child = new Block; child = bufferManager.readBlock(fileName, childNum); string chInfo = child->CBlock; chInfo.replace(5, 3, toLength(intToStr(node->blockNum), 4)); write(child, chInfo); } } } } } } void BPlusTree::updateKey(string key, int blockOffset, int offset) { string boff, off; string fileName = "file/index/" + myIndexInfo.tableName + "_" + myIndexInfo.name + ".txt"; int bnum = searchLeaf(key); Block *newBlock = bufferManager.readBlock(fileName, bnum); string info = newBlock->CBlock; int i,start,num; num = getValueNum(info.substr(1, 4)); boff = toLength(intToStr(blockOffset), 4); off = toLength(intToStr(offset), 4); for (i = 0; i < num; i++) { start = 8 + i*(8 + myIndexInfo.length); if (key == info.substr(start + 8, myIndexInfo.length)) { info.replace(start, 8, boff + off); write(newBlock, info); break; } } }
8d15fbf8a4470ed1ec899e1ccd1b0fe53e1afbbb
010b385e60d4c6d71f20f9067147001790edc05d
/src/LoadData.h
c6758d82c73ca1aa1960588b4a8c5260ce59e585
[]
no_license
ericgorlin/cs156b
edbc51e216044411fc8e25c97d0491ba5798a1cf
afe295af0f0c652291e6cb2b10f3bdc3bf781686
refs/heads/master
2021-01-21T17:46:08.893248
2015-04-27T06:12:23
2015-04-27T06:12:23
33,847,707
0
0
null
2015-05-04T09:05:59
2015-04-13T04:27:04
C++
UTF-8
C++
false
false
922
h
LoadData.h
#ifndef LOADDATA_H #define LOADDATA_H #include <iostream> #include <fstream> #include <ctime> #define ARMA_64BIT_WORD #include <armadillo> #include <unordered_map> #include <math.h> using namespace std; class LoadData { public: LoadData(); virtual ~LoadData(); static arma::sp_mat start(); arma::umat loadRatingsVector(); static arma::umat probe(); static arma::sp_mat sparseFromMat(arma::umat y); int getUserMean(int userIdx); //KNN(); //KNN(arma::umat m); arma::vec normalize(unsigned int user); //virtual ~KNN(); //arma::umat getKNN(); double getUserStddev(int userIdx); int getMovieMean(int movieIdx); double getMovieStddev(int movieIdx); protected: private: unordered_map<int, vector<int>> userMap; unordered_map<int, vector<int>> movieMap; }; #endif // LOADDATA_H
96bec7287949d15afc24c6c33886a2a210423a2f
c7dcee816419434baa229cc017bfe66fe6e67a4e
/CodeJam/2014/B.cxx
132139882ac71fc5815444d9e207187394a3fe51
[]
no_license
Yuwain/Competitions
fb0cdb36f083cdc708fa4ddfb88a951a089aa88c
ba2563f8bd3f649adb4591af8d3370d51443afda
refs/heads/master
2021-01-10T14:41:44.184926
2015-09-24T01:29:19
2015-09-24T01:29:19
43,036,786
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cxx
B.cxx
#include <iostream> #include <iomanip> using std::cin; using std::cout; using std::endl; using std::fixed; using std::setprecision; double time_to_win() { double time = 0, time_win, farm_cost, time_farm, farm_speed, time_win_next, win_condition, cookies_per_second = 2; cin >> farm_cost >> farm_speed >> win_condition; while (true) { if (farm_cost > win_condition) { return (win_condition / cookies_per_second); } else { time_win = (win_condition / cookies_per_second); time_farm = (farm_cost / cookies_per_second); time_win_next = (win_condition / (cookies_per_second + farm_speed)); if (time_win > (time_farm + time_win_next)) { time += time_farm; cookies_per_second += farm_speed; } else { time += time_win; return time; } } } } int main() { int T; cout << fixed << setprecision(7); cin >> T; for (int i = 0; i < T; ++i) { cout << "Case #" << i+1 << ": " << time_to_win() << endl; } return 0; }
ba5791af2ade1bec6d430744487bfb151f61ad95
297497957c531d81ba286bc91253fbbb78b4d8be
/gfx/ots/RLBoxWOFF2Host.cpp
311490b61af7fd3f67ba98a1e8cefd5e60725f2c
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
6,888
cpp
RLBoxWOFF2Host.cpp
#include "RLBoxWOFF2Host.h" #include "nsPrintfCString.h" #include "nsThreadUtils.h" #include "mozilla/ClearOnShutdown.h" #include "mozilla/RLBoxUtils.h" #include "mozilla/ScopeExit.h" #include "opentype-sanitiser.h" using namespace rlbox; using namespace mozilla; tainted_woff2<BrotliDecoderResult> RLBoxBrotliDecoderDecompressCallback( rlbox_sandbox_woff2& aSandbox, tainted_woff2<unsigned long> aEncodedSize, tainted_woff2<const char*> aEncodedBuffer, tainted_woff2<unsigned long*> aDecodedSize, tainted_woff2<char*> aDecodedBuffer) { if (!aEncodedBuffer || !aDecodedSize || !aDecodedBuffer) { return BROTLI_DECODER_RESULT_ERROR; } size_t encodedSize = aEncodedSize.unverified_safe_because("Any size within sandbox is ok."); const uint8_t* encodedBuffer = reinterpret_cast<const uint8_t*>( aEncodedBuffer.unverified_safe_pointer_because( encodedSize, "Pointer fits within sandbox")); size_t decodedSize = (*aDecodedSize).unverified_safe_because("Any size within sandbox is ok."); uint8_t* decodedBuffer = reinterpret_cast<uint8_t*>(aDecodedBuffer.unverified_safe_pointer_because( decodedSize, "Pointer fits within sandbox")); BrotliDecoderResult res = BrotliDecoderDecompress( encodedSize, encodedBuffer, &decodedSize, decodedBuffer); *aDecodedSize = decodedSize; return res; } UniquePtr<RLBoxSandboxDataBase> RLBoxWOFF2SandboxPool::CreateSandboxData( uint64_t aSize) { auto sandbox = MakeUnique<rlbox_sandbox_woff2>(); #if defined(MOZ_WASM_SANDBOXING_WOFF2) const w2c_mem_capacity capacity = get_valid_wasm2c_memory_capacity(aSize, true ); bool createOK = sandbox->create_sandbox( false, &capacity); #else bool createOK = sandbox->create_sandbox(); #endif NS_ENSURE_TRUE(createOK, nullptr); UniquePtr<RLBoxWOFF2SandboxData> sbxData = MakeUnique<RLBoxWOFF2SandboxData>(aSize, std::move(sandbox)); sbxData->mDecompressCallback = sbxData->Sandbox()->register_callback( RLBoxBrotliDecoderDecompressCallback); sbxData->Sandbox()->invoke_sandbox_function(RegisterWOFF2Callback, sbxData->mDecompressCallback); return sbxData; } StaticRefPtr<RLBoxWOFF2SandboxPool> RLBoxWOFF2SandboxPool::sSingleton; void RLBoxWOFF2SandboxPool::Initalize(size_t aDelaySeconds) { AssertIsOnMainThread(); RLBoxWOFF2SandboxPool::sSingleton = new RLBoxWOFF2SandboxPool(aDelaySeconds); ClearOnShutdown(&RLBoxWOFF2SandboxPool::sSingleton); } RLBoxWOFF2SandboxData::RLBoxWOFF2SandboxData( uint64_t aSize, mozilla::UniquePtr<rlbox_sandbox_woff2> aSandbox) : mozilla::RLBoxSandboxDataBase(aSize), mSandbox(std::move(aSandbox)) { MOZ_COUNT_CTOR(RLBoxWOFF2SandboxData); } RLBoxWOFF2SandboxData::~RLBoxWOFF2SandboxData() { MOZ_ASSERT(mSandbox); mDecompressCallback.unregister(); mSandbox->destroy_sandbox(); MOZ_COUNT_DTOR(RLBoxWOFF2SandboxData); } static bool Woff2SizeValidator(size_t aLength, size_t aSize, size_t aLimit) { if (aSize < aLength) { NS_WARNING("Size of decompressed WOFF 2.0 is less than compressed size"); return false; } else if (aSize == 0) { NS_WARNING("Size of decompressed WOFF 2.0 is set to 0"); return false; } else if (aSize > aLimit) { NS_WARNING( nsPrintfCString("Size of decompressed WOFF 2.0 font exceeds %gMB", aLimit / (1024.0 * 1024.0)) .get()); return false; } return true; } static uint32_t ComputeWOFF2FinalSize(const uint8_t* aData, size_t aLength, size_t aLimit) { if (aLength < 20) { return 0; } uint32_t decompressedSize = 0; const void* location = &(aData[16]); std::memcpy(&decompressedSize, location, sizeof(decompressedSize)); decompressedSize = ots_ntohl(decompressedSize); if (!Woff2SizeValidator(aLength, decompressedSize, aLimit)) { return 0; } return decompressedSize; } template <typename T> using TransferBufferToWOFF2 = mozilla::RLBoxTransferBufferToSandbox<T, rlbox_woff2_sandbox_type>; template <typename T> using WOFF2Alloc = mozilla::RLBoxAllocateInSandbox<T, rlbox_woff2_sandbox_type>; bool RLBoxProcessWOFF2(ots::FontFile* aHeader, ots::OTSStream* aOutput, const uint8_t* aData, size_t aLength, uint32_t aIndex, ProcessTTCFunc* aProcessTTC, ProcessTTFFunc* aProcessTTF) { MOZ_ASSERT(aProcessTTC); MOZ_ASSERT(aProcessTTF); NS_ENSURE_TRUE(aLength >= 8, false); size_t limit = std::min(size_t(OTS_MAX_DECOMPRESSED_FILE_SIZE), aOutput->size()); uint32_t expectedSize = ComputeWOFF2FinalSize(aData, aLength, limit); NS_ENSURE_TRUE(expectedSize > 0, false); const uint64_t expectedSandboxSize = static_cast<uint64_t>(2 * (aLength + expectedSize)); auto sandboxPoolData = RLBoxWOFF2SandboxPool::sSingleton->PopOrCreate(expectedSandboxSize); NS_ENSURE_TRUE(sandboxPoolData, false); const auto* sandboxData = static_cast<const RLBoxWOFF2SandboxData*>(sandboxPoolData->SandboxData()); MOZ_ASSERT(sandboxData); auto* sandbox = sandboxData->Sandbox(); auto data = TransferBufferToWOFF2<char>( sandbox, reinterpret_cast<const char*>(aData), aLength); NS_ENSURE_TRUE(*data, false); auto sizep = WOFF2Alloc<unsigned long>(sandbox); auto bufp = WOFF2Alloc<char*>(sandbox); auto bufOwnerString = WOFF2Alloc<void*>(sandbox); if (!sandbox ->invoke_sandbox_function(RLBoxConvertWOFF2ToTTF, *data, aLength, expectedSize, sizep.get(), bufOwnerString.get(), bufp.get()) .unverified_safe_because( "The ProcessTT* functions validate the decompressed data.")) { return false; } auto bufCleanup = mozilla::MakeScopeExit([&sandbox, &bufOwnerString] { sandbox->invoke_sandbox_function(RLBoxDeleteWOFF2String, bufOwnerString.get()); }); bool validateOK = false; unsigned long actualSize = (*sizep.get()).copy_and_verify([&](unsigned long val) { validateOK = Woff2SizeValidator(aLength, val, limit); return val; }); NS_ENSURE_TRUE(validateOK, false); const uint8_t* decompressed = reinterpret_cast<const uint8_t*>( (*bufp.get()) .unverified_safe_pointer_because( actualSize, "Only care that the buffer is within sandbox boundary.")); NS_ENSURE_TRUE(decompressed, false); if (aData[4] == 't' && aData[5] == 't' && aData[6] == 'c' && aData[7] == 'f') { return aProcessTTC(aHeader, aOutput, decompressed, actualSize, aIndex); } ots::Font font(aHeader); return aProcessTTF(aHeader, &font, aOutput, decompressed, actualSize, 0); }
780e6913f1ff2aa5e9a6dfec90700a97647c38f9
0f31e3262a348c7c5cfa83ab734ea31651656e76
/deferRendering/JGlobalVariables.h
cdea4c7e3a785faeae070c98edf155af3b1a3b4b
[]
no_license
ingun37/deferredRendering
d56fb1dbec0cdeabb489ec274ebff886ad9cf601
8a6afb021b8cb69c86614a26666b5e1420053411
refs/heads/master
2020-04-16T13:23:06.074858
2015-04-27T17:10:40
2015-04-27T17:10:40
33,111,610
0
0
null
null
null
null
UTF-8
C++
false
false
208
h
JGlobalVariables.h
#pragma once #include "JLinearAlgebra.h" class JGlobalVariables { public: static JVector3 gWorldCameraEyePos; static JVector3 gSunlightDir; JGlobalVariables(void); ~JGlobalVariables(void); };
dca81f61bc1494361f0b6e74232c736fe34030d8
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/v8/src/api-arguments.cc
f8d6c8fcc3ddda3ee8d83e5419be4b7127ff8f8a
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,165
cc
api-arguments.cc
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/api-arguments.h" #include "src/tracing/trace-event.h" #include "src/vm-state-inl.h" namespace v8 { namespace internal { Handle<Object> FunctionCallbackArguments::Call(FunctionCallback f) { Isolate* isolate = this->isolate(); RuntimeCallTimerScope timer(isolate, &RuntimeCallStats::FunctionCallback); VMState<EXTERNAL> state(isolate); ExternalCallbackScope call_scope(isolate, FUNCTION_ADDR(f)); FunctionCallbackInfo<v8::Value> info(begin(), argv_, argc_); f(info); return GetReturnValue<Object>(isolate); } Handle<JSObject> PropertyCallbackArguments::Call( IndexedPropertyEnumeratorCallback f) { Isolate* isolate = this->isolate(); RuntimeCallTimerScope timer(isolate, &RuntimeCallStats::PropertyCallback); VMState<EXTERNAL> state(isolate); ExternalCallbackScope call_scope(isolate, FUNCTION_ADDR(f)); PropertyCallbackInfo<v8::Array> info(begin()); f(info); return GetReturnValue<JSObject>(isolate); } } // namespace internal } // namespace v8
f0394bd3938dba902437ccd2993e956c813bff15
7aa33c0eb23f57534b08fb023ffcb624dfa275d5
/include/Entities/Entity.h
2289599b9e64a37c890fb120eeb3623dbf24c5c7
[]
no_license
danielzelayadev/jrpg-cpp
52a0c6091d438cb792a15074686585cfe80552af
bff5f7ef3fa22ea48442e8e0c1c55fadc9d723de
refs/heads/master
2021-05-29T23:06:44.263996
2015-07-08T00:21:57
2015-07-08T00:21:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
h
Entity.h
#ifndef ENTITY_H #define ENTITY_H #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "Animation.h" #include "TMX/RectangleMapObject.h" enum WalkDirs { WALK_DOWN, WALK_LEFT, WALK_RIGHT, WALK_UP }; class Entity { public: Entity(SDL_Renderer* renderer, RectangleMapObject* obj); virtual ~Entity(); void update(); void render(SDL_Renderer* renderer); int getX() { return object->x; } int getY() { return object->y; } void setX(int x) { object->x = x; } void setY(int y) { object->y = y; } RectangleMapObject* getMapObject() { return object; } Animation* getMovementAnim() { return movements; } protected: RectangleMapObject* object; SDL_Texture* spritesheet; Animation* movements; int speed; string spritesheetSrc; void loadMOProperties(); }; #endif // ENTITY_H
74dc680a5175ca69280877e0f8e099fca2f14fa6
5a5b980cfea3cf29e07596c8716e66e606c5eebc
/namespace1.cpp
976fd18cc5cba47347617721759459b2a33f4b92
[]
no_license
Seanoy/cpp_test
74d3cab28b8a89fde32242b334434d8da41f1fcd
2d70718bac559e61986f970bd0470cc8767f7924
refs/heads/master
2021-05-21T08:09:51.216807
2020-05-25T13:49:20
2020-05-25T13:49:20
252,611,388
0
0
null
2020-04-28T07:38:50
2020-04-03T02:12:17
null
GB18030
C++
false
false
2,110
cpp
namespace1.cpp
#include <iostream> #include <string> #include <vector> #include <cstdlib> #include <stdexcept> using namespace std; namespace first_space { void foo() { cout << "within first place" << endl; } } namespace second_space { void foo() { cout << "within second place" << endl; } } template <typename T> inline T const& Max(T const& a, T const& b) { return a < b ? b : a; } template <class T> class Stack { private: vector<T> elems;//elements public: void push(T const& elem);//入栈 void pop();//出栈 T top() const;//返回栈顶元素 bool empty() const { return elems.empty(); } }; template <class T> void Stack<T>::push(T const &elem) { //追加传入元素的副本 elems.push_back(elem); } template <class T> void Stack<T>::pop() { if (elems.empty()) { throw out_of_range("Stack<>::pop: empty stack"); } //删除最后一个元素 elems.pop_back(); } template <class T> T Stack<T>::top() const { if (elems.empty()) { throw out_of_range("Stack<>::top(): empty stack"); } //弹出栈顶元素 return elems.back(); } #define MKSTR(x) #x #define CONCAT(x,y) x ## y int main() { /* first_space::foo(); second_space::foo(); int i = 39; int j = 20; cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; */ /* try { Stack<int> intStack; Stack<string> stringStack; intStack.push(6); cout << intStack.top() << endl; intStack.pop(); stringStack.push("Hello"); cout << stringStack.top() << endl; stringStack.pop(); stringStack.pop(); } catch (exception const &ex) { cerr << "Exception: " << ex.what() << endl; system("pause"); return -1; } */ string helloworld = "hello, world"; cout << MKSTR(hello) << endl; cout << CONCAT(hello, world) << endl; cout << "current line:" << __LINE__ << endl; cout << "current date:" << __DATE__ << endl; cout << "current file:" << __FILE__ << endl; cout << "current time:" << __TIME__ << endl; system("pause"); return 0; }